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