root/OpenSceneGraph/trunk/examples/osgpick/osgpick.cpp @ 3995

Revision 3995, 9.3 kB (checked in by robert, 10 years ago)

Added #include <osg/io_utils>

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
Line 
1/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2003 Robert Osfield
2 *
3 * This library is open source and may be redistributed and/or modified under 
4 * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
5 * (at your option) any later version.  The full license is in LICENSE file
6 * included with this distribution, and on the openscenegraph.org website.
7 *
8 * This library is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11 * OpenSceneGraph Public License for more details.
12*/
13/* osgpick sample
14* demonstrate use of osgUtil/PickVisitor for picking in a HUD or
15* in a 3d scene,
16*/
17
18#include <osgUtil/Optimizer>
19#include <osgDB/ReadFile>
20#include <osgProducer/Viewer>
21
22#include <osg/Material>
23#include <osg/Geode>
24#include <osg/BlendFunc>
25#include <osg/Depth>
26#include <osg/Projection>
27#include <osg/MatrixTransform>
28#include <osg/io_utils>
29
30#include <osgText/Text>
31
32#include <sstream>
33
34// class to handle events with a pick
35class PickHandler : public osgGA::GUIEventHandler {
36public:
37
38    PickHandler(osgProducer::Viewer* viewer,osgText::Text* updateText):
39        _viewer(viewer),
40        _updateText(updateText) {}
41       
42    ~PickHandler() {}
43   
44    bool handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter& us);
45
46    virtual void pick(const osgGA::GUIEventAdapter& ea);
47
48    void setLabel(const std::string& name)
49    {
50        if (_updateText.get()) _updateText->setText(name);
51    }
52   
53protected:
54
55    osgProducer::Viewer* _viewer;
56    osg::ref_ptr<osgText::Text>  _updateText;
57};
58
59bool PickHandler::handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter&)
60{
61    switch(ea.getEventType())
62    {
63    case(osgGA::GUIEventAdapter::FRAME):
64        {
65            pick(ea);
66        }
67        return false;
68       
69    default:
70        return false;
71    }
72}
73
74void PickHandler::pick(const osgGA::GUIEventAdapter& ea)
75{
76    osgUtil::IntersectVisitor::HitList hlist;
77   
78    std::string gdlist="";
79    if (_viewer->computeIntersections(ea.getX(),ea.getY(),hlist))
80    {
81        for(osgUtil::IntersectVisitor::HitList::iterator hitr=hlist.begin();
82            hitr!=hlist.end();
83            ++hitr)
84        {
85            std::ostringstream os;
86            if (hitr->_geode.valid() && !hitr->_geode->getName().empty())
87            {
88                // the geodes are identified by name.
89                os<<"Object \""<<hitr->_geode->getName()<<"\""<<std::endl;
90            }
91            else if (hitr->_drawable.valid())
92            {
93                os<<"Object \""<<hitr->_drawable->className()<<"\""<<std::endl;
94            }
95
96            os<<"        local coords vertex("<< hitr->getLocalIntersectPoint()<<")"<<"  normal("<<hitr->getLocalIntersectNormal()<<")"<<std::endl;
97            os<<"        world coords vertex("<< hitr->getWorldIntersectPoint()<<")"<<"  normal("<<hitr->getWorldIntersectNormal()<<")"<<std::endl;
98            osgUtil::Hit::VecIndexList& vil = hitr->_vecIndexList;
99            for(unsigned int i=0;i<vil.size();++i)
100            {
101                os<<"        vertex indices ["<<i<<"] = "<<vil[i]<<std::endl;
102            }
103           
104            gdlist += os.str();
105        }
106    }
107    setLabel(gdlist);
108}
109
110osg::Node* createHUD(osgText::Text* updateText)
111{    // create the hud. derived from osgHud.cpp
112    // adds a set of quads, each in a separate Geode - which can be picked individually
113    // eg to be used as a menuing/help system!
114    // Can pick texts too!
115    osg::MatrixTransform* modelview_abs = new osg::MatrixTransform;
116    modelview_abs->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
117    modelview_abs->setMatrix(osg::Matrix::identity());
118   
119    osg::Projection* projection = new osg::Projection;
120    projection->setMatrix(osg::Matrix::ortho2D(0,1280,0,1024));
121    projection->addChild(modelview_abs);
122   
123   
124    std::string timesFont("fonts/times.ttf");
125   
126    // turn lighting off for the text and disable depth test to ensure its always ontop.
127    osg::Vec3 position(150.0f,800.0f,0.0f);
128    osg::Vec3 delta(0.0f,-60.0f,0.0f);
129   
130    {
131        osg::Geode* geode = new osg::Geode();
132        osg::StateSet* stateset = geode->getOrCreateStateSet();
133        stateset->setMode(GL_LIGHTING,osg::StateAttribute::OFF);
134        stateset->setMode(GL_DEPTH_TEST,osg::StateAttribute::OFF);
135        geode->setName("simple");
136        modelview_abs->addChild(geode);
137       
138        osgText::Text* text = new  osgText::Text;
139        geode->addDrawable( text );
140       
141        text->setFont(timesFont);
142        text->setText("Picking in Head Up Displays is simple !=]");
143        text->setPosition(position);
144       
145        position += delta;
146    }   
147   
148   
149    for (int i=0; i<5; i++) {
150        osg::Vec3 dy(0.0f,-30.0f,0.0f);
151        osg::Vec3 dx(120.0f,0.0f,0.0f);
152        osg::Geode* geode = new osg::Geode();
153        osg::StateSet* stateset = geode->getOrCreateStateSet();
154        const char *opts[]={"One", "Two", "Three", "January", "Feb", "2003"};
155        osg::Geometry *quad=new osg::Geometry;
156        stateset->setMode(GL_LIGHTING,osg::StateAttribute::OFF);
157        stateset->setMode(GL_DEPTH_TEST,osg::StateAttribute::OFF);
158        std::string name="subOption";
159        name += " ";
160        name += std::string(opts[i]);
161        geode->setName(name);
162        osg::Vec3Array* vertices = new osg::Vec3Array(4); // 1 quad
163        osg::Vec4Array* colors = new osg::Vec4Array;
164        colors = new osg::Vec4Array;
165        colors->push_back(osg::Vec4(0.8-0.1*i,0.1*i,0.2*i, 1.0));
166        quad->setColorArray(colors);
167        quad->setColorBinding(osg::Geometry::BIND_PER_PRIMITIVE);
168        (*vertices)[0]=position;
169        (*vertices)[1]=position+dx;
170        (*vertices)[2]=position+dx+dy;
171        (*vertices)[3]=position+dy;
172        quad->setVertexArray(vertices);
173        quad->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::QUADS,0,4));
174        geode->addDrawable(quad);
175        modelview_abs->addChild(geode);
176       
177        position += delta;
178    }   
179   
180   
181   
182    { // this displays what has been selected
183        osg::Geode* geode = new osg::Geode();
184        osg::StateSet* stateset = geode->getOrCreateStateSet();
185        stateset->setMode(GL_LIGHTING,osg::StateAttribute::OFF);
186        stateset->setMode(GL_DEPTH_TEST,osg::StateAttribute::OFF);
187        geode->setName("The text label");
188        geode->addDrawable( updateText );
189        modelview_abs->addChild(geode);
190       
191        updateText->setCharacterSize(20.0f);
192        updateText->setFont(timesFont);
193        updateText->setColor(osg::Vec4(1.0f,1.0f,0.0f,1.0f));
194        updateText->setText("");
195        updateText->setPosition(position);
196       
197        position += delta;
198    }   
199   
200    return projection;
201
202}
203
204int main( int argc, char **argv )
205{
206
207    // use an ArgumentParser object to manage the program arguments.
208    osg::ArgumentParser arguments(&argc,argv);
209   
210    // set up the usage document, in case we need to print out how to use this program.
211    arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the example which demonstrates how to do Head Up Displays.");
212    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] [filename] ...");
213    arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
214   
215
216    // construct the viewer.
217    osgProducer::Viewer viewer(arguments);
218
219    // set up the value with sensible default event handlers.
220    viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS);
221
222    // get details on keyboard and mouse bindings used by the viewer.
223    viewer.getUsage(*arguments.getApplicationUsage());
224
225    // if user request help write it out to cout.
226    if (arguments.read("-h") || arguments.read("--help"))
227    {
228        arguments.getApplicationUsage()->write(std::cout);
229        return 1;
230    }
231
232    // any option left unread are converted into errors to write out later.
233    arguments.reportRemainingOptionsAsUnrecognized();
234
235    // report any errors if they have occured when parsing the program aguments.
236    if (arguments.errors())
237    {
238        arguments.writeErrorMessages(std::cout);
239        return 1;
240    }
241   
242    // read the scene from the list of file specified commandline args.
243    osg::ref_ptr<osg::Node> scene = osgDB::readNodeFiles(arguments);
244
245    osg::ref_ptr<osg::Group> group = dynamic_cast<osg::Group*>(scene.get());
246    if (!group)
247    {
248        group = new osg::Group;
249        group->addChild(scene.get());
250    }
251
252    osg::ref_ptr<osgText::Text> updateText = new osgText::Text;
253
254    // add the HUD subgraph.   
255    group->addChild(createHUD(updateText.get()));
256
257    // add the handler for doing the picking
258    viewer.getEventHandlerList().push_front(new PickHandler(&viewer,updateText.get()));
259
260    // set the scene to render
261    viewer.setSceneData(group.get());
262
263    // create the windows and run the threads.
264    viewer.realize();
265
266    while( !viewer.done() )
267    {
268        // wait for all cull and draw threads to complete.
269        viewer.sync();
270
271        // update the scene by traversing it with the the update visitor which will
272        // call all node update callbacks and animations.
273        viewer.update();
274         
275        // fire off the cull and draw traversals of the scene.
276        viewer.frame();
277       
278    }
279   
280    // wait for all cull and draw threads to complete before exit.
281    viewer.sync();
282   
283    return 0;
284}
Note: See TracBrowser for help on using the browser.