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

Revision 12930, 17.2 kB (checked in by robert, 3 years ago)

Improved the handling of osgManipulator::Constraint, DraggerCallbacks? and Command so that they now use a Visitor Pattern

to ensure the correct methods on constraints and callbaks are called for each Command. Also fixed the handling of

Constraints when applied to composite Draggers.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
Line 
1/* OpenSceneGraph example, osgmanipulator.
2*
3*  Permission is hereby granted, free of charge, to any person obtaining a copy
4*  of this software and associated documentation files (the "Software"), to deal
5*  in the Software without restriction, including without limitation the rights
6*  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7*  copies of the Software, and to permit persons to whom the Software is
8*  furnished to do so, subject to the following conditions:
9*
10*  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
11*  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
12*  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
13*  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
14*  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
15*  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
16*  THE SOFTWARE.
17*/
18
19#include <osgDB/ReadFile>
20#include <osgUtil/Optimizer>
21#include <osgViewer/Viewer>
22#include <osg/CoordinateSystemNode>
23#include <osgText/Text>
24
25#include <osgManipulator/TabBoxDragger>
26#include <osgManipulator/TabBoxTrackballDragger>
27#include <osgManipulator/TabPlaneDragger>
28#include <osgManipulator/TabPlaneTrackballDragger>
29#include <osgManipulator/Scale1DDragger>
30#include <osgManipulator/Scale2DDragger>
31#include <osgManipulator/TrackballDragger>
32#include <osgManipulator/Translate1DDragger>
33#include <osgManipulator/Translate2DDragger>
34#include <osgManipulator/TranslateAxisDragger>
35#include <osgManipulator/TranslatePlaneDragger>
36
37#include <osg/ShapeDrawable>
38#include <osg/MatrixTransform>
39#include <osg/Geometry>
40#include <osg/Material>
41#include <osg/io_utils>
42
43#include <iostream>
44
45class PlaneConstraint : public osgManipulator::Constraint
46{
47public:
48        PlaneConstraint() {}
49   
50        virtual bool constrain(osgManipulator::TranslateInLineCommand& command) const
51        {
52            OSG_NOTICE<<"TranslateInLineCommand "<<command.getTranslation()<<std::endl;
53            return true;           
54        }
55        virtual bool constrain(osgManipulator::TranslateInPlaneCommand& command) const
56        {
57            //command.setTranslation(osg::Vec3(0.0f,0.0f,0.0f));
58            OSG_NOTICE<<"TranslateInPlaneCommand "<<command.getTranslation()<<std::endl;
59            return true;
60        }
61        virtual bool constrain(osgManipulator::Scale1DCommand& command) const
62        {
63            //command.setScale(1.0f);
64            OSG_NOTICE<<"Scale1DCommand"<<command.getScale()<<std::endl;
65            return true;           
66        }
67        virtual bool constrain(osgManipulator::Scale2DCommand& command) const
68        {
69            //command.setScale(osg::Vec2d(1.0,1.0));
70            OSG_NOTICE<<"Scale2DCommand "<<command.getScale()<<std::endl;
71            return true;
72        }
73        virtual bool constrain(osgManipulator::ScaleUniformCommand& command) const
74        {
75            OSG_NOTICE<<"ScaleUniformCommand"<<command.getScale()<<std::endl;
76            return true;           
77        }
78};
79
80osgManipulator::Dragger* createDragger(const std::string& name)
81{
82    osgManipulator::Dragger* dragger = 0;
83    if ("TabPlaneDragger" == name)
84    {
85        osgManipulator::TabPlaneDragger* d = new osgManipulator::TabPlaneDragger();
86        d->setupDefaultGeometry();
87        d->addConstraint(new PlaneConstraint());
88        dragger = d;
89    }
90    else if ("TabPlaneTrackballDragger" == name)
91    {
92        osgManipulator::TabPlaneTrackballDragger* d = new osgManipulator::TabPlaneTrackballDragger();
93        d->setupDefaultGeometry();
94        dragger = d;
95    }
96    else if ("TabBoxTrackballDragger" == name)
97    {
98        osgManipulator::TabBoxTrackballDragger* d = new osgManipulator::TabBoxTrackballDragger();
99        d->setupDefaultGeometry();
100        dragger = d;
101    }
102    else if ("TrackballDragger" == name)
103    {
104        osgManipulator::TrackballDragger* d = new osgManipulator::TrackballDragger();
105        d->setupDefaultGeometry();
106        dragger = d;
107    }
108    else if ("Translate1DDragger" == name)
109    {
110        osgManipulator::Translate1DDragger* d = new osgManipulator::Translate1DDragger();
111        d->setupDefaultGeometry();
112        dragger = d;
113    }
114    else if ("Translate2DDragger" == name)
115    {
116        osgManipulator::Translate2DDragger* d = new osgManipulator::Translate2DDragger();
117        d->setupDefaultGeometry();
118        dragger = d;
119    }
120    else if ("TranslateAxisDragger" == name)
121    {
122        osgManipulator::TranslateAxisDragger* d = new osgManipulator::TranslateAxisDragger();
123        d->setupDefaultGeometry();
124        dragger = d;
125    }
126    else if ("TranslatePlaneDragger" == name)
127    {
128        osgManipulator::TranslatePlaneDragger* d = new osgManipulator::TranslatePlaneDragger();
129        d->setupDefaultGeometry();
130        dragger = d;
131    }
132    else if ("Scale1DDragger" == name)
133    {
134        osgManipulator::Scale1DDragger* d = new osgManipulator::Scale1DDragger();
135        d->setupDefaultGeometry();
136        dragger = d;
137    }
138    else if ("Scale2DDragger" == name)
139    {
140        osgManipulator::Scale2DDragger* d = new osgManipulator::Scale2DDragger();
141        d->setupDefaultGeometry();
142        dragger = d;
143    }
144    else
145    {
146        osgManipulator::TabBoxDragger* d = new osgManipulator::TabBoxDragger();
147        d->setupDefaultGeometry();
148        dragger = d;
149    }
150
151   
152 
153    return dragger;
154}
155
156// The DraggerContainer node is used to fix the dragger's size on the screen
157class DraggerContainer : public osg::Group
158{
159public:
160    DraggerContainer() : _draggerSize(240.0f), _active(true) {}
161   
162    DraggerContainer( const DraggerContainer& copy, const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY )
163    :   osg::Group(copy, copyop),
164        _dragger(copy._dragger), _draggerSize(copy._draggerSize), _active(copy._active)
165    {}
166   
167    META_Node( osgManipulator, DraggerContainer );
168   
169    void setDragger( osgManipulator::Dragger* dragger )
170    {
171        _dragger = dragger;
172        if ( !containsNode(dragger) ) addChild( dragger );
173    }
174   
175    osgManipulator::Dragger* getDragger() { return _dragger.get(); }
176    const osgManipulator::Dragger* getDragger() const { return _dragger.get(); }
177   
178    void setDraggerSize( float size ) { _draggerSize = size; }
179    float getDraggerSize() const { return _draggerSize; }
180   
181    void setActive( bool b ) { _active = b; }
182    bool getActive() const { return _active; }
183   
184    void traverse( osg::NodeVisitor& nv )
185    {
186        if ( _dragger.valid() )
187        {
188            if ( _active && nv.getVisitorType()==osg::NodeVisitor::CULL_VISITOR )
189            {
190                osgUtil::CullVisitor* cv = static_cast<osgUtil::CullVisitor*>(&nv);
191               
192                float pixelSize = cv->pixelSize(_dragger->getBound().center(), 0.48f);
193                if ( pixelSize!=_draggerSize )
194                {
195                    float pixelScale = pixelSize>0.0f ? _draggerSize/pixelSize : 1.0f;
196                    osg::Vec3d scaleFactor(pixelScale, pixelScale, pixelScale);
197                   
198                    osg::Vec3 trans = _dragger->getMatrix().getTrans();
199                    _dragger->setMatrix( osg::Matrix::scale(scaleFactor) * osg::Matrix::translate(trans) );
200                }
201            }
202        }
203        osg::Group::traverse(nv);
204    }
205   
206protected:
207    osg::ref_ptr<osgManipulator::Dragger> _dragger;
208    float _draggerSize;
209    bool _active;
210};
211
212osg::Node* addDraggerToScene(osg::Node* scene, const std::string& name, bool fixedSizeInScreen)
213{
214    scene->getOrCreateStateSet()->setMode(GL_NORMALIZE, osg::StateAttribute::ON);
215
216    osg::MatrixTransform* selection = new osg::MatrixTransform;
217    selection->addChild(scene);
218
219    osgManipulator::Dragger* dragger = createDragger(name);
220
221    osg::Group* root = new osg::Group;
222    root->addChild(selection);
223
224    if ( fixedSizeInScreen )
225    {
226        DraggerContainer* draggerContainer = new DraggerContainer;
227        draggerContainer->setDragger( dragger );
228        root->addChild(draggerContainer);
229    }
230    else
231        root->addChild(dragger);
232
233    float scale = scene->getBound().radius() * 1.6;
234    dragger->setMatrix(osg::Matrix::scale(scale, scale, scale) *
235                       osg::Matrix::translate(scene->getBound().center()));
236
237    dragger->addTransformUpdating(selection);
238
239    // we want the dragger to handle it's own events automatically
240    dragger->setHandleEvents(true);
241
242    // if we don't set an activation key or mod mask then any mouse click on
243    // the dragger will activate it, however if do define either of ActivationModKeyMask or
244    // and ActivationKeyEvent then you'll have to press either than mod key or the specified key to
245    // be able to activate the dragger when you mouse click on it.  Please note the follow allows
246    // activation if either the ctrl key or the 'a' key is pressed and held down.
247    dragger->setActivationModKeyMask(osgGA::GUIEventAdapter::MODKEY_CTRL);
248    dragger->setActivationKeyEvent('a');
249
250    return root;
251}
252
253osg::Node* createDemoScene(bool fixedSizeInScreen) {
254 
255    osg::Group* root = new osg::Group;
256
257    osg::ref_ptr<osg::Geode> geode_1 = new osg::Geode;
258    osg::ref_ptr<osg::MatrixTransform> transform_1 = new osg::MatrixTransform;
259
260    osg::ref_ptr<osg::Geode> geode_2 = new osg::Geode;
261    osg::ref_ptr<osg::MatrixTransform> transform_2 = new osg::MatrixTransform;
262
263    osg::ref_ptr<osg::Geode> geode_3 = new osg::Geode;
264    osg::ref_ptr<osg::MatrixTransform> transform_3 = new osg::MatrixTransform;
265
266    osg::ref_ptr<osg::Geode> geode_4 = new osg::Geode;
267    osg::ref_ptr<osg::MatrixTransform> transform_4 = new osg::MatrixTransform;
268
269    osg::ref_ptr<osg::Geode> geode_5 = new osg::Geode;
270    osg::ref_ptr<osg::MatrixTransform> transform_5 = new osg::MatrixTransform;
271
272    osg::ref_ptr<osg::Geode> geode_6 = new osg::Geode;
273    osg::ref_ptr<osg::MatrixTransform> transform_6 = new osg::MatrixTransform;
274
275    osg::ref_ptr<osg::Geode> geode_7 = new osg::Geode;
276    osg::ref_ptr<osg::MatrixTransform> transform_7 = new osg::MatrixTransform;
277
278 
279
280
281
282    const float radius = 0.8f;
283    const float height = 1.0f;
284    osg::ref_ptr<osg::TessellationHints> hints = new osg::TessellationHints;
285    hints->setDetailRatio(2.0f);
286    osg::ref_ptr<osg::ShapeDrawable> shape;
287
288    shape = new osg::ShapeDrawable(new osg::Box(osg::Vec3(0.0f, 0.0f, -2.0f), 10, 10.0f, 0.1f), hints.get());
289    shape->setColor(osg::Vec4(0.5f, 0.5f, 0.7f, 1.0f));
290    geode_1->addDrawable(shape.get());
291
292    shape = new osg::ShapeDrawable(new osg::Cylinder(osg::Vec3(0.0f, 0.0f, 0.0f), radius * 2,radius), hints.get());
293    shape->setColor(osg::Vec4(0.8f, 0.8f, 0.8f, 1.0f));
294    geode_2->addDrawable(shape.get());
295
296    shape = new osg::ShapeDrawable(new osg::Cylinder(osg::Vec3(-3.0f, 0.0f, 0.0f), radius,radius), hints.get());
297    shape->setColor(osg::Vec4(0.6f, 0.8f, 0.8f, 1.0f));
298    geode_3->addDrawable(shape.get());
299
300    shape = new osg::ShapeDrawable(new osg::Cone(osg::Vec3(3.0f, 0.0f, 0.0f), 2 * radius,radius), hints.get());
301    shape->setColor(osg::Vec4(0.4f, 0.9f, 0.3f, 1.0f));
302    geode_4->addDrawable(shape.get());
303
304    shape = new osg::ShapeDrawable(new osg::Cone(osg::Vec3(0.0f, -3.0f, 0.0f), radius, height), hints.get());
305    shape->setColor(osg::Vec4(0.2f, 0.5f, 0.7f, 1.0f));
306    geode_5->addDrawable(shape.get());
307
308    shape = new osg::ShapeDrawable(new osg::Cylinder(osg::Vec3(0.0f, 3.0f, 0.0f), radius, height), hints.get());
309    shape->setColor(osg::Vec4(1.0f, 0.3f, 0.3f, 1.0f));
310    geode_6->addDrawable(shape.get());
311
312    shape = new osg::ShapeDrawable(new osg::Cone(osg::Vec3(0.0f, 0.0f, 3.0f), 2.0f, 2.0f), hints.get());
313    shape->setColor(osg::Vec4(0.8f, 0.8f, 0.4f, 1.0f));
314    geode_7->addDrawable(shape.get());
315
316
317
318
319
320
321    // material
322    osg::ref_ptr<osg::Material> matirial = new osg::Material;
323    matirial->setColorMode(osg::Material::DIFFUSE);
324    matirial->setAmbient(osg::Material::FRONT_AND_BACK, osg::Vec4(0, 0, 0, 1));
325    matirial->setSpecular(osg::Material::FRONT_AND_BACK, osg::Vec4(1, 1, 1, 1));
326    matirial->setShininess(osg::Material::FRONT_AND_BACK, 64.0f);
327    root->getOrCreateStateSet()->setAttributeAndModes(matirial.get(), osg::StateAttribute::ON);
328
329    transform_1.get()->addChild(addDraggerToScene(geode_1.get(),"TabBoxDragger",fixedSizeInScreen));
330    transform_2.get()->addChild(addDraggerToScene(geode_2.get(),"TabPlaneDragger",fixedSizeInScreen));
331    transform_3.get()->addChild(addDraggerToScene(geode_3.get(),"TabBoxTrackballDragger",fixedSizeInScreen));
332    transform_4.get()->addChild(addDraggerToScene(geode_4.get(),"TrackballDragger",fixedSizeInScreen));
333    transform_5.get()->addChild(addDraggerToScene(geode_5.get(),"Translate1DDragger",fixedSizeInScreen));
334    transform_6.get()->addChild(addDraggerToScene(geode_6.get(),"Translate2DDragger",fixedSizeInScreen));
335    transform_7.get()->addChild(addDraggerToScene(geode_7.get(),"TranslateAxisDragger",fixedSizeInScreen));
336
337    root->addChild(transform_1.get());
338    root->addChild(transform_2.get());
339    root->addChild(transform_3.get());
340    root->addChild(transform_4.get());
341    root->addChild(transform_5.get());
342    root->addChild(transform_6.get());
343    root->addChild(transform_7.get());
344
345 
346 
347    return root;
348}
349//
350int main( int argc, char **argv )
351{
352
353    // use an ArgumentParser object to manage the program arguments.
354    osg::ArgumentParser arguments(&argc,argv);
355   
356    // set up the usage document, in case we need to print out how to use this program.
357    arguments.getApplicationUsage()->setApplicationName(arguments.getApplicationName());
358    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ...");
359    arguments.getApplicationUsage()->addCommandLineOption("--image <filename>","Load an image and render it on a quad");
360    arguments.getApplicationUsage()->addCommandLineOption("--dem <filename>","Load an image/DEM and render it on a HeightField");
361    arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display command line parameters");
362    arguments.getApplicationUsage()->addCommandLineOption("--help-env","Display environmental variables available");
363    arguments.getApplicationUsage()->addCommandLineOption("--help-keys","Display keyboard & mouse bindings available");
364    arguments.getApplicationUsage()->addCommandLineOption("--help-all","Display all command line, env vars and keyboard & mouse bindings.");
365
366    arguments.getApplicationUsage()->addCommandLineOption("--dragger <draggername>","Use the specified dragger for manipulation [TabPlaneDragger, TabPlaneTrackballDragger, TrackballDragger, Translate1DDragger, Translate2DDragger, TranslateAxisDragger, TabBoxDragger, TranslatePlaneDragger, Scale1DDragger, Scale2DDragger]");
367    arguments.getApplicationUsage()->addCommandLineOption("--fixedDraggerSize","Fix the size of the dragger geometry in the screen space");
368   
369    bool fixedSizeInScreen = false;
370    while (arguments.read("--fixedDraggerSize")) { fixedSizeInScreen = true; }
371
372    // construct the viewer.
373    osgViewer::Viewer viewer;
374
375    // get details on keyboard and mouse bindings used by the viewer.
376    viewer.getUsage(*arguments.getApplicationUsage());
377
378    // if user request help write it out to cout.
379    bool helpAll = arguments.read("--help-all");
380    unsigned int helpType = ((helpAll || arguments.read("-h") || arguments.read("--help"))? osg::ApplicationUsage::COMMAND_LINE_OPTION : 0 ) |
381                            ((helpAll ||  arguments.read("--help-env"))? osg::ApplicationUsage::ENVIRONMENTAL_VARIABLE : 0 ) |
382                            ((helpAll ||  arguments.read("--help-keys"))? osg::ApplicationUsage::KEYBOARD_MOUSE_BINDING : 0 );
383    if (helpType)
384    {
385        arguments.getApplicationUsage()->write(std::cout, helpType);
386        return 1;
387    }
388
389    // report any errors if they have occurred when parsing the program arguments.
390    if (arguments.errors())
391    {
392        arguments.writeErrorMessages(std::cout);
393        return 1;
394    }
395
396    std::string dragger_name = "TabBoxDragger";
397    arguments.read("--dragger", dragger_name);
398
399    osg::Timer_t start_tick = osg::Timer::instance()->tick();
400
401    // read the scene from the list of file specified command line args.
402    osg::ref_ptr<osg::Node> loadedModel = osgDB::readNodeFiles(arguments);
403
404    // if no model has been successfully loaded report failure.
405    bool tragger2Scene(true);
406    if (!loadedModel)
407    {
408        //std::cout << arguments.getApplicationName() <<": No data loaded" << std::endl;
409        //return 1;
410        loadedModel = createDemoScene(fixedSizeInScreen);
411        tragger2Scene=false;
412    }
413
414    // any option left unread are converted into errors to write out later.
415    arguments.reportRemainingOptionsAsUnrecognized();
416
417    // report any errors if they have occurred when parsing the program arguments.
418    if (arguments.errors())
419    {
420        arguments.writeErrorMessages(std::cout);
421    }
422
423    osg::Timer_t end_tick = osg::Timer::instance()->tick();
424
425    std::cout << "Time to load = "<<osg::Timer::instance()->delta_s(start_tick,end_tick)<<std::endl;
426
427
428    // optimize the scene graph, remove redundant nodes and state etc.
429    osgUtil::Optimizer optimizer;
430    optimizer.optimize(loadedModel.get());
431
432   
433    // pass the loaded scene graph to the viewer.
434    if ( tragger2Scene ) {
435        viewer.setSceneData(addDraggerToScene(loadedModel.get(), dragger_name, fixedSizeInScreen));
436    } else {
437        viewer.setSceneData(loadedModel.get());
438    }
439
440
441    return viewer.run();
442}
Note: See TracBrowser for help on using the browser.