]> git.mxchange.org Git - simgear.git/blob - simgear/scene/sky/dome.cxx
Fix a NaN at higher altitudes: sin_beta could become greater than 1.0 which is hard...
[simgear.git] / simgear / scene / sky / dome.cxx
1 // dome.cxx -- model sky with an upside down "bowl"
2 //
3 // Written by Curtis Olson, started December 1997.
4 // SSG-ified by Curtis Olson, February 2000.
5 //
6 // Copyright (C) 1997-2000  Curtis L. Olson  - http://www.flightgear.org/~curt
7 //
8 // This library is free software; you can redistribute it and/or
9 // modify it under the terms of the GNU Library General Public
10 // License as published by the Free Software Foundation; either
11 // version 2 of the License, or (at your option) any later version.
12 //
13 // This library is distributed in the hope that it will be useful,
14 // but WITHOUT ANY WARRANTY; without even the implied warranty of
15 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16 // Library General Public License for more details.
17 //
18 // You should have received a copy of the GNU General Public License
19 // along with this program; if not, write to the Free Software
20 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
21
22 #ifdef HAVE_CONFIG_H
23 #  include <simgear_config.h>
24 #endif
25
26 #include <math.h>
27
28 #include <simgear/compiler.h>
29
30 #include <osg/Array>
31 #include <osg/Geode>
32 #include <osg/Geometry>
33 #include <osg/Node>
34 #include <osg/Math>
35 #include <osg/MatrixTransform>
36 #include <osg/Material>
37 #include <osg/ShadeModel>
38 #include <osg/PrimitiveSet>
39
40 #include <simgear/debug/logstream.hxx>
41 #include <simgear/math/Math.hxx>
42 #include <simgear/scene/util/VectorArrayAdapter.hxx>
43
44 #include "dome.hxx"
45
46 using namespace osg;
47 using namespace simgear;
48
49 // proportions of max dimensions fed to the build() routine
50 static const float center_elev = 1.0;
51
52 namespace
53 {
54 struct DomeParam
55 {
56     float radius;
57     float elev;
58 } domeParams[] = {{.5, .8660},  // 60deg from horizon
59                   {.8660, .5},  // 30deg from horizon
60                   // Original dome horizon vertices
61                   {0.9701, 0.2425}, {0.9960, 0.0885},
62                   {1.0, 0.0}, {0.9922, -0.1240}};
63
64 const int numRings = sizeof(domeParams) / sizeof(domeParams[0]);
65 const int numBands = 12;
66 }
67
68 static const float upper_radius = 0.9701; // (.6, 0.15)
69 static const float upper_elev = 0.2425;
70
71 static const float middle_radius = 0.9960; // (.9, .08)
72 static const float middle_elev = 0.0885;
73
74 static const float lower_radius = 1.0;
75 static const float lower_elev = 0.0;
76
77 static const float bottom_radius = 0.9922; // (.8, -.1)
78 static const float bottom_elev = -0.1240;
79
80
81 // Constructor
82 SGSkyDome::SGSkyDome( void ) {
83     asl = 0;
84 }
85
86
87 // Destructor
88 SGSkyDome::~SGSkyDome( void ) {
89 }
90
91 // Generate indices for a dome mesh. Assume a center vertex at 0, then
92 // rings of vertices. Each ring's vertices are stored together. An
93 // even number of longitudinal bands are assumed.
94
95 namespace
96 {
97 // Calculate the index of a vertex in the grid by using its address in
98 // the array that holds its location.
99 struct GridIndex
100 {
101     VectorArrayAdapter<Vec3Array> gridAdapter;
102     Vec3Array& grid;
103     GridIndex(Vec3Array& array, int rowStride, int baseOffset) :
104         gridAdapter(array, rowStride, baseOffset), grid(array)
105     {
106     }
107     unsigned short operator() (int ring, int band)
108     {
109         return (unsigned short)(&gridAdapter(ring, band) - &grid[0]);
110     }
111 };
112 }
113 void SGSkyDome::makeDome(int rings, int bands, DrawElementsUShort& elements)
114 {
115     std::back_insert_iterator<DrawElementsUShort> pusher
116         = std::back_inserter(elements);
117     GridIndex grid(*dome_vl, numBands, 1);
118     for (int i = 0; i < bands; i += 2) {
119         *pusher = 0;  *pusher = grid(0, i);  *pusher = grid(0, i + 1);  
120         // down a band
121         for (int j = 0; j < rings - 1; ++j) {
122             *pusher = grid(j, i);  *pusher = grid(j, i + 1);
123             *pusher = grid(j + 1, i + 1);
124             *pusher = grid(j, i);  *pusher =  grid(j + 1, i + 1);
125             *pusher =  grid(j + 1, i);
126         }
127         // and up the next one
128         for (int j = rings - 1; j > 0; --j) {
129             *pusher = grid(j, i + 1);  *pusher = grid(j - 1, i + 1);
130             *pusher = grid(j, (i + 2) % bands);
131             *pusher = grid(j, (i + 2) % bands); *pusher = grid(j - 1, i + 1);
132             *pusher = grid(j - 1, (i + 2) % bands);
133         }
134         *pusher = grid(0, i + 1);  *pusher = 0;
135         *pusher = grid(0, (i + 2) % bands);
136     }
137 }
138
139 // initialize the sky object and connect it into our scene graph
140 osg::Node*
141 SGSkyDome::build( double hscale, double vscale ) {
142
143     osg::Geode* geode = new osg::Geode;
144
145     // set up the state
146     osg::StateSet* stateSet = geode->getOrCreateStateSet();
147     stateSet->setRenderBinDetails(-10, "RenderBin");
148
149     osg::ShadeModel* shadeModel = new osg::ShadeModel;
150     shadeModel->setMode(osg::ShadeModel::SMOOTH);
151     stateSet->setAttributeAndModes(shadeModel);
152     stateSet->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
153     stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
154     stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
155     stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
156     stateSet->setMode(GL_BLEND, osg::StateAttribute::OFF);
157     stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::OFF);
158     osg::Material* material = new osg::Material;
159     stateSet->setAttribute(material);
160
161     dome_vl = new osg::Vec3Array(1 + numRings * numBands);
162     dome_cl = new osg::Vec3Array(1 + numRings * numBands);
163     // generate the raw vertex data
164
165     (*dome_vl)[0].set(0.0, 0.0, center_elev * vscale);
166     simgear::VectorArrayAdapter<Vec3Array> vertices(*dome_vl, numBands, 1);
167
168     for ( int i = 0; i < numBands; ++i ) {
169         double theta = (i * 30) * SGD_DEGREES_TO_RADIANS;
170         double sTheta = hscale*sin(theta);
171         double cTheta = hscale*cos(theta);
172         for (int j = 0; j < numRings; ++j) {
173             vertices(j, i).set(cTheta * domeParams[j].radius,
174                                sTheta * domeParams[j].radius,
175                                domeParams[j].elev * vscale);
176         }
177     }
178
179     DrawElementsUShort* domeElements
180         = new osg::DrawElementsUShort(GL_TRIANGLES);
181     makeDome(numRings, numBands, *domeElements);
182     osg::Geometry* geom = new Geometry;
183     geom->setName("Dome Elements");
184     geom->setUseDisplayList(false);
185     geom->setVertexArray(dome_vl.get());
186     geom->setColorArray(dome_cl.get());
187     geom->setColorBinding(osg::Geometry::BIND_PER_VERTEX);
188     geom->setNormalBinding(osg::Geometry::BIND_OFF);
189     geom->addPrimitiveSet(domeElements);
190     geode->addDrawable(geom);
191     // force a repaint of the sky colors with ugly defaults
192     repaint(SGVec3f(1, 1, 1), SGVec3f(1, 1, 1), 0.0, 5000.0 );
193     dome_transform = new osg::MatrixTransform;
194     dome_transform->addChild(geode);
195
196     return dome_transform.get();
197 }
198
199 static void fade_to_black(osg::Vec3 sky_color[], float asl, int count) {
200     const float ref_asl = 10000.0f;
201     const float d = exp( - asl / ref_asl );
202     for(int i = 0; i < count ; i++)
203         sky_color[i] *= d;
204 }
205
206 inline void clampColor(osg::Vec3& color)
207 {
208     color.x() = osg::clampTo(color.x(), 0.0f, 1.0f);
209     color.y() = osg::clampTo(color.y(), 0.0f, 1.0f);
210     color.z() = osg::clampTo(color.z(), 0.0f, 1.0f);
211 }
212
213 // repaint the sky colors based on current value of sun_angle, sky,
214 // and fog colors.  This updates the color arrays for ssgVtxTable.
215 // sun angle in degrees relative to verticle
216 // 0 degrees = high noon
217 // 90 degrees = sun rise/set
218 // 180 degrees = darkest midnight
219 bool
220 SGSkyDome::repaint( const SGVec3f& sky_color, const SGVec3f& fog_color,
221                     double sun_angle, double vis )
222 {
223     SGVec3f outer_param, outer_diff;
224     SGVec3f middle_param, middle_diff;
225
226     // Check for sunrise/sunset condition
227     if (sun_angle > 80) {
228         // 0.0 - 0.4
229         double sunAngleFactor = 10.0 - fabs(90.0 - sun_angle);
230         static const SGVec3f outerConstant(1.0 / 20.0, 1.0 / 40.0, -1.0 / 30.0);
231         static const SGVec3f middleConstant(1.0 / 40.0, 1.0 / 80.0, 0.0);
232         outer_param = sunAngleFactor * outerConstant;
233         middle_param = sunAngleFactor * middleConstant;
234         outer_diff = (1.0 / 6.0) * outer_param;
235         middle_diff = (1.0 / 6.0) * middle_param;
236     } else {
237         outer_param = SGVec3f(0, 0, 0);
238         middle_param = SGVec3f(0, 0, 0);
239         outer_diff = SGVec3f(0, 0, 0);
240         middle_diff = SGVec3f(0, 0, 0);
241     }
242     // printf("  outer_red_param = %.2f  outer_red_diff = %.2f\n", 
243     //        outer_red_param, outer_red_diff);
244
245     // calculate transition colors between sky and fog
246     SGVec3f outer_amt = outer_param;
247     SGVec3f middle_amt = middle_param;
248
249     //
250     // First, recalulate the basic colors
251     //
252
253     // Magic factors for coloring the sky according visibility and
254     // zenith angle.
255     const double cvf = osg::clampBelow(vis, 45000.0);
256     const double vis_factor = osg::clampTo((vis - 1000.0) / 2000.0, 0.0, 1.0);
257     const float upperVisFactor = 1.0 - vis_factor * (0.7 + 0.3 * cvf/45000);
258     const float middleVisFactor = 1.0 - vis_factor * (0.1 + 0.85 * cvf/45000);
259
260     (*dome_cl)[0] = sky_color.osg();
261     simgear::VectorArrayAdapter<Vec3Array> colors(*dome_cl, numBands, 1);
262     const double saif = sun_angle/SG_PI;
263     static const SGVec3f blueShift(0.8, 1.0, 1.2);
264     const SGVec3f skyFogDelta = sky_color - fog_color;
265     // For now the colors of the upper two rings are linearly
266     // interpolated between the zenith color and the first horizon
267     // ring color.
268     
269     for (int i = 0; i < 7; i++) {
270         SGVec3f diff = mult(skyFogDelta, blueShift);
271         diff *= (0.8 + saif - ((6-i)/10));
272         colors(2, i) = (sky_color - upperVisFactor * diff).osg();
273         colors(3, i) = (sky_color - middleVisFactor * diff + middle_amt).osg();
274         colors(4, i) = (fog_color + outer_amt).osg();
275         // Interpolate using distance along dome segment
276         colors(0, i) = simgear::math::lerp(sky_color.osg(), colors(2, i), .3942);
277         colors(1, i) = simgear::math::lerp(sky_color.osg(), colors(2, i), .7885);
278         for (int j = 0; j < numRings - 1; ++j)
279             clampColor(colors(j, i));
280         outer_amt -= outer_diff;
281         middle_amt -= middle_diff;
282     }
283
284     for (int i = 7; i < 12; ++i)
285         for (int j = 0; j < 5; ++j)
286             colors(j, i) = colors(j, 12 - i);
287
288     fade_to_black(&(*dome_cl)[0], asl * center_elev, 1);
289     for (int i = 0; i < numRings - 1; ++i)
290         fade_to_black(&colors(i, 0), (asl+0.05f) * domeParams[i].elev,
291                       numBands);
292
293     for ( int i = 0; i < numBands; i++ )
294         colors(numRings - 1, i) = fog_color.osg();
295     dome_cl->dirty();
296     return true;
297 }
298
299
300 // reposition the sky at the specified origin and orientation
301 // lon specifies a rotation about the Z axis
302 // lat specifies a rotation about the new Y axis
303 // spin specifies a rotation about the new Z axis (and orients the
304 // sunrise/set effects
305 bool
306 SGSkyDome::reposition( const SGVec3f& p, double _asl,
307                        double lon, double lat, double spin ) {
308     asl = _asl;
309
310     osg::Matrix T, LON, LAT, SPIN;
311
312     // Translate to view position
313     // Point3D zero_elev = current_view.get_cur_zero_elev();
314     // xglTranslatef( zero_elev.x(), zero_elev.y(), zero_elev.z() );
315     T.makeTranslate( p.osg() );
316
317     // printf("  Translated to %.2f %.2f %.2f\n", 
318     //        zero_elev.x, zero_elev.y, zero_elev.z );
319
320     // Rotate to proper orientation
321     // printf("  lon = %.2f  lat = %.2f\n",
322     //        lon * SGD_RADIANS_TO_DEGREES,
323     //        lat * SGD_RADIANS_TO_DEGREES);
324     // xglRotatef( lon * SGD_RADIANS_TO_DEGREES, 0.0, 0.0, 1.0 );
325     LON.makeRotate(lon, osg::Vec3(0, 0, 1));
326
327     // xglRotatef( 90.0 - f->get_Latitude() * SGD_RADIANS_TO_DEGREES,
328     //             0.0, 1.0, 0.0 );
329     LAT.makeRotate(90.0 * SGD_DEGREES_TO_RADIANS - lat, osg::Vec3(0, 1, 0));
330
331     // xglRotatef( l->sun_rotation * SGD_RADIANS_TO_DEGREES, 0.0, 0.0, 1.0 );
332     SPIN.makeRotate(spin, osg::Vec3(0, 0, 1));
333
334     dome_transform->setMatrix( SPIN*LAT*LON*T );
335     return true;
336 }