root/OpenSceneGraph/trunk/examples/osgparametric/osgparametric.cpp @ 4349

Revision 4349, 9.4 kB (checked in by robert, 9 years ago)

Added option for terrain texturing.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
Line 
1#include <osg/Vec3>
2#include <osg/Vec4>
3#include <osg/Quat>
4#include <osg/Matrix>
5#include <osg/ShapeDrawable>
6#include <osg/Geometry>
7#include <osg/Geode>
8#include <osg/Texture2D>
9
10#include <osgDB/FileUtils>
11#include <osgDB/ReadFile>
12
13#include <osgUtil/Optimizer>
14
15#include <osgProducer/Viewer>
16
17// for the grid data..
18#include "../osghangglide/terrain_coords.h"
19
20///////////////////////////////////////////////////////////////////
21// vertex shader using just Vec4 coefficients
22char vertexShaderSource_simple[] =
23    "uniform vec4 coeff; \n"
24    "\n"
25    "void main(void) \n"
26    "{ \n"
27    "\n"
28    "    gl_TexCoord[0] = gl_Vertex; \n"
29    "    gl_Vertex.z = gl_Vertex.x*coeff[0] + gl_Vertex.x*gl_Vertex.x* coeff[1] + \n"
30    "                  gl_Vertex.y*coeff[2] + gl_Vertex.y*gl_Vertex.y* coeff[3]; \n"
31    "    gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;\n"
32    "}\n";
33 
34 
35//////////////////////////////////////////////////////////////////
36// vertex shader using full Matrix4 coefficients
37char vertexShaderSource_matrix[] =
38    "uniform vec4  origin; \n"
39    "uniform mat4  coeffMatrix; \n"
40    "\n"
41    "void main(void) \n"
42    "{ \n"
43    "\n"
44    "    gl_TexCoord[0] = gl_Vertex; \n"
45    "    vec4 v = vec4(gl_Vertex.x, gl_Vertex.x*gl_Vertex.x, gl_Vertex.y, gl_Vertex.y*gl_Vertex.y ); \n"
46    "    gl_Position = gl_ModelViewProjectionMatrix * (origin + coeffMatrix * v);\n"
47    "}\n";
48
49//////////////////////////////////////////////////////////////////
50// vertex shader using texture read
51char vertexShaderSource_texture[] =
52    "uniform sampler2D vertexTexture; \n"
53    "\n"
54    "void main(void) \n"
55    "{ \n"
56    "\n"
57    "    gl_TexCoord[0] = gl_Vertex; \n"
58    "    gl_Vertex.z = texture2D( vertexTexture, gl_TexCoord[0].xy).x*0.0001; \n"
59    "    gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;\n"
60    "}\n";
61
62
63//////////////////////////////////////////////////////////////////
64// fragment shader
65//
66char fragmentShaderSource[] =
67    "uniform sampler2D baseTexture; \n"
68    "\n"
69    "void main(void) \n"
70    "{ \n"
71    "    gl_FragColor = texture2D( baseTexture, gl_TexCoord[0].xy); \n"
72    "}\n";
73
74
75
76class UniformVarying : public osg::Uniform::Callback
77{
78    virtual void operator () (osg::Uniform* uniform, osg::NodeVisitor* nv)
79    {
80        const osg::FrameStamp* fs = nv->getFrameStamp();
81        float value = sinf(fs->getReferenceTime());
82        uniform->set(osg::Vec4(value,-value,-value,value));
83    }
84};
85
86osg::Node* createModel(const std::string& shader, const std::string& textureFileName, const std::string& terrainFileName)
87{
88    osg::Geode* geode = new osg::Geode;
89   
90    osg::Geometry* geom = new osg::Geometry;
91    geode->addDrawable(geom);
92   
93    // dimensions for ~one million triangles :-)
94    unsigned int num_x = 708;
95    unsigned int num_y = 708;
96
97    // set up state
98    {
99   
100        osg::StateSet* stateset = geom->getOrCreateStateSet();
101
102        osg::Program* program = new osg::Program;
103        stateset->setAttribute(program);
104
105        if (shader=="simple")
106        {
107            osg::Shader* vertex_shader = new osg::Shader(osg::Shader::VERTEX, vertexShaderSource_simple);
108            program->addShader(vertex_shader);
109
110            osg::Uniform* coeff = new osg::Uniform("coeff",osg::Vec4(1.0,-1.0f,-1.0f,1.0f));
111            coeff->setUpdateCallback(new UniformVarying);
112            stateset->addUniform(coeff);
113        }
114        else if (shader=="matrix")
115        {
116            osg::Shader* vertex_shader = new osg::Shader(osg::Shader::VERTEX, vertexShaderSource_matrix);
117            program->addShader(vertex_shader);
118
119            osg::Uniform* origin = new osg::Uniform("origin",osg::Vec4(0.0f,0.0f,0.0f,1.0f));
120            stateset->addUniform(origin);
121
122            osg::Uniform* coeffMatrix = new osg::Uniform("coeffMatrix",
123                osg::Matrix(1.0f,0.0f,1.0f,0.0f,
124                            0.0f,0.0f,-1.0f,0.0f,
125                            0.0f,1.0f,-1.0f,0.0f,
126                            0.0f,0.0f,1.0f,0.0f));
127
128            stateset->addUniform(coeffMatrix);
129        }
130        else if (shader=="texture")
131        {
132            osg::Shader* vertex_shader = new osg::Shader(osg::Shader::VERTEX, vertexShaderSource_texture);
133            program->addShader(vertex_shader);
134
135            osg::Image* image = 0;
136
137            if (terrainFileName.empty())
138            {
139                image = new osg::Image;
140                unsigned int tx = 38;
141                unsigned int ty = 39;
142                image->allocateImage(tx,ty,1,GL_LUMINANCE,GL_FLOAT,1);
143                for(unsigned int r=0;r<ty;++r)
144                {
145                    for(unsigned int c=0;c<tx;++c)
146                    {
147                        *((float*)image->data(c,r)) = vertex[r+c*39][2]*0.1;
148                    }
149                }
150
151                num_x = tx;
152                num_y = tx;
153            }
154            else
155            {
156                image = osgDB::readImageFile(terrainFileName);
157
158                num_x = image->s();
159                num_y = image->t();
160            }
161
162            osg::Texture2D* vertexTexture = new osg::Texture2D(image);
163
164
165            vertexTexture->setFilter(osg::Texture::MIN_FILTER,osg::Texture::NEAREST);
166            vertexTexture->setFilter(osg::Texture::MAG_FILTER,osg::Texture::NEAREST);
167            vertexTexture->setInternalFormat(GL_LUMINANCE_FLOAT32_ATI);
168            stateset->setTextureAttributeAndModes(1,vertexTexture);
169
170            osg::Uniform* vertexTextureSampler = new osg::Uniform("vertexTexture",1);
171            stateset->addUniform(vertexTextureSampler);
172
173        }
174
175        osg::Shader* fragment_shader = new osg::Shader(osg::Shader::FRAGMENT, fragmentShaderSource);
176        program->addShader(fragment_shader);
177
178        osg::Texture2D* texture = new osg::Texture2D(osgDB::readImageFile(textureFileName));
179        stateset->setTextureAttributeAndModes(0,texture);
180
181        osg::Uniform* baseTextureSampler = new osg::Uniform("baseTexture",0);
182        stateset->addUniform(baseTextureSampler);
183
184    }
185
186
187    // set up geometry data.
188
189    osg::Vec3Array* vertices = new osg::Vec3Array( num_x * num_y );
190   
191    float dx = 1.0f/(float)(num_x-1);
192    float dy = 1.0f/(float)(num_y-1);
193    osg::Vec3 row(0.0f,0.0f,0.0);
194   
195    unsigned int vert_no = 0;
196    for(unsigned int iy=0; iy<num_y; ++iy)
197    {
198        osg::Vec3 column = row;
199        for(unsigned int ix=0;ix<num_x;++ix)
200        {
201            (*vertices)[vert_no++] = column;
202            column.x() += dx;
203        }       
204        row.y() += dy;
205    }
206
207    geom->setVertexArray(vertices);
208
209    for(unsigned int iy=0; iy<num_y-1; ++iy)
210    {
211        unsigned int element_no = 0;
212        osg::DrawElementsUInt* elements = new osg::DrawElementsUInt(GL_TRIANGLE_STRIP, num_x*2);
213        unsigned int index = iy * num_x;
214        for(unsigned int ix = 0; ix<num_x; ++ix)
215        {
216            (*elements)[element_no++] = index + num_x;
217            (*elements)[element_no++] = index++;
218        }
219        geom->addPrimitiveSet(elements);   
220    }
221   
222    geom->setUseVertexBufferObjects(true);
223   
224   
225
226
227    return geode;
228
229}
230
231int main(int argc, char *argv[])
232{
233    // use an ArgumentParser object to manage the program arguments.
234    osg::ArgumentParser arguments(&argc,argv);
235
236    // set up the usage document, in case we need to print out how to use this program.
237    arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the example which demonstrate support for ARB_vertex_program.");
238    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ...");
239    arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
240   
241    // construct the viewer.
242    osgProducer::Viewer viewer(arguments);
243
244    // set up the value with sensible default event handlers.
245    viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS);
246   
247    std::string shader("simple");
248    while(arguments.read("-s",shader)) {}
249   
250    std::string textureFileName("lz.rgb");
251    while(arguments.read("-t",textureFileName)) {}
252
253    std::string terrainFileName("");
254    while(arguments.read("-d",terrainFileName)) {}
255
256    // get details on keyboard and mouse bindings used by the viewer.
257    viewer.getUsage(*arguments.getApplicationUsage());
258
259    // if user request help write it out to cout.
260    if (arguments.read("-h") || arguments.read("--help"))
261    {
262        arguments.getApplicationUsage()->write(std::cout);
263        return 1;
264    }
265
266    // any option left unread are converted into errors to write out later.
267    arguments.reportRemainingOptionsAsUnrecognized();
268
269    // report any errors if they have occured when parsing the program aguments.
270    if (arguments.errors())
271    {
272        arguments.writeErrorMessages(std::cout);
273        return 1;
274    }
275
276    // load the nodes from the commandline arguments.
277    osg::Node* model = createModel(shader,textureFileName,terrainFileName);
278    if (!model)
279    {
280        return 1;
281    }
282
283    // add a viewport to the viewer and attach the scene graph.
284    viewer.setSceneData(model);
285   
286    // create the windows and run the threads.
287    viewer.realize();
288
289    while( !viewer.done() )
290    {
291        // wait for all cull and draw threads to complete.
292        viewer.sync();
293
294        // update the scene by traversing it with the the update visitor which will
295        // call all node update callbacks and animations.
296        viewer.update();
297         
298        // fire off the cull and draw traversals of the scene.
299        viewer.frame();
300       
301    }
302   
303    // wait for all cull and draw threads to complete before exit.
304    viewer.sync();
305
306    return 0;
307}
Note: See TracBrowser for help on using the browser.