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

Revision 1885, 8.8 kB (checked in by robert, 11 years ago)

Added convinence methods to osgProducer::Viewer:

/** compute, from normalized mouse coords, for sepecified Camera, the pixel coords relative to that Camera's RenderSurface?.*/
bool computePixelCoords(float x,float y,unsigned int cameraNum,float& pixel_x,float& pixel_y);

/** compute, from normalized mouse coords, for sepecified Camera, the near and far points in worlds coords.*/
bool computeNearFar(float x,float y,unsigned int cameraNum,osg::Vec3& near, osg::Vec3& far);

/** compute, from normalized mouse coords, for sepecified Camera, intersections with the scene.*/
bool computeIntersections(float x,float y,unsigned int cameraNum,osgUtil::IntersectVisitor::HitList?& hits);

/** compute, from normalized mouse coords, for all Cameras, intersections with the scene.*/
bool computeIntersections(float x,float y,osgUtil::IntersectVisitor::HitList?& hits);

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