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