]> git.mxchange.org Git - simgear.git/blob - simgear/scene/sky/newcloud.cxx
Stuart Buchanan :
[simgear.git] / simgear / scene / sky / newcloud.cxx
1 // 3D cloud class
2 //
3 // Written by Harald JOHNSEN, started April 2005.
4 //
5 // Copyright (C) 2005  Harald JOHNSEN - hjohnsen@evc.net
6 //
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License as
9 // published by the Free Software Foundation; either version 2 of the
10 // License, or (at your option) any later version.
11 //
12 // This program 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.
16 //
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.
20 //
21 //
22
23 #ifdef HAVE_CONFIG_H
24 #  include <simgear_config.h>
25 #endif
26
27 #include <osg/AlphaFunc>
28 #include <osg/Program>
29 #include <osg/Uniform>
30 #include <osg/ref_ptr>
31 #include <osg/Texture2D>
32 #include <osg/NodeVisitor>
33 #include <osg/PositionAttitudeTransform>
34 #include <osg/Material>
35 #include <osgUtil/UpdateVisitor>
36 #include <osgDB/ReadFile>
37 #include <osgDB/FileUtils>
38
39
40 #include <simgear/compiler.h>
41
42 #include <plib/sg.h>
43 #include <simgear/math/sg_random.h>
44 #include <simgear/misc/sg_path.hxx>
45 #include <simgear/misc/PathOptions.hxx>
46 #include <simgear/scene/model/model.hxx>
47 #include <simgear/scene/util/StateAttributeFactory.hxx>
48 #include <simgear/scene/util/SGUpdateVisitor.hxx>
49
50 #include <algorithm>
51 #include <osg/GLU>
52
53 #include "cloudfield.hxx"
54 #include "newcloud.hxx"
55 #include "CloudShaderGeometry.hxx"
56
57 using namespace simgear;
58 using namespace osg;
59
60 typedef std::map<std::string, osg::ref_ptr<osg::StateSet> > StateSetMap;
61 typedef std::vector< osg::ref_ptr<osg::Geode> > GeodeList;
62 typedef std::map<std::string, GeodeList*> CloudMap;
63
64 static StateSetMap cloudTextureMap;
65 static CloudMap cloudMap;
66 double SGNewCloud::sprite_density = 1.0;
67 int SGNewCloud::num_flavours = 10;
68
69 static char vertexShaderSource[] = 
70     "#version 120\n"
71     "\n"
72     "varying float fogFactor;\n"
73     "attribute float textureIndexX;\n"
74     "attribute float textureIndexY;\n"
75     "attribute float wScale;\n"
76     "attribute float hScale;\n"
77     "attribute float shade;\n"
78     "attribute float cloud_height;\n"
79     "void main(void)\n"
80     "{\n"
81     "  gl_TexCoord[0] = gl_MultiTexCoord0 + vec4(textureIndexX, textureIndexY, 0.0, 0.0);\n"
82     "  vec4 ep = gl_ModelViewMatrixInverse * vec4(0.0,0.0,0.0,1.0);\n"
83     "  vec4 l  = gl_ModelViewMatrixInverse * vec4(0.0,0.0,1.0,1.0);\n"
84     "  vec3 u = normalize(ep.xyz - l.xyz);\n"
85 // Find a rotation matrix that rotates 1,0,0 into u. u, r and w are
86 // the columns of that matrix.
87     "  vec3 absu = abs(u);\n"
88     "  vec3 r = normalize(vec3(-u.y, u.x, 0));\n"
89     "  vec3 w = cross(u, r);\n"
90 // Do the matrix multiplication by [ u r w pos]. Assume no
91 // scaling in the homogeneous component of pos.
92     "  gl_Position = vec4(0.0, 0.0, 0.0, 1.0);\n"
93     "  gl_Position.xyz = gl_Vertex.x * u * wScale;\n"
94     "  gl_Position.xyz += gl_Vertex.y * r * hScale;\n"
95     "  gl_Position.xyz += gl_Vertex.z * w;\n"
96     "  gl_Position.xyz += gl_Color.xyz;\n"
97 // Determine a lighting normal based on the vertex position from the
98 // center of the cloud, so that sprite on the opposite side of the cloud to the sun are darker.
99     "  float n = dot(normalize(gl_LightSource[0].position.xyz), normalize(mat3x3(gl_ModelViewMatrix) * gl_Position.xyz));\n"
100 // Determine the position - used for fog and shading calculations        
101     "  vec3 ecPosition = vec3(gl_ModelViewMatrix * gl_Position);\n"
102     "  float fogCoord = abs(ecPosition.z);\n"
103     "  float fract = smoothstep(0.0, cloud_height, gl_Position.z + cloud_height);\n"
104 // Final position of the sprite
105     "  gl_Position = gl_ModelViewProjectionMatrix * gl_Position;\n"
106 // Limit the normal range from [0,1.0], and apply the shading (vertical factor)
107     "  n = min(smoothstep(-0.5, 0.5, n), shade * (1.0 - fract) + fract);\n"
108 // This lighting normal is then used to mix between almost pure ambient (0) and diffuse (1.0) light
109     "  vec4 backlight = 0.9 * gl_LightSource[0].ambient + 0.1 * gl_LightSource[0].diffuse;\n"
110     "  gl_FrontColor = mix(backlight, gl_LightSource[0].diffuse, n);\n"
111     "  gl_FrontColor += gl_FrontLightModelProduct.sceneColor;\n"
112 // As we get within 100m of the sprite, it is faded out
113     "  gl_FrontColor.a = smoothstep(10.0, 100.0, fogCoord);\n"
114     "  gl_BackColor = gl_FrontColor;\n"
115 // Fog doesn't affect clouds as much as other objects.        
116     "  fogFactor = exp( -gl_Fog.density * fogCoord * 0.5);\n"
117     "  fogFactor = clamp(fogFactor, 0.0, 1.0);\n"
118     "}\n";
119
120 static char fragmentShaderSource[] = 
121     "uniform sampler2D baseTexture; \n"
122     "varying float fogFactor;\n"
123     "\n"
124     "void main(void)\n"
125     "{\n"
126     "  vec4 base = texture2D( baseTexture, gl_TexCoord[0].st);\n"
127     "  vec4 finalColor = base * gl_Color;\n"
128     "  gl_FragColor = mix(gl_Fog.color, finalColor, fogFactor );\n"
129     "}\n";
130
131 class SGCloudFogUpdateCallback : public osg::StateAttribute::Callback {
132     public:
133         virtual void operator () (osg::StateAttribute* sa, osg::NodeVisitor* nv)
134         {
135             SGUpdateVisitor* updateVisitor = static_cast<SGUpdateVisitor*>(nv);
136             osg::Fog* fog = static_cast<osg::Fog*>(sa);
137             fog->setMode(osg::Fog::EXP);
138             fog->setColor(updateVisitor->getFogColor().osg());
139             fog->setDensity(updateVisitor->getFogExpDensity());
140         }
141 };
142
143 SGNewCloud::SGNewCloud(string type,
144                        const SGPath &tex_path, 
145                        string tex,
146                        double min_w,
147                        double max_w,
148                        double min_h,
149                        double max_h,
150                        double min_sprite_w,
151                        double max_sprite_w,
152                        double min_sprite_h,
153                        double max_sprite_h,
154                        double b,
155                        int n,
156                        int nt_x,
157                        int nt_y) :
158         min_width(min_w),
159         max_width(max_w),
160         min_height(min_h),
161         max_height(max_h),
162         min_sprite_width(min_sprite_w),
163         max_sprite_width(max_sprite_w),
164         min_sprite_height(min_sprite_h),
165         max_sprite_height(max_sprite_h),
166         bottom_shade(b),
167         num_sprites(n),
168         num_textures_x(nt_x),
169         num_textures_y(nt_y),
170         texture(tex),
171         name(type)
172 {
173     // Create a new StateSet for the texture, if required.
174     StateSetMap::iterator iter = cloudTextureMap.find(texture);
175
176     if (iter == cloudTextureMap.end()) {
177         stateSet = new osg::StateSet;
178                 
179         osg::ref_ptr<osgDB::ReaderWriter::Options> options = makeOptionsFromPath(tex_path);
180                 
181         osg::Texture2D *tex = new osg::Texture2D;
182         tex->setWrap( osg::Texture2D::WRAP_S, osg::Texture2D::CLAMP );
183         tex->setWrap( osg::Texture2D::WRAP_T, osg::Texture2D::CLAMP );
184         tex->setImage(osgDB::readImageFile(texture, options.get()));
185                 
186         StateAttributeFactory* attribFactory = StateAttributeFactory::instance();
187         
188         stateSet->setMode(GL_LIGHTING,  osg::StateAttribute::ON);
189         stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
190         
191         // Fog handling
192         osg::Fog* fog = new osg::Fog;
193         fog->setUpdateCallback(new SGCloudFogUpdateCallback);
194         stateSet->setAttributeAndModes(fog);
195         stateSet->setDataVariance(osg::Object::DYNAMIC);
196         
197         stateSet->setAttributeAndModes(attribFactory->getSmoothShadeModel());
198         stateSet->setAttributeAndModes(attribFactory->getStandardBlendFunc());
199
200         stateSet->setTextureAttributeAndModes(0, tex, osg::StateAttribute::ON );
201         stateSet->setRenderBinDetails(osg::StateSet::TRANSPARENT_BIN, "DepthSortedBin");
202                 
203         static ref_ptr<AlphaFunc> alphaFunc;
204         static ref_ptr<Program> program;
205         static ref_ptr<Uniform> baseTextureSampler;
206         static ref_ptr<Material> material;
207                   
208         // Generate the shader etc, if we don't already have one.
209         if (!program.valid()) {
210             alphaFunc = new AlphaFunc;
211             alphaFunc->setFunction(AlphaFunc::GREATER,0.001f);
212             program  = new Program;
213             baseTextureSampler = new osg::Uniform("baseTexture", 0);
214             Shader* vertex_shader = new Shader(Shader::VERTEX, vertexShaderSource);
215             program->addShader(vertex_shader);
216             program->addBindAttribLocation("textureIndexX", CloudShaderGeometry::TEXTURE_INDEX_X);
217             program->addBindAttribLocation("textureIndexY", CloudShaderGeometry::TEXTURE_INDEX_Y);
218             program->addBindAttribLocation("wScale", CloudShaderGeometry::WIDTH);
219             program->addBindAttribLocation("hScale", CloudShaderGeometry::HEIGHT);
220             program->addBindAttribLocation("shade", CloudShaderGeometry::SHADE);
221             program->addBindAttribLocation("cloud_height", CloudShaderGeometry::CLOUD_HEIGHT);
222                   
223             Shader* fragment_shader = new Shader(Shader::FRAGMENT, fragmentShaderSource);
224             program->addShader(fragment_shader);
225             material = new Material;
226             // DonĀ“t track vertex color
227             material->setColorMode(Material::OFF);
228             
229             // We don't actually use the material information either - see shader.
230             material->setAmbient(Material::FRONT_AND_BACK,
231                                  Vec4(0.5f, 0.5f, 0.5f, 1.0f));
232             material->setDiffuse(Material::FRONT_AND_BACK,
233                                  Vec4(0.5f, 0.5f, 0.5f, 1.0f));
234         }
235                   
236         stateSet->setAttributeAndModes(alphaFunc.get());
237         stateSet->setAttribute(program.get());
238         stateSet->addUniform(baseTextureSampler.get());
239         stateSet->setMode(GL_VERTEX_PROGRAM_TWO_SIDE, StateAttribute::ON);
240         stateSet->setAttribute(material.get());
241                 
242         // Add the newly created texture to the map for use later.
243         cloudTextureMap.insert(StateSetMap::value_type(texture,  stateSet));
244     } else {
245         stateSet = iter->second.get();
246     }
247     
248     quad = createOrthQuad(min_sprite_width, min_sprite_height, num_textures_x, num_textures_y);
249 }
250
251 SGNewCloud::~SGNewCloud() {
252 }
253
254 osg::Geometry* SGNewCloud::createOrthQuad(float w, float h, int varieties_x, int varieties_y)
255 {
256     // Create front and back polygons so we don't need to screw around
257     // with two-sided lighting in the shader.
258     osg::Vec3Array& v = *(new osg::Vec3Array(4));
259     osg::Vec3Array& n = *(new osg::Vec3Array(4));
260     osg::Vec2Array& t = *(new osg::Vec2Array(4));
261     
262     float cw = w*0.5f;
263
264     v[0].set(0.0f, -cw, 0.0f);
265     v[1].set(0.0f,  cw, 0.0f);
266     v[2].set(0.0f,  cw, h);
267     v[3].set(0.0f, -cw, h);
268     
269     // The texture coordinate range is not the
270     // entire coordinate space - as the texture
271     // has a number of different clouds on it.
272     float tx = 1.0f/varieties_x;
273     float ty = 1.0f/varieties_y;
274
275     t[0].set(0.0f, 0.0f);
276     t[1].set(  tx, 0.0f);
277     t[2].set(  tx, ty);
278     t[3].set(0.0f, ty);
279
280     // The normal isn't actually use in lighting.
281     n[0].set(1.0f, -1.0f, -1.0f);
282     n[1].set(1.0f,  1.0f, -1.0f);
283     n[2].set(1.0f,  1.0f,  1.0f);
284     n[3].set(1.0f, -1.0f,  1.0f);
285
286     osg::Geometry *geom = new osg::Geometry;
287
288     geom->setVertexArray(&v);
289     geom->setTexCoordArray(0, &t);
290     geom->setNormalArray(&n);
291     geom->setNormalBinding(Geometry::BIND_PER_VERTEX);
292     // No color for now; that's used to pass the position.
293     geom->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::QUADS,0,4));
294
295     return geom;
296 }
297
298 // return a random number between -n/2 and n/2, tending to 0
299 static float Rnd(float n) {
300     return n * (-0.5f + (sg_random() + sg_random()) / 2.0f);
301 }
302
303 osg::ref_ptr<Geode> SGNewCloud::genCloud() {
304     
305     CloudMap::iterator iter = cloudMap.find(name);
306     osg::ref_ptr<osg::Geode> geode;
307     
308     // We generate up to num_flavours of different versions
309     // of the same cloud before we start re-using them. This
310     // allows us to strike a balance between performance and
311     // visual complexity.
312     
313     GeodeList* g = (*iter).second;
314
315     if (iter == cloudMap.end() || g->size() < num_flavours) 
316     {
317         geode = new Geode;
318         
319         CloudShaderGeometry* sg = new CloudShaderGeometry(num_textures_x, num_textures_y, max_width, max_height);
320         
321         // Determine how big this specific cloud instance is. Note that we subtract
322         // the sprite size because the width/height is used to define the limits of
323         // the center of the sprites, not their edges.
324         float width = min_width + sg_random() * (max_width - min_width) - min_sprite_width;
325         float height = min_height + sg_random() * (max_height - min_height) - min_sprite_height;
326         
327         // Determine the cull distance. This is used to remove sprites that are too close together.
328         // The value is squared as we use vector calculations.
329         float cull_distance_squared = min_sprite_height * min_sprite_height * 0.1f;
330         
331         // The number of sprites we actually used is a function of the (user-controlled) density
332         int n_sprites = num_sprites * sprite_density;
333         
334         for (int i = 0; i < n_sprites; i++)
335         {
336             // Determine the position of the sprite. Rather than being completely random,
337             // we place them on the surface of a distorted sphere. However, we place
338             // the first and second sprites on the top and bottom, and the third in the
339             // center of the sphere (and at maximum size) to ensure good coverage and
340             // reduce the chance of there being "holes" in our cloud.
341             float x, y, z;
342             
343             if (i == 0) {
344                 x = 0;
345                 y = 0;
346                 z = height * 0.5f;
347             } else if (i == 1) {
348                 x = 0;
349                 y = 0;
350                 z = - height * 0.5f;
351             } else if (i == 2) {
352                 x = 0;
353                 y = 0;
354                 z = 0;
355             } else {
356                 double theta = sg_random() * SGD_2PI;
357                 double elev  = sg_random() * SGD_PI;
358                 x = width * cos(theta) * 0.5f * sin(elev);
359                 y = width * sin(theta) * 0.5f * sin(elev);
360                 z = height * cos(elev) * 0.5f; 
361             }
362             
363             SGVec3f *pos = new SGVec3f(x, y, z); 
364     
365             // Determine the height and width as scaling factors on the minimum size (used to create the quad)
366             float sprite_width = 1.0f + sg_random() * (max_sprite_width - min_sprite_width) / min_sprite_width;
367             float sprite_height = 1.0f + sg_random() * (max_sprite_height - min_sprite_height) / min_sprite_height;
368             
369             if (i == 2) {
370                 // The center sprite is always maximum size to fill up any holes.
371                 sprite_width = 1.0f + (max_sprite_width - min_sprite_width) / min_sprite_width;
372                 sprite_height = 1.0f + (max_sprite_height - min_sprite_height) / min_sprite_height;
373             }
374             
375             // Determine the sprite texture indexes;
376             int index_x = (int) floor(sg_random() * num_textures_x);
377             if (index_x == num_textures_x) { index_x--; }
378             
379             int index_y = (int) floor(sg_random() * num_textures_y);
380             if (index_y == num_textures_y) { index_y--; }
381             
382             sg->addSprite(*pos, 
383                         index_x, 
384                         index_y, 
385                         sprite_width, 
386                         sprite_height, 
387                         bottom_shade, 
388                         cull_distance_squared, 
389                         height * 0.5f);
390         }
391         
392         
393         sg->setGeometry(quad);
394         geode->addDrawable(sg);
395         geode->setName("3D cloud");
396         geode->setStateSet(stateSet.get());
397         
398         if (iter == cloudMap.end())
399         {
400             // This is the first of this cloud to be generated.
401             GeodeList* geodelist = new GeodeList;
402             geodelist->push_back(geode);
403             cloudMap.insert(CloudMap::value_type(name,  geodelist));
404         }
405         else
406         {
407             // Add the new cloud to the list of geodes
408             (*iter).second->push_back(geode.get());
409         }
410     
411     } else {
412         
413         int index = sg_random() * num_flavours;
414         if (index == num_flavours) index--;
415         
416         geode = iter->second->at(index);
417     }
418     
419     return geode;
420 }
421