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

Revision 1875, 9.5 kB (checked in by robert, 12 years ago)

Updates to the osgpick code.

Updates to osgGA::CameraManipulors?.

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