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

Revision 10809, 24.9 kB (checked in by robert, 4 years ago)

From Rafa Gaitan, "Current ffmpeg plugin didn't support pause and seek, I have added this
functionality and I also modified osgmovie example to support "seek"."

Note from Robert Osfield, changes osgmovie to use '>' for the seek as '+' was already used in a separate submission that had been merged.

  • 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
[10799]46    MovieEventHandler():_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
[6624]119    bool            _trackMouse;
[2810]120    ImageStreamList _imageStreamList;
[10809]121    unsigned int    _seekIncr;
[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                {
[10799]214                    osg::ImageStream::StreamStatus playToggle = (*itr)->getStatus();
215                    if (playToggle != osg::ImageStream::PLAYING)
[7615]216                    {
[10799]217                        std::cout<< (*itr).get() << " Play"<<std::endl;
[7615]218                        (*itr)->play();
219                    }
220                    else
221                    {
222                        // playing, so pause
[10799]223                        std::cout<< (*itr).get() << " Pause"<<std::endl;
[7615]224                        (*itr)->pause();
225                    }
[2810]226                }
227                return true;
228            }
229            else if (ea.getKey()=='r')
230            {
[4520]231                for(ImageStreamList::iterator itr=_imageStreamList.begin();
232                    itr!=_imageStreamList.end();
233                    ++itr)
234                {
[10799]235                    std::cout<< (*itr).get() << " Restart"<<std::endl;
[4520]236                    (*itr)->rewind();
237                    (*itr)->play();
238                }
[2810]239                return true;
240            }
[10809]241            else if (ea.getKey()=='>')
242            {
243                for(ImageStreamList::iterator itr=_imageStreamList.begin();
244                    itr!=_imageStreamList.end();
245                    ++itr)
246                {
247                    std::cout<<"Seeking"<<std::endl;
248                    if(_seekIncr > 3) _seekIncr = 0;
249                    double length = (*itr)->getLength();
250                    double t_pos = (length/4.0f)*_seekIncr;
251                    //(*itr)->rewind();
252                    (*itr)->seek(t_pos);
253                    (*itr)->play();
254                    _seekIncr++;
255                }
256                return true;
257            }
[7615]258            else if (ea.getKey()=='L')
[2810]259            {
[4520]260                for(ImageStreamList::iterator itr=_imageStreamList.begin();
261                    itr!=_imageStreamList.end();
262                    ++itr)
263                {
264                    if ( (*itr)->getLoopingMode() == osg::ImageStream::LOOPING)
265                    {
[10799]266                        std::cout<< (*itr).get() << " Toggle Looping Off"<<std::endl;
[4520]267                        (*itr)->setLoopingMode( osg::ImageStream::NO_LOOPING );
268                    }
269                    else
270                    {
[10799]271                        std::cout<< (*itr).get() << " Toggle Looping On"<<std::endl;
[4520]272                        (*itr)->setLoopingMode( osg::ImageStream::LOOPING );
273                    }
274                }
[2810]275                return true;
276            }
[10799]277            else if (ea.getKey()=='+')
278            {
279                for(ImageStreamList::iterator itr=_imageStreamList.begin();
280                    itr!=_imageStreamList.end();
281                    ++itr)
282                {
283                    double tm = (*itr)->getTimeMultiplier();
284                    tm += 0.1;
285                    (*itr)->setTimeMultiplier(tm);
286                    std::cout << (*itr).get() << " Increase speed rate "<< (*itr)->getTimeMultiplier() << std::endl;
287                }
288                return true;
289            }
290            else if (ea.getKey()=='-')
291            {
292                for(ImageStreamList::iterator itr=_imageStreamList.begin();
293                    itr!=_imageStreamList.end();
294                    ++itr)
295                {
296                    double tm = (*itr)->getTimeMultiplier();
297                    tm -= 0.1;
298                    (*itr)->setTimeMultiplier(tm);
299                    std::cout << (*itr).get() << " Decrease speed rate "<< (*itr)->getTimeMultiplier() << std::endl;
300                }
301                return true;
302            }
303            else if (ea.getKey()=='o')
304            {
305                for(ImageStreamList::iterator itr=_imageStreamList.begin();
306                    itr!=_imageStreamList.end();
307                    ++itr)
308                {
309                    std::cout<< (*itr).get() << " Frame rate  "<< (*itr)->getFrameRate() <<std::endl;
310                }
311                return true;
312            }
[2810]313            return false;
314        }
315
316        default:
317            return false;
318    }
[4956]319    return false;
[2810]320}
321
322void MovieEventHandler::getUsage(osg::ApplicationUsage& usage) const
323{
[7615]324    usage.addKeyboardMouseBinding("p","Play/Pause movie");
[4520]325    usage.addKeyboardMouseBinding("r","Restart movie");
[2810]326    usage.addKeyboardMouseBinding("l","Toggle looping of movie");
[10799]327    usage.addKeyboardMouseBinding("+","Increase speed of movie");
328    usage.addKeyboardMouseBinding("-","Decrease speed of movie");
329    usage.addKeyboardMouseBinding("o","Display frame rate of movie");
[10809]330    usage.addKeyboardMouseBinding(">","Advance the movie using seek");
[2810]331}
332
333
[7479]334osg::Geometry* myCreateTexturedQuadGeometry(const osg::Vec3& pos,float width,float height, osg::Image* image, bool useTextureRectangle, bool xyPlane, bool option_flip)
[2693]335{
[6947]336    bool flip = image->getOrigin()==osg::Image::TOP_LEFT;
[7479]337    if (option_flip) flip = !flip;
[9705]338
[2809]339    if (useTextureRectangle)
340    {
[4746]341        osg::Geometry* pictureQuad = osg::createTexturedQuadGeometry(pos,
[2809]342                                           osg::Vec3(width,0.0f,0.0f),
[7477]343                                           xyPlane ? osg::Vec3(0.0f,height,0.0f) : osg::Vec3(0.0f,0.0f,height),
[6947]344                                           0.0f, flip ? image->t() : 0.0, image->s(), flip ? 0.0 : image->t());
[4321]345
[6941]346        osg::TextureRectangle* texture = new osg::TextureRectangle(image);
347        texture->setWrap(osg::Texture::WRAP_S, osg::Texture::CLAMP_TO_EDGE);
348        texture->setWrap(osg::Texture::WRAP_T, osg::Texture::CLAMP_TO_EDGE);
[9705]349
350
[2809]351        pictureQuad->getOrCreateStateSet()->setTextureAttributeAndModes(0,
[6941]352                                                                        texture,
353                                                                        osg::StateAttribute::ON);
[9705]354
[2809]355        return pictureQuad;
[2693]356    }
[2809]357    else
358    {
[4746]359        osg::Geometry* pictureQuad = osg::createTexturedQuadGeometry(pos,
[2809]360                                           osg::Vec3(width,0.0f,0.0f),
[7477]361                                           xyPlane ? osg::Vec3(0.0f,height,0.0f) : osg::Vec3(0.0f,0.0f,height),
[6947]362                                           0.0f, flip ? 1.0f : 0.0f , 1.0f, flip ? 0.0f : 1.0f);
[9705]363
[4321]364        osg::Texture2D* texture = new osg::Texture2D(image);
[8857]365        texture->setResizeNonPowerOfTwoHint(false);
[6941]366        texture->setFilter(osg::Texture::MIN_FILTER,osg::Texture::LINEAR);
367        texture->setWrap(osg::Texture::WRAP_S, osg::Texture::CLAMP_TO_EDGE);
368        texture->setWrap(osg::Texture::WRAP_T, osg::Texture::CLAMP_TO_EDGE);
[9705]369
370
[2809]371        pictureQuad->getOrCreateStateSet()->setTextureAttributeAndModes(0,
[4321]372                    texture,
[2809]373                    osg::StateAttribute::ON);
[2693]374
[2809]375        return pictureQuad;
376    }
[2693]377}
378
[9849]379#if USE_SDL
380
381class SDLAudioSink : public osg::AudioSink
[9847]382{
383    public:
[10188]384
[9849]385        SDLAudioSink(osg::AudioStream* audioStream):
[9847]386            _playing(false),
387            _audioStream(audioStream) {}
[9849]388
[10188]389        ~SDLAudioSink();
[9849]390
[10188]391        virtual void startPlaying();
[9847]392        virtual bool playing() const { return _playing; }
393
[9849]394
[9847]395        bool                                _playing;
396        osg::observer_ptr<osg::AudioStream> _audioStream;
397};
398
[9849]399#endif
400
[2693]401int main(int argc, char** argv)
402{
403    // use an ArgumentParser object to manage the program arguments.
404    osg::ArgumentParser arguments(&argc,argv);
[9705]405
[2693]406    // set up the usage document, in case we need to print out how to use this program.
407    arguments.getApplicationUsage()->setApplicationName(arguments.getApplicationName());
[4780]408    arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" example demonstrates the use of ImageStream for rendering movies as textures.");
[2693]409    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ...");
410    arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
[5927]411    arguments.getApplicationUsage()->addCommandLineOption("--texture2D","Use Texture2D rather than TextureRectangle.");
412    arguments.getApplicationUsage()->addCommandLineOption("--shader","Use shaders to post process the video.");
[7480]413    arguments.getApplicationUsage()->addCommandLineOption("--interactive","Use camera manipulator to allow movement around movie.");
414    arguments.getApplicationUsage()->addCommandLineOption("--flip","Flip the movie so top becomes bottom.");
[9705]415#if defined(WIN32) || defined(__APPLE__)
[7594]416    arguments.getApplicationUsage()->addCommandLineOption("--devices","Print the Video input capability via QuickTime and exit.");
[9705]417#endif
418
[4321]419    bool useTextureRectangle = true;
420    bool useShader = false;
[2693]421
422    // construct the viewer.
[7475]423    osgViewer::Viewer viewer(arguments);
[9705]424
[6625]425    if (arguments.argc()<=1)
426    {
427        arguments.getApplicationUsage()->write(std::cout,osg::ApplicationUsage::COMMAND_LINE_OPTION);
428        return 1;
429    }
430
[9705]431#if defined(WIN32) || defined(__APPLE__)
[7594]432    // if user requests devices video capability.
433    if (arguments.read("-devices") || arguments.read("--devices"))
434    {
435        // Force load QuickTime plugin, probe video capability, exit
436        osgDB::readImageFile("devices.live");
437        return 1;
438    }
[9705]439#endif
[7594]440
[4321]441    while (arguments.read("--texture2D")) useTextureRectangle=false;
442    while (arguments.read("--shader")) useShader=true;
[2693]443
[8073]444    bool mouseTracking = false;
[9705]445    while (arguments.read("--mouse")) mouseTracking=true;
[8073]446
447
[2693]448    // if user request help write it out to cout.
449    if (arguments.read("-h") || arguments.read("--help"))
450    {
451        arguments.getApplicationUsage()->write(std::cout);
452        return 1;
453    }
454
[7477]455    bool fullscreen = !arguments.read("--interactive");
[7479]456    bool flip = arguments.read("--flip");
[4321]457
[7477]458    osg::ref_ptr<osg::Geode> geode = new osg::Geode;
[4322]459
[7477]460    osg::StateSet* stateset = geode->getOrCreateStateSet();
461    stateset->setMode(GL_LIGHTING,osg::StateAttribute::OFF);
[4322]462
[7477]463    if (useShader)
464    {
465        //useTextureRectangle = false;
[4321]466
[7477]467        static const char *shaderSourceTextureRec = {
468            "uniform vec4 cutoff_color;\n"
469            "uniform samplerRect movie_texture;\n"
470            "void main(void)\n"
471            "{\n"
[8857]472            "    vec4 texture_color = textureRect(movie_texture, gl_TexCoord[0].st); \n"
[7477]473            "    if (all(lessThanEqual(texture_color,cutoff_color))) discard; \n"
474            "    gl_FragColor = texture_color;\n"
475            "}\n"
476        };
[4321]477
[7477]478        static const char *shaderSourceTexture2D = {
479            "uniform vec4 cutoff_color;\n"
480            "uniform sampler2D movie_texture;\n"
481            "void main(void)\n"
482            "{\n"
[8857]483            "    vec4 texture_color = texture2D(movie_texture, gl_TexCoord[0].st); \n"
[7477]484            "    if (all(lessThanEqual(texture_color,cutoff_color))) discard; \n"
485            "    gl_FragColor = texture_color;\n"
486            "}\n"
487        };
[4321]488
[7477]489        osg::Program* program = new osg::Program;
[4321]490
[7477]491        program->addShader(new osg::Shader(osg::Shader::FRAGMENT,
492                                           useTextureRectangle ? shaderSourceTextureRec : shaderSourceTexture2D));
[4321]493
[7477]494        stateset->addUniform(new osg::Uniform("cutoff_color",osg::Vec4(0.1f,0.1f,0.1f,1.0f)));
495        stateset->addUniform(new osg::Uniform("movie_texture",0));
[6625]496
[7477]497        stateset->setAttribute(program);
[6625]498
[7477]499    }
[6625]500
[7477]501    osg::Vec3 pos(0.0f,0.0f,0.0f);
502    osg::Vec3 topleft = pos;
503    osg::Vec3 bottomright = pos;
[9705]504
[7477]505    bool xyPlane = fullscreen;
[9847]506   
[9849]507    bool useAudioSink = false;
508    while(arguments.read("--audio")) { useAudioSink = true; }
[9914]509   
[9928]510#if USE_SDL
[9914]511    unsigned int numAudioStreamsEnabled = 0;
[9928]512#endif
[9705]513
[7477]514    for(int i=1;i<arguments.argc();++i)
515    {
516        if (arguments.isString(i))
[2809]517        {
[7477]518            osg::Image* image = osgDB::readImageFile(arguments[i]);
519            osg::ImageStream* imagestream = dynamic_cast<osg::ImageStream*>(image);
[9847]520            if (imagestream)
521            {
522                osg::ImageStream::AudioStreams& audioStreams = imagestream->getAudioStreams();
[9849]523                if (useAudioSink && !audioStreams.empty())
[9847]524                {
525                    osg::AudioStream* audioStream = audioStreams[0].get();
526                    osg::notify(osg::NOTICE)<<"AudioStream read ["<<audioStream->getName()<<"]"<<std::endl;
[9849]527#if USE_SDL
[9914]528                    if (numAudioStreamsEnabled==0)
529                    {
530                        audioStream->setAudioSink(new SDLAudioSink(audioStream));
531                       
532                        ++numAudioStreamsEnabled;
533                    }
[9849]534#endif
[9847]535                }
[7477]536
[9847]537
538                imagestream->play();
539            }
540
[7477]541            if (image)
[4082]542            {
[9911]543                osg::notify(osg::NOTICE)<<"image->s()"<<image->s()<<" image-t()="<<image->t()<<" aspectRatio="<<image->getPixelAspectRatio()<<std::endl;
[9705]544
[9913]545                float width = image->s() * image->getPixelAspectRatio();
546                float height = image->t();
[9705]547
[9911]548                osg::ref_ptr<osg::Drawable> drawable = myCreateTexturedQuadGeometry(pos, width, height,image, useTextureRectangle, xyPlane, flip);
549               
550                if (image->isImageTranslucent())
551                {
552                    osg::notify(osg::NOTICE)<<"Transparent movie, enabling blending."<<std::endl;
[6624]553
[9911]554                    drawable->getOrCreateStateSet()->setMode(GL_BLEND, osg::StateAttribute::ON);
555                    drawable->getOrCreateStateSet()->setRenderingHint(osg::StateSet::TRANSPARENT_BIN);
556                }
557
558                geode->addDrawable(drawable.get());
559
560                bottomright = pos + osg::Vec3(width,height,0.0f);
561
562                if (xyPlane) pos.y() += height*1.05f;
563                else pos.z() += height*1.05f;
[4082]564            }
[7477]565            else
566            {
567                std::cout<<"Unable to read file "<<arguments[i]<<std::endl;
[9705]568            }
[2809]569        }
570    }
[9705]571
[7477]572    // set the scene to render
573    viewer.setSceneData(geode.get());
[2809]574
[7477]575    if (viewer.getSceneData()==0)
576    {
577        arguments.getApplicationUsage()->write(std::cout);
578        return 1;
579    }
580
[2810]581    // pass the model to the MovieEventHandler so it can pick out ImageStream's to manipulate.
[4956]582    MovieEventHandler* meh = new MovieEventHandler();
[8073]583    meh->setMouseTracking( mouseTracking );
[7615]584    meh->set( viewer.getSceneData() );
585    viewer.addEventHandler( meh );
[2809]586
[7615]587    viewer.addEventHandler( new osgViewer::StatsHandler );
588    viewer.addEventHandler( new osgGA::StateSetManipulator( viewer.getCamera()->getOrCreateStateSet() ) );
589    viewer.addEventHandler( new osgViewer::WindowSizeHandler );
590
591    // add the record camera path handler
592    viewer.addEventHandler(new osgViewer::RecordCameraPathHandler);
593
[7648]594    // report any errors if they have occurred when parsing the program arguments.
[2693]595    if (arguments.errors())
596    {
597        arguments.writeErrorMessages(std::cout);
598        return 1;
599    }
600
[7477]601    if (fullscreen)
602    {
603        viewer.realize();
[9911]604       
605        viewer.getCamera()->setClearColor(osg::Vec4(0.0f,0.0f,0.0f,1.0f));
[6624]606
[9911]607        float screenAspectRatio = 1280.0f/1024.0f;
608
609        osg::GraphicsContext::WindowingSystemInterface* wsi = osg::GraphicsContext::getWindowingSystemInterface();
610        if (wsi)
611        {
612            unsigned int width, height;
613            wsi->getScreenResolution(osg::GraphicsContext::ScreenIdentifier(0), width, height);
614           
615            screenAspectRatio = float(width) / float(height);
616        }
617       
618        float modelAspectRatio = (bottomright.x()-topleft.x())/(bottomright.y()-topleft.y());
619       
[7477]620        viewer.getCamera()->setViewMatrix(osg::Matrix::identity());
[9911]621
622
623        osg::Vec3 center = (bottomright + topleft)*0.5f;
624        osg::Vec3 dx(bottomright.x()-center.x(), 0.0f, 0.0f);
625        osg::Vec3 dy(0.0f, topleft.y()-center.y(), 0.0f);
626
627        float ratio = modelAspectRatio/screenAspectRatio;
628
629        if (ratio>1.0f)
630        {
631            // use model width as the control on model size.
632            bottomright = center + dx - dy * ratio;
633            topleft = center - dx + dy * ratio;
634        }
635        else
636        {
637            // use model height as the control on model size.
638            bottomright = center + dx / ratio - dy;
639            topleft = center - dx / ratio + dy;
640        }
641
[7477]642        viewer.getCamera()->setProjectionMatrixAsOrtho2D(topleft.x(),bottomright.x(),topleft.y(),bottomright.y());
[2693]643
[7477]644        while(!viewer.done())
645        {
646            viewer.frame();
647        }
648        return 0;
649    }
650    else
651    {
652        // create the windows and run the threads.
653        return viewer.run();
654    }
[2693]655}
[9705]656
[10188]657#if USE_SDL
658
659#include "SDL.h"
660
[10193]661static void soundReadCallback(void * user_data, uint8_t * data, int datalen)
662{
663    SDLAudioSink * sink = reinterpret_cast<SDLAudioSink*>(user_data);
664    osg::ref_ptr<osg::AudioStream> as = sink->_audioStream.get();
665    if (as.valid())
666    {
667        as->consumeAudioBuffer(data, datalen);
668    }
669}
670
[10188]671SDLAudioSink::~SDLAudioSink()
672{
673    if (_playing)
674    {
675
676        SDL_PauseAudio(1);
677        SDL_CloseAudio();
678
679        osg::notify(osg::NOTICE)<<"~SDLAudioSink() destructor, but still playing"<<std::endl;
680    }
681}
682
683void SDLAudioSink::startPlaying()
684{
685    _playing = true;
686    osg::notify(osg::NOTICE)<<"SDLAudioSink()::startPlaying()"<<std::endl;
687
688    osg::notify(osg::NOTICE)<<"  audioFrequency()="<<_audioStream->audioFrequency()<<std::endl;
689    osg::notify(osg::NOTICE)<<"  audioNbChannels()="<<_audioStream->audioNbChannels()<<std::endl;
690    osg::notify(osg::NOTICE)<<"  audioSampleFormat()="<<_audioStream->audioSampleFormat()<<std::endl;
691
692    SDL_AudioSpec specs = { 0 };
693    SDL_AudioSpec wanted_specs = { 0 };
694
695    wanted_specs.freq = _audioStream->audioFrequency();
696    wanted_specs.format = AUDIO_S16SYS;
697    wanted_specs.channels = _audioStream->audioNbChannels();
698    wanted_specs.silence = 0;
699    wanted_specs.samples = 1024;
700    wanted_specs.callback = soundReadCallback;
701    wanted_specs.userdata = this;
702
703    if (SDL_OpenAudio(&wanted_specs, &specs) < 0)
704        throw "SDL_OpenAudio() failed (" + std::string(SDL_GetError()) + ")";
705
706    SDL_PauseAudio(0);
707
708}
709
710
711#endif
Note: See TracBrowser for help on using the browser.