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

Revision 13019, 18.0 kB (checked in by robert, 2 years ago)

Added RotateCylinderDragger? and RotateSphereDragger? to list of manipulators for testing purposes

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