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