root/OpenSceneGraph/trunk/examples/osgpoints/osgpoints.cpp @ 5381

Revision 5381, 8.3 kB (checked in by robert, 8 years ago)

Added viewer.cleanup_frame() to all examples.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
Line 
1/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield
2 *
3 * This application is open source and may be redistributed and/or modified   
4 * freely and without restriction, both in commericial and non commericial applications,
5 * as long as this copyright notice is maintained.
6 *
7 * This application is distributed in the hope that it will be useful,
8 * but WITHOUT ANY WARRANTY; without even the implied warranty of
9 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
10*/
11
12#include <osgDB/ReadFile>
13#include <osgUtil/Optimizer>
14#include <osgProducer/Viewer>
15
16#include <osg/Point>
17#include <osg/BlendFunc>
18#include <osg/Texture2D>
19#include <osg/PointSprite>
20
21class KeyboardEventHandler : public osgGA::GUIEventHandler
22{
23public:
24   
25        KeyboardEventHandler(osg::StateSet* stateset):
26            _stateset(stateset)
27        {
28            _point = new osg::Point;
29            _point->setDistanceAttenuation(osg::Vec3(0.0,0.0000,0.05f));
30            _stateset->setAttribute(_point.get());
31        }
32   
33        virtual bool handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter&)
34        {
35            switch(ea.getEventType())
36            {
37                case(osgGA::GUIEventAdapter::KEYDOWN):
38                {
39                    if (ea.getKey()=='+' || ea.getKey()==osgGA::GUIEventAdapter::KEY_KP_Add)
40                    {
41                       changePointSize(1.0f);
42                       return true;
43                    }
44                    else if (ea.getKey()=='-' || ea.getKey()==osgGA::GUIEventAdapter::KEY_KP_Subtract)
45                    {
46                       changePointSize(-1.0f);
47                       return true;
48                    }
49                    else if (ea.getKey()=='<')
50                    {
51                       changePointAttenuation(1.1f);
52                       return true;
53                    }
54                    else if (ea.getKey()=='>')
55                    {
56                       changePointAttenuation(1.0f/1.1f);
57                       return true;
58                    }
59                    break;
60                }
61                default:
62                    break;
63            }
64            return false;
65        }
66
67        virtual void accept(osgGA::GUIEventHandlerVisitor& v)
68        {
69            v.visit(*this);
70        }
71       
72       
73        float getPointSize() const
74        {
75            return _point->getSize();
76        }
77       
78        void setPointSize(float psize)
79        {
80            if (psize>0.0)
81            {
82                _point->setSize(psize);
83            }
84            std::cout<<"Point size "<<psize<<std::endl;
85        }
86
87        void changePointSize(float delta)
88        {
89            setPointSize(getPointSize()+delta);
90        }
91
92        void changePointAttenuation(float scale)
93        {
94            _point->setDistanceAttenuation(_point->getDistanceAttenuation()*scale);
95        }
96       
97        osg::ref_ptr<osg::StateSet> _stateset;
98        osg::ref_ptr<osg::Point>    _point;
99       
100};
101
102int main( int argc, char **argv )
103{
104
105    // use an ArgumentParser object to manage the program arguments.
106    osg::ArgumentParser arguments(&argc,argv);
107   
108    // set up the usage document, in case we need to print out how to use this program.
109    arguments.getApplicationUsage()->setApplicationName(arguments.getApplicationName());
110    arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" example provides an interactive viewer for visualising point clouds..");
111    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ...");
112    arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
113    arguments.getApplicationUsage()->addCommandLineOption("--sprites","Point sprites.");
114   
115
116    // construct the viewer.
117    osgProducer::Viewer viewer(arguments);
118
119    // set up the value with sensible default event handlers.
120    viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS);
121
122    // get details on keyboard and mouse bindings used by the viewer.
123    viewer.getUsage(*arguments.getApplicationUsage());
124
125    bool shader = false;
126    while (arguments.read("--shader")) shader = true;
127
128    // if user request help write it out to cout.
129    if (arguments.read("-h") || arguments.read("--help"))
130    {
131        arguments.getApplicationUsage()->write(std::cout);
132        return 1;
133    }
134   
135    bool usePointSprites = false;
136    while (arguments.read("--sprites")) { usePointSprites = true; };
137
138    // any option left unread are converted into errors to write out later.
139    arguments.reportRemainingOptionsAsUnrecognized();
140
141    // report any errors if they have occured when parsing the program aguments.
142    if (arguments.errors())
143    {
144        arguments.writeErrorMessages(std::cout);
145        return 1;
146    }
147   
148    if (arguments.argc()<=1)
149    {
150        arguments.getApplicationUsage()->write(std::cout,osg::ApplicationUsage::COMMAND_LINE_OPTION);
151        return 1;
152    }
153
154    osg::Timer timer;
155    osg::Timer_t start_tick = timer.tick();
156
157    // read the scene from the list of file specified commandline args.
158    osg::ref_ptr<osg::Node> loadedModel = osgDB::readNodeFiles(arguments);
159
160    // if no model has been successfully loaded report failure.
161    if (!loadedModel)
162    {
163        std::cout << arguments.getApplicationName() <<": No data loaded" << std::endl;
164        return 1;
165    }
166
167    osg::Timer_t end_tick = timer.tick();
168
169    std::cout << "Time to load = "<<timer.delta_s(start_tick,end_tick)<<std::endl;
170
171    // optimize the scene graph, remove rendundent nodes and state etc.
172    osgUtil::Optimizer optimizer;
173    optimizer.optimize(loadedModel.get());
174
175
176    // set the scene to render
177    viewer.setSceneData(loadedModel.get());
178   
179
180    if (usePointSprites)   
181    {
182        osg::StateSet* stateset = loadedModel->getOrCreateStateSet();
183
184        /// Setup cool blending
185        osg::BlendFunc *fn = new osg::BlendFunc();
186        stateset->setAttributeAndModes(fn, osg::StateAttribute::ON);
187
188        /// Setup the point sprites
189        osg::PointSprite *sprite = new osg::PointSprite();
190        stateset->setTextureAttributeAndModes(0, sprite, osg::StateAttribute::ON);
191
192        /// The texture for the sprites
193        osg::Texture2D *tex = new osg::Texture2D();
194        tex->setImage(osgDB::readImageFile("Images/particle.rgb"));
195        stateset->setTextureAttributeAndModes(0, tex, osg::StateAttribute::ON);
196    }
197   
198
199    // register the handler for modifying the point size
200    viewer.getEventHandlerList().push_front(new KeyboardEventHandler(viewer.getGlobalStateSet()));
201
202
203    if (shader)
204    {
205        osg::StateSet* stateset = loadedModel->getOrCreateStateSet();
206   
207        ///////////////////////////////////////////////////////////////////
208        // vertex shader using just Vec4 coefficients
209        char vertexShaderSource[] =
210            "void main(void) \n"
211            "{ \n"
212            "\n"
213            "    gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;\n"
214            "}\n";
215
216
217
218        osg::Program* program = new osg::Program;
219        stateset->setAttribute(program);
220
221        osg::Shader* vertex_shader = new osg::Shader(osg::Shader::VERTEX, vertexShaderSource);
222        program->addShader(vertex_shader);
223
224#if 0
225        //////////////////////////////////////////////////////////////////
226        // fragment shader
227        //
228        char fragmentShaderSource[] =
229            "void main(void) \n"
230            "{ \n"
231            "    gl_FragColor = gl_Color; \n"
232            "}\n";
233
234        osg::Shader* fragment_shader = new osg::Shader(osg::Shader::FRAGMENT, fragmentShaderSource);
235        program->addShader(fragment_shader);
236#endif
237    }
238
239
240
241    // create the windows and run the threads.
242    viewer.realize();
243
244    while( !viewer.done() )
245    {
246        // wait for all cull and draw threads to complete.
247        viewer.sync();
248
249        // update the scene by traversing it with the the update visitor which will
250        // call all node update callbacks and animations.
251        viewer.update();
252         
253        // fire off the cull and draw traversals of the scene.
254        viewer.frame();
255       
256    }
257   
258    // wait for all cull and draw threads to complete.
259    viewer.sync();
260
261    // run a clean up frame to delete all OpenGL objects.
262    viewer.cleanup_frame();
263
264    // wait for all the clean up frame to complete.
265    viewer.sync();
266
267    return 0;
268}
Note: See TracBrowser for help on using the browser.