]> git.mxchange.org Git - simgear.git/blob - simgear/scene/sky/dome.cxx
Work around apparent OSG 3.2.0 normal binding bug.
[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 #include <iterator>
28
29 #include <simgear/compiler.h>
30
31 #include <osg/Array>
32 #include <osg/Geode>
33 #include <osg/Geometry>
34 #include <osg/Node>
35 #include <osg/Math>
36 #include <osg/MatrixTransform>
37 #include <osg/Material>
38 #include <osg/ShadeModel>
39 #include <osg/PrimitiveSet>
40 #include <osg/CullFace>
41 #include <osgDB/Registry>
42
43 #include <simgear/debug/logstream.hxx>
44 #include <simgear/scene/util/OsgMath.hxx>
45 #include <simgear/scene/util/SGReaderWriterOptions.hxx>
46 #include <simgear/scene/util/VectorArrayAdapter.hxx>
47 #include <simgear/scene/material/Effect.hxx>
48 #include <simgear/scene/material/EffectGeode.hxx>
49
50 #include "dome.hxx"
51
52 using namespace osg;
53 using namespace simgear;
54
55 // proportions of max dimensions fed to the build() routine
56 static const float center_elev = 1.0;
57
58 namespace
59 {
60 /* unused ?
61 struct DomeParam
62 {
63     float radius;
64     float elev;
65 } domeParams[] = {{.5, .8660},  // 60deg from horizon
66                   {.8660, .5},  // 30deg from horizon
67                   // Original dome horizon vertices
68                   {0.9701, 0.2425},
69                   {0.9960, 0.0885},
70                   {1.0, 0.0},
71                   {0.9922, -0.1240}};
72 */
73
74 const int numRings = 64; //sizeof(domeParams) / sizeof(domeParams[0]);
75 const int numBands = 64; // 12
76 const int halfBands = numBands / 2;
77
78 // Make dome a bit over half sphere
79 const float domeAngle = 120.0;
80
81 const float bandDelta = 360.0 / numBands;
82 const float ringDelta = domeAngle / (numRings+1);
83
84 // Which band is at horizon
85 const int halfRings = numRings * (90.0 / domeAngle);
86 const int upperRings = numRings * (60.0 / domeAngle); // top half
87 const int middleRings = numRings * (15.0 / domeAngle);
88
89 }
90
91 static const float upper_radius = 0.9701; // (.6, 0.15)
92 static const float upper_elev = 0.2425;
93
94 static const float middle_radius = 0.9960; // (.9, .08)
95 static const float middle_elev = 0.0885;
96
97 static const float lower_radius = 1.0;
98 static const float lower_elev = 0.0;
99
100 static const float bottom_radius = 0.9922; // (.8, -.1)
101 static const float bottom_elev = -0.1240;
102
103
104 // Constructor
105 SGSkyDome::SGSkyDome( void ) {
106     asl = 0;
107 }
108
109
110 // Destructor
111 SGSkyDome::~SGSkyDome( void ) {
112 }
113
114 // Generate indices for a dome mesh. Assume a center vertex at 0, then
115 // rings of vertices. Each ring's vertices are stored together. An
116 // even number of longitudinal bands are assumed.
117
118 namespace
119 {
120 // Calculate the index of a vertex in the grid by using its address in
121 // the array that holds its location.
122 struct GridIndex
123 {
124     VectorArrayAdapter<Vec3Array> gridAdapter;
125     Vec3Array& grid;
126     GridIndex(Vec3Array& array, int rowStride, int baseOffset) :
127         gridAdapter(array, rowStride, baseOffset), grid(array)
128     {
129     }
130     unsigned short operator() (int ring, int band)
131     {
132         return (unsigned short)(&gridAdapter(ring, band) - &grid[0]);
133     }
134 };
135 }
136 void SGSkyDome::makeDome(int rings, int bands, DrawElementsUShort& elements)
137 {
138     std::back_insert_iterator<DrawElementsUShort> pusher
139         = std::back_inserter(elements);
140     GridIndex grid(*dome_vl, numBands, 1);
141     for (int i = 0; i < bands; i++) {
142         *pusher = 0;  *pusher = grid(0, i+1);  *pusher = grid(0, i);
143         // down a band
144         for (int j = 0; j < rings - 1; ++j) {
145             *pusher = grid(j, i);  *pusher = grid(j, (i + 1)%bands);
146             *pusher = grid(j + 1, (i + 1)%bands);
147             *pusher = grid(j, i);  *pusher =  grid(j + 1, (i + 1)%bands);
148             *pusher =  grid(j + 1, i);
149         }
150         // and up the next one
151 /*        for (int j = rings - 1; j > 0; --j) {
152             *pusher = grid(j, i + 1);  *pusher = grid(j - 1, i + 1);
153             *pusher = grid(j, (i + 2) % bands);
154             *pusher = grid(j, (i + 2) % bands); *pusher = grid(j - 1, i + 1);
155             *pusher = grid(j - 1, (i + 2) % bands);
156         }
157         *pusher = grid(0, i + 1);  *pusher = 0;
158         *pusher = grid(0, (i + 2) % bands);*/
159     }
160 }
161
162 // initialize the sky object and connect it into our scene graph
163 osg::Node*
164 SGSkyDome::build( double hscale, double vscale, simgear::SGReaderWriterOptions *options ) {
165
166     EffectGeode* geode = new EffectGeode;
167 //    Geode* geode = new Geode;
168     geode->setName("Skydome");
169     geode->setCullingActive(false); // Prevent skydome from being culled away
170
171     Effect *effect = makeEffect("Effects/skydome", true, options);
172     if(effect)
173       geode->setEffect(effect);
174
175     // set up the state
176     osg::StateSet* stateSet = geode->getOrCreateStateSet();
177     stateSet->setRenderBinDetails(-10, "RenderBin");
178
179     osg::ShadeModel* shadeModel = new osg::ShadeModel;
180     shadeModel->setMode(osg::ShadeModel::SMOOTH);
181     stateSet->setAttributeAndModes(shadeModel);
182     stateSet->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
183     stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
184     stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
185     stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::ON);
186     stateSet->setMode(GL_BLEND, osg::StateAttribute::OFF);
187     stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::OFF);
188
189     stateSet->setAttribute(new osg::CullFace(osg::CullFace::BACK));
190
191     osg::Material* material = new osg::Material;
192     stateSet->setAttribute(material);
193
194     dome_vl = new osg::Vec3Array(1 + numRings * numBands);
195     dome_cl = new osg::Vec3Array(1 + numRings * numBands);
196     // generate the raw vertex data
197
198     (*dome_vl)[0].set(0.0, 0.0, center_elev * vscale);
199     simgear::VectorArrayAdapter<Vec3Array> vertices(*dome_vl, numBands, 1);
200
201     for ( int i = 0; i < numBands; ++i ) {
202         double theta = (i * bandDelta) * SGD_DEGREES_TO_RADIANS;
203         double sTheta = hscale*sin(theta);
204         double cTheta = hscale*cos(theta);
205         for (int j = 0; j < numRings; ++j) {
206             vertices(j, i).set(cTheta * sin((j+1)*ringDelta*SGD_DEGREES_TO_RADIANS), //domeParams[j].radius,
207                                sTheta * sin((j+1)*ringDelta*SGD_DEGREES_TO_RADIANS),// domeParams[j].radius,
208                                vscale * cos((j+1)*ringDelta*SGD_DEGREES_TO_RADIANS)); //domeParams[j].elev * vscale);
209         }
210     }
211
212     DrawElementsUShort* domeElements
213         = new osg::DrawElementsUShort(GL_TRIANGLES);
214     makeDome(numRings, numBands, *domeElements);
215     osg::Geometry* geom = new Geometry;
216     geom->setName("Dome Elements");
217     geom->setUseDisplayList(false);
218     geom->setVertexArray(dome_vl.get());
219     geom->setColorArray(dome_cl.get());
220     geom->setColorBinding(osg::Geometry::BIND_PER_VERTEX);
221     geom->setNormalBinding(osg::Geometry::BIND_OFF);
222     geom->addPrimitiveSet(domeElements);
223     geode->addDrawable(geom);
224     // force a repaint of the sky colors with ugly defaults
225     repaint(SGVec3f(1, 1, 1), SGVec3f(1, 1, 1), SGVec3f(1, 1, 1), 0.0, 5000.0 );
226     dome_transform = new osg::MatrixTransform;
227     dome_transform->addChild(geode);
228
229     return dome_transform.get();
230 }
231
232 static void fade_to_black(osg::Vec3 sky_color[], float asl, int count) {
233     const float ref_asl = 10000.0f;
234     const float d = exp( - asl / ref_asl );
235     for(int i = 0; i < count ; i++)
236         sky_color[i] *= d;
237 }
238
239 static inline void clampColor(osg::Vec3& color)
240 {
241     color.x() = osg::clampTo(color.x(), 0.0f, 1.0f);
242     color.y() = osg::clampTo(color.y(), 0.0f, 1.0f);
243     color.z() = osg::clampTo(color.z(), 0.0f, 1.0f);
244 }
245
246 // repaint the sky colors based on current value of sun_angle, sky,
247 // and fog colors.  This updates the color arrays for ssgVtxTable.
248 // sun angle in degrees relative to verticle
249 // 0 degrees = high noon
250 // 90 degrees = sun rise/set
251 // 180 degrees = darkest midnight
252 bool
253 SGSkyDome::repaint( const SGVec3f& sun_color, const SGVec3f& sky_color,
254                     const SGVec3f& fog_color, double sun_angle, double vis )
255 {
256     SGVec3f outer_param, outer_diff;
257     SGVec3f middle_param, middle_diff;
258
259     // Check for sunrise/sunset condition
260     if (sun_angle > 80) {
261         // 0.0 - 0.4
262         double sunAngleFactor = 10.0 - fabs(90.0 - sun_angle);
263         static const SGVec3f outerConstant(1.0 / 20.0, 1.0 / 40.0, -1.0 / 30.0);
264         static const SGVec3f middleConstant(1.0 / 40.0, 1.0 / 80.0, 0.0);
265         outer_param = sunAngleFactor * outerConstant;
266         middle_param = sunAngleFactor * middleConstant;
267         outer_diff = (1.0 / numRings) * outer_param;
268         middle_diff = (1.0 / numRings) * middle_param;
269     } else {
270         outer_param = SGVec3f(0, 0, 0);
271         middle_param = SGVec3f(0, 0, 0);
272         outer_diff = SGVec3f(0, 0, 0);
273         middle_diff = SGVec3f(0, 0, 0);
274     }
275     // printf("  outer_red_param = %.2f  outer_red_diff = %.2f\n", 
276     //        outer_red_param, outer_red_diff);
277
278     // calculate transition colors between sky and fog
279     SGVec3f outer_amt = outer_param;
280     SGVec3f middle_amt = middle_param;
281
282     //
283     // First, recalulate the basic colors
284     //
285
286     // Magic factors for coloring the sky according visibility and
287     // zenith angle.
288     const double cvf = osg::clampBelow(vis, 45000.0);
289     const double vis_factor = osg::clampTo((vis - 1000.0) / 2000.0, 0.0, 1.0);
290     const float upperVisFactor = 1.0 - vis_factor * (0.7 + 0.3 * cvf/45000);
291     const float middleVisFactor = 1.0 - vis_factor * (0.1 + 0.85 * cvf/45000);
292
293     // Dome top is always sky_color
294     (*dome_cl)[0] = toOsg(sky_color);
295     simgear::VectorArrayAdapter<Vec3Array> colors(*dome_cl, numBands, 1);
296     const double saif = sun_angle/SG_PI;
297     static const SGVec3f blueShift(0.8, 1.0, 1.2);
298     const SGVec3f skyFogDelta = sky_color - fog_color;
299 //    const SGVec3f sunSkyDelta = sun_color - sky_color;
300
301     // For now the colors of the upper two rings are linearly
302     // interpolated between the zenith color and the first horizon
303     // ring color. Means angles from top to 30 degrees
304
305     for (int i = 0; i < halfBands+1; i++) {
306         SGVec3f diff = mult(skyFogDelta, blueShift);
307         diff *= (0.8 + saif - ((halfBands-i)/(float)(numBands-2)));
308
309         // Color the ~60 deg ring
310         colors(upperRings, i) = toOsg(sky_color - upperVisFactor * diff);
311
312         int j=0;
313         // Color top half by linear interpolation (90...60 degrees)
314         for (; j < upperRings; j++)
315             colors(j, i) = SGMiscf::lerp(toOsg(sky_color), colors(upperRings, i), j / (float)upperRings);
316
317         j++; // Skip the 60 deg ring
318         // From 60 to ~85 degrees
319         for (int l = 0; j < upperRings + middleRings + 1; j++, l++)
320             colors(j, i) = SGMiscf::lerp(colors(upperRings, i),
321                        toOsg(sky_color - middleVisFactor * diff + middle_amt), l / (float)middleRings);
322
323         // 85 to 90 degrees
324         for (int l = 0; j < halfRings; j++, l++)
325             colors(j, i) = SGMiscf::lerp(colors(upperRings + middleRings, i), toOsg(fog_color + outer_amt),
326                         l / (float)(halfRings - upperRings - middleRings));
327
328         // Original colors
329         //colors(2, i) = toOsg(sky_color - upperVisFactor * diff);
330         //colors(3, i) = toOsg(sky_color - middleVisFactor * diff + middle_amt);
331         //colors(4, i) = toOsg(fog_color + outer_amt);
332         //colors(0, i) = simgear::math::lerp(toOsg(sky_color), colors(2, i), .3942);
333         //colors(1, i) = simgear::math::lerp(toOsg(sky_color), colors(2, i), .7885);
334
335         for (int j = 0; j < numRings - 1; ++j)
336             clampColor(colors(j, i));
337
338         outer_amt -= outer_diff;
339         middle_amt -= middle_diff;
340     }
341
342     // Other side of dome is mirror of the other
343     for (int i = halfBands+1; i < numBands; ++i)
344         for (int j = 0; j < numRings-1; ++j)
345             colors(j, i) = colors(j, numBands - i);
346
347     // Fade colors to black when going to space
348     // Center of dome is blackest and then fade decreases towards horizon
349     fade_to_black(&(*dome_cl)[0], asl * center_elev, 1);
350     for (int i = 0; i < numRings - 1; ++i) {
351         float fadeValue = (asl+0.05f) * cos(i*ringDelta*SGD_DEGREES_TO_RADIANS);
352         if(fadeValue < 0.0) fadeValue = 0.0; // Prevent brightening up if dome is over 90 degrees
353         fade_to_black(&colors(i, 0), fadeValue, //domeParams[i].elev,
354                       numBands);
355     }
356
357     // All rings below horizon are fog color
358     for ( int i = halfRings; i < numRings; i++)
359         for ( int j = 0; j < numBands; j++ )
360             colors(i, j) = toOsg(fog_color);
361
362     dome_cl->dirty();
363     return true;
364 }
365
366
367 // reposition the sky at the specified origin and orientation
368 // lon specifies a rotation about the Z axis
369 // lat specifies a rotation about the new Y axis
370 // spin specifies a rotation about the new Z axis (and orients the
371 // sunrise/set effects
372 bool
373 SGSkyDome::reposition( const SGVec3f& p, double _asl,
374                        double lon, double lat, double spin ) {
375     asl = _asl;
376
377     osg::Matrix T, LON, LAT, SPIN;
378
379     // Translate to view position
380     // Point3D zero_elev = current_view.get_cur_zero_elev();
381     // xglTranslatef( zero_elev.x(), zero_elev.y(), zero_elev.z() );
382     T.makeTranslate( toOsg(p) );
383
384     // printf("  Translated to %.2f %.2f %.2f\n", 
385     //        zero_elev.x, zero_elev.y, zero_elev.z );
386
387     // Rotate to proper orientation
388     // printf("  lon = %.2f  lat = %.2f\n",
389     //        lon * SGD_RADIANS_TO_DEGREES,
390     //        lat * SGD_RADIANS_TO_DEGREES);
391     // xglRotatef( lon * SGD_RADIANS_TO_DEGREES, 0.0, 0.0, 1.0 );
392     LON.makeRotate(lon, osg::Vec3(0, 0, 1));
393
394     // xglRotatef( 90.0 - f->get_Latitude() * SGD_RADIANS_TO_DEGREES,
395     //             0.0, 1.0, 0.0 );
396     LAT.makeRotate(90.0 * SGD_DEGREES_TO_RADIANS - lat, osg::Vec3(0, 1, 0));
397
398     // xglRotatef( l->sun_rotation * SGD_RADIANS_TO_DEGREES, 0.0, 0.0, 1.0 );
399     SPIN.makeRotate(spin, osg::Vec3(0, 0, 1));
400
401     dome_transform->setMatrix( SPIN*LAT*LON*T );
402     return true;
403 }