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

Revision 12933, 17.5 kB (checked in by robert, 3 years ago)

Renamed selection to transform to make it clear to understand what is being done.

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