root/OpenSceneGraph/trunk/examples/osgmanipulator/osgmanipulator.cpp @ 6143

Revision 6143, 14.0 kB (checked in by robert, 7 years ago)

From Vivek Rajan, new osgManipulator library, with a few minor tweaks and rename for osgDragger to osgManipulator for build by Robert Osfield.
Vivek's email to osg-submissions:

"I'm happy to release the osgdragger nodekit to the OSG community. I
implemented the nodekit for my company, Fugro-Jason Inc., and they
have kindly agreed to open source it.

The nodekit contains a few draggers but it should be easy to build new
draggers on top of it. The design of the nodekit is based on a
SIGGRAPH 2002 course - "Design and Implementation of Direct
Manipulation in 3D". You can find the course notes at
http://www.pauliface.com/Sigg02/index.html. Reading pages 20 - 29 of
the course notes should give you a fair understanding of how the
nodekit works.

The source code also contains an example of how to use the draggers."

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
Line 
1#include <osgDB/ReadFile>
2#include <osgUtil/Optimizer>
3#include <osgProducer/Viewer>
4#include <osg/CoordinateSystemNode>
5#include <osgText/Text>
6
7#include <osgManipulator/CommandManager>
8#include <osgManipulator/TabBoxDragger>
9#include <osgManipulator/TabPlaneDragger>
10#include <osgManipulator/TabPlaneTrackballDragger>
11#include <osgManipulator/TrackballDragger>
12#include <osgManipulator/Translate1DDragger>
13#include <osgManipulator/Translate2DDragger>
14#include <osgManipulator/TranslateAxisDragger>
15
16osgManipulator::Dragger* createDragger(const std::string& name)
17{
18    osgManipulator::Dragger* dragger = 0;
19    if ("TabPlaneDragger" == name)
20    {
21        osgManipulator::TabPlaneDragger* d = new osgManipulator::TabPlaneDragger();
22        d->setupDefaultGeometry();
23        dragger = d;
24    }
25    else if ("TabPlaneTrackballDragger" == name)
26    {
27        osgManipulator::TabPlaneTrackballDragger* d = new osgManipulator::TabPlaneTrackballDragger();
28        d->setupDefaultGeometry();
29        dragger = d;
30    }
31    else if ("TrackballDragger" == name)
32    {
33        osgManipulator::TrackballDragger* d = new osgManipulator::TrackballDragger();
34        d->setupDefaultGeometry();
35        dragger = d;
36    }
37    else if ("Translate1DDragger" == name)
38    {
39        osgManipulator::Translate1DDragger* d = new osgManipulator::Translate1DDragger();
40        d->setupDefaultGeometry();
41        dragger = d;
42    }
43    else if ("Translate2DDragger" == name)
44    {
45        osgManipulator::Translate2DDragger* d = new osgManipulator::Translate2DDragger();
46        d->setupDefaultGeometry();
47        dragger = d;
48    }
49    else if ("TranslateAxisDragger" == name)
50    {
51        osgManipulator::TranslateAxisDragger* d = new osgManipulator::TranslateAxisDragger();
52        d->setupDefaultGeometry();
53        dragger = d;
54    }
55    else
56    {
57        osgManipulator::TabBoxDragger* d = new osgManipulator::TabBoxDragger();
58        d->setupDefaultGeometry();
59        dragger = d;
60    }
61 
62    return dragger;
63}
64
65osg::Node* createHUD()
66{
67    osg::Geode* geode = new osg::Geode();
68   
69    std::string timesFont("fonts/arial.ttf");
70
71    osg::StateSet* stateset = geode->getOrCreateStateSet();
72    stateset->setMode(GL_LIGHTING,osg::StateAttribute::OFF);
73
74    osgText::Text* text = new  osgText::Text;
75    geode->addDrawable( text );
76
77    osg::Vec3 position(50.0f,50.0f,0.0f);
78    text->setPosition(position);
79    text->setText("Use the Tab key to switch between the trackball and pick modes.");
80    text->setFont(timesFont);
81
82    osg::Camera* camera = new osg::Camera;
83
84    // set the projection matrix
85    camera->setProjectionMatrix(osg::Matrix::ortho2D(0,1280,0,1024));
86
87    // set the view matrix   
88    camera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
89    camera->setViewMatrix(osg::Matrix::identity());
90
91    // only clear the depth buffer
92    camera->setClearMask(GL_DEPTH_BUFFER_BIT);
93
94    // draw subgraph after main camera view.
95    camera->setRenderOrder(osg::Camera::POST_RENDER);
96
97    camera->addChild(geode);
98   
99    return camera;
100}
101
102
103bool computePixelCoords(osgProducer::Viewer* viewer,float x,float y,unsigned int cameraNum,float& pixel_x,float& pixel_y)
104{
105    Producer::KeyboardMouse* km = viewer->getKeyboardMouse();
106    if (!km) return false;
107           
108    if (cameraNum>=viewer->getNumberOfCameras()) return false;
109
110    Producer::Camera* camera=viewer->getCamera(cameraNum);
111    Producer::RenderSurface* rs = camera->getRenderSurface();
112
113    Producer::InputArea* inputArea = km->getInputArea();
114    if( inputArea != NULL )
115    {
116        // first locate which InputRectange is appropriate for specified RenderSurface.
117        unsigned int i;
118        for(i=0;i<inputArea->getNumRenderSurfaces();++i)
119        {
120            if (inputArea->getRenderSurface(i)==rs) break;
121        }
122       
123        // the RenderSurface isn't in the InputArea list.. therefore cannot make mouse coords to it.
124        if (i==inputArea->getNumRenderSurfaces()) return false;
125
126        // we have a valid InputRectangle
127        Producer::RenderSurface::InputRectangle ir = inputArea->getRenderSurface(i)->getInputRectangle();
128
129        float rx = (x-ir.left())/ir.width();
130        float ry = (y-ir.bottom())/ir.height();
131       
132        int wx, wy;
133        unsigned int w, h;
134        rs->getWindowRectangle( wx, wy, w, h );
135
136        pixel_x = ((float)w)* rx;
137        pixel_y = ((float)h)* ry;
138    }
139    else
140    {
141        float rx = (x+1.0f)*0.5f;
142        float ry = (y+1.0f)*0.5f;
143
144        int wx, wy;
145        unsigned int w, h;
146        rs->getWindowRectangle( wx, wy, w, h );
147
148        pixel_x = ((float)w)* rx;
149        pixel_y = ((float)h)* ry;
150    }
151    return true;
152}
153
154osg::Node* addDraggerToScene(osg::Node* scene, osgManipulator::CommandManager* cmdMgr, const std::string& name)
155{
156    scene->getOrCreateStateSet()->setMode(GL_NORMALIZE, osg::StateAttribute::ON);
157
158    osgManipulator::Selection* selection = new osgManipulator::Selection;
159    selection->addChild(scene);
160
161    osgManipulator::Dragger* dragger = createDragger(name);
162
163    osg::Group* root = new osg::Group;
164    root->addChild(dragger);
165    root->addChild(selection);
166    root->addChild(createHUD());
167
168    float scale = scene->getBound().radius() * 1.6;
169    dragger->setMatrix(osg::Matrix::scale(scale, scale, scale) *
170                       osg::Matrix::translate(scene->getBound().center()));
171    cmdMgr->connect(*dragger, *selection);
172
173    return root;
174}
175
176class PickModeHandler : public osgGA::GUIEventHandler
177{
178    public:
179        enum Modes
180        {
181            VIEW = 0,
182            PICK
183        };
184
185        PickModeHandler(osgProducer::Viewer *viewer) : osgGA::GUIEventHandler(),
186                                                       _viewer(viewer), _mode(VIEW), _activeDragger(0)
187        {
188        }       
189       
190        bool handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa,
191                    osg::Object*, osg::NodeVisitor*)
192        {
193            if (ea.getKey() == osgGA::GUIEventAdapter::KEY_Tab &&
194                ea.getEventType() == osgGA::GUIEventAdapter::KEYDOWN &&
195                _activeDragger == 0)
196            {
197                _mode = ! _mode;
198            }
199           
200            if (VIEW == _mode) return false;
201
202            for(unsigned int i=0;i<_viewer->getNumberOfCameras();++i)
203            {
204                if ((ea.getEventType() == osgGA::GUIEventAdapter::PUSH) &&
205                    _viewer->computeIntersections(ea.getX(), ea.getY(), i, hitList))
206                {
207                    float pixel_x,pixel_y;
208                    if (computePixelCoords(_viewer,ea.getX(),ea.getY(),i,pixel_x,pixel_y))
209                    {
210                        Producer::Camera* camera=_viewer->getCamera(i);
211
212                        osgProducer::OsgSceneHandler* sh = dynamic_cast<osgProducer::OsgSceneHandler*>(camera->getSceneHandler());
213                        osgUtil::SceneView* sv = sh ? sh->getSceneView() : 0;
214                        if (! sv) continue;
215
216                        for (osg::NodePath::iterator itr = hitList.front().getNodePath().begin();
217                             itr != hitList.front().getNodePath().end();
218                             ++itr)
219                        {
220                            osgManipulator::Dragger* dragger = dynamic_cast<osgManipulator::Dragger*>(*itr);
221                            if (dragger)
222                            {
223                                dragger->handle(int(pixel_x+0.5), int(pixel_y+0.5), *sv,
224                                                hitList, hitList.begin(),
225                                                ea, aa);
226                                _activeDragger = dragger;
227                                break;
228                            }                   
229                        }
230                    }
231                }
232               
233                switch (ea.getEventType())
234                {
235                    case osgGA::GUIEventAdapter::DRAG:
236                    case osgGA::GUIEventAdapter::RELEASE:
237                        if (_activeDragger)
238                        {
239                            float pixel_x,pixel_y;
240                            if (computePixelCoords(_viewer,ea.getX(),ea.getY(),i,pixel_x,pixel_y))
241                            {
242                                Producer::Camera* camera=_viewer->getCamera(i);
243
244                                osgProducer::OsgSceneHandler* sh = dynamic_cast<osgProducer::OsgSceneHandler*>(camera->getSceneHandler());
245                                osgUtil::SceneView* sv = sh ? sh->getSceneView() : 0;
246                                if (_activeDragger && sv)
247                                    _activeDragger->handle(int(pixel_x+0.5), int(pixel_y+0.5), *sv,
248                                                           hitList, hitList.begin(),
249                                                           ea, aa);
250                            }
251                        }
252                        break;
253
254                    default:
255                        break;
256                }
257                if (ea.getEventType() == osgGA::GUIEventAdapter::RELEASE)
258                {
259                    _activeDragger = 0;
260                    hitList.clear();
261                }
262            }
263            return true;
264        }
265       
266    private:
267        osgProducer::Viewer* _viewer;
268        unsigned int _mode;
269        osgManipulator::Dragger* _activeDragger;
270        osgUtil::IntersectVisitor::HitList hitList;
271};
272
273int main( int argc, char **argv )
274{
275
276    // use an ArgumentParser object to manage the program arguments.
277    osg::ArgumentParser arguments(&argc,argv);
278   
279    // set up the usage document, in case we need to print out how to use this program.
280    arguments.getApplicationUsage()->setApplicationName(arguments.getApplicationName());
281    arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the standard OpenSceneGraph example which loads and visualises 3d models.");
282    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ...");
283    arguments.getApplicationUsage()->addCommandLineOption("--image <filename>","Load an image and render it on a quad");
284    arguments.getApplicationUsage()->addCommandLineOption("--dem <filename>","Load an image/DEM and render it on a HeightField");
285    arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display command line parameters");
286    arguments.getApplicationUsage()->addCommandLineOption("--help-env","Display environmental variables available");
287    arguments.getApplicationUsage()->addCommandLineOption("--help-keys","Display keyboard & mouse bindings available");
288    arguments.getApplicationUsage()->addCommandLineOption("--help-all","Display all command line, env vars and keyboard & mouse bindings.");
289
290    arguments.getApplicationUsage()->addCommandLineOption("--dragger <draggername>","Use the specified dragger for manipulation");
291   
292
293    // construct the viewer.
294    osgProducer::Viewer viewer(arguments);
295
296    // set up the value with sensible default event handlers.
297    viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS);
298
299    // get details on keyboard and mouse bindings used by the viewer.
300    viewer.getUsage(*arguments.getApplicationUsage());
301
302    // if user request help write it out to cout.
303    bool helpAll = arguments.read("--help-all");
304    unsigned int helpType = ((helpAll || arguments.read("-h") || arguments.read("--help"))? osg::ApplicationUsage::COMMAND_LINE_OPTION : 0 ) |
305                            ((helpAll ||  arguments.read("--help-env"))? osg::ApplicationUsage::ENVIRONMENTAL_VARIABLE : 0 ) |
306                            ((helpAll ||  arguments.read("--help-keys"))? osg::ApplicationUsage::KEYBOARD_MOUSE_BINDING : 0 );
307    if (helpType)
308    {
309        arguments.getApplicationUsage()->write(std::cout, helpType);
310        return 1;
311    }
312
313    // report any errors if they have occurred when parsing the program arguments.
314    if (arguments.errors())
315    {
316        arguments.writeErrorMessages(std::cout);
317        return 1;
318    }
319   
320    if (arguments.argc()<=1)
321    {
322        arguments.getApplicationUsage()->write(std::cout,osg::ApplicationUsage::COMMAND_LINE_OPTION);
323        return 1;
324    }
325
326    std::string dragger_name = "TabBoxDragger";
327    arguments.read("--dragger", dragger_name);
328
329    osg::Timer_t start_tick = osg::Timer::instance()->tick();
330
331    // read the scene from the list of file specified command line args.
332    osg::ref_ptr<osg::Node> loadedModel = osgDB::readNodeFiles(arguments);
333
334    // if no model has been successfully loaded report failure.
335    if (!loadedModel)
336    {
337        std::cout << arguments.getApplicationName() <<": No data loaded" << std::endl;
338        return 1;
339    }
340
341    // any option left unread are converted into errors to write out later.
342    arguments.reportRemainingOptionsAsUnrecognized();
343
344    // report any errors if they have occurred when parsing the program arguments.
345    if (arguments.errors())
346    {
347        arguments.writeErrorMessages(std::cout);
348    }
349
350    osg::Timer_t end_tick = osg::Timer::instance()->tick();
351
352    std::cout << "Time to load = "<<osg::Timer::instance()->delta_s(start_tick,end_tick)<<std::endl;
353
354
355    // optimize the scene graph, remove redundant nodes and state etc.
356    osgUtil::Optimizer optimizer;
357    optimizer.optimize(loadedModel.get());
358
359    osg::ref_ptr<osgManipulator::CommandManager> cmdMgr = new osgManipulator::CommandManager;
360   
361    // pass the loaded scene graph to the viewer.
362    viewer.setSceneData(addDraggerToScene(loadedModel.get(), cmdMgr.get(), dragger_name));
363
364    viewer.getEventHandlerList().push_front(new PickModeHandler(&viewer));
365
366    // create the windows and run the threads.
367    viewer.realize();
368
369    while( !viewer.done() )
370    {
371        // wait for all cull and draw threads to complete.
372        viewer.sync();
373
374        // update the scene by traversing it with the the update visitor which will
375        // call all node update callbacks and animations.
376        viewer.update();
377         
378        // fire off the cull and draw traversals of the scene.
379        viewer.frame();
380       
381    }
382   
383    // wait for all cull and draw threads to complete.
384    viewer.sync();
385
386    // run a clean up frame to delete all OpenGL objects.
387    viewer.cleanup_frame();
388
389    // wait for all the clean up frame to complete.
390    viewer.sync();
391
392    return 0;
393}
Note: See TracBrowser for help on using the browser.