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