]> git.mxchange.org Git - flightgear.git/blob - src/Main/fg_commands.cxx
Initial work on 'reposition' command
[flightgear.git] / src / Main / fg_commands.cxx
1 // fg_commands.cxx - internal FGFS commands.
2
3 #ifdef HAVE_CONFIG_H
4 #  include "config.h"
5 #endif
6
7 #include <string.h>             // strcmp()
8
9 #include <simgear/compiler.h>
10
11 #include <string>
12 #include <fstream>
13
14 #include <simgear/sg_inlines.h>
15 #include <simgear/debug/logstream.hxx>
16 #include <simgear/math/sg_random.h>
17 #include <simgear/scene/material/mat.hxx>
18 #include <simgear/scene/material/matlib.hxx>
19 #include <simgear/structure/exception.hxx>
20 #include <simgear/structure/commands.hxx>
21 #include <simgear/props/props.hxx>
22 #include <simgear/props/props_io.hxx>
23 #include <simgear/structure/event_mgr.hxx>
24 #include <simgear/sound/soundmgr_openal.hxx>
25 #include <simgear/timing/sg_time.hxx>
26 #include <simgear/io/HTTPMemoryRequest.hxx>
27
28 #include <FDM/flight.hxx>
29 #include <GUI/gui.h>
30 #include <GUI/new_gui.hxx>
31 #include <GUI/dialog.hxx>
32 #include <Aircraft/replay.hxx>
33 #include <Scenery/scenery.hxx>
34 #include <Scenery/tilemgr.hxx>
35 #include <Scripting/NasalSys.hxx>
36 #include <Sound/sample_queue.hxx>
37 #include <Airports/xmlloader.hxx>
38 #include <Network/HTTPClient.hxx>
39 #include <Viewer/viewmgr.hxx>
40 #include <Viewer/viewer.hxx>
41 #include <Environment/presets.hxx>
42
43 #include "fg_init.hxx"
44 #include "fg_io.hxx"
45 #include "fg_os.hxx"
46 #include "fg_commands.hxx"
47 #include "fg_props.hxx"
48 #include "globals.hxx"
49 #include "logger.hxx"
50 #include "util.hxx"
51 #include "main.hxx"
52 #include "positioninit.hxx"
53
54 #include <boost/scoped_array.hpp>
55
56 #if FG_HAVE_GPERFTOOLS
57 # include <google/profiler.h>
58 #endif
59
60 using std::string;
61 using std::ifstream;
62 using std::ofstream;
63
64
65 ////////////////////////////////////////////////////////////////////////
66 // Static helper functions.
67 ////////////////////////////////////////////////////////////////////////
68
69
70 static inline SGPropertyNode *
71 get_prop (const SGPropertyNode * arg)
72 {
73     return fgGetNode(arg->getStringValue("property[0]", "/null"), true);
74 }
75
76 static inline SGPropertyNode *
77 get_prop2 (const SGPropertyNode * arg)
78 {
79     return fgGetNode(arg->getStringValue("property[1]", "/null"), true);
80 }
81
82
83 /**
84  * Get a double value and split it as required.
85  */
86 static void
87 split_value (double full_value, const char * mask,
88              double * unmodifiable, double * modifiable)
89 {
90     if (!strcmp("integer", mask)) {
91         *modifiable = (full_value < 0 ? ceil(full_value) : floor (full_value));
92         *unmodifiable = full_value - *modifiable;
93     } else if (!strcmp("decimal", mask)) {
94         *unmodifiable = (full_value < 0 ? ceil(full_value) : floor(full_value));
95         *modifiable = full_value - *unmodifiable;
96     } else {
97         if (strcmp("all", mask))
98             SG_LOG(SG_GENERAL, SG_ALERT, "Bad value " << mask << " for mask;"
99                    << " assuming 'all'");
100         *unmodifiable = 0;
101         *modifiable = full_value;
102     }
103 }
104
105
106 /**
107  * Clamp or wrap a value as specified.
108  */
109 static void
110 limit_value (double * value, const SGPropertyNode * arg)
111 {
112     const SGPropertyNode * min_node = arg->getChild("min");
113     const SGPropertyNode * max_node = arg->getChild("max");
114
115     bool wrap = arg->getBoolValue("wrap");
116
117     if (min_node == 0 || max_node == 0)
118         wrap = false;
119   
120     if (wrap) {                 // wrap such that min <= x < max
121         double min_val = min_node->getDoubleValue();
122         double max_val = max_node->getDoubleValue();
123         double resolution = arg->getDoubleValue("resolution");
124         if (resolution > 0.0) {
125             // snap to (min + N*resolution), taking special care to handle imprecision
126             int n = (int)floor((*value - min_val) / resolution + 0.5);
127             int steps = (int)floor((max_val - min_val) / resolution + 0.5);
128             SG_NORMALIZE_RANGE(n, 0, steps);
129             *value = min_val + resolution * n;
130         } else {
131             // plain circular wrapping
132             SG_NORMALIZE_RANGE(*value, min_val, max_val);
133         }
134     } else {                    // clamp such that min <= x <= max
135         if ((min_node != 0) && (*value < min_node->getDoubleValue()))
136             *value = min_node->getDoubleValue();
137         else if ((max_node != 0) && (*value > max_node->getDoubleValue()))
138             *value = max_node->getDoubleValue();
139     }
140 }
141
142 static bool
143 compare_values (SGPropertyNode * value1, SGPropertyNode * value2)
144 {
145     switch (value1->getType()) {
146     case simgear::props::BOOL:
147         return (value1->getBoolValue() == value2->getBoolValue());
148     case simgear::props::INT:
149         return (value1->getIntValue() == value2->getIntValue());
150     case simgear::props::LONG:
151         return (value1->getLongValue() == value2->getLongValue());
152     case simgear::props::FLOAT:
153         return (value1->getFloatValue() == value2->getFloatValue());
154     case simgear::props::DOUBLE:
155         return (value1->getDoubleValue() == value2->getDoubleValue());
156     default:
157         return !strcmp(value1->getStringValue(), value2->getStringValue());
158     }
159 }
160
161
162
163 ////////////////////////////////////////////////////////////////////////
164 // Command implementations.
165 ////////////////////////////////////////////////////////////////////////
166
167
168 /**
169  * Built-in command: do nothing.
170  */
171 static bool
172 do_null (const SGPropertyNode * arg)
173 {
174   return true;
175 }
176
177 /**
178  * Built-in command: run a Nasal script.
179  */
180 static bool
181 do_nasal (const SGPropertyNode * arg)
182 {
183     return ((FGNasalSys*)globals->get_subsystem("nasal"))->handleCommand(arg);
184 }
185
186 /**
187  * Built-in command: exit FlightGear.
188  *
189  * status: the exit status to return to the operating system (defaults to 0)
190  */
191 static bool
192 do_exit (const SGPropertyNode * arg)
193 {
194     SG_LOG(SG_INPUT, SG_INFO, "Program exit requested.");
195     fgSetBool("/sim/signals/exit", true);
196     globals->saveUserSettings();
197     fgOSExit(arg->getIntValue("status", 0));
198     return true;
199 }
200
201
202 /**
203  * Reset FlightGear (Shift-Escape or Menu->File->Reset)
204  */
205 static bool
206 do_reset (const SGPropertyNode * arg)
207 {
208     fgReInitSubsystems();
209     return true;
210 }
211
212 /**
213  */
214 static bool
215 do_reposition (const SGPropertyNode * arg)
216 {
217   fgStartReposition();
218   return true;
219 }
220
221 /**
222  * Built-in command: replay the FDR buffer
223  */
224 static bool
225 do_replay (const SGPropertyNode * arg)
226 {
227     FGReplay *r = (FGReplay *)(globals->get_subsystem( "replay" ));
228     return r->start();
229 }
230
231 /**
232  * Built-in command: pause/unpause the sim
233  */
234 static bool
235 do_pause (const SGPropertyNode * arg)
236 {
237     bool paused = fgGetBool("/sim/freeze/master",true) || fgGetBool("/sim/freeze/clock",true);
238     if (paused && (fgGetInt("/sim/freeze/replay-state",0)>0))
239     {
240         do_replay(NULL);
241     }
242     else
243     {
244         fgSetBool("/sim/freeze/master",!paused);
245         fgSetBool("/sim/freeze/clock",!paused);
246     }
247   
248     SGPropertyNode_ptr args(new SGPropertyNode);
249     args->setStringValue("id", "sim-pause");
250     if (!paused && fgGetBool("/sim/view-name-popup")) {
251       args->setStringValue("label", "Simulation is paused");
252       globals->get_commands()->execute("show-message", args);
253     } else {
254       globals->get_commands()->execute("clear-message", args);
255     }
256   
257     return true;
258 }
259
260 /**
261  * Built-in command: load flight.
262  *
263  * file (optional): the name of the file to load (relative to current
264  *   directory).  Defaults to "fgfs.sav"
265  */
266 static bool
267 do_load (const SGPropertyNode * arg)
268 {
269     string file = arg->getStringValue("file", "fgfs.sav");
270     if (file.size() < 4 || file.substr(file.size() - 4) != ".sav")
271         file += ".sav";
272
273     if (!fgValidatePath(file.c_str(), false)) {
274         SG_LOG(SG_IO, SG_ALERT, "load: reading '" << file << "' denied "
275                 "(unauthorized access)");
276         return false;
277     }
278
279     ifstream input(file.c_str());
280     if (input.good() && fgLoadFlight(input)) {
281         input.close();
282         SG_LOG(SG_INPUT, SG_INFO, "Restored flight from " << file);
283         return true;
284     } else {
285         SG_LOG(SG_INPUT, SG_WARN, "Cannot load flight from " << file);
286         return false;
287     }
288 }
289
290
291 /**
292  * Built-in command: save flight.
293  *
294  * file (optional): the name of the file to save (relative to the
295  * current directory).  Defaults to "fgfs.sav".
296  */
297 static bool
298 do_save (const SGPropertyNode * arg)
299 {
300     string file = arg->getStringValue("file", "fgfs.sav");
301     if (file.size() < 4 || file.substr(file.size() - 4) != ".sav")
302         file += ".sav";
303
304     if (!fgValidatePath(file.c_str(), false)) {
305         SG_LOG(SG_IO, SG_ALERT, "save: writing '" << file << "' denied "
306                 "(unauthorized access)");
307         return false;
308     }
309
310     bool write_all = arg->getBoolValue("write-all", false);
311     SG_LOG(SG_INPUT, SG_INFO, "Saving flight");
312     ofstream output(file.c_str());
313     if (output.good() && fgSaveFlight(output, write_all)) {
314         output.close();
315         SG_LOG(SG_INPUT, SG_INFO, "Saved flight to " << file);
316         return true;
317     } else {
318         SG_LOG(SG_INPUT, SG_ALERT, "Cannot save flight to " << file);
319         return false;
320     }
321 }
322
323 /**
324  * Built-in command: save flight recorder tape.
325  *
326  */
327 static bool
328 do_save_tape (const SGPropertyNode * arg)
329 {
330     FGReplay* replay = (FGReplay*) globals->get_subsystem("replay");
331     replay->saveTape(arg);
332
333     return true;
334 }
335 /**
336  * Built-in command: load flight recorder tape.
337  *
338  */
339 static bool
340 do_load_tape (const SGPropertyNode * arg)
341 {
342     FGReplay* replay = (FGReplay*) globals->get_subsystem("replay");
343     replay->loadTape(arg);
344
345     return true;
346 }
347
348 /**
349  * Built-in command: (re)load the panel.
350  *
351  * path (optional): the file name to load the panel from 
352  * (relative to FG_ROOT).  Defaults to the value of /sim/panel/path,
353  * and if that's unspecified, to "Panels/Default/default.xml".
354  */
355 static bool
356 do_panel_load (const SGPropertyNode * arg)
357 {
358   string panel_path = arg->getStringValue("path");
359   if (!panel_path.empty()) {
360     // write to the standard property, which will force a load
361     fgSetString("/sim/panel/path", panel_path.c_str());
362   }
363   
364   return true;
365 }
366
367 /**
368  * Built-in command: (re)load preferences.
369  *
370  * path (optional): the file name to load the panel from (relative
371  * to FG_ROOT). Defaults to "preferences.xml".
372  */
373 static bool
374 do_preferences_load (const SGPropertyNode * arg)
375 {
376   try {
377     fgLoadProps(arg->getStringValue("path", "preferences.xml"),
378                 globals->get_props());
379   } catch (const sg_exception &e) {
380     guiErrorMessage("Error reading global preferences: ", e);
381     return false;
382   }
383   SG_LOG(SG_INPUT, SG_INFO, "Successfully read global preferences.");
384   return true;
385 }
386
387 static void
388 do_view_next(bool do_it)
389 {
390   // Only switch view if really requested to do so (and not for example while
391   // reset/reposition where /command/view/next is set to false)
392   if( do_it )
393   {
394     globals->get_current_view()->setHeadingOffset_deg(0.0);
395     globals->get_viewmgr()->next_view();
396   }
397 }
398
399 static void
400 do_view_prev(bool do_it)
401 {
402   if( do_it )
403   {
404     globals->get_current_view()->setHeadingOffset_deg(0.0);
405     globals->get_viewmgr()->prev_view();
406   }
407 }
408
409 /**
410  * An fgcommand to toggle fullscreen mode.
411  * No parameters.
412  */
413 static bool
414 do_toggle_fullscreen(const SGPropertyNode *arg)
415 {
416     fgOSFullScreen();
417     return true;
418 }
419
420 /**
421  * Built-in command: cycle view.
422  */
423 static bool
424 do_view_cycle (const SGPropertyNode * arg)
425 {
426   globals->get_current_view()->setHeadingOffset_deg(0.0);
427   globals->get_viewmgr()->next_view();
428   return true;
429 }
430
431 /**
432  * Built-in command: capture screen.
433  */
434 static bool
435 do_screen_capture (const SGPropertyNode * arg)
436 {
437   return fgDumpSnapShot();
438 }
439
440 static bool
441 do_reload_shaders (const SGPropertyNode*)
442 {
443     simgear::reload_shaders();
444     return true;
445 }
446
447 static bool
448 do_dump_scene_graph (const SGPropertyNode*)
449 {
450     fgDumpSceneGraph();
451     return true;
452 }
453
454 static bool
455 do_dump_terrain_branch (const SGPropertyNode*)
456 {
457     fgDumpTerrainBranch();
458
459     double lon_deg = fgGetDouble("/position/longitude-deg");
460     double lat_deg = fgGetDouble("/position/latitude-deg");
461     SGGeod geodPos = SGGeod::fromDegFt(lon_deg, lat_deg, 0.0);
462     SGVec3d zero = SGVec3d::fromGeod(geodPos);
463
464     SG_LOG(SG_INPUT, SG_INFO, "Model parameters:");
465     SG_LOG(SG_INPUT, SG_INFO, "Center: " << zero.x() << ", " << zero.y() << ", " << zero.z() );
466     SG_LOG(SG_INPUT, SG_INFO, "Rotation: " << lat_deg << ", " << lon_deg );
467
468     return true;
469 }
470
471 static bool
472 do_print_visible_scene_info(const SGPropertyNode*)
473 {
474     fgPrintVisibleSceneInfoCommand();
475     return true;
476 }
477
478 /**
479  * Built-in command: hires capture screen.
480  */
481 static bool
482 do_hires_screen_capture (const SGPropertyNode * arg)
483 {
484   fgHiResDump();
485   return true;
486 }
487
488
489 /**
490  * Reload the tile cache.
491  */
492 static bool
493 do_tile_cache_reload (const SGPropertyNode * arg)
494 {
495     SGPropertyNode *master_freeze = fgGetNode("/sim/freeze/master");
496     bool freeze = master_freeze->getBoolValue();
497     SG_LOG(SG_INPUT, SG_INFO, "ReIniting TileCache");
498     if ( !freeze ) {
499         master_freeze->setBoolValue(true);
500     }
501
502     globals->get_subsystem("tile-manager")->reinit();
503
504     if ( !freeze ) {
505         master_freeze->setBoolValue(false);
506     }
507     return true;
508 }
509
510 /**
511  * Reload the materials definition
512  */
513 static bool
514 do_materials_reload (const SGPropertyNode * arg)
515 {
516     SG_LOG(SG_INPUT, SG_INFO, "Reloading Materials");
517     SGMaterialLib* new_matlib =  new SGMaterialLib;
518     SGPath mpath( globals->get_fg_root() );
519     mpath.append( fgGetString("/sim/rendering/materials-file") );
520     bool loaded = new_matlib->load(globals->get_fg_root(), 
521                                   mpath.str(), 
522                                   globals->get_props());
523
524     if ( ! loaded ) {
525        SG_LOG( SG_GENERAL, SG_ALERT,
526                "Error loading materials file " << mpath.str() );
527        return false;
528     }  
529
530     globals->set_matlib(new_matlib);    
531     FGTileMgr* tileManager = static_cast<FGTileMgr*>(globals->get_subsystem("tile-manager"));
532     tileManager->materialLibChanged();
533     
534     return true;
535 }
536
537
538 #if 0
539 These do_set_(some-environment-parameters) are deprecated and no longer 
540 useful/functional - Torsten Dreyer, January 2011
541 /**
542  * Set the sea level outside air temperature and assigning that to all
543  * boundary and aloft environment layers.
544  */
545 static bool
546 do_set_sea_level_degc ( double temp_sea_level_degc)
547 {
548     SGPropertyNode *node, *child;
549
550     // boundary layers
551     node = fgGetNode( "/environment/config/boundary" );
552     if ( node != NULL ) {
553       int i = 0;
554       while ( ( child = node->getNode( "entry", i ) ) != NULL ) {
555         child->setDoubleValue( "temperature-sea-level-degc",
556                                temp_sea_level_degc );
557         ++i;
558       }
559     }
560
561     // aloft layers
562     node = fgGetNode( "/environment/config/aloft" );
563     if ( node != NULL ) {
564       int i = 0;
565       while ( ( child = node->getNode( "entry", i ) ) != NULL ) {
566         child->setDoubleValue( "temperature-sea-level-degc",
567                                temp_sea_level_degc );
568         ++i;
569       }
570     }
571
572     return true;
573 }
574
575 static bool
576 do_set_sea_level_degc (const SGPropertyNode * arg)
577 {
578     return do_set_sea_level_degc( arg->getDoubleValue("temp-degc", 15.0) );
579 }
580
581
582 /**
583  * Set the outside air temperature at the "current" altitude by first
584  * calculating the corresponding sea level temp, and assigning that to
585  * all boundary and aloft environment layers.
586  */
587 static bool
588 do_set_oat_degc (const SGPropertyNode * arg)
589 {
590     double oat_degc = arg->getDoubleValue("temp-degc", 15.0);
591     // check for an altitude specified in the arguments, otherwise use
592     // current aircraft altitude.
593     const SGPropertyNode *altitude_ft = arg->getChild("altitude-ft");
594     if ( altitude_ft == NULL ) {
595         altitude_ft = fgGetNode("/position/altitude-ft");
596     }
597
598     FGEnvironment dummy;        // instantiate a dummy so we can leech a method
599     dummy.set_elevation_ft( altitude_ft->getDoubleValue() );
600     dummy.set_temperature_degc( oat_degc );
601     return do_set_sea_level_degc( dummy.get_temperature_sea_level_degc());
602 }
603
604 /**
605  * Set the sea level outside air dewpoint and assigning that to all
606  * boundary and aloft environment layers.
607  */
608 static bool
609 do_set_dewpoint_sea_level_degc (double dewpoint_sea_level_degc)
610 {
611
612     SGPropertyNode *node, *child;
613
614     // boundary layers
615     node = fgGetNode( "/environment/config/boundary" );
616     if ( node != NULL ) {
617       int i = 0;
618       while ( ( child = node->getNode( "entry", i ) ) != NULL ) {
619         child->setDoubleValue( "dewpoint-sea-level-degc",
620                                dewpoint_sea_level_degc );
621         ++i;
622       }
623     }
624
625     // aloft layers
626     node = fgGetNode( "/environment/config/aloft" );
627     if ( node != NULL ) {
628       int i = 0;
629       while ( ( child = node->getNode( "entry", i ) ) != NULL ) {
630         child->setDoubleValue( "dewpoint-sea-level-degc",
631                                dewpoint_sea_level_degc );
632         ++i;
633       }
634     }
635
636     return true;
637 }
638
639 static bool
640 do_set_dewpoint_sea_level_degc (const SGPropertyNode * arg)
641 {
642     return do_set_dewpoint_sea_level_degc(arg->getDoubleValue("dewpoint-degc", 5.0));
643 }
644
645 /**
646  * Set the outside air dewpoint at the "current" altitude by first
647  * calculating the corresponding sea level dewpoint, and assigning
648  * that to all boundary and aloft environment layers.
649  */
650 static bool
651 do_set_dewpoint_degc (const SGPropertyNode * arg)
652 {
653     double dewpoint_degc = arg->getDoubleValue("dewpoint-degc", 5.0);
654
655     // check for an altitude specified in the arguments, otherwise use
656     // current aircraft altitude.
657     const SGPropertyNode *altitude_ft = arg->getChild("altitude-ft");
658     if ( altitude_ft == NULL ) {
659         altitude_ft = fgGetNode("/position/altitude-ft");
660     }
661
662     FGEnvironment dummy;        // instantiate a dummy so we can leech a method
663     dummy.set_elevation_ft( altitude_ft->getDoubleValue() );
664     dummy.set_dewpoint_degc( dewpoint_degc );
665     return do_set_dewpoint_sea_level_degc(dummy.get_dewpoint_sea_level_degc());
666 }
667 #endif
668
669 /**
670  * Built-in command: toggle a bool property value.
671  *
672  * property: The name of the property to toggle.
673  */
674 static bool
675 do_property_toggle (const SGPropertyNode * arg)
676 {
677   SGPropertyNode * prop = get_prop(arg);
678   return prop->setBoolValue(!prop->getBoolValue());
679 }
680
681
682 /**
683  * Built-in command: assign a value to a property.
684  *
685  * property: the name of the property to assign.
686  * value: the value to assign; or
687  * property[1]: the property to copy from.
688  */
689 static bool
690 do_property_assign (const SGPropertyNode * arg)
691 {
692   SGPropertyNode * prop = get_prop(arg);
693   const SGPropertyNode * value = arg->getNode("value");
694
695   if (value != 0)
696       return prop->setUnspecifiedValue(value->getStringValue());
697   else
698   {
699       const SGPropertyNode * prop2 = get_prop2(arg);
700       if (prop2)
701           return prop->setUnspecifiedValue(prop2->getStringValue());
702       else
703           return false;
704   }
705 }
706
707
708 /**
709  * Built-in command: increment or decrement a property value.
710  *
711  * If the 'step' argument is present, it will be used; otherwise,
712  * the command uses 'offset' and 'factor', usually from the mouse.
713  *
714  * property: the name of the property to increment or decrement.
715  * step: the amount of the increment or decrement (default: 0).
716  * offset: offset from the current setting (used for the mouse; multiplied 
717  *         by factor)
718  * factor: scaling amount for the offset (defaults to 1).
719  * min: the minimum allowed value (default: no minimum).
720  * max: the maximum allowed value (default: no maximum).
721  * mask: 'integer' to apply only to the left of the decimal point, 
722  *       'decimal' to apply only to the right of the decimal point,
723  *       or 'all' to apply to the whole number (the default).
724  * wrap: true if the value should be wrapped when it passes min or max;
725  *       both min and max must be present for this to work (default:
726  *       false).
727  */
728 static bool
729 do_property_adjust (const SGPropertyNode * arg)
730 {
731   SGPropertyNode * prop = get_prop(arg);
732
733   double amount = 0;
734   if (arg->hasValue("step"))
735       amount = arg->getDoubleValue("step");
736   else
737       amount = (arg->getDoubleValue("factor", 1)
738                 * arg->getDoubleValue("offset"));
739           
740   double unmodifiable, modifiable;
741   split_value(prop->getDoubleValue(), arg->getStringValue("mask", "all"),
742               &unmodifiable, &modifiable);
743   modifiable += amount;
744   limit_value(&modifiable, arg);
745
746   prop->setDoubleValue(unmodifiable + modifiable);
747
748   return true;
749 }
750
751
752 /**
753  * Built-in command: multiply a property value.
754  *
755  * property: the name of the property to multiply.
756  * factor: the amount by which to multiply.
757  * min: the minimum allowed value (default: no minimum).
758  * max: the maximum allowed value (default: no maximum).
759  * mask: 'integer' to apply only to the left of the decimal point, 
760  *       'decimal' to apply only to the right of the decimal point,
761  *       or 'all' to apply to the whole number (the default).
762  * wrap: true if the value should be wrapped when it passes min or max;
763  *       both min and max must be present for this to work (default:
764  *       false).
765  */
766 static bool
767 do_property_multiply (const SGPropertyNode * arg)
768 {
769   SGPropertyNode * prop = get_prop(arg);
770   double factor = arg->getDoubleValue("factor", 1);
771
772   double unmodifiable, modifiable;
773   split_value(prop->getDoubleValue(), arg->getStringValue("mask", "all"),
774               &unmodifiable, &modifiable);
775   modifiable *= factor;
776   limit_value(&modifiable, arg);
777
778   prop->setDoubleValue(unmodifiable + modifiable);
779
780   return true;
781 }
782
783
784 /**
785  * Built-in command: swap two property values.
786  *
787  * property[0]: the name of the first property.
788  * property[1]: the name of the second property.
789  */
790 static bool
791 do_property_swap (const SGPropertyNode * arg)
792 {
793   SGPropertyNode * prop1 = get_prop(arg);
794   SGPropertyNode * prop2 = get_prop2(arg);
795
796                                 // FIXME: inefficient
797   const string & tmp = prop1->getStringValue();
798   return (prop1->setUnspecifiedValue(prop2->getStringValue()) &&
799           prop2->setUnspecifiedValue(tmp.c_str()));
800 }
801
802
803 /**
804  * Built-in command: Set a property to an axis or other moving input.
805  *
806  * property: the name of the property to set.
807  * setting: the current input setting, usually between -1.0 and 1.0.
808  * offset: the offset to shift by, before applying the factor.
809  * factor: the factor to multiply by (use negative to reverse).
810  */
811 static bool
812 do_property_scale (const SGPropertyNode * arg)
813 {
814   SGPropertyNode * prop = get_prop(arg);
815   double setting = arg->getDoubleValue("setting");
816   double offset = arg->getDoubleValue("offset", 0.0);
817   double factor = arg->getDoubleValue("factor", 1.0);
818   bool squared = arg->getBoolValue("squared", false);
819   int power = arg->getIntValue("power", (squared ? 2 : 1));
820
821   int sign = (setting < 0 ? -1 : 1);
822
823   switch (power) {
824   case 1:
825       break;
826   case 2:
827       setting = setting * setting * sign;
828       break;
829   case 3:
830       setting = setting * setting * setting;
831       break;
832   case 4:
833       setting = setting * setting * setting * setting * sign;
834       break;
835   default:
836       setting =  pow(setting, power);
837       if ((power % 2) == 0)
838           setting *= sign;
839       break;
840   }
841
842   return prop->setDoubleValue((setting + offset) * factor);
843 }
844
845
846 /**
847  * Built-in command: cycle a property through a set of values.
848  *
849  * If the current value isn't in the list, the cycle will
850  * (re)start from the beginning.
851  *
852  * property: the name of the property to cycle.
853  * value[*]: the list of values to cycle through.
854  */
855 static bool
856 do_property_cycle (const SGPropertyNode * arg)
857 {
858     SGPropertyNode * prop = get_prop(arg);
859     std::vector<SGPropertyNode_ptr> values = arg->getChildren("value");
860     
861     bool wrap = arg->getBoolValue("wrap", true);
862     // compatible with knob/pick animations
863     int offset = arg->getIntValue("offset", 1);
864     
865     int selection = -1;
866     int nSelections = values.size();
867
868     if (nSelections < 1) {
869         SG_LOG(SG_GENERAL, SG_ALERT, "No values for property-cycle");
870         return false;
871     }
872
873                                 // Try to find the current selection
874     for (int i = 0; i < nSelections; i++) {
875         if (compare_values(prop, values[i])) {
876             selection = i;
877             break;
878         }
879     }
880
881     if (selection < 0) { // default to first selection
882         selection = 0;
883     } else {
884         selection += offset;
885         if (wrap) {
886             selection = (selection + nSelections) % nSelections;
887         } else {
888             SG_CLAMP_RANGE(selection, 0, nSelections - 1);
889         }
890     }
891     
892     prop->setUnspecifiedValue(values[selection]->getStringValue());
893     return true;
894 }
895
896
897 /**
898  * Built-in command: randomize a numeric property value.
899  *
900  * property: the name of the property value to randomize.
901  * min: the minimum allowed value.
902  * max: the maximum allowed value.
903  */
904 static bool
905 do_property_randomize (const SGPropertyNode * arg)
906 {
907     SGPropertyNode * prop = get_prop(arg);
908     double min = arg->getDoubleValue("min", DBL_MIN);
909     double max = arg->getDoubleValue("max", DBL_MAX);
910     prop->setDoubleValue(sg_random() * (max - min) + min);
911     return true;
912 }
913
914 /**
915  * Built-in command: interpolate a property value over time
916  *
917  * property:        the name of the property value to interpolate.
918  * type:            the interpolation type ("numeric", "color", etc.)
919  * easing:          name of easing function (see http://easings.net/)
920  * value[0..n]      any number of constant values to interpolate
921  * time/rate[0..n]  time between each value, number of time elements must
922  *                  match those of value elements. Instead of time also rate can
923  *                  be used which automatically calculates the time to change
924  *                  the property value at the given speed.
925  * -or-
926  * property[1..n+1] any number of target values taken from named properties
927  * time/rate[0..n]  time between each value, number of time elements must
928  *                  match those of value elements. Instead of time also rate can
929  *                  be used which automatically calculates the time to change
930  *                  the property value at the given speed.
931  */
932 static bool
933 do_property_interpolate (const SGPropertyNode * arg)
934 {
935   SGPropertyNode * prop = get_prop(arg);
936   if( !prop )
937     return false;
938
939   simgear::PropertyList time_nodes = arg->getChildren("time");
940   simgear::PropertyList rate_nodes = arg->getChildren("rate");
941
942   if( !time_nodes.empty() && !rate_nodes.empty() )
943     // mustn't specify time and rate
944     return false;
945
946   simgear::PropertyList::size_type num_times = time_nodes.empty()
947                                              ? rate_nodes.size()
948                                              : time_nodes.size();
949
950   simgear::PropertyList value_nodes = arg->getChildren("value");
951   if( value_nodes.empty() )
952   {
953     simgear::PropertyList prop_nodes = arg->getChildren("property");
954
955     // must have one more property node
956     if( prop_nodes.size() != num_times + 1 )
957       return false;
958
959     value_nodes.reserve(num_times);
960     for( size_t i = 1; i < prop_nodes.size(); ++i )
961       value_nodes.push_back( fgGetNode(prop_nodes[i]->getStringValue()) );
962   }
963
964   // must match
965   if( value_nodes.size() != num_times )
966     return false;
967
968   double_list deltas;
969   deltas.reserve(num_times);
970
971   if( !time_nodes.empty() )
972   {
973     for( size_t i = 0; i < num_times; ++i )
974       deltas.push_back( time_nodes[i]->getDoubleValue() );
975   }
976   else
977   {
978     for( size_t i = 0; i < num_times; ++i )
979     {
980       // TODO calculate delta based on property type
981       double delta = value_nodes[i]->getDoubleValue()
982                    - ( i > 0
983                      ? value_nodes[i - 1]->getDoubleValue()
984                      : prop->getDoubleValue()
985                      );
986       deltas.push_back( fabs(delta / rate_nodes[i]->getDoubleValue()) );
987     }
988   }
989
990   return prop->interpolate
991   (
992     arg->getStringValue("type", "numeric"),
993     value_nodes,
994     deltas,
995     arg->getStringValue("easing", "linear")
996   );
997 }
998
999 /**
1000  * Built-in command: reinit the data logging system based on the
1001  * current contents of the /logger tree.
1002  */
1003 static bool
1004 do_data_logging_commit (const SGPropertyNode * arg)
1005 {
1006     FGLogger *log = (FGLogger *)globals->get_subsystem("logger");
1007     log->reinit();
1008     return true;
1009 }
1010
1011 /**
1012  * Built-in command: Add a dialog to the GUI system.  Does *not*
1013  * display the dialog.  The property node should have the same format
1014  * as a dialog XML configuration.  It must include:
1015  *
1016  * name: the name of the GUI dialog for future reference.
1017  */
1018 static bool
1019 do_dialog_new (const SGPropertyNode * arg)
1020 {
1021     NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1022     if (!gui) {
1023       return false;
1024     }
1025   
1026     // Note the casting away of const: this is *real*.  Doing a
1027     // "dialog-apply" command later on will mutate this property node.
1028     // I'm not convinced that this isn't the Right Thing though; it
1029     // allows client to create a node, pass it to dialog-new, and get
1030     // the values back from the dialog by reading the same node.
1031     // Perhaps command arguments are not as "const" as they would
1032     // seem?
1033     gui->newDialog((SGPropertyNode*)arg);
1034     return true;
1035 }
1036
1037 /**
1038  * Built-in command: Show an XML-configured dialog.
1039  *
1040  * dialog-name: the name of the GUI dialog to display.
1041  */
1042 static bool
1043 do_dialog_show (const SGPropertyNode * arg)
1044 {
1045     NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1046     gui->showDialog(arg->getStringValue("dialog-name"));
1047     return true;
1048 }
1049
1050
1051 /**
1052  * Built-in Command: Hide the active XML-configured dialog.
1053  */
1054 static bool
1055 do_dialog_close (const SGPropertyNode * arg)
1056 {
1057     NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1058     if(arg->hasValue("dialog-name"))
1059         return gui->closeDialog(arg->getStringValue("dialog-name"));
1060     return gui->closeActiveDialog();
1061 }
1062
1063
1064 /**
1065  * Update a value in the active XML-configured dialog.
1066  *
1067  * object-name: The name of the GUI object(s) (all GUI objects if omitted).
1068  */
1069 static bool
1070 do_dialog_update (const SGPropertyNode * arg)
1071 {
1072     NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1073     FGDialog * dialog;
1074     if (arg->hasValue("dialog-name"))
1075         dialog = gui->getDialog(arg->getStringValue("dialog-name"));
1076     else
1077         dialog = gui->getActiveDialog();
1078
1079     if (dialog != 0) {
1080         dialog->updateValues(arg->getStringValue("object-name"));
1081         return true;
1082     } else {
1083         return false;
1084     }
1085 }
1086
1087 static bool
1088 do_open_browser (const SGPropertyNode * arg)
1089 {
1090     string path;
1091     if (arg->hasValue("path"))
1092         path = arg->getStringValue("path");
1093     else
1094     if (arg->hasValue("url"))
1095         path = arg->getStringValue("url");
1096     else
1097         return false;
1098
1099     return openBrowser(path);
1100 }
1101
1102 /**
1103  * Apply a value in the active XML-configured dialog.
1104  *
1105  * object-name: The name of the GUI object(s) (all GUI objects if omitted).
1106  */
1107 static bool
1108 do_dialog_apply (const SGPropertyNode * arg)
1109 {
1110     NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1111     FGDialog * dialog;
1112     if (arg->hasValue("dialog-name"))
1113         dialog = gui->getDialog(arg->getStringValue("dialog-name"));
1114     else
1115         dialog = gui->getActiveDialog();
1116
1117     if (dialog != 0) {
1118         dialog->applyValues(arg->getStringValue("object-name"));
1119         return true;
1120     } else {
1121         return false;
1122     }
1123 }
1124
1125
1126 /**
1127  * Redraw GUI (applying new widget colors). Doesn't reload the dialogs,
1128  * unlike reinit().
1129  */
1130 static bool
1131 do_gui_redraw (const SGPropertyNode * arg)
1132 {
1133     NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1134     gui->redraw();
1135     return true;
1136 }
1137
1138
1139 /**
1140  * Adds model to the scenery. The path to the added branch (/models/model[*])
1141  * is returned in property "property".
1142  */
1143 static bool
1144 do_add_model (const SGPropertyNode * arg)
1145 {
1146     SGPropertyNode * model = fgGetNode("models", true);
1147     int i;
1148     for (i = 0; model->hasChild("model",i); i++);
1149     model = model->getChild("model", i, true);
1150     copyProperties(arg, model);
1151     if (model->hasValue("elevation-m"))
1152         model->setDoubleValue("elevation-ft", model->getDoubleValue("elevation-m")
1153                 * SG_METER_TO_FEET);
1154     model->getNode("load", true);
1155     model->removeChildren("load");
1156     const_cast<SGPropertyNode *>(arg)->setStringValue("property", model->getPath());
1157     return true;
1158 }
1159
1160 /**
1161  * Built-in command: play an audio message (i.e. a wav file) This is
1162  * fire and forget.  Call this once per message and it will get dumped
1163  * into a queue.  Messages are played sequentially so they do not
1164  * overlap.
1165  */
1166 static bool
1167 do_play_audio_sample (const SGPropertyNode * arg)
1168 {
1169     SGSoundMgr *smgr = globals->get_soundmgr();
1170     if (!smgr) {
1171         SG_LOG(SG_GENERAL, SG_WARN, "play-audio-sample: sound-manager not running");
1172         return false;
1173     }
1174   
1175     string path = arg->getStringValue("path");
1176     string file = arg->getStringValue("file");
1177     float volume = arg->getFloatValue("volume");
1178     // cout << "playing " << path << " / " << file << endl;
1179     try {
1180         FGSampleQueue *queue = globals->get_chatter_queue();
1181         if ( !queue ) {
1182             queue = new FGSampleQueue(smgr, "chatter");
1183             queue->tie_to_listener();
1184             globals->set_chatter_queue(queue);
1185         }
1186
1187         SGSoundSample *msg = new SGSoundSample(file.c_str(), path);
1188         msg->set_volume( volume );
1189         queue->add( msg );
1190
1191         return true;
1192
1193     } catch (const sg_io_exception&) {
1194         SG_LOG(SG_GENERAL, SG_ALERT, "play-audio-sample: "
1195                 "failed to load" << path << '/' << file);
1196         return false;
1197     }
1198 }
1199
1200 /**
1201  * Built-in command: commit presets (read from in /sim/presets/)
1202  */
1203 static bool
1204 do_presets_commit (const SGPropertyNode * arg)
1205 {
1206     if (fgGetBool("/sim/initialized", false)) {
1207       fgReInitSubsystems();
1208     } else {
1209       // Nasal can trigger this during initial init, which confuses
1210       // the logic in ReInitSubsystems, since initial state has not been
1211       // saved at that time. Short-circuit everything here.
1212       flightgear::initPosition();
1213     }
1214     
1215     return true;
1216 }
1217
1218 /**
1219  * Built-in command: set log level (0 ... 7)
1220  */
1221 static bool
1222 do_log_level (const SGPropertyNode * arg)
1223 {
1224    sglog().setLogLevels( SG_ALL, (sgDebugPriority)arg->getIntValue() );
1225
1226    return true;
1227 }
1228
1229 /*
1230 static bool
1231 do_decrease_visibility (const SGPropertyNode * arg)
1232 {
1233     Environment::Presets::VisibilitySingleton::instance()->adjust( 0.9 );
1234     return true;
1235 }
1236  
1237 static bool
1238 do_increase_visibility (const SGPropertyNode * arg)
1239 {
1240     Environment::Presets::VisibilitySingleton::instance()->adjust( 1.1 );
1241     return true;
1242 }
1243 */
1244 /**
1245  * An fgcommand to allow loading of xml files via nasal,
1246  * the xml file's structure will be made available within
1247  * a property tree node defined under argument "targetnode",
1248  * or in the given argument tree under "data" otherwise.
1249  *
1250  * @param filename a string to hold the complete path & filename of an XML file
1251  * @param targetnode a string pointing to a location within the property tree
1252  * where to store the parsed XML file. If <targetnode> is undefined, then the
1253  * file contents are stored under a node <data> in the argument tree.
1254  */
1255
1256 static bool
1257 do_load_xml_to_proptree(const SGPropertyNode * arg)
1258 {
1259     SGPath file(arg->getStringValue("filename"));
1260     if (file.str().empty())
1261         return false;
1262
1263     if (file.extension() != "xml")
1264         file.concat(".xml");
1265     
1266     std::string icao = arg->getStringValue("icao");
1267     if (icao.empty()) {
1268         if (file.isRelative()) {
1269           SGPath absPath = globals->resolve_maybe_aircraft_path(file.str());
1270           if (!absPath.isNull())
1271               file = absPath;
1272           else
1273           {
1274               SG_LOG(SG_IO, SG_ALERT, "loadxml: Cannot find XML property file '"  
1275                           << file.str() << "'.");
1276               return false;
1277           }
1278         }
1279     } else {
1280         if (!XMLLoader::findAirportData(icao, file.str(), file)) {
1281           SG_LOG(SG_IO, SG_INFO, "loadxml: failed to find airport data for "
1282             << file.str() << " at ICAO:" << icao);
1283           return false;
1284         }
1285     }
1286     
1287     if (!fgValidatePath(file.c_str(), false)) {
1288         SG_LOG(SG_IO, SG_ALERT, "loadxml: reading '" << file.str() << "' denied "
1289                 "(unauthorized access)");
1290         return false;
1291     }
1292
1293     SGPropertyNode *targetnode;
1294     if (arg->hasValue("targetnode"))
1295         targetnode = fgGetNode(arg->getStringValue("targetnode"), true);
1296     else
1297         targetnode = const_cast<SGPropertyNode *>(arg)->getNode("data", true);
1298
1299     try {
1300         readProperties(file.c_str(), targetnode, true);
1301     } catch (const sg_exception &e) {
1302         SG_LOG(SG_IO, SG_WARN, "loadxml: " << e.getFormattedMessage());
1303         return false;
1304     }
1305
1306     return true;
1307 }
1308
1309 class RemoteXMLRequest:
1310   public simgear::HTTP::MemoryRequest
1311 {
1312 public:
1313     SGPropertyNode_ptr _complete;
1314     SGPropertyNode_ptr _status;
1315     SGPropertyNode_ptr _failed;
1316     SGPropertyNode_ptr _target;
1317
1318     RemoteXMLRequest(const std::string& url, SGPropertyNode* targetNode) :
1319       simgear::HTTP::MemoryRequest(url),
1320       _target(targetNode)
1321     {
1322     }
1323     
1324     void setCompletionProp(SGPropertyNode_ptr p)
1325     {
1326         _complete = p;
1327     }
1328     
1329     void setStatusProp(SGPropertyNode_ptr p)
1330     {
1331         _status = p;
1332     }
1333     
1334     void setFailedProp(SGPropertyNode_ptr p)
1335     {
1336         _failed = p;
1337     }
1338     
1339 protected:
1340     
1341     virtual void onFail()
1342     {
1343         SG_LOG(SG_IO, SG_INFO, "network level failure in RemoteXMLRequest");
1344         if (_failed) {
1345             _failed->setBoolValue(true);
1346         }
1347     }
1348     
1349     virtual void onDone()
1350     {
1351         int response = responseCode();
1352         bool failed = false;
1353         if (response == 200) {
1354             try {
1355                 const char* buffer = responseBody().c_str();
1356                 readProperties(buffer, responseBody().size(), _target, true);
1357             } catch (const sg_exception &e) {
1358                 SG_LOG(SG_IO, SG_WARN, "parsing XML from remote, failed: " << e.getFormattedMessage());
1359                 failed = true;
1360                 response = 406; // 'not acceptable', anything better?
1361             }
1362         } else {
1363             failed = true;
1364         }
1365     // now the response data is output, signal Nasal / listeners
1366         if (_complete) _complete->setBoolValue(true);
1367         if (_status) _status->setIntValue(response);
1368         if (_failed && failed) _failed->setBoolValue(true);
1369     }
1370 };
1371
1372
1373 static bool
1374 do_load_xml_from_url(const SGPropertyNode * arg)
1375 {
1376     FGHTTPClient* http = static_cast<FGHTTPClient*>(globals->get_subsystem("http"));
1377     if (!http) {
1378         SG_LOG(SG_IO, SG_ALERT, "xmlhttprequest: HTTP client not running");
1379         return false;
1380     }
1381   
1382     std::string url(arg->getStringValue("url"));
1383     if (url.empty())
1384         return false;
1385         
1386     SGPropertyNode *targetnode;
1387     if (arg->hasValue("targetnode"))
1388         targetnode = fgGetNode(arg->getStringValue("targetnode"), true);
1389     else
1390         targetnode = const_cast<SGPropertyNode *>(arg)->getNode("data", true);
1391     
1392     RemoteXMLRequest* req = new RemoteXMLRequest(url, targetnode);
1393     
1394     if (arg->hasChild("body"))
1395         req->setBodyData(arg->getChild("body"));
1396     
1397 // connect up optional reporting properties
1398     if (arg->hasValue("complete")) 
1399         req->setCompletionProp(fgGetNode(arg->getStringValue("complete"), true));
1400     if (arg->hasValue("failure")) 
1401         req->setFailedProp(fgGetNode(arg->getStringValue("failure"), true));
1402     if (arg->hasValue("status")) 
1403         req->setStatusProp(fgGetNode(arg->getStringValue("status"), true));
1404         
1405     http->makeRequest(req);
1406     return true;
1407 }
1408
1409
1410 /**
1411  * An fgcommand to allow saving of xml files via nasal,
1412  * the file's structure will be determined based on what's
1413  * encountered in the passed (source) property tree node
1414  *
1415  * @param filename a string to hold the complete path & filename of the (new)
1416  * XML file
1417  * @param sourcenode a string pointing to a location within the property tree
1418  * where to find the nodes that should be written recursively into an XML file
1419  * @param data if no sourcenode is given, then the file contents are taken from
1420  * the argument tree's "data" node.
1421  */
1422
1423 static bool
1424 do_save_xml_from_proptree(const SGPropertyNode * arg)
1425 {
1426     SGPath file(arg->getStringValue("filename"));
1427     if (file.str().empty())
1428         return false;
1429
1430     if (file.extension() != "xml")
1431         file.concat(".xml");
1432
1433     if (!fgValidatePath(file.c_str(), true)) {
1434         SG_LOG(SG_IO, SG_ALERT, "savexml: writing to '" << file.str() << "' denied "
1435                 "(unauthorized access)");
1436         return false;
1437     }
1438
1439     SGPropertyNode *sourcenode;
1440     if (arg->hasValue("sourcenode"))
1441         sourcenode = fgGetNode(arg->getStringValue("sourcenode"), true);
1442     else if (arg->getNode("data", false))
1443         sourcenode = const_cast<SGPropertyNode *>(arg)->getNode("data");
1444     else
1445         return false;
1446
1447     try {
1448         writeProperties (file.c_str(), sourcenode, true);
1449     } catch (const sg_exception &e) {
1450         SG_LOG(SG_IO, SG_WARN, "savexml: " << e.getFormattedMessage());
1451         return false;
1452     }
1453
1454     return true;
1455 }
1456
1457 static bool
1458 do_press_cockpit_button (const SGPropertyNode *arg)
1459 {
1460   const char *prefix = arg->getStringValue("prefix");
1461
1462   if (arg->getBoolValue("guarded") && fgGetDouble((string(prefix) + "-guard").c_str()) < 1)
1463     return true;
1464
1465   string prop = string(prefix) + "-button";
1466   double value;
1467
1468   if (arg->getBoolValue("latching"))
1469     value = fgGetDouble(prop.c_str()) > 0 ? 0 : 1;
1470   else
1471     value = 1;
1472
1473   fgSetDouble(prop.c_str(), value);
1474   fgSetBool(arg->getStringValue("discrete"), value > 0);
1475
1476   return true;
1477 }
1478
1479 static bool
1480 do_release_cockpit_button (const SGPropertyNode *arg)
1481 {
1482   const char *prefix = arg->getStringValue("prefix");
1483
1484   if (arg->getBoolValue("guarded")) {
1485     string prop = string(prefix) + "-guard";
1486     if (fgGetDouble(prop.c_str()) < 1) {
1487       fgSetDouble(prop.c_str(), 1);
1488       return true;
1489     }
1490   }
1491
1492   if (! arg->getBoolValue("latching")) {
1493     fgSetDouble((string(prefix) + "-button").c_str(), 0);
1494     fgSetBool(arg->getStringValue("discrete"), false);
1495   }
1496
1497   return true;
1498 }
1499
1500 // Optional profiling commands using gperftools:
1501 // http://code.google.com/p/gperftools/
1502
1503 #if !FG_HAVE_GPERFTOOLS
1504 static void
1505 no_profiling_support()
1506 {
1507   SG_LOG
1508   (
1509     SG_GENERAL,
1510     SG_WARN,
1511     "No profiling support! Install gperftools and reconfigure/rebuild fgfs."
1512   );
1513 }
1514 #endif
1515
1516 static bool
1517 do_profiler_start(const SGPropertyNode *arg)
1518 {
1519 #if FG_HAVE_GPERFTOOLS
1520   const char *filename = arg->getStringValue("filename", "fgfs.profile");
1521   ProfilerStart(filename);
1522   return true;
1523 #else
1524   no_profiling_support();
1525   return false;
1526 #endif
1527 }
1528
1529 static bool
1530 do_profiler_stop(const SGPropertyNode *arg)
1531 {
1532 #if FG_HAVE_GPERFTOOLS
1533   ProfilerStop();
1534   return true;
1535 #else
1536   no_profiling_support();
1537   return false;
1538 #endif
1539 }
1540
1541
1542 ////////////////////////////////////////////////////////////////////////
1543 // Command setup.
1544 ////////////////////////////////////////////////////////////////////////
1545
1546
1547 /**
1548  * Table of built-in commands.
1549  *
1550  * New commands do not have to be added here; any module in the application
1551  * can add a new command using globals->get_commands()->addCommand(...).
1552  */
1553 static struct {
1554   const char * name;
1555   SGCommandMgr::command_t command;
1556 } built_ins [] = {
1557     { "null", do_null },
1558     { "nasal", do_nasal },
1559     { "exit", do_exit },
1560     { "reset", do_reset },
1561     { "reposition", do_reposition },
1562     { "pause", do_pause },
1563     { "load", do_load },
1564     { "save", do_save },
1565     { "save-tape", do_save_tape },
1566     { "load-tape", do_load_tape },
1567     { "panel-load", do_panel_load },
1568     { "preferences-load", do_preferences_load },
1569     { "toggle-fullscreen", do_toggle_fullscreen },
1570     { "view-cycle", do_view_cycle },
1571     { "screen-capture", do_screen_capture },
1572     { "hires-screen-capture", do_hires_screen_capture },
1573     { "tile-cache-reload", do_tile_cache_reload },
1574     /*
1575     { "set-sea-level-air-temp-degc", do_set_sea_level_degc },
1576     { "set-outside-air-temp-degc", do_set_oat_degc },
1577     { "set-dewpoint-sea-level-air-temp-degc", do_set_dewpoint_sea_level_degc },
1578     { "set-dewpoint-temp-degc", do_set_dewpoint_degc },
1579     */
1580     { "property-toggle", do_property_toggle },
1581     { "property-assign", do_property_assign },
1582     { "property-adjust", do_property_adjust },
1583     { "property-multiply", do_property_multiply },
1584     { "property-swap", do_property_swap },
1585     { "property-scale", do_property_scale },
1586     { "property-cycle", do_property_cycle },
1587     { "property-randomize", do_property_randomize },
1588     { "property-interpolate", do_property_interpolate },
1589     { "data-logging-commit", do_data_logging_commit },
1590     { "dialog-new", do_dialog_new },
1591     { "dialog-show", do_dialog_show },
1592     { "dialog-close", do_dialog_close },
1593     { "dialog-update", do_dialog_update },
1594     { "dialog-apply", do_dialog_apply },
1595     { "open-browser", do_open_browser },
1596     { "gui-redraw", do_gui_redraw },
1597     { "add-model", do_add_model },
1598     { "play-audio-sample", do_play_audio_sample },
1599     { "presets-commit", do_presets_commit },
1600     { "log-level", do_log_level },
1601     { "replay", do_replay },
1602     /*
1603     { "decrease-visibility", do_decrease_visibility },
1604     { "increase-visibility", do_increase_visibility },
1605     */
1606     { "loadxml", do_load_xml_to_proptree},
1607     { "savexml", do_save_xml_from_proptree },
1608     { "xmlhttprequest", do_load_xml_from_url },
1609     { "press-cockpit-button", do_press_cockpit_button },
1610     { "release-cockpit-button", do_release_cockpit_button },
1611     { "dump-scenegraph", do_dump_scene_graph },
1612     { "dump-terrainbranch", do_dump_terrain_branch },
1613     { "print-visible-scene", do_print_visible_scene_info },
1614     { "reload-shaders", do_reload_shaders },
1615     { "reload-materials", do_materials_reload },
1616
1617     { "profiler-start", do_profiler_start },
1618     { "profiler-stop",  do_profiler_stop },
1619
1620     { 0, 0 }                    // zero-terminated
1621 };
1622
1623
1624 /**
1625  * Initialize the default built-in commands.
1626  *
1627  * Other commands may be added by other parts of the application.
1628  */
1629 void
1630 fgInitCommands ()
1631 {
1632   SG_LOG(SG_GENERAL, SG_BULK, "Initializing basic built-in commands:");
1633   for (int i = 0; built_ins[i].name != 0; i++) {
1634     SG_LOG(SG_GENERAL, SG_BULK, "  " << built_ins[i].name);
1635     globals->get_commands()->addCommand(built_ins[i].name,
1636                                         built_ins[i].command);
1637   }
1638
1639   typedef bool (*dummy)();
1640   fgTie( "/command/view/next", dummy(0), do_view_next );
1641   fgTie( "/command/view/prev", dummy(0), do_view_prev );
1642
1643   globals->get_props()->setValueReadOnly( "/sim/debug/profiler-available",
1644                                           bool(FG_HAVE_GPERFTOOLS) );
1645 }
1646
1647 // end of fg_commands.cxx