3 // Written by Harald JOHNSEN, started April 2005.
5 // Copyright (C) 2005 Harald JOHNSEN - hjohnsen@evc.net
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.
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.
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 <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>
40 #include <simgear/compiler.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>
53 #include "cloudfield.hxx"
54 #include "newcloud.hxx"
55 #include "CloudShaderGeometry.hxx"
57 using namespace simgear;
60 typedef std::map<std::string, osg::ref_ptr<osg::StateSet> > StateSetMap;
62 static StateSetMap cloudTextureMap;
64 static char vertexShaderSource[] =
67 "varying float fogFactor;\n"
68 "attribute float textureIndexX;\n"
69 "attribute float textureIndexY;\n"
70 "attribute float wScale;\n"
71 "attribute float hScale;\n"
72 "attribute float shade;\n"
75 " gl_TexCoord[0] = gl_MultiTexCoord0 + vec4(textureIndexX, textureIndexY, 0.0, 0.0);\n"
76 " vec4 ep = gl_ModelViewMatrixInverse * vec4(0.0,0.0,0.0,1.0);\n"
77 " vec4 l = gl_ModelViewMatrixInverse * vec4(0.0,0.0,1.0,1.0);\n"
78 " vec3 u = normalize(ep.xyz - l.xyz);\n"
79 // Find a rotation matrix that rotates 1,0,0 into u. u, r and w are
80 // the columns of that matrix.
81 " vec3 absu = abs(u);\n"
82 " vec3 r = normalize(vec3(-u.y, u.x, 0));\n"
83 " vec3 w = cross(u, r);\n"
84 // Do the matrix multiplication by [ u r w pos]. Assume no
85 // scaling in the homogeneous component of pos.
86 " gl_Position = vec4(0.0, 0.0, 0.0, 1.0);\n"
87 " gl_Position.xyz = gl_Vertex.x * u * wScale;\n"
88 " gl_Position.xyz += gl_Vertex.y * r * hScale;\n"
89 " gl_Position.xyz += gl_Vertex.z * w;\n"
90 " gl_Position.xyz += gl_Color.xyz;\n"
91 // Determine a lighting normal based on the sprites position from the
92 // center of the cloud.
93 " float n = dot(normalize(gl_LightSource[0].position.xyz), normalize(mat3x3(gl_ModelViewMatrix) * gl_Position.xyz));\n"
94 // Determine the position - used for fog and shading calculations
95 " vec3 ecPosition = vec3(gl_ModelViewMatrix * gl_Position);\n"
96 " float fogCoord = abs(ecPosition.z);\n"
97 // Final position of the sprite
98 " gl_Position = gl_ModelViewProjectionMatrix * gl_Position;\n"
99 // Limit the normal range from [0,1.0], and apply the shading (vertical factor)
100 " n = min(smoothstep(-0.5, 0.5, n), shade);\n"
101 // This lighting normal is then used to mix between almost pure ambient (0) and diffuse (1.0) light
102 " vec4 backlight = 0.8 * gl_LightSource[0].ambient + 0.2 * gl_LightSource[0].diffuse;\n"
103 " gl_FrontColor = mix(backlight, gl_LightSource[0].diffuse, n);\n"
104 " gl_FrontColor += gl_FrontLightModelProduct.sceneColor;\n"
105 // As we get within 100m of the sprite, it is faded out
106 " gl_FrontColor.a = smoothstep(10.0, 100.0, fogCoord);\n"
107 " gl_BackColor = gl_FrontColor;\n"
108 // Fog doesn't affect clouds as much as other objects.
109 " fogFactor = exp( -gl_Fog.density * fogCoord * 0.5);\n"
110 " fogFactor = clamp(fogFactor, 0.0, 1.0);\n"
113 static char fragmentShaderSource[] =
114 "uniform sampler2D baseTexture; \n"
115 "varying float fogFactor;\n"
119 " vec4 base = texture2D( baseTexture, gl_TexCoord[0].st);\n"
120 " vec4 finalColor = base * gl_Color;\n"
121 " gl_FragColor = mix(gl_Fog.color, finalColor, fogFactor );\n"
124 class SGCloudFogUpdateCallback : public osg::StateAttribute::Callback {
126 virtual void operator () (osg::StateAttribute* sa, osg::NodeVisitor* nv)
128 SGUpdateVisitor* updateVisitor = static_cast<SGUpdateVisitor*>(nv);
129 osg::Fog* fog = static_cast<osg::Fog*>(sa);
130 fog->setMode(osg::Fog::EXP);
131 fog->setColor(updateVisitor->getFogColor().osg());
132 fog->setDensity(updateVisitor->getFogExpDensity());
136 SGNewCloud::SGNewCloud(const SGPath &tex_path,
154 min_sprite_width(min_sprite_w),
155 max_sprite_width(max_sprite_w),
156 min_sprite_height(min_sprite_h),
157 max_sprite_height(max_sprite_h),
160 num_textures_x(nt_x),
161 num_textures_y(nt_y),
164 // Create a new StateSet for the texture, if required.
165 StateSetMap::iterator iter = cloudTextureMap.find(texture);
167 if (iter == cloudTextureMap.end()) {
168 stateSet = new osg::StateSet;
170 osg::ref_ptr<osgDB::ReaderWriter::Options> options = makeOptionsFromPath(tex_path);
172 osg::Texture2D *tex = new osg::Texture2D;
173 tex->setWrap( osg::Texture2D::WRAP_S, osg::Texture2D::CLAMP );
174 tex->setWrap( osg::Texture2D::WRAP_T, osg::Texture2D::CLAMP );
175 tex->setImage(osgDB::readImageFile(texture, options.get()));
177 StateAttributeFactory* attribFactory = StateAttributeFactory::instance();
179 stateSet->setMode(GL_LIGHTING, osg::StateAttribute::ON);
180 stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
183 osg::Fog* fog = new osg::Fog;
184 fog->setUpdateCallback(new SGCloudFogUpdateCallback);
185 stateSet->setAttributeAndModes(fog);
186 stateSet->setDataVariance(osg::Object::DYNAMIC);
188 stateSet->setAttributeAndModes(attribFactory->getSmoothShadeModel());
189 stateSet->setAttributeAndModes(attribFactory->getStandardBlendFunc());
191 stateSet->setTextureAttributeAndModes(0, tex, osg::StateAttribute::ON );
192 stateSet->setRenderBinDetails(osg::StateSet::TRANSPARENT_BIN, "DepthSortedBin");
194 static ref_ptr<AlphaFunc> alphaFunc;
195 static ref_ptr<Program> program;
196 static ref_ptr<Uniform> baseTextureSampler;
197 static ref_ptr<Material> material;
199 // Generate the shader etc, if we don't already have one.
200 if (!program.valid()) {
201 alphaFunc = new AlphaFunc;
202 alphaFunc->setFunction(AlphaFunc::GREATER,0.002f);
203 program = new Program;
204 baseTextureSampler = new osg::Uniform("baseTexture", 0);
205 Shader* vertex_shader = new Shader(Shader::VERTEX, vertexShaderSource);
206 program->addShader(vertex_shader);
207 program->addBindAttribLocation("textureIndexX", CloudShaderGeometry::TEXTURE_INDEX_X);
208 program->addBindAttribLocation("textureIndexY", CloudShaderGeometry::TEXTURE_INDEX_Y);
209 program->addBindAttribLocation("wScale", CloudShaderGeometry::WIDTH);
210 program->addBindAttribLocation("hScale", CloudShaderGeometry::HEIGHT);
211 program->addBindAttribLocation("shade", CloudShaderGeometry::SHADE);
213 Shader* fragment_shader = new Shader(Shader::FRAGMENT, fragmentShaderSource);
214 program->addShader(fragment_shader);
215 material = new Material;
216 // DonĀ“t track vertex color
217 material->setColorMode(Material::OFF);
219 // We don't actually use the material information either - see shader.
220 material->setAmbient(Material::FRONT_AND_BACK,
221 Vec4(0.5f, 0.5f, 0.5f, 1.0f));
222 material->setDiffuse(Material::FRONT_AND_BACK,
223 Vec4(0.5f, 0.5f, 0.5f, 1.0f));
226 stateSet->setAttributeAndModes(alphaFunc.get());
227 stateSet->setAttribute(program.get());
228 stateSet->addUniform(baseTextureSampler.get());
229 stateSet->setMode(GL_VERTEX_PROGRAM_TWO_SIDE, StateAttribute::ON);
230 stateSet->setAttribute(material.get());
232 // Add the newly created texture to the map for use later.
233 cloudTextureMap.insert(StateSetMap::value_type(texture, stateSet));
235 stateSet = iter->second.get();
238 quad = createOrthQuad(min_sprite_width, min_sprite_height, num_textures_x, num_textures_y);
241 SGNewCloud::~SGNewCloud() {
244 osg::Geometry* SGNewCloud::createOrthQuad(float w, float h, int varieties_x, int varieties_y)
246 // Create front and back polygons so we don't need to screw around
247 // with two-sided lighting in the shader.
248 osg::Vec3Array& v = *(new osg::Vec3Array(4));
249 osg::Vec3Array& n = *(new osg::Vec3Array(4));
250 osg::Vec2Array& t = *(new osg::Vec2Array(4));
254 v[0].set(0.0f, -cw, 0.0f);
255 v[1].set(0.0f, cw, 0.0f);
256 v[2].set(0.0f, cw, h);
257 v[3].set(0.0f, -cw, h);
259 // The texture coordinate range is not the
260 // entire coordinate space - as the texture
261 // has a number of different clouds on it.
262 float tx = 1.0f/varieties_x;
263 float ty = 1.0f/varieties_y;
265 t[0].set(0.0f, 0.0f);
270 // The normal isn't actually use in lighting.
271 n[0].set(1.0f, -1.0f, -1.0f);
272 n[1].set(1.0f, 1.0f, -1.0f);
273 n[2].set(1.0f, 1.0f, 1.0f);
274 n[3].set(1.0f, -1.0f, 1.0f);
276 osg::Geometry *geom = new osg::Geometry;
278 geom->setVertexArray(&v);
279 geom->setTexCoordArray(0, &t);
280 geom->setNormalArray(&n);
281 geom->setNormalBinding(Geometry::BIND_PER_VERTEX);
282 // No color for now; that's used to pass the position.
283 geom->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::QUADS,0,4));
288 // return a random number between -n/2 and n/2, tending to 0
289 static float Rnd(float n) {
290 return n * (-0.5f + (sg_random() + sg_random()) / 2.0f);
293 osg::ref_ptr<Geode> SGNewCloud::genCloud() {
294 Geode* geode = new Geode;
295 CloudShaderGeometry* sg = new CloudShaderGeometry(num_textures_x, num_textures_y);
298 // Determine how big this specific cloud instance is. Note that we subtract
299 // the sprite size because the width/height is used to define the limits of
300 // the center of the sprites, not their edges.
301 float width = min_width + sg_random() * (max_width - min_width) - max_sprite_width;
302 float height = min_height + sg_random() * (max_height - min_height) - max_sprite_height;
304 // Determine the cull distance. This is used to remove sprites that are too close together.
305 // The value is squared as we use vector calculations.
306 float cull_distance_squared = min_sprite_height * min_sprite_height * 0.1f;
308 for (int i = 0; i < num_sprites; i++)
310 // Determine the position of the sprite. Rather than being completely random,
311 // sprites are placed on a squashed sphere.
312 double theta = sg_random() * SGD_2PI;
313 float x = width * cos(theta) * 0.5f;
314 float y = width * sin(theta) * 0.5f;
315 float z = height * cos(sg_random() * SGD_2PI) * 0.5f;
317 SGVec3f *pos = new SGVec3f(x, y, z);
319 // Determine the height and width as scaling factors on the minimum size (used to create the quad)
320 float sprite_width = 1.0f + sg_random() * (max_sprite_width - min_sprite_width) / min_sprite_width;
321 float sprite_height = 1.0f + sg_random() * (max_sprite_height - min_sprite_height) / min_sprite_height;
323 // The shade varies from bottom_shade to 1.0 non-linearly
328 shade = ((2 * z + height) / height) * (1 - bottom_shade) + bottom_shade;
331 // Determine the sprite texture indexes;
332 int index_x = (int) floor(sg_random() * num_textures_x);
333 if (index_x == num_textures_x) { index_x--; }
335 int index_y = (int) floor(sg_random() * num_textures_y);
336 if (index_y == num_textures_y) { index_y--; }
338 sg->addSprite(*pos, index_x, index_y, sprite_width, sprite_height, shade, cull_distance_squared);
341 sg->setGeometry(quad);
342 geode->addDrawable(sg);
343 geode->setName("3D cloud");
344 geode->setStateSet(stateSet.get());