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