]> git.mxchange.org Git - flightgear.git/blob - src/Environment/environment_ctrl.cxx
c03afd61c840a16241bdce6f9d144129df9a505f
[flightgear.git] / src / Environment / environment_ctrl.cxx
1 // environment_ctrl.cxx -- manager for natural environment information.
2 //
3 // Written by David Megginson, started February 2002.
4 //
5 // Copyright (C) 2002  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 #include <simgear/debug/logstream.hxx>
24
25 #include <stdlib.h>
26 #include <algorithm>
27
28 #include <simgear/structure/commands.hxx>
29 #include <simgear/structure/exception.hxx>
30
31 #include <Airports/simple.hxx>
32 #include <Main/fg_props.hxx>
33 #include <Main/util.hxx>
34
35 #include "environment_mgr.hxx"
36 #include "environment_ctrl.hxx"
37
38 SG_USING_STD(sort);
39
40 // FIXME, from options.cxx
41 extern void fgSetupWind (double min_hdg, double max_hdg, double speed, double gust);
42
43
44 \f
45 ////////////////////////////////////////////////////////////////////////
46 // Implementation of FGEnvironmentCtrl abstract base class.
47 ////////////////////////////////////////////////////////////////////////
48
49 FGEnvironmentCtrl::FGEnvironmentCtrl ()
50   : _environment(0),
51     _lon_deg(0),
52     _lat_deg(0),
53     _elev_ft(0)
54 {
55 }
56
57 FGEnvironmentCtrl::~FGEnvironmentCtrl ()
58 {
59 }
60
61 void
62 FGEnvironmentCtrl::setEnvironment (FGEnvironment * environment)
63 {
64   _environment = environment;
65 }
66
67 void
68 FGEnvironmentCtrl::setLongitudeDeg (double lon_deg)
69 {
70   _lon_deg = lon_deg;
71 }
72
73 void
74 FGEnvironmentCtrl::setLatitudeDeg (double lat_deg)
75 {
76   _lat_deg = lat_deg;
77 }
78
79 void
80 FGEnvironmentCtrl::setElevationFt (double elev_ft)
81 {
82   _elev_ft = elev_ft;
83 }
84
85 void
86 FGEnvironmentCtrl::setPosition (double lon_deg, double lat_deg, double elev_ft)
87 {
88   _lon_deg = lon_deg;
89   _lat_deg = lat_deg;
90   _elev_ft = elev_ft;
91 }
92
93
94 \f
95 ////////////////////////////////////////////////////////////////////////
96 // Implementation of FGUserDefEnvironmentCtrl.
97 ////////////////////////////////////////////////////////////////////////
98
99 FGUserDefEnvironmentCtrl::FGUserDefEnvironmentCtrl ()
100   : _base_wind_speed_node(0),
101     _gust_wind_speed_node(0),
102     _current_wind_speed_kt(0),
103     _delta_wind_speed_kt(0)
104 {
105 }
106
107 FGUserDefEnvironmentCtrl::~FGUserDefEnvironmentCtrl ()
108 {
109 }
110
111 void
112 FGUserDefEnvironmentCtrl::init ()
113 {
114                                 // Fill in some defaults.
115   if (!fgHasNode("/environment/params/base-wind-speed-kt"))
116     fgSetDouble("/environment/params/base-wind-speed-kt",
117                 fgGetDouble("/environment/wind-speed-kt"));
118   if (!fgHasNode("/environment/params/gust-wind-speed-kt"))
119     fgSetDouble("/environment/params/gust-wind-speed-kt",
120                 fgGetDouble("/environment/params/base-wind-speed-kt"));
121
122   _base_wind_speed_node =
123     fgGetNode("/environment/params/base-wind-speed-kt", true);
124   _gust_wind_speed_node =
125     fgGetNode("/environment/params/gust-wind-speed-kt", true);
126
127   _current_wind_speed_kt = _base_wind_speed_node->getDoubleValue();
128   _delta_wind_speed_kt = 0.1;
129 }
130
131 void
132 FGUserDefEnvironmentCtrl::update (double dt)
133 {
134   double base_wind_speed = _base_wind_speed_node->getDoubleValue();
135   double gust_wind_speed = _gust_wind_speed_node->getDoubleValue();
136
137   if (gust_wind_speed < base_wind_speed) {
138       gust_wind_speed = base_wind_speed;
139       _gust_wind_speed_node->setDoubleValue(gust_wind_speed);
140   }
141
142   if (base_wind_speed == gust_wind_speed) {
143     _current_wind_speed_kt = base_wind_speed;
144   } else {
145     int rn = rand() % 128;
146     int sign = (_delta_wind_speed_kt < 0 ? -1 : 1);
147     double gust = _current_wind_speed_kt - base_wind_speed;
148     double incr = gust / 50;
149
150     if (rn == 0)
151       _delta_wind_speed_kt = - _delta_wind_speed_kt;
152     else if (rn < 4)
153       _delta_wind_speed_kt -= incr * sign;
154     else if (rn < 16)
155       _delta_wind_speed_kt += incr * sign;
156
157     _current_wind_speed_kt += _delta_wind_speed_kt;
158
159     if (_current_wind_speed_kt < base_wind_speed) {
160       _current_wind_speed_kt = base_wind_speed;
161       _delta_wind_speed_kt = 0.01;
162     } else if (_current_wind_speed_kt > gust_wind_speed) {
163       _current_wind_speed_kt = gust_wind_speed;
164       _delta_wind_speed_kt = -0.01;
165     }
166   }
167   
168   if (_environment != 0)
169     _environment->set_wind_speed_kt(_current_wind_speed_kt);
170 }
171
172
173 \f
174 ////////////////////////////////////////////////////////////////////////
175 // Implementation of FGInterpolateEnvironmentCtrl.
176 ////////////////////////////////////////////////////////////////////////
177
178 FGInterpolateEnvironmentCtrl::FGInterpolateEnvironmentCtrl ()
179 {
180 }
181
182 FGInterpolateEnvironmentCtrl::~FGInterpolateEnvironmentCtrl ()
183 {
184     unsigned int i;
185     for (i = 0; i < _boundary_table.size(); i++)
186         delete _boundary_table[i];
187     for (i = 0; i < _aloft_table.size(); i++)
188         delete _aloft_table[i];
189 }
190
191
192
193 void
194 FGInterpolateEnvironmentCtrl::init ()
195 {
196     read_table(fgGetNode("/environment/config/boundary", true),
197                _boundary_table);
198     read_table(fgGetNode("/environment/config/aloft", true),
199                _aloft_table);
200 }
201
202 void
203 FGInterpolateEnvironmentCtrl::reinit ()
204 {
205     unsigned int i;
206     for (i = 0; i < _boundary_table.size(); i++)
207         delete _boundary_table[i];
208     for (i = 0; i < _aloft_table.size(); i++)
209         delete _aloft_table[i];
210     _boundary_table.clear();
211     _aloft_table.clear();
212     init();
213 }
214
215 void
216 FGInterpolateEnvironmentCtrl::read_table (const SGPropertyNode * node,
217                                           vector<bucket *> &table)
218 {
219     for (int i = 0; i < node->nChildren(); i++) {
220         const SGPropertyNode * child = node->getChild(i);
221         if ( strcmp(child->getName(), "entry") == 0
222              && child->getStringValue("elevation-ft", "")[0] != '\0'
223              && ( child->getDoubleValue("elevation-ft") > 0.1 || i == 0 ) )
224         {
225             bucket * b = new bucket;
226             if (i > 0)
227                 b->environment.copy(table[i-1]->environment);
228             b->environment.read(child);
229             b->altitude_ft = b->environment.get_elevation_ft();
230             table.push_back(b);
231         }
232     }
233     sort(table.begin(), table.end());
234 }
235
236 void
237 FGInterpolateEnvironmentCtrl::update (double delta_time_sec)
238 {
239                                 // FIXME
240     double altitude_ft = fgGetDouble("/position/altitude-ft");
241     double altitude_agl_ft = fgGetDouble("/position/altitude-agl-ft");
242     double boundary_transition =
243         fgGetDouble("/environment/config/boundary-transition-ft", 500);
244
245     // double ground_elevation_ft = altitude_ft - altitude_agl_ft;
246
247     int length = _boundary_table.size();
248
249     if (length > 0) {
250                                 // boundary table
251         double boundary_limit = _boundary_table[length-1]->altitude_ft;
252         if (boundary_limit >= altitude_agl_ft) {
253             do_interpolate(_boundary_table, altitude_agl_ft,
254                            _environment);
255             return;
256         } else if ((boundary_limit + boundary_transition) >= altitude_agl_ft) {
257                                 // both tables
258             do_interpolate(_boundary_table, altitude_agl_ft, &env1);
259             do_interpolate(_aloft_table, altitude_ft, &env2);
260             double fraction =
261                 (altitude_agl_ft - boundary_limit) / boundary_transition;
262             interpolate(&env1, &env2, fraction, _environment);
263             return;
264         }
265     }
266
267                                 // aloft table
268     do_interpolate(_aloft_table, altitude_ft, _environment);
269 }
270
271 void
272 FGInterpolateEnvironmentCtrl::do_interpolate (vector<bucket *> &table,
273                                               double altitude_ft,
274                                               FGEnvironment * environment)
275 {
276     int length = table.size();
277     if (length == 0)
278         return;
279
280                                 // Boundary conditions
281     if ((length == 1) || (table[0]->altitude_ft >= altitude_ft)) {
282         environment->copy(table[0]->environment);
283         return;
284     } else if (table[length-1]->altitude_ft <= altitude_ft) {
285         environment->copy(table[length-1]->environment);
286         return;
287     }
288         
289                                 // Search the interpolation table
290     for (int i = 0; i < length - 1; i++) {
291         if ((i == length - 1) || (table[i]->altitude_ft <= altitude_ft)) {
292                 FGEnvironment * env1 = &(table[i]->environment);
293                 FGEnvironment * env2 = &(table[i+1]->environment);
294                 double fraction;
295                 if (table[i]->altitude_ft == table[i+1]->altitude_ft)
296                     fraction = 1.0;
297                 else
298                     fraction =
299                         ((altitude_ft - table[i]->altitude_ft) /
300                          (table[i+1]->altitude_ft - table[i]->altitude_ft));
301                 interpolate(env1, env2, fraction, environment);
302
303                 return;
304         }
305     }
306 }
307
308 bool
309 FGInterpolateEnvironmentCtrl::bucket::operator< (const bucket &b) const
310 {
311     return (altitude_ft < b.altitude_ft);
312 }
313
314
315 \f
316 ////////////////////////////////////////////////////////////////////////
317 // Implementation of FGMetarEnvironmentCtrl.
318 ////////////////////////////////////////////////////////////////////////
319
320 FGMetarEnvironmentCtrl::FGMetarEnvironmentCtrl ()
321     : env( new FGInterpolateEnvironmentCtrl ),
322       _icao( fgGetString("/sim/presets/airport-id") ),
323       update_interval_sec( 60.0 ),
324       elapsed( 60.0 )
325 {
326 }
327
328 FGMetarEnvironmentCtrl::~FGMetarEnvironmentCtrl ()
329 {
330    delete env;
331    env = NULL;
332 }
333
334
335 // use a "command" to set station temp at station elevation
336 static void set_temp_at_altitude( float temp_degc, float altitude_ft ) {
337     SGPropertyNode args;
338     SGPropertyNode *node = args.getNode("temp-degc", 0, true);
339     node->setFloatValue( temp_degc );
340     node = args.getNode("altitude-ft", 0, true);
341     node->setFloatValue( altitude_ft );
342     globals->get_commands()->execute("set-outside-air-temp-degc", &args);
343 }
344
345
346 static void set_dewpoint_at_altitude( float dewpoint_degc, float altitude_ft ) {
347     SGPropertyNode args;
348     SGPropertyNode *node = args.getNode("dewpoint-degc", 0, true);
349     node->setFloatValue( dewpoint_degc );
350     node = args.getNode("altitude-ft", 0, true);
351     node->setFloatValue( altitude_ft );
352     globals->get_commands()->execute("set-dewpoint-temp-degc", &args);
353 }
354
355
356 void
357 FGMetarEnvironmentCtrl::update_env_config ()
358 {
359     fgSetupWind( fgGetDouble("/environment/metar/base-wind-range-from"),
360                  fgGetDouble("/environment/metar/base-wind-range-to"),
361                  fgGetDouble("/environment/metar/base-wind-speed-kt"),
362                  fgGetDouble("/environment/metar/gust-wind-speed-kt") );
363
364     fgDefaultWeatherValue( "visibility-m",
365                            fgGetDouble("/environment/metar/min-visibility-m") );
366     set_temp_at_altitude( fgGetDouble("/environment/metar/temperature-degc"),
367                           station_elevation_ft );
368     set_dewpoint_at_altitude( fgGetDouble("/environment/metar/dewpoint-degc"),
369                               station_elevation_ft );
370     fgDefaultWeatherValue( "pressure-sea-level-inhg",
371                            fgGetDouble("/environment/metar/pressure-inhg") );
372 }
373
374 void
375 FGMetarEnvironmentCtrl::init ()
376 {
377     const SGPropertyNode *longitude
378         = fgGetNode( "/position/longitude-deg", true );
379     const SGPropertyNode *latitude
380         = fgGetNode( "/position/latitude-deg", true );
381
382     bool found_metar = false;
383     while ( !found_metar ) {
384         FGAirport a = globals->get_airports()
385             ->search( longitude->getDoubleValue(),
386                       latitude->getDoubleValue(),
387                       true );
388         if ( fetch_data( a.id ) ) {
389             cout << "closest station w/ metar = " << a.id << endl;
390             _icao = a.id;
391             elapsed = 0.0;
392             update_env_config();
393             env->init();
394             found_metar = true;
395         } else {
396             // mark as no metar so it doesn't show up in subsequent
397             // searches.
398             cout << "no metar at metar = " << a.id << endl;
399             globals->get_airports()->no_metar( a.id );
400         }
401     }
402 }
403
404 void
405 FGMetarEnvironmentCtrl::reinit ()
406 {
407 #if 0
408     update_env_config();
409 #endif
410
411     env->reinit();
412 }
413
414 void
415 FGMetarEnvironmentCtrl::update(double delta_time_sec)
416 {
417     const SGPropertyNode *longitude
418         = fgGetNode( "/position/longitude-deg", true );
419     const SGPropertyNode *latitude
420         = fgGetNode( "/position/latitude-deg", true );
421     elapsed += delta_time_sec;
422     if ( elapsed > update_interval_sec ) {
423         FGAirport a = globals->get_airports()
424             ->search( longitude->getDoubleValue(),
425                       latitude->getDoubleValue(),
426                       true );
427         if ( fetch_data( a.id ) ) {
428             cout << "closest station w/ metar = " << a.id << endl;
429            _icao = a.id;
430             elapsed = 0.0;
431             update_env_config();
432             env->init();
433         } else {
434             // mark as no metar so it doesn't show up in subsequent
435             // searches.
436             cout << "no metar at metar = " << a.id << endl;
437             globals->get_airports()->no_metar( a.id );
438         }
439     }
440     env->update(delta_time_sec);
441 }
442
443 void
444 FGMetarEnvironmentCtrl::setEnvironment (FGEnvironment * environment)
445 {
446     env->setEnvironment(environment);
447 }
448
449 bool
450 FGMetarEnvironmentCtrl::fetch_data (const string &icao)
451 {
452     char s[128];
453     double d, dt;
454     int i;
455
456     if ((icao == "") && (_icao == "")) {
457         _icao = fgGetString("/sim/presets/airport-id");
458
459     } else if (icao != "") {
460         _icao = icao;
461     }
462
463     // fetch station elevation if exists
464     FGAirport a = globals->get_airports()->search( _icao );
465     station_elevation_ft = a.elevation;
466
467     // fetch current metar data
468     SGMetar *m;
469     try {
470         m = new SGMetar( _icao.c_str() );
471     } catch (const sg_io_exception& e) {
472         SG_LOG( SG_GENERAL, SG_WARN, "Error fetching live weather data: "
473                                       << e.getFormattedMessage().c_str() );
474         return false;
475     }
476
477     d = m->getMinVisibility().getVisibility_m();
478     d = (d != SGMetarNaN) ? d : 10000;
479     fgSetDouble("/environment/metar/min-visibility-m", d);
480
481     dt =  m->getMaxVisibility().getVisibility_m();
482     d = (dt != SGMetarNaN) ? dt : d;
483     fgSetDouble("/environment/metar/max-visibility-m", d);
484
485     SGMetarVisibility *dirvis = m->getDirVisibility();
486     for (i = 0; i < 8; i++, dirvis++) {
487         const char *min = "/environment/metar/visibility[%d]/min-m";
488         const char *max = "/environment/metar/visibility[%d]/max-m";
489         char s[128];
490
491         d = dirvis->getVisibility_m();
492         d = (d != SGMetarNaN) ? d : 10000;
493
494         snprintf(s, 128, min, i);
495         fgSetDouble(s, d);
496         snprintf(s, 128, max, i);
497         fgSetDouble(s, d);
498     }
499
500     i = m->getWindDir();
501     if ( i == -1 ) {
502         fgSetInt("/environment/metar/base-wind-range-from",
503                     m->getWindRangeFrom() );
504         fgSetInt("/environment/metar/base-wind-range-to",
505                     m->getWindRangeTo() );
506     } else {
507         fgSetInt("/environment/metar/base-wind-range-from", i);
508         fgSetInt("/environment/metar/base-wind-range-to", i);
509     }
510     fgSetDouble("/environment/metar/base-wind-speed-kt",
511                 m->getWindSpeed_kt() );
512
513     d = m->getGustSpeed_kt();
514     d = (d != SGMetarNaN) ? d : 0.0;
515     fgSetDouble("/environment/metar/gust-wind-speed-kt", d);
516
517     d = m->getTemperature_C();
518     if (d != SGMetarNaN) {
519         dt = m->getDewpoint_C();
520         dt = (dt != SGMetarNaN) ? dt : 0.0;
521         fgSetDouble("/environment/metar/dewpoint-degc", dt);
522         fgSetDouble("/environment/metar/rel-humidity-norm",
523                     m->getRelHumidity() );
524     }   
525     d = (d != SGMetarNaN) ? d : 15.0;
526     fgSetDouble("/environment/metar/temperature-degc", d);
527
528     d = m->getPressure_inHg();
529     d = (d != SGMetarNaN) ? d : 30.0;
530     fgSetDouble("/environment/metar/pressure-inhg", d);
531
532     vector<SGMetarCloud> cv = m->getClouds();
533     vector<SGMetarCloud>::iterator cloud;
534
535     const char *cl = "/environment/clouds/layer[%i]";
536     for (i = 0, cloud = cv.begin(); cloud != cv.end(); cloud++, i++) {
537         const char *coverage_string[5] = 
538             { "clear", "few", "scattered", "broken", "overcast" };
539         const double thickness[5] = { 0, 65, 600,750, 1000};
540         int q;
541
542         snprintf(s, 128, cl, i);
543         strncat(s, "/coverage", 128);
544         q = cloud->getCoverage();
545         q = (q != -1 ) ? q : 0;
546         fgSetString(s, coverage_string[q] );
547
548         snprintf(s, 128, cl, i);
549         strncat(s, "/elevation-ft", 128);
550         d = cloud->getAltitude_ft();
551         d = (d != SGMetarNaN) ? d : -9999;
552         fgSetDouble(s, d + station_elevation_ft);
553
554         snprintf(s, 128, cl, i);
555         strncat(s, "/thickness-ft", 128);
556         fgSetDouble(s, thickness[q]);
557
558         snprintf(s, 128, cl, i);
559         strncat(s, "/span-m", 128);
560         fgSetDouble(s, 40000.0);
561     }
562     for (; i < FGEnvironmentMgr::MAX_CLOUD_LAYERS; i++) {
563         snprintf(s, 128, cl, i);
564         strncat(s, "/coverage", 128);
565         fgSetString(s, "clear");
566
567         snprintf(s, 128, cl, i);
568         strncat(s, "/elevation-ft", 128);
569         fgSetDouble(s, -9999);
570
571         snprintf(s, 128, cl, i);
572         strncat(s, "/thickness-ft", 128);
573         fgSetDouble(s, 0);
574
575         snprintf(s, 128, cl, i);
576         strncat(s, "/span-m", 128);
577         fgSetDouble(s, 40000.0);
578     }
579
580     delete m;
581
582     return true;
583 }
584
585
586 // end of environment_ctrl.cxx