]> git.mxchange.org Git - flightgear.git/blob - src/Main/fg_props.cxx
46acff3e580dc4850a274eacf16e8c3bc704a933
[flightgear.git] / src / Main / fg_props.cxx
1 // fg_props.cxx -- support for FlightGear properties.
2 //
3 // Written by David Megginson, started 2000.
4 //
5 // Copyright (C) 2000, 2001 David Megginson - david@megginson.com
6 //
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License as
9 // published by the Free Software Foundation; either version 2 of the
10 // License, or (at your option) any later version.
11 //
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 // General Public License for more details.
16 //
17 // You should have received a copy of the GNU General Public License
18 // along with this program; if not, write to the Free Software
19 // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20 //
21 // $Id$
22
23 #ifdef HAVE_CONFIG_H
24 #  include <simgear/compiler.h>
25 #endif
26
27 #include <simgear/structure/exception.hxx>
28 #include <simgear/magvar/magvar.hxx>
29 #include <simgear/timing/sg_time.hxx>
30 #include <simgear/misc/sg_path.hxx>
31 #include <simgear/scene/material/matlib.hxx>
32 #include <simgear/sound/soundmgr.hxx>
33
34 #include STL_IOSTREAM
35
36 #include <ATC/ATCdisplay.hxx>
37 #include <Aircraft/aircraft.hxx>
38 #include <Time/tmp.hxx>
39 #include <FDM/UIUCModel/uiuc_aircraftdir.h>
40 #ifdef FG_WEATHERCM
41 #  include <WeatherCM/FGLocalWeatherDatabase.h>
42 #else
43 #  include <Environment/environment.hxx>
44 #endif // FG_WEATHERCM
45
46 #include <GUI/gui.h>
47
48 #include "globals.hxx"
49 #include "fg_props.hxx"
50
51 SG_USING_STD(istream);
52 SG_USING_STD(ostream);
53
54 #ifdef FG_WEATHERCM
55 static double getWindNorth ();
56 static double getWindEast ();
57 static double getWindDown ();
58 #endif // FG_WEATHERCM
59
60 static bool winding_ccw = true; // FIXME: temporary
61
62 static bool fdm_data_logging = false; // FIXME: temporary
63
64 static bool frozen = false;     // FIXME: temporary
65
66
67 \f
68 ////////////////////////////////////////////////////////////////////////
69 // Default property bindings (not yet handled by any module).
70 ////////////////////////////////////////////////////////////////////////
71
72 struct LogClassMapping {
73   sgDebugClass c;
74   string name;
75   LogClassMapping(sgDebugClass cc, string nname) { c = cc; name = nname; }
76 };
77
78 LogClassMapping log_class_mappings [] = {
79   LogClassMapping(SG_NONE, "none"),
80   LogClassMapping(SG_TERRAIN, "terrain"),
81   LogClassMapping(SG_ASTRO, "astro"),
82   LogClassMapping(SG_FLIGHT, "flight"),
83   LogClassMapping(SG_INPUT, "input"),
84   LogClassMapping(SG_GL, "gl"),
85   LogClassMapping(SG_VIEW, "view"),
86   LogClassMapping(SG_COCKPIT, "cockpit"),
87   LogClassMapping(SG_GENERAL, "general"),
88   LogClassMapping(SG_MATH, "math"),
89   LogClassMapping(SG_EVENT, "event"),
90   LogClassMapping(SG_AIRCRAFT, "aircraft"),
91   LogClassMapping(SG_AUTOPILOT, "autopilot"),
92   LogClassMapping(SG_IO, "io"),
93   LogClassMapping(SG_CLIPPER, "clipper"),
94   LogClassMapping(SG_NETWORK, "network"),
95   LogClassMapping(SG_UNDEFD, "")
96 };
97
98
99 /**
100  * Get the logging classes.
101  */
102 static const char *
103 getLoggingClasses ()
104 {
105   sgDebugClass classes = logbuf::get_log_classes();
106   static string result = "";    // FIXME
107   for (int i = 0; log_class_mappings[i].c != SG_UNDEFD; i++) {
108     if ((classes&log_class_mappings[i].c) > 0) {
109       if (!result.empty())
110         result += '|';
111       result += log_class_mappings[i].name;
112     }
113   }
114   return result.c_str();
115 }
116
117
118 static void
119 addLoggingClass (const string &name)
120 {
121   sgDebugClass classes = logbuf::get_log_classes();
122   for (int i = 0; log_class_mappings[i].c != SG_UNDEFD; i++) {
123     if (name == log_class_mappings[i].name) {
124       logbuf::set_log_classes(sgDebugClass(classes|log_class_mappings[i].c));
125       return;
126     }
127   }
128   SG_LOG(SG_GENERAL, SG_WARN, "Unknown logging class: " << name);
129 }
130
131
132 /**
133  * Set the logging classes.
134  */
135 static void
136 setLoggingClasses (const char * c)
137 {
138   string classes = c;
139   logbuf::set_log_classes(SG_NONE);
140
141   if (classes == "none") {
142     SG_LOG(SG_GENERAL, SG_INFO, "Disabled all logging classes");
143     return;
144   }
145
146   if (classes.empty() || classes == "all") { // default
147     logbuf::set_log_classes(SG_ALL);
148     SG_LOG(SG_GENERAL, SG_INFO, "Enabled all logging classes: "
149            << getLoggingClasses());
150     return;
151   }
152
153   string rest = classes;
154   string name = "";
155   int sep = rest.find('|');
156   while (sep > 0) {
157     name = rest.substr(0, sep);
158     rest = rest.substr(sep+1);
159     addLoggingClass(name);
160     sep = rest.find('|');
161   }
162   addLoggingClass(rest);
163   SG_LOG(SG_GENERAL, SG_INFO, "Set logging classes to "
164          << getLoggingClasses());
165 }
166
167
168 /**
169  * Get the logging priority.
170  */
171 static const char *
172 getLoggingPriority ()
173 {
174   switch (logbuf::get_log_priority()) {
175   case SG_BULK:
176     return "bulk";
177   case SG_DEBUG:
178     return "debug";
179   case SG_INFO:
180     return "info";
181   case SG_WARN:
182     return "warn";
183   case SG_ALERT:
184     return "alert";
185   default:
186     SG_LOG(SG_GENERAL, SG_WARN, "Internal: Unknown logging priority number: "
187            << logbuf::get_log_priority());
188     return "unknown";
189   }
190 }
191
192
193 /**
194  * Set the logging priority.
195  */
196 static void
197 setLoggingPriority (const char * p)
198 {
199   if (p == 0)
200       return;
201   string priority = p;
202   if (priority == "bulk") {
203     logbuf::set_log_priority(SG_BULK);
204   } else if (priority == "debug") {
205     logbuf::set_log_priority(SG_DEBUG);
206   } else if (priority.empty() || priority == "info") { // default
207     logbuf::set_log_priority(SG_INFO);
208   } else if (priority == "warn") {
209     logbuf::set_log_priority(SG_WARN);
210   } else if (priority == "alert") {
211     logbuf::set_log_priority(SG_ALERT);
212   } else {
213     SG_LOG(SG_GENERAL, SG_WARN, "Unknown logging priority " << priority);
214   }
215   SG_LOG(SG_GENERAL, SG_DEBUG, "Logging priority is " << getLoggingPriority());
216 }
217
218
219 /**
220  * Return the current frozen state.
221  */
222 static bool
223 getFreeze ()
224 {
225   return frozen;
226 }
227
228
229 /**
230  * Set the current frozen state.
231  */
232 static void
233 setFreeze (bool f)
234 {
235     frozen = f;
236
237     // Stop sound on a pause
238     SGSoundMgr *s = globals->get_soundmgr();
239     if ( s != NULL ) {
240         if ( f ) {
241             s->pause();
242         } else {
243             s->resume();
244         }
245     }
246 }
247
248
249 /**
250  * Return the current aircraft directory (UIUC) as a string.
251  */
252 static const char *
253 getAircraftDir ()
254 {
255   return aircraft_dir.c_str();
256 }
257
258
259 /**
260  * Set the current aircraft directory (UIUC).
261  */
262 static void
263 setAircraftDir (const char * dir)
264 {
265   aircraft_dir = dir;
266 }
267
268
269 /**
270  * Return the number of milliseconds elapsed since simulation started.
271  */
272 static double
273 getElapsedTime_sec ()
274 {
275   return globals->get_sim_time_sec();
276 }
277
278
279 /**
280  * Return the current Zulu time.
281  */
282 static const char *
283 getDateString ()
284 {
285   static char buf[64];          // FIXME
286   struct tm * t = globals->get_time_params()->getGmt();
287   sprintf(buf, "%.4d-%.2d-%.2dT%.2d:%.2d:%.2d",
288           t->tm_year + 1900, t->tm_mon + 1, t->tm_mday,
289           t->tm_hour, t->tm_min, t->tm_sec);
290   return buf;
291 }
292
293
294 /**
295  * Set the current Zulu time.
296  */
297 static void
298 setDateString (const char * date_string)
299 {
300   static const SGPropertyNode *cur_time_override
301         = fgGetNode("/sim/time/cur-time-override", true);
302
303   SGTime * st = globals->get_time_params();
304   struct tm * current_time = st->getGmt();
305   struct tm new_time;
306
307                                 // Scan for basic ISO format
308                                 // YYYY-MM-DDTHH:MM:SS
309   int ret = sscanf(date_string, "%d-%d-%dT%d:%d:%d",
310                    &(new_time.tm_year), &(new_time.tm_mon),
311                    &(new_time.tm_mday), &(new_time.tm_hour),
312                    &(new_time.tm_min), &(new_time.tm_sec));
313
314                                 // Be pretty picky about this, so
315                                 // that strange things don't happen
316                                 // if the save file has been edited
317                                 // by hand.
318   if (ret != 6) {
319     SG_LOG(SG_INPUT, SG_WARN, "Date/time string " << date_string
320            << " not in YYYY-MM-DDTHH:MM:SS format; skipped");
321     return;
322   }
323
324                                 // OK, it looks like we got six
325                                 // values, one way or another.
326   new_time.tm_year -= 1900;
327   new_time.tm_mon -= 1;
328
329                                 // Now, tell flight gear to use
330                                 // the new time.  This was far
331                                 // too difficult, by the way.
332   long int warp =
333     mktime(&new_time) - mktime(current_time) + globals->get_warp();
334   double lon = current_aircraft.fdm_state->get_Longitude();
335   double lat = current_aircraft.fdm_state->get_Latitude();
336   globals->set_warp(warp);
337   st->update(lon, lat, cur_time_override->getLongValue(), warp);
338 }
339
340 /**
341  * Return the GMT as a string.
342  */
343 static const char *
344 getGMTString ()
345 {
346   static char buf[16];          // FIXME
347   struct tm *t = globals->get_time_params()->getGmt();
348   sprintf(buf, " %.2d:%.2d:%.2d",
349           t->tm_hour, t->tm_min, t->tm_sec);
350   // cout << t << " " << buf << endl;
351   return buf;
352 }
353
354
355 /**
356  * Return the magnetic variation
357  */
358 static double
359 getMagVar ()
360 {
361   return globals->get_mag()->get_magvar() * SGD_RADIANS_TO_DEGREES;
362 }
363
364
365 /**
366  * Return the magnetic dip
367  */
368 static double
369 getMagDip ()
370 {
371   return globals->get_mag()->get_magdip() * SGD_RADIANS_TO_DEGREES;
372 }
373
374
375 /**
376  * Return the current heading in degrees.
377  */
378 static double
379 getHeadingMag ()
380 {
381   double magheading;
382   magheading = current_aircraft.fdm_state->get_Psi() * SGD_RADIANS_TO_DEGREES - getMagVar();
383   if (magheading < 0) magheading += 360;
384   return magheading;
385 }
386
387
388 #ifdef FG_WEATHERCM
389
390 /**
391  * Get the current visibility (meters).
392  */
393 static double
394 getVisibility ()
395 {
396   return WeatherDatabase->getWeatherVisibility();
397 }
398
399
400 /**
401  * Set the current visibility (meters).
402  */
403 static void
404 setVisibility (double visibility)
405 {
406   WeatherDatabase->setWeatherVisibility(visibility);
407 }
408
409 /**
410  * Get the current wind north velocity (feet/second).
411  */
412 static double
413 getWindNorth ()
414 {
415   return current_aircraft.fdm_state->get_V_north_airmass();
416 }
417
418
419 /**
420  * Set the current wind north velocity (feet/second).
421  */
422 static void
423 setWindNorth (double speed)
424 {
425   current_aircraft.fdm_state
426     ->set_Velocities_Local_Airmass(speed, getWindEast(), getWindDown());
427 }
428
429
430 /**
431  * Get the current wind east velocity (feet/second).
432  */
433 static double
434 getWindEast ()
435 {
436   return current_aircraft.fdm_state->get_V_east_airmass();
437 }
438
439
440 /**
441  * Set the current wind east velocity (feet/second).
442  */
443 static void
444 setWindEast (double speed)
445 {
446   SG_LOG(SG_GENERAL, SG_INFO,, "Set wind-east to " << speed );
447   current_aircraft.fdm_state->set_Velocities_Local_Airmass(getWindNorth(),
448                                                            speed,
449                                                            getWindDown());
450 }
451
452
453 /**
454  * Get the current wind down velocity (feet/second).
455  */
456 static double
457 getWindDown ()
458 {
459   return current_aircraft.fdm_state->get_V_down_airmass();
460 }
461
462
463 /**
464  * Set the current wind down velocity (feet/second).
465  */
466 static void
467 setWindDown (double speed)
468 {
469   current_aircraft.fdm_state->set_Velocities_Local_Airmass(getWindNorth(),
470                                                            getWindEast(),
471                                                            speed);
472 }
473
474 #endif // FG_WEATHERCM
475
476 static long
477 getWarp ()
478 {
479   return globals->get_warp();
480 }
481
482 static void
483 setWarp (long warp)
484 {
485   globals->set_warp(warp);
486 }
487
488 static long
489 getWarpDelta ()
490 {
491   return globals->get_warp_delta();
492 }
493
494 static void
495 setWarpDelta (long delta)
496 {
497   globals->set_warp_delta(delta);
498 }
499
500 static bool
501 getWindingCCW ()
502 {
503   return winding_ccw;
504 }
505
506 static void
507 setWindingCCW (bool state)
508 {
509   winding_ccw = state;
510   if ( winding_ccw )
511     glFrontFace ( GL_CCW );
512   else
513     glFrontFace ( GL_CW );
514 }
515
516 static bool
517 getFullScreen ()
518 {
519 #if defined(FX) && !defined(WIN32)
520   return globals->get_fullscreen();
521 #else
522   return false;
523 #endif
524 }
525
526 static void
527 setFullScreen (bool state)
528 {
529 #if defined(FX) && !defined(WIN32)
530   globals->set_fullscreen(state);
531 #  if defined(XMESA_FX_FULLSCREEN) && defined(XMESA_FX_WINDOW)
532   XMesaSetFXmode( state ? XMESA_FX_FULLSCREEN : XMESA_FX_WINDOW );
533 #  endif
534 #endif
535 }
536
537 static bool
538 getFDMDataLogging ()
539 {
540   return fdm_data_logging;
541 }
542
543 static void
544 setFDMDataLogging (bool state)
545 {
546                                 // kludge; no getter or setter available
547   if (state != fdm_data_logging) {
548     fgToggleFDMdataLogging();
549     fdm_data_logging = state;
550   }
551 }
552
553 \f
554 ////////////////////////////////////////////////////////////////////////
555 // Tie the properties.
556 ////////////////////////////////////////////////////////////////////////
557
558 void
559 fgInitProps ()
560 {
561   SG_LOG(SG_GENERAL, SG_DEBUG, "start of fgInitProps()" );
562                                 // Simulation
563   fgTie("/sim/logging/priority", getLoggingPriority, setLoggingPriority);
564   fgTie("/sim/logging/classes", getLoggingClasses, setLoggingClasses);
565   fgTie("/sim/freeze/master", getFreeze, setFreeze);
566   fgTie("/sim/aircraft-dir", getAircraftDir, setAircraftDir);
567
568   fgTie("/sim/time/elapsed-sec", getElapsedTime_sec);
569   fgTie("/sim/time/gmt", getDateString, setDateString);
570   fgSetArchivable("/sim/time/gmt");
571   fgTie("/sim/time/gmt-string", getGMTString);
572
573                                 // Orientation
574   fgTie("/orientation/heading-magnetic-deg", getHeadingMag);
575
576                                 // Environment
577 #ifdef FG_WEATHERCM
578   fgTie("/environment/visibility-m", getVisibility, setVisibility);
579   fgSetArchivable("/environment/visibility-m");
580   fgTie("/environment/wind-from-north-fps", getWindNorth, setWindNorth);
581   fgSetArchivable("/environment/wind-from-north-fps");
582   fgTie("/environment/wind-from-east-fps", getWindEast, setWindEast);
583   fgSetArchivable("/environment/wind-from-east-fps");
584   fgTie("/environment/wind-from-down-fps", getWindDown, setWindDown);
585   fgSetArchivable("/environment/wind-from-down-fps");
586 #endif
587
588   fgTie("/environment/magnetic-variation-deg", getMagVar);
589   fgTie("/environment/magnetic-dip-deg", getMagDip);
590
591   fgTie("/sim/time/warp", getWarp, setWarp, false);
592   fgTie("/sim/time/warp-delta", getWarpDelta, setWarpDelta);
593
594                                 // Misc. Temporary junk.
595   fgTie("/sim/temp/winding-ccw", getWindingCCW, setWindingCCW, false);
596   fgTie("/sim/temp/full-screen", getFullScreen, setFullScreen);
597   fgTie("/sim/temp/fdm-data-logging", getFDMDataLogging, setFDMDataLogging);
598
599   SG_LOG(SG_GENERAL, SG_DEBUG, "end of fgInitProps()" );
600 }
601
602
603 void
604 fgUpdateProps ()
605 {
606 }
607
608
609 \f
610 ////////////////////////////////////////////////////////////////////////
611 // Save and restore.
612 ////////////////////////////////////////////////////////////////////////
613
614
615 /**
616  * Save the current state of the simulator to a stream.
617  */
618 bool
619 fgSaveFlight (ostream &output, bool write_all)
620 {
621
622   fgSetBool("/sim/presets/onground", false);
623   fgSetArchivable("/sim/presets/onground");
624   fgSetBool("/sim/presets/trim", false);
625   fgSetArchivable("/sim/presets/trim");
626   fgSetString("/sim/presets/speed-set", "UVW");
627   fgSetArchivable("/sim/presets/speed-set");
628
629   try {
630     writeProperties(output, globals->get_props(), write_all);
631   } catch (const sg_exception &e) {
632     guiErrorMessage("Error saving flight: ", e);
633     return false;
634   }
635   return true;
636 }
637
638
639 /**
640  * Restore the current state of the simulator from a stream.
641  */
642 bool
643 fgLoadFlight (istream &input)
644 {
645   SGPropertyNode props;
646   try {
647     readProperties(input, &props);
648   } catch (const sg_exception &e) {
649     guiErrorMessage("Error reading saved flight: ", e);
650     return false;
651   }
652
653   fgSetBool("/sim/presets/onground", false);
654   fgSetBool("/sim/presets/trim", false);
655   fgSetString("/sim/presets/speed-set", "UVW");
656
657   copyProperties(&props, globals->get_props());
658   // When loading a flight, make it the
659   // new initial state.
660   globals->saveInitialState();
661   return true;
662 }
663
664
665 bool
666 fgLoadProps (const char * path, SGPropertyNode * props, bool in_fg_root)
667 {
668     string fullpath;
669     if (in_fg_root) {
670         SGPath loadpath(globals->get_fg_root());
671         loadpath.append(path);
672         fullpath = loadpath.str();
673     } else {
674         fullpath = path;
675     }
676
677     try {
678         readProperties(fullpath, props);
679     } catch (const sg_exception &e) {
680         guiErrorMessage("Error reading properties: ", e);
681         return false;
682     }
683     return true;
684 }
685
686
687 \f
688 ////////////////////////////////////////////////////////////////////////
689 // Property convenience functions.
690 ////////////////////////////////////////////////////////////////////////
691
692 SGPropertyNode *
693 fgGetNode (const char * path, bool create)
694 {
695   return globals->get_props()->getNode(path, create);
696 }
697
698 SGPropertyNode * 
699 fgGetNode (const char * path, int index, bool create)
700 {
701   return globals->get_props()->getNode(path, index, create);
702 }
703
704 bool
705 fgHasNode (const char * path)
706 {
707   return (fgGetNode(path, false) != 0);
708 }
709
710 void
711 fgAddChangeListener (SGPropertyChangeListener * listener, const char * path)
712 {
713   fgGetNode(path, true)->addChangeListener(listener);
714 }
715
716 void
717 fgAddChangeListener (SGPropertyChangeListener * listener,
718                      const char * path, int index)
719 {
720   fgGetNode(path, index, true)->addChangeListener(listener);
721 }
722
723 bool
724 fgGetBool (const char * name, bool defaultValue)
725 {
726   return globals->get_props()->getBoolValue(name, defaultValue);
727 }
728
729 int
730 fgGetInt (const char * name, int defaultValue)
731 {
732   return globals->get_props()->getIntValue(name, defaultValue);
733 }
734
735 int
736 fgGetLong (const char * name, long defaultValue)
737 {
738   return globals->get_props()->getLongValue(name, defaultValue);
739 }
740
741 float
742 fgGetFloat (const char * name, float defaultValue)
743 {
744   return globals->get_props()->getFloatValue(name, defaultValue);
745 }
746
747 double
748 fgGetDouble (const char * name, double defaultValue)
749 {
750   return globals->get_props()->getDoubleValue(name, defaultValue);
751 }
752
753 const char *
754 fgGetString (const char * name, const char * defaultValue)
755 {
756   return globals->get_props()->getStringValue(name, defaultValue);
757 }
758
759 bool
760 fgSetBool (const char * name, bool val)
761 {
762   return globals->get_props()->setBoolValue(name, val);
763 }
764
765 bool
766 fgSetInt (const char * name, int val)
767 {
768   return globals->get_props()->setIntValue(name, val);
769 }
770
771 bool
772 fgSetLong (const char * name, long val)
773 {
774   return globals->get_props()->setLongValue(name, val);
775 }
776
777 bool
778 fgSetFloat (const char * name, float val)
779 {
780   return globals->get_props()->setFloatValue(name, val);
781 }
782
783 bool
784 fgSetDouble (const char * name, double val)
785 {
786   return globals->get_props()->setDoubleValue(name, val);
787 }
788
789 bool
790 fgSetString (const char * name, const char * val)
791 {
792   return globals->get_props()->setStringValue(name, val);
793 }
794
795 void
796 fgSetArchivable (const char * name, bool state)
797 {
798   SGPropertyNode * node = globals->get_props()->getNode(name);
799   if (node == 0)
800     SG_LOG(SG_GENERAL, SG_DEBUG,
801            "Attempt to set archive flag for non-existant property "
802            << name);
803   else
804     node->setAttribute(SGPropertyNode::ARCHIVE, state);
805 }
806
807 void
808 fgSetReadable (const char * name, bool state)
809 {
810   SGPropertyNode * node = globals->get_props()->getNode(name);
811   if (node == 0)
812     SG_LOG(SG_GENERAL, SG_DEBUG,
813            "Attempt to set read flag for non-existant property "
814            << name);
815   else
816     node->setAttribute(SGPropertyNode::READ, state);
817 }
818
819 void
820 fgSetWritable (const char * name, bool state)
821 {
822   SGPropertyNode * node = globals->get_props()->getNode(name);
823   if (node == 0)
824     SG_LOG(SG_GENERAL, SG_DEBUG,
825            "Attempt to set write flag for non-existant property "
826            << name);
827   else
828     node->setAttribute(SGPropertyNode::WRITE, state);
829 }
830
831 void
832 fgUntie (const char * name)
833 {
834   if (!globals->get_props()->untie(name))
835     SG_LOG(SG_GENERAL, SG_WARN, "Failed to untie property " << name);
836 }
837
838
839 // end of fg_props.cxx