]> git.mxchange.org Git - simgear.git/blob - simgear/scene/sky/cloud.cxx
9e848e3bb9d251ee9059489b635ff5d0f122e32e
[simgear.git] / simgear / scene / sky / cloud.cxx
1 // cloud.cxx -- model a single cloud layer
2 //
3 // Written by Curtis Olson, started June 2000.
4 //
5 // Copyright (C) 2000  Curtis L. Olson  - curt@flightgear.org
6 //
7 // This program is distributed in the hope that it will be useful, but
8 // WITHOUT ANY WARRANTY; without even the implied warranty of
9 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
10 // General Public License for more details.
11 //
12 // You should have received a copy of the GNU General Public License
13 // along with this program; if not, write to the Free Software
14 // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
15 //
16 // $Id$
17
18
19 #include <simgear/compiler.h>
20
21 // #include <stdio.h>
22 #include <math.h>
23
24 // #if defined (__APPLE__) 
25 // // any C++ header file undefines isinf and isnan
26 // // so this should be included before <iostream>
27 // inline int (isinf)(double r) { return isinf(r); }
28 // inline int (isnan)(double r) { return isnan(r); } 
29 // #endif
30
31 // #include STL_IOSTREAM
32
33 #include <plib/sg.h>
34 #include <plib/ssg.h>
35
36 #include <simgear/math/point3d.hxx>
37 #include <simgear/math/polar3d.hxx>
38 #include <simgear/math/sg_random.h>
39 #include <simgear/debug/logstream.hxx>
40 #include <simgear/misc/sg_path.hxx>
41 #include <simgear/screen/extensions.hxx>
42 #include <simgear/screen/texture.hxx>
43
44 #include "cloud.hxx"
45
46
47 static ssgStateSelector *layer_states[SGCloudLayer::SG_MAX_CLOUD_COVERAGES];
48 static bool state_initialized = false;
49 static bool bump_mapping = false;
50 static int nb_texture_unit = 0;
51 static ssgTexture *normal_map[SGCloudLayer::SG_MAX_CLOUD_COVERAGES][2] = { 0 };
52 static ssgTexture *color_map[SGCloudLayer::SG_MAX_CLOUD_COVERAGES][2] = { 0 };
53 static GLuint normalization_cube_map;
54
55 static glActiveTextureProc glActiveTexturePtr = 0;
56 static glClientActiveTextureProc glClientActiveTexturePtr = 0;
57
58 bool SGCloudLayer::enable_bump_mapping = false;
59
60 static void
61 generateNormalizationCubeMap()
62 {
63     unsigned char data[ 32 * 32 * 3 ];
64     const int size = 32;
65     const float half_size = 16.0f,
66                 offset = 0.5f;
67     sgVec3 zero_normal;
68     sgSetVec3( zero_normal, 0.5f, 0.5f, 0.5f );
69     int i, j;
70
71     unsigned char *ptr = data;
72     for ( j = 0; j < size; j++ ) {
73         for ( i = 0; i < size; i++ ) {
74             sgVec3 tmp;
75             sgSetVec3( tmp, half_size,
76                             -( j + offset - half_size ),
77                             -( i + offset - half_size ) );
78             sgNormalizeVec3( tmp );
79             sgScaleVec3( tmp, 0.5f );
80             sgAddVec3( tmp, zero_normal );
81
82             *ptr++ = (unsigned char)( tmp[ 0 ] * 255 );
83             *ptr++ = (unsigned char)( tmp[ 1 ] * 255 );
84             *ptr++ = (unsigned char)( tmp[ 2 ] * 255 );
85         }
86     }
87     glTexImage2D( GL_TEXTURE_CUBE_MAP_POSITIVE_X_ARB,
88                   0, GL_RGBA8, 32, 32, 0, GL_RGB, GL_UNSIGNED_BYTE, data );
89
90     ptr = data;
91     for ( j = 0; j < size; j++ ) {
92         for ( i = 0; i < size; i++ ) {
93             sgVec3 tmp;
94             sgSetVec3( tmp, -half_size,
95                             -( j + offset - half_size ),
96                             ( i + offset - half_size ) );
97             sgNormalizeVec3( tmp );
98             sgScaleVec3( tmp, 0.5f );
99             sgAddVec3( tmp, zero_normal );
100
101             *ptr++ = (unsigned char)( tmp[ 0 ] * 255 );
102             *ptr++ = (unsigned char)( tmp[ 1 ] * 255 );
103             *ptr++ = (unsigned char)( tmp[ 2 ] * 255 );
104         }
105     }
106     glTexImage2D( GL_TEXTURE_CUBE_MAP_NEGATIVE_X_ARB,
107                   0, GL_RGBA8, 32, 32, 0, GL_RGB, GL_UNSIGNED_BYTE, data );
108
109     ptr = data;
110     for ( j = 0; j < size; j++ ) {
111         for ( i = 0; i < size; i++ ) {
112             sgVec3 tmp;
113             sgSetVec3( tmp, ( i + offset - half_size ),
114                             half_size,
115                             ( j + offset - half_size ) );
116             sgNormalizeVec3( tmp );
117             sgScaleVec3( tmp, 0.5f );
118             sgAddVec3( tmp, zero_normal );
119
120             *ptr++ = (unsigned char)( tmp[ 0 ] * 255 );
121             *ptr++ = (unsigned char)( tmp[ 1 ] * 255 );
122             *ptr++ = (unsigned char)( tmp[ 2 ] * 255 );
123         }
124     }
125     glTexImage2D( GL_TEXTURE_CUBE_MAP_POSITIVE_Y_ARB,
126                   0, GL_RGBA8, 32, 32, 0, GL_RGB, GL_UNSIGNED_BYTE, data );
127
128     ptr = data;
129     for ( j = 0; j < size; j++ ) {
130         for ( i = 0; i < size; i++ ) {
131             sgVec3 tmp;
132             sgSetVec3( tmp, ( i + offset - half_size ),
133                             -half_size,
134                             -( j + offset - half_size ) );
135             sgNormalizeVec3( tmp );
136             sgScaleVec3( tmp, 0.5f );
137             sgAddVec3( tmp, zero_normal );
138
139             *ptr++ = (unsigned char)( tmp[ 0 ] * 255 );
140             *ptr++ = (unsigned char)( tmp[ 1 ] * 255 );
141             *ptr++ = (unsigned char)( tmp[ 2 ] * 255 );
142         }
143     }
144     glTexImage2D( GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_ARB,
145                   0, GL_RGBA8, 32, 32, 0, GL_RGB, GL_UNSIGNED_BYTE, data );
146
147     ptr = data;
148     for ( j = 0; j < size; j++ ) {
149         for ( i = 0; i < size; i++ ) {
150             sgVec3 tmp;
151             sgSetVec3( tmp, ( i + offset - half_size ),
152                             -( j + offset - half_size ),
153                             half_size );
154             sgNormalizeVec3( tmp );
155             sgScaleVec3( tmp, 0.5f );
156             sgAddVec3( tmp, zero_normal );
157
158             *ptr++ = (unsigned char)( tmp[ 0 ] * 255 );
159             *ptr++ = (unsigned char)( tmp[ 1 ] * 255 );
160             *ptr++ = (unsigned char)( tmp[ 2 ] * 255 );
161         }
162     }
163     glTexImage2D( GL_TEXTURE_CUBE_MAP_POSITIVE_Z_ARB,
164                   0, GL_RGBA8, 32, 32, 0, GL_RGB, GL_UNSIGNED_BYTE, data );
165
166     ptr = data;
167     for ( j = 0; j < size; j++ ) {
168         for ( i = 0; i < size; i++ ) {
169             sgVec3 tmp;
170             sgSetVec3( tmp, -( i + offset - half_size ),
171                             -( j + offset - half_size ),
172                             -half_size );
173             sgNormalizeVec3( tmp );
174             sgScaleVec3( tmp, 0.5f );
175             sgAddVec3( tmp, zero_normal );
176
177             *ptr++ = (unsigned char)( tmp[ 0 ] * 255 );
178             *ptr++ = (unsigned char)( tmp[ 1 ] * 255 );
179             *ptr++ = (unsigned char)( tmp[ 2 ] * 255 );
180         }
181     }
182     glTexImage2D( GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_ARB,
183                   0, GL_RGBA8, 32, 32, 0, GL_RGB, GL_UNSIGNED_BYTE, data );
184 }
185
186
187 // Constructor
188 SGCloudLayer::SGCloudLayer( const string &tex_path ) :
189     layer_root(new ssgRoot),
190     layer_transform(new ssgTransform),
191     state_sel(0),
192     texture_path(tex_path),
193     layer_span(0.0),
194     layer_asl(0.0),
195     layer_thickness(0.0),
196     layer_transition(0.0),
197     layer_coverage(SG_CLOUD_CLEAR),
198     scale(4000.0),
199     speed(0.0),
200     direction(0.0),
201     last_lon(0.0),
202     last_lat(0.0),
203     vertices(0),
204     indices(0)
205 {
206     cl[0] = cl[1] = cl[2] = cl[3] = NULL;
207     vl[0] = vl[1] = vl[2] = vl[3] = NULL;
208     tl[0] = tl[1] = tl[2] = tl[3] = NULL;
209     layer[0] = layer[1] = layer[2] = layer[3] = NULL;
210
211     layer_root->addKid(layer_transform);
212     rebuild();
213 }
214
215 // Destructor
216 SGCloudLayer::~SGCloudLayer()
217 {
218     delete vertices;
219     delete indices;
220     delete layer_root;          // deletes layer_transform and layer as well
221 }
222
223 float
224 SGCloudLayer::getSpan_m () const
225 {
226     return layer_span;
227 }
228
229 void
230 SGCloudLayer::setSpan_m (float span_m)
231 {
232     if (span_m != layer_span) {
233         layer_span = span_m;
234         rebuild();
235     }
236 }
237
238 float
239 SGCloudLayer::getElevation_m () const
240 {
241     return layer_asl;
242 }
243
244 void
245 SGCloudLayer::setElevation_m (float elevation_m, bool set_span)
246 {
247     layer_asl = elevation_m;
248
249     if (set_span) {
250         if (elevation_m > 4000)
251             setSpan_m(  elevation_m * 10 );
252         else
253             setSpan_m( 40000 );
254     }
255 }
256
257 float
258 SGCloudLayer::getThickness_m () const
259 {
260     return layer_thickness;
261 }
262
263 void
264 SGCloudLayer::setThickness_m (float thickness_m)
265 {
266     layer_thickness = thickness_m;
267 }
268
269 float
270 SGCloudLayer::getTransition_m () const
271 {
272     return layer_transition;
273 }
274
275 void
276 SGCloudLayer::setTransition_m (float transition_m)
277 {
278     layer_transition = transition_m;
279 }
280
281 SGCloudLayer::Coverage
282 SGCloudLayer::getCoverage () const
283 {
284     return layer_coverage;
285 }
286
287 void
288 SGCloudLayer::setCoverage (Coverage coverage)
289 {
290     if (coverage != layer_coverage) {
291         layer_coverage = coverage;
292         rebuild();
293     }
294 }
295
296
297 // build the cloud object
298 void
299 SGCloudLayer::rebuild()
300 {
301     // Initialize states and sizes if necessary.
302     if ( !state_initialized ) { 
303         state_initialized = true;
304
305         SG_LOG(SG_ASTRO, SG_INFO, "initializing cloud layers");
306
307         bump_mapping = SGIsOpenGLExtensionSupported("GL_ARB_multitexture") &&
308                        SGIsOpenGLExtensionSupported("GL_ARB_texture_cube_map") &&
309                        SGIsOpenGLExtensionSupported("GL_ARB_texture_env_combine") &&
310                        SGIsOpenGLExtensionSupported("GL_ARB_texture_env_dot3") && true;
311
312         if ( bump_mapping ) {
313             glGetIntegerv( GL_MAX_TEXTURE_UNITS_ARB, &nb_texture_unit );
314             if ( nb_texture_unit < 2 ) {
315                 bump_mapping = false;
316             }
317         }
318
319         if ( bump_mapping ) {
320
321             // This bump mapping code was inspired by the tutorial available at 
322             // http://www.paulsprojects.net/tutorials/simplebump/simplebump.html
323             // and a NVidia white paper 
324             //  http://developer.nvidia.com/object/bumpmappingwithregistercombiners.html
325             // The normal map textures were generated by the normal map Gimp plugin :
326             //  http://nifelheim.dyndns.org/~cocidius/normalmap/
327             //
328             SGPath cloud_path;
329
330             glActiveTexturePtr = (glActiveTextureProc)SGLookupFunction("glActiveTextureARB");
331             glClientActiveTexturePtr = (glClientActiveTextureProc)SGLookupFunction("glClientActiveTextureARB");
332
333             cloud_path.set(texture_path.str());
334             cloud_path.append("overcast.rgb");
335             color_map[ SG_CLOUD_OVERCAST ][ 0 ] = new ssgTexture( cloud_path.str().c_str() );
336             color_map[ SG_CLOUD_OVERCAST ][ 0 ]->ref();
337             cloud_path.set(texture_path.str());
338             cloud_path.append("overcast_n.rgb");
339             normal_map[ SG_CLOUD_OVERCAST ][ 0 ] = new ssgTexture( cloud_path.str().c_str() );
340             normal_map[ SG_CLOUD_OVERCAST ][ 0 ]->ref();
341
342             cloud_path.set(texture_path.str());
343             cloud_path.append("overcast_top.rgb");
344             color_map[ SG_CLOUD_OVERCAST ][ 1 ] = new ssgTexture( cloud_path.str().c_str() );
345             color_map[ SG_CLOUD_OVERCAST ][ 1 ]->ref();
346             cloud_path.set(texture_path.str());
347             cloud_path.append("overcast_top_n.rgb");
348             normal_map[ SG_CLOUD_OVERCAST ][ 1 ] = new ssgTexture( cloud_path.str().c_str() );
349             normal_map[ SG_CLOUD_OVERCAST ][ 1 ]->ref();
350
351             cloud_path.set(texture_path.str());
352             cloud_path.append("broken.rgba");
353             color_map[ SG_CLOUD_BROKEN ][ 0 ] = new ssgTexture( cloud_path.str().c_str() );
354             color_map[ SG_CLOUD_BROKEN ][ 0 ]->ref();
355             cloud_path.set(texture_path.str());
356             cloud_path.append("broken_n.rgb");
357             normal_map[ SG_CLOUD_BROKEN ][ 0 ] = new ssgTexture( cloud_path.str().c_str() );
358             normal_map[ SG_CLOUD_BROKEN ][ 0 ]->ref();
359
360             cloud_path.set(texture_path.str());
361             cloud_path.append("scattered.rgba");
362             color_map[ SG_CLOUD_SCATTERED ][ 0 ] = new ssgTexture( cloud_path.str().c_str() );
363             color_map[ SG_CLOUD_SCATTERED ][ 0 ]->ref();
364             cloud_path.set(texture_path.str());
365             cloud_path.append("scattered_n.rgb");
366             normal_map[ SG_CLOUD_SCATTERED ][ 0 ] = new ssgTexture( cloud_path.str().c_str() );
367             normal_map[ SG_CLOUD_SCATTERED ][ 0 ]->ref();
368
369             cloud_path.set(texture_path.str());
370             cloud_path.append("few.rgba");
371             color_map[ SG_CLOUD_FEW ][ 0 ] = new ssgTexture( cloud_path.str().c_str() );
372             color_map[ SG_CLOUD_FEW ][ 0 ]->ref();
373             cloud_path.set(texture_path.str());
374             cloud_path.append("few_n.rgb");
375             normal_map[ SG_CLOUD_FEW ][ 0 ] = new ssgTexture( cloud_path.str().c_str() );
376             normal_map[ SG_CLOUD_FEW ][ 0 ]->ref();
377
378             cloud_path.set(texture_path.str());
379             cloud_path.append("cirrus.rgba");
380             color_map[ SG_CLOUD_CIRRUS ][ 0 ] = new ssgTexture( cloud_path.str().c_str() );
381             color_map[ SG_CLOUD_CIRRUS ][ 0 ]->ref();
382             cloud_path.set(texture_path.str());
383             cloud_path.append("cirrus_n.rgb");
384             normal_map[ SG_CLOUD_CIRRUS ][ 0 ] = new ssgTexture( cloud_path.str().c_str() );
385             normal_map[ SG_CLOUD_CIRRUS ][ 0 ]->ref();
386
387             glGenTextures( 1, &normalization_cube_map );
388             glBindTexture( GL_TEXTURE_CUBE_MAP_ARB, normalization_cube_map );
389             generateNormalizationCubeMap();
390             glTexParameteri( GL_TEXTURE_CUBE_MAP_ARB, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
391             glTexParameteri( GL_TEXTURE_CUBE_MAP_ARB, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
392             glTexParameteri( GL_TEXTURE_CUBE_MAP_ARB, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );
393             glTexParameteri( GL_TEXTURE_CUBE_MAP_ARB, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );
394             glTexParameteri( GL_TEXTURE_CUBE_MAP_ARB, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE );
395         } /* else */ {
396             SGPath cloud_path;
397             ssgStateSelector *state_sel;
398             ssgSimpleState *state;
399
400             state_sel = new ssgStateSelector( 2 );
401             state_sel->ref();
402             cloud_path.set(texture_path.str());
403             cloud_path.append("overcast.rgb");
404             state_sel->setStep( 0, sgCloudMakeState(cloud_path.str()) );
405             cloud_path.set(texture_path.str());
406             cloud_path.append("overcast_top.rgb");
407             state_sel->setStep( 1, sgCloudMakeState(cloud_path.str()) );
408             layer_states[SG_CLOUD_OVERCAST] = state_sel;
409
410             state_sel = new ssgStateSelector( 2 );
411             state_sel->ref();
412             cloud_path.set(texture_path.str());
413             cloud_path.append("broken.rgba");
414             state = sgCloudMakeState(cloud_path.str());
415             state_sel->setStep( 0, state );
416             state_sel->setStep( 1, state );
417             layer_states[SG_CLOUD_BROKEN] = state_sel;
418
419             state_sel = new ssgStateSelector( 2 );
420             state_sel->ref();
421             cloud_path.set(texture_path.str());
422             cloud_path.append("scattered.rgba");
423             state = sgCloudMakeState(cloud_path.str());
424             state_sel->setStep( 0, state );
425             state_sel->setStep( 1, state );
426             layer_states[SG_CLOUD_SCATTERED] = state_sel;
427
428             state_sel = new ssgStateSelector( 2 );
429             state_sel->ref();
430             cloud_path.set(texture_path.str());
431             cloud_path.append("few.rgba");
432             state = sgCloudMakeState(cloud_path.str());
433             state_sel->setStep( 0, state );
434             state_sel->setStep( 1, state );
435             layer_states[SG_CLOUD_FEW] = state_sel;
436
437             state_sel = new ssgStateSelector( 2 );
438             state_sel->ref();
439             cloud_path.set(texture_path.str());
440             cloud_path.append("cirrus.rgba");
441             state = sgCloudMakeState(cloud_path.str());
442             state_sel->setStep( 0, state );
443             state_sel->setStep( 1, state );
444             layer_states[SG_CLOUD_CIRRUS] = state_sel;
445
446             layer_states[SG_CLOUD_CLEAR] = 0;
447         }
448     }
449
450     if ( bump_mapping ) {
451
452         if ( !vertices ) {
453             vertices = new CloudVertex[ 25 ];
454             indices = new unsigned int[ 40 ];
455         }
456
457         sgVec2 base;
458         sgSetVec2( base, sg_random(), sg_random() );
459
460         const float layer_scale = layer_span / scale;
461         const float layer_to_core = (SG_EARTH_RAD * 1000 + layer_asl);
462         const float half_angle = 0.5 * layer_span / layer_to_core;
463
464         int i;
465         for ( i = -2; i <= 2; i++ ) {
466             for ( int j = -2; j <= 2; j++ ) {
467                 CloudVertex &v1 = vertices[ (i+2)*5 + (j+2) ];
468                 sgSetVec3( v1.position,
469                            0.5 * i * layer_span,
470                            0.5 * j * layer_span,
471                            -layer_to_core * ( 1 - cos( i * half_angle ) * cos( j * half_angle ) ) );
472                 sgSetVec2( v1.texCoord,
473                            base[0] + layer_scale * i * 0.25,
474                            base[1] + layer_scale * j * 0.25 );
475                 sgSetVec3( v1.sTangent,
476                            cos( i * half_angle ),
477                            0.f,
478                            -sin( i * half_angle ) );
479                 sgSetVec3( v1.tTangent,
480                            0.f,
481                            cos( j * half_angle ),
482                            -sin( j * half_angle ) );
483                 sgVectorProductVec3( v1.normal, v1.tTangent, v1.sTangent );
484                 sgSetVec4( v1.color, 1.0f, 1.0f, 1.0f, (i == 0) ? 0.0f : 0.15f );
485             }
486         }
487         /*
488          * 0 1 5 6 10 11 15 16 20 21
489          * 1 2 6 7 11 12 16 17 21 22
490          * 2 3 7 8 12 13 17 18 22 23
491          * 3 4 8 9 13 14 18 19 23 24
492          */
493         for ( i = 0; i < 4; i++ ) {
494             for ( int j = 0; j < 5; j++ ) {
495                 indices[ i*10 + (j*2) ]     =     i + 5 * j;
496                 indices[ i*10 + (j*2) + 1 ] = 1 + i + 5 * j;
497             }
498         }
499
500     } /* else */ {
501
502         scale = 4000.0;
503         last_lon = last_lat = -999.0f;
504
505         sgVec2 base;
506         sgSetVec2( base, sg_random(), sg_random() );
507
508         // build the cloud layer
509         sgVec4 color;
510         sgVec3 vertex;
511         sgVec2 tc;
512
513         const float layer_scale = layer_span / scale;
514         const float mpi = SG_PI/4;
515
516         // caclculate the difference between a flat-earth model and 
517         // a round earth model given the span and altutude ASL of
518         // the cloud layer. This is the difference in altitude between
519         // the top of the inverted bowl and the edge of the bowl.
520         // const float alt_diff = layer_asl * 0.8;
521         const float layer_to_core = (SG_EARTH_RAD * 1000 + layer_asl);
522         const float layer_angle = 0.5*layer_span / layer_to_core; // The angle is half the span
523         const float border_to_core = layer_to_core * cos(layer_angle);
524         const float alt_diff = layer_to_core - border_to_core;
525
526         for (int i = 0; i < 4; i++)
527         {
528             if ( layer[i] != NULL ) {
529                 layer_transform->removeKid(layer[i]); // automatic delete
530             }
531
532             vl[i] = new ssgVertexArray( 10 );
533             cl[i] = new ssgColourArray( 10 );
534             tl[i] = new ssgTexCoordArray( 10 );
535
536
537             sgSetVec3( vertex, layer_span*(i-2)/2, -layer_span,
538                             alt_diff * (sin(i*mpi) - 2) );
539
540             sgSetVec2( tc, base[0] + layer_scale * i/4, base[1] );
541
542             sgSetVec4( color, 1.0f, 1.0f, 1.0f, (i == 0) ? 0.0f : 0.15f );
543
544             cl[i]->add( color );
545             vl[i]->add( vertex );
546             tl[i]->add( tc );
547
548             for (int j = 0; j < 4; j++)
549             {
550                 sgSetVec3( vertex, layer_span*(i-1)/2, layer_span*(j-2)/2,
551                                 alt_diff * (sin((i+1)*mpi) + sin(j*mpi) - 2) );
552
553                 sgSetVec2( tc, base[0] + layer_scale * (i+1)/4,
554                             base[1] + layer_scale * j/4 );
555
556                 sgSetVec4( color, 1.0f, 1.0f, 1.0f,
557                                 ( (j == 0) || (i == 3)) ?  
558                                 ( (j == 0) && (i == 3)) ? 0.0f : 0.15f : 1.0f );
559
560                 cl[i]->add( color );
561                 vl[i]->add( vertex );
562                 tl[i]->add( tc );
563
564
565                 sgSetVec3( vertex, layer_span*(i-2)/2, layer_span*(j-1)/2,
566                                 alt_diff * (sin(i*mpi) + sin((j+1)*mpi) - 2) );
567
568                 sgSetVec2( tc, base[0] + layer_scale * i/4,
569                             base[1] + layer_scale * (j+1)/4 );
570
571                 sgSetVec4( color, 1.0f, 1.0f, 1.0f,
572                                 ((j == 3) || (i == 0)) ?
573                                 ((j == 3) && (i == 0)) ? 0.0f : 0.15f : 1.0f );
574                 cl[i]->add( color );
575                 vl[i]->add( vertex );
576                 tl[i]->add( tc );
577             }
578
579             sgSetVec3( vertex, layer_span*(i-1)/2, layer_span, 
580                             alt_diff * (sin((i+1)*mpi) - 2) );
581
582             sgSetVec2( tc, base[0] + layer_scale * (i+1)/4,
583                         base[1] + layer_scale );
584
585             sgSetVec4( color, 1.0f, 1.0f, 1.0f, (i == 3) ? 0.0f : 0.15f );
586
587             cl[i]->add( color );
588             vl[i]->add( vertex );
589             tl[i]->add( tc );
590
591             layer[i] = new ssgVtxTable(GL_TRIANGLE_STRIP, vl[i], NULL, tl[i], cl[i]);
592             layer_transform->addKid( layer[i] );
593
594             if ( layer_states[layer_coverage] != NULL ) {
595                 layer[i]->setState( layer_states[layer_coverage] );
596             }
597             state_sel = layer_states[layer_coverage];
598         }
599
600         // force a repaint of the sky colors with arbitrary defaults
601         repaint( color );
602     }
603 }
604
605
606 // repaint the cloud layer colors
607 bool SGCloudLayer::repaint( sgVec3 fog_color ) {
608
609     if ( bump_mapping && enable_bump_mapping ) {
610
611         for ( int i = 0; i < 25; i++ ) {
612             sgCopyVec3( vertices[ i ].color, fog_color );
613         }
614
615     } else {
616         float *color;
617
618         for ( int i = 0; i < 4; i++ ) {
619             for ( int j = 0; j < 10; ++j ) {
620                 color = cl[i]->get( j );
621                 sgCopyVec3( color, fog_color );
622             }
623         }
624     }
625
626     return true;
627 }
628
629
630 // reposition the cloud layer at the specified origin and orientation
631 // lon specifies a rotation about the Z axis
632 // lat specifies a rotation about the new Y axis
633 // spin specifies a rotation about the new Z axis (and orients the
634 // sunrise/set effects
635 bool SGCloudLayer::reposition( sgVec3 p, sgVec3 up, double lon, double lat,
636                                double alt, double dt )
637 {
638     sgMat4 T1, LON, LAT;
639     sgVec3 axis;
640
641     // combine p and asl (meters) to get translation offset
642     sgVec3 asl_offset;
643     sgCopyVec3( asl_offset, up );
644     sgNormalizeVec3( asl_offset );
645     if ( alt <= layer_asl ) {
646         sgScaleVec3( asl_offset, layer_asl );
647     } else {
648         sgScaleVec3( asl_offset, layer_asl + layer_thickness );
649     }
650     // cout << "asl_offset = " << asl_offset[0] << "," << asl_offset[1]
651     //      << "," << asl_offset[2] << endl;
652     sgAddVec3( asl_offset, p );
653     // cout << "  asl_offset = " << asl_offset[0] << "," << asl_offset[1]
654     //      << "," << asl_offset[2] << endl;
655
656     // Translate to zero elevation
657     // Point3D zero_elev = current_view.get_cur_zero_elev();
658     sgMakeTransMat4( T1, asl_offset );
659
660     // printf("  Translated to %.2f %.2f %.2f\n", 
661     //        zero_elev.x, zero_elev.y, zero_elev.z );
662
663     // Rotate to proper orientation
664     // printf("  lon = %.2f  lat = %.2f\n", 
665     //        lon * SGD_RADIANS_TO_DEGREES,
666     //        lat * SGD_RADIANS_TO_DEGREES);
667     sgSetVec3( axis, 0.0, 0.0, 1.0 );
668     sgMakeRotMat4( LON, lon * SGD_RADIANS_TO_DEGREES, axis );
669
670     sgSetVec3( axis, 0.0, 1.0, 0.0 );
671     sgMakeRotMat4( LAT, 90.0 - lat * SGD_RADIANS_TO_DEGREES, axis );
672
673     sgMat4 TRANSFORM;
674
675     sgCopyMat4( TRANSFORM, T1 );
676     sgPreMultMat4( TRANSFORM, LON );
677     sgPreMultMat4( TRANSFORM, LAT );
678
679     sgCoord layerpos;
680     sgSetCoord( &layerpos, TRANSFORM );
681
682     layer_transform->setTransform( &layerpos );
683
684     // now calculate update texture coordinates
685     if ( last_lon < -900 ) {
686         last_lon = lon;
687         last_lat = lat;
688     }
689
690     double sp_dist = speed*dt;
691
692     if ( lon != last_lon || lat != last_lat || sp_dist != 0 ) {
693         Point3D start( last_lon, last_lat, 0.0 );
694         Point3D dest( lon, lat, 0.0 );
695         double course = 0.0, dist = 0.0;
696
697         calc_gc_course_dist( dest, start, &course, &dist );
698         // cout << "course = " << course << ", dist = " << dist << endl;
699
700         // if start and dest are too close together,
701         // calc_gc_course_dist() can return a course of "nan".  If
702         // this happens, lets just use the last known good course.
703         // This is a hack, and it would probably be better to make
704         // calc_gc_course_dist() more robust.
705         if ( isnan(course) ) {
706             course = last_course;
707         } else {
708             last_course = course;
709         }
710
711         // calculate cloud movement due to external forces
712         double ax = 0.0, ay = 0.0, bx = 0.0, by = 0.0;
713
714         if (dist > 0.0) {
715             ax = cos(course) * dist;
716             ay = sin(course) * dist;
717         }
718
719         if (sp_dist > 0) {
720             bx = cos(-direction * SGD_DEGREES_TO_RADIANS) * sp_dist;
721             by = sin(-direction * SGD_DEGREES_TO_RADIANS) * sp_dist;
722         }
723
724
725         double xoff = (ax + bx) / (2 * scale);
726         double yoff = (ay + by) / (2 * scale);
727
728         const float layer_scale = layer_span / scale;
729
730         // cout << "xoff = " << xoff << ", yoff = " << yoff << endl;
731
732         float *base;
733         if ( bump_mapping && enable_bump_mapping ) {
734             base = vertices[12].texCoord;
735         } else {
736             base = tl[0]->get( 0 );
737         }
738         base[0] += xoff;
739
740         // the while loops can lead to *long* pauses if base[0] comes
741         // with a bogus value.
742         // while ( base[0] > 1.0 ) { base[0] -= 1.0; }
743         // while ( base[0] < 0.0 ) { base[0] += 1.0; }
744         if ( base[0] > -10.0 && base[0] < 10.0 ) {
745             base[0] -= (int)base[0];
746         } else {
747             SG_LOG(SG_ASTRO, SG_DEBUG,
748                 "Error: base = " << base[0] << "," << base[1] <<
749                 " course = " << course << " dist = " << dist );
750             base[0] = 0.0;
751         }
752
753         base[1] += yoff;
754         // the while loops can lead to *long* pauses if base[0] comes
755         // with a bogus value.
756         // while ( base[1] > 1.0 ) { base[1] -= 1.0; }
757         // while ( base[1] < 0.0 ) { base[1] += 1.0; }
758         if ( base[1] > -10.0 && base[1] < 10.0 ) {
759             base[1] -= (int)base[1];
760         } else {
761             SG_LOG(SG_ASTRO, SG_ALERT,
762                     "Error: base = " << base[0] << "," << base[1] <<
763                     " course = " << course << " dist = " << dist );
764             base[1] = 0.0;
765         }
766
767         if ( bump_mapping && enable_bump_mapping ) {
768
769             for ( int i = -2; i <= 2; i++ ) {
770                 for ( int j = -2; j <= 2; j++ ) {
771                     if ( i == 0 && j == 0 )
772                         continue; // Already done on base
773                     CloudVertex &v1 = vertices[ (i+2)*5 + (j+2) ];
774                     sgSetVec2( v1.texCoord,
775                             base[0] + layer_scale * i * 0.25,
776                             base[1] + layer_scale * j * 0.25 );
777                 }
778             }
779
780         } else {
781                 // cout << "base = " << base[0] << "," << base[1] << endl;
782
783             float *tc;
784             for (int i = 0; i < 4; i++) {
785                 tc = tl[i]->get( 0 );
786                 sgSetVec2( tc, base[0] + layer_scale * i/4, base[1] );
787                 
788                 for (int j = 0; j < 4; j++)
789                 {
790                     tc = tl[i]->get( j*2+1 );
791                     sgSetVec2( tc, base[0] + layer_scale * (i+1)/4,
792                                 base[1] + layer_scale * j/4 );
793         
794                     tc = tl[i]->get( (j+1)*2 );
795                     sgSetVec2( tc, base[0] + layer_scale * i/4,
796                                 base[1] + layer_scale * (j+1)/4 );
797                 }
798         
799                 tc = tl[i]->get( 9 );
800                 sgSetVec2( tc, base[0] + layer_scale * (i+1)/4,
801                             base[1] + layer_scale );
802             }
803         }
804
805         last_lon = lon;
806         last_lat = lat;
807     }
808
809     return true;
810 }
811
812
813 void SGCloudLayer::draw( bool top ) {
814     if ( layer_coverage != SG_CLOUD_CLEAR ) {
815
816         if ( bump_mapping && enable_bump_mapping ) {
817
818             sgMat4 modelview,
819                    tmp,
820                    transform;
821             ssgGetModelviewMatrix( modelview );
822             layer_transform->getTransform( transform );
823
824             sgInvertMat4( tmp, transform );
825
826             sgPostMultMat4( transform, modelview );
827             ssgLoadModelviewMatrix( transform );
828
829             sgVec3 lightVec;
830             ssgGetLight( 0 )->getPosition( lightVec );
831             sgNegateVec3( lightVec );
832             sgXformVec3( lightVec, tmp );
833
834             for ( int i = 0; i < 25; i++ ) {
835                 CloudVertex &v = vertices[ i ];
836                 sgSetVec3( v.tangentSpLight,
837                            sgScalarProductVec3( v.sTangent, lightVec ),
838                            sgScalarProductVec3( v.tTangent, lightVec ),
839                            sgScalarProductVec3( v.normal, lightVec ) );
840             }
841
842             ssgTexture *decal = color_map[ layer_coverage ][ top ? 1 : 0 ];
843             if ( top && decal == 0 ) {
844                 decal = color_map[ layer_coverage ][ 0 ];
845             }
846             ssgTexture *normal = normal_map[ layer_coverage ][ top ? 1 : 0 ];
847             if ( top && normal == 0 ) {
848                 normal = normal_map[ layer_coverage ][ 0 ];
849             }
850
851             glDisable( GL_LIGHTING );
852             glDisable( GL_CULL_FACE );
853             glEnable( GL_ALPHA_TEST );
854             glAlphaFunc ( GL_GREATER, 0.1 ) ;
855             glEnable( GL_BLEND ); 
856             glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
857
858             glPolygonMode( GL_FILL, GL_FRONT_AND_BACK );
859             glShadeModel( GL_SMOOTH );
860             glEnable( GL_COLOR_MATERIAL ); 
861             sgVec4 color;
862             sgSetVec4( color, 0.05, 0.05, 0.05, 0.0 );
863             glMaterialfv( GL_FRONT_AND_BACK, GL_EMISSION, color );
864             sgSetVec4( color, 0.8, 0.8, 0.8, 0.0 );
865             glMaterialfv( GL_FRONT_AND_BACK, GL_AMBIENT, color );
866             sgSetVec4( color, 0.5, 0.5, 0.5, 0.0 );
867             glMaterialfv( GL_FRONT_AND_BACK, GL_DIFFUSE, color );
868             sgSetVec4( color, 1.0, 1.0, 1.0, 1.0 );
869             glMaterialfv( GL_FRONT_AND_BACK, GL_SPECULAR, color );
870
871             glActiveTexturePtr( GL_TEXTURE0_ARB );
872             glBindTexture( GL_TEXTURE_2D, normal->getHandle() );
873             glEnable( GL_TEXTURE_2D );
874
875             //Bind normalisation cube map to texture unit 1
876             glActiveTexturePtr( GL_TEXTURE1_ARB );
877             glBindTexture( GL_TEXTURE_CUBE_MAP_ARB, normalization_cube_map );
878             glEnable( GL_TEXTURE_CUBE_MAP_ARB );
879             glActiveTexturePtr( GL_TEXTURE0_ARB );
880
881             //Set vertex arrays for cloud
882             glVertexPointer( 3, GL_FLOAT, sizeof(CloudVertex), &vertices[0].position );
883             glEnableClientState( GL_VERTEX_ARRAY );
884
885             if ( nb_texture_unit >= 3 ) {
886                 glColorPointer( 4, GL_FLOAT, sizeof(CloudVertex), &vertices[0].color );
887                 glEnableClientState( GL_COLOR_ARRAY );
888             }
889
890             //Send texture coords for normal map to unit 0
891             glTexCoordPointer( 2, GL_FLOAT, sizeof(CloudVertex), &vertices[0].texCoord );
892             glEnableClientState( GL_TEXTURE_COORD_ARRAY );
893
894             //Send tangent space light vectors for normalisation to unit 1
895             glClientActiveTexturePtr( GL_TEXTURE1_ARB );
896             glTexCoordPointer( 3, GL_FLOAT, sizeof(CloudVertex), &vertices[0].tangentSpLight );
897             glEnableClientState( GL_TEXTURE_COORD_ARRAY );
898
899             //Set up texture environment to do (tex0 dot tex1)*color
900             glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_ARB );
901             glTexEnvi( GL_TEXTURE_ENV, GL_SOURCE0_RGB_ARB, GL_TEXTURE );
902             glTexEnvi( GL_TEXTURE_ENV, GL_COMBINE_RGB_ARB, GL_REPLACE );
903             glTexEnvi( GL_TEXTURE_ENV, GL_SOURCE0_ALPHA_ARB, GL_TEXTURE );
904             glTexEnvi( GL_TEXTURE_ENV, GL_COMBINE_ALPHA_ARB, GL_REPLACE );
905
906             glActiveTexturePtr( GL_TEXTURE1_ARB );
907
908             glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_ARB );
909             glTexEnvi( GL_TEXTURE_ENV, GL_SOURCE0_RGB_ARB, GL_TEXTURE );
910             glTexEnvi( GL_TEXTURE_ENV, GL_COMBINE_RGB_ARB, GL_DOT3_RGB_ARB );
911             glTexEnvi( GL_TEXTURE_ENV, GL_SOURCE1_RGB_ARB, GL_PREVIOUS_ARB );
912
913             if ( nb_texture_unit >= 3 ) {
914                 glActiveTexturePtr( GL_TEXTURE2_ARB );
915                 glBindTexture( GL_TEXTURE_2D, decal->getHandle() );
916
917                 glClientActiveTexturePtr( GL_TEXTURE2_ARB );
918                 glTexCoordPointer( 2, GL_FLOAT, sizeof(CloudVertex), &vertices[0].texCoord );
919                 glEnableClientState( GL_TEXTURE_COORD_ARRAY );
920
921                 sgVec4 factors;
922                 if ( top || layer_coverage != SG_CLOUD_OVERCAST ) {
923                     sgSetVec4( factors, 0.5f, 0.5f, 0.3f, 1.0f );
924                 } else {
925                     sgSetVec4( factors, 0.1f, 0.1f, 0.0f, 1.0f );
926                 }
927                 glTexEnvfv( GL_TEXTURE_ENV, GL_TEXTURE_ENV_COLOR, factors );
928
929                 glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_ARB );
930                 glTexEnvi( GL_TEXTURE_ENV, GL_COMBINE_RGB_ARB, GL_INTERPOLATE_ARB );
931                 glTexEnvi( GL_TEXTURE_ENV, GL_SOURCE0_RGB_ARB, GL_TEXTURE );
932                 glTexEnvi( GL_TEXTURE_ENV, GL_SOURCE1_RGB_ARB, GL_PREVIOUS_ARB );
933                 glTexEnvi( GL_TEXTURE_ENV, GL_SOURCE2_RGB_ARB, GL_CONSTANT_ARB );
934
935                 glClientActiveTexturePtr( GL_TEXTURE0_ARB );
936                 glActiveTexturePtr( GL_TEXTURE0_ARB );
937
938                 //Draw cloud layer
939                 glDrawElements( GL_TRIANGLE_STRIP, 10, GL_UNSIGNED_INT, &indices[0] );
940                 glDrawElements( GL_TRIANGLE_STRIP, 10, GL_UNSIGNED_INT, &indices[10] );
941                 glDrawElements( GL_TRIANGLE_STRIP, 10, GL_UNSIGNED_INT, &indices[20] );
942                 glDrawElements( GL_TRIANGLE_STRIP, 10, GL_UNSIGNED_INT, &indices[30] );
943
944                 glDisable( GL_TEXTURE_2D );
945                 glActiveTexturePtr( GL_TEXTURE1_ARB );
946                 glDisable( GL_TEXTURE_CUBE_MAP_ARB );
947                 glActiveTexturePtr( GL_TEXTURE2_ARB );
948                 glDisable( GL_TEXTURE_2D );
949                 glActiveTexturePtr( GL_TEXTURE0_ARB );
950
951                 glDisableClientState( GL_TEXTURE_COORD_ARRAY );
952                 glClientActiveTexturePtr( GL_TEXTURE1_ARB );
953                 glDisableClientState( GL_TEXTURE_COORD_ARRAY );
954                 glClientActiveTexturePtr( GL_TEXTURE2_ARB );
955                 glDisableClientState( GL_TEXTURE_COORD_ARRAY );
956                 glClientActiveTexturePtr( GL_TEXTURE0_ARB );
957
958                 glDisableClientState( GL_COLOR_ARRAY );
959
960             } else {
961                 glClientActiveTexturePtr( GL_TEXTURE0_ARB );
962                 glActiveTexturePtr( GL_TEXTURE0_ARB );
963
964                 //Draw cloud layer
965                 glDrawElements( GL_TRIANGLE_STRIP, 10, GL_UNSIGNED_INT, &indices[0] );
966                 glDrawElements( GL_TRIANGLE_STRIP, 10, GL_UNSIGNED_INT, &indices[10] );
967                 glDrawElements( GL_TRIANGLE_STRIP, 10, GL_UNSIGNED_INT, &indices[20] );
968                 glDrawElements( GL_TRIANGLE_STRIP, 10, GL_UNSIGNED_INT, &indices[30] );
969
970
971                 //Disable textures
972                 glDisable( GL_TEXTURE_2D );
973
974                 glActiveTexturePtr( GL_TEXTURE1_ARB );
975                 glDisable( GL_TEXTURE_CUBE_MAP_ARB );
976                 glActiveTexturePtr( GL_TEXTURE0_ARB );
977
978                 //disable vertex arrays
979                 glDisableClientState( GL_VERTEX_ARRAY );
980
981                 glDisableClientState( GL_TEXTURE_COORD_ARRAY );
982                 glClientActiveTexturePtr( GL_TEXTURE1_ARB );
983                 glDisableClientState( GL_TEXTURE_COORD_ARRAY );
984                 glClientActiveTexturePtr( GL_TEXTURE0_ARB );
985
986                 //Return to standard modulate texenv
987                 glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE );
988
989                 glDepthFunc(GL_LEQUAL);
990                 //Enable multiplicative blending
991                 glBlendFunc( GL_DST_COLOR, GL_ZERO );
992
993                 //Perform a second pass to color the torus
994                 //Bind decal texture
995                 glBindTexture( GL_TEXTURE_2D, decal->getHandle() );
996                 glEnable(GL_TEXTURE_2D);
997
998                 //Set vertex arrays for torus
999                 glVertexPointer( 3, GL_FLOAT, sizeof(CloudVertex), &vertices[0].position );
1000                 glEnableClientState( GL_VERTEX_ARRAY );
1001
1002                 //glColorPointer( 4, GL_FLOAT, sizeof(CloudVertex), &vertices[0].color );
1003                 //glEnableClientState( GL_COLOR_ARRAY );
1004
1005                 glNormalPointer( GL_FLOAT, sizeof(CloudVertex), &vertices[0].normal );
1006                 glEnableClientState( GL_NORMAL_ARRAY );
1007
1008                 glTexCoordPointer( 2, GL_FLOAT, sizeof(CloudVertex), &vertices[0].texCoord );
1009                 glEnableClientState( GL_TEXTURE_COORD_ARRAY );
1010
1011                 //Draw cloud layer
1012                 glDrawElements( GL_TRIANGLE_STRIP, 10, GL_UNSIGNED_INT, &indices[0] );
1013                 glDrawElements( GL_TRIANGLE_STRIP, 10, GL_UNSIGNED_INT, &indices[10] );
1014                 glDrawElements( GL_TRIANGLE_STRIP, 10, GL_UNSIGNED_INT, &indices[20] );
1015                 glDrawElements( GL_TRIANGLE_STRIP, 10, GL_UNSIGNED_INT, &indices[30] );
1016
1017                 glDisableClientState( GL_TEXTURE_COORD_ARRAY );
1018             }
1019             //Disable texture
1020             glDisable( GL_TEXTURE_2D );
1021
1022             glDisableClientState( GL_VERTEX_ARRAY );
1023             glDisableClientState( GL_NORMAL_ARRAY );
1024
1025             glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE );
1026
1027             glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
1028             glEnable( GL_LIGHTING );
1029             glEnable( GL_CULL_FACE );
1030             glDepthFunc(GL_LESS);
1031
1032             ssgLoadModelviewMatrix( modelview );
1033
1034         } else {
1035             state_sel->selectStep( top ? 1 : 0 );
1036             ssgCullAndDraw( layer_root );
1037         }
1038     }
1039 }
1040
1041
1042 // make an ssgSimpleState for a cloud layer given the named texture
1043 ssgSimpleState *sgCloudMakeState( const string &path ) {
1044     ssgSimpleState *state = new ssgSimpleState();
1045
1046     SG_LOG(SG_ASTRO, SG_INFO, " texture = ");
1047
1048     state->setTexture( (char *)path.c_str() );
1049     state->setShadeModel( GL_SMOOTH );
1050     state->disable( GL_LIGHTING );
1051     state->disable( GL_CULL_FACE );
1052     state->enable( GL_TEXTURE_2D );
1053     state->enable( GL_COLOR_MATERIAL );
1054     state->setColourMaterial( GL_AMBIENT_AND_DIFFUSE );
1055     state->setMaterial( GL_EMISSION, 0.05, 0.05, 0.05, 0.0 );
1056     state->setMaterial( GL_AMBIENT, 0.2, 0.2, 0.2, 0.0 );
1057     state->setMaterial( GL_DIFFUSE, 0.5, 0.5, 0.5, 0.0 );
1058     state->setMaterial( GL_SPECULAR, 0.0, 0.0, 0.0, 0.0 );
1059     state->enable( GL_BLEND );
1060     state->enable( GL_ALPHA_TEST );
1061     state->setAlphaClamp( 0.01 );
1062
1063     return state;
1064 }