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.
24 # include <simgear_config.h>
27 #include <simgear/compiler.h>
33 #include <osg/AlphaFunc>
34 #include <osg/BlendFunc>
36 #include <osg/Geometry>
37 #include <osg/Material>
38 #include <osg/ShadeModel>
40 #include <osg/TexEnvCombine>
41 #include <osg/Texture2D>
42 #include <osg/TextureCubeMap>
45 #include <simgear/math/sg_random.h>
46 #include <simgear/misc/PathOptions.hxx>
47 #include <simgear/debug/logstream.hxx>
48 #include <simgear/scene/model/model.hxx>
49 #include <simgear/scene/util/RenderConstants.hxx>
50 #include <simgear/scene/util/StateAttributeFactory.hxx>
51 #include <simgear/math/polar3d.hxx>
53 #include "newcloud.hxx"
54 #include "cloudfield.hxx"
57 using namespace simgear;
58 // #if defined(__MINGW32__)
59 // #define isnan(x) _isnan(x)
62 // #if defined (__FreeBSD__)
63 // # if __FreeBSD_version < 500000
65 // inline int isnan(double r) { return !(r <= 0 || r >= 0); }
70 #if defined (__CYGWIN__)
74 static osg::ref_ptr<osg::StateSet> layer_states[SGCloudLayer::SG_MAX_CLOUD_COVERAGES];
75 static osg::ref_ptr<osg::StateSet> layer_states2[SGCloudLayer::SG_MAX_CLOUD_COVERAGES];
76 static osg::ref_ptr<osg::TextureCubeMap> cubeMap;
77 static bool state_initialized = false;
78 static bool bump_mapping = false;
80 bool SGCloudLayer::enable_bump_mapping = false;
82 // make an StateSet for a cloud layer given the named texture
84 SGMakeState(const SGPath &path, const char* colorTexture,
85 const char* normalTexture)
87 osg::StateSet *stateSet = new osg::StateSet;
89 osg::ref_ptr<osgDB::ReaderWriter::Options> options
90 = makeOptionsFromPath(path);
91 stateSet->setTextureAttribute(0, SGLoadTexture2D(colorTexture,
93 stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::ON);
94 StateAttributeFactory* attribFactory = StateAttributeFactory::instance();
95 stateSet->setAttributeAndModes(attribFactory->getSmoothShadeModel());
96 stateSet->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
97 stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
98 stateSet->setAttributeAndModes(attribFactory->getStandardAlphaFunc());
99 stateSet->setAttributeAndModes(attribFactory->getStandardBlendFunc());
101 // osg::Material* material = new osg::Material;
102 // material->setColorMode(osg::Material::AMBIENT_AND_DIFFUSE);
103 // material->setEmission(osg::Material::FRONT_AND_BACK,
104 // osg::Vec4(0.05, 0.05, 0.05, 0));
105 // material->setSpecular(osg::Material::FRONT_AND_BACK,
106 // osg::Vec4(0, 0, 0, 1));
107 // stateSet->setAttribute(material);
109 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
111 // OSGFIXME: invented by me ...
112 // stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
113 // stateSet->setMode(GL_LIGHTING, osg::StateAttribute::ON);
115 // stateSet->setMode(GL_LIGHT0, osg::StateAttribute::OFF);
117 // If the normal texture is given prepare a bumpmapping enabled state
118 // if (normalTexture) {
119 // SGPath normalPath(path);
120 // normalPath.append(normalTexture);
121 // stateSet->setTextureAttribute(2, SGLoadTexture2D(normalPath));
122 // stateSet->setTextureMode(2, GL_TEXTURE_2D, osg::StateAttribute::ON);
129 SGCloudLayer::SGCloudLayer( const string &tex_path ) :
130 layer_root(new osg::Switch),
131 group_top(new osg::Group),
132 group_bottom(new osg::Group),
133 layer_transform(new osg::MatrixTransform),
135 texture_path(tex_path),
138 layer_thickness(0.0),
139 layer_transition(0.0),
140 layer_coverage(SG_CLOUD_CLEAR),
148 // Render bottoms before the rest of transparent objects (rendered
149 // in bin 10), tops after. The negative numbers on the bottoms
150 // RenderBins and the positive numbers on the tops enforce this
152 layer_root->addChild(group_bottom.get());
153 layer_root->addChild(group_top.get());
154 osg::StateSet *rootSet = layer_root->getOrCreateStateSet();
155 rootSet->setRenderBinDetails(CLOUDS_BIN, "DepthSortedBin");
156 rootSet->setTextureAttribute(0, new osg::TexMat);
157 // Combiner for fog color and cloud alpha
158 osg::TexEnvCombine* combine0 = new osg::TexEnvCombine;
159 osg::TexEnvCombine* combine1 = new osg::TexEnvCombine;
160 combine0->setCombine_RGB(osg::TexEnvCombine::MODULATE);
161 combine0->setSource0_RGB(osg::TexEnvCombine::PREVIOUS);
162 combine0->setOperand0_RGB(osg::TexEnvCombine::SRC_COLOR);
163 combine0->setSource1_RGB(osg::TexEnvCombine::TEXTURE0);
164 combine0->setOperand1_RGB(osg::TexEnvCombine::SRC_COLOR);
165 combine0->setCombine_Alpha(osg::TexEnvCombine::MODULATE);
166 combine0->setSource0_Alpha(osg::TexEnvCombine::PREVIOUS);
167 combine0->setOperand0_Alpha(osg::TexEnvCombine::SRC_ALPHA);
168 combine0->setSource1_Alpha(osg::TexEnvCombine::TEXTURE0);
169 combine0->setOperand1_Alpha(osg::TexEnvCombine::SRC_ALPHA);
171 combine1->setCombine_RGB(osg::TexEnvCombine::MODULATE);
172 combine1->setSource0_RGB(osg::TexEnvCombine::PREVIOUS);
173 combine1->setOperand0_RGB(osg::TexEnvCombine::SRC_COLOR);
174 combine1->setSource1_RGB(osg::TexEnvCombine::CONSTANT);
175 combine1->setOperand1_RGB(osg::TexEnvCombine::SRC_COLOR);
176 combine1->setCombine_Alpha(osg::TexEnvCombine::MODULATE);
177 combine1->setSource0_Alpha(osg::TexEnvCombine::PREVIOUS);
178 combine1->setOperand0_Alpha(osg::TexEnvCombine::SRC_ALPHA);
179 combine1->setSource1_Alpha(osg::TexEnvCombine::CONSTANT);
180 combine1->setOperand1_Alpha(osg::TexEnvCombine::SRC_ALPHA);
181 combine1->setDataVariance(osg::Object::DYNAMIC);
182 rootSet->setTextureAttributeAndModes(0, combine0);
183 rootSet->setTextureAttributeAndModes(1, combine1);
184 rootSet->setTextureMode(1, GL_TEXTURE_2D, osg::StateAttribute::ON);
185 rootSet->setTextureAttributeAndModes(1, StateAttributeFactory::instance()
187 osg::StateAttribute::ON);
188 rootSet->setDataVariance(osg::Object::DYNAMIC);
190 base = osg::Vec2(sg_random(), sg_random());
192 group_top->addChild(layer_transform.get());
193 group_bottom->addChild(layer_transform.get());
195 layer3D = new SGCloudField;
200 SGCloudLayer::~SGCloudLayer()
206 SGCloudLayer::getSpan_m () const
212 SGCloudLayer::setSpan_m (float span_m)
214 if (span_m != layer_span) {
221 SGCloudLayer::getElevation_m () const
227 SGCloudLayer::setElevation_m (float elevation_m, bool set_span)
229 layer_asl = elevation_m;
232 if (elevation_m > 4000)
233 setSpan_m( elevation_m * 10 );
240 SGCloudLayer::getThickness_m () const
242 return layer_thickness;
246 SGCloudLayer::setThickness_m (float thickness_m)
248 layer_thickness = thickness_m;
252 SGCloudLayer::getTransition_m () const
254 return layer_transition;
258 SGCloudLayer::setTransition_m (float transition_m)
260 layer_transition = transition_m;
263 SGCloudLayer::Coverage
264 SGCloudLayer::getCoverage () const
266 return layer_coverage;
270 SGCloudLayer::setCoverage (Coverage coverage)
272 if (coverage != layer_coverage) {
273 layer_coverage = coverage;
279 SGCloudLayer::setTextureOffset(const osg::Vec2& offset)
281 osg::StateAttribute* attr = layer_root->getStateSet()
282 ->getTextureAttribute(0, osg::StateAttribute::TEXMAT);
283 osg::TexMat* texMat = dynamic_cast<osg::TexMat*>(attr);
286 texMat->setMatrix(osg::Matrix::translate(offset[0], offset[1], 0.0));
289 // build the cloud object
291 SGCloudLayer::rebuild()
293 // Initialize states and sizes if necessary.
294 if ( !state_initialized ) {
295 state_initialized = true;
297 SG_LOG(SG_ASTRO, SG_INFO, "initializing cloud layers");
299 osg::Texture::Extensions* extensions;
300 extensions = osg::Texture::getExtensions(0, true);
302 bump_mapping = extensions->isMultiTexturingSupported() &&
303 (2 <= extensions->numTextureUnits()) &&
304 SGIsOpenGLExtensionSupported("GL_ARB_texture_env_combine") &&
305 SGIsOpenGLExtensionSupported("GL_ARB_texture_env_dot3");
307 osg::TextureCubeMap::Extensions* extensions2;
308 extensions2 = osg::TextureCubeMap::getExtensions(0, true);
309 bump_mapping = bump_mapping && extensions2->isCubeMapSupported();
311 // This bump mapping code was inspired by the tutorial available at
312 // http://www.paulsprojects.net/tutorials/simplebump/simplebump.html
313 // and a NVidia white paper
314 // http://developer.nvidia.com/object/bumpmappingwithregistercombiners.html
315 // The normal map textures were generated by the normal map Gimp plugin :
316 // http://nifelheim.dyndns.org/~cocidius/normalmap/
318 cubeMap = new osg::TextureCubeMap;
319 cubeMap->setFilter(osg::Texture::MIN_FILTER, osg::Texture::LINEAR);
320 cubeMap->setFilter(osg::Texture::MAG_FILTER, osg::Texture::LINEAR);
321 cubeMap->setWrap(osg::Texture::WRAP_S, osg::Texture::CLAMP_TO_EDGE);
322 cubeMap->setWrap(osg::Texture::WRAP_T, osg::Texture::CLAMP_TO_EDGE);
323 cubeMap->setWrap(osg::Texture::WRAP_R, osg::Texture::CLAMP_TO_EDGE);
326 const float half_size = 16.0f;
327 const float offset = 0.5f;
328 osg::Vec3 zero_normal(0.5, 0.5, 0.5);
330 osg::Image* image = new osg::Image;
331 image->allocateImage(size, size, 1, GL_RGB, GL_UNSIGNED_BYTE);
332 unsigned char *ptr = image->data(0, 0);
333 for (int j = 0; j < size; j++ ) {
334 for (int i = 0; i < size; i++ ) {
335 osg::Vec3 tmp(half_size, -( j + offset - half_size ),
336 -( i + offset - half_size ) );
338 tmp = tmp*0.5 - zero_normal;
340 *ptr++ = (unsigned char)( tmp[ 0 ] * 255 );
341 *ptr++ = (unsigned char)( tmp[ 1 ] * 255 );
342 *ptr++ = (unsigned char)( tmp[ 2 ] * 255 );
345 cubeMap->setImage(osg::TextureCubeMap::POSITIVE_X, image);
347 image = new osg::Image;
348 image->allocateImage(size, size, 1, GL_RGB, GL_UNSIGNED_BYTE);
349 ptr = image->data(0, 0);
350 for (int j = 0; j < size; j++ ) {
351 for (int i = 0; i < size; i++ ) {
352 osg::Vec3 tmp(-half_size, -( j + offset - half_size ),
353 ( i + offset - half_size ) );
355 tmp = tmp*0.5 - zero_normal;
357 *ptr++ = (unsigned char)( tmp[ 0 ] * 255 );
358 *ptr++ = (unsigned char)( tmp[ 1 ] * 255 );
359 *ptr++ = (unsigned char)( tmp[ 2 ] * 255 );
362 cubeMap->setImage(osg::TextureCubeMap::NEGATIVE_X, image);
364 image = new osg::Image;
365 image->allocateImage(size, size, 1, GL_RGB, GL_UNSIGNED_BYTE);
366 ptr = image->data(0, 0);
367 for (int j = 0; j < size; j++ ) {
368 for (int i = 0; i < size; i++ ) {
369 osg::Vec3 tmp(( i + offset - half_size ), half_size,
370 ( j + offset - half_size ) );
372 tmp = tmp*0.5 - zero_normal;
374 *ptr++ = (unsigned char)( tmp[ 0 ] * 255 );
375 *ptr++ = (unsigned char)( tmp[ 1 ] * 255 );
376 *ptr++ = (unsigned char)( tmp[ 2 ] * 255 );
379 cubeMap->setImage(osg::TextureCubeMap::POSITIVE_Y, image);
381 image = new osg::Image;
382 image->allocateImage(size, size, 1, GL_RGB, GL_UNSIGNED_BYTE);
383 ptr = image->data(0, 0);
384 for (int j = 0; j < size; j++ ) {
385 for (int i = 0; i < size; i++ ) {
386 osg::Vec3 tmp(( i + offset - half_size ), -half_size,
387 -( j + offset - half_size ) );
389 tmp = tmp*0.5 - zero_normal;
391 *ptr++ = (unsigned char)( tmp[ 0 ] * 255 );
392 *ptr++ = (unsigned char)( tmp[ 1 ] * 255 );
393 *ptr++ = (unsigned char)( tmp[ 2 ] * 255 );
396 cubeMap->setImage(osg::TextureCubeMap::NEGATIVE_Y, image);
398 image = new osg::Image;
399 image->allocateImage(size, size, 1, GL_RGB, GL_UNSIGNED_BYTE);
400 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(( i + offset - half_size ),
404 -( j + offset - half_size ), half_size );
406 tmp = tmp*0.5 - zero_normal;
408 *ptr++ = (unsigned char)( tmp[ 0 ] * 255 );
409 *ptr++ = (unsigned char)( tmp[ 1 ] * 255 );
410 *ptr++ = (unsigned char)( tmp[ 2 ] * 255 );
413 cubeMap->setImage(osg::TextureCubeMap::POSITIVE_Z, image);
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(-( i + offset - half_size ),
421 -( j + offset - half_size ), -half_size );
423 tmp = tmp*0.5 - zero_normal;
424 *ptr++ = (unsigned char)( tmp[ 0 ] * 255 );
425 *ptr++ = (unsigned char)( tmp[ 1 ] * 255 );
426 *ptr++ = (unsigned char)( tmp[ 2 ] * 255 );
429 cubeMap->setImage(osg::TextureCubeMap::NEGATIVE_Z, image);
431 osg::StateSet* state;
432 state = SGMakeState(texture_path, "overcast.rgb", "overcast_n.rgb");
433 layer_states[SG_CLOUD_OVERCAST] = state;
434 state = SGMakeState(texture_path, "overcast_top.rgb", "overcast_top_n.rgb");
435 layer_states2[SG_CLOUD_OVERCAST] = state;
437 state = SGMakeState(texture_path, "broken.rgba", "broken_n.rgb");
438 layer_states[SG_CLOUD_BROKEN] = state;
439 layer_states2[SG_CLOUD_BROKEN] = state;
441 state = SGMakeState(texture_path, "scattered.rgba", "scattered_n.rgb");
442 layer_states[SG_CLOUD_SCATTERED] = state;
443 layer_states2[SG_CLOUD_SCATTERED] = state;
445 state = SGMakeState(texture_path, "few.rgba", "few_n.rgb");
446 layer_states[SG_CLOUD_FEW] = state;
447 layer_states2[SG_CLOUD_FEW] = state;
449 state = SGMakeState(texture_path, "cirrus.rgba", "cirrus_n.rgb");
450 layer_states[SG_CLOUD_CIRRUS] = state;
451 layer_states2[SG_CLOUD_CIRRUS] = state;
453 layer_states[SG_CLOUD_CLEAR] = 0;
454 layer_states2[SG_CLOUD_CLEAR] = 0;
457 // SGNewCloud::loadTextures(texture_path.str());
458 // layer3D->buildTestLayer();
462 last_lon = last_lat = -999.0f;
464 setTextureOffset(base);
465 // build the cloud layer
466 const float layer_scale = layer_span / scale;
467 const float mpi = SG_PI/4;
469 // caclculate the difference between a flat-earth model and
470 // a round earth model given the span and altutude ASL of
471 // the cloud layer. This is the difference in altitude between
472 // the top of the inverted bowl and the edge of the bowl.
473 // const float alt_diff = layer_asl * 0.8;
474 const float layer_to_core = (SG_EARTH_RAD * 1000 + layer_asl);
475 const float layer_angle = 0.5*layer_span / layer_to_core; // The angle is half the span
476 const float border_to_core = layer_to_core * cos(layer_angle);
477 const float alt_diff = layer_to_core - border_to_core;
479 for (int i = 0; i < 4; i++) {
480 if ( layer[i] != NULL ) {
481 layer_transform->removeChild(layer[i].get()); // automatic delete
484 vl[i] = new osg::Vec3Array;
485 cl[i] = new osg::Vec4Array;
486 tl[i] = new osg::Vec2Array;
489 osg::Vec3 vertex(layer_span*(i-2)/2, -layer_span,
490 alt_diff * (sin(i*mpi) - 2));
491 osg::Vec2 tc(layer_scale * i/4, 0.0f);
492 osg::Vec4 color(1.0f, 1.0f, 1.0f, (i == 0) ? 0.0f : 0.15f);
494 cl[i]->push_back(color);
495 vl[i]->push_back(vertex);
496 tl[i]->push_back(tc);
498 for (int j = 0; j < 4; j++) {
499 vertex = osg::Vec3(layer_span*(i-1)/2, layer_span*(j-2)/2,
500 alt_diff * (sin((i+1)*mpi) + sin(j*mpi) - 2));
501 tc = osg::Vec2(layer_scale * (i+1)/4, layer_scale * j/4);
502 color = osg::Vec4(1.0f, 1.0f, 1.0f,
503 ( (j == 0) || (i == 3)) ?
504 ( (j == 0) && (i == 3)) ? 0.0f : 0.15f : 1.0f );
506 cl[i]->push_back(color);
507 vl[i]->push_back(vertex);
508 tl[i]->push_back(tc);
510 vertex = osg::Vec3(layer_span*(i-2)/2, layer_span*(j-1)/2,
511 alt_diff * (sin(i*mpi) + sin((j+1)*mpi) - 2) );
512 tc = osg::Vec2(layer_scale * i/4, layer_scale * (j+1)/4 );
513 color = osg::Vec4(1.0f, 1.0f, 1.0f,
514 ((j == 3) || (i == 0)) ?
515 ((j == 3) && (i == 0)) ? 0.0f : 0.15f : 1.0f );
516 cl[i]->push_back(color);
517 vl[i]->push_back(vertex);
518 tl[i]->push_back(tc);
521 vertex = osg::Vec3(layer_span*(i-1)/2, layer_span,
522 alt_diff * (sin((i+1)*mpi) - 2));
524 tc = osg::Vec2(layer_scale * (i+1)/4, layer_scale);
526 color = osg::Vec4(1.0f, 1.0f, 1.0f, (i == 3) ? 0.0f : 0.15f );
528 cl[i]->push_back( color );
529 vl[i]->push_back( vertex );
530 tl[i]->push_back( tc );
532 osg::Geometry* geometry = new osg::Geometry;
533 geometry->setUseDisplayList(false);
534 geometry->setVertexArray(vl[i].get());
535 geometry->setNormalBinding(osg::Geometry::BIND_OFF);
536 geometry->setColorArray(cl[i].get());
537 geometry->setColorBinding(osg::Geometry::BIND_PER_VERTEX);
538 geometry->setTexCoordArray(0, tl[i].get());
539 geometry->addPrimitiveSet(new osg::DrawArrays(GL_TRIANGLE_STRIP, 0, vl[i]->size()));
540 layer[i] = new osg::Geode;
542 std::stringstream sstr;
543 sstr << "Cloud Layer (" << i << ")";
544 geometry->setName(sstr.str());
545 layer[i]->setName(sstr.str());
546 layer[i]->addDrawable(geometry);
547 layer_transform->addChild(layer[i].get());
551 if ( layer_states[layer_coverage].valid() ) {
552 osg::CopyOp copyOp; // shallow copy
553 // render bin will be set in reposition
554 osg::StateSet* stateSet = static_cast<osg::StateSet*>(layer_states2[layer_coverage]->clone(copyOp));
555 stateSet->setDataVariance(osg::Object::DYNAMIC);
556 group_top->setStateSet(stateSet);
557 stateSet = static_cast<osg::StateSet*>(layer_states2[layer_coverage]->clone(copyOp));
558 stateSet->setDataVariance(osg::Object::DYNAMIC);
559 group_bottom->setStateSet(stateSet);
567 ssgGetModelviewMatrix( modelview );
568 layer_transform->getTransform( transform );
570 sgTransposeNegateMat4( tmp, transform );
572 sgPostMultMat4( transform, modelview );
573 ssgLoadModelviewMatrix( transform );
576 ssgGetLight( 0 )->getPosition( lightVec );
577 sgNegateVec3( lightVec );
578 sgXformVec3( lightVec, tmp );
580 for ( int i = 0; i < 25; i++ ) {
581 CloudVertex &v = vertices[ i ];
582 sgSetVec3( v.tangentSpLight,
583 sgScalarProductVec3( v.sTangent, lightVec ),
584 sgScalarProductVec3( v.tTangent, lightVec ),
585 sgScalarProductVec3( v.normal, lightVec ) );
588 ssgTexture *decal = color_map[ layer_coverage ][ top ? 1 : 0 ];
589 if ( top && decal == 0 ) {
590 decal = color_map[ layer_coverage ][ 0 ];
592 ssgTexture *normal = normal_map[ layer_coverage ][ top ? 1 : 0 ];
593 if ( top && normal == 0 ) {
594 normal = normal_map[ layer_coverage ][ 0 ];
597 glDisable( GL_LIGHTING );
598 glDisable( GL_CULL_FACE );
599 // glDisable( GL_ALPHA_TEST );
600 if ( layer_coverage == SG_CLOUD_FEW ) {
601 glEnable( GL_ALPHA_TEST );
602 glAlphaFunc ( GL_GREATER, 0.01 );
604 glEnable( GL_BLEND );
605 glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
607 glShadeModel( GL_SMOOTH );
608 glEnable( GL_COLOR_MATERIAL );
612 ssgGetLight( 0 )->getColour( GL_DIFFUSE, color );
613 emis = ( color[0]+color[1]+color[2] ) / 3.0;
617 sgSetVec4( color, emis, emis, emis, 0.0 );
618 glMaterialfv( GL_FRONT_AND_BACK, GL_EMISSION, color );
619 sgSetVec4( color, 1.0f, 1.0f, 1.0f, 0.0 );
620 glMaterialfv( GL_FRONT_AND_BACK, GL_AMBIENT, color );
621 sgSetVec4( color, 1.0, 1.0, 1.0, 0.0 );
622 glMaterialfv( GL_FRONT_AND_BACK, GL_DIFFUSE, color );
623 sgSetVec4( color, 0.0, 0.0, 0.0, 0.0 );
624 glMaterialfv( GL_FRONT_AND_BACK, GL_SPECULAR, color );
626 glColor4f( 1.0f, 1.0f, 1.0f, 1.0f );
628 glActiveTexturePtr( GL_TEXTURE0_ARB );
629 glBindTexture( GL_TEXTURE_2D, normal->getHandle() );
630 glEnable( GL_TEXTURE_2D );
632 //Bind normalisation cube map to texture unit 1
633 glActiveTexturePtr( GL_TEXTURE1_ARB );
634 glBindTexture( GL_TEXTURE_CUBE_MAP_ARB, normalization_cube_map );
635 glEnable( GL_TEXTURE_CUBE_MAP_ARB );
636 glActiveTexturePtr( GL_TEXTURE0_ARB );
638 //Set vertex arrays for cloud
639 glVertexPointer( 3, GL_FLOAT, sizeof(CloudVertex), &vertices[0].position );
640 glEnableClientState( GL_VERTEX_ARRAY );
642 if ( nb_texture_unit >= 3 ) {
643 glColorPointer( 4, GL_FLOAT, sizeof(CloudVertex), &vertices[0].color );
644 glEnableClientState( GL_COLOR_ARRAY );
647 //Send texture coords for normal map to unit 0
648 glTexCoordPointer( 2, GL_FLOAT, sizeof(CloudVertex), &vertices[0].texCoord );
649 glEnableClientState( GL_TEXTURE_COORD_ARRAY );
651 //Send tangent space light vectors for normalisation to unit 1
652 glClientActiveTexturePtr( GL_TEXTURE1_ARB );
653 glTexCoordPointer( 3, GL_FLOAT, sizeof(CloudVertex), &vertices[0].tangentSpLight );
654 glEnableClientState( GL_TEXTURE_COORD_ARRAY );
656 //Set up texture environment to do (tex0 dot tex1)*color
657 glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_ARB );
658 glTexEnvi( GL_TEXTURE_ENV, GL_SOURCE0_RGB_ARB, GL_TEXTURE );
659 glTexEnvi( GL_TEXTURE_ENV, GL_COMBINE_RGB_ARB, GL_REPLACE );
660 glTexEnvi( GL_TEXTURE_ENV, GL_SOURCE0_ALPHA_ARB, GL_TEXTURE );
661 glTexEnvi( GL_TEXTURE_ENV, GL_COMBINE_ALPHA_ARB, GL_REPLACE );
663 // use TexEnvCombine to add the highlights to the original lighting
664 osg::TexEnvCombine *te = new osg::TexEnvCombine;
665 te->setSource0_RGB(osg::TexEnvCombine::TEXTURE);
666 te->setCombine_RGB(osg::TexEnvCombine::REPLACE);
667 te->setSource0_Alpha(osg::TexEnvCombine::TEXTURE);
668 te->setCombine_Alpha(osg::TexEnvCombine::REPLACE);
669 ss->setTextureAttributeAndModes(0, te, osg::StateAttribute::OVERRIDE | osg::StateAttribute::ON);
672 glActiveTexturePtr( GL_TEXTURE1_ARB );
674 glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_ARB );
675 glTexEnvi( GL_TEXTURE_ENV, GL_SOURCE0_RGB_ARB, GL_TEXTURE );
676 glTexEnvi( GL_TEXTURE_ENV, GL_COMBINE_RGB_ARB, GL_DOT3_RGB_ARB );
677 glTexEnvi( GL_TEXTURE_ENV, GL_SOURCE1_RGB_ARB, GL_PREVIOUS_ARB );
678 glTexEnvi( GL_TEXTURE_ENV, GL_SOURCE0_ALPHA_ARB, GL_PREVIOUS_ARB );
679 glTexEnvi( GL_TEXTURE_ENV, GL_COMBINE_ALPHA_ARB, GL_REPLACE );
681 osg::TexEnvCombine *te = new osg::TexEnvCombine;
682 te->setSource0_RGB(osg::TexEnvCombine::TEXTURE);
683 te->setCombine_RGB(osg::TexEnvCombine::DOT3_RGB);
684 te->setSource1_RGB(osg::TexEnvCombine::PREVIOUS);
685 te->setSource0_Alpha(osg::TexEnvCombine::PREVIOUS);
686 te->setCombine_Alpha(osg::TexEnvCombine::REPLACE);
687 ss->setTextureAttributeAndModes(0, te, osg::StateAttribute::OVERRIDE | osg::StateAttribute::ON);
690 if ( nb_texture_unit >= 3 ) {
691 glActiveTexturePtr( GL_TEXTURE2_ARB );
692 glBindTexture( GL_TEXTURE_2D, decal->getHandle() );
694 glClientActiveTexturePtr( GL_TEXTURE2_ARB );
695 glTexCoordPointer( 2, GL_FLOAT, sizeof(CloudVertex), &vertices[0].texCoord );
696 glEnableClientState( GL_TEXTURE_COORD_ARRAY );
698 glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_ARB );
699 glTexEnvi( GL_TEXTURE_ENV, GL_COMBINE_RGB_ARB, GL_ADD );
700 glTexEnvi( GL_TEXTURE_ENV, GL_SOURCE0_RGB_ARB, GL_TEXTURE );
701 glTexEnvi( GL_TEXTURE_ENV, GL_SOURCE1_RGB_ARB, GL_PREVIOUS_ARB );
703 glClientActiveTexturePtr( GL_TEXTURE0_ARB );
704 glActiveTexturePtr( GL_TEXTURE0_ARB );
707 glDrawElements( GL_TRIANGLE_STRIP, 10, GL_UNSIGNED_INT, &indices[0] );
708 glDrawElements( GL_TRIANGLE_STRIP, 10, GL_UNSIGNED_INT, &indices[10] );
709 glDrawElements( GL_TRIANGLE_STRIP, 10, GL_UNSIGNED_INT, &indices[20] );
710 glDrawElements( GL_TRIANGLE_STRIP, 10, GL_UNSIGNED_INT, &indices[30] );
712 glDisable( GL_TEXTURE_2D );
713 glActiveTexturePtr( GL_TEXTURE1_ARB );
714 glDisable( GL_TEXTURE_CUBE_MAP_ARB );
715 glActiveTexturePtr( GL_TEXTURE2_ARB );
716 glDisable( GL_TEXTURE_2D );
717 glActiveTexturePtr( GL_TEXTURE0_ARB );
719 glDisableClientState( GL_TEXTURE_COORD_ARRAY );
720 glClientActiveTexturePtr( GL_TEXTURE1_ARB );
721 glDisableClientState( GL_TEXTURE_COORD_ARRAY );
722 glClientActiveTexturePtr( GL_TEXTURE2_ARB );
723 glDisableClientState( GL_TEXTURE_COORD_ARRAY );
724 glClientActiveTexturePtr( GL_TEXTURE0_ARB );
726 glDisableClientState( GL_COLOR_ARRAY );
727 glEnable( GL_LIGHTING );
729 glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE );
732 glClientActiveTexturePtr( GL_TEXTURE0_ARB );
733 glActiveTexturePtr( GL_TEXTURE0_ARB );
736 glDrawElements( GL_TRIANGLE_STRIP, 10, GL_UNSIGNED_INT, &indices[0] );
737 glDrawElements( GL_TRIANGLE_STRIP, 10, GL_UNSIGNED_INT, &indices[10] );
738 glDrawElements( GL_TRIANGLE_STRIP, 10, GL_UNSIGNED_INT, &indices[20] );
739 glDrawElements( GL_TRIANGLE_STRIP, 10, GL_UNSIGNED_INT, &indices[30] );
742 glDisable( GL_TEXTURE_2D );
744 glActiveTexturePtr( GL_TEXTURE1_ARB );
745 glDisable( GL_TEXTURE_CUBE_MAP_ARB );
746 glActiveTexturePtr( GL_TEXTURE0_ARB );
748 //disable vertex arrays
749 glDisableClientState( GL_VERTEX_ARRAY );
751 glDisableClientState( GL_TEXTURE_COORD_ARRAY );
752 glClientActiveTexturePtr( GL_TEXTURE1_ARB );
753 glDisableClientState( GL_TEXTURE_COORD_ARRAY );
754 glClientActiveTexturePtr( GL_TEXTURE0_ARB );
756 //Return to standard modulate texenv
757 glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE );
759 if ( layer_coverage == SG_CLOUD_OVERCAST ) {
760 glDepthFunc(GL_LEQUAL);
762 glEnable( GL_LIGHTING );
764 ssgGetLight( 0 )->getColour( GL_DIFFUSE, color );
765 float average = ( color[0] + color[1] + color[2] ) / 3.0f;
766 average = 0.15 + average/10;
768 sgSetVec4( averageColor, average, average, average, 1.0f );
769 ssgGetLight( 0 )->setColour( GL_DIFFUSE, averageColor );
771 glBlendColorPtr( average, average, average, 1.0f );
772 glBlendFunc( GL_ONE_MINUS_CONSTANT_COLOR, GL_CONSTANT_COLOR );
774 //Perform a second pass to color the torus
776 glBindTexture( GL_TEXTURE_2D, decal->getHandle() );
777 glEnable(GL_TEXTURE_2D);
779 //Set vertex arrays for torus
780 glVertexPointer( 3, GL_FLOAT, sizeof(CloudVertex), &vertices[0].position );
781 glEnableClientState( GL_VERTEX_ARRAY );
783 //glColorPointer( 4, GL_FLOAT, sizeof(CloudVertex), &vertices[0].color );
784 //glEnableClientState( GL_COLOR_ARRAY );
786 glNormalPointer( GL_FLOAT, sizeof(CloudVertex), &vertices[0].normal );
787 glEnableClientState( GL_NORMAL_ARRAY );
789 glTexCoordPointer( 2, GL_FLOAT, sizeof(CloudVertex), &vertices[0].texCoord );
790 glEnableClientState( GL_TEXTURE_COORD_ARRAY );
793 glDrawElements( GL_TRIANGLE_STRIP, 10, GL_UNSIGNED_INT, &indices[0] );
794 glDrawElements( GL_TRIANGLE_STRIP, 10, GL_UNSIGNED_INT, &indices[10] );
795 glDrawElements( GL_TRIANGLE_STRIP, 10, GL_UNSIGNED_INT, &indices[20] );
796 glDrawElements( GL_TRIANGLE_STRIP, 10, GL_UNSIGNED_INT, &indices[30] );
798 ssgGetLight( 0 )->setColour( GL_DIFFUSE, color );
800 glDisableClientState( GL_TEXTURE_COORD_ARRAY );
804 glDisable( GL_TEXTURE_2D );
806 glDisableClientState( GL_VERTEX_ARRAY );
807 glDisableClientState( GL_NORMAL_ARRAY );
809 glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
810 glEnable( GL_CULL_FACE );
811 glDepthFunc(GL_LESS);
813 ssgLoadModelviewMatrix( modelview );
816 // repaint the cloud layer colors
817 bool SGCloudLayer::repaint( const SGVec3f& fog_color ) {
818 osg::Vec4f combineColor(fog_color.osg(), cloud_alpha);
819 osg::TexEnvCombine* combiner
820 = dynamic_cast<osg::TexEnvCombine*>(layer_root->getStateSet()
821 ->getTextureAttribute(1, osg::StateAttribute::TEXENV));
822 combiner->setConstantColor(combineColor);
826 // reposition the cloud layer at the specified origin and orientation
827 // lon specifies a rotation about the Z axis
828 // lat specifies a rotation about the new Y axis
829 // spin specifies a rotation about the new Z axis (and orients the
830 // sunrise/set effects
831 bool SGCloudLayer::reposition( const SGVec3f& p, const SGVec3f& up, double lon, double lat,
832 double alt, double dt )
834 // combine p and asl (meters) to get translation offset
835 osg::Vec3 asl_offset(up.osg());
836 asl_offset.normalize();
837 if ( alt <= layer_asl ) {
838 asl_offset *= layer_asl;
840 asl_offset *= layer_asl + layer_thickness;
843 // cout << "asl_offset = " << asl_offset[0] << "," << asl_offset[1]
844 // << "," << asl_offset[2] << endl;
845 asl_offset += p.osg();
846 // cout << " asl_offset = " << asl_offset[0] << "," << asl_offset[1]
847 // << "," << asl_offset[2] << endl;
849 osg::Matrix T, LON, LAT;
850 // Translate to zero elevation
851 // Point3D zero_elev = current_view.get_cur_zero_elev();
852 T.makeTranslate( asl_offset );
854 // printf(" Translated to %.2f %.2f %.2f\n",
855 // zero_elev.x, zero_elev.y, zero_elev.z );
857 // Rotate to proper orientation
858 // printf(" lon = %.2f lat = %.2f\n",
859 // lon * SGD_RADIANS_TO_DEGREES,
860 // lat * SGD_RADIANS_TO_DEGREES);
861 LON.makeRotate(lon, osg::Vec3(0, 0, 1));
863 // xglRotatef( 90.0 - f->get_Latitude() * SGD_RADIANS_TO_DEGREES,
865 LAT.makeRotate(90.0 * SGD_DEGREES_TO_RADIANS - lat, osg::Vec3(0, 1, 0));
867 layer_transform->setMatrix( LAT*LON*T );
868 // The layers need to be drawn in order because they are
869 // translucent, but OSG transparency sorting doesn't work because
870 // the cloud polys are huge. However, the ordering is simple: the
871 // bottom polys should be drawn from high altitude to low, and the
872 // top polygons from low to high. The altitude can be used
873 // directly to order the polygons!
874 group_bottom->getStateSet()->setRenderBinDetails(-(int)layer_asl,
876 group_top->getStateSet()->setRenderBinDetails((int)layer_asl,
878 if ( alt <= layer_asl ) {
879 layer_root->setSingleChildOn(0);
880 } else if ( alt >= layer_asl + layer_thickness ) {
881 layer_root->setSingleChildOn(1);
883 layer_root->setAllChildrenOff();
887 // now calculate update texture coordinates
888 if ( last_lon < -900 ) {
893 double sp_dist = speed*dt;
895 if ( lon != last_lon || lat != last_lat || sp_dist != 0 ) {
896 Point3D start( last_lon, last_lat, 0.0 );
897 Point3D dest( lon, lat, 0.0 );
898 double course = 0.0, dist = 0.0;
900 calc_gc_course_dist( dest, start, &course, &dist );
901 // cout << "course = " << course << ", dist = " << dist << endl;
903 // if start and dest are too close together,
904 // calc_gc_course_dist() can return a course of "nan". If
905 // this happens, lets just use the last known good course.
906 // This is a hack, and it would probably be better to make
907 // calc_gc_course_dist() more robust.
908 if ( isnan(course) ) {
909 course = last_course;
911 last_course = course;
914 // calculate cloud movement due to external forces
915 double ax = 0.0, ay = 0.0, bx = 0.0, by = 0.0;
918 ax = cos(course) * dist;
919 ay = sin(course) * dist;
923 bx = cos((180.0-direction) * SGD_DEGREES_TO_RADIANS) * sp_dist;
924 by = sin((180.0-direction) * SGD_DEGREES_TO_RADIANS) * sp_dist;
928 double xoff = (ax + bx) / (2 * scale);
929 double yoff = (ay + by) / (2 * scale);
931 const float layer_scale = layer_span / scale;
933 // cout << "xoff = " << xoff << ", yoff = " << yoff << endl;
936 // the while loops can lead to *long* pauses if base[0] comes
937 // with a bogus value.
938 // while ( base[0] > 1.0 ) { base[0] -= 1.0; }
939 // while ( base[0] < 0.0 ) { base[0] += 1.0; }
940 if ( base[0] > -10.0 && base[0] < 10.0 ) {
941 base[0] -= (int)base[0];
943 SG_LOG(SG_ASTRO, SG_DEBUG,
944 "Error: base = " << base[0] << "," << base[1] <<
945 " course = " << course << " dist = " << dist );
950 // the while loops can lead to *long* pauses if base[0] comes
951 // with a bogus value.
952 // while ( base[1] > 1.0 ) { base[1] -= 1.0; }
953 // while ( base[1] < 0.0 ) { base[1] += 1.0; }
954 if ( base[1] > -10.0 && base[1] < 10.0 ) {
955 base[1] -= (int)base[1];
957 SG_LOG(SG_ASTRO, SG_DEBUG,
958 "Error: base = " << base[0] << "," << base[1] <<
959 " course = " << course << " dist = " << dist );
963 // cout << "base = " << base[0] << "," << base[1] << endl;
965 setTextureOffset(base);
970 // layer3D->reposition( p, up, lon, lat, alt, dt, direction, speed);