root/OpenSceneGraph/trunk/examples/osgkeyboardmouse/osgkeyboardmouse.cpp @ 5677

Revision 5677, 12.1 kB (checked in by robert, 7 years ago)

Improved handling of projected coords in new intersection classes

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
Line 
1// C++ source file - (C) 2003 Robert Osfield, released under the OSGPL.
2//
3// Simple example of use of Producer::RenderSurface + KeyboardMouseCallback + SceneView
4// example that provides the user with control over view position with basic picking.
5
6#include <Producer/RenderSurface>
7#include <Producer/KeyboardMouse>
8#include <Producer/Trackball>
9
10#include <osg/Timer>
11#include <osg/io_utils>
12#include <osg/observer_ptr>
13
14#include <osgUtil/SceneView>
15#include <osgUtil/IntersectVisitor>
16#include <osgUtil/IntersectionVisitor>
17
18#include <osgDB/ReadFile>
19#include <osgDB/WriteFile>
20
21#include <osgGA/SimpleViewer>
22#include <osgGA/TrackballManipulator>
23#include <osgGA/StateSetManipulator>
24
25#include <osgFX/Scribe>
26
27// ----------- Begining of glue classes to adapter Producer's keyboard mouse events to osgGA's abstraction events.
28class MyKeyboardMouseCallback : public Producer::KeyboardMouseCallback
29{
30public:
31
32    MyKeyboardMouseCallback(osgGA::EventQueue* eventQueue) :
33        _done(false),
34        _eventQueue(eventQueue)
35    {
36    }
37
38    virtual void shutdown()
39    {
40        _done = true;
41    }
42
43    virtual void specialKeyPress( Producer::KeyCharacter key )
44    {
45        if (key==Producer::KeyChar_Escape)
46                    shutdown();
47
48        _eventQueue->keyPress( (osgGA::GUIEventAdapter::KeySymbol) key );
49    }
50
51    virtual void specialKeyRelease( Producer::KeyCharacter key )
52    {
53        _eventQueue->keyRelease( (osgGA::GUIEventAdapter::KeySymbol) key );
54    }
55
56    virtual void keyPress( Producer::KeyCharacter key)
57    {
58        _eventQueue->keyPress( (osgGA::GUIEventAdapter::KeySymbol) key );
59    }
60
61    virtual void keyRelease( Producer::KeyCharacter key)
62    {
63        _eventQueue->keyRelease( (osgGA::GUIEventAdapter::KeySymbol) key );
64    }
65
66    virtual void mouseMotion( float mx, float my )
67    {
68        _eventQueue->mouseMotion( mx, my );
69    }
70
71    virtual void buttonPress( float mx, float my, unsigned int mbutton )
72    {
73        _eventQueue->mouseButtonPress(mx, my, mbutton);
74    }
75   
76    virtual void buttonRelease( float mx, float my, unsigned int mbutton )
77    {
78        _eventQueue->mouseButtonRelease(mx, my, mbutton);
79    }
80
81    bool done() { return _done; }
82
83private:
84
85    bool                                _done;
86    osg::ref_ptr<osgGA::EventQueue>     _eventQueue;
87};
88
89class MyActionAdapter : public osgGA::GUIActionAdapter, public osg::Referenced
90{
91public:
92    // Override from GUIActionAdapter
93    virtual void requestRedraw() {}
94
95    // Override from GUIActionAdapter
96    virtual void requestContinuousUpdate(bool =true) {}
97
98    // Override from GUIActionAdapter
99    virtual void requestWarpPointer(float ,float ) {}
100   
101};
102
103// ----------- End of glue classes to adapter Producer's keyboard mouse events to osgGA's abstraction events.
104
105
106class CreateModelToSaveVisitor : public osg::NodeVisitor
107{
108public:
109
110    CreateModelToSaveVisitor():
111        osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN)       
112    {
113        _group = new osg::Group;
114        _addToModel = false;
115    }
116   
117    virtual void apply(osg::Node& node)
118    {
119        osgFX::Scribe* scribe = dynamic_cast<osgFX::Scribe*>(&node);
120        if (scribe)
121        {
122            for(unsigned int i=0; i<scribe->getNumChildren(); ++i)
123            {
124                _group->addChild(scribe->getChild(i));
125            }
126        }
127        else
128        {
129            traverse(node);
130        }
131    }
132   
133    osg::ref_ptr<osg::Group> _group;
134    bool _addToModel;
135};
136
137// class to handle events with a pick
138class PickHandler : public osgGA::GUIEventHandler {
139public:
140
141    PickHandler(osgUtil::SceneView* sceneView):
142        _sceneView(sceneView),
143        _mx(0.0),_my(0.0) {}
144
145    ~PickHandler() {}
146
147    bool handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter&)
148    {
149        switch(ea.getEventType())
150        {
151            case(osgGA::GUIEventAdapter::KEYUP):
152            {
153                if (ea.getKey()=='s')
154                {
155                    saveSelectedModel();
156                }
157                return false;
158            }
159            case(osgGA::GUIEventAdapter::PUSH):
160            case(osgGA::GUIEventAdapter::MOVE):
161            {
162                _mx = ea.getX();
163                _my = ea.getY();
164                return false;
165            }
166            case(osgGA::GUIEventAdapter::RELEASE):
167            {
168                if (_mx == ea.getX() && _my == ea.getY())
169                {
170                    // only do a pick if the mouse hasn't moved
171                    pick(ea);
172                }
173                return true;
174            }   
175
176            default:
177                return false;
178        }
179    }
180
181    void pick(const osgGA::GUIEventAdapter& ea)
182    {
183
184        osg::Node* scene = _sceneView.valid() ? _sceneView->getSceneData() : 0;
185        if (!scene) return;
186
187        // remap the mouse x,y into viewport coordinates.
188       
189
190       osg::notify(osg::NOTICE)<<std::endl;
191
192#if 0
193        // use non dimension coordinates - in projection/clip space
194        osgUtil::LineSegmentIntersector* picker = new osgUtil::LineSegmentIntersector(osgUtil::Intersector::PROJECTION, osg::Vec3d(ea.getXnormalized(),ea.getYnormalized(),0.0), osg::Vec3d(ea.getXnormalized(),ea.getYnormalized(),1.0) );
195#else
196        // use window coordinates
197        float mx = _sceneView->getViewport()->x() + (int)((float)_sceneView->getViewport()->width()*(ea.getXnormalized()*0.5f+0.5f));
198        float my = _sceneView->getViewport()->y() + (int)((float)_sceneView->getViewport()->height()*(ea.getYnormalized()*0.5f+0.5f));
199        osgUtil::LineSegmentIntersector* picker = new osgUtil::LineSegmentIntersector(osgUtil::Intersector::WINDOW, osg::Vec3d(mx,my,0.0), osg::Vec3d(mx,my,1.0) );
200#endif
201
202        osgUtil::IntersectionVisitor iv(picker);
203       
204        _sceneView->getCamera()->accept(iv);
205       
206        osg::notify(osg::NOTICE)<<"Done pick, "<<picker->containsIntersections()<<std::endl;
207       
208        if (picker->containsIntersections())
209        {
210            osgUtil::LineSegmentIntersector::Intersection intersection = picker->getFirstIntersection();
211            osg::notify(osg::NOTICE)<<"Picking "<<intersection.localIntersectionPoint<<std::endl;
212
213#if 0
214            osg::NodePath& nodePath = intersection.nodePath;
215            osg::Node* node = (nodePath.size()>=1)?nodePath[nodePath.size()-1]:0;
216            osg::Group* parent = (nodePath.size()>=2)?dynamic_cast<osg::Group*>(nodePath[nodePath.size()-2]):0;
217
218            if (node) std::cout<<"  Hits "<<node->className()<<" nodePath size"<<nodePath.size()<<std::endl;
219
220            // now we try to decorate the hit node by the osgFX::Scribe to show that its been "picked"
221            if (parent && node)
222            {
223
224                std::cout<<"  parent "<<parent->className()<<std::endl;
225
226                osgFX::Scribe* parentAsScribe = dynamic_cast<osgFX::Scribe*>(parent);
227                if (!parentAsScribe)
228                {
229                    // node not already picked, so highlight it with an osgFX::Scribe
230                    osgFX::Scribe* scribe = new osgFX::Scribe();
231                    scribe->addChild(node);
232                    parent->replaceChild(node,scribe);
233                }
234                else
235                {
236                    // node already picked so we want to remove scribe to unpick it.
237                    osg::Node::ParentList parentList = parentAsScribe->getParents();
238                    for(osg::Node::ParentList::iterator itr=parentList.begin();
239                        itr!=parentList.end();
240                        ++itr)
241                    {
242                        (*itr)->replaceChild(parentAsScribe,node);
243                    }
244                }
245            }
246#endif
247
248        }
249       
250
251        {
252            float mx = _sceneView->getViewport()->x() + (int)((float)_sceneView->getViewport()->width()*(ea.getXnormalized()*0.5f+0.5f));
253            float my = _sceneView->getViewport()->y() + (int)((float)_sceneView->getViewport()->height()*(ea.getYnormalized()*0.5f+0.5f));
254
255            // do the pick traversal use the other PickVisitor to double check results.
256            osgUtil::PickVisitor pick(_sceneView->getViewport(),
257                                      _sceneView->getProjectionMatrix(),
258                                      _sceneView->getViewMatrix(), mx, my);
259            scene->accept(pick);
260
261            osgUtil::PickVisitor::LineSegmentHitListMap& segHitList = pick.getSegHitList();
262            if (!segHitList.empty() && !segHitList.begin()->second.empty())
263            {
264
265                // get the hits for the first segment
266                osgUtil::PickVisitor::HitList& hits = segHitList.begin()->second;
267
268                // just take the first hit - nearest the eye point.
269                osgUtil::Hit& hit = hits.front();
270
271                std::cout<<"Got hits"<<hit.getLocalIntersectPoint()<<std::endl;
272            }
273        }
274
275    }
276
277    void saveSelectedModel()
278    {
279        CreateModelToSaveVisitor cmtsv;
280        _sceneView->getSceneData()->accept(cmtsv);
281       
282        if (cmtsv._group->getNumChildren()>0)
283        {
284            std::cout<<"Writing selected compoents to 'selected_model.osg'"<<std::endl;
285            osgDB::writeNodeFile(*cmtsv._group, "selected_model.osg");
286        }
287    }
288
289protected:
290
291    osg::observer_ptr<osgUtil::SceneView> _sceneView;
292    float _mx,_my;
293};
294
295int main( int argc, char **argv )
296{
297    if (argc<2)
298    {
299        std::cout << argv[0] <<": requires filename argument." << std::endl;
300        return 1;
301    }
302
303    // load the scene.
304    osg::ref_ptr<osg::Node> loadedModel = osgDB::readNodeFile(argv[1]);
305    if (!loadedModel)
306    {
307        std::cout << argv[0] <<": No data loaded." << std::endl;
308        return 1;
309    }
310   
311    // create the window to draw to.
312    osg::ref_ptr<Producer::RenderSurface> renderSurface = new Producer::RenderSurface;
313    renderSurface->setWindowName("osgkeyboardmouse");
314    renderSurface->setWindowRectangle(100,100,800,600);
315    renderSurface->useBorder(true);
316    renderSurface->realize();
317   
318
319    // create the view of the scene.
320    osgGA::SimpleViewer viewer;
321    viewer.setSceneData(loadedModel.get());
322   
323    // set up a KeyboardMouse to manage the events comming in from the RenderSurface
324    osg::ref_ptr<Producer::KeyboardMouse>  kbm = new Producer::KeyboardMouse(renderSurface.get());
325
326    // create a KeyboardMouseCallback to handle the mouse events within this applications
327    osg::ref_ptr<MyKeyboardMouseCallback> kbmcb = new MyKeyboardMouseCallback(viewer.getEventQueue());
328
329    // create a tracball manipulator to move the camera around in response to keyboard/mouse events
330    viewer.setCameraManipulator( new osgGA::TrackballManipulator );
331
332    osg::ref_ptr<osgGA::StateSetManipulator> statesetManipulator = new osgGA::StateSetManipulator;
333    statesetManipulator->setStateSet(viewer.getSceneView()->getGlobalStateSet());
334    viewer.addEventHandler(statesetManipulator.get());
335
336    // add the pick handler
337    viewer.addEventHandler(new PickHandler(viewer.getSceneView()));
338   
339    // set the window dimensions
340    viewer.getEventQueue()->getCurrentEventState()->setWindowRectangle(100,100,800,600);
341
342    // set the mouse input range.
343    // Producer defaults to using non-dimensional units, so we pass this onto osgGA, most windowing toolkits use pixel coords so use the window size instead.
344    viewer.getEventQueue()->getCurrentEventState()->setInputRange(-1.0, -1.0, 1.0, 1.0);
345
346    // Producer has the y axis increase upwards, like OpenGL, and contary to most Windowing toolkits.
347    // we need to construct the event queue so that it knows about this convention.
348    viewer.getEventQueue()->getCurrentEventState()->setMouseYOrientation(osgGA::GUIEventAdapter::Y_INCREASING_UPWARDS);
349
350    viewer.init();
351
352    // main loop (note, window toolkits which take control over the main loop will require a window redraw callback containing the code below.)
353    while( renderSurface->isRealized() && !kbmcb->done())
354    {
355        // update the window dimensions, in case the window has been resized.
356         viewer.getEventQueue()->windowResize(0,0,renderSurface->getWindowWidth(),renderSurface->getWindowHeight(), false);
357
358        // pass any keyboard mouse events onto the local keyboard mouse callback.
359        kbm->update( *kbmcb );
360       
361        viewer.frame();
362
363        // Swap Buffers
364        renderSurface->swapBuffers();
365    }
366
367    return 0;
368}
Note: See TracBrowser for help on using the browser.