1 // cloud.cxx -- model a single cloud layer
3 // Written by Curtis Olson, started June 2000.
5 // Copyright (C) 2000 Curtis L. Olson - http://www.flightgear.org/~curt
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.
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.
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.
23 # include <simgear_config.h>
26 #include <simgear/compiler.h>
32 #include <simgear/structure/OSGVersion.hxx>
33 #include <osg/AlphaFunc>
34 #include <osg/BlendFunc>
35 #include <osg/CullFace>
37 #include <osg/Geometry>
38 #include <osg/Material>
39 #include <osg/ShadeModel>
41 #include <osg/TexEnvCombine>
42 #include <osg/Texture2D>
43 #include <osg/TextureCubeMap>
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>
56 #include "newcloud.hxx"
57 #include "cloudfield.hxx"
60 using namespace simgear;
63 #if defined(__MINGW32__)
64 #define isnan(x) _isnan(x)
67 // #if defined (__FreeBSD__)
68 // # if __FreeBSD_version < 500000
70 // inline int isnan(double r) { return !(r <= 0 || r >= 0); }
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;
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";
87 // make an StateSet for a cloud layer given the named texture
89 SGMakeState(const SGPath &path, const char* colorTexture,
90 const char* normalTexture)
92 osg::StateSet *stateSet = new osg::StateSet;
94 osg::ref_ptr<SGReaderWriterOptions> options;
95 options = SGReaderWriterOptions::fromPath(path.str());
96 stateSet->setTextureAttribute(0, SGLoadTexture2D(colorTexture,
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());
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);
113 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
115 // OSGFIXME: invented by me ...
116 // stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
117 // stateSet->setMode(GL_LIGHTING, osg::StateAttribute::ON);
119 // stateSet->setMode(GL_LIGHT0, osg::StateAttribute::OFF);
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);
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),
140 texture_path(tex_path),
143 layer_thickness(0.0),
144 layer_transition(0.0),
145 layer_visibility(25.0),
146 layer_coverage(SG_CLOUD_CLEAR),
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
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);
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()
195 osg::StateAttribute::ON);
196 rootSet->setDataVariance(osg::Object::DYNAMIC);
198 // Ensure repeatability of the random seed within 10 minutes,
199 // to keep multi-computer systems in sync.
200 sg_srandom_time_10();
201 base = osg::Vec2(sg_random(), sg_random());
202 group_top->addChild(layer_transform.get());
203 group_bottom->addChild(layer_transform.get());
205 layer3D = new SGCloudField();
206 cloud_root->addChild(layer3D->getNode(), false);
212 SGCloudLayer::~SGCloudLayer()
218 SGCloudLayer::getSpan_m () const
224 SGCloudLayer::setSpan_m (float span_m)
226 if (span_m != layer_span) {
233 SGCloudLayer::getElevation_m () const
239 SGCloudLayer::setElevation_m (float elevation_m, bool set_span)
241 layer_asl = elevation_m;
244 if (elevation_m > 4000)
245 setSpan_m( elevation_m * 10 );
252 SGCloudLayer::getThickness_m () const
254 return layer_thickness;
258 SGCloudLayer::setThickness_m (float thickness_m)
260 layer_thickness = thickness_m;
264 SGCloudLayer::getVisibility_m() const
266 return layer_visibility;
270 SGCloudLayer::setVisibility_m (float visibility_m)
272 layer_visibility = visibility_m;
276 SGCloudLayer::getTransition_m () const
278 return layer_transition;
282 SGCloudLayer::setTransition_m (float transition_m)
284 layer_transition = transition_m;
287 SGCloudLayer::Coverage
288 SGCloudLayer::getCoverage () const
290 return layer_coverage;
294 SGCloudLayer::setCoverage (Coverage coverage)
296 if (coverage != layer_coverage) {
297 layer_coverage = coverage;
303 SGCloudLayer::getCoverageString( Coverage coverage )
306 case SG_CLOUD_OVERCAST:
307 return SG_CLOUD_OVERCAST_STRING;
308 case SG_CLOUD_BROKEN:
309 return SG_CLOUD_BROKEN_STRING;
310 case SG_CLOUD_SCATTERED:
311 return SG_CLOUD_SCATTERED_STRING;
313 return SG_CLOUD_FEW_STRING;
314 case SG_CLOUD_CIRRUS:
315 return SG_CLOUD_CIRRUS_STRING;
318 return SG_CLOUD_CLEAR_STRING;
322 SGCloudLayer::Coverage
323 SGCloudLayer::getCoverageType( const std::string & coverage )
325 if( SG_CLOUD_OVERCAST_STRING == coverage ) {
326 return SG_CLOUD_OVERCAST;
327 } else if( SG_CLOUD_BROKEN_STRING == coverage ) {
328 return SG_CLOUD_BROKEN;
329 } else if( SG_CLOUD_SCATTERED_STRING == coverage ) {
330 return SG_CLOUD_SCATTERED;
331 } else if( SG_CLOUD_FEW_STRING == coverage ) {
333 } else if( SG_CLOUD_CIRRUS_STRING == coverage ) {
334 return SG_CLOUD_CIRRUS;
336 return SG_CLOUD_CLEAR;
341 SGCloudLayer::getCoverageString() const
343 return getCoverageString(layer_coverage);
347 SGCloudLayer::setCoverageString( const std::string & coverage )
349 setCoverage( getCoverageType(coverage) );
353 SGCloudLayer::setTextureOffset(const osg::Vec2& offset)
355 osg::StateAttribute* attr = layer_root->getStateSet()
356 ->getTextureAttribute(0, osg::StateAttribute::TEXMAT);
357 osg::TexMat* texMat = dynamic_cast<osg::TexMat*>(attr);
360 texMat->setMatrix(osg::Matrix::translate(offset[0], offset[1], 0.0));
363 // colors for debugging the cloud layers
365 Vec3 cloudColors[] = {Vec3(1.0f, 1.0f, 1.0f), Vec3(1.0f, 0.0f, 0.0f),
366 Vec3(0.0f, 1.0f, 0.0f), Vec3(0.0f, 0.0f, 1.0f)};
368 Vec3 cloudColors[] = {Vec3(1.0f, 1.0f, 1.0f), Vec3(1.0f, 1.0f, 1.0f),
369 Vec3(1.0f, 1.0f, 1.0f), Vec3(1.0f, 1.0f, 1.0f)};
372 // build the cloud object
374 SGCloudLayer::rebuild()
376 // Initialize states and sizes if necessary.
377 if ( !state_initialized ) {
378 state_initialized = true;
380 SG_LOG(SG_ASTRO, SG_INFO, "initializing cloud layers");
382 // This bump mapping code was inspired by the tutorial available at
383 // http://www.paulsprojects.net/tutorials/simplebump/simplebump.html
384 // and a NVidia white paper
385 // http://developer.nvidia.com/object/bumpmappingwithregistercombiners.html
386 // The normal map textures were generated by the normal map Gimp plugin :
387 // http://nifelheim.dyndns.org/~cocidius/normalmap/
389 cubeMap = new osg::TextureCubeMap;
390 cubeMap->setFilter(osg::Texture::MIN_FILTER, osg::Texture::LINEAR);
391 cubeMap->setFilter(osg::Texture::MAG_FILTER, osg::Texture::LINEAR);
392 cubeMap->setWrap(osg::Texture::WRAP_S, osg::Texture::CLAMP_TO_EDGE);
393 cubeMap->setWrap(osg::Texture::WRAP_T, osg::Texture::CLAMP_TO_EDGE);
394 cubeMap->setWrap(osg::Texture::WRAP_R, osg::Texture::CLAMP_TO_EDGE);
397 const float half_size = 16.0f;
398 const float offset = 0.5f;
399 osg::Vec3 zero_normal(0.5, 0.5, 0.5);
401 osg::Image* image = new osg::Image;
402 image->allocateImage(size, size, 1, GL_RGB, GL_UNSIGNED_BYTE);
403 unsigned char *ptr = image->data(0, 0);
404 for (int j = 0; j < size; j++ ) {
405 for (int i = 0; i < size; i++ ) {
406 osg::Vec3 tmp(half_size, -( j + offset - half_size ),
407 -( i + offset - half_size ) );
409 tmp = tmp*0.5 - zero_normal;
411 *ptr++ = (unsigned char)( tmp[ 0 ] * 255 );
412 *ptr++ = (unsigned char)( tmp[ 1 ] * 255 );
413 *ptr++ = (unsigned char)( tmp[ 2 ] * 255 );
416 cubeMap->setImage(osg::TextureCubeMap::POSITIVE_X, image);
418 image = new osg::Image;
419 image->allocateImage(size, size, 1, GL_RGB, GL_UNSIGNED_BYTE);
420 ptr = image->data(0, 0);
421 for (int j = 0; j < size; j++ ) {
422 for (int i = 0; i < size; i++ ) {
423 osg::Vec3 tmp(-half_size, -( j + offset - half_size ),
424 ( i + offset - half_size ) );
426 tmp = tmp*0.5 - zero_normal;
428 *ptr++ = (unsigned char)( tmp[ 0 ] * 255 );
429 *ptr++ = (unsigned char)( tmp[ 1 ] * 255 );
430 *ptr++ = (unsigned char)( tmp[ 2 ] * 255 );
433 cubeMap->setImage(osg::TextureCubeMap::NEGATIVE_X, image);
435 image = new osg::Image;
436 image->allocateImage(size, size, 1, GL_RGB, GL_UNSIGNED_BYTE);
437 ptr = image->data(0, 0);
438 for (int j = 0; j < size; j++ ) {
439 for (int i = 0; i < size; i++ ) {
440 osg::Vec3 tmp(( i + offset - half_size ), half_size,
441 ( j + offset - half_size ) );
443 tmp = tmp*0.5 - zero_normal;
445 *ptr++ = (unsigned char)( tmp[ 0 ] * 255 );
446 *ptr++ = (unsigned char)( tmp[ 1 ] * 255 );
447 *ptr++ = (unsigned char)( tmp[ 2 ] * 255 );
450 cubeMap->setImage(osg::TextureCubeMap::POSITIVE_Y, image);
452 image = new osg::Image;
453 image->allocateImage(size, size, 1, GL_RGB, GL_UNSIGNED_BYTE);
454 ptr = image->data(0, 0);
455 for (int j = 0; j < size; j++ ) {
456 for (int i = 0; i < size; i++ ) {
457 osg::Vec3 tmp(( i + offset - half_size ), -half_size,
458 -( j + offset - half_size ) );
460 tmp = tmp*0.5 - zero_normal;
462 *ptr++ = (unsigned char)( tmp[ 0 ] * 255 );
463 *ptr++ = (unsigned char)( tmp[ 1 ] * 255 );
464 *ptr++ = (unsigned char)( tmp[ 2 ] * 255 );
467 cubeMap->setImage(osg::TextureCubeMap::NEGATIVE_Y, image);
469 image = new osg::Image;
470 image->allocateImage(size, size, 1, GL_RGB, GL_UNSIGNED_BYTE);
471 ptr = image->data(0, 0);
472 for (int j = 0; j < size; j++ ) {
473 for (int i = 0; i < size; i++ ) {
474 osg::Vec3 tmp(( i + offset - half_size ),
475 -( j + offset - half_size ), half_size );
477 tmp = tmp*0.5 - zero_normal;
479 *ptr++ = (unsigned char)( tmp[ 0 ] * 255 );
480 *ptr++ = (unsigned char)( tmp[ 1 ] * 255 );
481 *ptr++ = (unsigned char)( tmp[ 2 ] * 255 );
484 cubeMap->setImage(osg::TextureCubeMap::POSITIVE_Z, image);
486 image = new osg::Image;
487 image->allocateImage(size, size, 1, GL_RGB, GL_UNSIGNED_BYTE);
488 ptr = image->data(0, 0);
489 for (int j = 0; j < size; j++ ) {
490 for (int i = 0; i < size; i++ ) {
491 osg::Vec3 tmp(-( i + offset - half_size ),
492 -( j + offset - half_size ), -half_size );
494 tmp = tmp*0.5 - zero_normal;
495 *ptr++ = (unsigned char)( tmp[ 0 ] * 255 );
496 *ptr++ = (unsigned char)( tmp[ 1 ] * 255 );
497 *ptr++ = (unsigned char)( tmp[ 2 ] * 255 );
500 cubeMap->setImage(osg::TextureCubeMap::NEGATIVE_Z, image);
502 osg::StateSet* state;
503 state = SGMakeState(texture_path, "overcast.png", "overcast_n.png");
504 layer_states[SG_CLOUD_OVERCAST] = state;
505 state = SGMakeState(texture_path, "overcast_top.png", "overcast_top_n.png");
506 layer_states2[SG_CLOUD_OVERCAST] = state;
508 state = SGMakeState(texture_path, "broken.png", "broken_n.png");
509 layer_states[SG_CLOUD_BROKEN] = state;
510 layer_states2[SG_CLOUD_BROKEN] = state;
512 state = SGMakeState(texture_path, "scattered.png", "scattered_n.png");
513 layer_states[SG_CLOUD_SCATTERED] = state;
514 layer_states2[SG_CLOUD_SCATTERED] = state;
516 state = SGMakeState(texture_path, "few.png", "few_n.png");
517 layer_states[SG_CLOUD_FEW] = state;
518 layer_states2[SG_CLOUD_FEW] = state;
520 state = SGMakeState(texture_path, "cirrus.png", "cirrus_n.png");
521 layer_states[SG_CLOUD_CIRRUS] = state;
522 layer_states2[SG_CLOUD_CIRRUS] = state;
524 layer_states[SG_CLOUD_CLEAR] = 0;
525 layer_states2[SG_CLOUD_CLEAR] = 0;
527 // experimental optimization that may not make any difference
530 for (int i = 0; i < SG_MAX_CLOUD_COVERAGES; ++i) {
531 StateAttributeFactory *saf = StateAttributeFactory::instance();
532 if (layer_states[i].valid()) {
533 if (layer_states[i] == layer_states2[i])
534 layer_states2[i] = static_cast<osg::StateSet*>(layer_states[i]->clone(copyOp));
535 layer_states[i]->setAttribute(saf ->getCullFaceFront());
536 layer_states2[i]->setAttribute(saf ->getCullFaceBack());
544 setTextureOffset(base);
545 // build the cloud layer
546 const float layer_scale = layer_span / scale;
547 const float mpi = SG_PI/4;
549 // caclculate the difference between a flat-earth model and
550 // a round earth model given the span and altutude ASL of
551 // the cloud layer. This is the difference in altitude between
552 // the top of the inverted bowl and the edge of the bowl.
553 // const float alt_diff = layer_asl * 0.8;
554 const float layer_to_core = (SG_EARTH_RAD * 1000 + layer_asl);
555 const float layer_angle = 0.5*layer_span / layer_to_core; // The angle is half the span
556 const float border_to_core = layer_to_core * cos(layer_angle);
557 const float alt_diff = layer_to_core - border_to_core;
559 for (int i = 0; i < 4; i++) {
560 if ( layer[i] != NULL ) {
561 layer_transform->removeChild(layer[i].get()); // automatic delete
564 vl[i] = new osg::Vec3Array;
565 cl[i] = new osg::Vec4Array;
566 tl[i] = new osg::Vec2Array;
569 osg::Vec3 vertex(layer_span*(i-2)/2, -layer_span,
570 alt_diff * (sin(i*mpi) - 2));
571 osg::Vec2 tc(layer_scale * i/4, 0.0f);
572 osg::Vec4 color(cloudColors[0], (i == 0) ? 0.0f : 0.15f);
574 cl[i]->push_back(color);
575 vl[i]->push_back(vertex);
576 tl[i]->push_back(tc);
578 for (int j = 0; j < 4; j++) {
579 vertex = osg::Vec3(layer_span*(i-1)/2, layer_span*(j-2)/2,
580 alt_diff * (sin((i+1)*mpi) + sin(j*mpi) - 2));
581 tc = osg::Vec2(layer_scale * (i+1)/4, layer_scale * j/4);
582 color = osg::Vec4(cloudColors[0],
583 ( (j == 0) || (i == 3)) ?
584 ( (j == 0) && (i == 3)) ? 0.0f : 0.15f : 1.0f );
586 cl[i]->push_back(color);
587 vl[i]->push_back(vertex);
588 tl[i]->push_back(tc);
590 vertex = osg::Vec3(layer_span*(i-2)/2, layer_span*(j-1)/2,
591 alt_diff * (sin(i*mpi) + sin((j+1)*mpi) - 2) );
592 tc = osg::Vec2(layer_scale * i/4, layer_scale * (j+1)/4 );
593 color = osg::Vec4(cloudColors[0],
594 ((j == 3) || (i == 0)) ?
595 ((j == 3) && (i == 0)) ? 0.0f : 0.15f : 1.0f );
596 cl[i]->push_back(color);
597 vl[i]->push_back(vertex);
598 tl[i]->push_back(tc);
601 vertex = osg::Vec3(layer_span*(i-1)/2, layer_span,
602 alt_diff * (sin((i+1)*mpi) - 2));
604 tc = osg::Vec2(layer_scale * (i+1)/4, layer_scale);
606 color = osg::Vec4(cloudColors[0], (i == 3) ? 0.0f : 0.15f );
608 cl[i]->push_back( color );
609 vl[i]->push_back( vertex );
610 tl[i]->push_back( tc );
612 osg::Geometry* geometry = new osg::Geometry;
613 geometry->setUseDisplayList(false);
614 geometry->setVertexArray(vl[i].get());
615 geometry->setNormalBinding(osg::Geometry::BIND_OFF);
616 geometry->setColorArray(cl[i].get());
617 geometry->setColorBinding(osg::Geometry::BIND_PER_VERTEX);
618 geometry->setTexCoordArray(0, tl[i].get());
619 geometry->addPrimitiveSet(new osg::DrawArrays(GL_TRIANGLE_STRIP, 0, vl[i]->size()));
620 layer[i] = new osg::Geode;
622 std::stringstream sstr;
623 sstr << "Cloud Layer (" << i << ")";
624 geometry->setName(sstr.str());
625 layer[i]->setName(sstr.str());
626 layer[i]->addDrawable(geometry);
627 layer_transform->addChild(layer[i].get());
631 if ( layer_states[layer_coverage].valid() ) {
632 osg::CopyOp copyOp; // shallow copy
633 // render bin will be set in reposition
634 osg::StateSet* stateSet = static_cast<osg::StateSet*>(layer_states2[layer_coverage]->clone(copyOp));
635 stateSet->setDataVariance(osg::Object::DYNAMIC);
636 group_top->setStateSet(stateSet);
637 stateSet = static_cast<osg::StateSet*>(layer_states[layer_coverage]->clone(copyOp));
638 stateSet->setDataVariance(osg::Object::DYNAMIC);
639 group_bottom->setStateSet(stateSet);
643 // repaint the cloud layer colors
644 bool SGCloudLayer::repaint( const SGVec3f& fog_color ) {
645 osg::Vec4f combineColor(toOsg(fog_color), cloud_alpha);
646 osg::TexEnvCombine* combiner
647 = dynamic_cast<osg::TexEnvCombine*>(layer_root->getStateSet()
648 ->getTextureAttribute(1, osg::StateAttribute::TEXENV));
649 combiner->setConstantColor(combineColor);
651 // Set the fog color for the 3D clouds too.
652 //cloud3dfog->setColor(combineColor);
656 // reposition the cloud layer at the specified origin and orientation
657 // lon specifies a rotation about the Z axis
658 // lat specifies a rotation about the new Y axis
659 // spin specifies a rotation about the new Z axis (and orients the
660 // sunrise/set effects
661 bool SGCloudLayer::reposition( const SGVec3f& p, const SGVec3f& up, double lon, double lat,
662 double alt, double dt )
665 if (getCoverage() != SGCloudLayer::SG_CLOUD_CLEAR)
667 // combine p and asl (meters) to get translation offset
668 osg::Vec3 asl_offset(toOsg(up));
669 asl_offset.normalize();
670 if ( alt <= layer_asl ) {
671 asl_offset *= layer_asl;
673 asl_offset *= layer_asl + layer_thickness;
676 // cout << "asl_offset = " << asl_offset[0] << "," << asl_offset[1]
677 // << "," << asl_offset[2] << endl;
678 asl_offset += toOsg(p);
679 // cout << " asl_offset = " << asl_offset[0] << "," << asl_offset[1]
680 // << "," << asl_offset[2] << endl;
682 osg::Matrix T, LON, LAT;
683 // Translate to zero elevation
684 // Point3D zero_elev = current_view.get_cur_zero_elev();
685 T.makeTranslate( asl_offset );
687 // printf(" Translated to %.2f %.2f %.2f\n",
688 // zero_elev.x, zero_elev.y, zero_elev.z );
690 // Rotate to proper orientation
691 // printf(" lon = %.2f lat = %.2f\n",
692 // lon * SGD_RADIANS_TO_DEGREES,
693 // lat * SGD_RADIANS_TO_DEGREES);
694 LON.makeRotate(lon, osg::Vec3(0, 0, 1));
696 // xglRotatef( 90.0 - f->get_Latitude() * SGD_RADIANS_TO_DEGREES,
698 LAT.makeRotate(90.0 * SGD_DEGREES_TO_RADIANS - lat, osg::Vec3(0, 1, 0));
700 layer_transform->setMatrix( LAT*LON*T );
702 // The layers need to be drawn in order because they are
703 // translucent, but OSG transparency sorting doesn't work because
704 // the cloud polys are huge. However, the ordering is simple: the
705 // bottom polys should be drawn from high altitude to low, and the
706 // top polygons from low to high. The altitude can be used
707 // directly to order the polygons!
708 group_bottom->getStateSet()->setRenderBinDetails(-(int)layer_asl,
710 group_top->getStateSet()->setRenderBinDetails((int)layer_asl,
712 if ( alt <= layer_asl ) {
713 layer_root->setSingleChildOn(0);
714 } else if ( alt >= layer_asl + layer_thickness ) {
715 layer_root->setSingleChildOn(1);
717 layer_root->setAllChildrenOff();
721 // now calculate update texture coordinates
722 SGGeod pos = SGGeod::fromRad(lon, lat);
723 if ( last_pos == SGGeod() ) {
727 double sp_dist = speed*dt;
730 if ( lon != last_pos.getLongitudeRad() || lat != last_pos.getLatitudeRad() || sp_dist != 0 ) {
731 double course = SGGeodesy::courseDeg(last_pos, pos) * SG_DEGREES_TO_RADIANS,
732 dist = SGGeodesy::distanceM(last_pos, pos);
734 // if start and dest are too close together,
735 // calc_gc_course_dist() can return a course of "nan". If
736 // this happens, lets just use the last known good course.
737 // This is a hack, and it would probably be better to make
738 // calc_gc_course_dist() more robust.
739 if ( isnan(course) ) {
740 course = last_course;
742 last_course = course;
745 // calculate cloud movement due to external forces
746 double ax = 0.0, ay = 0.0, bx = 0.0, by = 0.0;
749 ax = -cos(course) * dist;
750 ay = sin(course) * dist;
754 bx = cos((180.0-direction) * SGD_DEGREES_TO_RADIANS) * sp_dist;
755 by = sin((180.0-direction) * SGD_DEGREES_TO_RADIANS) * sp_dist;
759 double xoff = (ax + bx) / (2 * scale);
760 double yoff = (ay + by) / (2 * scale);
763 // const float layer_scale = layer_span / scale;
765 // cout << "xoff = " << xoff << ", yoff = " << yoff << endl;
768 // the while loops can lead to *long* pauses if base[0] comes
769 // with a bogus value.
770 // while ( base[0] > 1.0 ) { base[0] -= 1.0; }
771 // while ( base[0] < 0.0 ) { base[0] += 1.0; }
772 if ( base[0] > -10.0 && base[0] < 10.0 ) {
773 base[0] -= (int)base[0];
775 SG_LOG(SG_ASTRO, SG_DEBUG,
776 "Error: base = " << base[0] << "," << base[1] <<
777 " course = " << course << " dist = " << dist );
782 // the while loops can lead to *long* pauses if base[0] comes
783 // with a bogus value.
784 // while ( base[1] > 1.0 ) { base[1] -= 1.0; }
785 // while ( base[1] < 0.0 ) { base[1] += 1.0; }
786 if ( base[1] > -10.0 && base[1] < 10.0 ) {
787 base[1] -= (int)base[1];
789 SG_LOG(SG_ASTRO, SG_DEBUG,
790 "Error: base = " << base[0] << "," << base[1] <<
791 " course = " << course << " dist = " << dist );
795 // cout << "base = " << base[0] << "," << base[1] << endl;
797 setTextureOffset(base);
802 layer3D->reposition( p, up, lon, lat, dt, layer_asl, speed, direction);
806 void SGCloudLayer::set_enable3dClouds(bool enable) {
808 if (layer3D->isDefined3D() && enable) {
809 cloud_root->setChildValue(layer3D->getNode(), true);
810 cloud_root->setChildValue(layer_root.get(), false);
812 cloud_root->setChildValue(layer3D->getNode(), false);
813 cloud_root->setChildValue(layer_root.get(), true);