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