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