root/OpenSceneGraph/trunk/examples/osgdistortion/osgdistortion.cpp @ 2590

Revision 2590, 9.9 kB (checked in by robert, 11 years ago)

Added osgdistortion demo.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
Line 
1#include <osg/GLExtensions>
2#include <osg/Node>
3#include <osg/Geometry>
4#include <osg/Notify>
5#include <osg/MatrixTransform>
6#include <osg/Texture2D>
7#include <osg/Stencil>
8#include <osg/ColorMask>
9#include <osg/Depth>
10#include <osg/Billboard>
11#include <osg/Material>
12#include <osg/Projection>
13
14#include <osgGA/TrackballManipulator>
15#include <osgGA/FlightManipulator>
16#include <osgGA/DriveManipulator>
17
18#include <osgUtil/TransformCallback>
19#include <osgUtil/RenderToTextureStage>
20#include <osgUtil/SmoothingVisitor>
21
22#include <osgDB/Registry>
23#include <osgDB/ReadFile>
24
25#include <osgProducer/Viewer>
26
27class DistortionNode : public osg::Group
28{
29public:
30
31    DistortionNode();
32   
33    DistortionNode(const DistortionNode& rhs,const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY):
34        osg::Group(rhs,copyop) {}
35
36    META_Node(osgDistortion, DistortionNode);
37
38    virtual void traverse(osg::NodeVisitor& nv);
39
40protected:
41
42    void createHUDSubgraph();
43
44    void preRender(osgUtil::CullVisitor& nv);   
45
46    osg::ref_ptr<osg::Node>         _hudSubgraph;
47    osg::ref_ptr<osg::Texture2D>    _texture;   
48    osg::ref_ptr<osg::StateSet>     _localStateSet;
49   
50};
51
52
53DistortionNode::DistortionNode()
54{
55    createHUDSubgraph();
56}
57
58void DistortionNode::createHUDSubgraph()
59{
60    // create the quad to visualize.
61    osg::Geometry* polyGeom = new osg::Geometry();
62
63    polyGeom->setSupportsDisplayList(false);
64
65    osg::Vec3 origin(0.0f,0.0f,0.0f);
66    osg::Vec3 xAxis(1.0f,0.0f,0.0f);
67    osg::Vec3 yAxis(0.0f,1.0f,0.0f);
68    osg::Vec3 zAxis(0.0f,0.0f,1.0f);
69    float height = 1024.0f;
70    float width = 1280.0f;
71    int noSteps = 50;
72   
73    osg::Vec3Array* vertices = new osg::Vec3Array;
74    osg::Vec2Array* texcoords = new osg::Vec2Array;
75    osg::Vec4Array* colors = new osg::Vec4Array;
76
77    osg::Vec3 bottom = origin;
78    osg::Vec3 dx = xAxis*(width/((float)(noSteps-1)));
79    osg::Vec3 dy = yAxis*(height/((float)(noSteps-1)));
80   
81    osg::Vec2 bottom_texcoord(0.0f,0.0f);
82    osg::Vec2 dx_texcoord(1.0f/(float)(noSteps-1),0.0f);
83    osg::Vec2 dy_texcoord(0.0f,1.0f/(float)(noSteps-1));
84   
85    osg::Vec3 cursor = bottom;
86    osg::Vec2 texcoord = bottom_texcoord;
87    int i,j;
88    for(i=0;i<noSteps;++i)
89    {
90        osg::Vec3 cursor = bottom+dy*(float)i;
91        osg::Vec2 texcoord = bottom_texcoord+dy_texcoord*(float)i;
92        for(j=0;j<noSteps;++j)
93        {
94            vertices->push_back(cursor);
95            texcoords->push_back(osg::Vec2((sin(texcoord.x()*osg::PI-osg::PI*0.5)+1.0f)*0.5f,(sin(texcoord.y()*osg::PI-osg::PI*0.5)+1.0f)*0.5f));
96            colors->push_back(osg::Vec4(1.0f,1.0f,1.0f,1.0f));
97           
98            cursor += dx;
99            texcoord += dx_texcoord;
100        }
101    }
102
103    // pass the created vertex array to the points geometry object.
104    polyGeom->setVertexArray(vertices);
105
106    polyGeom->setColorArray(colors);
107    polyGeom->setColorBinding(osg::Geometry::BIND_PER_VERTEX);
108
109    polyGeom->setTexCoordArray(0,texcoords);
110   
111
112    for(i=0;i<noSteps-1;++i)
113    {
114        osg::DrawElementsUShort* elements = new osg::DrawElementsUShort(osg::PrimitiveSet::QUAD_STRIP);
115        for(j=0;j<noSteps;++j)
116        {
117            elements->push_back(j+(i+1)*noSteps);
118            elements->push_back(j+(i)*noSteps);
119        }
120        polyGeom->addPrimitiveSet(elements);
121    }
122
123
124    // new we need to add the texture to the Drawable, we do so by creating a
125    // StateSet to contain the Texture StateAttribute.
126    osg::StateSet* stateset = new osg::StateSet;
127
128    osg::Texture2D* texture = new osg::Texture2D;
129//     texture->setFilter(osg::Texture2D::MIN_FILTER,osg::Texture2D::NEAREST);
130//     texture->setFilter(osg::Texture2D::MAG_FILTER,osg::Texture2D::NEAREST);
131    texture->setFilter(osg::Texture2D::MIN_FILTER,osg::Texture2D::LINEAR);
132    texture->setFilter(osg::Texture2D::MAG_FILTER,osg::Texture2D::LINEAR);
133    stateset->setTextureAttributeAndModes(0, texture,osg::StateAttribute::ON);
134    stateset->setMode(GL_LIGHTING,osg::StateAttribute::OFF);
135    polyGeom->setStateSet(stateset);
136   
137    _texture = texture;
138
139    osg::Geode* geode = new osg::Geode();
140    geode->addDrawable(polyGeom);
141
142    // create the hud.
143    osg::MatrixTransform* modelview_abs = new osg::MatrixTransform;
144    modelview_abs->setReferenceFrame(osg::Transform::RELATIVE_TO_ABSOLUTE);
145    modelview_abs->setMatrix(osg::Matrix::identity());
146    modelview_abs->addChild(geode);
147
148    osg::Projection* projection = new osg::Projection;
149    projection->setMatrix(osg::Matrix::ortho2D(0,1280,0,1024));
150    projection->addChild(modelview_abs);
151
152    _hudSubgraph = projection;
153   
154    _localStateSet = new osg::StateSet;
155
156
157}
158
159
160void DistortionNode::traverse(osg::NodeVisitor& nv)
161{
162    if (nv.getVisitorType()==osg::NodeVisitor::CULL_VISITOR)
163    {
164        osgUtil::CullVisitor* cullVisitor = dynamic_cast<osgUtil::CullVisitor*>(&nv);
165        if (cullVisitor && _texture.valid() && _hudSubgraph.valid())
166        {
167            preRender(*cullVisitor);
168           
169            _hudSubgraph->accept(nv);
170           
171            return;
172        }
173    }
174   
175    Group::traverse(nv);
176}
177
178void DistortionNode::preRender(osgUtil::CullVisitor& cv)
179{   
180    // create the render to texture stage.
181    osg::ref_ptr<osgUtil::RenderToTextureStage> rtts = new osgUtil::RenderToTextureStage;
182
183    // set up lighting.
184    // currently ignore lights in the scene graph itself..
185    // will do later.
186    osgUtil::RenderStage* previous_stage = cv.getCurrentRenderBin()->_stage;
187
188    // set up the background color and clear mask.
189    rtts->setClearColor(osg::Vec4(0.1f,0.1f,0.3f,1.0f));
190    rtts->setClearMask(previous_stage->getClearMask());
191
192    // set up to charge the same RenderStageLighting is the parent previous stage.
193    rtts->setRenderStageLighting(previous_stage->getRenderStageLighting());
194
195
196    // record the render bin, to be restored after creation
197    // of the render to text
198    osgUtil::RenderBin* previousRenderBin = cv.getCurrentRenderBin();
199
200    // set the current renderbin to be the newly created stage.
201    cv.setCurrentRenderBin(rtts.get());
202
203    cv.pushStateSet(_localStateSet.get());
204
205    {
206
207        // traverse the subgraph
208        Group::traverse(cv);
209
210    }
211
212    cv.popStateSet();
213
214    // restore the previous renderbin.
215    cv.setCurrentRenderBin(previousRenderBin);
216
217    if (rtts->_renderGraphList.size()==0 && rtts->_bins.size()==0)
218    {
219        // getting to this point means that all the subgraph has been
220        // culled by small feature culling or is beyond LOD ranges.
221        return;
222    }
223
224    int height = 1024;
225    int width  = 1024;
226
227
228    const osg::Viewport& viewport = *cv.getViewport();
229
230    // offset the impostor viewport from the center of the main window
231    // viewport as often the edges of the viewport might be obscured by
232    // other windows, which can cause image/reading writing problems.
233    int center_x = viewport.x()+viewport.width()/2;
234    int center_y = viewport.y()+viewport.height()/2;
235
236    osg::Viewport* new_viewport = new osg::Viewport;
237    new_viewport->setViewport(center_x-width/2,center_y-height/2,width,height);
238    rtts->setViewport(new_viewport);
239   
240    _localStateSet->setAttribute(new_viewport);
241
242    // and the render to texture stage to the current stages
243    // dependancy list.
244    cv.getCurrentRenderBin()->_stage->addToDependencyList(rtts.get());
245
246    // if one exist attach texture to the RenderToTextureStage.
247    if (_texture.valid()) rtts->setTexture(_texture.get());
248}
249
250
251int main( int argc, char **argv )
252{
253    // use an ArgumentParser object to manage the program arguments.
254    osg::ArgumentParser arguments(&argc,argv);
255
256    // set up the usage document, in case we need to print out how to use this program.
257    arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the example which demonstrates pre rendering of scene to a texture, and then apply this texture to geometry.");
258    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ...");
259    arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
260   
261    // construct the viewer.
262    osgProducer::Viewer viewer(arguments);
263
264    // set up the value with sensible default event handlers.
265    viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS);
266
267    // get details on keyboard and mouse bindings used by the viewer.
268    viewer.getUsage(*arguments.getApplicationUsage());
269
270    // if user request help write it out to cout.
271    if (arguments.read("-h") || arguments.read("--help"))
272    {
273        arguments.getApplicationUsage()->write(std::cout);
274        return 1;
275    }
276
277    // any option left unread are converted into errors to write out later.
278    arguments.reportRemainingOptionsAsUnrecognized();
279
280    // report any errors if they have occured when parsing the program aguments.
281    if (arguments.errors())
282    {
283        arguments.writeErrorMessages(std::cout);
284        return 1;
285    }
286   
287    if (arguments.argc()<=1)
288    {
289        arguments.getApplicationUsage()->write(std::cout,osg::ApplicationUsage::COMMAND_LINE_OPTION);
290        return 1;
291    }
292
293   
294    // load the nodes from the commandline arguments.
295    osg::Node* loadedModel = osgDB::readNodeFiles(arguments);
296    if (!loadedModel)
297    {
298//        write_usage(osg::notify(osg::NOTICE),argv[0]);
299        return 1;
300    }
301   
302    // create a transform to spin the model.
303    DistortionNode* distortionNode = new DistortionNode;
304    distortionNode->addChild(loadedModel);
305
306    // add model to the viewer.
307    viewer.setSceneData( distortionNode );
308
309    // create the windows and run the threads.
310    viewer.realize();
311
312    while( !viewer.done() )
313    {
314        // wait for all cull and draw threads to complete.
315        viewer.sync();
316
317        // update the scene by traversing it with the the update visitor which will
318        // call all node update callbacks and animations.
319        viewer.update();
320         
321        // fire off the cull and draw traversals of the scene.
322        viewer.frame();
323       
324    }
325   
326    // wait for all cull and draw threads to complete before exit.
327    viewer.sync();
328
329    return 0;
330}
Note: See TracBrowser for help on using the browser.