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/Texture2D>
41 #include <osg/TextureCubeMap>
44 #include <simgear/math/sg_random.h>
45 #include <simgear/misc/PathOptions.hxx>
46 #include <simgear/debug/logstream.hxx>
47 #include <simgear/scene/model/model.hxx>
48 #include <simgear/scene/util/RenderConstants.hxx>
49 #include <simgear/scene/util/StateAttributeFactory.hxx>
50 #include <simgear/math/polar3d.hxx>
52 #include "newcloud.hxx"
53 #include "cloudfield.hxx"
56 using namespace simgear;
57 // #if defined(__MINGW32__)
58 // #define isnan(x) _isnan(x)
61 // #if defined (__FreeBSD__)
62 // # if __FreeBSD_version < 500000
64 // inline int isnan(double r) { return !(r <= 0 || r >= 0); }
69 #if defined (__CYGWIN__)
73 static osg::ref_ptr<osg::StateSet> layer_states[SGCloudLayer::SG_MAX_CLOUD_COVERAGES];
74 static osg::ref_ptr<osg::StateSet> layer_states2[SGCloudLayer::SG_MAX_CLOUD_COVERAGES];
75 static osg::ref_ptr<osg::TextureCubeMap> cubeMap;
76 static bool state_initialized = false;
77 static bool bump_mapping = false;
79 bool SGCloudLayer::enable_bump_mapping = false;
81 // make an StateSet for a cloud layer given the named texture
83 SGMakeState(const SGPath &path, const char* colorTexture,
84 const char* normalTexture)
86 osg::StateSet *stateSet = new osg::StateSet;
88 osg::ref_ptr<osgDB::ReaderWriter::Options> options
89 = makeOptionsFromPath(path);
90 stateSet->setTextureAttribute(0, SGLoadTexture2D(colorTexture,
92 stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::ON);
93 StateAttributeFactory* attribFactory = StateAttributeFactory::instance();
94 stateSet->setTextureAttribute(0, attribFactory->getStandardTexEnv());
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 base = osg::Vec2(sg_random(), sg_random());
159 group_top->addChild(layer_transform.get());
160 group_bottom->addChild(layer_transform.get());
162 layer3D = new SGCloudField;
167 SGCloudLayer::~SGCloudLayer()
173 SGCloudLayer::getSpan_m () const
179 SGCloudLayer::setSpan_m (float span_m)
181 if (span_m != layer_span) {
188 SGCloudLayer::getElevation_m () const
194 SGCloudLayer::setElevation_m (float elevation_m, bool set_span)
196 layer_asl = elevation_m;
199 if (elevation_m > 4000)
200 setSpan_m( elevation_m * 10 );
207 SGCloudLayer::getThickness_m () const
209 return layer_thickness;
213 SGCloudLayer::setThickness_m (float thickness_m)
215 layer_thickness = thickness_m;
219 SGCloudLayer::getTransition_m () const
221 return layer_transition;
225 SGCloudLayer::setTransition_m (float transition_m)
227 layer_transition = transition_m;
230 SGCloudLayer::Coverage
231 SGCloudLayer::getCoverage () const
233 return layer_coverage;
237 SGCloudLayer::setCoverage (Coverage coverage)
239 if (coverage != layer_coverage) {
240 layer_coverage = coverage;
246 SGCloudLayer::setTextureOffset(const osg::Vec2& offset)
248 osg::StateAttribute* attr = layer_root->getStateSet()
249 ->getTextureAttribute(0, osg::StateAttribute::TEXMAT);
250 osg::TexMat* texMat = dynamic_cast<osg::TexMat*>(attr);
253 texMat->setMatrix(osg::Matrix::translate(offset[0], offset[1], 0.0));
256 // build the cloud object
258 SGCloudLayer::rebuild()
260 // Initialize states and sizes if necessary.
261 if ( !state_initialized ) {
262 state_initialized = true;
264 SG_LOG(SG_ASTRO, SG_INFO, "initializing cloud layers");
266 osg::Texture::Extensions* extensions;
267 extensions = osg::Texture::getExtensions(0, true);
269 bump_mapping = extensions->isMultiTexturingSupported() &&
270 (2 <= extensions->numTextureUnits()) &&
271 SGIsOpenGLExtensionSupported("GL_ARB_texture_env_combine") &&
272 SGIsOpenGLExtensionSupported("GL_ARB_texture_env_dot3");
274 osg::TextureCubeMap::Extensions* extensions2;
275 extensions2 = osg::TextureCubeMap::getExtensions(0, true);
276 bump_mapping = bump_mapping && extensions2->isCubeMapSupported();
278 // This bump mapping code was inspired by the tutorial available at
279 // http://www.paulsprojects.net/tutorials/simplebump/simplebump.html
280 // and a NVidia white paper
281 // http://developer.nvidia.com/object/bumpmappingwithregistercombiners.html
282 // The normal map textures were generated by the normal map Gimp plugin :
283 // http://nifelheim.dyndns.org/~cocidius/normalmap/
285 cubeMap = new osg::TextureCubeMap;
286 cubeMap->setFilter(osg::Texture::MIN_FILTER, osg::Texture::LINEAR);
287 cubeMap->setFilter(osg::Texture::MAG_FILTER, osg::Texture::LINEAR);
288 cubeMap->setWrap(osg::Texture::WRAP_S, osg::Texture::CLAMP_TO_EDGE);
289 cubeMap->setWrap(osg::Texture::WRAP_T, osg::Texture::CLAMP_TO_EDGE);
290 cubeMap->setWrap(osg::Texture::WRAP_R, osg::Texture::CLAMP_TO_EDGE);
293 const float half_size = 16.0f;
294 const float offset = 0.5f;
295 osg::Vec3 zero_normal(0.5, 0.5, 0.5);
297 osg::Image* image = new osg::Image;
298 image->allocateImage(size, size, 1, GL_RGB, GL_UNSIGNED_BYTE);
299 unsigned char *ptr = image->data(0, 0);
300 for (int j = 0; j < size; j++ ) {
301 for (int i = 0; i < size; i++ ) {
302 osg::Vec3 tmp(half_size, -( j + offset - half_size ),
303 -( i + offset - half_size ) );
305 tmp = tmp*0.5 - zero_normal;
307 *ptr++ = (unsigned char)( tmp[ 0 ] * 255 );
308 *ptr++ = (unsigned char)( tmp[ 1 ] * 255 );
309 *ptr++ = (unsigned char)( tmp[ 2 ] * 255 );
312 cubeMap->setImage(osg::TextureCubeMap::POSITIVE_X, image);
314 image = new osg::Image;
315 image->allocateImage(size, size, 1, GL_RGB, GL_UNSIGNED_BYTE);
316 ptr = image->data(0, 0);
317 for (int j = 0; j < size; j++ ) {
318 for (int i = 0; i < size; i++ ) {
319 osg::Vec3 tmp(-half_size, -( j + offset - half_size ),
320 ( i + offset - half_size ) );
322 tmp = tmp*0.5 - zero_normal;
324 *ptr++ = (unsigned char)( tmp[ 0 ] * 255 );
325 *ptr++ = (unsigned char)( tmp[ 1 ] * 255 );
326 *ptr++ = (unsigned char)( tmp[ 2 ] * 255 );
329 cubeMap->setImage(osg::TextureCubeMap::NEGATIVE_X, image);
331 image = new osg::Image;
332 image->allocateImage(size, size, 1, GL_RGB, GL_UNSIGNED_BYTE);
333 ptr = image->data(0, 0);
334 for (int j = 0; j < size; j++ ) {
335 for (int i = 0; i < size; i++ ) {
336 osg::Vec3 tmp(( i + offset - half_size ), half_size,
337 ( j + offset - half_size ) );
339 tmp = tmp*0.5 - zero_normal;
341 *ptr++ = (unsigned char)( tmp[ 0 ] * 255 );
342 *ptr++ = (unsigned char)( tmp[ 1 ] * 255 );
343 *ptr++ = (unsigned char)( tmp[ 2 ] * 255 );
346 cubeMap->setImage(osg::TextureCubeMap::POSITIVE_Y, image);
348 image = new osg::Image;
349 image->allocateImage(size, size, 1, GL_RGB, GL_UNSIGNED_BYTE);
350 ptr = image->data(0, 0);
351 for (int j = 0; j < size; j++ ) {
352 for (int i = 0; i < size; i++ ) {
353 osg::Vec3 tmp(( i + offset - half_size ), -half_size,
354 -( j + offset - half_size ) );
356 tmp = tmp*0.5 - zero_normal;
358 *ptr++ = (unsigned char)( tmp[ 0 ] * 255 );
359 *ptr++ = (unsigned char)( tmp[ 1 ] * 255 );
360 *ptr++ = (unsigned char)( tmp[ 2 ] * 255 );
363 cubeMap->setImage(osg::TextureCubeMap::NEGATIVE_Y, image);
365 image = new osg::Image;
366 image->allocateImage(size, size, 1, GL_RGB, GL_UNSIGNED_BYTE);
367 ptr = image->data(0, 0);
368 for (int j = 0; j < size; j++ ) {
369 for (int i = 0; i < size; i++ ) {
370 osg::Vec3 tmp(( i + offset - half_size ),
371 -( j + offset - half_size ), half_size );
373 tmp = tmp*0.5 - zero_normal;
375 *ptr++ = (unsigned char)( tmp[ 0 ] * 255 );
376 *ptr++ = (unsigned char)( tmp[ 1 ] * 255 );
377 *ptr++ = (unsigned char)( tmp[ 2 ] * 255 );
380 cubeMap->setImage(osg::TextureCubeMap::POSITIVE_Z, image);
382 image = new osg::Image;
383 image->allocateImage(size, size, 1, GL_RGB, GL_UNSIGNED_BYTE);
384 ptr = image->data(0, 0);
385 for (int j = 0; j < size; j++ ) {
386 for (int i = 0; i < size; i++ ) {
387 osg::Vec3 tmp(-( i + offset - half_size ),
388 -( j + offset - half_size ), -half_size );
390 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_Z, image);
398 osg::StateSet* state;
399 state = SGMakeState(texture_path, "overcast.rgb", "overcast_n.rgb");
400 layer_states[SG_CLOUD_OVERCAST] = state;
401 state = SGMakeState(texture_path, "overcast_top.rgb", "overcast_top_n.rgb");
402 layer_states2[SG_CLOUD_OVERCAST] = state;
404 state = SGMakeState(texture_path, "broken.rgba", "broken_n.rgb");
405 layer_states[SG_CLOUD_BROKEN] = state;
406 layer_states2[SG_CLOUD_BROKEN] = state;
408 state = SGMakeState(texture_path, "scattered.rgba", "scattered_n.rgb");
409 layer_states[SG_CLOUD_SCATTERED] = state;
410 layer_states2[SG_CLOUD_SCATTERED] = state;
412 state = SGMakeState(texture_path, "few.rgba", "few_n.rgb");
413 layer_states[SG_CLOUD_FEW] = state;
414 layer_states2[SG_CLOUD_FEW] = state;
416 state = SGMakeState(texture_path, "cirrus.rgba", "cirrus_n.rgb");
417 layer_states[SG_CLOUD_CIRRUS] = state;
418 layer_states2[SG_CLOUD_CIRRUS] = state;
420 layer_states[SG_CLOUD_CLEAR] = 0;
421 layer_states2[SG_CLOUD_CLEAR] = 0;
424 // SGNewCloud::loadTextures(texture_path.str());
425 // layer3D->buildTestLayer();
429 last_lon = last_lat = -999.0f;
431 setTextureOffset(base);
432 // build the cloud layer
433 const float layer_scale = layer_span / scale;
434 const float mpi = SG_PI/4;
436 // caclculate the difference between a flat-earth model and
437 // a round earth model given the span and altutude ASL of
438 // the cloud layer. This is the difference in altitude between
439 // the top of the inverted bowl and the edge of the bowl.
440 // const float alt_diff = layer_asl * 0.8;
441 const float layer_to_core = (SG_EARTH_RAD * 1000 + layer_asl);
442 const float layer_angle = 0.5*layer_span / layer_to_core; // The angle is half the span
443 const float border_to_core = layer_to_core * cos(layer_angle);
444 const float alt_diff = layer_to_core - border_to_core;
446 for (int i = 0; i < 4; i++) {
447 if ( layer[i] != NULL ) {
448 layer_transform->removeChild(layer[i].get()); // automatic delete
451 vl[i] = new osg::Vec3Array;
452 cl[i] = new osg::Vec4Array;
453 tl[i] = new osg::Vec2Array;
456 osg::Vec3 vertex(layer_span*(i-2)/2, -layer_span,
457 alt_diff * (sin(i*mpi) - 2));
458 osg::Vec2 tc(layer_scale * i/4, 0.0f);
459 osg::Vec4 color(1.0f, 1.0f, 1.0f, (i == 0) ? 0.0f : 0.15f);
461 cl[i]->push_back(color);
462 vl[i]->push_back(vertex);
463 tl[i]->push_back(tc);
465 for (int j = 0; j < 4; j++) {
466 vertex = osg::Vec3(layer_span*(i-1)/2, layer_span*(j-2)/2,
467 alt_diff * (sin((i+1)*mpi) + sin(j*mpi) - 2));
468 tc = osg::Vec2(layer_scale * (i+1)/4, layer_scale * j/4);
469 color = osg::Vec4(1.0f, 1.0f, 1.0f,
470 ( (j == 0) || (i == 3)) ?
471 ( (j == 0) && (i == 3)) ? 0.0f : 0.15f : 1.0f );
473 cl[i]->push_back(color);
474 vl[i]->push_back(vertex);
475 tl[i]->push_back(tc);
477 vertex = osg::Vec3(layer_span*(i-2)/2, layer_span*(j-1)/2,
478 alt_diff * (sin(i*mpi) + sin((j+1)*mpi) - 2) );
479 tc = osg::Vec2(layer_scale * i/4, layer_scale * (j+1)/4 );
480 color = osg::Vec4(1.0f, 1.0f, 1.0f,
481 ((j == 3) || (i == 0)) ?
482 ((j == 3) && (i == 0)) ? 0.0f : 0.15f : 1.0f );
483 cl[i]->push_back(color);
484 vl[i]->push_back(vertex);
485 tl[i]->push_back(tc);
488 vertex = osg::Vec3(layer_span*(i-1)/2, layer_span,
489 alt_diff * (sin((i+1)*mpi) - 2));
491 tc = osg::Vec2(layer_scale * (i+1)/4, layer_scale);
493 color = osg::Vec4(1.0f, 1.0f, 1.0f, (i == 3) ? 0.0f : 0.15f );
495 cl[i]->push_back( color );
496 vl[i]->push_back( vertex );
497 tl[i]->push_back( tc );
499 osg::Geometry* geometry = new osg::Geometry;
500 geometry->setUseDisplayList(false);
501 geometry->setVertexArray(vl[i].get());
502 geometry->setNormalBinding(osg::Geometry::BIND_OFF);
503 geometry->setColorArray(cl[i].get());
504 geometry->setColorBinding(osg::Geometry::BIND_PER_VERTEX);
505 geometry->setTexCoordArray(0, tl[i].get());
506 geometry->addPrimitiveSet(new osg::DrawArrays(GL_TRIANGLE_STRIP, 0, vl[i]->size()));
507 layer[i] = new osg::Geode;
509 std::stringstream sstr;
510 sstr << "Cloud Layer (" << i << ")";
511 geometry->setName(sstr.str());
512 layer[i]->setName(sstr.str());
513 layer[i]->addDrawable(geometry);
514 layer_transform->addChild(layer[i].get());
518 if ( layer_states[layer_coverage].valid() ) {
519 osg::CopyOp copyOp(osg::CopyOp::DEEP_COPY_ALL
520 & ~osg::CopyOp::DEEP_COPY_TEXTURES);
521 // render bin will be set in reposition
522 osg::StateSet* stateSet = static_cast<osg::StateSet*>(layer_states2[layer_coverage]->clone(copyOp));
523 stateSet->setDataVariance(osg::Object::DYNAMIC);
524 group_top->setStateSet(stateSet);
525 stateSet = static_cast<osg::StateSet*>(layer_states2[layer_coverage]->clone(copyOp));
526 stateSet->setDataVariance(osg::Object::DYNAMIC);
527 group_bottom->setStateSet(stateSet);
535 ssgGetModelviewMatrix( modelview );
536 layer_transform->getTransform( transform );
538 sgTransposeNegateMat4( tmp, transform );
540 sgPostMultMat4( transform, modelview );
541 ssgLoadModelviewMatrix( transform );
544 ssgGetLight( 0 )->getPosition( lightVec );
545 sgNegateVec3( lightVec );
546 sgXformVec3( lightVec, tmp );
548 for ( int i = 0; i < 25; i++ ) {
549 CloudVertex &v = vertices[ i ];
550 sgSetVec3( v.tangentSpLight,
551 sgScalarProductVec3( v.sTangent, lightVec ),
552 sgScalarProductVec3( v.tTangent, lightVec ),
553 sgScalarProductVec3( v.normal, lightVec ) );
556 ssgTexture *decal = color_map[ layer_coverage ][ top ? 1 : 0 ];
557 if ( top && decal == 0 ) {
558 decal = color_map[ layer_coverage ][ 0 ];
560 ssgTexture *normal = normal_map[ layer_coverage ][ top ? 1 : 0 ];
561 if ( top && normal == 0 ) {
562 normal = normal_map[ layer_coverage ][ 0 ];
565 glDisable( GL_LIGHTING );
566 glDisable( GL_CULL_FACE );
567 // glDisable( GL_ALPHA_TEST );
568 if ( layer_coverage == SG_CLOUD_FEW ) {
569 glEnable( GL_ALPHA_TEST );
570 glAlphaFunc ( GL_GREATER, 0.01 );
572 glEnable( GL_BLEND );
573 glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
575 glShadeModel( GL_SMOOTH );
576 glEnable( GL_COLOR_MATERIAL );
580 ssgGetLight( 0 )->getColour( GL_DIFFUSE, color );
581 emis = ( color[0]+color[1]+color[2] ) / 3.0;
585 sgSetVec4( color, emis, emis, emis, 0.0 );
586 glMaterialfv( GL_FRONT_AND_BACK, GL_EMISSION, color );
587 sgSetVec4( color, 1.0f, 1.0f, 1.0f, 0.0 );
588 glMaterialfv( GL_FRONT_AND_BACK, GL_AMBIENT, color );
589 sgSetVec4( color, 1.0, 1.0, 1.0, 0.0 );
590 glMaterialfv( GL_FRONT_AND_BACK, GL_DIFFUSE, color );
591 sgSetVec4( color, 0.0, 0.0, 0.0, 0.0 );
592 glMaterialfv( GL_FRONT_AND_BACK, GL_SPECULAR, color );
594 glColor4f( 1.0f, 1.0f, 1.0f, 1.0f );
596 glActiveTexturePtr( GL_TEXTURE0_ARB );
597 glBindTexture( GL_TEXTURE_2D, normal->getHandle() );
598 glEnable( GL_TEXTURE_2D );
600 //Bind normalisation cube map to texture unit 1
601 glActiveTexturePtr( GL_TEXTURE1_ARB );
602 glBindTexture( GL_TEXTURE_CUBE_MAP_ARB, normalization_cube_map );
603 glEnable( GL_TEXTURE_CUBE_MAP_ARB );
604 glActiveTexturePtr( GL_TEXTURE0_ARB );
606 //Set vertex arrays for cloud
607 glVertexPointer( 3, GL_FLOAT, sizeof(CloudVertex), &vertices[0].position );
608 glEnableClientState( GL_VERTEX_ARRAY );
610 if ( nb_texture_unit >= 3 ) {
611 glColorPointer( 4, GL_FLOAT, sizeof(CloudVertex), &vertices[0].color );
612 glEnableClientState( GL_COLOR_ARRAY );
615 //Send texture coords for normal map to unit 0
616 glTexCoordPointer( 2, GL_FLOAT, sizeof(CloudVertex), &vertices[0].texCoord );
617 glEnableClientState( GL_TEXTURE_COORD_ARRAY );
619 //Send tangent space light vectors for normalisation to unit 1
620 glClientActiveTexturePtr( GL_TEXTURE1_ARB );
621 glTexCoordPointer( 3, GL_FLOAT, sizeof(CloudVertex), &vertices[0].tangentSpLight );
622 glEnableClientState( GL_TEXTURE_COORD_ARRAY );
624 //Set up texture environment to do (tex0 dot tex1)*color
625 glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_ARB );
626 glTexEnvi( GL_TEXTURE_ENV, GL_SOURCE0_RGB_ARB, GL_TEXTURE );
627 glTexEnvi( GL_TEXTURE_ENV, GL_COMBINE_RGB_ARB, GL_REPLACE );
628 glTexEnvi( GL_TEXTURE_ENV, GL_SOURCE0_ALPHA_ARB, GL_TEXTURE );
629 glTexEnvi( GL_TEXTURE_ENV, GL_COMBINE_ALPHA_ARB, GL_REPLACE );
631 // use TexEnvCombine to add the highlights to the original lighting
632 osg::TexEnvCombine *te = new osg::TexEnvCombine;
633 te->setSource0_RGB(osg::TexEnvCombine::TEXTURE);
634 te->setCombine_RGB(osg::TexEnvCombine::REPLACE);
635 te->setSource0_Alpha(osg::TexEnvCombine::TEXTURE);
636 te->setCombine_Alpha(osg::TexEnvCombine::REPLACE);
637 ss->setTextureAttributeAndModes(0, te, osg::StateAttribute::OVERRIDE | osg::StateAttribute::ON);
640 glActiveTexturePtr( GL_TEXTURE1_ARB );
642 glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_ARB );
643 glTexEnvi( GL_TEXTURE_ENV, GL_SOURCE0_RGB_ARB, GL_TEXTURE );
644 glTexEnvi( GL_TEXTURE_ENV, GL_COMBINE_RGB_ARB, GL_DOT3_RGB_ARB );
645 glTexEnvi( GL_TEXTURE_ENV, GL_SOURCE1_RGB_ARB, GL_PREVIOUS_ARB );
646 glTexEnvi( GL_TEXTURE_ENV, GL_SOURCE0_ALPHA_ARB, GL_PREVIOUS_ARB );
647 glTexEnvi( GL_TEXTURE_ENV, GL_COMBINE_ALPHA_ARB, GL_REPLACE );
649 osg::TexEnvCombine *te = new osg::TexEnvCombine;
650 te->setSource0_RGB(osg::TexEnvCombine::TEXTURE);
651 te->setCombine_RGB(osg::TexEnvCombine::DOT3_RGB);
652 te->setSource1_RGB(osg::TexEnvCombine::PREVIOUS);
653 te->setSource0_Alpha(osg::TexEnvCombine::PREVIOUS);
654 te->setCombine_Alpha(osg::TexEnvCombine::REPLACE);
655 ss->setTextureAttributeAndModes(0, te, osg::StateAttribute::OVERRIDE | osg::StateAttribute::ON);
658 if ( nb_texture_unit >= 3 ) {
659 glActiveTexturePtr( GL_TEXTURE2_ARB );
660 glBindTexture( GL_TEXTURE_2D, decal->getHandle() );
662 glClientActiveTexturePtr( GL_TEXTURE2_ARB );
663 glTexCoordPointer( 2, GL_FLOAT, sizeof(CloudVertex), &vertices[0].texCoord );
664 glEnableClientState( GL_TEXTURE_COORD_ARRAY );
666 glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_ARB );
667 glTexEnvi( GL_TEXTURE_ENV, GL_COMBINE_RGB_ARB, GL_ADD );
668 glTexEnvi( GL_TEXTURE_ENV, GL_SOURCE0_RGB_ARB, GL_TEXTURE );
669 glTexEnvi( GL_TEXTURE_ENV, GL_SOURCE1_RGB_ARB, GL_PREVIOUS_ARB );
671 glClientActiveTexturePtr( GL_TEXTURE0_ARB );
672 glActiveTexturePtr( GL_TEXTURE0_ARB );
675 glDrawElements( GL_TRIANGLE_STRIP, 10, GL_UNSIGNED_INT, &indices[0] );
676 glDrawElements( GL_TRIANGLE_STRIP, 10, GL_UNSIGNED_INT, &indices[10] );
677 glDrawElements( GL_TRIANGLE_STRIP, 10, GL_UNSIGNED_INT, &indices[20] );
678 glDrawElements( GL_TRIANGLE_STRIP, 10, GL_UNSIGNED_INT, &indices[30] );
680 glDisable( GL_TEXTURE_2D );
681 glActiveTexturePtr( GL_TEXTURE1_ARB );
682 glDisable( GL_TEXTURE_CUBE_MAP_ARB );
683 glActiveTexturePtr( GL_TEXTURE2_ARB );
684 glDisable( GL_TEXTURE_2D );
685 glActiveTexturePtr( GL_TEXTURE0_ARB );
687 glDisableClientState( GL_TEXTURE_COORD_ARRAY );
688 glClientActiveTexturePtr( GL_TEXTURE1_ARB );
689 glDisableClientState( GL_TEXTURE_COORD_ARRAY );
690 glClientActiveTexturePtr( GL_TEXTURE2_ARB );
691 glDisableClientState( GL_TEXTURE_COORD_ARRAY );
692 glClientActiveTexturePtr( GL_TEXTURE0_ARB );
694 glDisableClientState( GL_COLOR_ARRAY );
695 glEnable( GL_LIGHTING );
697 glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE );
700 glClientActiveTexturePtr( GL_TEXTURE0_ARB );
701 glActiveTexturePtr( GL_TEXTURE0_ARB );
704 glDrawElements( GL_TRIANGLE_STRIP, 10, GL_UNSIGNED_INT, &indices[0] );
705 glDrawElements( GL_TRIANGLE_STRIP, 10, GL_UNSIGNED_INT, &indices[10] );
706 glDrawElements( GL_TRIANGLE_STRIP, 10, GL_UNSIGNED_INT, &indices[20] );
707 glDrawElements( GL_TRIANGLE_STRIP, 10, GL_UNSIGNED_INT, &indices[30] );
710 glDisable( GL_TEXTURE_2D );
712 glActiveTexturePtr( GL_TEXTURE1_ARB );
713 glDisable( GL_TEXTURE_CUBE_MAP_ARB );
714 glActiveTexturePtr( GL_TEXTURE0_ARB );
716 //disable vertex arrays
717 glDisableClientState( GL_VERTEX_ARRAY );
719 glDisableClientState( GL_TEXTURE_COORD_ARRAY );
720 glClientActiveTexturePtr( GL_TEXTURE1_ARB );
721 glDisableClientState( GL_TEXTURE_COORD_ARRAY );
722 glClientActiveTexturePtr( GL_TEXTURE0_ARB );
724 //Return to standard modulate texenv
725 glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE );
727 if ( layer_coverage == SG_CLOUD_OVERCAST ) {
728 glDepthFunc(GL_LEQUAL);
730 glEnable( GL_LIGHTING );
732 ssgGetLight( 0 )->getColour( GL_DIFFUSE, color );
733 float average = ( color[0] + color[1] + color[2] ) / 3.0f;
734 average = 0.15 + average/10;
736 sgSetVec4( averageColor, average, average, average, 1.0f );
737 ssgGetLight( 0 )->setColour( GL_DIFFUSE, averageColor );
739 glBlendColorPtr( average, average, average, 1.0f );
740 glBlendFunc( GL_ONE_MINUS_CONSTANT_COLOR, GL_CONSTANT_COLOR );
742 //Perform a second pass to color the torus
744 glBindTexture( GL_TEXTURE_2D, decal->getHandle() );
745 glEnable(GL_TEXTURE_2D);
747 //Set vertex arrays for torus
748 glVertexPointer( 3, GL_FLOAT, sizeof(CloudVertex), &vertices[0].position );
749 glEnableClientState( GL_VERTEX_ARRAY );
751 //glColorPointer( 4, GL_FLOAT, sizeof(CloudVertex), &vertices[0].color );
752 //glEnableClientState( GL_COLOR_ARRAY );
754 glNormalPointer( GL_FLOAT, sizeof(CloudVertex), &vertices[0].normal );
755 glEnableClientState( GL_NORMAL_ARRAY );
757 glTexCoordPointer( 2, GL_FLOAT, sizeof(CloudVertex), &vertices[0].texCoord );
758 glEnableClientState( GL_TEXTURE_COORD_ARRAY );
761 glDrawElements( GL_TRIANGLE_STRIP, 10, GL_UNSIGNED_INT, &indices[0] );
762 glDrawElements( GL_TRIANGLE_STRIP, 10, GL_UNSIGNED_INT, &indices[10] );
763 glDrawElements( GL_TRIANGLE_STRIP, 10, GL_UNSIGNED_INT, &indices[20] );
764 glDrawElements( GL_TRIANGLE_STRIP, 10, GL_UNSIGNED_INT, &indices[30] );
766 ssgGetLight( 0 )->setColour( GL_DIFFUSE, color );
768 glDisableClientState( GL_TEXTURE_COORD_ARRAY );
772 glDisable( GL_TEXTURE_2D );
774 glDisableClientState( GL_VERTEX_ARRAY );
775 glDisableClientState( GL_NORMAL_ARRAY );
777 glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
778 glEnable( GL_CULL_FACE );
779 glDepthFunc(GL_LESS);
781 ssgLoadModelviewMatrix( modelview );
784 // repaint the cloud layer colors
785 bool SGCloudLayer::repaint( const SGVec3f& fog_color ) {
786 for ( int i = 0; i < 4; i++ ) {
787 osg::Vec4 color(fog_color.osg(), 1);
788 color[3] = (i == 0) ? 0.0f : cloud_alpha * 0.15f;
791 for ( int j = 0; j < 4; ++j ) {
793 ((j == 0) || (i == 3)) ?
794 ((j == 0) && (i == 3)) ? 0.0f : cloud_alpha * 0.15f : cloud_alpha;
795 (*cl[i])[(2*j) + 1] = color;
798 ((j == 3) || (i == 0)) ?
799 ((j == 3) && (i == 0)) ? 0.0f : cloud_alpha * 0.15f : cloud_alpha;
800 (*cl[i])[(2*j) + 2] = color;
803 color[3] = (i == 3) ? 0.0f : cloud_alpha * 0.15f;
812 // reposition the cloud layer at the specified origin and orientation
813 // lon specifies a rotation about the Z axis
814 // lat specifies a rotation about the new Y axis
815 // spin specifies a rotation about the new Z axis (and orients the
816 // sunrise/set effects
817 bool SGCloudLayer::reposition( const SGVec3f& p, const SGVec3f& up, double lon, double lat,
818 double alt, double dt )
820 // combine p and asl (meters) to get translation offset
821 osg::Vec3 asl_offset(up.osg());
822 asl_offset.normalize();
823 if ( alt <= layer_asl ) {
824 asl_offset *= layer_asl;
826 asl_offset *= layer_asl + layer_thickness;
829 // cout << "asl_offset = " << asl_offset[0] << "," << asl_offset[1]
830 // << "," << asl_offset[2] << endl;
831 asl_offset += p.osg();
832 // cout << " asl_offset = " << asl_offset[0] << "," << asl_offset[1]
833 // << "," << asl_offset[2] << endl;
835 osg::Matrix T, LON, LAT;
836 // Translate to zero elevation
837 // Point3D zero_elev = current_view.get_cur_zero_elev();
838 T.makeTranslate( asl_offset );
840 // printf(" Translated to %.2f %.2f %.2f\n",
841 // zero_elev.x, zero_elev.y, zero_elev.z );
843 // Rotate to proper orientation
844 // printf(" lon = %.2f lat = %.2f\n",
845 // lon * SGD_RADIANS_TO_DEGREES,
846 // lat * SGD_RADIANS_TO_DEGREES);
847 LON.makeRotate(lon, osg::Vec3(0, 0, 1));
849 // xglRotatef( 90.0 - f->get_Latitude() * SGD_RADIANS_TO_DEGREES,
851 LAT.makeRotate(90.0 * SGD_DEGREES_TO_RADIANS - lat, osg::Vec3(0, 1, 0));
853 layer_transform->setMatrix( LAT*LON*T );
854 // The layers need to be drawn in order because they are
855 // translucent, but OSG transparency sorting doesn't work because
856 // the cloud polys are huge. However, the ordering is simple: the
857 // bottom polys should be drawn from high altitude to low, and the
858 // top polygons from low to high. The altitude can be used
859 // directly to order the polygons!
860 group_bottom->getStateSet()->setRenderBinDetails(-(int)layer_asl,
862 group_top->getStateSet()->setRenderBinDetails((int)layer_asl,
864 if ( alt <= layer_asl ) {
865 layer_root->setSingleChildOn(0);
866 } else if ( alt >= layer_asl + layer_thickness ) {
867 layer_root->setSingleChildOn(1);
869 layer_root->setAllChildrenOff();
873 // now calculate update texture coordinates
874 if ( last_lon < -900 ) {
879 double sp_dist = speed*dt;
881 if ( lon != last_lon || lat != last_lat || sp_dist != 0 ) {
882 Point3D start( last_lon, last_lat, 0.0 );
883 Point3D dest( lon, lat, 0.0 );
884 double course = 0.0, dist = 0.0;
886 calc_gc_course_dist( dest, start, &course, &dist );
887 // cout << "course = " << course << ", dist = " << dist << endl;
889 // if start and dest are too close together,
890 // calc_gc_course_dist() can return a course of "nan". If
891 // this happens, lets just use the last known good course.
892 // This is a hack, and it would probably be better to make
893 // calc_gc_course_dist() more robust.
894 if ( isnan(course) ) {
895 course = last_course;
897 last_course = course;
900 // calculate cloud movement due to external forces
901 double ax = 0.0, ay = 0.0, bx = 0.0, by = 0.0;
904 ax = cos(course) * dist;
905 ay = sin(course) * dist;
909 bx = cos((180.0-direction) * SGD_DEGREES_TO_RADIANS) * sp_dist;
910 by = sin((180.0-direction) * SGD_DEGREES_TO_RADIANS) * sp_dist;
914 double xoff = (ax + bx) / (2 * scale);
915 double yoff = (ay + by) / (2 * scale);
917 const float layer_scale = layer_span / scale;
919 // cout << "xoff = " << xoff << ", yoff = " << yoff << endl;
922 // the while loops can lead to *long* pauses if base[0] comes
923 // with a bogus value.
924 // while ( base[0] > 1.0 ) { base[0] -= 1.0; }
925 // while ( base[0] < 0.0 ) { base[0] += 1.0; }
926 if ( base[0] > -10.0 && base[0] < 10.0 ) {
927 base[0] -= (int)base[0];
929 SG_LOG(SG_ASTRO, SG_DEBUG,
930 "Error: base = " << base[0] << "," << base[1] <<
931 " course = " << course << " dist = " << dist );
936 // the while loops can lead to *long* pauses if base[0] comes
937 // with a bogus value.
938 // while ( base[1] > 1.0 ) { base[1] -= 1.0; }
939 // while ( base[1] < 0.0 ) { base[1] += 1.0; }
940 if ( base[1] > -10.0 && base[1] < 10.0 ) {
941 base[1] -= (int)base[1];
943 SG_LOG(SG_ASTRO, SG_DEBUG,
944 "Error: base = " << base[0] << "," << base[1] <<
945 " course = " << course << " dist = " << dist );
949 // cout << "base = " << base[0] << "," << base[1] << endl;
951 setTextureOffset(base);
956 // layer3D->reposition( p, up, lon, lat, alt, dt, direction, speed);