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