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