]> git.mxchange.org Git - flightgear.git/blob - src/Main/fg_commands.cxx
Update/simplify property interpolation to latest SimGear changes
[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     int selection = -1;
840     int nSelections = values.size();
841
842     if (nSelections < 1) {
843         SG_LOG(SG_GENERAL, SG_ALERT, "No values for property-cycle");
844         return false;
845     }
846
847                                 // Try to find the current selection
848     for (int i = 0; i < nSelections; i++) {
849         if (compare_values(prop, values[i])) {
850             selection = i + 1;
851             break;
852         }
853     }
854
855                                 // Default or wrap to the first selection
856     if (selection < 0 || selection >= nSelections)
857         selection = 0;
858
859     prop->setUnspecifiedValue(values[selection]->getStringValue());
860     return true;
861 }
862
863
864 /**
865  * Built-in command: randomize a numeric property value.
866  *
867  * property: the name of the property value to randomize.
868  * min: the minimum allowed value.
869  * max: the maximum allowed value.
870  */
871 static bool
872 do_property_randomize (const SGPropertyNode * arg)
873 {
874     SGPropertyNode * prop = get_prop(arg);
875     double min = arg->getDoubleValue("min", DBL_MIN);
876     double max = arg->getDoubleValue("max", DBL_MAX);
877     prop->setDoubleValue(sg_random() * (max - min) + min);
878     return true;
879 }
880
881 /**
882  * Built-in command: interpolate a property value over time
883  *
884  * property:        the name of the property value to interpolate.
885  * type:            the interpolation type ("numeric", "color", etc.)
886  * easing:          name of easing function (see http://easings.net/)
887  * value[0..n]      any number of constant values to interpolate
888  * time/rate[0..n]  time between each value, number of time elements must
889  *                  match those of value elements. Instead of time also rate can
890  *                  be used which automatically calculates the time to change
891  *                  the property value at the given speed.
892  * -or-
893  * property[1..n+1] any number of target values taken from named properties
894  * time/rate[0..n]  time between each value, number of time elements must
895  *                  match those of value elements. Instead of time also rate can
896  *                  be used which automatically calculates the time to change
897  *                  the property value at the given speed.
898  */
899 static bool
900 do_property_interpolate (const SGPropertyNode * arg)
901 {
902   SGPropertyNode * prop = get_prop(arg);
903   if( !prop )
904     return false;
905
906   simgear::PropertyList time_nodes = arg->getChildren("time");
907   simgear::PropertyList rate_nodes = arg->getChildren("rate");
908
909   if( !time_nodes.empty() && !rate_nodes.empty() )
910     // mustn't specify time and rate
911     return false;
912
913   simgear::PropertyList::size_type num_times = time_nodes.empty()
914                                              ? rate_nodes.size()
915                                              : time_nodes.size();
916
917   simgear::PropertyList value_nodes = arg->getChildren("value");
918   if( value_nodes.empty() )
919   {
920     simgear::PropertyList prop_nodes = arg->getChildren("property");
921
922     // must have one more property node
923     if( prop_nodes.size() != num_times + 1 )
924       return false;
925
926     value_nodes.reserve(num_times);
927     for( size_t i = 1; i < prop_nodes.size(); ++i )
928       value_nodes.push_back( fgGetNode(prop_nodes[i]->getStringValue()) );
929   }
930
931   // must match
932   if( value_nodes.size() != num_times )
933     return false;
934
935   double_list deltas;
936   deltas.reserve(num_times);
937
938   if( !time_nodes.empty() )
939   {
940     for( size_t i = 0; i < num_times; ++i )
941       deltas.push_back( time_nodes[i]->getDoubleValue() );
942   }
943   else
944   {
945     for( size_t i = 0; i < num_times; ++i )
946     {
947       // TODO calculate delta based on property type
948       double delta = value_nodes[i]->getDoubleValue()
949                    - ( i > 0
950                      ? value_nodes[i - 1]->getDoubleValue()
951                      : prop->getDoubleValue()
952                      );
953       deltas.push_back( fabs(delta / rate_nodes[i]->getDoubleValue()) );
954     }
955   }
956
957   return prop->interpolate
958   (
959     arg->getStringValue("type", "numeric"),
960     value_nodes,
961     deltas,
962     arg->getStringValue("easing", "linear")
963   );
964 }
965
966 /**
967  * Built-in command: reinit the data logging system based on the
968  * current contents of the /logger tree.
969  */
970 static bool
971 do_data_logging_commit (const SGPropertyNode * arg)
972 {
973     FGLogger *log = (FGLogger *)globals->get_subsystem("logger");
974     log->reinit();
975     return true;
976 }
977
978 /**
979  * Built-in command: Add a dialog to the GUI system.  Does *not*
980  * display the dialog.  The property node should have the same format
981  * as a dialog XML configuration.  It must include:
982  *
983  * name: the name of the GUI dialog for future reference.
984  */
985 static bool
986 do_dialog_new (const SGPropertyNode * arg)
987 {
988     NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
989     if (!gui) {
990       return false;
991     }
992   
993     // Note the casting away of const: this is *real*.  Doing a
994     // "dialog-apply" command later on will mutate this property node.
995     // I'm not convinced that this isn't the Right Thing though; it
996     // allows client to create a node, pass it to dialog-new, and get
997     // the values back from the dialog by reading the same node.
998     // Perhaps command arguments are not as "const" as they would
999     // seem?
1000     gui->newDialog((SGPropertyNode*)arg);
1001     return true;
1002 }
1003
1004 /**
1005  * Built-in command: Show an XML-configured dialog.
1006  *
1007  * dialog-name: the name of the GUI dialog to display.
1008  */
1009 static bool
1010 do_dialog_show (const SGPropertyNode * arg)
1011 {
1012     NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1013     gui->showDialog(arg->getStringValue("dialog-name"));
1014     return true;
1015 }
1016
1017
1018 /**
1019  * Built-in Command: Hide the active XML-configured dialog.
1020  */
1021 static bool
1022 do_dialog_close (const SGPropertyNode * arg)
1023 {
1024     NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1025     if(arg->hasValue("dialog-name"))
1026         return gui->closeDialog(arg->getStringValue("dialog-name"));
1027     return gui->closeActiveDialog();
1028 }
1029
1030
1031 /**
1032  * Update a value in the active XML-configured dialog.
1033  *
1034  * object-name: The name of the GUI object(s) (all GUI objects if omitted).
1035  */
1036 static bool
1037 do_dialog_update (const SGPropertyNode * arg)
1038 {
1039     NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1040     FGDialog * dialog;
1041     if (arg->hasValue("dialog-name"))
1042         dialog = gui->getDialog(arg->getStringValue("dialog-name"));
1043     else
1044         dialog = gui->getActiveDialog();
1045
1046     if (dialog != 0) {
1047         dialog->updateValues(arg->getStringValue("object-name"));
1048         return true;
1049     } else {
1050         return false;
1051     }
1052 }
1053
1054 static bool
1055 do_open_browser (const SGPropertyNode * arg)
1056 {
1057     string path;
1058     if (arg->hasValue("path"))
1059         path = arg->getStringValue("path");
1060     else
1061     if (arg->hasValue("url"))
1062         path = arg->getStringValue("url");
1063     else
1064         return false;
1065
1066     return openBrowser(path);
1067 }
1068
1069 /**
1070  * Apply a value in the active XML-configured dialog.
1071  *
1072  * object-name: The name of the GUI object(s) (all GUI objects if omitted).
1073  */
1074 static bool
1075 do_dialog_apply (const SGPropertyNode * arg)
1076 {
1077     NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1078     FGDialog * dialog;
1079     if (arg->hasValue("dialog-name"))
1080         dialog = gui->getDialog(arg->getStringValue("dialog-name"));
1081     else
1082         dialog = gui->getActiveDialog();
1083
1084     if (dialog != 0) {
1085         dialog->applyValues(arg->getStringValue("object-name"));
1086         return true;
1087     } else {
1088         return false;
1089     }
1090 }
1091
1092
1093 /**
1094  * Redraw GUI (applying new widget colors). Doesn't reload the dialogs,
1095  * unlike reinit().
1096  */
1097 static bool
1098 do_gui_redraw (const SGPropertyNode * arg)
1099 {
1100     NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1101     gui->redraw();
1102     return true;
1103 }
1104
1105
1106 /**
1107  * Adds model to the scenery. The path to the added branch (/models/model[*])
1108  * is returned in property "property".
1109  */
1110 static bool
1111 do_add_model (const SGPropertyNode * arg)
1112 {
1113     SGPropertyNode * model = fgGetNode("models", true);
1114     int i;
1115     for (i = 0; model->hasChild("model",i); i++);
1116     model = model->getChild("model", i, true);
1117     copyProperties(arg, model);
1118     if (model->hasValue("elevation-m"))
1119         model->setDoubleValue("elevation-ft", model->getDoubleValue("elevation-m")
1120                 * SG_METER_TO_FEET);
1121     model->getNode("load", true);
1122     model->removeChildren("load");
1123     const_cast<SGPropertyNode *>(arg)->setStringValue("property", model->getPath());
1124     return true;
1125 }
1126
1127 /**
1128  * Built-in command: play an audio message (i.e. a wav file) This is
1129  * fire and forget.  Call this once per message and it will get dumped
1130  * into a queue.  Messages are played sequentially so they do not
1131  * overlap.
1132  */
1133 static bool
1134 do_play_audio_sample (const SGPropertyNode * arg)
1135 {
1136     SGSoundMgr *smgr = globals->get_soundmgr();
1137     if (!smgr) {
1138         SG_LOG(SG_GENERAL, SG_WARN, "play-audio-sample: sound-manager not running");
1139         return false;
1140     }
1141   
1142     string path = arg->getStringValue("path");
1143     string file = arg->getStringValue("file");
1144     float volume = arg->getFloatValue("volume");
1145     // cout << "playing " << path << " / " << file << endl;
1146     try {
1147         static FGSampleQueue *queue = 0;
1148         if ( !queue ) {
1149            queue = new FGSampleQueue(smgr, "chatter");
1150            queue->tie_to_listener();
1151         }
1152
1153         SGSoundSample *msg = new SGSoundSample(file.c_str(), path);
1154         msg->set_volume( volume );
1155         queue->add( msg );
1156
1157         return true;
1158
1159     } catch (const sg_io_exception&) {
1160         SG_LOG(SG_GENERAL, SG_ALERT, "play-audio-sample: "
1161                 "failed to load" << path << '/' << file);
1162         return false;
1163     }
1164 }
1165
1166 /**
1167  * Built-in command: commit presets (read from in /sim/presets/)
1168  */
1169 static bool
1170 do_presets_commit (const SGPropertyNode * arg)
1171 {
1172     if (fgGetBool("/sim/initialized", false)) {
1173       fgReInitSubsystems();
1174     } else {
1175       // Nasal can trigger this during initial init, which confuses
1176       // the logic in ReInitSubsystems, since initial state has not been
1177       // saved at that time. Short-circuit everything here.
1178       flightgear::initPosition();
1179     }
1180     
1181     return true;
1182 }
1183
1184 /**
1185  * Built-in command: set log level (0 ... 7)
1186  */
1187 static bool
1188 do_log_level (const SGPropertyNode * arg)
1189 {
1190    sglog().setLogLevels( SG_ALL, (sgDebugPriority)arg->getIntValue() );
1191
1192    return true;
1193 }
1194
1195 /*
1196 static bool
1197 do_decrease_visibility (const SGPropertyNode * arg)
1198 {
1199     Environment::Presets::VisibilitySingleton::instance()->adjust( 0.9 );
1200     return true;
1201 }
1202  
1203 static bool
1204 do_increase_visibility (const SGPropertyNode * arg)
1205 {
1206     Environment::Presets::VisibilitySingleton::instance()->adjust( 1.1 );
1207     return true;
1208 }
1209 */
1210 /**
1211  * An fgcommand to allow loading of xml files via nasal,
1212  * the xml file's structure will be made available within
1213  * a property tree node defined under argument "targetnode",
1214  * or in the given argument tree under "data" otherwise.
1215  *
1216  * @param filename a string to hold the complete path & filename of an XML file
1217  * @param targetnode a string pointing to a location within the property tree
1218  * where to store the parsed XML file. If <targetnode> is undefined, then the
1219  * file contents are stored under a node <data> in the argument tree.
1220  */
1221
1222 static bool
1223 do_load_xml_to_proptree(const SGPropertyNode * arg)
1224 {
1225     SGPath file(arg->getStringValue("filename"));
1226     if (file.str().empty())
1227         return false;
1228
1229     if (file.extension() != "xml")
1230         file.concat(".xml");
1231     
1232     std::string icao = arg->getStringValue("icao");
1233     if (icao.empty()) {
1234         if (file.isRelative()) {
1235           SGPath absPath = globals->resolve_maybe_aircraft_path(file.str());
1236           if (!absPath.isNull())
1237               file = absPath;
1238           else
1239           {
1240               SG_LOG(SG_IO, SG_ALERT, "loadxml: Cannot find XML property file '"  
1241                           << file.str() << "'.");
1242               return false;
1243           }
1244         }
1245     } else {
1246         if (!XMLLoader::findAirportData(icao, file.str(), file)) {
1247           SG_LOG(SG_IO, SG_INFO, "loadxml: failed to find airport data for "
1248             << file.str() << " at ICAO:" << icao);
1249           return false;
1250         }
1251     }
1252     
1253     if (!fgValidatePath(file.c_str(), false)) {
1254         SG_LOG(SG_IO, SG_ALERT, "loadxml: reading '" << file.str() << "' denied "
1255                 "(unauthorized access)");
1256         return false;
1257     }
1258
1259     SGPropertyNode *targetnode;
1260     if (arg->hasValue("targetnode"))
1261         targetnode = fgGetNode(arg->getStringValue("targetnode"), true);
1262     else
1263         targetnode = const_cast<SGPropertyNode *>(arg)->getNode("data", true);
1264
1265     try {
1266         readProperties(file.c_str(), targetnode, true);
1267     } catch (const sg_exception &e) {
1268         SG_LOG(SG_IO, SG_WARN, "loadxml: " << e.getFormattedMessage());
1269         return false;
1270     }
1271
1272     return true;
1273 }
1274
1275 class RemoteXMLRequest : public simgear::HTTP::Request
1276 {
1277 public:
1278     SGPropertyNode_ptr _complete;
1279     SGPropertyNode_ptr _status;
1280     SGPropertyNode_ptr _failed;
1281     SGPropertyNode_ptr _target;
1282     string propsData;
1283     mutable string _requestBody;
1284     int _requestBodyLength;
1285     string _method;
1286     
1287     RemoteXMLRequest(const std::string& url, SGPropertyNode* targetNode) :
1288         simgear::HTTP::Request(url),
1289         _target(targetNode),
1290         _requestBodyLength(-1),
1291         _method("GET")
1292     {
1293     }
1294     
1295     void setCompletionProp(SGPropertyNode_ptr p)
1296     {
1297         _complete = p;
1298     }
1299     
1300     void setStatusProp(SGPropertyNode_ptr p)
1301     {
1302         _status = p;
1303     }
1304     
1305     void setFailedProp(SGPropertyNode_ptr p)
1306     {
1307         _failed = p;
1308     }
1309   
1310     void setRequestData(const SGPropertyNode* body)
1311     {
1312         _method = "POST";
1313         std::stringstream buf;
1314         writeProperties(buf, body, true);
1315         _requestBody = buf.str();
1316         _requestBodyLength = _requestBody.size();
1317     }
1318     
1319     virtual std::string method() const
1320     {
1321         return _method;
1322     }
1323 protected:
1324     virtual int requestBodyLength() const
1325     {
1326         return _requestBodyLength;
1327     }
1328     
1329     virtual void getBodyData(char* s, int& count) const
1330     {
1331         int toRead = std::min(count, (int) _requestBody.size());
1332         memcpy(s, _requestBody.c_str(), toRead);
1333         count = toRead;
1334         _requestBody = _requestBody.substr(count);
1335     }
1336     
1337     virtual std::string requestBodyType() const
1338     {
1339         return "application/xml";
1340     }
1341     
1342     virtual void gotBodyData(const char* s, int n)
1343     {
1344         propsData += string(s, n);
1345     }
1346     
1347     virtual void failed()
1348     {
1349         SG_LOG(SG_IO, SG_INFO, "network level failure in RemoteXMLRequest");
1350         if (_failed) {
1351             _failed->setBoolValue(true);
1352         }
1353     }
1354     
1355     virtual void responseComplete()
1356     {
1357         simgear::HTTP::Request::responseComplete();
1358         
1359         int response = responseCode();
1360         bool failed = false;
1361         if (response == 200) {
1362             try {
1363                 const char* buffer = propsData.c_str();
1364                 readProperties(buffer, propsData.size(), _target, true);
1365             } catch (const sg_exception &e) {
1366                 SG_LOG(SG_IO, SG_WARN, "parsing XML from remote, failed: " << e.getFormattedMessage());
1367                 failed = true;
1368                 response = 406; // 'not acceptable', anything better?
1369             }
1370         } else {
1371             failed = true;
1372         }
1373     // now the response data is output, signal Nasal / listeners
1374         if (_complete) _complete->setBoolValue(true);
1375         if (_status) _status->setIntValue(response);
1376         if (_failed && failed) _failed->setBoolValue(true);
1377     }
1378 };
1379
1380
1381 static bool
1382 do_load_xml_from_url(const SGPropertyNode * arg)
1383 {
1384     FGHTTPClient* http = static_cast<FGHTTPClient*>(globals->get_subsystem("http"));
1385     if (!http) {
1386         SG_LOG(SG_IO, SG_ALERT, "xmlhttprequest: HTTP client not running");
1387         return false;
1388     }
1389   
1390     std::string url(arg->getStringValue("url"));
1391     if (url.empty())
1392         return false;
1393         
1394     SGPropertyNode *targetnode;
1395     if (arg->hasValue("targetnode"))
1396         targetnode = fgGetNode(arg->getStringValue("targetnode"), true);
1397     else
1398         targetnode = const_cast<SGPropertyNode *>(arg)->getNode("data", true);
1399     
1400     RemoteXMLRequest* req = new RemoteXMLRequest(url, targetnode);
1401     
1402     if (arg->hasChild("body"))
1403         req->setRequestData(arg->getChild("body"));
1404     
1405 // connect up optional reporting properties
1406     if (arg->hasValue("complete")) 
1407         req->setCompletionProp(fgGetNode(arg->getStringValue("complete"), true));
1408     if (arg->hasValue("failure")) 
1409         req->setFailedProp(fgGetNode(arg->getStringValue("failure"), true));
1410     if (arg->hasValue("status")) 
1411         req->setStatusProp(fgGetNode(arg->getStringValue("status"), true));
1412         
1413     http->makeRequest(req);
1414     return true;
1415 }
1416
1417
1418 /**
1419  * An fgcommand to allow saving of xml files via nasal,
1420  * the file's structure will be determined based on what's
1421  * encountered in the passed (source) property tree node
1422  *
1423  * @param filename a string to hold the complete path & filename of the (new)
1424  * XML file
1425  * @param sourcenode a string pointing to a location within the property tree
1426  * where to find the nodes that should be written recursively into an XML file
1427  * @param data if no sourcenode is given, then the file contents are taken from
1428  * the argument tree's "data" node.
1429  */
1430
1431 static bool
1432 do_save_xml_from_proptree(const SGPropertyNode * arg)
1433 {
1434     SGPath file(arg->getStringValue("filename"));
1435     if (file.str().empty())
1436         return false;
1437
1438     if (file.extension() != "xml")
1439         file.concat(".xml");
1440
1441     if (!fgValidatePath(file.c_str(), true)) {
1442         SG_LOG(SG_IO, SG_ALERT, "savexml: writing to '" << file.str() << "' denied "
1443                 "(unauthorized access)");
1444         return false;
1445     }
1446
1447     SGPropertyNode *sourcenode;
1448     if (arg->hasValue("sourcenode"))
1449         sourcenode = fgGetNode(arg->getStringValue("sourcenode"), true);
1450     else if (arg->getNode("data", false))
1451         sourcenode = const_cast<SGPropertyNode *>(arg)->getNode("data");
1452     else
1453         return false;
1454
1455     try {
1456         writeProperties (file.c_str(), sourcenode, true);
1457     } catch (const sg_exception &e) {
1458         SG_LOG(SG_IO, SG_WARN, "savexml: " << e.getFormattedMessage());
1459         return false;
1460     }
1461
1462     return true;
1463 }
1464
1465 static bool
1466 do_press_cockpit_button (const SGPropertyNode *arg)
1467 {
1468   const char *prefix = arg->getStringValue("prefix");
1469
1470   if (arg->getBoolValue("guarded") && fgGetDouble((string(prefix) + "-guard").c_str()) < 1)
1471     return true;
1472
1473   string prop = string(prefix) + "-button";
1474   double value;
1475
1476   if (arg->getBoolValue("latching"))
1477     value = fgGetDouble(prop.c_str()) > 0 ? 0 : 1;
1478   else
1479     value = 1;
1480
1481   fgSetDouble(prop.c_str(), value);
1482   fgSetBool(arg->getStringValue("discrete"), value > 0);
1483
1484   return true;
1485 }
1486
1487 static bool
1488 do_release_cockpit_button (const SGPropertyNode *arg)
1489 {
1490   const char *prefix = arg->getStringValue("prefix");
1491
1492   if (arg->getBoolValue("guarded")) {
1493     string prop = string(prefix) + "-guard";
1494     if (fgGetDouble(prop.c_str()) < 1) {
1495       fgSetDouble(prop.c_str(), 1);
1496       return true;
1497     }
1498   }
1499
1500   if (! arg->getBoolValue("latching")) {
1501     fgSetDouble((string(prefix) + "-button").c_str(), 0);
1502     fgSetBool(arg->getStringValue("discrete"), false);
1503   }
1504
1505   return true;
1506 }
1507
1508 // Optional profiling commands using gperftools:
1509 // http://code.google.com/p/gperftools/
1510
1511 #ifndef FG_HAVE_GPERFTOOLS
1512 static void
1513 no_profiling_support()
1514 {
1515   SG_LOG
1516   (
1517     SG_GENERAL,
1518     SG_WARN,
1519     "No profiling support! Install gperftools and reconfigure/rebuild fgfs."
1520   );
1521 }
1522 #endif
1523
1524 static bool
1525 do_profiler_start(const SGPropertyNode *arg)
1526 {
1527 #ifdef FG_HAVE_GPERFTOOLS
1528   const char *filename = arg->getStringValue("filename", "fgfs.profile");
1529   ProfilerStart(filename);
1530   return true;
1531 #else
1532   no_profiling_support();
1533   return false;
1534 #endif
1535 }
1536
1537 static bool
1538 do_profiler_stop(const SGPropertyNode *arg)
1539 {
1540 #ifdef FG_HAVE_GPERFTOOLS
1541   ProfilerStop();
1542   return true;
1543 #else
1544   no_profiling_support();
1545   return false;
1546 #endif
1547 }
1548
1549
1550 ////////////////////////////////////////////////////////////////////////
1551 // Command setup.
1552 ////////////////////////////////////////////////////////////////////////
1553
1554
1555 /**
1556  * Table of built-in commands.
1557  *
1558  * New commands do not have to be added here; any module in the application
1559  * can add a new command using globals->get_commands()->addCommand(...).
1560  */
1561 static struct {
1562   const char * name;
1563   SGCommandMgr::command_t command;
1564 } built_ins [] = {
1565     { "null", do_null },
1566     { "nasal", do_nasal },
1567     { "exit", do_exit },
1568     { "reset", do_reset },
1569     { "pause", do_pause },
1570     { "load", do_load },
1571     { "save", do_save },
1572     { "save-tape", do_save_tape },
1573     { "load-tape", do_load_tape },
1574     { "panel-load", do_panel_load },
1575     { "preferences-load", do_preferences_load },
1576     { "toggle-fullscreen", do_toggle_fullscreen },
1577     { "view-cycle", do_view_cycle },
1578     { "screen-capture", do_screen_capture },
1579     { "hires-screen-capture", do_hires_screen_capture },
1580     { "tile-cache-reload", do_tile_cache_reload },
1581     /*
1582     { "set-sea-level-air-temp-degc", do_set_sea_level_degc },
1583     { "set-outside-air-temp-degc", do_set_oat_degc },
1584     { "set-dewpoint-sea-level-air-temp-degc", do_set_dewpoint_sea_level_degc },
1585     { "set-dewpoint-temp-degc", do_set_dewpoint_degc },
1586     */
1587     { "property-toggle", do_property_toggle },
1588     { "property-assign", do_property_assign },
1589     { "property-adjust", do_property_adjust },
1590     { "property-multiply", do_property_multiply },
1591     { "property-swap", do_property_swap },
1592     { "property-scale", do_property_scale },
1593     { "property-cycle", do_property_cycle },
1594     { "property-randomize", do_property_randomize },
1595     { "property-interpolate", do_property_interpolate },
1596     { "data-logging-commit", do_data_logging_commit },
1597     { "dialog-new", do_dialog_new },
1598     { "dialog-show", do_dialog_show },
1599     { "dialog-close", do_dialog_close },
1600     { "dialog-update", do_dialog_update },
1601     { "dialog-apply", do_dialog_apply },
1602     { "open-browser", do_open_browser },
1603     { "gui-redraw", do_gui_redraw },
1604     { "add-model", do_add_model },
1605     { "play-audio-sample", do_play_audio_sample },
1606     { "presets-commit", do_presets_commit },
1607     { "log-level", do_log_level },
1608     { "replay", do_replay },
1609     /*
1610     { "decrease-visibility", do_decrease_visibility },
1611     { "increase-visibility", do_increase_visibility },
1612     */
1613     { "loadxml", do_load_xml_to_proptree},
1614     { "savexml", do_save_xml_from_proptree },
1615     { "xmlhttprequest", do_load_xml_from_url },
1616     { "press-cockpit-button", do_press_cockpit_button },
1617     { "release-cockpit-button", do_release_cockpit_button },
1618     { "dump-scenegraph", do_dump_scene_graph },
1619     { "dump-terrainbranch", do_dump_terrain_branch },
1620     { "print-visible-scene", do_print_visible_scene_info },
1621     { "reload-shaders", do_reload_shaders },
1622     { "reload-materials", do_materials_reload },
1623
1624     { "profiler-start", do_profiler_start },
1625     { "profiler-stop",  do_profiler_stop },
1626
1627     { 0, 0 }                    // zero-terminated
1628 };
1629
1630
1631 /**
1632  * Initialize the default built-in commands.
1633  *
1634  * Other commands may be added by other parts of the application.
1635  */
1636 void
1637 fgInitCommands ()
1638 {
1639   SG_LOG(SG_GENERAL, SG_BULK, "Initializing basic built-in commands:");
1640   for (int i = 0; built_ins[i].name != 0; i++) {
1641     SG_LOG(SG_GENERAL, SG_BULK, "  " << built_ins[i].name);
1642     globals->get_commands()->addCommand(built_ins[i].name,
1643                                         built_ins[i].command);
1644   }
1645
1646   typedef bool (*dummy)();
1647   fgTie( "/command/view/next", dummy(0), do_view_next );
1648   fgTie( "/command/view/prev", dummy(0), do_view_prev );
1649
1650   SGPropertyNode* profiler_available =
1651     globals->get_props()->getNode("/sim/debug/profiler-available", true);
1652 #ifdef FG_HAVE_GPERFTOOLS
1653   profiler_available->setBoolValue(true);
1654 #else
1655   profiler_available->setBoolValue(false);
1656 #endif
1657   profiler_available->setAttributes(SGPropertyNode::READ);
1658 }
1659
1660 // end of fg_commands.cxx