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

Revision 1868, 9.4 kB (checked in by robert, 12 years ago)

Added Geoff Michel's osgpick and osgUtil::PickVisitor? code.

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