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