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

Revision 1883, 12.8 kB (checked in by robert, 11 years ago)

Changed OsgSceneHandler? so it re-uses osgUtil::SceneView? project and modelview
matrices.

Changed the osgpick demo so that it uses the OsgSceneHandler?'s projection and
modelview matrices where possible.

  • 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
35static Producer::CameraConfig *BuildConfig(void)
36{
37    Producer::RenderSurface *rs1 = new Producer::RenderSurface;
38    rs1->setScreenNum(0);
39    //rs1->useBorder(false);
40    rs1->setWindowRect(0,0,640,480);
41    Producer::Camera *camera1 = new Producer::Camera;
42    camera1->setRenderSurface(rs1);
43    camera1->setOffset( 1.0, 0.0 );
44
45    Producer::RenderSurface *rs2 = new Producer::RenderSurface;
46    rs2->setScreenNum(0);
47    //rs2->useBorder(false);
48    rs2->setWindowRect(640,0,640,480);
49    Producer::Camera *camera2 = new Producer::Camera;
50    camera2->setRenderSurface(rs2);
51    camera2->setOffset( -1.0, 0.0 );
52
53    Producer::InputArea *ia = new Producer::InputArea;
54    ia->addInputRectangle( rs1, Producer::InputRectangle(0.0,0.5,0.0,1.0));
55    ia->addInputRectangle( rs2, Producer::InputRectangle(0.5,1.0,0.0,1.0));
56//    ia->addInputRectangle( rs1, Producer::InputRectangle(-1.0,0.0,-1.0,1.0));
57//    ia->addInputRectangle( rs2, Producer::InputRectangle(0.0,1.0,-1.0,1.0));
58
59
60    Producer::CameraConfig *cfg = new Producer::CameraConfig;
61    cfg->addCamera("Camera 1",camera1);
62    cfg->addCamera("Camera 2", camera2);
63    cfg->setInputArea(ia);
64    return cfg;
65}
66
67// class to handle events with a pick
68class PickHandler : public osgGA::GUIEventHandler {
69public:
70
71    PickHandler(osgProducer::Viewer* viewer,osgText::Text* updateText):
72        _viewer(viewer),
73        _updateText(updateText) {}
74       
75    ~PickHandler() {}
76   
77    bool handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter& us);
78
79    virtual void pick(const osgGA::GUIEventAdapter& ea);
80
81    void setLabel(const std::string& name)
82    {
83        if (_updateText.get()) _updateText->setText(name);
84    }
85   
86protected:
87
88    osgProducer::Viewer* _viewer;
89    osg::ref_ptr<osgText::Text>  _updateText;
90};
91
92bool PickHandler::handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter&)
93{
94    switch(ea.getEventType())
95    {
96    case(osgGA::GUIEventAdapter::FRAME):
97        {
98            pick(ea);
99        }
100        return false;
101       
102    default:
103        return false;
104    }
105}
106
107void PickHandler::pick(const osgGA::GUIEventAdapter& ea)
108{
109    // OK here is the interesting bit - How To Pick a Geode
110    // including geodes in a HUD under a Projection Matrix
111    osg::Node *scene=_viewer->getSceneData();//main node of the scene.
112    if (scene)
113    {
114        float x=ea.getX();
115        float y=ea.getY();
116
117
118        Producer::KeyboardMouse* km = _viewer->getKeyboardMouse();
119
120
121        std::string gdlist="";
122
123        for(unsigned int i=0;i<_viewer->getNumberOfCameras();++i)
124        {
125            Producer::Camera* cmm=_viewer->getCamera(i);
126            Producer::RenderSurface* rs = cmm->getRenderSurface();
127
128            //std::cout << "checking camara "<<i<<std::endl;
129
130            float pixel_x,pixel_y;
131            if (km->computePixelCoords(x,y,rs,pixel_x,pixel_y))
132            {
133                //std::cout << "    compute pixel coords "<<pixel_x<<"  "<<pixel_y<<std::endl;
134
135                int pr_wx, pr_wy;
136                unsigned int pr_width, pr_height;
137                cmm->getProjectionRect( pr_wx, pr_wy, pr_width, pr_height );
138
139                int rs_wx, rs_wy;
140                unsigned int rs_width, rs_height;
141                rs->getWindowRect( rs_wx, rs_wy, rs_width, rs_height );
142               
143                pr_wx += rs_wx;
144                pr_wy += rs_wy;
145
146                //std::cout << "    wx = "<<pr_wx<<"  wy = "<<pr_wy<<" width="<<pr_width<<" height="<<pr_height<<std::endl;
147
148
149
150                if (pixel_x<(float)pr_wx) break;
151                if (pixel_x>(float)(pr_wx+pr_width)) break;
152
153                if (pixel_y<(float)pr_wy) break;
154                if (pixel_y>(float)(pr_wy+pr_height)) break;
155
156
157                float rx = 2.0f*(pixel_x - (float)pr_wx)/(float)pr_width-1.0f;
158                float ry = 2.0f*(pixel_y - (float)pr_wy)/(float)pr_height-1.0f;
159
160                //std::cout << "    rx "<<rx<<"  "<<ry<<std::endl;
161               
162                osgProducer::OsgSceneHandler* sh = dynamic_cast<osgProducer::OsgSceneHandler*>(cmm->getSceneHandler());
163                osg::Matrix vum;
164                if (sh!=0 && sh->getModelViewMatrix()!=0 && sh->getProjectionMatrix()!=0)
165                {
166                    vum.set((*(sh->getModelViewMatrix())) *
167                            (*(sh->getProjectionMatrix())));
168                }
169                else
170                {
171                    vum.set(osg::Matrix(cmm->getViewMatrix()) *
172                            osg::Matrix(cmm->getProjectionMatrix())/* *
173                            osg::Matrix::translate(1.0f,1.0f,1.0f) *
174                            osg::Matrix::scale(0.5f,0.5f,0.5f)*/);
175                }
176               
177                osgUtil::PickVisitor iv;
178                osgUtil::IntersectVisitor::HitList& hlist=iv.getHits(scene, vum, rx,ry);
179                if (iv.hits())
180                {
181                    for(osgUtil::IntersectVisitor::HitList::iterator hitr=hlist.begin();
182                    hitr!=hlist.end();
183                    ++hitr)
184                    {
185                        //osg::Vec3 ip = hitr->getLocalIntersectPoint();
186                        //osg::Vec3 in = hitr->getLocalIntersectNormal();
187                        osg::Geode* geode = hitr->_geode.get();
188                        // the geodes are identified by name.
189                        if (geode)
190                        {
191                            if (!geode->getName().empty())
192                            {
193                                gdlist=gdlist+" "+geode->getName();
194                            }
195                            else
196                            {
197                                gdlist=gdlist+" geode";
198                            }
199                        }
200                    }
201                }
202            }
203        }
204
205        setLabel(gdlist);
206    }
207}
208
209osg::Node* createHUD(osgText::Text* updateText)
210{    // create the hud. derived from osgHud.cpp
211    // adds a set of quads, each in a separate Geode - which can be picked individually
212    // eg to be used as a menuing/help system!
213    // Can pick texts too!
214    osg::MatrixTransform* modelview_abs = new osg::MatrixTransform;
215    modelview_abs->setReferenceFrame(osg::Transform::RELATIVE_TO_ABSOLUTE);
216    modelview_abs->setMatrix(osg::Matrix::identity());
217   
218    osg::Projection* projection = new osg::Projection;
219    projection->setMatrix(osg::Matrix::ortho2D(0,1280,0,1024));
220    projection->addChild(modelview_abs);
221   
222   
223    std::string timesFont("fonts/times.ttf");
224   
225    // turn lighting off for the text and disable depth test to ensure its always ontop.
226    osg::Vec3 position(150.0f,800.0f,0.0f);
227    osg::Vec3 delta(0.0f,-60.0f,0.0f);
228   
229    {
230        osg::Geode* geode = new osg::Geode();
231        osg::StateSet* stateset = geode->getOrCreateStateSet();
232        stateset->setMode(GL_LIGHTING,osg::StateAttribute::OFF);
233        stateset->setMode(GL_DEPTH_TEST,osg::StateAttribute::OFF);
234        geode->setName("simple");
235        modelview_abs->addChild(geode);
236       
237        osgText::Text* text = new  osgText::Text;
238        geode->addDrawable( text );
239       
240        text->setFont(timesFont);
241        text->setText("Picking in Head Up Displays is simple !=]");
242        text->setPosition(position);
243       
244        position += delta;
245    }   
246   
247   
248    for (int i=0; i<5; i++) {
249        osg::Vec3 dy(0.0f,-30.0f,0.0f);
250        osg::Vec3 dx(120.0f,0.0f,0.0f);
251        osg::Geode* geode = new osg::Geode();
252        osg::StateSet* stateset = geode->getOrCreateStateSet();
253        const char *opts[]={"One", "Two", "Three", "January", "Feb", "2003"};
254        osg::Geometry *quad=new osg::Geometry;
255        stateset->setMode(GL_LIGHTING,osg::StateAttribute::OFF);
256        stateset->setMode(GL_DEPTH_TEST,osg::StateAttribute::OFF);
257        std::string name="subOption";
258        name += " ";
259        name += std::string(opts[i]);
260        geode->setName(name);
261        osg::Vec3Array* vertices = new osg::Vec3Array(4); // 1 quad
262        osg::Vec4Array* colors = new osg::Vec4Array;
263        colors = new osg::Vec4Array;
264        colors->push_back(osg::Vec4(0.8-0.1*i,0.1*i,0.2*i, 1.0));
265        quad->setColorArray(colors);
266        quad->setColorBinding(osg::Geometry::BIND_PER_PRIMITIVE);
267        (*vertices)[0]=position;
268        (*vertices)[1]=position+dx;
269        (*vertices)[2]=position+dx+dy;
270        (*vertices)[3]=position+dy;
271        quad->setVertexArray(vertices);
272        quad->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::QUADS,0,4));
273        geode->addDrawable(quad);
274        modelview_abs->addChild(geode);
275       
276        position += delta;
277    }   
278   
279   
280   
281    { // this displays what has been selected
282        osg::Geode* geode = new osg::Geode();
283        osg::StateSet* stateset = geode->getOrCreateStateSet();
284        stateset->setMode(GL_LIGHTING,osg::StateAttribute::OFF);
285        stateset->setMode(GL_DEPTH_TEST,osg::StateAttribute::OFF);
286        geode->setName("whatis");
287        geode->addDrawable( updateText );
288        modelview_abs->addChild(geode);
289       
290        updateText->setFont(timesFont);
291        updateText->setText("whatis will tell you what is under the mouse");
292        updateText->setPosition(position);
293       
294        position += delta;
295    }   
296   
297    return projection;
298
299}
300
301int main( int argc, char **argv )
302{
303
304    // use an ArgumentParser object to manage the program arguments.
305    osg::ArgumentParser arguments(&argc,argv);
306   
307    // set up the usage document, in case we need to print out how to use this program.
308    arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the example which demonstrates how to do Head Up Displays.");
309    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] [filename] ...");
310    arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
311   
312
313    // construct the viewer.
314    //osgProducer::Viewer viewer(arguments);
315    osgProducer::Viewer viewer(BuildConfig());
316
317    // set up the value with sensible default event handlers.
318    viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS);
319
320    // get details on keyboard and mouse bindings used by the viewer.
321    viewer.getUsage(*arguments.getApplicationUsage());
322
323    // if user request help write it out to cout.
324    if (arguments.read("-h") || arguments.read("--help"))
325    {
326        arguments.getApplicationUsage()->write(std::cout);
327        return 1;
328    }
329
330    // any option left unread are converted into errors to write out later.
331    arguments.reportRemainingOptionsAsUnrecognized();
332
333    // report any errors if they have occured when parsing the program aguments.
334    if (arguments.errors())
335    {
336        arguments.writeErrorMessages(std::cout);
337        return 1;
338    }
339   
340    // read the scene from the list of file specified commandline args.
341    osg::ref_ptr<osg::Node> scene = osgDB::readNodeFiles(arguments);
342
343    osg::ref_ptr<osg::Group> group = dynamic_cast<osg::Group*>(scene.get());
344    if (!group)
345    {
346        group = new osg::Group;
347        group->addChild(scene.get());
348    }
349
350    osg::ref_ptr<osgText::Text> updateText = new osgText::Text;
351
352    // add the HUD subgraph.   
353    group->addChild(createHUD(updateText.get()));
354
355    // add the handler for doing the picking
356    viewer.getEventHandlerList().push_front(new PickHandler(&viewer,updateText.get()));
357
358    // set the scene to render
359    viewer.setSceneData(group.get());
360
361    // create the windows and run the threads.
362    viewer.realize();
363
364    while( !viewer.done() )
365    {
366        // wait for all cull and draw threads to complete.
367        viewer.sync();
368
369        // update the scene by traversing it with the the update visitor which will
370        // call all node update callbacks and animations.
371        viewer.update();
372         
373        // fire off the cull and draw traversals of the scene.
374        viewer.frame();
375       
376    }
377   
378    // wait for all cull and draw threads to complete before exit.
379    viewer.sync();
380   
381    return 0;
382}
Note: See TracBrowser for help on using the browser.