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