root/OpenSceneGraph/trunk/examples/osgstereoimage/osgstereoimage.cpp @ 1813

Revision 1813, 17.3 kB (checked in by robert, 12 years ago)

Fixed setView to work with new OsgCameraGroup::setView

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
Line 
1/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2003 Robert Osfield
2 *
3 * This library is open source and may be redistributed and/or modified under 
4 * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
5 * (at your option) any later version.  The full license is in LICENSE file
6 * included with this distribution, and on the openscenegraph.org website.
7 *
8 * This library is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11 * OpenSceneGraph Public License for more details.
12*/
13
14#include <osgProducer/Viewer>
15#include <osgDB/ReadFile>
16#include <osgDB/WriteFile>
17#include <osgUtil/Optimizer>
18
19#include <osg/Geode>
20#include <osg/Notify>
21#include <osg/MatrixTransform>
22#include <osg/Switch>
23#include <osg/TexMat>
24#include <osg/Texture2D>
25
26
27
28typedef std::vector<std::string> FileList;
29
30class SlideEventHandler : public osgGA::GUIEventHandler, public osg::NodeCallback
31{
32public:
33
34    SlideEventHandler();
35   
36    META_Object(osgStereImageApp,SlideEventHandler);
37
38
39    void set(osg::Switch* sw, float offsetX, float offsetY, osg::TexMat* texmatLeft, osg::TexMat* texmatRight, float timePerSlide, bool autoSteppingActive);
40
41    virtual void accept(osgGA::GUIEventHandlerVisitor& v) { v.visit(*this); }
42
43    virtual bool handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter&);
44   
45    virtual void getUsage(osg::ApplicationUsage& usage) const;
46
47    virtual void operator()(osg::Node* node, osg::NodeVisitor* nv);
48   
49    void nextSlide();
50   
51    void previousSlide();
52   
53    void scaleImage(float s);
54   
55    void offsetImage(float ds,float dt);
56
57    void rotateImage(float rx,float ry);
58
59    void initTexMatrices();
60
61protected:
62
63    ~SlideEventHandler() {}
64    SlideEventHandler(const SlideEventHandler&,const osg::CopyOp&) {}
65
66    osg::ref_ptr<osg::Switch>   _switch;
67    osg::ref_ptr<osg::TexMat>   _texmatLeft;
68    osg::ref_ptr<osg::TexMat>   _texmatRight;
69    bool                        _firstTraversal;
70    unsigned int                _activeSlide;
71    double                      _previousTime;
72    double                      _timePerSlide;
73    bool                        _autoSteppingActive;
74    float                       _initSeperationX;
75    float                       _currentSeperationX;
76    float                       _initSeperationY;
77    float                       _currentSeperationY;
78       
79};
80
81SlideEventHandler::SlideEventHandler():
82    _switch(0),
83    _texmatLeft(0),
84    _texmatRight(0),
85    _firstTraversal(true),
86    _activeSlide(0),
87    _previousTime(-1.0f),
88    _timePerSlide(5.0),
89    _autoSteppingActive(false)
90{
91}
92
93void SlideEventHandler::set(osg::Switch* sw, float offsetX, float offsetY, osg::TexMat* texmatLeft, osg::TexMat* texmatRight, float timePerSlide, bool autoSteppingActive)
94{
95    _switch = sw;
96    _switch->setUpdateCallback(this);
97
98    _texmatLeft = texmatLeft;
99    _texmatRight = texmatRight;
100
101    _timePerSlide = timePerSlide;
102    _autoSteppingActive = autoSteppingActive;   
103   
104    _initSeperationX = offsetX;
105    _currentSeperationX = _initSeperationX;
106
107    _initSeperationY = offsetY;
108    _currentSeperationY = _initSeperationY;
109
110    initTexMatrices();
111
112}
113
114bool SlideEventHandler::handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter&)
115{
116    switch(ea.getEventType())
117    {
118        case(osgGA::GUIEventAdapter::KEYDOWN):
119        {
120            if (ea.getKey()=='a')
121            {
122                _autoSteppingActive = !_autoSteppingActive;
123                _previousTime = ea.time();
124                return true;
125            }
126            else if (ea.getKey()=='n')
127            {
128                nextSlide();
129                return true;
130            }
131            else if (ea.getKey()=='p')
132            {
133                previousSlide();
134                return true;
135            }
136            else if (ea.getKey()=='w')
137            {
138                scaleImage(0.99f);
139                return true;
140            }
141            else if (ea.getKey()=='s')
142            {
143                scaleImage(1.01f);
144                return true;
145            }
146            else if (ea.getKey()=='j')
147            {
148                offsetImage(-0.001f,0.0f);
149                return true;
150            }
151            else if (ea.getKey()=='k')
152            {
153                offsetImage(0.001f,0.0f);
154                return true;
155            }
156            else if (ea.getKey()=='i')
157            {
158                offsetImage(0.0f,-0.001f);
159                return true;
160            }
161            else if (ea.getKey()=='m')
162            {
163                offsetImage(0.0f,0.001f);
164                return true;
165            }
166            else if (ea.getKey()==' ')
167            {
168                initTexMatrices();
169                return true;
170            }
171            return false;
172        }
173        case(osgGA::GUIEventAdapter::DRAG):
174        case(osgGA::GUIEventAdapter::MOVE):
175        {
176            static float px = ea.getX();
177            static float py = ea.getY();
178           
179            float dx = ea.getX()-px;
180            float dy = ea.getY()-py;
181           
182            px = ea.getX();
183            py = ea.getY();
184           
185            rotateImage((float)dx/(float)(ea.getXmax()-ea.getXmin()),(float)dy/(float)(ea.getYmax()-ea.getYmin()));
186           
187            return true;
188        }
189
190        default:
191            return false;
192    }
193}
194
195void SlideEventHandler::getUsage(osg::ApplicationUsage& usage) const
196{
197    usage.addKeyboardMouseBinding("Space","Reset the image position to center");
198    usage.addKeyboardMouseBinding("a","Toggle on/off the automatic advancement for image to image");
199    usage.addKeyboardMouseBinding("n","Advance to next image");
200    usage.addKeyboardMouseBinding("p","Move to previous image");
201    usage.addKeyboardMouseBinding("q","Zoom into the image");
202    usage.addKeyboardMouseBinding("a","Zoom out of the image");
203    usage.addKeyboardMouseBinding("j","Reduce horizontal offset");
204    usage.addKeyboardMouseBinding("k","Increase horizontal offset");
205    usage.addKeyboardMouseBinding("m","Reduce vertical offset");
206    usage.addKeyboardMouseBinding("i","Increase vertical offset");
207}
208
209void SlideEventHandler::operator()(osg::Node* node, osg::NodeVisitor* nv)
210{
211    if (_autoSteppingActive && nv->getFrameStamp())
212    {
213        double time = nv->getFrameStamp()->getReferenceTime();
214       
215        if (_firstTraversal)
216        {
217            _firstTraversal = false;
218            _previousTime = time;
219        }
220        else if (time-_previousTime>_timePerSlide)
221        {
222            _previousTime = time;
223           
224            nextSlide();
225        }
226       
227    }
228
229    traverse(node,nv);
230}
231
232void SlideEventHandler::nextSlide()
233{
234    if (_switch->getNumChildren()==0) return;
235
236    ++_activeSlide;
237    if (_activeSlide>=_switch->getNumChildren()) _activeSlide = 0;
238
239    _switch->setSingleChildOn(_activeSlide);
240}
241
242void SlideEventHandler::previousSlide()
243{
244    if (_switch->getNumChildren()==0) return;
245
246    if (_activeSlide==0) _activeSlide = _switch->getNumChildren()-1;
247    else --_activeSlide;
248
249    _switch->setSingleChildOn(_activeSlide);
250}
251
252void SlideEventHandler::scaleImage(float s)
253{
254    _texmatLeft->setMatrix(_texmatLeft->getMatrix()*osg::Matrix::translate(-0.5f,-0.5f,0.0f)*osg::Matrix::scale(s,s,1.0f)*osg::Matrix::translate(0.5f,0.5f,0.0f));
255    _texmatRight->setMatrix(_texmatRight->getMatrix()*osg::Matrix::translate(-0.5f,-0.5f,0.0f)*osg::Matrix::scale(s,s,1.0f)*osg::Matrix::translate(0.5f,0.5f,0.0f));
256}
257
258void SlideEventHandler::offsetImage(float ds,float dt)
259{
260    _currentSeperationX+=ds;
261    _currentSeperationY+=dt;
262    osg::notify(osg::NOTICE)<<"image offset x = "<<_currentSeperationX<<"  y ="<<_currentSeperationY<<std::endl;
263    _texmatLeft->setMatrix(_texmatLeft->getMatrix()*osg::Matrix::translate(ds,dt,0.0f));
264    _texmatRight->setMatrix(_texmatRight->getMatrix()*osg::Matrix::translate(-ds,-dt,0.0f));
265}
266
267void SlideEventHandler::rotateImage(float rx,float ry)
268{
269    const float scale = 0.5f;
270    _texmatLeft->setMatrix(_texmatLeft->getMatrix()*osg::Matrix::translate(-rx*scale,ry*scale,0.0f));
271    _texmatRight->setMatrix(_texmatRight->getMatrix()*osg::Matrix::translate(-rx*scale,ry*scale,0.0f));
272}
273
274void SlideEventHandler::initTexMatrices()
275{
276    _texmatLeft->setMatrix(osg::Matrix::translate(_initSeperationX,_initSeperationY,0.0f));
277    _texmatRight->setMatrix(osg::Matrix::translate(-_initSeperationX,-_initSeperationY,0.0f));
278}
279
280
281osg::Geode* createSectorForImage(osg::Image* image, osg::TexMat* texmat, float s,float t, float radius, float height, float length)
282{
283
284    int numSegments = 20;
285    float Theta = length/radius;
286    float dTheta = Theta/(float)(numSegments-1);
287   
288    float ThetaZero = height*s/(t*radius);
289   
290    // set up the texture.
291    osg::Texture2D* texture = new osg::Texture2D;
292    texture->setFilter(osg::Texture2D::MIN_FILTER,osg::Texture2D::LINEAR);
293    texture->setFilter(osg::Texture2D::MAG_FILTER,osg::Texture2D::LINEAR);
294    texture->setImage(image);
295
296    // set up the drawstate.
297    osg::StateSet* dstate = new osg::StateSet;
298    dstate->setMode(GL_CULL_FACE,osg::StateAttribute::OFF);
299    dstate->setMode(GL_LIGHTING,osg::StateAttribute::OFF);
300    dstate->setTextureAttributeAndModes(0, texture,osg::StateAttribute::ON);
301    dstate->setTextureAttribute(0, texmat);
302
303    // set up the geoset.
304    osg::Geometry* geom = new osg::Geometry;
305    geom->setStateSet(dstate);
306
307    osg::Vec3Array* coords = new osg::Vec3Array();
308    osg::Vec2Array* tcoords = new osg::Vec2Array();
309   
310    int i;
311    float angle = -Theta/2.0f;
312    for(i=0;
313        i<numSegments;
314        ++i, angle+=dTheta)
315    {
316        coords->push_back(osg::Vec3(sinf(angle)*radius,cosf(angle)*radius,height*0.5f)); // top
317        coords->push_back(osg::Vec3(sinf(angle)*radius,cosf(angle)*radius,-height*0.5f)); // bottom.
318       
319        tcoords->push_back(osg::Vec2(angle/ThetaZero+0.5f,1.0f)); // top
320        tcoords->push_back(osg::Vec2(angle/ThetaZero+0.5f,0.0f)); // bottom.
321
322    }
323
324    osg::Vec4Array* colors = new osg::Vec4Array();
325    colors->push_back(osg::Vec4(1.0f,1.0f,1.0f,1.0f));
326
327    osg::DrawArrays* elements = new osg::DrawArrays(osg::PrimitiveSet::QUAD_STRIP,0,coords->size());
328
329   
330
331    geom->setVertexArray(coords);
332    geom->setTexCoordArray(0,tcoords);
333    geom->setColorArray(colors);
334    geom->setColorBinding(osg::Geometry::BIND_OVERALL);
335
336    geom->addPrimitiveSet(elements);
337
338    // set up the geode.
339    osg::Geode* geode = new osg::Geode;
340    geode->addDrawable(geom);
341
342    return geode;
343
344}
345
346// create a switch containing a set of child each containing a
347// stereo image pair.
348osg::Switch* createScene(const FileList& fileList, osg::TexMat* texmatLeft, osg::TexMat* texmatRight, float radius, float height, float length)
349{
350    osg::Switch* sw = new osg::Switch;
351
352    // load the images.
353    for(unsigned int i=0;i+1<fileList.size();i+=2)
354    {
355        osg::ref_ptr<osg::Image> imageLeft = osgDB::readImageFile(fileList[i]);
356        osg::ref_ptr<osg::Image> imageRight = osgDB::readImageFile(fileList[i+1]);
357        if (imageLeft.valid() && imageRight.valid())
358        {
359            float average_s = (imageLeft->s()+imageRight->s())*0.5f;
360            float average_t = (imageLeft->t()+imageRight->t())*0.5f;
361
362            osg::Geode* geodeLeft = createSectorForImage(imageLeft.get(),texmatLeft,average_s,average_t, radius, height, length);
363            geodeLeft->setNodeMask(0x01);
364
365            osg::Geode* geodeRight = createSectorForImage(imageRight.get(),texmatRight,average_s,average_t, radius, height, length);
366            geodeRight->setNodeMask(0x02);
367
368            osg::ref_ptr<osg::Group> imageGroup = new osg::Group;
369           
370            imageGroup->addChild(geodeLeft);
371            imageGroup->addChild(geodeRight);
372           
373            sw->addChild(imageGroup.get());
374        }
375        else
376        {
377            std::cout << "Warning: Unable to load both image files, '"<<fileList[i]<<"' & '"<<fileList[i+1]<<"', required for stereo imaging."<<std::endl;
378        }
379    }
380
381
382    if (sw->getNumChildren()>0)
383    {
384        // select first child.
385        sw->setSingleChildOn(0);
386    }
387
388    return sw;
389}
390
391int main( int argc, char **argv )
392{
393
394    // use an ArgumentParser object to manage the program arguments.
395    osg::ArgumentParser arguments(&argc,argv);
396   
397    // set up the usage document, in case we need to print out how to use this program.
398    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getProgramName()+" [options] image_file_left_eye image_file_right_eye");
399    arguments.getApplicationUsage()->addCommandLineOption("-d <float>","Time delay in sceonds between the display of successive image pairs when in auto advance mode.");
400    arguments.getApplicationUsage()->addCommandLineOption("-a","Enter auto advance of image pairs on start up.");
401    arguments.getApplicationUsage()->addCommandLineOption("-x <float>","Horizontal offset of left and right images.");
402    arguments.getApplicationUsage()->addCommandLineOption("-y <float>","Vertical offset of left and right images.");
403    arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
404   
405
406    // construct the viewer.
407    osgProducer::Viewer viewer(arguments);
408
409    // set up the value with sensible default event handlers.
410    viewer.setUpViewer(osgProducer::Viewer::ESCAPE_SETS_DONE);
411
412    // register the handler to add keyboard and mosue handling.
413    SlideEventHandler* seh = new SlideEventHandler();
414    viewer.getEventHandlerList().push_front(seh);
415
416
417    // get details on keyboard and mouse bindings used by the viewer.
418    viewer.getUsage(*arguments.getApplicationUsage());
419
420    // read any time delay argument.
421    float timeDelayBetweenSlides = 5.0f;
422    while (arguments.read("-d",timeDelayBetweenSlides)) {}
423
424    bool autoSteppingActive = false;
425    while (arguments.read("-a")) autoSteppingActive = true;
426
427    float offsetX=0.0f;
428    while (arguments.read("-x",offsetX)) {}
429
430    float offsetY=0.0f;
431    while (arguments.read("-y",offsetY)) {}
432
433    // if user request help write it out to cout.
434    if (arguments.read("-h") || arguments.read("--help"))
435    {
436        arguments.getApplicationUsage()->write(std::cout);
437        return 1;
438    }
439
440    // any option left unread are converted into errors to write out later.
441    arguments.reportRemainingOptionsAsUnrecognized();
442
443    // report any errors if they have occured when parsing the program aguments.
444    if (arguments.errors())
445    {
446        arguments.writeErrorMessages(std::cout);
447        return 1;
448    }
449
450    // extract the filenames from the arguments list.
451    FileList fileList;
452    for(int pos=1;pos<arguments.argc();++pos)
453    {
454        if (arguments.isString(pos)) fileList.push_back(arguments[pos]);
455    }
456
457    if (fileList.size()<2)
458    {
459        return 1;
460    }
461
462    // set up the use of stereo by default.
463    osg::DisplaySettings* ds = viewer.getDisplaySettings();
464    if (!ds) ds = osg::DisplaySettings::instance();
465    if (ds) ds->setStereo(true);
466
467    // create the windows and run the threads.
468    viewer.realize(Producer::CameraGroup::ThreadPerCamera);
469
470    // now the windows have been realized we switch off the cursor to prevent it
471    // distracting the people seeing the stereo images.
472    float fovy = 1.0f;
473    for( unsigned int i = 0; i < viewer.getCameraConfig()->getNumberOfCameras(); i++ )
474    {
475        Producer::Camera* cam = viewer.getCameraConfig()->getCamera(i);
476        Producer::RenderSurface* rs = cam->getRenderSurface();
477        rs->useCursor(false);
478        fovy = cam->getLensVerticalFov();
479    }
480
481    float radius = 1.0f;
482    float height = 2*radius*tan(fovy*0.5f);
483    float length = osg::PI*radius;  // half a cylinder.
484
485    // use a texure matrix to control the placement of the image.
486    osg::TexMat* texmatLeft = new osg::TexMat;
487    osg::TexMat* texmatRight = new osg::TexMat;
488
489    // creat the scene from the file list.
490    osg::ref_ptr<osg::Switch> rootNode = createScene(fileList,texmatLeft,texmatRight,radius,height,length);
491
492
493    //osgDB::writeNodeFile(*rootNode,"test.osg");
494
495    // set the scene to render
496    viewer.setSceneData(rootNode.get());
497
498
499    // set all the sceneview's up so that their left and right add cull masks are set up.
500    for(osgProducer::OsgCameraGroup::SceneHandlerList::iterator itr=viewer.getSceneHandlerList().begin();
501        itr!=viewer.getSceneHandlerList().end();
502        ++itr)
503    {
504        osgUtil::SceneView* sceneview = itr->get();
505        sceneview->setCullMask(0xffffffff);
506        sceneview->setCullMaskLeft(0x00000001);
507        sceneview->setCullMaskRight(0x00000002);
508        sceneview->setFusionDistance(osgUtil::SceneView::USE_FUSION_DISTANCE_VALUE,radius);
509        sceneview->setCamera(0);
510    }
511
512
513    // set up the SlideEventHandler.
514    seh->set(rootNode.get(),offsetX,offsetY,texmatLeft,texmatRight,timeDelayBetweenSlides,autoSteppingActive);
515   
516   
517    osg::Matrix homePosition;
518    homePosition.makeLookAt(osg::Vec3(0.0f,0.0f,0.0f),osg::Vec3(0.0f,1.0f,0.0f),osg::Vec3(0.0f,0.0f,1.0f));
519       
520    while( !viewer.done() )
521    {
522        // wait for all cull and draw threads to complete.
523        viewer.sync();
524
525        // update the scene by traversing it with the the update visitor which will
526        // call all node update callbacks and animations.
527        viewer.update();
528         
529        viewer.setView(homePosition);
530
531        // fire off the cull and draw traversals of the scene.
532        viewer.frame();
533       
534    }
535   
536    // wait for all cull and draw threads to complete before exit.
537    viewer.sync();
538   
539    return 0;
540}
Note: See TracBrowser for help on using the browser.