Debian Codegraph @

src/Main/fg_commands.cxx

raw symbols SCIP
1
2 /*
3 * SPDX-FileName: fg_commands.hxx
4 * SPDX-FileComment: built-in commands for FlightGear.
5 * SPDX-License-Identifier: GPL-2.0-or-later
6 */
7
8 #include <config.h>
9
10 #include <string.h> // strcmp()
11
12 #include <simgear/compiler.h>
13
14 #include <string>
15 #include <fstream>
16
17 #include <simgear/debug/ErrorReportingCallback.hxx>
18 #include <simgear/debug/logstream.hxx>
19 #include <simgear/io/iostreams/sgstream.hxx>
20 #include <simgear/math/sg_random.hxx>
21 #include <simgear/misc/simgear_optional.hxx>
22 #include <simgear/props/props.hxx>
23 #include <simgear/props/props_io.hxx>
24 #include <simgear/sg_inlines.h>
25 #include <simgear/structure/commands.hxx>
26 #include <simgear/structure/event_mgr.hxx>
27 #include <simgear/structure/exception.hxx>
28 #include <simgear/timing/sg_time.hxx>
29
30 #include <Network/RemoteXMLRequest.hxx>
31
32 #include <FDM/flight.hxx>
33 #include <Aircraft/replay.hxx>
34 #include <Scripting/NasalSys.hxx>
35 #include <Airports/xmlloader.hxx>
36 #include <Network/HTTPClient.hxx>
37 #include <Viewer/viewmgr.hxx>
38 #include <Viewer/view.hxx>
39 #include <Environment/presets.hxx>
40 #include <Navaids/NavDataCache.hxx>
41 #include <GUI/gui.h>
42 #include <Main/sentryIntegration.hxx>
43
44 #include "fg_init.hxx"
45 #include "fg_io.hxx"
46 #include "fg_os.hxx"
47 #include "fg_commands.hxx"
48 #include "fg_props.hxx"
49 #include "globals.hxx"
50 #include "logger.hxx"
51 #include "main.hxx"
52 #include "positioninit.hxx"
53
54 #if FG_HAVE_GPERFTOOLS
55 # include <google/profiler.h>
56 #endif
57
58 using std::string;
59 using std::ifstream;
60 using std::ofstream;
61
62
63 ////////////////////////////////////////////////////////////////////////
64 // Static helper functions.
65 ////////////////////////////////////////////////////////////////////////
66
67
68 static inline SGPropertyNode *
69 get_prop (const SGPropertyNode * arg, SGPropertyNode * root)
70 {
71 if (root != nullptr)
72 {
73 SGPropertyNode *rv = nullptr;
74 rv = root->getNode(arg->getStringValue("property[0]", "/null"), true);
75 if (rv == nullptr)
76 {
77 rv = root->getNode(arg->getStringValue("property[0]", "/null"), true);
78 return fgGetNode(arg->getStringValue("property[0]", "/null"), true);
79 }
80 return rv;
81 }
82 return fgGetNode(arg->getStringValue("property[0]", "/null"), true);
83 }
84
85 static inline SGPropertyNode *
86 get_prop2 (const SGPropertyNode * arg, SGPropertyNode * root)
87 {
88 if (root != nullptr)
89 {
90 SGPropertyNode *rv = nullptr;
91 rv = root->getNode(arg->getStringValue("property[1]", "/null"), true);
92 if (rv == nullptr)
93 {
94 rv = root->getNode(arg->getStringValue("property[1]", "/null"), true);
95 return fgGetNode(arg->getStringValue("property[1]", "/null"), true);
96 }
97 return rv;
98 }
99 return fgGetNode(arg->getStringValue("property[1]", "/null"), true);
100 }
101
102
103 /**
104 * Get a double value and split it as required.
105 */
106 static void
107 split_value (double full_value, const char * mask,
108 double * unmodifiable, double * modifiable)
109 {
110 if (!strcmp("integer", mask)) {
111 *modifiable = (full_value < 0 ? ceil(full_value) : floor (full_value));
112 *unmodifiable = full_value - *modifiable;
113 } else if (!strcmp("decimal", mask)) {
114 *unmodifiable = (full_value < 0 ? ceil(full_value) : floor(full_value));
115 *modifiable = full_value - *unmodifiable;
116 } else {
117 if (strcmp("all", mask))
118 SG_LOG(SG_GENERAL, SG_ALERT, "Bad value " << mask << " for mask;"
119 << " assuming 'all'");
120 *unmodifiable = 0;
121 *modifiable = full_value;
122 }
123 }
124
125 /**
126 * @brief Retrive a typed value from a node, either from <foo> directly or indirectly
127 *
128 * @param node - base node from the command to look inside
129 * @param name - direct name of the argument, eg 'min' or 'max'
130 * @param indirectName - indirect name to use, eg, 'min-path'. If empty, the name is formed using the base
131 * name and appending '-prop', eg 'min-prop' and 'max-prop'.
132 * @return std::optional<T>
133 */
134 template <class T>
135 static simgear::optional<T>
136 getValueIndirect(const SGPropertyNode* node, const std::string& name, const std::string& indirectName = {})
137 {
138 auto indirectNode = node->getChild(indirectName.empty() ? (name + "-prop") : indirectName);
139 if (indirectNode) {
140 const auto resolvedNode = fgGetNode(indirectNode->getStringValue());
141 if (resolvedNode) {
142 return resolvedNode->getValue<T>();
143 }
144
145 // if the path is not valid, warn
146 SG_LOG(SG_GENERAL, SG_DEV_WARN, "getValueIndirect: property:" << indirectNode->getNameString() << " has value '" << indirectNode->getStringValue() << "' which was not found in the global property tree. Falling back to "
147 "value defined by argument '"
148 << name << "'");
149
150 // deliberate fall through here, so we use the value from the direct prop
151 }
152
153 auto directNode = node->getChild(name);
154 if (directNode)
155 return directNode->getValue<T>();
156
157 return {};
158 }
159
160 /**
161 * Clamp or wrap a value as specified.
162 */
163 static double
164 limit_value(double value, const SGPropertyNode* arg)
165 {
166 const auto minv = getValueIndirect<double>(arg, "min");
167 const auto maxv = getValueIndirect<double>(arg, "max");
168
169 // we can wrap only if requested, and
170 const bool canWrap = (minv && maxv);
171 const bool wantsWrap = arg->getBoolValue("wrap");
172 const bool wrap = canWrap && wantsWrap;
173 if (wantsWrap && !canWrap) {
174 SG_LOG(SG_GENERAL, SG_DEV_WARN, "limit_value: wrap requested, but no min/max values defined");
175 }
176
177 if (wrap) { // wrap such that min <= x < max
178 const double resolution = arg->getDoubleValue("resolution");
179 if (resolution > 0.0) {
180 // snap to (min + N*resolution), taking special care to handle imprecision
181 int n = (int)floor((value - minv.value()) / resolution + 0.5);
182 int steps = (int)floor((maxv.value() - minv.value()) / resolution + 0.5);
183 SG_NORMALIZE_RANGE(n, 0, steps);
184 return minv.value() + resolution * n;
185 } else {
186 // plain circular wrapping
187 return SGMiscd::normalizePeriodic(minv.value(), maxv.value(), value);
188 }
189 } else { // clamp such that min <= x <= max
190 if (minv && (value < minv.value())) {
191 return minv.value();
192 }
193
194 if (maxv && (value > maxv.value())) {
195 return maxv.value();
196 }
197 }
198
199 return value; // return unmodified value
200 }
201
202 static bool
203 compare_values (SGPropertyNode * value1, SGPropertyNode * value2)
204 {
205 switch (value1->getType()) {
206 case simgear::props::BOOL:
207 return (value1->getBoolValue() == value2->getBoolValue());
208 case simgear::props::INT:
209 return (value1->getIntValue() == value2->getIntValue());
210 case simgear::props::LONG:
211 return (value1->getLongValue() == value2->getLongValue());
212 case simgear::props::FLOAT:
213 return (value1->getFloatValue() == value2->getFloatValue());
214 case simgear::props::DOUBLE:
215 return (value1->getDoubleValue() == value2->getDoubleValue());
216 default:
217 return value1->getStringValue() == value2->getStringValue();
218 }
219 }
220
221
222
223 ////////////////////////////////////////////////////////////////////////
224 // Command implementations.
225 ////////////////////////////////////////////////////////////////////////
226
227
228 /**
229 * Built-in command: do nothing.
230 */
231 static bool
232 do_null (const SGPropertyNode * arg, SGPropertyNode * root)
233 {
234 return true;
235 }
236
237 /**
238 * Built-in command: run a Nasal script.
239 */
240 static bool
241 do_nasal (const SGPropertyNode * arg, SGPropertyNode * root)
242 {
243 auto nasalSys = globals->get_subsystem<FGNasalSys>();
244 if (!nasalSys) {
245 SG_LOG(SG_GUI, SG_ALERT, "do_nasal command: Nasal subsystem not found");
246 return false;
247 }
248
249 return nasalSys->handleCommand(arg, root);
250 }
251
252 /**
253 * Built-in command: replay the FDR buffer
254 */
255 static bool
256 do_replay (const SGPropertyNode * arg, SGPropertyNode * root)
257 {
258 auto r = globals->get_subsystem<FGReplay>();
259 return r->start();
260 }
261
262 /**
263 * Built-in command: pause/unpause the sim
264 */
265 static bool
266 do_pause (const SGPropertyNode * arg, SGPropertyNode * root)
267 {
268 bool forcePause = arg->getBoolValue("force-pause", false );
269 bool forcePlay = arg->getBoolValue("force-play", false );
270
271 bool paused = fgGetBool("/sim/freeze/master",true) || fgGetBool("/sim/freeze/clock",true);
272
273 if(forcePause) paused = false;
274 if(forcePlay) paused = true;
275
276 if (paused && (fgGetInt("/sim/freeze/replay-state",0)>0))
277 {
278 do_replay(NULL, nullptr);
279 }
280 else
281 {
282 fgSetBool("/sim/freeze/master",!paused);
283 fgSetBool("/sim/freeze/clock",!paused);
284 }
285
286 syncPausePopupState();
287 return true;
288 }
289
290 /**
291 * Built-in command: load flight.
292 *
293 * file (optional): the name of the file to load (relative to current
294 * directory). Defaults to "fgfs.sav"
295 */
296 static bool
297 do_load (const SGPropertyNode * arg, SGPropertyNode * root)
298 {
299 SGPath file(arg->getStringValue("file", "fgfs.sav").c_str());
300
301 if (file.extension() != "sav")
302 file.concat(".sav");
303
304 const SGPath validated_path = SGPath(file).validate(false);
305 if (validated_path.isNull()) {
306 SG_LOG(SG_IO, SG_ALERT, "load: reading '" << file << "' denied "
307 "(unauthorized access)");
308 return false;
309 }
310
311 sg_ifstream input(validated_path);
312 if (input.good() && fgLoadFlight(input)) {
313 input.close();
314 SG_LOG(SG_INPUT, SG_INFO, "Restored flight from " << file);
315 return true;
316 } else {
317 SG_LOG(SG_INPUT, SG_WARN, "Cannot load flight from " << file);
318 return false;
319 }
320 }
321
322
323 /**
324 * Built-in command: save flight.
325 *
326 * file (optional): the name of the file to save (relative to the
327 * current directory). Defaults to "fgfs.sav".
328 */
329 static bool
330 do_save (const SGPropertyNode * arg, SGPropertyNode * root)
331 {
332 SGPath file(arg->getStringValue("file", "fgfs.sav").c_str());
333
334 if (file.extension() != "sav")
335 file.concat(".sav");
336
337 const SGPath validated_path = SGPath(file).validate(true);
338 if (validated_path.isNull()) {
339 SG_LOG(SG_IO, SG_ALERT, "save: writing '" << file << "' denied "
340 "(unauthorized access)");
341 return false;
342 }
343
344 bool write_all = arg->getBoolValue("write-all", false);
345 SG_LOG(SG_INPUT, SG_INFO, "Saving flight");
346 sg_ofstream output(validated_path);
347 if (output.good() && fgSaveFlight(output, write_all)) {
348 output.close();
349 SG_LOG(SG_INPUT, SG_INFO, "Saved flight to " << file);
350 return true;
351 } else {
352 SG_LOG(SG_INPUT, SG_ALERT, "Cannot save flight to " << file);
353 return false;
354 }
355 }
356
357 /**
358 * Built-in command: save flight recorder tape.
359 *
360 */
361 static bool
362 do_save_tape (const SGPropertyNode * arg, SGPropertyNode * root)
363 {
364 auto replay = globals->get_subsystem<FGReplay>();
365 replay->saveTape(arg);
366
367 return true;
368 }
369 /**
370 * Built-in command: load flight recorder tape.
371 *
372 */
373 static bool
374 do_load_tape (const SGPropertyNode * arg, SGPropertyNode * root)
375 {
376 auto replay = globals->get_subsystem<FGReplay>();
377 replay->loadTape(arg);
378
379 return true;
380 }
381
382 static void
383 do_view_next(bool do_it)
384 {
385 // Only switch view if really requested to do so (and not for example while
386 // reset/reposition where /command/view/next is set to false)
387 if( do_it )
388 {
389 globals->get_current_view()->setHeadingOffset_deg(0.0);
390 globals->get_viewmgr()->next_view();
391 }
392 }
393
394 static void
395 do_view_prev(bool do_it)
396 {
397 if( do_it )
398 {
399 globals->get_current_view()->setHeadingOffset_deg(0.0);
400 globals->get_viewmgr()->prev_view();
401 }
402 }
403
404 /**
405 * Built-in command: cycle view.
406 */
407 static bool
408 do_view_cycle (const SGPropertyNode * arg, SGPropertyNode * root)
409 {
410 globals->get_current_view()->setHeadingOffset_deg(0.0);
411 globals->get_viewmgr()->next_view();
412 return true;
413 }
414
415
416 /**
417 * Built-in command: view-push.
418 */
419 static bool
420 do_view_push (const SGPropertyNode * arg, SGPropertyNode * root)
421 {
422 SG_LOG(SG_GENERAL, SG_DEBUG, "do_view_push() called");
423 globals->get_viewmgr()->view_push();
424 return true;
425 }
426
427
428 /**
429 * Built-in command: clone view.
430 */
431 static bool
432 do_view_clone (const SGPropertyNode * arg, SGPropertyNode * root)
433 {
434 SG_LOG(SG_GENERAL, SG_DEBUG, "do_view_clone() called");
435 globals->get_viewmgr()->clone_current_view(arg);
436 return true;
437 }
438
439
440 /**
441 * Built-in command: view last pair.
442 */
443 static bool
444 do_view_last_pair (const SGPropertyNode * arg, SGPropertyNode * root)
445 {
446 SG_LOG(SG_GENERAL, SG_DEBUG, "do_view_last_pair() called");
447 globals->get_viewmgr()->clone_last_pair(arg);
448 return true;
449 }
450
451
452 /**
453 * Built-in command: double view last pair.
454 */
455 static bool
456 do_view_last_pair_double (const SGPropertyNode * arg, SGPropertyNode * root)
457 {
458 SG_LOG(SG_GENERAL, SG_DEBUG, "do_view_last_pair_double() called");
459 globals->get_viewmgr()->clone_last_pair_double(arg);
460 return true;
461 }
462
463
464 /**
465 * Built-in command: double view last pair.
466 */
467 static bool
468 do_view_new (const SGPropertyNode * arg, SGPropertyNode * root)
469 {
470 SG_LOG(SG_GENERAL, SG_ALERT, "do_view_new() called");
471 globals->get_viewmgr()->view_new(arg);
472 return true;
473 }
474
475 /**
476 * Built-in command: video-start.
477 *
478 * If arg->name exists, we use it as the leafname of the generated video,
479 * appending '.'+{/sim/video/container} if it doesn't contain '.' already.
480 *
481 * Otherwise we use:
482 * fgvideo-{/sim/aircraft}-YYMMDD-HHMMSS.{/sim/video/container}
483 *
484 * The video file is generated in directory {/sim/paths/screenshot-dir}.
485 *
486 * We also create a convenience link in the same directory called
487 * fgvideo-{/sim/aircraft}.<suffix> (where <suffix> is the same suffix as the
488 * recording file) that points to the video file.
489 */
490 static bool
491 do_video_start (const SGPropertyNode * arg, SGPropertyNode * root)
492 {
493 auto view_mgr = globals->get_subsystem<FGViewMgr>();
494 if (!view_mgr) return false;
495 view_mgr->video_start(
496 arg->getStringValue("name"),
497 arg->getStringValue("codec"),
498 arg->getDoubleValue("quality", -1),
499 arg->getDoubleValue("speed", -1),
500 arg->getIntValue("bitrate", 0)
501 );
502 return true;
503 }
504
505 /**
506 * Built-in command: video-stop.
507 */
508 static bool
509 do_video_stop (const SGPropertyNode * arg, SGPropertyNode * root)
510 {
511 auto view_mgr = globals->get_subsystem<FGViewMgr>();
512 if (!view_mgr) return false;
513 view_mgr->video_stop();
514 return true;
515 }
516
517 /**
518 * Built-in command: toggle a bool property value.
519 *
520 * property: The name of the property to toggle.
521 */
522 static bool
523 do_property_toggle (const SGPropertyNode * arg, SGPropertyNode * root)
524 {
525 SGPropertyNode * prop = get_prop(arg, root);
526 return prop->setBoolValue(!prop->getBoolValue());
527 }
528
529
530 /**
531 * Built-in command: assign a value to a property.
532 *
533 * property: the name of the property to assign.
534 * value: the value to assign; or
535 * property[1]: the property to copy from.
536 */
537 static bool
538 do_property_assign (const SGPropertyNode * arg, SGPropertyNode * root)
539 {
540 SGPropertyNode * prop = get_prop(arg,root);
541 const SGPropertyNode * value = arg->getNode("value");
542
543 if (value != 0)
544 return prop->setUnspecifiedValue(value->getStringValue());
545 else
546 {
547 const SGPropertyNode * prop2 = get_prop2(arg,root);
548 if (prop2)
549 return prop->setUnspecifiedValue(prop2->getStringValue());
550 else
551 return false;
552 }
553 }
554
555
556 /**
557 * Built-in command: increment or decrement a property value.
558 *
559 * If the 'step' argument is present, it will be used; otherwise,
560 * the command uses 'offset' and 'factor', usually from the mouse.
561 *
562 * property: the name of the property to increment or decrement.
563 * step: the amount of the increment or decrement (default: 0).
564 * offset: offset from the current setting (used for the mouse; multiplied
565 * by factor)
566 * factor: scaling amount for the offset (defaults to 1).
567 * min: the minimum allowed value (default: no minimum).
568 * max: the maximum allowed value (default: no maximum).
569 * mask: 'integer' to apply only to the left of the decimal point,
570 * 'decimal' to apply only to the right of the decimal point,
571 * or 'all' to apply to the whole number (the default).
572 * wrap: true if the value should be wrapped when it passes min or max;
573 * both min and max must be present for this to work (default:
574 * false).
575 */
576 static bool
577 do_property_adjust (const SGPropertyNode * arg, SGPropertyNode * root)
578 {
579 SGPropertyNode * prop = get_prop(arg,root);
580
581 double amount = 0;
582 if (arg->hasValue("step"))
583 amount = arg->getDoubleValue("step");
584 else
585 amount = (arg->getDoubleValue("factor", 1.0)
586 * arg->getDoubleValue("offset"));
587
588 double unmodifiable, modifiable;
589 split_value(prop->getDoubleValue(), arg->getStringValue("mask", "all").c_str(),
590 &unmodifiable, &modifiable);
591 modifiable += amount;
592 modifiable = limit_value(modifiable, arg);
593
594 prop->setDoubleValue(unmodifiable + modifiable);
595
596 return true;
597 }
598
599
600 /**
601 * Built-in command: multiply a property value.
602 *
603 * property: the name of the property to multiply.
604 * factor: the amount by which to multiply.
605 * min: the minimum allowed value (default: no minimum).
606 * max: the maximum allowed value (default: no maximum).
607 * mask: 'integer' to apply only to the left of the decimal point,
608 * 'decimal' to apply only to the right of the decimal point,
609 * or 'all' to apply to the whole number (the default).
610 * wrap: true if the value should be wrapped when it passes min or max;
611 * both min and max must be present for this to work (default:
612 * false).
613 */
614 static bool
615 do_property_multiply (const SGPropertyNode * arg, SGPropertyNode * root)
616 {
617 SGPropertyNode * prop = get_prop(arg,root);
618 auto factorValue = getValueIndirect<double>(arg, "factor");
619 if (!factorValue) {
620 SG_LOG(SG_GENERAL, SG_DEV_WARN, "property-multiply: missing factor/factor-prop argument");
621 return false;
622 }
623
624 double unmodifiable, modifiable;
625 split_value(prop->getDoubleValue(), arg->getStringValue("mask", "all").c_str(),
626 &unmodifiable, &modifiable);
627 modifiable *= factorValue.value();
628 modifiable = limit_value(modifiable, arg);
629
630 prop->setDoubleValue(unmodifiable + modifiable);
631
632 return true;
633 }
634
635
636 /**
637 * Built-in command: swap two property values.
638 *
639 * property[0]: the name of the first property.
640 * property[1]: the name of the second property.
641 */
642 static bool
643 do_property_swap (const SGPropertyNode * arg, SGPropertyNode * root)
644 {
645 SGPropertyNode * prop1 = get_prop(arg,root);
646 SGPropertyNode * prop2 = get_prop2(arg,root);
647
648 // FIXME: inefficient
649 const string & tmp = prop1->getStringValue();
650 return (prop1->setUnspecifiedValue(prop2->getStringValue()) &&
651 prop2->setUnspecifiedValue(tmp.c_str()));
652 }
653
654
655 /**
656 * Built-in command: Set a property to an axis or other moving input.
657 *
658 * property: the name of the property to set.
659 * setting: the current input setting, usually between -1.0 and 1.0.
660 * offset: the offset to shift by, before applying the factor.
661 * factor: the factor to multiply by (use negative to reverse).
662 */
663 static bool
664 do_property_scale (const SGPropertyNode * arg, SGPropertyNode * root)
665 {
666 SGPropertyNode * prop = get_prop(arg,root);
667 double setting = arg->getDoubleValue("setting");
668 double offset = arg->getDoubleValue("offset", 0.0);
669 double factor = arg->getDoubleValue("factor", 1.0);
670 bool squared = arg->getBoolValue("squared", false);
671 int power = arg->getIntValue("power", (squared ? 2 : 1));
672
673 int sign = (setting < 0 ? -1 : 1);
674
675 switch (power) {
676 case 1:
677 break;
678 case 2:
679 setting = setting * setting * sign;
680 break;
681 case 3:
682 setting = setting * setting * setting;
683 break;
684 case 4:
685 setting = setting * setting * setting * setting * sign;
686 break;
687 default:
688 setting = pow(setting, power);
689 if ((power % 2) == 0)
690 setting *= sign;
691 break;
692 }
693
694 return prop->setDoubleValue((setting + offset) * factor);
695 }
696
697
698 /**
699 * Built-in command: cycle a property through a set of values.
700 *
701 * If the current value isn't in the list, the cycle will
702 * (re)start from the beginning.
703 *
704 * property: the name of the property to cycle.
705 * value[*]: the list of values to cycle through.
706 */
707 static bool
708 do_property_cycle (const SGPropertyNode * arg, SGPropertyNode * root)
709 {
710 SGPropertyNode * prop = get_prop(arg,root);
711 std::vector<SGPropertyNode_ptr> values = arg->getChildren("value");
712
713 bool wrap = arg->getBoolValue("wrap", true);
714 // compatible with knob/pick animations
715 int offset = arg->getIntValue("offset", 1);
716
717 int selection = -1;
718 int nSelections = values.size();
719
720 if (nSelections < 1) {
721 SG_LOG(SG_GENERAL, SG_ALERT, "No values for property-cycle");
722 return false;
723 }
724
725 // Try to find the current selection
726 for (int i = 0; i < nSelections; i++) {
727 if (compare_values(prop, values[i])) {
728 selection = i;
729 break;
730 }
731 }
732
733 if (selection < 0) { // default to first selection
734 selection = 0;
735 } else {
736 selection += offset;
737 if (wrap) {
738 selection = (selection + nSelections) % nSelections;
739 } else {
740 SG_CLAMP_RANGE(selection, 0, nSelections - 1);
741 }
742 }
743
744 prop->setUnspecifiedValue(values[selection]->getStringValue());
745 return true;
746 }
747
748
749 /**
750 * Built-in command: randomize a numeric property value.
751 *
752 * property: the name of the property value to randomize.
753 * min: the minimum allowed value.
754 * max: the maximum allowed value.
755 */
756 static bool
757 do_property_randomize (const SGPropertyNode * arg, SGPropertyNode * root)
758 {
759 SGPropertyNode * prop = get_prop(arg,root);
760 double min = arg->getDoubleValue("min", DBL_MIN);
761 double max = arg->getDoubleValue("max", DBL_MAX);
762 prop->setDoubleValue(sg_random() * (max - min) + min);
763 return true;
764 }
765
766 /**
767 * Built-in command: interpolate a property value over time
768 *
769 * property: the name of the property value to interpolate.
770 * type: the interpolation type ("numeric", "color", etc.)
771 * easing: name of easing function (see http://easings.net/)
772 * value[0..n] any number of constant values to interpolate
773 * time/rate[0..n] time between each value, number of time elements must
774 * match those of value elements. Instead of time also rate can
775 * be used which automatically calculates the time to change
776 * the property value at the given speed.
777 * -or-
778 * property[1..n+1] any number of target values taken from named properties
779 * time/rate[0..n] time between each value, number of time elements must
780 * match those of value elements. Instead of time also rate can
781 * be used which automatically calculates the time to change
782 * the property value at the given speed.
783 */
784 static bool
785 do_property_interpolate (const SGPropertyNode * arg, SGPropertyNode * root)
786 {
787 SGPropertyNode * prop = get_prop(arg,root);
788 if( !prop )
789 return false;
790
791 simgear::PropertyList time_nodes = arg->getChildren("time");
792 simgear::PropertyList rate_nodes = arg->getChildren("rate");
793
794 if( !time_nodes.empty() && !rate_nodes.empty() )
795 // mustn't specify time and rate
796 return false;
797
798 simgear::PropertyList::size_type num_times = time_nodes.empty()
799 ? rate_nodes.size()
800 : time_nodes.size();
801
802 simgear::PropertyList value_nodes = arg->getChildren("value");
803 if( value_nodes.empty() )
804 {
805 simgear::PropertyList prop_nodes = arg->getChildren("property");
806
807 // must have one more property node
808 if( prop_nodes.size() != num_times + 1 )
809 return false;
810
811 value_nodes.reserve(num_times);
812 for( size_t i = 1; i < prop_nodes.size(); ++i )
813 value_nodes.push_back( fgGetNode(prop_nodes[i]->getStringValue()) );
814 }
815
816 // must match
817 if( value_nodes.size() != num_times )
818 return false;
819
820 double_list deltas;
821 deltas.reserve(num_times);
822
823 if( !time_nodes.empty() )
824 {
825 for( size_t i = 0; i < num_times; ++i )
826 deltas.push_back( time_nodes[i]->getDoubleValue() );
827 }
828 else
829 {
830 for( size_t i = 0; i < num_times; ++i )
831 {
832 // TODO calculate delta based on property type
833 double delta = value_nodes[i]->getDoubleValue()
834 - ( i > 0
835 ? value_nodes[i - 1]->getDoubleValue()
836 : prop->getDoubleValue()
837 );
838 deltas.push_back( fabs(delta / rate_nodes[i]->getDoubleValue()) );
839 }
840 }
841
842 return prop->interpolate
843 (
844 arg->getStringValue("type", "numeric"),
845 value_nodes,
846 deltas,
847 arg->getStringValue("easing", "linear")
848 );
849 }
850
851 /**
852 * Built-in command: reinit the data logging system based on the
853 * current contents of the /logger tree.
854 */
855 static bool
856 do_data_logging_commit (const SGPropertyNode * arg, SGPropertyNode * root)
857 {
858 auto log = globals->get_subsystem<FGLogger>();
859 log->reinit();
860 return true;
861 }
862
863 /**
864 * Built-in command: set log level (0 ... 7)
865 */
866 static bool
867 do_log_level (const SGPropertyNode * arg, SGPropertyNode * root)
868 {
869 sglog().setLogLevels( SG_ALL, (sgDebugPriority)arg->getIntValue() );
870
871 return true;
872 }
873
874 /**
875 * An fgcommand to allow loading of xml files via nasal,
876 * the xml file's structure will be made available within
877 * a property tree node defined under argument "targetnode",
878 * or in the given argument tree under "data" otherwise.
879 *
880 * @param filename a string to hold the complete path & filename of an XML file
881 * @param targetnode a string pointing to a location within the property tree
882 * where to store the parsed XML file. If <targetnode> is undefined, then the
883 * file contents are stored under a node <data> in the argument tree.
884 */
885
886 static bool
887 do_load_xml_to_proptree(const SGPropertyNode * arg, SGPropertyNode * root)
888 {
889 SGPath file(arg->getStringValue("filename"));
890 if (file.isNull())
891 return false;
892
893 if (file.extension() != "xml")
894 file.concat(".xml");
895
896 // some Nasal uses loadxml to also speculatively probe for existence of
897 // files. This flag allows us not to be noisy in the logs, in that case.
898 const bool quiet = arg->getBoolValue("quiet", false);
899
900 std::string icao = arg->getStringValue("icao");
901 if (icao.empty()) {
902 if (file.isRelative()) {
903 SGPath absPath = globals->resolve_maybe_aircraft_path(file.utf8Str());
904 if (!absPath.isNull())
905 file = absPath;
906 else
907 {
908 if (!quiet) {
909 SG_LOG(SG_IO, SG_ALERT, "loadxml: Cannot find XML property file '" << file << "'.");
910 simgear::reportFailure(simgear::LoadFailure::NotFound, simgear::ErrorCode::XMLLoadCommand,
911 "loadxml: no such file:" + file.utf8Str(), file);
912 }
913 return false;
914 }
915 }
916 } else {
917 if (!XMLLoader::findAirportData(icao, file.utf8Str(), file)) {
918 if (!quiet) {
919 SG_LOG(SG_IO, SG_INFO, "loadxml: failed to find airport data for " << file << " at ICAO:" << icao);
920 simgear::reportFailure(simgear::LoadFailure::NotFound, simgear::ErrorCode::XMLLoadCommand,
921 "loadxml: no airport data file for:" + icao, file);
922 }
923 return false;
924 }
925 }
926
927 if (!file.exists()) {
928 if (!quiet) {
929 SG_LOG(SG_IO, SG_WARN, "loadxml: no such file:" << file);
930 }
931 return false;
932 }
933
934 const SGPath validated_path = SGPath(file).validate(false);
935 if (validated_path.isNull()) {
936 SG_LOG(SG_IO, quiet ? SG_DEV_WARN : SG_ALERT, "loadxml: reading '" << file << "' denied "
937 "(unauthorized directory - authorization no longer follows symlinks; to authorize reading additional directories, pass them to --allow-nasal-read)");
938 return false;
939 }
940
941 SGPropertyNode *targetnode;
942 if (arg->hasValue("targetnode"))
943 targetnode = fgGetNode(arg->getStringValue("targetnode"), true);
944 else
945 targetnode = const_cast<SGPropertyNode *>(arg)->getNode("data", true);
946
947 try {
948 readProperties(validated_path, targetnode, true);
949 } catch (const sg_exception &e) {
950 if (!quiet) {
951 simgear::reportFailure(simgear::LoadFailure::BadData, simgear::ErrorCode::XMLLoadCommand,
952 "loadxml exception:" + e.getFormattedMessage(), e.getLocation());
953 }
954 SG_LOG(SG_IO, quiet ? SG_DEV_WARN : SG_WARN, "loadxml exception: " << e.getFormattedMessage());
955 return false;
956 }
957
958 return true;
959 }
960
961 static bool
962 do_load_xml_from_url(const SGPropertyNode * arg, SGPropertyNode * root)
963 {
964 auto http = globals->get_subsystem<FGHTTPClient>();
965 if (!http) {
966 SG_LOG(SG_IO, SG_ALERT, "xmlhttprequest: HTTP client not running");
967 return false;
968 }
969
970 std::string url(arg->getStringValue("url"));
971 if (url.empty())
972 return false;
973
974 SGPropertyNode *targetnode;
975 if (arg->hasValue("targetnode"))
976 targetnode = fgGetNode(arg->getStringValue("targetnode"), true);
977 else
978 targetnode = const_cast<SGPropertyNode *>(arg)->getNode("data", true);
979
980 RemoteXMLRequest* req = new RemoteXMLRequest(url, targetnode);
981
982 if (arg->hasChild("body"))
983 req->setBodyData(arg->getChild("body"));
984
985 // connect up optional reporting properties
986 if (arg->hasValue("complete"))
987 req->setCompletionProp(fgGetNode(arg->getStringValue("complete"), true));
988 if (arg->hasValue("failure"))
989 req->setFailedProp(fgGetNode(arg->getStringValue("failure"), true));
990 if (arg->hasValue("status"))
991 req->setStatusProp(fgGetNode(arg->getStringValue("status"), true));
992
993 http->makeRequest(req);
994 return true;
995 }
996
997
998 /**
999 * An fgcommand to allow saving of xml files via nasal,
1000 * the file's structure will be determined based on what's
1001 * encountered in the passed (source) property tree node
1002 *
1003 * @param filename a string to hold the complete path & filename of the (new)
1004 * XML file
1005 * @param sourcenode a string pointing to a location within the property tree
1006 * where to find the nodes that should be written recursively into an XML file
1007 * @param data if no sourcenode is given, then the file contents are taken from
1008 * the argument tree's "data" node.
1009 */
1010
1011 static bool
1012 do_save_xml_from_proptree(const SGPropertyNode * arg, SGPropertyNode * root)
1013 {
1014 SGPath file(arg->getStringValue("filename"));
1015 if (file.isNull())
1016 return false;
1017
1018 if (file.extension() != "xml")
1019 file.concat(".xml");
1020
1021 const SGPath validated_path = SGPath(file).validate(true);
1022 if (validated_path.isNull()) {
1023 SG_LOG(SG_IO, SG_ALERT, "savexml: writing to '" << file << "' denied "
1024 "(unauthorized directory - authorization no longer follows symlinks)");
1025 return false;
1026 }
1027
1028 SGPropertyNode *sourcenode;
1029 if (arg->hasValue("sourcenode"))
1030 sourcenode = fgGetNode(arg->getStringValue("sourcenode"), true);
1031 else if (arg->getNode("data", false))
1032 sourcenode = const_cast<SGPropertyNode *>(arg)->getNode("data");
1033 else
1034 return false;
1035
1036 try {
1037 writeProperties (validated_path, sourcenode, true);
1038 } catch (const sg_exception &e) {
1039 SG_LOG(SG_IO, SG_WARN, "savexml: " << e.getFormattedMessage());
1040 return false;
1041 }
1042
1043 return true;
1044 }
1045
1046 // Optional profiling commands using gperftools:
1047 // http://code.google.com/p/gperftools/
1048
1049 #if !FG_HAVE_GPERFTOOLS
1050 static void
1051 no_profiling_support()
1052 {
1053 SG_LOG
1054 (
1055 SG_GENERAL,
1056 SG_ALERT,
1057 "No profiling support! Install gperftools and reconfigure/rebuild fgfs."
1058 );
1059 }
1060 #endif
1061
1062 static bool
1063 do_profiler_start(const SGPropertyNode *arg, SGPropertyNode *root)
1064 {
1065 #if FG_HAVE_GPERFTOOLS
1066 const char *filename = arg->getStringValue("filename", "fgfs.profile");
1067 ProfilerStart(filename);
1068 return true;
1069 #else
1070 no_profiling_support();
1071 return false;
1072 #endif
1073 }
1074
1075 static bool
1076 do_profiler_stop(const SGPropertyNode *arg, SGPropertyNode *root)
1077 {
1078 #if FG_HAVE_GPERFTOOLS
1079 ProfilerStop();
1080 return true;
1081 #else
1082 no_profiling_support();
1083 return false;
1084 #endif
1085 }
1086
1087 static bool do_reload_nasal_module(const SGPropertyNode* arg, SGPropertyNode*)
1088 {
1089 auto nasalSys = globals->get_subsystem<FGNasalSys>();
1090 if (!nasalSys) {
1091 SG_LOG(SG_GUI, SG_ALERT, "reloadModuleFromFile command: Nasal subsystem not found");
1092 return false;
1093 }
1094
1095 return nasalSys->reloadModuleFromFile(arg->getStringValue("module"));
1096 }
1097
1098
1099 ////////////////////////////////////////////////////////////////////////
1100 // Command setup.
1101 ////////////////////////////////////////////////////////////////////////
1102
1103
1104 /**
1105 * Table of built-in commands.
1106 *
1107 * New commands do not have to be added here; any module in the application
1108 * can add a new command using globals->get_commands()->addCommand(...).
1109 */
1110 static struct {
1111 const char * name;
1112 SGCommandMgr::command_t command;
1113 } built_ins[] = {
1114 {"null", do_null},
1115 {"nasal", do_nasal},
1116 {"nasal-reload", do_reload_nasal_module}, // avoid conflict with modules.nas which defines 'nasal-module-reload'
1117 {"pause", do_pause},
1118 {"load", do_load},
1119 {"save", do_save},
1120 {"save-tape", do_save_tape},
1121 {"load-tape", do_load_tape},
1122 {"view-cycle", do_view_cycle},
1123 {"view-push", do_view_push},
1124 {"view-clone", do_view_clone},
1125 {"view-last-pair", do_view_last_pair},
1126 {"view-last-pair-double", do_view_last_pair_double},
1127 {"view-new", do_view_new},
1128 /*
1129 { "set-sea-level-air-temp-degc", do_set_sea_level_degc },
1130 { "set-outside-air-temp-degc", do_set_oat_degc },
1131 { "set-dewpoint-sea-level-air-temp-degc", do_set_dewpoint_sea_level_degc },
1132 { "set-dewpoint-temp-degc", do_set_dewpoint_degc },
1133 */
1134 {"property-toggle", do_property_toggle},
1135 {"property-assign", do_property_assign},
1136 {"property-adjust", do_property_adjust},
1137 {"property-multiply", do_property_multiply},
1138 {"property-swap", do_property_swap},
1139 {"property-scale", do_property_scale},
1140 {"property-cycle", do_property_cycle},
1141 {"property-randomize", do_property_randomize},
1142 {"property-interpolate", do_property_interpolate},
1143 {"data-logging-commit", do_data_logging_commit},
1144 {"log-level", do_log_level},
1145 {"replay", do_replay},
1146 /*
1147 { "decrease-visibility", do_decrease_visibility },
1148 { "increase-visibility", do_increase_visibility },
1149 */
1150 {"loadxml", do_load_xml_to_proptree},
1151 {"savexml", do_save_xml_from_proptree},
1152 {"xmlhttprequest", do_load_xml_from_url},
1153
1154 {"profiler-start", do_profiler_start},
1155 {"profiler-stop", do_profiler_stop},
1156
1157 {"video-start", do_video_start},
1158 {"video-stop", do_video_stop},
1159
1160 {0, 0} // zero-terminated
1161 };
1162
1163
1164 /**
1165 * Initialize the default built-in commands.
1166 *
1167 * Other commands may be added by other parts of the application.
1168 */
1169 void
1170 fgInitCommands ()
1171 {
1172 // set our property root as the implicit default root for the
1173 // command managr
1174 SGCommandMgr::instance()->setImplicitRoot(globals->get_props());
1175
1176 SG_LOG(SG_GENERAL, SG_BULK, "Initializing basic built-in commands:");
1177 for (int i = 0; built_ins[i].name != 0; i++) {
1178 SG_LOG(SG_GENERAL, SG_BULK, " " << built_ins[i].name);
1179 globals->get_commands()->addCommand(built_ins[i].name,
1180 built_ins[i].command);
1181 }
1182
1183 typedef bool (*dummy)();
1184 fgTie( "/command/view/next", dummy(0), do_view_next );
1185 fgTie( "/command/view/prev", dummy(0), do_view_prev );
1186
1187 globals->get_props()->setValueReadOnly( "/sim/debug/profiler-available",
1188 bool(FG_HAVE_GPERFTOOLS) );
1189 }
1190
1191 // end of fg_commands.cxx