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