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