]> git.mxchange.org Git - simgear.git/blob - simgear/scene/sky/cloud.cxx
Don't reset the random texture base when rebuilding a cloud layer
[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  - http://www.flightgear.org/~curt
6 //
7 // This library is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU Library General Public
9 // License as published by the Free Software Foundation; either
10 // version 2 of the License, or (at your option) any later version.
11 //
12 // This library 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 // $Id$
22
23 #ifdef HAVE_CONFIG_H
24 #  include <simgear_config.h>
25 #endif
26
27 #include <simgear/compiler.h>
28
29 #include <sstream>
30
31 #include <math.h>
32
33 #include <osg/AlphaFunc>
34 #include <osg/BlendFunc>
35 #include <osg/Geode>
36 #include <osg/Geometry>
37 #include <osg/Material>
38 #include <osg/ShadeModel>
39 #include <osg/TexEnv>
40 #include <osg/Texture2D>
41 #include <osg/TextureCubeMap>
42 #include <osg/TexMat>
43
44 #include <simgear/math/sg_random.h>
45 #include <simgear/debug/logstream.hxx>
46 #include <simgear/scene/model/model.hxx>
47 #include <simgear/math/polar3d.hxx>
48
49 #include "newcloud.hxx"
50 #include "cloudfield.hxx"
51 #include "cloud.hxx"
52
53 // #if defined(__MINGW32__)
54 // #define isnan(x) _isnan(x)
55 // #endif
56
57 // #if defined (__FreeBSD__)
58 // #  if __FreeBSD_version < 500000
59 //      extern "C" {
60 //        inline int isnan(double r) { return !(r <= 0 || r >= 0); }
61 //      }
62 // #  endif
63 // #endif
64
65 #if defined (__CYGWIN__)
66 #include <ieeefp.h>
67 #endif
68
69 static osg::ref_ptr<osg::StateSet> layer_states[SGCloudLayer::SG_MAX_CLOUD_COVERAGES];
70 static osg::ref_ptr<osg::StateSet> layer_states2[SGCloudLayer::SG_MAX_CLOUD_COVERAGES];
71 static osg::ref_ptr<osg::TextureCubeMap> cubeMap;
72 static bool state_initialized = false;
73 static bool bump_mapping = false;
74
75 bool SGCloudLayer::enable_bump_mapping = false;
76
77 // make an StateSet for a cloud layer given the named texture
78 static osg::StateSet*
79 SGMakeState(const SGPath &path, const char* colorTexture,
80             const char* normalTexture)
81 {
82     osg::StateSet *stateSet = new osg::StateSet;
83
84     SGPath colorPath(path);
85     colorPath.append(colorTexture);
86     stateSet->setTextureAttribute(0, SGLoadTexture2D(colorPath));
87     stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::ON);
88
89     osg::TexEnv* texEnv = new osg::TexEnv;
90     texEnv->setMode(osg::TexEnv::MODULATE);
91     stateSet->setTextureAttribute(0, texEnv);
92  
93     osg::ShadeModel* shadeModel = new osg::ShadeModel;
94     // FIXME: TRUE??
95     shadeModel->setMode(osg::ShadeModel::SMOOTH);
96     stateSet->setAttributeAndModes(shadeModel);
97
98     stateSet->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
99     stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
100
101 //     osg::AlphaFunc* alphaFunc = new osg::AlphaFunc;
102 //     alphaFunc->setFunction(osg::AlphaFunc::GREATER);
103 //     alphaFunc->setReferenceValue(0.01);
104 //     stateSet->setAttribute(alphaFunc);
105 //     stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::ON);
106     stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::OFF);
107
108     osg::BlendFunc* blendFunc = new osg::BlendFunc;
109     blendFunc->setSource(osg::BlendFunc::SRC_ALPHA);
110     blendFunc->setDestination(osg::BlendFunc::ONE_MINUS_SRC_ALPHA);
111     stateSet->setAttribute(blendFunc);
112     stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
113
114 //     osg::Material* material = new osg::Material;
115 //     material->setColorMode(osg::Material::AMBIENT_AND_DIFFUSE);
116 //     material->setEmission(osg::Material::FRONT_AND_BACK,
117 //                           osg::Vec4(0.05, 0.05, 0.05, 0));
118 //     material->setSpecular(osg::Material::FRONT_AND_BACK,
119 //                           osg::Vec4(0, 0, 0, 1));
120 //     stateSet->setAttribute(material);
121
122     stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
123
124     // OSGFIXME: invented by me ...
125 //     stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
126 //     stateSet->setMode(GL_LIGHTING, osg::StateAttribute::ON);
127
128 //     stateSet->setMode(GL_LIGHT0, osg::StateAttribute::OFF);
129
130     // If the normal texture is given prepare a bumpmapping enabled state
131 //     if (normalTexture) {
132 //       SGPath normalPath(path);
133 //       normalPath.append(normalTexture);
134 //       stateSet->setTextureAttribute(2, SGLoadTexture2D(normalPath));
135 //       stateSet->setTextureMode(2, GL_TEXTURE_2D, osg::StateAttribute::ON);
136 //     }
137
138     return stateSet;
139 }
140
141 // Constructor
142 SGCloudLayer::SGCloudLayer( const string &tex_path ) :
143     layer_root(new osg::Switch),
144     group_top(new osg::Group),
145     group_bottom(new osg::Group),
146     layer_transform(new osg::MatrixTransform),
147     cloud_alpha(1.0),
148     texture_path(tex_path),
149     layer_span(0.0),
150     layer_asl(0.0),
151     layer_thickness(0.0),
152     layer_transition(0.0),
153     layer_coverage(SG_CLOUD_CLEAR),
154     scale(4000.0),
155     speed(0.0),
156     direction(0.0),
157     last_lon(0.0),
158     last_lat(0.0)
159 {
160   layer_root->addChild(group_bottom.get());
161   layer_root->addChild(group_top.get());
162   // Force the cloud layers into recursive bins of bin 4.
163   osg::StateSet *rootSet = layer_root->getOrCreateStateSet();
164   rootSet->setRenderBinDetails(4, "RenderBin");
165   rootSet->setTextureAttribute(0, new osg::TexMat());
166   base = osg::Vec2(sg_random(), sg_random());
167
168   group_top->addChild(layer_transform.get());
169   group_bottom->addChild(layer_transform.get());
170
171   layer3D = new SGCloudField;
172   rebuild();
173 }
174
175 // Destructor
176 SGCloudLayer::~SGCloudLayer()
177 {
178   delete layer3D;
179 }
180
181 float
182 SGCloudLayer::getSpan_m () const
183 {
184     return layer_span;
185 }
186
187 void
188 SGCloudLayer::setSpan_m (float span_m)
189 {
190     if (span_m != layer_span) {
191         layer_span = span_m;
192         rebuild();
193     }
194 }
195
196 float
197 SGCloudLayer::getElevation_m () const
198 {
199     return layer_asl;
200 }
201
202 void
203 SGCloudLayer::setElevation_m (float elevation_m, bool set_span)
204 {
205     layer_asl = elevation_m;
206
207     if (set_span) {
208         if (elevation_m > 4000)
209             setSpan_m(  elevation_m * 10 );
210         else
211             setSpan_m( 40000 );
212     }
213 }
214
215 float
216 SGCloudLayer::getThickness_m () const
217 {
218     return layer_thickness;
219 }
220
221 void
222 SGCloudLayer::setThickness_m (float thickness_m)
223 {
224     layer_thickness = thickness_m;
225 }
226
227 float
228 SGCloudLayer::getTransition_m () const
229 {
230     return layer_transition;
231 }
232
233 void
234 SGCloudLayer::setTransition_m (float transition_m)
235 {
236     layer_transition = transition_m;
237 }
238
239 SGCloudLayer::Coverage
240 SGCloudLayer::getCoverage () const
241 {
242     return layer_coverage;
243 }
244
245 void
246 SGCloudLayer::setCoverage (Coverage coverage)
247 {
248     if (coverage != layer_coverage) {
249         layer_coverage = coverage;
250         rebuild();
251     }
252 }
253
254 void
255 SGCloudLayer::setTextureOffset(const osg::Vec2& offset)
256 {
257     osg::StateAttribute* attr = layer_root->getStateSet()
258         ->getTextureAttribute(0, osg::StateAttribute::TEXMAT);
259     osg::TexMat* texMat = dynamic_cast<osg::TexMat*>(attr);
260     if (!texMat)
261         return;
262     texMat->setMatrix(osg::Matrix::translate(offset[0], offset[1], 0.0));
263 }
264
265 // build the cloud object
266 void
267 SGCloudLayer::rebuild()
268 {
269     // Initialize states and sizes if necessary.
270     if ( !state_initialized ) { 
271         state_initialized = true;
272
273         SG_LOG(SG_ASTRO, SG_INFO, "initializing cloud layers");
274
275         osg::Texture::Extensions* extensions;
276         extensions = osg::Texture::getExtensions(0, true);
277         // OSGFIXME
278         bump_mapping = extensions->isMultiTexturingSupported() &&
279           (2 <= extensions->numTextureUnits()) &&
280           SGIsOpenGLExtensionSupported("GL_ARB_texture_env_combine") &&
281           SGIsOpenGLExtensionSupported("GL_ARB_texture_env_dot3");
282
283         osg::TextureCubeMap::Extensions* extensions2;
284         extensions2 = osg::TextureCubeMap::getExtensions(0, true);
285         bump_mapping = bump_mapping && extensions2->isCubeMapSupported();
286
287         // This bump mapping code was inspired by the tutorial available at 
288         // http://www.paulsprojects.net/tutorials/simplebump/simplebump.html
289         // and a NVidia white paper 
290         //  http://developer.nvidia.com/object/bumpmappingwithregistercombiners.html
291         // The normal map textures were generated by the normal map Gimp plugin :
292         //  http://nifelheim.dyndns.org/~cocidius/normalmap/
293         //
294         cubeMap = new osg::TextureCubeMap;
295         cubeMap->setFilter(osg::Texture::MIN_FILTER, osg::Texture::LINEAR);
296         cubeMap->setFilter(osg::Texture::MAG_FILTER, osg::Texture::LINEAR);
297         cubeMap->setWrap(osg::Texture::WRAP_S, osg::Texture::CLAMP_TO_EDGE);
298         cubeMap->setWrap(osg::Texture::WRAP_T, osg::Texture::CLAMP_TO_EDGE);
299         cubeMap->setWrap(osg::Texture::WRAP_R, osg::Texture::CLAMP_TO_EDGE);
300
301         const int size = 32;
302         const float half_size = 16.0f;
303         const float offset = 0.5f;
304         osg::Vec3 zero_normal(0.5, 0.5, 0.5);
305
306         osg::Image* image = new osg::Image;
307         image->allocateImage(size, size, 1, GL_RGB, GL_UNSIGNED_BYTE);
308         unsigned char *ptr = image->data(0, 0);
309         for (int j = 0; j < size; j++ ) {
310           for (int i = 0; i < size; i++ ) {
311             osg::Vec3 tmp(half_size, -( j + offset - half_size ),
312                           -( i + offset - half_size ) );
313             tmp.normalize();
314             tmp = tmp*0.5 - zero_normal;
315             
316             *ptr++ = (unsigned char)( tmp[ 0 ] * 255 );
317             *ptr++ = (unsigned char)( tmp[ 1 ] * 255 );
318             *ptr++ = (unsigned char)( tmp[ 2 ] * 255 );
319           }
320         }
321         cubeMap->setImage(osg::TextureCubeMap::POSITIVE_X, image);
322
323         image = new osg::Image;
324         image->allocateImage(size, size, 1, GL_RGB, GL_UNSIGNED_BYTE);
325         ptr = image->data(0, 0);
326         for (int j = 0; j < size; j++ ) {
327           for (int i = 0; i < size; i++ ) {
328             osg::Vec3 tmp(-half_size, -( j + offset - half_size ),
329                           ( i + offset - half_size ) );
330             tmp.normalize();
331             tmp = tmp*0.5 - zero_normal;
332             
333             *ptr++ = (unsigned char)( tmp[ 0 ] * 255 );
334             *ptr++ = (unsigned char)( tmp[ 1 ] * 255 );
335             *ptr++ = (unsigned char)( tmp[ 2 ] * 255 );
336           }
337         }
338         cubeMap->setImage(osg::TextureCubeMap::NEGATIVE_X, image);
339
340         image = new osg::Image;
341         image->allocateImage(size, size, 1, GL_RGB, GL_UNSIGNED_BYTE);
342         ptr = image->data(0, 0);
343         for (int j = 0; j < size; j++ ) {
344           for (int i = 0; i < size; i++ ) {
345             osg::Vec3 tmp(( i + offset - half_size ), half_size,
346                           ( j + offset - half_size ) );
347             tmp.normalize();
348             tmp = tmp*0.5 - zero_normal;
349             
350             *ptr++ = (unsigned char)( tmp[ 0 ] * 255 );
351             *ptr++ = (unsigned char)( tmp[ 1 ] * 255 );
352             *ptr++ = (unsigned char)( tmp[ 2 ] * 255 );
353           }
354         }
355         cubeMap->setImage(osg::TextureCubeMap::POSITIVE_Y, image);
356
357         image = new osg::Image;
358         image->allocateImage(size, size, 1, GL_RGB, GL_UNSIGNED_BYTE);
359         ptr = image->data(0, 0);
360         for (int j = 0; j < size; j++ ) {
361           for (int i = 0; i < size; i++ ) {
362             osg::Vec3 tmp(( i + offset - half_size ), -half_size,
363                           -( j + offset - half_size ) );
364             tmp.normalize();
365             tmp = tmp*0.5 - zero_normal;
366
367             *ptr++ = (unsigned char)( tmp[ 0 ] * 255 );
368             *ptr++ = (unsigned char)( tmp[ 1 ] * 255 );
369             *ptr++ = (unsigned char)( tmp[ 2 ] * 255 );
370           }
371         }
372         cubeMap->setImage(osg::TextureCubeMap::NEGATIVE_Y, image);
373
374         image = new osg::Image;
375         image->allocateImage(size, size, 1, GL_RGB, GL_UNSIGNED_BYTE);
376         ptr = image->data(0, 0);
377         for (int j = 0; j < size; j++ ) {
378           for (int i = 0; i < size; i++ ) {
379             osg::Vec3 tmp(( i + offset - half_size ),
380                           -( j + offset - half_size ), half_size );
381             tmp.normalize();
382             tmp = tmp*0.5 - zero_normal;
383             
384             *ptr++ = (unsigned char)( tmp[ 0 ] * 255 );
385             *ptr++ = (unsigned char)( tmp[ 1 ] * 255 );
386             *ptr++ = (unsigned char)( tmp[ 2 ] * 255 );
387           }
388         }
389         cubeMap->setImage(osg::TextureCubeMap::POSITIVE_Z, image);
390
391         image = new osg::Image;
392         image->allocateImage(size, size, 1, GL_RGB, GL_UNSIGNED_BYTE);
393         ptr = image->data(0, 0);
394         for (int j = 0; j < size; j++ ) {
395           for (int i = 0; i < size; i++ ) {
396             osg::Vec3 tmp(-( i + offset - half_size ),
397                           -( j + offset - half_size ), -half_size );
398             tmp.normalize();
399             tmp = tmp*0.5 - zero_normal;
400             *ptr++ = (unsigned char)( tmp[ 0 ] * 255 );
401             *ptr++ = (unsigned char)( tmp[ 1 ] * 255 );
402             *ptr++ = (unsigned char)( tmp[ 2 ] * 255 );
403           }
404         }
405         cubeMap->setImage(osg::TextureCubeMap::NEGATIVE_Z, image);
406
407         osg::StateSet* state;
408         state = SGMakeState(texture_path, "overcast.rgb", "overcast_n.rgb");
409         layer_states[SG_CLOUD_OVERCAST] = state;
410         state = SGMakeState(texture_path, "overcast_top.rgb", "overcast_top_n.rgb");
411         layer_states2[SG_CLOUD_OVERCAST] = state;
412         
413         state = SGMakeState(texture_path, "broken.rgba", "broken_n.rgb");
414         layer_states[SG_CLOUD_BROKEN] = state;
415         layer_states2[SG_CLOUD_BROKEN] = state;
416         
417         state = SGMakeState(texture_path, "scattered.rgba", "scattered_n.rgb");
418         layer_states[SG_CLOUD_SCATTERED] = state;
419         layer_states2[SG_CLOUD_SCATTERED] = state;
420         
421         state = SGMakeState(texture_path, "few.rgba", "few_n.rgb");
422         layer_states[SG_CLOUD_FEW] = state;
423         layer_states2[SG_CLOUD_FEW] = state;
424         
425         state = SGMakeState(texture_path, "cirrus.rgba", "cirrus_n.rgb");
426         layer_states[SG_CLOUD_CIRRUS] = state;
427         layer_states2[SG_CLOUD_CIRRUS] = state;
428         
429         layer_states[SG_CLOUD_CLEAR] = 0;
430         layer_states2[SG_CLOUD_CLEAR] = 0;
431
432       // OSGFIXME
433 //              SGNewCloud::loadTextures(texture_path.str());
434 //              layer3D->buildTestLayer();
435     }
436
437     scale = 4000.0;
438     last_lon = last_lat = -999.0f;
439
440     setTextureOffset(base);
441     // build the cloud layer
442     const float layer_scale = layer_span / scale;
443     const float mpi = SG_PI/4;
444     
445     // caclculate the difference between a flat-earth model and 
446     // a round earth model given the span and altutude ASL of
447     // the cloud layer. This is the difference in altitude between
448     // the top of the inverted bowl and the edge of the bowl.
449     // const float alt_diff = layer_asl * 0.8;
450     const float layer_to_core = (SG_EARTH_RAD * 1000 + layer_asl);
451     const float layer_angle = 0.5*layer_span / layer_to_core; // The angle is half the span
452     const float border_to_core = layer_to_core * cos(layer_angle);
453     const float alt_diff = layer_to_core - border_to_core;
454     
455     for (int i = 0; i < 4; i++) {
456       if ( layer[i] != NULL ) {
457         layer_transform->removeChild(layer[i].get()); // automatic delete
458       }
459       
460       vl[i] = new osg::Vec3Array;
461       cl[i] = new osg::Vec4Array;
462       tl[i] = new osg::Vec2Array;
463       
464       
465       osg::Vec3 vertex(layer_span*(i-2)/2, -layer_span,
466                        alt_diff * (sin(i*mpi) - 2));
467       osg::Vec2 tc(layer_scale * i/4, 0.0f);
468       osg::Vec4 color(1.0f, 1.0f, 1.0f, (i == 0) ? 0.0f : 0.15f);
469       
470       cl[i]->push_back(color);
471       vl[i]->push_back(vertex);
472       tl[i]->push_back(tc);
473       
474       for (int j = 0; j < 4; j++) {
475         vertex = osg::Vec3(layer_span*(i-1)/2, layer_span*(j-2)/2,
476                            alt_diff * (sin((i+1)*mpi) + sin(j*mpi) - 2));
477         tc = osg::Vec2(layer_scale * (i+1)/4, layer_scale * j/4);
478         color = osg::Vec4(1.0f, 1.0f, 1.0f,
479                           ( (j == 0) || (i == 3)) ?  
480                           ( (j == 0) && (i == 3)) ? 0.0f : 0.15f : 1.0f );
481         
482         cl[i]->push_back(color);
483         vl[i]->push_back(vertex);
484         tl[i]->push_back(tc);
485         
486         vertex = osg::Vec3(layer_span*(i-2)/2, layer_span*(j-1)/2,
487                            alt_diff * (sin(i*mpi) + sin((j+1)*mpi) - 2) );
488         tc = osg::Vec2(layer_scale * i/4, layer_scale * (j+1)/4 );
489         color = osg::Vec4(1.0f, 1.0f, 1.0f,
490                           ((j == 3) || (i == 0)) ?
491                           ((j == 3) && (i == 0)) ? 0.0f : 0.15f : 1.0f );
492         cl[i]->push_back(color);
493         vl[i]->push_back(vertex);
494         tl[i]->push_back(tc);
495       }
496       
497       vertex = osg::Vec3(layer_span*(i-1)/2, layer_span, 
498                          alt_diff * (sin((i+1)*mpi) - 2));
499       
500       tc = osg::Vec2(layer_scale * (i+1)/4, layer_scale);
501       
502       color = osg::Vec4(1.0f, 1.0f, 1.0f, (i == 3) ? 0.0f : 0.15f );
503       
504       cl[i]->push_back( color );
505       vl[i]->push_back( vertex );
506       tl[i]->push_back( tc );
507       
508       osg::Geometry* geometry = new osg::Geometry;
509       geometry->setUseDisplayList(false);
510       geometry->setVertexArray(vl[i].get());
511       geometry->setNormalBinding(osg::Geometry::BIND_OFF);
512       geometry->setColorArray(cl[i].get());
513       geometry->setColorBinding(osg::Geometry::BIND_PER_VERTEX);
514       geometry->setTexCoordArray(0, tl[i].get());
515       geometry->addPrimitiveSet(new osg::DrawArrays(GL_TRIANGLE_STRIP, 0, vl[i]->size()));
516       layer[i] = new osg::Geode;
517       
518       std::stringstream sstr;
519       sstr << "Cloud Layer (" << i << ")";
520       geometry->setName(sstr.str());
521       layer[i]->setName(sstr.str());
522       layer[i]->addDrawable(geometry);
523       layer_transform->addChild(layer[i].get());
524     }
525     
526     //OSGFIXME: true
527     if ( layer_states[layer_coverage].valid() ) {
528       osg::CopyOp copyOp(osg::CopyOp::DEEP_COPY_ALL
529                          & ~osg::CopyOp::DEEP_COPY_TEXTURES);
530       // render bin will be set in reposition
531       osg::StateSet* stateSet = static_cast<osg::StateSet*>(layer_states2[layer_coverage]->clone(copyOp));
532       stateSet->setDataVariance(osg::Object::DYNAMIC);
533       group_top->setStateSet(stateSet);
534       stateSet = static_cast<osg::StateSet*>(layer_states2[layer_coverage]->clone(copyOp));
535       stateSet->setDataVariance(osg::Object::DYNAMIC);
536       group_bottom->setStateSet(stateSet);
537     }
538 }
539
540 #if 0
541             sgMat4 modelview,
542                    tmp,
543                    transform;
544             ssgGetModelviewMatrix( modelview );
545             layer_transform->getTransform( transform );
546
547             sgTransposeNegateMat4( tmp, transform );
548
549             sgPostMultMat4( transform, modelview );
550             ssgLoadModelviewMatrix( transform );
551
552             sgVec3 lightVec;
553             ssgGetLight( 0 )->getPosition( lightVec );
554             sgNegateVec3( lightVec );
555             sgXformVec3( lightVec, tmp );
556
557             for ( int i = 0; i < 25; i++ ) {
558                 CloudVertex &v = vertices[ i ];
559                 sgSetVec3( v.tangentSpLight,
560                            sgScalarProductVec3( v.sTangent, lightVec ),
561                            sgScalarProductVec3( v.tTangent, lightVec ),
562                            sgScalarProductVec3( v.normal, lightVec ) );
563             }
564
565             ssgTexture *decal = color_map[ layer_coverage ][ top ? 1 : 0 ];
566             if ( top && decal == 0 ) {
567                 decal = color_map[ layer_coverage ][ 0 ];
568             }
569             ssgTexture *normal = normal_map[ layer_coverage ][ top ? 1 : 0 ];
570             if ( top && normal == 0 ) {
571                 normal = normal_map[ layer_coverage ][ 0 ];
572             }
573
574             glDisable( GL_LIGHTING );
575             glDisable( GL_CULL_FACE );
576 //            glDisable( GL_ALPHA_TEST );
577             if ( layer_coverage == SG_CLOUD_FEW ) {
578                 glEnable( GL_ALPHA_TEST );
579                 glAlphaFunc ( GL_GREATER, 0.01 );
580             }
581             glEnable( GL_BLEND ); 
582             glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
583
584             glShadeModel( GL_SMOOTH );
585             glEnable( GL_COLOR_MATERIAL ); 
586             sgVec4 color;
587             float emis = 0.05;
588             if ( 1 ) {
589                 ssgGetLight( 0 )->getColour( GL_DIFFUSE, color );
590                 emis = ( color[0]+color[1]+color[2] ) / 3.0;
591                 if ( emis < 0.05 )
592                     emis = 0.05;
593             }
594             sgSetVec4( color, emis, emis, emis, 0.0 );
595             glMaterialfv( GL_FRONT_AND_BACK, GL_EMISSION, color );
596             sgSetVec4( color, 1.0f, 1.0f, 1.0f, 0.0 );
597             glMaterialfv( GL_FRONT_AND_BACK, GL_AMBIENT, color );
598             sgSetVec4( color, 1.0, 1.0, 1.0, 0.0 );
599             glMaterialfv( GL_FRONT_AND_BACK, GL_DIFFUSE, color );
600             sgSetVec4( color, 0.0, 0.0, 0.0, 0.0 );
601             glMaterialfv( GL_FRONT_AND_BACK, GL_SPECULAR, color );
602
603             glColor4f( 1.0f, 1.0f, 1.0f, 1.0f );
604
605             glActiveTexturePtr( GL_TEXTURE0_ARB );
606             glBindTexture( GL_TEXTURE_2D, normal->getHandle() );
607             glEnable( GL_TEXTURE_2D );
608
609             //Bind normalisation cube map to texture unit 1
610             glActiveTexturePtr( GL_TEXTURE1_ARB );
611             glBindTexture( GL_TEXTURE_CUBE_MAP_ARB, normalization_cube_map );
612             glEnable( GL_TEXTURE_CUBE_MAP_ARB );
613             glActiveTexturePtr( GL_TEXTURE0_ARB );
614
615             //Set vertex arrays for cloud
616             glVertexPointer( 3, GL_FLOAT, sizeof(CloudVertex), &vertices[0].position );
617             glEnableClientState( GL_VERTEX_ARRAY );
618 /*
619             if ( nb_texture_unit >= 3 ) {
620                 glColorPointer( 4, GL_FLOAT, sizeof(CloudVertex), &vertices[0].color );
621                 glEnableClientState( GL_COLOR_ARRAY );
622             }
623 */
624             //Send texture coords for normal map to unit 0
625             glTexCoordPointer( 2, GL_FLOAT, sizeof(CloudVertex), &vertices[0].texCoord );
626             glEnableClientState( GL_TEXTURE_COORD_ARRAY );
627
628             //Send tangent space light vectors for normalisation to unit 1
629             glClientActiveTexturePtr( GL_TEXTURE1_ARB );
630             glTexCoordPointer( 3, GL_FLOAT, sizeof(CloudVertex), &vertices[0].tangentSpLight );
631             glEnableClientState( GL_TEXTURE_COORD_ARRAY );
632
633             //Set up texture environment to do (tex0 dot tex1)*color
634             glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_ARB );
635             glTexEnvi( GL_TEXTURE_ENV, GL_SOURCE0_RGB_ARB, GL_TEXTURE );
636             glTexEnvi( GL_TEXTURE_ENV, GL_COMBINE_RGB_ARB, GL_REPLACE );
637             glTexEnvi( GL_TEXTURE_ENV, GL_SOURCE0_ALPHA_ARB, GL_TEXTURE );
638             glTexEnvi( GL_TEXTURE_ENV, GL_COMBINE_ALPHA_ARB, GL_REPLACE );
639
640 // use TexEnvCombine to add the highlights to the original lighting
641 osg::TexEnvCombine *te = new osg::TexEnvCombine;    
642 te->setSource0_RGB(osg::TexEnvCombine::TEXTURE);
643 te->setCombine_RGB(osg::TexEnvCombine::REPLACE);
644 te->setSource0_Alpha(osg::TexEnvCombine::TEXTURE);
645 te->setCombine_Alpha(osg::TexEnvCombine::REPLACE);
646 ss->setTextureAttributeAndModes(0, te, osg::StateAttribute::OVERRIDE | osg::StateAttribute::ON);
647
648
649             glActiveTexturePtr( GL_TEXTURE1_ARB );
650
651             glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_ARB );
652             glTexEnvi( GL_TEXTURE_ENV, GL_SOURCE0_RGB_ARB, GL_TEXTURE );
653             glTexEnvi( GL_TEXTURE_ENV, GL_COMBINE_RGB_ARB, GL_DOT3_RGB_ARB );
654             glTexEnvi( GL_TEXTURE_ENV, GL_SOURCE1_RGB_ARB, GL_PREVIOUS_ARB );
655             glTexEnvi( GL_TEXTURE_ENV, GL_SOURCE0_ALPHA_ARB, GL_PREVIOUS_ARB );
656             glTexEnvi( GL_TEXTURE_ENV, GL_COMBINE_ALPHA_ARB, GL_REPLACE );
657
658 osg::TexEnvCombine *te = new osg::TexEnvCombine;    
659 te->setSource0_RGB(osg::TexEnvCombine::TEXTURE);
660 te->setCombine_RGB(osg::TexEnvCombine::DOT3_RGB);
661 te->setSource1_RGB(osg::TexEnvCombine::PREVIOUS);
662 te->setSource0_Alpha(osg::TexEnvCombine::PREVIOUS);
663 te->setCombine_Alpha(osg::TexEnvCombine::REPLACE);
664 ss->setTextureAttributeAndModes(0, te, osg::StateAttribute::OVERRIDE | osg::StateAttribute::ON);
665
666
667             if ( nb_texture_unit >= 3 ) {
668                 glActiveTexturePtr( GL_TEXTURE2_ARB );
669                 glBindTexture( GL_TEXTURE_2D, decal->getHandle() );
670
671                 glClientActiveTexturePtr( GL_TEXTURE2_ARB );
672                 glTexCoordPointer( 2, GL_FLOAT, sizeof(CloudVertex), &vertices[0].texCoord );
673                 glEnableClientState( GL_TEXTURE_COORD_ARRAY );
674
675                 glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_ARB );
676                 glTexEnvi( GL_TEXTURE_ENV, GL_COMBINE_RGB_ARB, GL_ADD );
677                 glTexEnvi( GL_TEXTURE_ENV, GL_SOURCE0_RGB_ARB, GL_TEXTURE );
678                 glTexEnvi( GL_TEXTURE_ENV, GL_SOURCE1_RGB_ARB, GL_PREVIOUS_ARB );
679
680                 glClientActiveTexturePtr( GL_TEXTURE0_ARB );
681                 glActiveTexturePtr( GL_TEXTURE0_ARB );
682
683                 //Draw cloud layer
684                 glDrawElements( GL_TRIANGLE_STRIP, 10, GL_UNSIGNED_INT, &indices[0] );
685                 glDrawElements( GL_TRIANGLE_STRIP, 10, GL_UNSIGNED_INT, &indices[10] );
686                 glDrawElements( GL_TRIANGLE_STRIP, 10, GL_UNSIGNED_INT, &indices[20] );
687                 glDrawElements( GL_TRIANGLE_STRIP, 10, GL_UNSIGNED_INT, &indices[30] );
688
689                 glDisable( GL_TEXTURE_2D );
690                 glActiveTexturePtr( GL_TEXTURE1_ARB );
691                 glDisable( GL_TEXTURE_CUBE_MAP_ARB );
692                 glActiveTexturePtr( GL_TEXTURE2_ARB );
693                 glDisable( GL_TEXTURE_2D );
694                 glActiveTexturePtr( GL_TEXTURE0_ARB );
695
696                 glDisableClientState( GL_TEXTURE_COORD_ARRAY );
697                 glClientActiveTexturePtr( GL_TEXTURE1_ARB );
698                 glDisableClientState( GL_TEXTURE_COORD_ARRAY );
699                 glClientActiveTexturePtr( GL_TEXTURE2_ARB );
700                 glDisableClientState( GL_TEXTURE_COORD_ARRAY );
701                 glClientActiveTexturePtr( GL_TEXTURE0_ARB );
702
703                 glDisableClientState( GL_COLOR_ARRAY );
704                 glEnable( GL_LIGHTING );
705
706                 glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE );
707
708             } else {
709                 glClientActiveTexturePtr( GL_TEXTURE0_ARB );
710                 glActiveTexturePtr( GL_TEXTURE0_ARB );
711
712                 //Draw cloud layer
713                 glDrawElements( GL_TRIANGLE_STRIP, 10, GL_UNSIGNED_INT, &indices[0] );
714                 glDrawElements( GL_TRIANGLE_STRIP, 10, GL_UNSIGNED_INT, &indices[10] );
715                 glDrawElements( GL_TRIANGLE_STRIP, 10, GL_UNSIGNED_INT, &indices[20] );
716                 glDrawElements( GL_TRIANGLE_STRIP, 10, GL_UNSIGNED_INT, &indices[30] );
717
718                 //Disable textures
719                 glDisable( GL_TEXTURE_2D );
720
721                 glActiveTexturePtr( GL_TEXTURE1_ARB );
722                 glDisable( GL_TEXTURE_CUBE_MAP_ARB );
723                 glActiveTexturePtr( GL_TEXTURE0_ARB );
724
725                 //disable vertex arrays
726                 glDisableClientState( GL_VERTEX_ARRAY );
727
728                 glDisableClientState( GL_TEXTURE_COORD_ARRAY );
729                 glClientActiveTexturePtr( GL_TEXTURE1_ARB );
730                 glDisableClientState( GL_TEXTURE_COORD_ARRAY );
731                 glClientActiveTexturePtr( GL_TEXTURE0_ARB );
732
733                 //Return to standard modulate texenv
734                 glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE );
735
736                 if ( layer_coverage == SG_CLOUD_OVERCAST ) {
737                     glDepthFunc(GL_LEQUAL);
738
739                     glEnable( GL_LIGHTING );
740                     sgVec4 color;
741                     ssgGetLight( 0 )->getColour( GL_DIFFUSE, color );
742                     float average = ( color[0] + color[1] + color[2] ) / 3.0f;
743                     average = 0.15 + average/10;
744                     sgVec4 averageColor;
745                     sgSetVec4( averageColor, average, average, average, 1.0f );
746                     ssgGetLight( 0 )->setColour( GL_DIFFUSE, averageColor );
747
748                     glBlendColorPtr( average, average, average, 1.0f );
749                     glBlendFunc( GL_ONE_MINUS_CONSTANT_COLOR, GL_CONSTANT_COLOR );
750
751                     //Perform a second pass to color the torus
752                     //Bind decal texture
753                     glBindTexture( GL_TEXTURE_2D, decal->getHandle() );
754                     glEnable(GL_TEXTURE_2D);
755
756                     //Set vertex arrays for torus
757                     glVertexPointer( 3, GL_FLOAT, sizeof(CloudVertex), &vertices[0].position );
758                     glEnableClientState( GL_VERTEX_ARRAY );
759
760                     //glColorPointer( 4, GL_FLOAT, sizeof(CloudVertex), &vertices[0].color );
761                     //glEnableClientState( GL_COLOR_ARRAY );
762
763                     glNormalPointer( GL_FLOAT, sizeof(CloudVertex), &vertices[0].normal );
764                     glEnableClientState( GL_NORMAL_ARRAY );
765
766                     glTexCoordPointer( 2, GL_FLOAT, sizeof(CloudVertex), &vertices[0].texCoord );
767                     glEnableClientState( GL_TEXTURE_COORD_ARRAY );
768
769                     //Draw cloud layer
770                     glDrawElements( GL_TRIANGLE_STRIP, 10, GL_UNSIGNED_INT, &indices[0] );
771                     glDrawElements( GL_TRIANGLE_STRIP, 10, GL_UNSIGNED_INT, &indices[10] );
772                     glDrawElements( GL_TRIANGLE_STRIP, 10, GL_UNSIGNED_INT, &indices[20] );
773                     glDrawElements( GL_TRIANGLE_STRIP, 10, GL_UNSIGNED_INT, &indices[30] );
774
775                     ssgGetLight( 0 )->setColour( GL_DIFFUSE, color );
776
777                     glDisableClientState( GL_TEXTURE_COORD_ARRAY );
778                 }
779             }
780             //Disable texture
781             glDisable( GL_TEXTURE_2D );
782
783             glDisableClientState( GL_VERTEX_ARRAY );
784             glDisableClientState( GL_NORMAL_ARRAY );
785
786             glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
787             glEnable( GL_CULL_FACE );
788             glDepthFunc(GL_LESS);
789
790             ssgLoadModelviewMatrix( modelview );
791 #endif
792
793 // repaint the cloud layer colors
794 bool SGCloudLayer::repaint( const SGVec3f& fog_color ) {
795   for ( int i = 0; i < 4; i++ ) {
796     osg::Vec4 color(fog_color.osg(), 1);
797     color[3] = (i == 0) ? 0.0f : cloud_alpha * 0.15f;
798     (*cl[i])[0] = color;
799     
800     for ( int j = 0; j < 4; ++j ) {
801       color[3] =
802         ((j == 0) || (i == 3)) ?
803         ((j == 0) && (i == 3)) ? 0.0f : cloud_alpha * 0.15f : cloud_alpha;
804       (*cl[i])[(2*j) + 1] = color;
805       
806       color[3] = 
807         ((j == 3) || (i == 0)) ?
808         ((j == 3) && (i == 0)) ? 0.0f : cloud_alpha * 0.15f : cloud_alpha;
809       (*cl[i])[(2*j) + 2] = color;
810     }
811     
812     color[3] = (i == 3) ? 0.0f : cloud_alpha * 0.15f;
813     (*cl[i])[9] = color;
814     
815     cl[i]->dirty();
816   }
817
818   return true;
819 }
820
821 // reposition the cloud layer at the specified origin and orientation
822 // lon specifies a rotation about the Z axis
823 // lat specifies a rotation about the new Y axis
824 // spin specifies a rotation about the new Z axis (and orients the
825 // sunrise/set effects
826 bool SGCloudLayer::reposition( const SGVec3f& p, const SGVec3f& up, double lon, double lat,
827                                double alt, double dt )
828 {
829     // combine p and asl (meters) to get translation offset
830     osg::Vec3 asl_offset(up.osg());
831     asl_offset.normalize();
832     if ( alt <= layer_asl ) {
833         asl_offset *= layer_asl;
834     } else {
835         asl_offset *= layer_asl + layer_thickness;
836     }
837
838     // cout << "asl_offset = " << asl_offset[0] << "," << asl_offset[1]
839     //      << "," << asl_offset[2] << endl;
840     asl_offset += p.osg();
841     // cout << "  asl_offset = " << asl_offset[0] << "," << asl_offset[1]
842     //      << "," << asl_offset[2] << endl;
843
844     osg::Matrix T, LON, LAT;
845     // Translate to zero elevation
846     // Point3D zero_elev = current_view.get_cur_zero_elev();
847     T.makeTranslate( asl_offset );
848
849     // printf("  Translated to %.2f %.2f %.2f\n", 
850     //        zero_elev.x, zero_elev.y, zero_elev.z );
851
852     // Rotate to proper orientation
853     // printf("  lon = %.2f  lat = %.2f\n", 
854     //        lon * SGD_RADIANS_TO_DEGREES,
855     //        lat * SGD_RADIANS_TO_DEGREES);
856     LON.makeRotate(lon, osg::Vec3(0, 0, 1));
857
858     // xglRotatef( 90.0 - f->get_Latitude() * SGD_RADIANS_TO_DEGREES,
859     //             0.0, 1.0, 0.0 );
860     LAT.makeRotate(90.0 * SGD_DEGREES_TO_RADIANS - lat, osg::Vec3(0, 1, 0));
861
862     layer_transform->setMatrix( LAT*LON*T );
863     // The layers need to be drawn in order because they are
864     // translucent, but OSG transparency sorting doesn't work because
865     // the cloud polys are huge. However, the ordering is simple: the
866     // bottom polys should be drawn from high altitude to low, and the
867     // top polygons from low to high. The altitude can be used
868     // directly to order the polygons!
869     layer_root->getChild(0)->getStateSet()->setRenderBinDetails(-(int)layer_asl,
870                                                                 "RenderBin");
871     layer_root->getChild(1)->getStateSet()->setRenderBinDetails((int)layer_asl,
872                                                                 "RenderBin");
873     if ( alt <= layer_asl ) {
874       layer_root->setSingleChildOn(0);
875     } else if ( alt >= layer_asl + layer_thickness ) {
876       layer_root->setSingleChildOn(1);
877     } else {
878       layer_root->setAllChildrenOff();
879     }
880         
881
882     // now calculate update texture coordinates
883     if ( last_lon < -900 ) {
884         last_lon = lon;
885         last_lat = lat;
886     }
887
888     double sp_dist = speed*dt;
889
890     if ( lon != last_lon || lat != last_lat || sp_dist != 0 ) {
891         Point3D start( last_lon, last_lat, 0.0 );
892         Point3D dest( lon, lat, 0.0 );
893         double course = 0.0, dist = 0.0;
894
895         calc_gc_course_dist( dest, start, &course, &dist );
896         // cout << "course = " << course << ", dist = " << dist << endl;
897
898         // if start and dest are too close together,
899         // calc_gc_course_dist() can return a course of "nan".  If
900         // this happens, lets just use the last known good course.
901         // This is a hack, and it would probably be better to make
902         // calc_gc_course_dist() more robust.
903         if ( isnan(course) ) {
904             course = last_course;
905         } else {
906             last_course = course;
907         }
908
909         // calculate cloud movement due to external forces
910         double ax = 0.0, ay = 0.0, bx = 0.0, by = 0.0;
911
912         if (dist > 0.0) {
913             ax = cos(course) * dist;
914             ay = sin(course) * dist;
915         }
916
917         if (sp_dist > 0) {
918             bx = cos((180.0-direction) * SGD_DEGREES_TO_RADIANS) * sp_dist;
919             by = sin((180.0-direction) * SGD_DEGREES_TO_RADIANS) * sp_dist;
920         }
921
922
923         double xoff = (ax + bx) / (2 * scale);
924         double yoff = (ay + by) / (2 * scale);
925
926         const float layer_scale = layer_span / scale;
927
928         // cout << "xoff = " << xoff << ", yoff = " << yoff << endl;
929         base[0] += xoff;
930
931         // the while loops can lead to *long* pauses if base[0] comes
932         // with a bogus value.
933         // while ( base[0] > 1.0 ) { base[0] -= 1.0; }
934         // while ( base[0] < 0.0 ) { base[0] += 1.0; }
935         if ( base[0] > -10.0 && base[0] < 10.0 ) {
936             base[0] -= (int)base[0];
937         } else {
938             SG_LOG(SG_ASTRO, SG_DEBUG,
939                 "Error: base = " << base[0] << "," << base[1] <<
940                 " course = " << course << " dist = " << dist );
941             base[0] = 0.0;
942         }
943
944         base[1] += yoff;
945         // the while loops can lead to *long* pauses if base[0] comes
946         // with a bogus value.
947         // while ( base[1] > 1.0 ) { base[1] -= 1.0; }
948         // while ( base[1] < 0.0 ) { base[1] += 1.0; }
949         if ( base[1] > -10.0 && base[1] < 10.0 ) {
950             base[1] -= (int)base[1];
951         } else {
952             SG_LOG(SG_ASTRO, SG_DEBUG,
953                     "Error: base = " << base[0] << "," << base[1] <<
954                     " course = " << course << " dist = " << dist );
955             base[1] = 0.0;
956         }
957
958         // cout << "base = " << base[0] << "," << base[1] << endl;
959
960         setTextureOffset(base);
961         last_lon = lon;
962         last_lat = lat;
963     }
964
965 //      layer3D->reposition( p, up, lon, lat, alt, dt, direction, speed);
966     return true;
967 }