root/OpenSceneGraph/trunk/examples/osgmovie/osgmovie.cpp @ 9705

Revision 9705, 18.0 kB (checked in by robert, 6 years ago)

From Paul Melis, "While trying out the osgbrowser example (where I had forgotten to update
LD_LIBRARY_PATH so the XUL libs would be found) I noticed that although
the gecko plugin was found it could not be loaded. But this did not
trigger any visible warning/error message (at least not without INFO
notify level). Would you mind if we change the notify level for a
dlerror() to WARNING? This will also make it more explicit for the case
when a plugin isn't actually found, which seems to come up a lot for
novice users (e.g. no freetype on win32, so no freetype plugin, etc).
Also, the current error message is misleading ("Warning: Could not FIND
plugin to ...") because the it's not always a case of not finding the
plugin. I slightly enhanced the situation of not finding a plugin versus
finding it but not being able to load it.

Here's also a few fixes to some of the examples:
- osgfont: make usage help line more in line with the actual behaviour
- osgcompositeviewer: complain when no model file was provided
- osgmovie: don't include quicktime-dependent feature on Linux
- osgocclussionquery: comment addition (as I was surprised that lines
were being drawn in a function called createRandomTriangles())"

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
RevLine 
[6941]1/* OpenSceneGraph example, osgmovie.
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*/
[2693]18
[5927]19#include <osgViewer/Viewer>
[6949]20#include <osgViewer/ViewerEventHandlers>
[2693]21
22#include <osgDB/ReadFile>
23
24#include <osg/Geode>
25#include <osg/Geometry>
26#include <osg/StateSet>
27#include <osg/Material>
28#include <osg/Texture2D>
29#include <osg/TextureRectangle>
[6624]30#include <osg/TextureCubeMap>
[2693]31#include <osg/TexMat>
32#include <osg/CullFace>
[2810]33#include <osg/ImageStream>
[4956]34#include <osg/io_utils>
[2693]35
36#include <osgGA/TrackballManipulator>
[7615]37#include <osgGA/StateSetManipulator>
[4956]38#include <osgGA/EventVisitor>
[2693]39
[5927]40#include <iostream>
[3819]41
[2810]42class MovieEventHandler : public osgGA::GUIEventHandler
43{
44public:
45
[9395]46    MovieEventHandler():_playToggle(true),_trackMouse(false) {}
[9705]47
[6624]48    void setMouseTracking(bool track) { _trackMouse = track; }
49    bool getMouseTracking() const { return _trackMouse; }
[9705]50
[2810]51    void set(osg::Node* node);
52
[4956]53    virtual bool handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter& aa, osg::Object*, osg::NodeVisitor* nv);
[9705]54
[2810]55    virtual void getUsage(osg::ApplicationUsage& usage) const;
56
[7648]57    typedef std::vector< osg::observer_ptr<osg::ImageStream> > ImageStreamList;
[2810]58
59protected:
60
61    virtual ~MovieEventHandler() {}
62
63    class FindImageStreamsVisitor : public osg::NodeVisitor
64    {
65    public:
66        FindImageStreamsVisitor(ImageStreamList& imageStreamList):
67            _imageStreamList(imageStreamList) {}
[9705]68
[2810]69        virtual void apply(osg::Geode& geode)
70        {
71            apply(geode.getStateSet());
72
73            for(unsigned int i=0;i<geode.getNumDrawables();++i)
74            {
75                apply(geode.getDrawable(i)->getStateSet());
76            }
[9705]77
[2810]78            traverse(geode);
79        }
80
81        virtual void apply(osg::Node& node)
82        {
83            apply(node.getStateSet());
84            traverse(node);
85        }
[9705]86
[2810]87        inline void apply(osg::StateSet* stateset)
88        {
89            if (!stateset) return;
[9705]90
[2810]91            osg::StateAttribute* attr = stateset->getTextureAttribute(0,osg::StateAttribute::TEXTURE);
92            if (attr)
93            {
94                osg::Texture2D* texture2D = dynamic_cast<osg::Texture2D*>(attr);
95                if (texture2D) apply(dynamic_cast<osg::ImageStream*>(texture2D->getImage()));
96
97                osg::TextureRectangle* textureRec = dynamic_cast<osg::TextureRectangle*>(attr);
98                if (textureRec) apply(dynamic_cast<osg::ImageStream*>(textureRec->getImage()));
99            }
100        }
[9705]101
[2810]102        inline void apply(osg::ImageStream* imagestream)
103        {
[3819]104            if (imagestream)
105            {
[9705]106                _imageStreamList.push_back(imagestream);
[3819]107            }
[2810]108        }
[9705]109
[2810]110        ImageStreamList& _imageStreamList;
[9637]111
112    protected:
[9705]113
[9637]114        FindImageStreamsVisitor& operator = (const FindImageStreamsVisitor&) { return *this; }
115
[2810]116    };
117
118
[8757]119    bool            _playToggle;
[6624]120    bool            _trackMouse;
[2810]121    ImageStreamList _imageStreamList;
[9705]122
[2810]123};
124
125
126
127void MovieEventHandler::set(osg::Node* node)
128{
129    _imageStreamList.clear();
130    if (node)
131    {
132        FindImageStreamsVisitor fisv(_imageStreamList);
133        node->accept(fisv);
134    }
135}
136
137
[4956]138bool MovieEventHandler::handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter& aa, osg::Object*, osg::NodeVisitor* nv)
[2810]139{
140    switch(ea.getEventType())
141    {
[4956]142        case(osgGA::GUIEventAdapter::MOVE):
143        case(osgGA::GUIEventAdapter::PUSH):
144        case(osgGA::GUIEventAdapter::RELEASE):
145        {
[6624]146            if (_trackMouse)
[4956]147            {
[6624]148                osgViewer::View* view = dynamic_cast<osgViewer::View*>(&aa);
149                osgUtil::LineSegmentIntersector::Intersections intersections;
[8073]150                bool foundIntersection = view==0 ? false :
151                    (nv==0 ? view->computeIntersections(ea.getX(), ea.getY(), intersections) :
152                             view->computeIntersections(ea.getX(), ea.getY(), nv->getNodePath(), intersections));
[9705]153
[8073]154                if (foundIntersection)
[4956]155                {
156
[9705]157                    // use the nearest intersection
[6624]158                    const osgUtil::LineSegmentIntersector::Intersection& intersection = *(intersections.begin());
159                    osg::Drawable* drawable = intersection.drawable.get();
160                    osg::Geometry* geometry = drawable ? drawable->asGeometry() : 0;
161                    osg::Vec3Array* vertices = geometry ? dynamic_cast<osg::Vec3Array*>(geometry->getVertexArray()) : 0;
162                    if (vertices)
[4956]163                    {
[6624]164                        // get the vertex indices.
165                        const osgUtil::LineSegmentIntersector::Intersection::IndexList& indices = intersection.indexList;
166                        const osgUtil::LineSegmentIntersector::Intersection::RatioList& ratios = intersection.ratioList;
[4956]167
[6624]168                        if (indices.size()==3 && ratios.size()==3)
[4956]169                        {
[6624]170                            unsigned int i1 = indices[0];
171                            unsigned int i2 = indices[1];
172                            unsigned int i3 = indices[2];
[5951]173
[6624]174                            float r1 = ratios[0];
175                            float r2 = ratios[1];
176                            float r3 = ratios[2];
[5951]177
[6624]178                            osg::Array* texcoords = (geometry->getNumTexCoordArrays()>0) ? geometry->getTexCoordArray(0) : 0;
179                            osg::Vec2Array* texcoords_Vec2Array = dynamic_cast<osg::Vec2Array*>(texcoords);
180                            if (texcoords_Vec2Array)
181                            {
[9705]182                                // we have tex coord array so now we can compute the final tex coord at the point of intersection.
[6624]183                                osg::Vec2 tc1 = (*texcoords_Vec2Array)[i1];
184                                osg::Vec2 tc2 = (*texcoords_Vec2Array)[i2];
185                                osg::Vec2 tc3 = (*texcoords_Vec2Array)[i3];
186                                osg::Vec2 tc = tc1*r1 + tc2*r2 + tc3*r3;
187
188                                osg::notify(osg::NOTICE)<<"We hit tex coords "<<tc<<std::endl;
189
190                            }
[4956]191                        }
[6624]192                        else
193                        {
194                            osg::notify(osg::NOTICE)<<"Intersection has insufficient indices to work with";
195                        }
196
[4956]197                    }
[5951]198                }
[6624]199                else
200                {
201                    osg::notify(osg::NOTICE)<<"No intersection"<<std::endl;
202                }
[4956]203            }
204            break;
205        }
[2810]206        case(osgGA::GUIEventAdapter::KEYDOWN):
207        {
[7615]208            if (ea.getKey()=='p')
[2810]209            {
210                for(ImageStreamList::iterator itr=_imageStreamList.begin();
211                    itr!=_imageStreamList.end();
212                    ++itr)
213                {
[8757]214                    _playToggle = !_playToggle;
215                    if ( _playToggle )
[7615]216                    {
217                        // playing, so pause
218                        std::cout<<"Play"<<std::endl;
219                        (*itr)->play();
220                    }
221                    else
222                    {
223                        // playing, so pause
224                        std::cout<<"Pause"<<std::endl;
225                        (*itr)->pause();
226                    }
[2810]227                }
228                return true;
229            }
230            else if (ea.getKey()=='r')
231            {
[4520]232                for(ImageStreamList::iterator itr=_imageStreamList.begin();
233                    itr!=_imageStreamList.end();
234                    ++itr)
235                {
236                    std::cout<<"Restart"<<std::endl;
237                    (*itr)->rewind();
238                    (*itr)->play();
239                }
[2810]240                return true;
241            }
[7615]242            else if (ea.getKey()=='L')
[2810]243            {
[4520]244                for(ImageStreamList::iterator itr=_imageStreamList.begin();
245                    itr!=_imageStreamList.end();
246                    ++itr)
247                {
248                    if ( (*itr)->getLoopingMode() == osg::ImageStream::LOOPING)
249                    {
250                        std::cout<<"Toggle Looping Off"<<std::endl;
251                        (*itr)->setLoopingMode( osg::ImageStream::NO_LOOPING );
252                    }
253                    else
254                    {
255                        std::cout<<"Toggle Looping On"<<std::endl;
256                        (*itr)->setLoopingMode( osg::ImageStream::LOOPING );
257                    }
258                }
[2810]259                return true;
260            }
261            return false;
262        }
263
264        default:
265            return false;
266    }
[4956]267    return false;
[2810]268}
269
270void MovieEventHandler::getUsage(osg::ApplicationUsage& usage) const
271{
[7615]272    usage.addKeyboardMouseBinding("p","Play/Pause movie");
[4520]273    usage.addKeyboardMouseBinding("r","Restart movie");
[2810]274    usage.addKeyboardMouseBinding("l","Toggle looping of movie");
275}
276
277
[7479]278osg::Geometry* myCreateTexturedQuadGeometry(const osg::Vec3& pos,float width,float height, osg::Image* image, bool useTextureRectangle, bool xyPlane, bool option_flip)
[2693]279{
[6947]280    bool flip = image->getOrigin()==osg::Image::TOP_LEFT;
[7479]281    if (option_flip) flip = !flip;
[9705]282
[2809]283    if (useTextureRectangle)
284    {
[4746]285        osg::Geometry* pictureQuad = osg::createTexturedQuadGeometry(pos,
[2809]286                                           osg::Vec3(width,0.0f,0.0f),
[7477]287                                           xyPlane ? osg::Vec3(0.0f,height,0.0f) : osg::Vec3(0.0f,0.0f,height),
[6947]288                                           0.0f, flip ? image->t() : 0.0, image->s(), flip ? 0.0 : image->t());
[4321]289
[6941]290        osg::TextureRectangle* texture = new osg::TextureRectangle(image);
291        texture->setWrap(osg::Texture::WRAP_S, osg::Texture::CLAMP_TO_EDGE);
292        texture->setWrap(osg::Texture::WRAP_T, osg::Texture::CLAMP_TO_EDGE);
[9705]293
294
[2809]295        pictureQuad->getOrCreateStateSet()->setTextureAttributeAndModes(0,
[6941]296                                                                        texture,
297                                                                        osg::StateAttribute::ON);
[9705]298
[2809]299        return pictureQuad;
[2693]300    }
[2809]301    else
302    {
[4746]303        osg::Geometry* pictureQuad = osg::createTexturedQuadGeometry(pos,
[2809]304                                           osg::Vec3(width,0.0f,0.0f),
[7477]305                                           xyPlane ? osg::Vec3(0.0f,height,0.0f) : osg::Vec3(0.0f,0.0f,height),
[6947]306                                           0.0f, flip ? 1.0f : 0.0f , 1.0f, flip ? 0.0f : 1.0f);
[9705]307
[4321]308        osg::Texture2D* texture = new osg::Texture2D(image);
[8857]309        texture->setResizeNonPowerOfTwoHint(false);
[6941]310        texture->setFilter(osg::Texture::MIN_FILTER,osg::Texture::LINEAR);
311        texture->setWrap(osg::Texture::WRAP_S, osg::Texture::CLAMP_TO_EDGE);
312        texture->setWrap(osg::Texture::WRAP_T, osg::Texture::CLAMP_TO_EDGE);
[9705]313
314
[2809]315        pictureQuad->getOrCreateStateSet()->setTextureAttributeAndModes(0,
[4321]316                    texture,
[2809]317                    osg::StateAttribute::ON);
[2693]318
[2809]319        return pictureQuad;
320    }
[2693]321}
322
323int main(int argc, char** argv)
324{
325    // use an ArgumentParser object to manage the program arguments.
326    osg::ArgumentParser arguments(&argc,argv);
[9705]327
[2693]328    // set up the usage document, in case we need to print out how to use this program.
329    arguments.getApplicationUsage()->setApplicationName(arguments.getApplicationName());
[4780]330    arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" example demonstrates the use of ImageStream for rendering movies as textures.");
[2693]331    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ...");
332    arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
[5927]333    arguments.getApplicationUsage()->addCommandLineOption("--texture2D","Use Texture2D rather than TextureRectangle.");
334    arguments.getApplicationUsage()->addCommandLineOption("--shader","Use shaders to post process the video.");
[7480]335    arguments.getApplicationUsage()->addCommandLineOption("--interactive","Use camera manipulator to allow movement around movie.");
336    arguments.getApplicationUsage()->addCommandLineOption("--flip","Flip the movie so top becomes bottom.");
[9705]337#if defined(WIN32) || defined(__APPLE__)
[7594]338    arguments.getApplicationUsage()->addCommandLineOption("--devices","Print the Video input capability via QuickTime and exit.");
[9705]339#endif
340
[4321]341    bool useTextureRectangle = true;
342    bool useShader = false;
[2693]343
344    // construct the viewer.
[7475]345    osgViewer::Viewer viewer(arguments);
[9705]346
[6625]347    if (arguments.argc()<=1)
348    {
349        arguments.getApplicationUsage()->write(std::cout,osg::ApplicationUsage::COMMAND_LINE_OPTION);
350        return 1;
351    }
352
[9705]353#if defined(WIN32) || defined(__APPLE__)
[7594]354    // if user requests devices video capability.
355    if (arguments.read("-devices") || arguments.read("--devices"))
356    {
357        // Force load QuickTime plugin, probe video capability, exit
358        osgDB::readImageFile("devices.live");
359        return 1;
360    }
[9705]361#endif
[7594]362
[4321]363    while (arguments.read("--texture2D")) useTextureRectangle=false;
364    while (arguments.read("--shader")) useShader=true;
[2693]365
[8073]366    bool mouseTracking = false;
[9705]367    while (arguments.read("--mouse")) mouseTracking=true;
[8073]368
369
[2693]370    // if user request help write it out to cout.
371    if (arguments.read("-h") || arguments.read("--help"))
372    {
373        arguments.getApplicationUsage()->write(std::cout);
374        return 1;
375    }
376
[7477]377    bool fullscreen = !arguments.read("--interactive");
[7479]378    bool flip = arguments.read("--flip");
[4321]379
[7477]380    osg::ref_ptr<osg::Geode> geode = new osg::Geode;
[4322]381
[7477]382    osg::StateSet* stateset = geode->getOrCreateStateSet();
383    stateset->setMode(GL_LIGHTING,osg::StateAttribute::OFF);
[4322]384
[7477]385    if (useShader)
386    {
387        //useTextureRectangle = false;
[4321]388
[7477]389        static const char *shaderSourceTextureRec = {
390            "uniform vec4 cutoff_color;\n"
391            "uniform samplerRect movie_texture;\n"
392            "void main(void)\n"
393            "{\n"
[8857]394            "    vec4 texture_color = textureRect(movie_texture, gl_TexCoord[0].st); \n"
[7477]395            "    if (all(lessThanEqual(texture_color,cutoff_color))) discard; \n"
396            "    gl_FragColor = texture_color;\n"
397            "}\n"
398        };
[4321]399
[7477]400        static const char *shaderSourceTexture2D = {
401            "uniform vec4 cutoff_color;\n"
402            "uniform sampler2D movie_texture;\n"
403            "void main(void)\n"
404            "{\n"
[8857]405            "    vec4 texture_color = texture2D(movie_texture, gl_TexCoord[0].st); \n"
[7477]406            "    if (all(lessThanEqual(texture_color,cutoff_color))) discard; \n"
407            "    gl_FragColor = texture_color;\n"
408            "}\n"
409        };
[4321]410
[7477]411        osg::Program* program = new osg::Program;
[4321]412
[7477]413        program->addShader(new osg::Shader(osg::Shader::FRAGMENT,
414                                           useTextureRectangle ? shaderSourceTextureRec : shaderSourceTexture2D));
[4321]415
[7477]416        stateset->addUniform(new osg::Uniform("cutoff_color",osg::Vec4(0.1f,0.1f,0.1f,1.0f)));
417        stateset->addUniform(new osg::Uniform("movie_texture",0));
[6625]418
[7477]419        stateset->setAttribute(program);
[6625]420
[7477]421    }
[6625]422
[7477]423    osg::Vec3 pos(0.0f,0.0f,0.0f);
424    osg::Vec3 topleft = pos;
425    osg::Vec3 bottomright = pos;
[9705]426
[7477]427    bool xyPlane = fullscreen;
[9705]428
[7477]429    for(int i=1;i<arguments.argc();++i)
430    {
431        if (arguments.isString(i))
[2809]432        {
[7477]433            osg::Image* image = osgDB::readImageFile(arguments[i]);
434            osg::ImageStream* imagestream = dynamic_cast<osg::ImageStream*>(image);
435            if (imagestream) imagestream->play();
436
437            if (image)
[4082]438            {
[8659]439                osg::notify(osg::NOTICE)<<"image->s()"<<image->s()<<" image-t()="<<image->t()<<std::endl;
[9705]440
[7479]441                geode->addDrawable(myCreateTexturedQuadGeometry(pos,image->s(),image->t(),image, useTextureRectangle, xyPlane, flip));
[9705]442
[7477]443                bottomright = pos + osg::Vec3(static_cast<float>(image->s()),static_cast<float>(image->t()),0.0f);
[6624]444
[8659]445                if (xyPlane) pos.y() += image->t()*1.05f;
446                else pos.z() += image->t()*1.05f;
[4082]447            }
[7477]448            else
449            {
450                std::cout<<"Unable to read file "<<arguments[i]<<std::endl;
[9705]451            }
[2809]452        }
453    }
[9705]454
[7477]455    // set the scene to render
456    viewer.setSceneData(geode.get());
[2809]457
[7477]458    if (viewer.getSceneData()==0)
459    {
460        arguments.getApplicationUsage()->write(std::cout);
461        return 1;
462    }
463
[2810]464    // pass the model to the MovieEventHandler so it can pick out ImageStream's to manipulate.
[4956]465    MovieEventHandler* meh = new MovieEventHandler();
[8073]466    meh->setMouseTracking( mouseTracking );
[7615]467    meh->set( viewer.getSceneData() );
468    viewer.addEventHandler( meh );
[2809]469
[7615]470    viewer.addEventHandler( new osgViewer::StatsHandler );
471    viewer.addEventHandler( new osgGA::StateSetManipulator( viewer.getCamera()->getOrCreateStateSet() ) );
472    viewer.addEventHandler( new osgViewer::WindowSizeHandler );
473
474    // add the record camera path handler
475    viewer.addEventHandler(new osgViewer::RecordCameraPathHandler);
476
[7648]477    // report any errors if they have occurred when parsing the program arguments.
[2693]478    if (arguments.errors())
479    {
480        arguments.writeErrorMessages(std::cout);
481        return 1;
482    }
483
[7477]484    if (fullscreen)
485    {
486        viewer.realize();
[6624]487
[7477]488        viewer.getCamera()->setViewMatrix(osg::Matrix::identity());
489        viewer.getCamera()->setProjectionMatrixAsOrtho2D(topleft.x(),bottomright.x(),topleft.y(),bottomright.y());
[2693]490
[7477]491        while(!viewer.done())
492        {
493            viewer.frame();
494        }
495        return 0;
496    }
497    else
498    {
499        // create the windows and run the threads.
500        return viewer.run();
501    }
[2693]502}
Note: See TracBrowser for help on using the browser.