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