1 // oursun.hxx -- model earth's sun
3 // Written by Durk Talsma. Originally started October 1997, for distribution
4 // with the FlightGear project. Version 2 was written in August and
5 // September 1998. This code is based upon algorithms and data kindly
6 // provided by Mr. Paul Schlyter. (pausch@saaf.se).
8 // Separated out rendering pieces and converted to ssg by Curt Olson,
10 // This library is free software; you can redistribute it and/or
11 // modify it under the terms of the GNU Library General Public
12 // License as published by the Free Software Foundation; either
13 // version 2 of the License, or (at your option) any later version.
15 // This library is distributed in the hope that it will be useful,
16 // but WITHOUT ANY WARRANTY; without even the implied warranty of
17 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 // Library General Public License for more details.
20 // You should have received a copy of the GNU General Public License
21 // along with this program; if not, write to the Free Software
22 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
28 # include <simgear_config.h>
31 #include <simgear/compiler.h>
36 // define the following to enable a cheesy lens flare effect for the sun
37 // #define FG_TEST_CHEESY_LENS_FLARE
39 #ifdef FG_TEST_CHEESY_LENS_FLARE
40 # include <plib/ssgaLensFlare.h>
43 #include <simgear/screen/colors.hxx>
47 static double sun_exp2_punch_through;
49 // Set up sun rendering call backs
50 static int sgSunPreDraw( ssgEntity *e ) {
51 /* cout << endl << "Sun orb pre draw" << endl << "----------------"
54 ssgLeaf *f = (ssgLeaf *)e;
55 if ( f -> hasState () ) f->getState()->apply() ;
57 glPushAttrib( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_FOG_BIT );
58 // cout << "push error = " << glGetError() << endl;
60 glDisable( GL_DEPTH_TEST );
62 glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
66 static int sgSunPostDraw( ssgEntity *e ) {
67 /* cout << endl << "Sun orb post draw" << endl << "----------------"
71 // cout << "pop error = " << glGetError() << endl;
76 static int sgSunHaloPreDraw( ssgEntity *e ) {
77 /* cout << endl << "Sun halo pre draw" << endl << "----------------"
80 ssgLeaf *f = (ssgLeaf *)e;
81 if ( f -> hasState () ) f->getState()->apply() ;
83 glPushAttrib( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_FOG_BIT );
84 // cout << "push error = " << glGetError() << endl;
86 glDisable( GL_DEPTH_TEST );
87 // glDisable( GL_FOG );
88 glFogf (GL_FOG_DENSITY, sun_exp2_punch_through);
89 glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
94 static int sgSunHaloPostDraw( ssgEntity *e ) {
95 /* cout << endl << "Sun halo post draw" << endl << "----------------"
99 // cout << "pop error = " << glGetError() << endl;
106 SGSun::SGSun( void ) {
107 prev_sun_angle = -9999.0;
108 visibility = -9999.0;
113 SGSun::~SGSun( void ) {
118 // this might be nice to keep, just as an example of how to generate a
119 // texture on the fly ...
120 static GLuint makeHalo( GLubyte *sun_texbuf, int width ) {
127 // create a texture id
128 #ifdef GL_VERSION_1_1
129 glGenTextures(1, &texid);
130 glBindTexture(GL_TEXTURE_2D, texid);
131 #elif GL_EXT_texture_object
132 glGenTexturesEXT(1, &texid);
133 glBindTextureEXT(GL_TEXTURE_2D, texid);
138 glPixelStorei( GL_UNPACK_ALIGNMENT, 4 );
139 glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
140 glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
141 glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
143 // create the actual texture contents
144 texSize = width * width;
147 SG_LOG( SG_EVENT, SG_ALERT,
148 "Could not allocate memroy for the sun texture");
154 radius = (double)(width / 2);
158 for ( i = 0; i < width; i++ ) {
159 for ( j = 0; j < width; j++ ) {
160 x = fabs((double)(i - (width / 2)));
161 y = fabs((double)(j - (width / 2)));
162 d = sqrt((x * x) + (y * y));
164 // t is 1.0 at center, 0.0 at edge
165 double t = 1.0 - (d / radius);
167 // inverse square looks nice
168 value = (int)((double) 0xff * (t*t));
181 /* glTexImage2D( GL_TEXTURE_2D,
186 GL_RGBA, GL_UNSIGNED_BYTE,
193 #define RGB 3 // 3 bytes of color info per pixel
194 #define RGBA 4 // 4 bytes of color+alpha info
195 void my_glWritePPMFile(const char *filename, GLubyte *buffer, int win_width, int win_height, int mode)
198 unsigned char *ibuffer;
200 int pixelSize = mode==GL_RGBA?4:3;
202 ibuffer = (unsigned char *) malloc(win_width*win_height*RGB);
204 fp = fopen(filename, "wb");
205 fprintf(fp, "P6\n# CREATOR: glReadPixel()\n%d %d\n%d\n",
206 win_width, win_height, UCHAR_MAX);
208 for (i = 0; i < win_height; i++) {
209 for (j = 0; j < win_width; j++) {
210 for (k = 0; k < RGB; k++) {
211 ibuffer[q++] = (unsigned char)
212 *(buffer + (pixelSize*((win_height-1-i)*win_width+j)+k));
217 // *(buffer + (pixelSize*((win_height-1-i)*win_width+j)+k));
219 fwrite(ibuffer, sizeof(unsigned char), RGB*win_width*win_height, fp);
223 printf("wrote file (%d x %d pixels, %d bytes)\n",
224 win_width, win_height, RGB*win_width*win_height);
228 // initialize the sun object and connect it into our scene graph root
229 ssgBranch * SGSun::build( SGPath path, double sun_size, SGPropertyNode *property_tree_Node ) {
231 env_node = property_tree_Node;
233 SGPath ihalopath = path, ohalopath = path;
236 sgSetVec4( color, 1.0, 1.0, 1.0, 1.0 );
238 sun_cl = new ssgColourArray( 1 );
239 sun_cl->add( color );
241 ihalo_cl = new ssgColourArray( 1 );
242 ihalo_cl->add( color );
244 ohalo_cl = new ssgColourArray( 1 );
245 ohalo_cl->add( color );
247 // force a repaint of the sun colors with arbitrary defaults
251 // set up the sun-state
252 path.append( "sun.rgba" );
253 sun_state = new ssgSimpleState();
254 sun_state->setShadeModel( GL_SMOOTH );
255 sun_state->disable( GL_LIGHTING );
256 sun_state->disable( GL_CULL_FACE );
257 sun_state->setTexture( (char *)path.c_str() );
258 sun_state->enable( GL_TEXTURE_2D );
259 sun_state->enable( GL_COLOR_MATERIAL );
260 sun_state->setColourMaterial( GL_AMBIENT_AND_DIFFUSE );
261 sun_state->setMaterial( GL_EMISSION, 0, 0, 0, 1 );
262 sun_state->setMaterial( GL_SPECULAR, 0, 0, 0, 1 );
263 sun_state->enable( GL_BLEND );
264 sun_state->setAlphaClamp( 0.01 );
265 sun_state->enable( GL_ALPHA_TEST );
267 // Build ssg structure
270 sun_vl = new ssgVertexArray;
271 sgSetVec3( va, -sun_size, 0.0, -sun_size );
273 sgSetVec3( va, sun_size, 0.0, -sun_size );
275 sgSetVec3( va, -sun_size, 0.0, sun_size );
277 sgSetVec3( va, sun_size, 0.0, sun_size );
281 sun_tl = new ssgTexCoordArray;
282 sgSetVec2( vb, 0.0f, 0.0f );
284 sgSetVec2( vb, 1.0, 0.0 );
286 sgSetVec2( vb, 0.0, 1.0 );
288 sgSetVec2( vb, 1.0, 1.0 );
293 new ssgVtxTable ( GL_TRIANGLE_STRIP, sun_vl, NULL, sun_tl, sun_cl );
294 sun->setState( sun_state );
296 sun->setCallback( SSG_CALLBACK_PREDRAW, sgSunPreDraw );
297 sun->setCallback( SSG_CALLBACK_POSTDRAW, sgSunPostDraw );
302 // sun_texbuf = new GLubyte[64*64*3];
303 // sun_texid = makeHalo( sun_texbuf, 64 );
304 // my_glWritePPMFile("sunhalo.ppm", sun_texbuf, 64, 64, RGB);
306 // set up the inner-halo state
308 ihalopath.append( "inner_halo.rgba" );
310 ihalo_state = new ssgSimpleState();
311 ihalo_state->setTexture( (char *)ihalopath.c_str() );
312 ihalo_state->enable( GL_TEXTURE_2D );
313 ihalo_state->disable( GL_LIGHTING );
314 ihalo_state->setShadeModel( GL_SMOOTH );
315 ihalo_state->disable( GL_CULL_FACE );
316 ihalo_state->enable( GL_COLOR_MATERIAL );
317 ihalo_state->setColourMaterial( GL_AMBIENT_AND_DIFFUSE );
318 ihalo_state->setMaterial( GL_EMISSION, 0, 0, 0, 1 );
319 ihalo_state->setMaterial( GL_SPECULAR, 0, 0, 0, 1 );
320 ihalo_state->enable( GL_ALPHA_TEST );
321 ihalo_state->setAlphaClamp(0.01);
322 ihalo_state->enable ( GL_BLEND ) ;
324 // Build ssg structure
325 double ihalo_size = sun_size * 2.0;
327 ihalo_vl = new ssgVertexArray;
328 sgSetVec3( vc, -ihalo_size, 0.0, -ihalo_size );
330 sgSetVec3( vc, ihalo_size, 0.0, -ihalo_size );
332 sgSetVec3( vc, -ihalo_size, 0.0, ihalo_size );
334 sgSetVec3( vc, ihalo_size, 0.0, ihalo_size );
338 ihalo_tl = new ssgTexCoordArray;
339 sgSetVec2( vd, 0.0f, 0.0f );
341 sgSetVec2( vd, 1.0, 0.0 );
343 sgSetVec2( vd, 0.0, 1.0 );
345 sgSetVec2( vd, 1.0, 1.0 );
349 new ssgVtxTable ( GL_TRIANGLE_STRIP, ihalo_vl, NULL, ihalo_tl, ihalo_cl );
350 ihalo->setState( ihalo_state );
353 // set up the outer halo state
355 ohalopath.append( "outer_halo.rgba" );
357 ohalo_state = new ssgSimpleState();
358 ohalo_state->setTexture( (char *)ohalopath.c_str() );
359 ohalo_state->enable( GL_TEXTURE_2D );
360 ohalo_state->disable( GL_LIGHTING );
361 ohalo_state->setShadeModel( GL_SMOOTH );
362 ohalo_state->disable( GL_CULL_FACE );
363 ohalo_state->enable( GL_COLOR_MATERIAL );
364 ohalo_state->setColourMaterial( GL_AMBIENT_AND_DIFFUSE );
365 ohalo_state->setMaterial( GL_EMISSION, 0, 0, 0, 1 );
366 ohalo_state->setMaterial( GL_SPECULAR, 0, 0, 0, 1 );
367 ohalo_state->enable( GL_ALPHA_TEST );
368 ohalo_state->setAlphaClamp(0.01);
369 ohalo_state->enable ( GL_BLEND ) ;
371 // Build ssg structure
372 double ohalo_size = sun_size * 7.0;
374 ohalo_vl = new ssgVertexArray;
375 sgSetVec3( ve, -ohalo_size, 0.0, -ohalo_size );
377 sgSetVec3( ve, ohalo_size, 0.0, -ohalo_size );
379 sgSetVec3( ve, -ohalo_size, 0.0, ohalo_size );
381 sgSetVec3( ve, ohalo_size, 0.0, ohalo_size );
385 ohalo_tl = new ssgTexCoordArray;
386 sgSetVec2( vf, 0.0f, 0.0f );
388 sgSetVec2( vf, 1.0, 0.0 );
390 sgSetVec2( vf, 0.0, 1.0 );
392 sgSetVec2( vf, 1.0, 1.0 );
396 new ssgVtxTable ( GL_TRIANGLE_STRIP, ohalo_vl, NULL, ohalo_tl, ohalo_cl );
397 ohalo->setState( ohalo_state );
400 // build the ssg scene graph sub tree for the sky and connected
401 // into the provide scene graph branch
402 sun_transform = new ssgTransform;
404 ihalo->setCallback( SSG_CALLBACK_PREDRAW, sgSunHaloPreDraw );
405 ihalo->setCallback( SSG_CALLBACK_POSTDRAW, sgSunHaloPostDraw );
406 ohalo->setCallback( SSG_CALLBACK_PREDRAW, sgSunHaloPreDraw );
407 ohalo->setCallback( SSG_CALLBACK_POSTDRAW, sgSunHaloPostDraw );
409 sun_transform->addKid( ohalo );
410 sun_transform->addKid( ihalo );
411 sun_transform->addKid( sun );
413 #ifdef FG_TEST_CHEESY_LENS_FLARE
415 sun_transform->addKid( new ssgaLensFlare );
418 return sun_transform;
422 // repaint the sun colors based on current value of sun_angle in
423 // degrees relative to verticle
424 // 0 degrees = high noon
425 // 90 degrees = sun rise/set
426 // 180 degrees = darkest midnight
427 bool SGSun::repaint( double sun_angle, double new_visibility ) {
429 if ( visibility != new_visibility ) {
430 visibility = new_visibility;
432 static const double sqrt_m_log01 = sqrt( -log( 0.01 ) );
433 sun_exp2_punch_through = sqrt_m_log01 / ( visibility * 15 );
436 if ( prev_sun_angle != sun_angle ) {
437 prev_sun_angle = sun_angle;
439 // determine how much aerosols are in the air (rough guess)
440 double aerosol_factor;
441 if ( visibility < 100 ){
442 aerosol_factor = 8000;
445 aerosol_factor = 80.5 / log( visibility / 100 );
448 // get environmental data from property tree or use defaults
449 double rel_humidity, density_avg;
458 rel_humidity = env_node->getFloatValue( "relative-humidity" );
459 density_avg = env_node->getFloatValue( "atmosphere/density-tropo-avg" );
462 // ok, now let's go and generate the sun color
463 sgVec4 i_halo_color, o_halo_color, sun_color;
466 // When the sunangle changes, light has to travel a longer distance through the atmosphere.
467 // So it's scattered more due to raleigh scattering, which affects blue more than green light.
468 // Red is almost not scattered and effectively only get's touched when the sun is near the horizon.
469 // Visability also affects suncolor inasmuch as more particles are in the air that cause more scattering.
470 // We base our calculation on the halo's color, which is most scattered.
472 // Red - is almost not scattered
475 double red_scat_f = ( aerosol_factor * path_distance * density_avg ) / 5E+07;
476 sun_color[0] = 1 - red_scat_f;
477 i_halo_color[0] = 1 - ( 1.1 * red_scat_f );
478 o_halo_color[0] = 1 - ( 1.4 * red_scat_f );
481 double green_scat_f = ( aerosol_factor * path_distance * density_avg ) / 8.8938E+06;
482 sun_color[1] = 1 - green_scat_f;
483 i_halo_color[1] = 1 - ( 1.1 * green_scat_f );
484 o_halo_color[1] = 1 - ( 1.4 * green_scat_f );
487 double blue_scat_f = ( aerosol_factor * path_distance * density_avg ) / 3.607E+06;
488 sun_color[2] = 1 - blue_scat_f;
489 i_halo_color[2] = 1 - ( 1.1 * blue_scat_f );
490 o_halo_color[2] = 1 - ( 1.4 * blue_scat_f );
496 o_halo_color[3] = blue_scat_f;
497 if ( ( new_visibility < 10000 ) && ( blue_scat_f > 1 )){
498 o_halo_color[3] = 2 - blue_scat_f;
502 // Now that we have the color calculated
503 // let's consider the saturation which is produced by mie scattering
504 double saturation = 1 - ( rel_humidity / 200 );
505 sun_color[1] += (( 1 - saturation ) * ( 1 - sun_color[1] ));
506 sun_color[2] += (( 1 - saturation ) * ( 1 - sun_color[2] ));
508 i_halo_color[1] += (( 1 - saturation ) * ( 1 - i_halo_color[1] ));
509 i_halo_color[2] += (( 1 - saturation ) * ( 1 - i_halo_color[2] ));
511 o_halo_color[1] += (( 1 - saturation ) * ( 1 - o_halo_color[1] ));
512 o_halo_color[2] += (( 1 - saturation ) * ( 1 - o_halo_color[2] ));
514 // just to make sure we're in the limits
515 if ( sun_color[0] < 0 ) sun_color[0] = 0;
516 else if ( sun_color[0] > 1) sun_color[0] = 1;
517 if ( i_halo_color[0] < 0 ) i_halo_color[0] = 0;
518 else if ( i_halo_color[0] > 1) i_halo_color[0] = 1;
519 if ( o_halo_color[0] < 0 ) o_halo_color[0] = 0;
520 else if ( o_halo_color[0] > 1) o_halo_color[0] = 1;
522 if ( sun_color[1] < 0 ) sun_color[1] = 0;
523 else if ( sun_color[1] > 1) sun_color[1] = 1;
524 if ( i_halo_color[1] < 0 ) i_halo_color[1] = 0;
525 else if ( i_halo_color[1] > 1) i_halo_color[1] = 1;
526 if ( o_halo_color[1] < 0 ) o_halo_color[1] = 0;
527 else if ( o_halo_color[1] > 1) o_halo_color[1] = 1;
529 if ( sun_color[2] < 0 ) sun_color[2] = 0;
530 else if ( sun_color[2] > 1) sun_color[2] = 1;
531 if ( i_halo_color[2] < 0 ) i_halo_color[2] = 0;
532 else if ( i_halo_color[2] > 1) i_halo_color[2] = 1;
533 if ( o_halo_color[2] < 0 ) o_halo_color[2] = 0;
534 else if ( o_halo_color[2] > 1) o_halo_color[2] = 1;
535 if ( o_halo_color[3] < 0 ) o_halo_color[2] = 0;
536 else if ( o_halo_color[3] > 1) o_halo_color[3] = 1;
539 gamma_correct_rgb( i_halo_color );
540 gamma_correct_rgb( o_halo_color );
541 gamma_correct_rgb( sun_color );
545 ptr = sun_cl->get( 0 );
546 sgCopyVec4( ptr, sun_color );
547 ptr = ihalo_cl->get( 0 );
548 sgCopyVec4( ptr, i_halo_color );
549 ptr = ohalo_cl->get( 0 );
550 sgCopyVec4( ptr, o_halo_color );
557 // reposition the sun at the specified right ascension and
558 // declination, offset by our current position (p) so that it appears
559 // fixed at a great distance from the viewer. Also add in an optional
560 // rotation (i.e. for the current time of day.)
561 // Then calculate stuff needed for the sun-coloring
562 bool SGSun::reposition( sgVec3 p, double angle,
563 double rightAscension, double declination,
564 double sun_dist, double lat, double alt_asl, double sun_angle)
566 // GST - GMT sidereal time
567 sgMat4 T1, T2, GST, RA, DEC;
571 sgMakeTransMat4( T1, p );
572 sgSetVec3( axis, 0.0, 0.0, -1.0 );
573 sgMakeRotMat4( GST, angle, axis );
575 // xglRotatef( ((SGD_RADIANS_TO_DEGREES * rightAscension)- 90.0),
577 sgSetVec3( axis, 0.0, 0.0, 1.0 );
578 sgMakeRotMat4( RA, (rightAscension * SGD_RADIANS_TO_DEGREES) - 90.0, axis );
580 // xglRotatef((SGD_RADIANS_TO_DEGREES * declination), 1.0, 0.0, 0.0);
581 sgSetVec3( axis, 1.0, 0.0, 0.0 );
582 sgMakeRotMat4( DEC, declination * SGD_RADIANS_TO_DEGREES, axis );
584 // xglTranslatef(0,sun_dist);
585 sgSetVec3( v, 0.0, sun_dist, 0.0 );
586 sgMakeTransMat4( T2, v );
589 sgCopyMat4( TRANSFORM, T1 );
590 sgPreMultMat4( TRANSFORM, GST );
591 sgPreMultMat4( TRANSFORM, RA );
592 sgPreMultMat4( TRANSFORM, DEC );
593 sgPreMultMat4( TRANSFORM, T2 );
596 sgSetCoord( &skypos, TRANSFORM );
598 sun_transform->setTransform( &skypos );
600 // Suncolor related things:
601 if ( prev_sun_angle != sun_angle ) {
602 if ( sun_angle == 0 ) sun_angle = 0.1;
603 const double r_earth_pole = 6356752.314;
604 const double r_tropo_pole = 6356752.314 + 8000;
605 const double epsilon_earth2 = 6.694380066E-3;
606 const double epsilon_tropo2 = 9.170014946E-3;
608 double r_tropo = r_tropo_pole / sqrt ( 1 - ( epsilon_tropo2 * pow ( cos( lat ), 2 )));
609 double r_earth = r_earth_pole / sqrt ( 1 - ( epsilon_earth2 * pow ( cos( lat ), 2 )));
611 double position_radius = r_earth + alt_asl;
613 double gamma = SG_PI - sun_angle;
614 double sin_beta = ( position_radius * sin ( gamma ) ) / r_tropo;
615 double alpha = SG_PI - gamma - asin( sin_beta );
617 // OK, now let's calculate the distance the light travels
618 path_distance = sqrt( pow( position_radius, 2 ) + pow( r_tropo, 2 )
619 - ( 2 * position_radius * r_tropo * cos( alpha ) ));
621 double alt_half = sqrt( pow ( r_tropo, 2 ) + pow( path_distance / 2, 2 ) - r_tropo * path_distance * cos( asin( sin_beta )) ) - r_earth;
623 if ( alt_half < 0.0 ) alt_half = 0.0;
625 // Push the data to the property tree, so it can be used in the enviromental code
627 env_node->setDoubleValue( "atmosphere/altitude-troposphere-top", r_tropo - r_earth );
628 env_node->setDoubleValue( "atmosphere/altitude-half-to-sun", alt_half );