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