]> git.mxchange.org Git - simgear.git/blob - simgear/scene/sky/cloud.cxx
Merge branch 'next' of git://gitorious.org/fg/simgear into next
[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 <simgear/structure/OSGVersion.hxx>
34 #include <osg/AlphaFunc>
35 #include <osg/BlendFunc>
36 #include <osg/CullFace>
37 #include <osg/Geode>
38 #include <osg/Geometry>
39 #include <osg/Material>
40 #include <osg/ShadeModel>
41 #include <osg/TexEnv>
42 #include <osg/TexEnvCombine>
43 #include <osg/Texture2D>
44 #include <osg/TextureCubeMap>
45 #include <osg/TexMat>
46 #include <osg/Fog>
47 #if SG_OSG_MIN_VERSION_REQUIRED(2,9,5)
48 #include <osgDB/Options>
49 #endif
50
51 #include <simgear/math/sg_random.h>
52 #include <simgear/misc/PathOptions.hxx>
53 #include <simgear/debug/logstream.hxx>
54 #include <simgear/scene/model/model.hxx>
55 #include <simgear/scene/util/RenderConstants.hxx>
56 #include <simgear/scene/util/StateAttributeFactory.hxx>
57 #include <simgear/screen/extensions.hxx>
58
59 #include "newcloud.hxx"
60 #include "cloudfield.hxx"
61 #include "cloud.hxx"
62
63 using namespace simgear;
64 using namespace osg;
65
66 #if defined(__MINGW32__)
67 #define isnan(x) _isnan(x)
68 #endif
69
70 // #if defined (__FreeBSD__)
71 // #  if __FreeBSD_version < 500000
72 //      extern "C" {
73 //        inline int isnan(double r) { return !(r <= 0 || r >= 0); }
74 //      }
75 // #  endif
76 // #endif
77
78 static osg::ref_ptr<osg::StateSet> layer_states[SGCloudLayer::SG_MAX_CLOUD_COVERAGES];
79 static osg::ref_ptr<osg::StateSet> layer_states2[SGCloudLayer::SG_MAX_CLOUD_COVERAGES];
80 static osg::ref_ptr<osg::TextureCubeMap> cubeMap;
81 static bool state_initialized = false;
82 static bool bump_mapping = false;
83
84 bool SGCloudLayer::enable_bump_mapping = false;
85
86 // make an StateSet for a cloud layer given the named texture
87 static osg::StateSet*
88 SGMakeState(const SGPath &path, const char* colorTexture,
89             const char* normalTexture)
90 {
91     osg::StateSet *stateSet = new osg::StateSet;
92
93     osg::ref_ptr<osgDB::ReaderWriter::Options> options
94         = makeOptionsFromPath(path);
95     stateSet->setTextureAttribute(0, SGLoadTexture2D(colorTexture,
96                                                      options.get()));
97     stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::ON);
98     StateAttributeFactory* attribFactory = StateAttributeFactory::instance();
99     stateSet->setAttributeAndModes(attribFactory->getSmoothShadeModel());
100     stateSet->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
101     stateSet->setAttributeAndModes(attribFactory->getStandardAlphaFunc());
102     stateSet->setAttributeAndModes(attribFactory->getStandardBlendFunc());
103
104 //     osg::Material* material = new osg::Material;
105 //     material->setColorMode(osg::Material::AMBIENT_AND_DIFFUSE);
106 //     material->setEmission(osg::Material::FRONT_AND_BACK,
107 //                           osg::Vec4(0.05, 0.05, 0.05, 0));
108 //     material->setSpecular(osg::Material::FRONT_AND_BACK,
109 //                           osg::Vec4(0, 0, 0, 1));
110 //     stateSet->setAttribute(material);
111
112     stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
113
114     // OSGFIXME: invented by me ...
115 //     stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
116 //     stateSet->setMode(GL_LIGHTING, osg::StateAttribute::ON);
117
118 //     stateSet->setMode(GL_LIGHT0, osg::StateAttribute::OFF);
119
120     // If the normal texture is given prepare a bumpmapping enabled state
121 //     if (normalTexture) {
122 //       SGPath normalPath(path);
123 //       normalPath.append(normalTexture);
124 //       stateSet->setTextureAttribute(2, SGLoadTexture2D(normalPath));
125 //       stateSet->setTextureMode(2, GL_TEXTURE_2D, osg::StateAttribute::ON);
126 //     }
127
128     return stateSet;
129 }
130
131 // Constructor
132 SGCloudLayer::SGCloudLayer( const string &tex_path ) :
133     cloud_root(new osg::Switch),
134     layer_root(new osg::Switch),
135     group_top(new osg::Group),
136     group_bottom(new osg::Group),
137     layer_transform(new osg::MatrixTransform),
138     cloud_alpha(1.0),
139     texture_path(tex_path),
140     layer_span(0.0),
141     layer_asl(0.0),
142     layer_thickness(0.0),
143     layer_transition(0.0),
144     layer_coverage(SG_CLOUD_CLEAR),
145     scale(4000.0),
146     speed(0.0),
147     direction(0.0)
148 {
149     // XXX
150     // Render bottoms before the rest of transparent objects (rendered
151     // in bin 10), tops after. The negative numbers on the bottoms
152     // RenderBins and the positive numbers on the tops enforce this
153     // order.
154   cloud_root->addChild(layer_root.get(), true);
155   layer_root->addChild(group_bottom.get());
156   layer_root->addChild(group_top.get());
157   osg::StateSet *rootSet = layer_root->getOrCreateStateSet();
158   rootSet->setRenderBinDetails(CLOUDS_BIN, "DepthSortedBin");
159   rootSet->setTextureAttribute(0, new osg::TexMat);
160   rootSet->setMode(GL_CULL_FACE, osg::StateAttribute::ON);
161   // Combiner for fog color and cloud alpha
162   osg::TexEnvCombine* combine0 = new osg::TexEnvCombine;
163   osg::TexEnvCombine* combine1 = new osg::TexEnvCombine;
164   combine0->setCombine_RGB(osg::TexEnvCombine::MODULATE);
165   combine0->setSource0_RGB(osg::TexEnvCombine::PREVIOUS);
166   combine0->setOperand0_RGB(osg::TexEnvCombine::SRC_COLOR);
167   combine0->setSource1_RGB(osg::TexEnvCombine::TEXTURE0);
168   combine0->setOperand1_RGB(osg::TexEnvCombine::SRC_COLOR);
169   combine0->setCombine_Alpha(osg::TexEnvCombine::MODULATE);
170   combine0->setSource0_Alpha(osg::TexEnvCombine::PREVIOUS);
171   combine0->setOperand0_Alpha(osg::TexEnvCombine::SRC_ALPHA);
172   combine0->setSource1_Alpha(osg::TexEnvCombine::TEXTURE0);
173   combine0->setOperand1_Alpha(osg::TexEnvCombine::SRC_ALPHA);
174
175   combine1->setCombine_RGB(osg::TexEnvCombine::MODULATE);
176   combine1->setSource0_RGB(osg::TexEnvCombine::PREVIOUS);
177   combine1->setOperand0_RGB(osg::TexEnvCombine::SRC_COLOR);
178   combine1->setSource1_RGB(osg::TexEnvCombine::CONSTANT);
179   combine1->setOperand1_RGB(osg::TexEnvCombine::SRC_COLOR);
180   combine1->setCombine_Alpha(osg::TexEnvCombine::MODULATE);
181   combine1->setSource0_Alpha(osg::TexEnvCombine::PREVIOUS);
182   combine1->setOperand0_Alpha(osg::TexEnvCombine::SRC_ALPHA);
183   combine1->setSource1_Alpha(osg::TexEnvCombine::CONSTANT);
184   combine1->setOperand1_Alpha(osg::TexEnvCombine::SRC_ALPHA);
185   combine1->setDataVariance(osg::Object::DYNAMIC);
186   rootSet->setTextureAttributeAndModes(0, combine0);
187   rootSet->setTextureAttributeAndModes(1, combine1);
188   rootSet->setTextureMode(1, GL_TEXTURE_2D, osg::StateAttribute::ON);
189   rootSet->setTextureAttributeAndModes(1, StateAttributeFactory::instance()
190                                        ->getWhiteTexture(),
191                                        osg::StateAttribute::ON);
192   rootSet->setDataVariance(osg::Object::DYNAMIC);
193
194   base = osg::Vec2(sg_random(), sg_random());
195   group_top->addChild(layer_transform.get());
196   group_bottom->addChild(layer_transform.get());
197
198   layer3D = new SGCloudField();
199   cloud_root->addChild(layer3D->getNode(), false);
200
201   rebuild();
202 }
203
204 // Destructor
205 SGCloudLayer::~SGCloudLayer()
206 {
207   delete layer3D;
208 }
209
210 float
211 SGCloudLayer::getSpan_m () const
212 {
213     return layer_span;
214 }
215
216 void
217 SGCloudLayer::setSpan_m (float span_m)
218 {
219     if (span_m != layer_span) {
220         layer_span = span_m;
221         rebuild();
222     }
223 }
224
225 float
226 SGCloudLayer::getElevation_m () const
227 {
228     return layer_asl;
229 }
230
231 void
232 SGCloudLayer::setElevation_m (float elevation_m, bool set_span)
233 {
234     layer_asl = elevation_m;
235
236     if (set_span) {
237         if (elevation_m > 4000)
238             setSpan_m(  elevation_m * 10 );
239         else
240             setSpan_m( 40000 );
241     }
242 }
243
244 float
245 SGCloudLayer::getThickness_m () const
246 {
247     return layer_thickness;
248 }
249
250 void
251 SGCloudLayer::setThickness_m (float thickness_m)
252 {
253     layer_thickness = thickness_m;
254 }
255
256 float
257 SGCloudLayer::getTransition_m () const
258 {
259     return layer_transition;
260 }
261
262 void
263 SGCloudLayer::setTransition_m (float transition_m)
264 {
265     layer_transition = transition_m;
266 }
267
268 SGCloudLayer::Coverage
269 SGCloudLayer::getCoverage () const
270 {
271     return layer_coverage;
272 }
273
274 void
275 SGCloudLayer::setCoverage (Coverage coverage)
276 {
277     if (coverage != layer_coverage) {
278         layer_coverage = coverage;
279         rebuild();
280         
281         double coverage_norm = 0.0;
282         if( coverage ==  SG_CLOUD_FEW)
283             coverage_norm = 2.0/8.0;    // <1-2
284         else if( coverage == SG_CLOUD_SCATTERED )
285             coverage_norm = 4.0/8.0;    // 3-4
286         else if( coverage == SG_CLOUD_BROKEN )
287             coverage_norm = 6.0/8.0;    // 5-7
288         else if( coverage == SG_CLOUD_OVERCAST )
289             coverage_norm = 8.0/8.0;    // 8
290         
291         layer3D->setCoverage(coverage_norm);
292         layer3D->applyCoverage();
293     }
294 }
295
296 void
297 SGCloudLayer::setTextureOffset(const osg::Vec2& offset)
298 {
299     osg::StateAttribute* attr = layer_root->getStateSet()
300         ->getTextureAttribute(0, osg::StateAttribute::TEXMAT);
301     osg::TexMat* texMat = dynamic_cast<osg::TexMat*>(attr);
302     if (!texMat)
303         return;
304     texMat->setMatrix(osg::Matrix::translate(offset[0], offset[1], 0.0));
305 }
306
307 // colors for debugging the cloud layers
308 #ifdef CLOUD_DEBUG
309 Vec3 cloudColors[] = {Vec3(1.0f, 1.0f, 1.0f), Vec3(1.0f, 0.0f, 0.0f),
310                       Vec3(0.0f, 1.0f, 0.0f), Vec3(0.0f, 0.0f, 1.0f)};
311 #else
312 Vec3 cloudColors[] = {Vec3(1.0f, 1.0f, 1.0f), Vec3(1.0f, 1.0f, 1.0f),
313                       Vec3(1.0f, 1.0f, 1.0f), Vec3(1.0f, 1.0f, 1.0f)};
314 #endif
315
316 // build the cloud object
317 void
318 SGCloudLayer::rebuild()
319 {
320     // Initialize states and sizes if necessary.
321     if ( !state_initialized ) { 
322         state_initialized = true;
323
324         SG_LOG(SG_ASTRO, SG_INFO, "initializing cloud layers");
325
326         osg::Texture::Extensions* extensions;
327         extensions = osg::Texture::getExtensions(0, true);
328         // OSGFIXME
329         bump_mapping = extensions->isMultiTexturingSupported() &&
330           (2 <= extensions->numTextureUnits()) &&
331           SGIsOpenGLExtensionSupported("GL_ARB_texture_env_combine") &&
332           SGIsOpenGLExtensionSupported("GL_ARB_texture_env_dot3");
333
334         osg::TextureCubeMap::Extensions* extensions2;
335         extensions2 = osg::TextureCubeMap::getExtensions(0, true);
336         bump_mapping = bump_mapping && extensions2->isCubeMapSupported();
337
338         // This bump mapping code was inspired by the tutorial available at 
339         // http://www.paulsprojects.net/tutorials/simplebump/simplebump.html
340         // and a NVidia white paper 
341         //  http://developer.nvidia.com/object/bumpmappingwithregistercombiners.html
342         // The normal map textures were generated by the normal map Gimp plugin :
343         //  http://nifelheim.dyndns.org/~cocidius/normalmap/
344         //
345         cubeMap = new osg::TextureCubeMap;
346         cubeMap->setFilter(osg::Texture::MIN_FILTER, osg::Texture::LINEAR);
347         cubeMap->setFilter(osg::Texture::MAG_FILTER, osg::Texture::LINEAR);
348         cubeMap->setWrap(osg::Texture::WRAP_S, osg::Texture::CLAMP_TO_EDGE);
349         cubeMap->setWrap(osg::Texture::WRAP_T, osg::Texture::CLAMP_TO_EDGE);
350         cubeMap->setWrap(osg::Texture::WRAP_R, osg::Texture::CLAMP_TO_EDGE);
351
352         const int size = 32;
353         const float half_size = 16.0f;
354         const float offset = 0.5f;
355         osg::Vec3 zero_normal(0.5, 0.5, 0.5);
356
357         osg::Image* image = new osg::Image;
358         image->allocateImage(size, size, 1, GL_RGB, GL_UNSIGNED_BYTE);
359         unsigned char *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(half_size, -( j + offset - half_size ),
363                           -( i + 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::POSITIVE_X, 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(-half_size, -( j + offset - half_size ),
380                           ( i + offset - 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::NEGATIVE_X, 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 ), half_size,
397                           ( j + offset - half_size ) );
398             tmp.normalize();
399             tmp = tmp*0.5 - zero_normal;
400             
401             *ptr++ = (unsigned char)( tmp[ 0 ] * 255 );
402             *ptr++ = (unsigned char)( tmp[ 1 ] * 255 );
403             *ptr++ = (unsigned char)( tmp[ 2 ] * 255 );
404           }
405         }
406         cubeMap->setImage(osg::TextureCubeMap::POSITIVE_Y, image);
407
408         image = new osg::Image;
409         image->allocateImage(size, size, 1, GL_RGB, GL_UNSIGNED_BYTE);
410         ptr = image->data(0, 0);
411         for (int j = 0; j < size; j++ ) {
412           for (int i = 0; i < size; i++ ) {
413             osg::Vec3 tmp(( i + offset - half_size ), -half_size,
414                           -( j + offset - half_size ) );
415             tmp.normalize();
416             tmp = tmp*0.5 - zero_normal;
417
418             *ptr++ = (unsigned char)( tmp[ 0 ] * 255 );
419             *ptr++ = (unsigned char)( tmp[ 1 ] * 255 );
420             *ptr++ = (unsigned char)( tmp[ 2 ] * 255 );
421           }
422         }
423         cubeMap->setImage(osg::TextureCubeMap::NEGATIVE_Y, image);
424
425         image = new osg::Image;
426         image->allocateImage(size, size, 1, GL_RGB, GL_UNSIGNED_BYTE);
427         ptr = image->data(0, 0);
428         for (int j = 0; j < size; j++ ) {
429           for (int i = 0; i < size; i++ ) {
430             osg::Vec3 tmp(( i + offset - half_size ),
431                           -( j + offset - half_size ), half_size );
432             tmp.normalize();
433             tmp = tmp*0.5 - zero_normal;
434             
435             *ptr++ = (unsigned char)( tmp[ 0 ] * 255 );
436             *ptr++ = (unsigned char)( tmp[ 1 ] * 255 );
437             *ptr++ = (unsigned char)( tmp[ 2 ] * 255 );
438           }
439         }
440         cubeMap->setImage(osg::TextureCubeMap::POSITIVE_Z, image);
441
442         image = new osg::Image;
443         image->allocateImage(size, size, 1, GL_RGB, GL_UNSIGNED_BYTE);
444         ptr = image->data(0, 0);
445         for (int j = 0; j < size; j++ ) {
446           for (int i = 0; i < size; i++ ) {
447             osg::Vec3 tmp(-( i + offset - half_size ),
448                           -( j + offset - half_size ), -half_size );
449             tmp.normalize();
450             tmp = tmp*0.5 - zero_normal;
451             *ptr++ = (unsigned char)( tmp[ 0 ] * 255 );
452             *ptr++ = (unsigned char)( tmp[ 1 ] * 255 );
453             *ptr++ = (unsigned char)( tmp[ 2 ] * 255 );
454           }
455         }
456         cubeMap->setImage(osg::TextureCubeMap::NEGATIVE_Z, image);
457
458         osg::StateSet* state;
459         state = SGMakeState(texture_path, "overcast.png", "overcast_n.png");
460         layer_states[SG_CLOUD_OVERCAST] = state;
461         state = SGMakeState(texture_path, "overcast_top.png", "overcast_top_n.png");
462         layer_states2[SG_CLOUD_OVERCAST] = state;
463         
464         state = SGMakeState(texture_path, "broken.png", "broken_n.png");
465         layer_states[SG_CLOUD_BROKEN] = state;
466         layer_states2[SG_CLOUD_BROKEN] = state;
467         
468         state = SGMakeState(texture_path, "scattered.png", "scattered_n.png");
469         layer_states[SG_CLOUD_SCATTERED] = state;
470         layer_states2[SG_CLOUD_SCATTERED] = state;
471         
472         state = SGMakeState(texture_path, "few.png", "few_n.png");
473         layer_states[SG_CLOUD_FEW] = state;
474         layer_states2[SG_CLOUD_FEW] = state;
475         
476         state = SGMakeState(texture_path, "cirrus.png", "cirrus_n.png");
477         layer_states[SG_CLOUD_CIRRUS] = state;
478         layer_states2[SG_CLOUD_CIRRUS] = state;
479         
480         layer_states[SG_CLOUD_CLEAR] = 0;
481         layer_states2[SG_CLOUD_CLEAR] = 0;
482 #if 1
483         // experimental optimization that may not make any difference
484         // at all :/
485         osg::CopyOp copyOp;
486         for (int i = 0; i < SG_MAX_CLOUD_COVERAGES; ++i) {
487             StateAttributeFactory *saf = StateAttributeFactory::instance();
488             if (layer_states[i].valid()) {
489                 if (layer_states[i] == layer_states2[i])
490                     layer_states2[i] = static_cast<osg::StateSet*>(layer_states[i]->clone(copyOp));
491                 layer_states[i]->setAttribute(saf ->getCullFaceFront());
492                 layer_states2[i]->setAttribute(saf ->getCullFaceBack());
493             }
494         }
495 #endif
496     }
497
498     scale = 4000.0;
499
500     setTextureOffset(base);
501     // build the cloud layer
502     const float layer_scale = layer_span / scale;
503     const float mpi = SG_PI/4;
504     
505     // caclculate the difference between a flat-earth model and 
506     // a round earth model given the span and altutude ASL of
507     // the cloud layer. This is the difference in altitude between
508     // the top of the inverted bowl and the edge of the bowl.
509     // const float alt_diff = layer_asl * 0.8;
510     const float layer_to_core = (SG_EARTH_RAD * 1000 + layer_asl);
511     const float layer_angle = 0.5*layer_span / layer_to_core; // The angle is half the span
512     const float border_to_core = layer_to_core * cos(layer_angle);
513     const float alt_diff = layer_to_core - border_to_core;
514     
515     for (int i = 0; i < 4; i++) {
516       if ( layer[i] != NULL ) {
517         layer_transform->removeChild(layer[i].get()); // automatic delete
518       }
519       
520       vl[i] = new osg::Vec3Array;
521       cl[i] = new osg::Vec4Array;
522       tl[i] = new osg::Vec2Array;
523       
524       
525       osg::Vec3 vertex(layer_span*(i-2)/2, -layer_span,
526                        alt_diff * (sin(i*mpi) - 2));
527       osg::Vec2 tc(layer_scale * i/4, 0.0f);
528       osg::Vec4 color(cloudColors[0], (i == 0) ? 0.0f : 0.15f);
529       
530       cl[i]->push_back(color);
531       vl[i]->push_back(vertex);
532       tl[i]->push_back(tc);
533       
534       for (int j = 0; j < 4; j++) {
535         vertex = osg::Vec3(layer_span*(i-1)/2, layer_span*(j-2)/2,
536                            alt_diff * (sin((i+1)*mpi) + sin(j*mpi) - 2));
537         tc = osg::Vec2(layer_scale * (i+1)/4, layer_scale * j/4);
538         color = osg::Vec4(cloudColors[0],
539                           ( (j == 0) || (i == 3)) ?  
540                           ( (j == 0) && (i == 3)) ? 0.0f : 0.15f : 1.0f );
541         
542         cl[i]->push_back(color);
543         vl[i]->push_back(vertex);
544         tl[i]->push_back(tc);
545         
546         vertex = osg::Vec3(layer_span*(i-2)/2, layer_span*(j-1)/2,
547                            alt_diff * (sin(i*mpi) + sin((j+1)*mpi) - 2) );
548         tc = osg::Vec2(layer_scale * i/4, layer_scale * (j+1)/4 );
549         color = osg::Vec4(cloudColors[0],
550                           ((j == 3) || (i == 0)) ?
551                           ((j == 3) && (i == 0)) ? 0.0f : 0.15f : 1.0f );
552         cl[i]->push_back(color);
553         vl[i]->push_back(vertex);
554         tl[i]->push_back(tc);
555       }
556       
557       vertex = osg::Vec3(layer_span*(i-1)/2, layer_span, 
558                          alt_diff * (sin((i+1)*mpi) - 2));
559       
560       tc = osg::Vec2(layer_scale * (i+1)/4, layer_scale);
561       
562       color = osg::Vec4(cloudColors[0], (i == 3) ? 0.0f : 0.15f );
563       
564       cl[i]->push_back( color );
565       vl[i]->push_back( vertex );
566       tl[i]->push_back( tc );
567       
568       osg::Geometry* geometry = new osg::Geometry;
569       geometry->setUseDisplayList(false);
570       geometry->setVertexArray(vl[i].get());
571       geometry->setNormalBinding(osg::Geometry::BIND_OFF);
572       geometry->setColorArray(cl[i].get());
573       geometry->setColorBinding(osg::Geometry::BIND_PER_VERTEX);
574       geometry->setTexCoordArray(0, tl[i].get());
575       geometry->addPrimitiveSet(new osg::DrawArrays(GL_TRIANGLE_STRIP, 0, vl[i]->size()));
576       layer[i] = new osg::Geode;
577       
578       std::stringstream sstr;
579       sstr << "Cloud Layer (" << i << ")";
580       geometry->setName(sstr.str());
581       layer[i]->setName(sstr.str());
582       layer[i]->addDrawable(geometry);
583       layer_transform->addChild(layer[i].get());
584     }
585     
586     //OSGFIXME: true
587     if ( layer_states[layer_coverage].valid() ) {
588       osg::CopyOp copyOp;    // shallow copy
589       // render bin will be set in reposition
590       osg::StateSet* stateSet = static_cast<osg::StateSet*>(layer_states2[layer_coverage]->clone(copyOp));
591       stateSet->setDataVariance(osg::Object::DYNAMIC);
592       group_top->setStateSet(stateSet);
593       stateSet = static_cast<osg::StateSet*>(layer_states[layer_coverage]->clone(copyOp));
594       stateSet->setDataVariance(osg::Object::DYNAMIC);
595       group_bottom->setStateSet(stateSet);
596     }
597 }
598
599 // repaint the cloud layer colors
600 bool SGCloudLayer::repaint( const SGVec3f& fog_color ) {
601     osg::Vec4f combineColor(toOsg(fog_color), cloud_alpha);
602     osg::TexEnvCombine* combiner
603         = dynamic_cast<osg::TexEnvCombine*>(layer_root->getStateSet()
604                                             ->getTextureAttribute(1, osg::StateAttribute::TEXENV));
605     combiner->setConstantColor(combineColor);
606
607     // Set the fog color for the 3D clouds too.
608     //cloud3dfog->setColor(combineColor);
609     return true;
610 }
611
612 // reposition the cloud layer at the specified origin and orientation
613 // lon specifies a rotation about the Z axis
614 // lat specifies a rotation about the new Y axis
615 // spin specifies a rotation about the new Z axis (and orients the
616 // sunrise/set effects
617 bool SGCloudLayer::reposition( const SGVec3f& p, const SGVec3f& up, double lon, double lat,
618                                double alt, double dt )
619 {
620     // combine p and asl (meters) to get translation offset
621     osg::Vec3 asl_offset(toOsg(up));
622     asl_offset.normalize();
623     if ( alt <= layer_asl ) {
624         asl_offset *= layer_asl;
625     } else {
626         asl_offset *= layer_asl + layer_thickness;
627     }
628
629     // cout << "asl_offset = " << asl_offset[0] << "," << asl_offset[1]
630     //      << "," << asl_offset[2] << endl;
631     asl_offset += toOsg(p);
632     // cout << "  asl_offset = " << asl_offset[0] << "," << asl_offset[1]
633     //      << "," << asl_offset[2] << endl;
634
635     osg::Matrix T, LON, LAT;
636     // Translate to zero elevation
637     // Point3D zero_elev = current_view.get_cur_zero_elev();
638     T.makeTranslate( asl_offset );
639
640     // printf("  Translated to %.2f %.2f %.2f\n", 
641     //        zero_elev.x, zero_elev.y, zero_elev.z );
642
643     // Rotate to proper orientation
644     // printf("  lon = %.2f  lat = %.2f\n", 
645     //        lon * SGD_RADIANS_TO_DEGREES,
646     //        lat * SGD_RADIANS_TO_DEGREES);
647     LON.makeRotate(lon, osg::Vec3(0, 0, 1));
648
649     // xglRotatef( 90.0 - f->get_Latitude() * SGD_RADIANS_TO_DEGREES,
650     //             0.0, 1.0, 0.0 );
651     LAT.makeRotate(90.0 * SGD_DEGREES_TO_RADIANS - lat, osg::Vec3(0, 1, 0));
652
653     layer_transform->setMatrix( LAT*LON*T );
654
655     // The layers need to be drawn in order because they are
656     // translucent, but OSG transparency sorting doesn't work because
657     // the cloud polys are huge. However, the ordering is simple: the
658     // bottom polys should be drawn from high altitude to low, and the
659     // top polygons from low to high. The altitude can be used
660     // directly to order the polygons!
661     group_bottom->getStateSet()->setRenderBinDetails(-(int)layer_asl,
662                                                      "RenderBin");
663     group_top->getStateSet()->setRenderBinDetails((int)layer_asl,
664                                                   "RenderBin");
665     if ( alt <= layer_asl ) {
666       layer_root->setSingleChildOn(0);
667     } else if ( alt >= layer_asl + layer_thickness ) {
668       layer_root->setSingleChildOn(1);
669     } else {
670       layer_root->setAllChildrenOff();
671     }
672         
673
674     // now calculate update texture coordinates
675     SGGeod pos = SGGeod::fromRad(lon, lat);
676     if ( last_pos == SGGeod() ) {
677         last_pos = pos;
678     }
679
680     double sp_dist = speed*dt;
681     
682     
683     if ( lon != last_pos.getLongitudeRad() || lat != last_pos.getLatitudeRad() || sp_dist != 0 ) {
684         double course = SGGeodesy::courseDeg(last_pos, pos) * SG_DEGREES_TO_RADIANS, 
685             dist = SGGeodesy::distanceM(last_pos, pos);
686
687         // if start and dest are too close together,
688         // calc_gc_course_dist() can return a course of "nan".  If
689         // this happens, lets just use the last known good course.
690         // This is a hack, and it would probably be better to make
691         // calc_gc_course_dist() more robust.
692         if ( isnan(course) ) {
693             course = last_course;
694         } else {
695             last_course = course;
696         }
697
698         // calculate cloud movement due to external forces
699         double ax = 0.0, ay = 0.0, bx = 0.0, by = 0.0;
700
701         if (dist > 0.0) {
702             ax = cos(course) * dist;
703             ay = sin(course) * dist;
704         }
705
706         if (sp_dist > 0) {
707             bx = cos((180.0-direction) * SGD_DEGREES_TO_RADIANS) * sp_dist;
708             by = sin((180.0-direction) * SGD_DEGREES_TO_RADIANS) * sp_dist;
709         }
710
711
712         double xoff = (ax + bx) / (2 * scale);
713         double yoff = (ay + by) / (2 * scale);
714
715 //        const float layer_scale = layer_span / scale;
716
717         // cout << "xoff = " << xoff << ", yoff = " << yoff << endl;
718         base[0] += xoff;
719
720         // the while loops can lead to *long* pauses if base[0] comes
721         // with a bogus value.
722         // while ( base[0] > 1.0 ) { base[0] -= 1.0; }
723         // while ( base[0] < 0.0 ) { base[0] += 1.0; }
724         if ( base[0] > -10.0 && base[0] < 10.0 ) {
725             base[0] -= (int)base[0];
726         } else {
727             SG_LOG(SG_ASTRO, SG_DEBUG,
728                 "Error: base = " << base[0] << "," << base[1] <<
729                 " course = " << course << " dist = " << dist );
730             base[0] = 0.0;
731         }
732
733         base[1] += yoff;
734         // the while loops can lead to *long* pauses if base[0] comes
735         // with a bogus value.
736         // while ( base[1] > 1.0 ) { base[1] -= 1.0; }
737         // while ( base[1] < 0.0 ) { base[1] += 1.0; }
738         if ( base[1] > -10.0 && base[1] < 10.0 ) {
739             base[1] -= (int)base[1];
740         } else {
741             SG_LOG(SG_ASTRO, SG_DEBUG,
742                     "Error: base = " << base[0] << "," << base[1] <<
743                     " course = " << course << " dist = " << dist );
744             base[1] = 0.0;
745         }
746
747         // cout << "base = " << base[0] << "," << base[1] << endl;
748
749         setTextureOffset(base);
750         last_pos = pos;
751     }
752
753     layer3D->reposition( p, up, lon, lat, dt, layer_asl);
754     return true;
755 }
756
757 void SGCloudLayer::set_enable3dClouds(bool enable) {
758      
759     if (layer3D->defined3D && enable) {
760         cloud_root->setChildValue(layer3D->getNode(), true);
761         cloud_root->setChildValue(layer_root.get(),   false);
762     } else {
763         cloud_root->setChildValue(layer3D->getNode(), false);
764         cloud_root->setChildValue(layer_root.get(),   true);
765     }
766 }