]> git.mxchange.org Git - flightgear.git/blob - src/Environment/fgclouds.cxx
Stuart BUCHANAN:
[flightgear.git] / src / Environment / fgclouds.cxx
1 // Build a cloud layer based on metar
2 //
3 // Written by Harald JOHNSEN, started April 2005.
4 //
5 // Copyright (C) 2005  Harald JOHNSEN - hjohnsen@evc.net
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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
20 //
21 //
22
23 #ifdef HAVE_CONFIG_H
24 #  include "config.h"
25 #endif
26
27 #include <Main/fg_props.hxx>
28
29 #include <simgear/constants.h>
30 #include <simgear/sound/soundmgr_openal.hxx>
31 #include <simgear/scene/sky/sky.hxx>
32 #include <simgear/environment/visual_enviro.hxx>
33 #include <simgear/scene/sky/cloudfield.hxx>
34 #include <simgear/scene/sky/newcloud.hxx>
35 #include <simgear/math/sg_random.h>
36 #include <simgear/props/props_io.hxx>
37
38 #include <Main/globals.hxx>
39 #include <Airports/simple.hxx>
40 #include <Main/util.hxx>
41
42 #include "environment_ctrl.hxx"
43 #include "environment_mgr.hxx"
44 #include "fgmetar.hxx"
45 #include "fgclouds.hxx"
46
47 extern SGSky *thesky;
48
49
50 FGClouds::FGClouds(FGEnvironmentCtrl * controller) :
51         station_elevation_ft(0.0),
52         _controller( controller ),
53         snd_lightning(NULL),
54         rebuild_required(true),
55     last_scenario( "unset" ),
56     last_env_config( new SGPropertyNode() ),
57     last_env_clouds( new SGPropertyNode() )
58 {
59         update_event = 0;
60 }
61 FGClouds::~FGClouds() {
62 }
63
64 int FGClouds::get_update_event(void) const {
65         return update_event;
66 }
67 void FGClouds::set_update_event(int count) {
68         update_event = count;
69         build();
70 }
71
72 void FGClouds::init(void) {
73         if( snd_lightning == NULL ) {
74                 snd_lightning = new SGSoundSample(globals->get_fg_root().c_str(), "Sounds/thunder.wav");
75                 snd_lightning->set_max_dist(7000.0f);
76                 snd_lightning->set_reference_dist(3000.0f);
77                 SGSoundMgr *soundMgr = globals->get_soundmgr();
78                 soundMgr->add( snd_lightning, "thunder" );
79                 sgEnviro.set_soundMgr( soundMgr );
80         }
81         
82         rebuild_required = true;
83 }
84
85 void FGClouds::buildCloud(SGPropertyNode *cloud_def_root, SGPropertyNode  *box_def_root, const string& name, sgVec3 pos, SGCloudField *layer) {
86         SGPropertyNode *box_def=NULL;
87         SGPropertyNode *cld_def=NULL;
88         
89         SGPath texture_root = globals->get_fg_root();
90         texture_root.append("Textures");
91         texture_root.append("Sky");
92
93         box_def = box_def_root->getChild(name.c_str());
94   
95         string base_name = name.substr(0,2);
96         if( !box_def ) {
97                 if( name[2] == '-' ) {
98                         box_def = box_def_root->getChild(base_name.c_str());
99                 }
100                 if( !box_def )
101                         return;
102         }
103         
104         for(int i = 0; i < box_def->nChildren() ; i++) {
105                 SGPropertyNode *abox = box_def->getChild(i);
106                 if( strcmp(abox->getName(), "box") == 0) {
107                         double x = abox->getDoubleValue("x") + pos[0];
108                         double y = abox->getDoubleValue("y") + pos[1];
109                         double z = abox->getDoubleValue("z") + pos[2];
110                         SGVec3f newpos = SGVec3f(x, z, y);
111                         
112                         string type = abox->getStringValue("type", "cu-small");
113                                
114                         cld_def = cloud_def_root->getChild(type.c_str());
115                         if ( !cld_def ) return;
116                         
117                         double min_width = cld_def->getDoubleValue("min-cloud-width-m", 500.0);
118                         double max_width = cld_def->getDoubleValue("max-cloud-width-m", 1000.0);
119                         double min_height = cld_def->getDoubleValue("min-cloud-height-m", min_width);
120                         double max_height = cld_def->getDoubleValue("max-cloud-height-m", max_width);
121                         double min_sprite_width = cld_def->getDoubleValue("min-sprite-width-m", 200.0);
122                         double max_sprite_width = cld_def->getDoubleValue("max-sprite-width-m", min_sprite_width);
123                         double min_sprite_height = cld_def->getDoubleValue("min-sprite-height-m", min_sprite_width);
124                         double max_sprite_height = cld_def->getDoubleValue("max-sprite-height-m", max_sprite_width);
125                         int num_sprites = cld_def->getIntValue("num-sprites", 20);
126                         int num_textures_x = cld_def->getIntValue("num-textures-x", 1);
127                         int num_textures_y = cld_def->getIntValue("num-textures-y", 1);
128                         double bottom_shade = cld_def->getDoubleValue("bottom-shade", 1.0);
129                         string texture = cld_def->getStringValue("texture", "cl_cumulus.rgb");
130           
131                         SGNewCloud *cld = 
132                                 new SGNewCloud(type,
133                                                texture_root, 
134                                                texture, 
135                                                min_width, 
136                                                max_width, 
137                                                min_height,
138                                                max_height,
139                                                min_sprite_width,
140                                                max_sprite_width,
141                                                min_sprite_height,
142                                                max_sprite_height,
143                                                bottom_shade,
144                                                num_sprites,
145                                                num_textures_x,
146                                                num_textures_y);
147                         layer->addCloud(newpos, cld);
148                 }
149         }
150 }
151
152 void FGClouds::buildLayer(int iLayer, const string& name, double alt, double coverage) {
153         struct {
154                 string name;
155                 double count;
156         } tCloudVariety[20];
157         int CloudVarietyCount = 0;
158         double totalCount = 0.0;
159         
160         if (! clouds_3d_enabled) return;
161         
162         SGPropertyNode *cloud_def_root = fgGetNode("/environment/cloudlayers/clouds", false);
163         SGPropertyNode *box_def_root   = fgGetNode("/environment/cloudlayers/boxes", false);
164         SGPropertyNode *layer_def_root = fgGetNode("/environment/cloudlayers/layers", false);
165         SGCloudField *layer = thesky->get_cloud_layer(iLayer)->get_layer3D();
166
167         layer->clear();
168         
169         // when we don't generate clouds the layer is rendered in 2D
170         if( coverage == 0.0 )
171                 return;
172         if( layer_def_root == NULL || cloud_def_root == NULL || box_def_root == NULL)
173                 return;
174         
175         SGPropertyNode *layer_def=NULL;
176
177         layer_def = layer_def_root->getChild(name.c_str());
178         if( !layer_def ) {
179                 if( name[2] == '-' ) {
180                         string base_name = name.substr(0,2);
181                         layer_def = layer_def_root->getChild(base_name.c_str());
182                 }
183                 if( !layer_def )
184                         return;
185         }
186         
187         double grid_x_size = layer_def->getDoubleValue("grid-x-size", 1000.0);
188         double grid_y_size = layer_def->getDoubleValue("grid-y-size", 1000.0);
189         double grid_x_rand = layer_def->getDoubleValue("grid-x-rand", grid_x_size);
190         double grid_y_rand = layer_def->getDoubleValue("grid-y-rand", grid_y_size);
191         double grid_z_rand = layer_def->getDoubleValue("grid-z-rand");
192
193         for(int i = 0; i < layer_def->nChildren() ; i++) {
194                 SGPropertyNode *acloud = layer_def->getChild(i);
195                 if( strcmp(acloud->getName(), "cloud") == 0) {
196                         string cloud_name = acloud->getStringValue("name");
197                         tCloudVariety[CloudVarietyCount].name = cloud_name;
198                         double count = acloud->getDoubleValue("count", 1.0);
199                         tCloudVariety[CloudVarietyCount].count = count;
200                         int variety = 0;
201                         cloud_name = cloud_name + "-%d";
202                         char variety_name[50];
203                         do {
204                                 variety++;
205                                 snprintf(variety_name, sizeof(variety_name), cloud_name.c_str(), variety);
206                         } while( box_def_root->getChild(variety_name, 0, false) );
207
208                         totalCount += count;
209                         if( CloudVarietyCount < 20 )
210                                 CloudVarietyCount++;
211                 }
212         }
213         totalCount = 1.0 / totalCount;
214         
215         for(double px = 0.0; px < SGCloudField::fieldSize; px += grid_x_size) {
216                 for(double py = 0.0; py < SGCloudField::fieldSize; py += grid_y_size) {
217                         double x = px + grid_x_rand * (sg_random() - 0.5) - (SGCloudField::fieldSize / 2.0);
218                         double y = py + grid_y_rand * (sg_random() - 0.5) - (SGCloudField::fieldSize / 2.0);
219                         double z = grid_z_rand * (sg_random() - 0.5);
220                         double choice = sg_random();
221
222                         for(int i = 0; i < CloudVarietyCount ; i ++) {
223                                 choice -= tCloudVariety[i].count * totalCount;
224                                 if( choice <= 0.0 ) {
225                                         sgVec3 pos={x,z,y};
226                                         buildCloud(cloud_def_root, box_def_root, tCloudVariety[i].name, pos, layer);
227                                         break;
228                                 }
229                         }
230                 }
231         }
232
233         // Now we've built any clouds, enable them and set the density (coverage)
234         layer->setCoverage(coverage);
235         layer->applyCoverage();
236         thesky->get_cloud_layer(iLayer)->set_enable3dClouds(clouds_3d_enabled);
237 }
238
239 // TODO:call this after real metar updates
240 void FGClouds::buildCloudLayers(void) {
241         SGPropertyNode *metar_root = fgGetNode("/environment", true);
242         
243         double wind_speed_kt     = metar_root->getDoubleValue("wind-speed-kt");
244         double temperature_degc  = metar_root->getDoubleValue("temperature-sea-level-degc");
245         double dewpoint_degc     = metar_root->getDoubleValue("dewpoint-sea-level-degc");
246         double pressure_mb              = metar_root->getDoubleValue("pressure-sea-level-inhg") * SG_INHG_TO_PA / 100.0;
247
248         double dewp = pow(10.0, 7.5 * dewpoint_degc / (237.7 + dewpoint_degc));
249         double temp = pow(10.0, 7.5 * temperature_degc / (237.7 + temperature_degc));
250         double rel_humidity = dewp * 100 / temp;
251
252         // formule d'Epsy, base d'un cumulus
253         double cumulus_base = 122.0 * (temperature_degc - dewpoint_degc);
254         double stratus_base = 100.0 * (100.0 - rel_humidity) * SG_FEET_TO_METER;
255
256         bool cu_seen = false;
257
258         for(int iLayer = 0 ; iLayer < thesky->get_cloud_layer_count(); iLayer++) {
259                 SGPropertyNode *cloud_root = fgGetNode("/environment/clouds/layer", iLayer, true);
260
261                 double alt_ft = cloud_root->getDoubleValue("elevation-ft");
262                 double alt_m = alt_ft * SG_FEET_TO_METER;
263                 string coverage = cloud_root->getStringValue("coverage");
264                 
265                 
266                 double coverage_norm = 0.0;
267                 if( coverage == "few" )
268                         coverage_norm = 2.0/8.0;        // <1-2
269                 else if( coverage == "scattered" )
270                         coverage_norm = 4.0/8.0;        // 3-4
271                 else if( coverage == "broken" )
272                         coverage_norm = 6.0/8.0;        // 5-7
273                 else if( coverage == "overcast" )
274                         coverage_norm = 8.0/8.0;        // 8
275
276                 string layer_type = "nn";
277                 if( coverage == "cirrus" ) {
278                         layer_type = "ci";
279                 } else if( alt_ft > 16500 ) {
280 //                      layer_type = "ci|cs|cc";
281                         layer_type = "ci";
282                 } else if( alt_ft > 6500 ) {
283 //                      layer_type = "as|ac|ns";
284                         layer_type = "ac";
285                         if( pressure_mb < 1005.0 && coverage_norm >= 5.5 )
286                                 layer_type = "ns";
287                 } else {
288 //                      layer_type = "st|cu|cb|sc";
289                         if( cumulus_base * 0.80 < alt_m && cumulus_base * 1.20 > alt_m ) {
290                                 // +/- 20% from cumulus probable base
291                                 layer_type = "cu";
292                         } else if( stratus_base * 0.80 < alt_m && stratus_base * 1.40 > alt_m ) {
293                                 // +/- 20% from stratus probable base
294                                 layer_type = "st";
295                         } else {
296                                 // above formulae is far from perfect
297                                 if ( alt_ft < 2000 )
298                                         layer_type = "st";
299                                 else if( alt_ft < 4500 )
300                                         layer_type = "cu";
301                                 else
302                                         layer_type = "sc";
303                         }
304                 }
305
306                 buildLayer(iLayer, layer_type, alt_m, coverage_norm);
307         }
308 }
309
310 // copy from FGMetarEnvironmentCtrl until better
311 void
312 FGClouds::update_metar_properties( const FGMetar *m )
313 {
314     int i;
315     int j;
316     double d;
317     char s[128];
318
319     fgSetString("/environment/metar/station-id", m->getId());
320     fgSetDouble("/environment/metar/min-visibility-m",
321                 m->getMinVisibility().getVisibility_m() );
322     fgSetDouble("/environment/metar/max-visibility-m",
323                 m->getMaxVisibility().getVisibility_m() );
324
325     const SGMetarVisibility *dirvis = m->getDirVisibility();
326     for (i = 0; i < 8; i++, dirvis++) {
327         const char *min = "/environment/metar/visibility[%d]/min-m";
328         const char *max = "/environment/metar/visibility[%d]/max-m";
329
330         d = dirvis->getVisibility_m();
331
332         snprintf(s, 128, min, i);
333         fgSetDouble(s, d);
334         snprintf(s, 128, max, i);
335         fgSetDouble(s, d);
336     }
337
338     fgSetInt("/environment/metar/base-wind-range-from",
339              m->getWindRangeFrom() );
340     fgSetInt("/environment/metar/base-wind-range-to",
341              m->getWindRangeTo() );
342     fgSetDouble("/environment/metar/base-wind-speed-kt",
343                 m->getWindSpeed_kt() );
344     fgSetDouble("/environment/metar/gust-wind-speed-kt",
345                 m->getGustSpeed_kt() );
346     fgSetDouble("/environment/metar/temperature-degc",
347                 m->getTemperature_C() );
348     fgSetDouble("/environment/metar/dewpoint-degc",
349                 m->getDewpoint_C() );
350     fgSetDouble("/environment/metar/rel-humidity-norm",
351                 m->getRelHumidity() );
352     fgSetDouble("/environment/metar/pressure-inhg",
353                 m->getPressure_inHg() );
354
355     vector<SGMetarCloud> cv = m->getClouds();
356     vector<SGMetarCloud>::const_iterator cloud;
357
358     // Load into both the METAR and environment properties to stop interpolation
359     const char *cl[] = {"/environment/metar/clouds/layer[%i]",
360                         "/environment/clouds/layer[%i]"};
361
362     for (j = 0; j < 2; j++)
363     {
364         for (i = 0, cloud = cv.begin(); cloud != cv.end(); cloud++, i++) {
365             const char *coverage_string[5] = 
366                 { "clear", "few", "scattered", "broken", "overcast" };
367             const double thickness[5] = { 0, 65, 600,750, 1000};
368             int q;
369     
370             snprintf(s, 128, cl[j], i);
371             strncat(s, "/coverage", 128);
372             q = cloud->getCoverage();
373             fgSetString(s, coverage_string[q] );
374             
375             snprintf(s, 128, cl[j], i);
376             strncat(s, "/elevation-ft", 128);
377             fgSetDouble(s, cloud->getAltitude_ft() + station_elevation_ft);
378             
379             snprintf(s, 128, cl[j], i);
380             strncat(s, "/thickness-ft", 128);
381             fgSetDouble(s, thickness[q]);
382             
383             snprintf(s, 128, cl[j], i);
384             strncat(s, "/span-m", 128);
385             fgSetDouble(s, 40000.0);
386         }
387     
388         for (; i < FGEnvironmentMgr::MAX_CLOUD_LAYERS; i++) {
389             
390             
391             snprintf(s, 128, cl[j], i);
392             strncat(s, "/coverage", 128);
393             fgSetString(s, "clear");
394     
395             snprintf(s, 128, cl[j], i);
396             strncat(s, "/elevation-ft", 128);
397             fgSetDouble(s, -9999);
398     
399             snprintf(s, 128, cl[j], i);
400             strncat(s, "/thickness-ft", 128);
401             fgSetDouble(s, 0);
402     
403             snprintf(s, 128, cl[j], i);
404             strncat(s, "/span-m", 128);
405             fgSetDouble(s, 40000.0);
406         }
407     }
408
409     fgSetDouble("/environment/metar/rain-norm", m->getRain());
410     fgSetDouble("/environment/metar/hail-norm", m->getHail());
411     fgSetDouble("/environment/metar/snow-norm", m->getSnow());
412     fgSetBool("/environment/metar/snow-cover", m->getSnowCover());
413 }
414
415 void
416 FGClouds::update_env_config ()
417 {
418     fgSetupWind( fgGetDouble("/environment/metar/base-wind-range-from"),
419                  fgGetDouble("/environment/metar/base-wind-range-to"),
420                  fgGetDouble("/environment/metar/base-wind-speed-kt"),
421                  fgGetDouble("/environment/metar/gust-wind-speed-kt") );
422
423     fgDefaultWeatherValue( "visibility-m",
424                            fgGetDouble("/environment/metar/min-visibility-m") );
425 #if 0
426     set_temp_at_altitude( fgGetDouble("/environment/metar/temperature-degc"),
427                           station_elevation_ft );
428     set_dewpoint_at_altitude( fgGetDouble("/environment/metar/dewpoint-degc"),
429                               station_elevation_ft );
430 #endif
431     fgDefaultWeatherValue( "pressure-sea-level-inhg",
432                            fgGetDouble("/environment/metar/pressure-inhg") );
433 }
434
435
436 void FGClouds::setLayer( int iLayer, float alt_ft, const string& coverage, const string& layer_type ) {
437         double coverage_norm = 0.0;
438         if( coverage == "few" )
439                 coverage_norm = 2.0/8.0;        // <1-2
440         else if( coverage == "scattered" )
441                 coverage_norm = 4.0/8.0;        // 3-4
442         else if( coverage == "broken" )
443                 coverage_norm = 6.0/8.0;        // 5-7
444         else if( coverage == "overcast" )
445                 coverage_norm = 8.0/8.0;        // 8
446
447         buildLayer(iLayer, layer_type, station_elevation_ft + alt_ft * SG_FEET_TO_METER, coverage_norm);
448 }
449
450 void FGClouds::buildScenario( const string& scenario ) {
451         string fakeMetar="";
452         string station = fgGetString("/environment/metar/station-id", "XXXX");
453         
454         // fetch station elevation if exists
455         if( station == "XXXX" )
456             station_elevation_ft = fgGetDouble("/position/ground-elev-m", 0.0);
457         else {
458             const FGAirport* a = globals->get_airports()->search( station );
459             station_elevation_ft = (a ? a->getElevation() : 0.0);
460         }
461
462         for(int iLayer = 0 ; iLayer < thesky->get_cloud_layer_count(); iLayer++) {
463             thesky->get_cloud_layer(iLayer)
464                 ->setCoverage(SGCloudLayer::SG_CLOUD_CLEAR);
465             thesky->get_cloud_layer(iLayer)->get_layer3D()->clear();
466         }
467
468         station += " 011000Z ";
469         if( scenario == "Fair weather" ) {
470                 fakeMetar = "15003KT 12SM SCT033 FEW200 20/08 Q1015 NOSIG";
471                 //setLayer(0, 3300.0, "scattered", "cu");
472         } else if( scenario == "Thunderstorm" ) {
473                 fakeMetar = "15012KT 08SM TSRA SCT040 BKN070 20/12 Q0995";
474                 setLayer(0, 4000.0, "scattered", "cb");
475                 setLayer(1, 7000.0, "scattered", "ns");
476         } else 
477                 return;
478         FGMetar *m = new FGMetar( station + fakeMetar );
479         update_metar_properties( m );
480         update_env_config();
481         // propagate aloft tables
482         //_controller->reinit();
483
484         fgSetString("/environment/metar/last-metar", m->getData());
485         // TODO:de-activate real metar updates
486         if( scenario == "Fair weather" ) {
487                 fgSetString("/environment/clouds/layer[1]/coverage", "cirrus");
488         }
489 }
490
491
492 void FGClouds::build() {
493         string scenario = fgGetString("/environment/weather-scenario", "METAR");
494
495         if(!rebuild_required && (scenario == last_scenario))
496             return;
497         
498         if( last_scenario == "none" ) {
499         // save clouds and weather conditions
500             SGPropertyNode *param = fgGetNode("/environment/config", true);
501             copyProperties( param, last_env_config );
502             param = fgGetNode("/environment/clouds", true);
503             copyProperties( param, last_env_clouds );
504         }
505                 
506         if( scenario == "METAR" ) {
507             string realMetar = fgGetString("/environment/metar/real-metar", "");
508
509             if( realMetar != "" ) {
510                 fgSetString("/environment/metar/last-metar", realMetar.c_str());
511                 FGMetar *m = new FGMetar( realMetar );
512                 update_metar_properties( m );
513                 update_env_config();
514                         // propagate aloft tables
515                 _controller->reinit();
516                 buildCloudLayers();
517             }
518         }
519         else if( scenario == "none" ) {
520         // restore clouds and weather conditions
521             SGPropertyNode *param = fgGetNode("/environment/config", true);
522             copyProperties( last_env_config, param );
523             param = fgGetNode("/environment/clouds", true);
524             copyProperties( last_env_clouds, param );
525             fgSetDouble("/environment/metar/rain-norm", 0.0);
526             fgSetDouble("/environment/metar/snow-norm", 0.0);
527 //          update_env_config();
528             // propagate aloft tables
529             _controller->reinit();
530             buildCloudLayers();
531         }
532         else {
533             buildScenario( scenario );
534             _controller->reinit();
535             buildCloudLayers();
536         }
537         
538         last_scenario = scenario;
539         rebuild_required = false;
540
541         if( snd_lightning == NULL )
542             init();
543 }
544
545 void FGClouds::set_3dClouds(bool enable)
546 {
547     if (enable != clouds_3d_enabled) {
548         clouds_3d_enabled = enable;
549
550         for(int iLayer = 0 ; iLayer < thesky->get_cloud_layer_count(); iLayer++) {
551             thesky->get_cloud_layer(iLayer)->set_enable3dClouds(enable);
552
553             if (!enable) {
554                 thesky->get_cloud_layer(iLayer)->get_layer3D()->clear();
555             }
556         }
557
558         if (enable) {
559             rebuild_required = true;
560             build();
561         }
562     }
563 }
564
565 bool FGClouds::get_3dClouds() const {
566     return clouds_3d_enabled;
567 }
568