]> git.mxchange.org Git - simgear.git/blob - simgear/scene/sky/cloudfield.cxx
809efb520ed6d6849278ac52b5f25ee7119afd44
[simgear.git] / simgear / scene / sky / cloudfield.cxx
1 // a layer of 3d clouds
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 <simgear_config.h>
25 #endif
26
27 #include <simgear/compiler.h>
28
29 #include <plib/sg.h>
30 #include <plib/ssg.h>
31 #include <simgear/math/sg_random.h>
32 #include <simgear/math/sg_geodesy.hxx>
33 #include <simgear/math/polar3d.hxx>
34
35 #include STL_ALGORITHM
36 #include <vector>
37
38 SG_USING_STD(vector);
39
40 #include <simgear/environment/visual_enviro.hxx>
41 #include "sky.hxx"
42 #include "newcloud.hxx"
43 #include "cloudfield.hxx"
44
45 #if defined(__MINGW32__)
46 #define isnan(x) _isnan(x)
47 #endif
48
49 #if defined (__FreeBSD__)
50 #  if __FreeBSD_version < 500000
51      extern "C" {
52        inline int isnan(double r) { return !(r <= 0 || r >= 0); }
53      }
54 #  endif
55 #endif
56
57
58 #if defined (__CYGWIN__)
59 #include <ieeefp.h>
60 #endif
61
62 extern SGSky *thesky;
63
64 static list_of_culledCloud inViewClouds;
65
66 // visibility distance for clouds in meters
67 float SGCloudField::CloudVis = 25000.0f;
68 bool SGCloudField::enable3D = false;
69 // fieldSize must be > CloudVis or we can destroy the impostor cache
70 // a cloud must only be seen once or the impostor will be generated for each of his positions
71 double SGCloudField::fieldSize = 50000.0;
72 float SGCloudField::density = 100.0;
73 double SGCloudField::timer_dt = 0.0;
74 sgVec3 SGCloudField::view_vec, SGCloudField::view_X, SGCloudField::view_Y;
75
76 static int last_cache_size = 1*1024;
77 static int cacheResolution = 64;
78 static sgVec3 last_sunlight={0.0f, 0.0f, 0.0f};
79
80 int SGCloudField::get_CacheResolution(void) {
81         return cacheResolution;
82 }
83
84 void SGCloudField::set_CacheResolution(int resolutionPixels) {
85         if(cacheResolution == resolutionPixels)
86                 return;
87         cacheResolution = resolutionPixels;
88         if(enable3D) {
89                 int count = last_cache_size * 1024 / (cacheResolution * cacheResolution * 4);
90                 if(count == 0)
91                         count = 1;
92                 SGNewCloud::cldCache->setCacheSize(count, cacheResolution);
93         }
94 }
95
96 int SGCloudField::get_CacheSize(void) { 
97         return SGNewCloud::cldCache->queryCacheSize(); 
98 }
99
100 void SGCloudField::set_CacheSize(int sizeKb) {
101         // apply in rendering option dialog
102         if(last_cache_size == sizeKb)
103                 return;
104         if(sizeKb == 0)
105                 return;
106         if(sizeKb)
107                 last_cache_size = sizeKb;
108         if(enable3D) {
109                 int count = last_cache_size * 1024 / (cacheResolution * cacheResolution * 4);
110                 if(count == 0)
111                         count = 1;
112                 SGNewCloud::cldCache->setCacheSize(count, cacheResolution);
113         }
114 }
115 void SGCloudField::set_CloudVis(float distance) {
116         if( distance <= fieldSize )
117                 SGCloudField::CloudVis = distance;
118 }
119 void SGCloudField::set_density(float density) {
120         SGCloudField::density = density;
121 }
122 void SGCloudField::set_enable3dClouds(bool enable) {
123         if(enable3D == enable)
124                 return;
125         enable3D = enable;
126         if(enable) {
127                 int count = last_cache_size * 1024 / (cacheResolution * cacheResolution * 4);
128                 if(count == 0)
129                         count = 1;
130                 SGNewCloud::cldCache->setCacheSize(count, cacheResolution);
131         } else {
132                 SGNewCloud::cldCache->setCacheSize(0);
133         }
134 }
135
136 // reposition the cloud layer at the specified origin and orientation
137 void SGCloudField::reposition( sgVec3 p, sgVec3 up, double lon, double lat, double alt, double dt, float direction, float speed) {
138     sgMat4 T1, LON, LAT;
139     sgVec3 axis;
140
141     sgMakeTransMat4( T1, p );
142
143     sgSetVec3( axis, 0.0, 0.0, 1.0 );
144     sgMakeRotMat4( LON, lon * SGD_RADIANS_TO_DEGREES, axis );
145
146     sgSetVec3( axis, 0.0, 1.0, 0.0 );
147     sgMakeRotMat4( LAT, 90.0 - lat * SGD_RADIANS_TO_DEGREES, axis );
148
149     sgMat4 TRANSFORM;
150
151     sgCopyMat4( TRANSFORM, T1 );
152     sgPreMultMat4( TRANSFORM, LON );
153     sgPreMultMat4( TRANSFORM, LAT );
154
155     sgCoord layerpos;
156     sgSetCoord( &layerpos, TRANSFORM );
157
158         sgMakeCoordMat4( transform, &layerpos );
159
160
161         this->alt = alt;
162
163         // simulate clouds movement from wind
164     double sp_dist = speed*dt;
165     if (sp_dist > 0) {
166         double bx = cos((180.0-direction) * SGD_DEGREES_TO_RADIANS) * sp_dist;
167         double by = sin((180.0-direction) * SGD_DEGREES_TO_RADIANS) * sp_dist;
168                 relative_position[SG_X] += bx;
169                 relative_position[SG_Y] += by;
170     }
171
172     if ( lon != last_lon || lat != last_lat || sp_dist != 0 ) {
173         Point3D start( last_lon, last_lat, 0.0 );
174         Point3D dest( lon, lat, 0.0 );
175         double course = 0.0, dist = 0.0;
176
177         calc_gc_course_dist( dest, start, &course, &dist );
178         // if start and dest are too close together,
179         // calc_gc_course_dist() can return a course of "nan".  If
180         // this happens, lets just use the last known good course.
181         // This is a hack, and it would probably be better to make
182         // calc_gc_course_dist() more robust.
183         if ( isnan(course) ) {
184             course = last_course;
185         } else {
186             last_course = course;
187         }
188
189         // calculate cloud movement due to external forces
190         double ax = 0.0, ay = 0.0;
191
192         if (dist > 0.0) {
193             ax = cos(course) * dist;
194             ay = sin(course) * dist;
195         }
196
197                 deltax += ax;
198                 deltay += ay;
199
200         last_lon = lon;
201         last_lat = lat;
202     }
203
204
205         // correct the frustum with the right far plane
206         ssgContext *context = ssgGetCurrentContext();
207         frustum = *context->getFrustum();
208
209         float w, h;
210         sgEnviro.getFOV( w, h );
211         frustum.setFOV( w, h );
212         frustum.setNearFar(1.0, CloudVis);
213         timer_dt = dt;
214 }
215
216 SGCloudField::SGCloudField() :
217         deltax(0.0),
218         deltay(0.0),
219         last_course(0.0),
220         last_density(0.0),
221         draw_in_3d(true)
222 {
223         sgSetVec3( relative_position, 0,0,0);
224         theField.reserve(200);
225         inViewClouds.reserve(200);
226         sg_srandom_time_10();
227 }
228
229 SGCloudField::~SGCloudField() {
230         list_of_Cloud::iterator iCloud;
231         for( iCloud = theField.begin() ; iCloud != theField.end() ; iCloud++ ) {
232                 delete iCloud->aCloud;
233         }
234         theField.clear();
235 }
236
237
238 void SGCloudField::clear(void) {
239         list_of_Cloud::iterator iCloud;
240         for( iCloud = theField.begin() ; iCloud != theField.end() ; iCloud++ ) {
241                 delete iCloud->aCloud;
242         }
243         theField.clear();
244         // force a recompute of density on first redraw
245         last_density = 0.0;
246         // true to come back in set density after layer is built
247         draw_in_3d = true;
248 }
249
250 // use a table or else we see poping when moving the slider...
251 static int densTable[][10] = {
252         {0,0,0,0,0,0,0,0,0,0},
253         {1,0,0,0,0,0,0,0,0,0},
254         {1,0,0,0,1,0,0,0,0,0},
255         {1,0,0,0,1,0,0,1,0,0}, // 30%
256         {1,0,1,0,1,0,0,1,0,0},
257         {1,0,1,0,1,0,1,1,0,0}, // 50%
258         {1,0,1,0,1,0,1,1,0,1},
259         {1,0,1,1,1,0,1,1,0,1}, // 70%
260         {1,1,1,1,1,0,1,1,0,1},
261         {1,1,1,1,1,0,1,1,1,1}, // 90%
262         {1,1,1,1,1,1,1,1,1,1}
263 };
264
265 // set the visible flag depending on density
266 void SGCloudField::applyDensity(void) {
267         int row = (int) (density / 10.0);
268         int col = 0;
269     sgBox fieldBox;
270
271         list_of_Cloud::iterator iCloud;
272         for( iCloud = theField.begin() ; iCloud != theField.end() ; iCloud++ ) {
273                 if(++col > 9)
274                         col = 0;
275                 if( densTable[row][col] ) {
276                         iCloud->visible = true;
277             fieldBox.extend( *iCloud->aCloud->getCenter() );
278                 } else
279                         iCloud->visible = false;
280         }
281         last_density = density;
282         draw_in_3d = ( theField.size() != 0);
283     sgVec3 center;
284     sgSubVec3( center, fieldBox.getMax(), fieldBox.getMin() );
285     sgScaleVec3( center, 0.5f );
286     center[1] = 0.0f;
287     field_sphere.setCenter( center );
288     field_sphere.setRadius( fieldSize * 0.5f * 1.414f );
289 }
290
291 // add one cloud, data is not copied, ownership given
292 void SGCloudField::addCloud( sgVec3 pos, SGNewCloud *cloud) {
293         Cloud cl;
294         cl.aCloud = cloud;
295         cl.visible = true;
296         cloud->SetPos( pos );
297         sgCopyVec3( cl.pos, *cloud->getCenter() );
298         theField.push_back( cl );
299 }
300
301
302 static float Rnd(float n) {
303         return n * (-0.5f + sg_random());
304 }
305
306 // for debug only
307 // build a field of cloud of size 25x25 km, its a grid of 11x11 clouds
308 void SGCloudField::buildTestLayer(void) {
309
310         const float s = 2250.0f;
311
312         for( int z = -5 ; z <= 5 ; z++) {
313                 for( int x = -5 ; x <= 5 ; x++ ) {
314                         SGNewCloud *cloud = new SGNewCloud(SGNewCloud::CLFamilly_cu);
315                         cloud->new_cu();
316                         sgVec3 pos = {(x+Rnd(0.7)) * s, 750.0f, (z+Rnd(0.7)) * s};
317             addCloud(pos, cloud);
318                 }
319         }
320         applyDensity();
321 }
322
323 // cull all clouds of a tiled field
324 void SGCloudField::cullClouds(sgVec3 eyePos, sgMat4 mat) {
325         list_of_Cloud::iterator iCloud;
326
327     sgSphere tile_sphere;
328     tile_sphere.setRadius( field_sphere.getRadius() );
329     sgVec3 tile_center;
330     sgSubVec3( tile_center, field_sphere.getCenter(), eyePos );
331     tile_sphere.setCenter( tile_center );
332     tile_sphere.orthoXform(mat);
333     if( frustum.contains( & tile_sphere ) == SG_OUTSIDE )
334         return;
335
336         for( iCloud = theField.begin() ; iCloud != theField.end() ; iCloud++ ) {
337                 sgVec3 dist;
338                 sgSphere sphere;
339                 if( ! iCloud->visible )
340                         continue;
341                 sgSubVec3( dist, iCloud->pos, eyePos );
342                 sphere.setCenter(dist[0], dist[2], dist[1] + eyePos[1]);
343                 float radius = iCloud->aCloud->getRadius();
344                 sphere.setRadius(radius);
345                 sphere.orthoXform(mat);
346                 if( frustum.contains( & sphere ) != SG_OUTSIDE ) {
347                         float squareDist = dist[0]*dist[0] + dist[1]*dist[1] + dist[2]*dist[2];
348                         culledCloud tmp;
349                         tmp.aCloud = iCloud->aCloud;
350                         sgCopyVec3( tmp.eyePos, eyePos ); 
351                         // save distance for later sort, opposite distance because we want back to front
352                         tmp.dist   =  - squareDist;
353                         tmp.heading = -SG_PI/2.0 - atan2( dist[0], dist[2] ); // + SG_PI;
354                         tmp.alt         = iCloud->pos[1];
355                         inViewClouds.push_back(tmp);
356                         if( squareDist - radius*radius < 100*100 )
357                                 sgEnviro.set_view_in_cloud(true);
358                 }
359         }
360
361 }
362
363
364 // Render a cloud field
365 // because no field can have an infinite size (and we don't want to reach his border)
366 // we draw this field and adjacent fields.
367 // adjacent fields are not real, its the same field displaced by some offset
368 void SGCloudField::Render(void) {
369     sgVec3 eyePos;
370         double relx, rely;
371
372         if( ! enable3D )
373                 return;
374
375         if( last_density != density ) {
376                 last_density = density;
377                 applyDensity();
378         }
379
380         if( ! draw_in_3d )
381                 return;
382
383         if( ! SGNewCloud::cldCache->isRttAvailable() )
384                 return;
385
386         inViewClouds.clear();
387
388  
389         glPushMatrix();
390  
391         sgMat4 modelview, tmp, invtrans;
392
393         // try to find the sun position
394         sgTransposeNegateMat4( invtrans, transform );
395     sgVec3 lightVec;
396     ssgGetLight( 0 )->getPosition( lightVec );
397     sgXformVec3( lightVec, invtrans );
398
399         sgSetVec3(  SGNewCloud::modelSunDir, lightVec[0], lightVec[2], lightVec[1]);
400         // try to find the lighting data (not accurate)
401         sgVec4 diffuse, ambient;
402         ssgGetLight( 0 )->getColour( GL_DIFFUSE, diffuse );
403         ssgGetLight( 0 )->getColour( GL_AMBIENT, ambient );
404 //      sgScaleVec3 ( SGNewCloud::sunlight, diffuse , 1.0f);
405         sgScaleVec3 ( SGNewCloud::ambLight, ambient , 1.1f);
406         // trying something else : clouds are more yellow/red at dawn/dusk
407         // and added a bit of blue ambient
408     float *sun_color = thesky->get_sun_color();
409         sgScaleVec3 ( SGNewCloud::sunlight, sun_color , 0.4f);
410         SGNewCloud::ambLight[2] += 0.1f;
411
412         sgVec3 delta_light;
413         sgSubVec3(delta_light, last_sunlight, SGNewCloud::sunlight);
414         if( (fabs(delta_light[0]) + fabs(delta_light[1]) + fabs(delta_light[2])) > 0.05f ) {
415                 sgCopyVec3( last_sunlight, SGNewCloud::sunlight );
416                 // force the redraw of all the impostors
417                 SGNewCloud::cldCache->invalidateCache();
418         }
419
420         // voodoo things on the matrix stack
421     ssgGetModelviewMatrix( modelview );
422         sgCopyMat4( tmp, transform );
423     sgPostMultMat4( tmp, modelview );
424
425         // cloud fields are tiled on the flat earth
426         // compute the position in the tile
427         relx = fmod( deltax + relative_position[SG_X], fieldSize );
428         rely = fmod( deltay + relative_position[SG_Y], fieldSize );
429
430         relx = fmod( relx + fieldSize, fieldSize );
431         rely = fmod( rely + fieldSize, fieldSize );
432         sgSetVec3( eyePos, relx, alt, rely);
433
434         sgSetVec3( view_X, tmp[0][0], tmp[1][0], tmp[2][0] );
435         sgSetVec3( view_Y, tmp[0][1], tmp[1][1], tmp[2][1] );
436         sgSetVec3( view_vec, tmp[0][2], tmp[1][2], tmp[2][2] );
437
438     ssgLoadModelviewMatrix( tmp );
439  
440 /* flat earth
441
442         ^
443         |
444         |    FFF
445         |    FoF
446         |    FFF
447         |
448         O----------->
449                 o = we are here
450                 F = adjacent fields
451 */
452
453         for(int x = -1 ; x <= 1 ; x++)
454                 for(int y = -1 ; y <= 1 ; y++ ) {
455                         sgVec3 fieldPos;
456                         // pretend we are not where we are
457                         sgSetVec3(fieldPos, eyePos[0] + x*fieldSize, eyePos[1], eyePos[2] + y*fieldSize);
458                         cullClouds(fieldPos, tmp);
459                 }
460         // sort all visible clouds back to front (because of transparency)
461         std::sort( inViewClouds.begin(), inViewClouds.end() );
462  
463         // TODO:push states
464         glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
465     glEnable(GL_ALPHA_TEST);
466     glAlphaFunc(GL_GREATER, 0.0f);
467         glDisable(GL_CULL_FACE);
468         glEnable(GL_DEPTH_TEST);
469         glDepthMask( GL_FALSE );
470         glEnable(GL_SMOOTH);
471     glEnable(GL_BLEND);
472         glBlendFunc( GL_ONE, GL_ONE_MINUS_SRC_ALPHA );
473         glEnable( GL_TEXTURE_2D );
474         glDisable( GL_FOG );
475     glDisable(GL_LIGHTING);
476
477         // test data: field = 11x11 cloud, 9 fields
478         // depending on position and view direction, perhaps 40 to 60 clouds not culled
479         list_of_culledCloud::iterator iCloud;
480         for( iCloud = inViewClouds.begin() ; iCloud != inViewClouds.end() ; iCloud++ ) {
481 //              iCloud->aCloud->drawContainers();
482                 iCloud->aCloud->Render(iCloud->eyePos);
483                 sgEnviro.callback_cloud(iCloud->heading, iCloud->alt, 
484                         iCloud->aCloud->getRadius(), iCloud->aCloud->getFamilly(), - iCloud->dist, iCloud->aCloud->getId());
485         }
486
487         glBindTexture(GL_TEXTURE_2D, 0);
488     glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
489         glEnable( GL_FOG );
490         glEnable(GL_CULL_FACE);
491         glEnable(GL_DEPTH_TEST);
492
493         ssgLoadModelviewMatrix( modelview );
494
495         glPopMatrix();
496
497 }
498