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