3 * Copyright (C) 2008 Stuart Buchanan
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU General Public License as
7 * published by the Free Software Foundation; either version 2 of the
8 * License, or (at your option) any later version.
10 * This program is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
26 #include <osg/AlphaFunc>
27 #include <osg/Billboard>
28 #include <osg/BlendFunc>
30 #include <osg/Geometry>
31 #include <osg/Material>
33 #include <osg/MatrixTransform>
35 #include <osg/StateSet>
36 #include <osg/Texture2D>
39 #include <osgDB/ReadFile>
40 #include <osgDB/FileUtils>
42 #include <simgear/misc/sg_path.hxx>
43 #include <simgear/scene/util/QuadTreeBuilder.hxx>
44 #include <simgear/scene/util/RenderConstants.hxx>
45 #include <simgear/scene/util/StateAttributeFactory.hxx>
47 #include "ShaderGeometry.hxx"
48 #include "TreeBin.hxx"
50 #define SG_TREE_QUAD_TREE_DEPTH 3
52 // Comments from Tim Moore:
53 // Some work remains for this code. Stuart's enhancement for multiple
54 // textures per forest should be integrated. We should try to use one
55 // ShaderGeometry for *all* the trees in the scene graph and do the
56 // rotation and scale with a MatrixTransform above the trees quad
57 // tree. The positions would of course have to be transformed by the
58 // inverse of that transform. Also, we should investigate whether it
59 // would be better to instantiate trees as polygons in a osg::Geometry
60 // object instead of using the ShaderGeometry instancing technique.
67 osg::Geometry* createOrthQuads(float w, float h, int varieties, const osg::Matrix& rotate)
70 //const osg::Vec3& pos = osg::Vec3(0.0f,0.0f,0.0f),
72 // Create front and back polygons so we don't need to screw around
73 // with two-sided lighting in the shader.
74 osg::Vec3Array& v = *(new osg::Vec3Array(8));
75 osg::Vec3Array& n = *(new osg::Vec3Array(8));
76 osg::Vec2Array& t = *(new osg::Vec2Array(8));
80 v[0].set(0.0f,-cw,0.0f);
81 v[1].set(0.0f, cw,0.0f);
85 v[4].set(-cw,0.0f,0.0f);
86 v[5].set( cw,0.0f,0.0f);
90 // The texture coordinate range is not the
91 // entire coordinate space - as the texture
92 // has a number of different trees on it.
93 float tx = 1.0f/varieties;
105 // For now the normal is normal to the quad. If we want to get
106 // fancier and approximate a cylindrical tree or something, then
107 // we would really want more geometry.
108 std::fill(n.begin(), n.begin() + 4, Vec3f(1.0f, 0.0f, 0.0f));
109 std::fill(n.begin() + 4, n.end(), Vec3f(0.0f, -1.0f, 0.0f));
110 for (unsigned int i = 0; i < 8; i++) {
111 v[i] = v[i] * rotate;
112 // Should be the inverse transpose, but assume that rotate is
114 n[i] = n[i] * rotate;
117 osg::Geometry *geom = new osg::Geometry;
119 geom->setVertexArray(&v);
120 geom->setTexCoordArray(0, &t);
121 geom->setNormalArray(&n);
122 geom->setNormalBinding(Geometry::BIND_PER_VERTEX);
123 // No color for now; that's used to pass the position.
124 geom->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::QUADS,0,8));
129 static char vertexShaderSource[] =
130 "varying float fogFactor;\n"
131 #ifndef TSG_PACKED_ATTRIBUTES
132 "attribute float textureIndex;\n"
137 #ifdef TSG_PACKED_ATTRIBUTES
138 " gl_TexCoord[0] = gl_MultiTexCoord0;\n"
140 " gl_TexCoord[0] = gl_MultiTexCoord0 + vec4(textureIndex, 0.0, 0.0, 0.0);\n"
142 " vec3 position = gl_Vertex.xyz * gl_Color.w + gl_Color.xyz;\n"
143 " gl_Position = gl_ModelViewProjectionMatrix * vec4(position,1.0);\n"
144 " vec3 ecPosition = vec3(gl_ModelViewMatrix * vec4(position, 1.0));\n"
145 " vec3 N = normalize(gl_NormalMatrix * gl_Normal);\n"
146 " vec3 diffuse = gl_FrontMaterial.diffuse.rgb * max(0.0, dot(N, gl_LightSource[0].position.xyz));\n"
147 " vec3 backDiffuse = gl_FrontMaterial.diffuse.rgb * max(0.0, dot(-N, gl_LightSource[0].position.xyz));\n"
148 " vec4 ambientColor = gl_FrontLightModelProduct.sceneColor + gl_LightSource[0].ambient * gl_FrontMaterial.ambient;\n"
149 " gl_FrontColor = ambientColor + gl_LightSource[0].diffuse * vec4(diffuse, 1.0);\n"
150 " gl_BackColor = ambientColor + gl_LightSource[0].diffuse * vec4(backDiffuse, 1.0)\n;"
151 // " gl_TexCoord[0] = gl_MultiTexCoord0;\n"
152 " float fogCoord = abs(ecPosition.z);\n"
153 " fogFactor = exp( -gl_Fog.density * gl_Fog.density * fogCoord * fogCoord);\n"
154 " fogFactor = clamp(fogFactor, 0.0, 1.0);\n"
157 static char fragmentShaderSource[] =
158 "uniform sampler2D baseTexture; \n"
159 "varying float fogFactor;\n"
163 " vec4 base = texture2D( baseTexture, gl_TexCoord[0].st);\n"
164 " vec4 finalColor = base * gl_Color;\n"
165 " gl_FragColor = mix(gl_Fog.color, finalColor, fogFactor );\n"
168 typedef std::map<std::string, osg::ref_ptr<StateSet> > StateSetMap;
170 static StateSetMap treeTextureMap;
172 // Helper classes for creating the quad tree
177 MakeTreesLeaf(float range, Geometry* geometry, int varieties) :
178 _range(range), _geometry(geometry), _varieties(varieties)
180 MakeTreesLeaf(const MakeTreesLeaf& rhs) :
181 _range(rhs._range), _geometry(rhs._geometry), _varieties(rhs._varieties) {}
182 LOD* operator() () const
184 LOD* result = new LOD;
185 Geode* geode = new Geode;
186 ShaderGeometry* sg = new ShaderGeometry(_varieties);
187 sg->setGeometry(_geometry);
188 geode->addDrawable(sg);
189 result->addChild(geode, 0, _range);
197 struct AddTreesLeafObject
199 void operator() (LOD* lod, const TreeBin::Tree& tree) const
201 Geode* geode = static_cast<Geode*>(lod->getChild(0));
203 = static_cast<ShaderGeometry*>(geode->getDrawable(0));
210 GetTreeCoord(const Matrix& transform) : _transform(transform) {}
211 GetTreeCoord(const GetTreeCoord& rhs) : _transform(rhs._transform) {}
212 Vec3 operator() (const TreeBin::Tree& tree) const
214 return tree.position.osg() * _transform;
219 typedef QuadTreeBuilder<LOD*, TreeBin::Tree, MakeTreesLeaf, AddTreesLeafObject,
220 GetTreeCoord> ShaderGeometryQuadtree;
223 osg::Group* createForest(TreeBin& forest, const osg::Matrix& transform)
225 // Set up some shared structures.
226 osg::Geometry* shared_geometry = createOrthQuads(forest.width,
228 forest.texture_varieties,
231 ref_ptr<Group> group;
233 osg::StateSet* stateset = 0;
234 StateSetMap::iterator iter = treeTextureMap.find(forest.texture);
235 if (iter == treeTextureMap.end()) {
236 osg::Texture2D *tex = new osg::Texture2D;
237 tex->setWrap( osg::Texture2D::WRAP_S, osg::Texture2D::CLAMP );
238 tex->setWrap( osg::Texture2D::WRAP_T, osg::Texture2D::CLAMP );
239 tex->setImage(osgDB::readImageFile(forest.texture));
241 static ref_ptr<AlphaFunc> alphaFunc;
242 static ref_ptr<Program> program;
243 static ref_ptr<Uniform> baseTextureSampler;
244 static ref_ptr<Material> material;
246 stateset = new osg::StateSet;
247 stateset->setTextureAttributeAndModes(0, tex, osg::StateAttribute::ON );
248 stateset->setRenderBinDetails(RANDOM_OBJECTS_BIN, "DepthSortedBin");
249 if (!program.valid()) {
250 alphaFunc = new AlphaFunc;
251 alphaFunc->setFunction(AlphaFunc::GEQUAL,0.33f);
252 program = new Program;
253 baseTextureSampler = new osg::Uniform("baseTexture", 0);
254 Shader* vertex_shader = new Shader(Shader::VERTEX, vertexShaderSource);
255 program->addShader(vertex_shader);
256 #ifndef TSG_PACKED_ATTRIBUTES
257 program->addBindAttribLocation("textureIndex", 1);
260 Shader* fragment_shader = new Shader(Shader::FRAGMENT,
261 fragmentShaderSource);
262 program->addShader(fragment_shader);
263 material = new Material;
264 // DonĀ“t track vertex color
265 material->setColorMode(Material::OFF);
266 material->setAmbient(Material::FRONT_AND_BACK,
267 Vec4(.8f, .8f, .8f, 1.0f));
268 material->setDiffuse(Material::FRONT_AND_BACK,
269 Vec4(.2f, .2f, .2f, 1.0f));
271 stateset->setAttributeAndModes(alphaFunc.get());
272 stateset->setAttribute(program.get());
273 stateset->addUniform(baseTextureSampler.get());
274 stateset->setMode(GL_VERTEX_PROGRAM_TWO_SIDE, StateAttribute::ON);
275 stateset->setAttribute(material.get());
277 treeTextureMap.insert(StateSetMap::value_type(forest.texture,
280 stateset = iter->second.get();
282 // Now, create a quadtree for the forest.
284 ShaderGeometryQuadtree quadtree(GetTreeCoord(Matrix::inverse(transform)),
285 AddTreesLeafObject(),
286 SG_TREE_QUAD_TREE_DEPTH,
287 MakeTreesLeaf(forest.range,
289 forest.texture_varieties));
290 quadtree.buildQuadTree(forest._trees.begin(), forest._trees.end());
291 group = quadtree.getRoot();
293 group->setStateSet(stateset);
294 return group.release();