root/OpenSceneGraph/trunk/examples/osgQtWidgets/osgQtWidgets.cpp @ 13863

Revision 13482, 28.6 kB (checked in by robert, 10 days ago)

Added shaders to support experimental shader based displacement mapping technique osgTerrain::ShaderTerrain?.

  • Property svn:eol-style set to native
Line 
1/* OpenSceneGraph example, osgcompositeviewer.
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 <iostream>
20
21#include <osg/Notify>
22#include <osg/io_utils>
23
24#include <osg/ArgumentParser>
25#include <osg/MatrixTransform>
26#include <osg/AutoTransform>
27#include <osg/Camera>
28#include <osg/TexMat>
29#include <osg/TextureRectangle>
30#include <osgDB/ReadFile>
31#include <osgDB/WriteFile>
32#include <osgGA/TrackballManipulator>
33#include <osgGA/StateSetManipulator>
34#include <osgViewer/Viewer>
35#include <osgViewer/ViewerEventHandlers>
36#include <osgWidget/Browser>
37
38
39//#include <QWebSettings>
40#include <QGraphicsScene>
41#include <QGraphicsView>
42#include <QApplication>
43#include <QPainter>
44#include <QtEvents>
45#include <QDialog>
46#include <QVBoxLayout>
47#include <QMainWindow>
48#include <QtOpenGL>
49
50#include <osgQt/QGraphicsViewAdapter>
51#include <osgQt/QWebViewImage>
52#include <osgQt/QWidgetImage>
53
54
55// Thread that runs the viewer's frame loop as we can't run Qt in the background...
56class ViewerFrameThread : public OpenThreads::Thread
57{
58    public:
59
60        ViewerFrameThread(osgViewer::ViewerBase* viewerBase, bool doQApplicationExit):
61            _viewerBase(viewerBase),
62            _doQApplicationExit(doQApplicationExit) {}
63
64        ~ViewerFrameThread()
65        {
66            cancel();
67            while(isRunning())
68            {
69                OpenThreads::Thread::YieldCurrentThread();
70            }
71        }
72
73        int cancel()
74        {
75            _viewerBase->setDone(true);
76            return 0;
77        }
78
79        void run()
80        {
81            int result = _viewerBase->run();
82
83            if (_doQApplicationExit) QApplication::exit(result);
84        }
85
86        osg::ref_ptr<osgViewer::ViewerBase> _viewerBase;
87        bool _doQApplicationExit;
88};
89
90
91class MyPushButton : public QPushButton
92{
93public:
94    MyPushButton(const QString& text) : QPushButton(text) {}
95
96protected:
97    virtual void mousePressEvent(QMouseEvent* e)
98    {
99        bool ok = false;
100#if QT_VERSION >= 0x040500
101        int val = QInputDialog::getInt(this, "Get integer", "Please enter an integer between 0 and pi", 0, 0, 3, 1, &ok);
102#else
103        int val = QInputDialog::getInteger(this, "Get integer", "Please enter an integer between 0 and pi", 0, 0, 3, 1, &ok);
104#endif
105        std::cout << "Ok was " << (ok ? "" : "not") << " pressed, val is " << val << std::endl;
106    }
107};
108
109
110//We would need to document the following somewhere in order to guide people on
111//what they need to use...
112//
113//----------------------------------------------
114//There are two angles to consider.
115//
116//1. If someone wants a widget in their Qt app to be an OSG-rendered scene, they
117//need GraphicsWindowQt (in the osgViewerQtContext example) or QOSGWidget (in the
118//osgViewerQt example). These two allow both OSG and Qt to manage their threads
119//in a way which is optimal to them. We've used QOSGWidget in the past and had
120//trouble when Qt tried to overlay other widgets over the QOSGWidget (since OSG
121//did its rendering independently of Qt, it would overwrite what Qt had drawn). I
122//haven't tried GraphicsWindowQt yet, but I expect since it uses QGLWidget, it
123//will result in Qt knowing when OSG has drawn and be able to do overlays at the
124//right time. Eventually GraphicsWindowQt can be brought into osgViewer I imagine...
125//
126//2. If someone wants to bring Qt widgets inside their OSG scene (to do HUDs or
127//an interface on a computer screen which is inside the 3D scene, or even
128//floating Qt widgets, for example). That's where QGraphicsViewAdapter +
129//QWidgetImage will be useful.
130//----------------------------------------------
131
132
133int main(int argc, char **argv)
134{
135    // Qt requires that we construct the global QApplication before creating any widgets.
136    QApplication app(argc, argv);
137
138    // use an ArgumentParser object to manage the program arguments.
139    osg::ArgumentParser arguments(&argc,argv);
140
141    // true = run osgViewer in a separate thread than Qt
142    // false = interleave osgViewer and Qt in the main thread
143    bool useFrameLoopThread = false;
144    if (arguments.read("--no-frame-thread")) useFrameLoopThread = false;
145    if (arguments.read("--frame-thread")) useFrameLoopThread = true;
146
147    // true = use QWidgetImage
148    // false = use QWebViewImage
149    bool useWidgetImage = false;
150    if (arguments.read("--useWidgetImage")) useWidgetImage = true;
151
152    // true = use QWebView in a QWidgetImage to compare to QWebViewImage
153    // false = make an interesting widget
154    bool useBrowser = false;
155    if (arguments.read("--useBrowser")) useBrowser = true;
156
157    // true = use a QLabel for text
158    // false = use a QTextEdit for text
159    // (only applies if useWidgetImage == true and useBrowser == false)
160    bool useLabel = false;
161    if (arguments.read("--useLabel")) useLabel = true;
162
163    // true = make a Qt window with the same content to compare to
164    // QWebViewImage/QWidgetImage
165    // false = use QWebViewImage/QWidgetImage (depending on useWidgetImage)
166    bool sanityCheck = false;
167    if (arguments.read("--sanityCheck")) sanityCheck = true;
168
169    // Add n floating windows inside the QGraphicsScene.
170    int numFloatingWindows = 0;
171    while (arguments.read("--numFloatingWindows", numFloatingWindows));
172
173    // true = Qt widgets will be displayed on a quad inside the 3D scene
174    // false = Qt widgets will be an overlay over the scene (like a HUD)
175    bool inScene = true;
176    if (arguments.read("--fullscreen")) { inScene = false; }
177
178
179    osg::ref_ptr<osg::Group> root = new osg::Group;
180
181    if (!useWidgetImage)
182    {
183        //-------------------------------------------------------------------
184        // QWebViewImage test
185        //-------------------------------------------------------------------
186        // Note: When the last few issues with QWidgetImage are fixed,
187        // QWebViewImage and this if() {} section can be removed since
188        // QWidgetImage can display a QWebView just like QWebViewImage. Use
189        // --useWidgetImage --useBrowser to see that in action.
190
191        if (!sanityCheck)
192        {
193            osg::ref_ptr<osgQt::QWebViewImage> image = new osgQt::QWebViewImage;
194
195            if (arguments.argc()>1) image->navigateTo((arguments[1]));
196            else image->navigateTo("http://www.youtube.com/");
197
198            osgWidget::GeometryHints hints(osg::Vec3(0.0f,0.0f,0.0f),
199                                           osg::Vec3(1.0f,0.0f,0.0f),
200                                           osg::Vec3(0.0f,0.0f,1.0f),
201                                           osg::Vec4(1.0f,1.0f,1.0f,1.0f),
202                                           osgWidget::GeometryHints::RESIZE_HEIGHT_TO_MAINTAINCE_ASPECT_RATIO);
203
204            osg::ref_ptr<osgWidget::Browser> browser = new osgWidget::Browser;
205            browser->assign(image.get(), hints);
206
207            root->addChild(browser.get());
208        }
209        else
210        {
211            // Sanity check, do the same thing as QGraphicsViewAdapter but in
212            // a separate Qt window.
213            QWebPage* webPage = new QWebPage;
214            webPage->settings()->setAttribute(QWebSettings::JavascriptEnabled, true);
215            webPage->settings()->setAttribute(QWebSettings::PluginsEnabled, true);
216
217            QWebView* webView = new QWebView;
218            webView->setPage(webPage);
219
220            if (arguments.argc()>1) webView->load(QUrl(arguments[1]));
221            else webView->load(QUrl("http://www.youtube.com/"));
222
223            QGraphicsScene* graphicsScene = new QGraphicsScene;
224            graphicsScene->addWidget(webView);
225
226            QGraphicsView* graphicsView = new QGraphicsView;
227            graphicsView->setScene(graphicsScene);
228
229            QMainWindow* mainWindow = new QMainWindow;
230            //mainWindow->setLayout(new QVBoxLayout);
231            mainWindow->setCentralWidget(graphicsView);
232            mainWindow->setGeometry(50, 50, 1024, 768);
233            mainWindow->show();
234            mainWindow->raise();
235        }
236    }
237    else
238    {
239        //-------------------------------------------------------------------
240        // QWidgetImage test
241        //-------------------------------------------------------------------
242        // QWidgetImage still has some issues, some examples are:
243        //
244        // 1. Editing in the QTextEdit doesn't work. Also when started with
245        //    --useBrowser, editing in the search field on YouTube doesn't
246        //    work. But that same search field when using QWebViewImage
247        //    works... And editing in the text field in the pop-up getInteger
248        //    dialog works too. All these cases use QGraphicsViewAdapter
249        //    under the hood, so why do some work and others don't?
250        //
251        //    a) osgQtBrowser --useWidgetImage [--fullscreen] (optional)
252        //    b) Try to click in the QTextEdit and type, or to select text
253        //       and drag-and-drop it somewhere else in the QTextEdit. These
254        //       don't work.
255        //    c) osgQtBrowser --useWidgetImage --sanityCheck
256        //    d) Try the operations in b), they all work.
257        //    e) osgQtBrowser --useWidgetImage --useBrowser [--fullscreen]
258        //    f) Try to click in the search field and type, it doesn't work.
259        //    g) osgQtBrowser
260        //    h) Try the operation in f), it works.
261        //
262        // 2. Operations on floating windows (--numFloatingWindows 1 or more).
263        //    Moving by dragging the titlebar, clicking the close button,
264        //    resizing them, none of these work. I wonder if it's because the
265        //    OS manages those functions (they're functions of the window
266        //    decorations) so we need to do something special for that? But
267        //    in --sanityCheck mode they work.
268        //
269        //    a) osgQtBrowser --useWidgetImage --numFloatingWindows 1 [--fullscreen]
270        //    b) Try to drag the floating window, click the close button, or
271        //       drag its sides to resize it. None of these work.
272        //    c) osgQtBrowser --useWidgetImage --numFloatingWindows 1 --sanityCheck
273        //    d) Try the operations in b), all they work.
274        //    e) osgQtBrowser --useWidgetImage [--fullscreen]
275        //    f) Click the button so that the getInteger() dialog is
276        //       displayed, then try to move that dialog or close it with the
277        //       close button, these don't work.
278        //    g) osgQtBrowser --useWidgetImage --sanityCheck
279        //    h) Try the operation in f), it works.
280        //
281        // 3. (Minor) The QGraphicsView's scrollbars don't appear when
282        //    using QWidgetImage or QWebViewImage. QGraphicsView is a
283        //    QAbstractScrollArea and it should display scrollbars as soon as
284        //    the scene is too large to fit the view.
285        //
286        //    a) osgQtBrowser --useWidgetImage --fullscreen
287        //    b) Resize the OSG window so it's smaller than the QTextEdit.
288        //       Scrollbars should appear but don't.
289        //    c) osgQtBrowser --useWidgetImage --sanityCheck
290        //    d) Try the operation in b), scrollbars appear. Even if you have
291        //       floating windows (by clicking the button or by adding
292        //       --numFloatingWindows 1) and move them outside the view,
293        //       scrollbars appear too. You can't test that case in OSG for
294        //       now because of problem 2 above, but that's pretty cool.
295        //
296        // 4. (Minor) In sanity check mode, the widget added to the
297        //    QGraphicsView is centered. With QGraphicsViewAdapter, it is not.
298        //
299        //    a) osgQtBrowser --useWidgetImage [--fullscreen]
300        //    b) The QTextEdit and button are not in the center of the image
301        //       generated by the QGraphicsViewAdapter.
302        //    c) osgQtBrowser --useWidgetImage --sanityCheck
303        //    d) The QTextEdit and button are in the center of the
304        //       QGraphicsView.
305
306
307        QWidget* widget = 0;
308        if (useBrowser)
309        {
310            QWebPage* webPage = new QWebPage;
311            webPage->settings()->setAttribute(QWebSettings::JavascriptEnabled, true);
312            webPage->settings()->setAttribute(QWebSettings::PluginsEnabled, true);
313
314            QWebView* webView = new QWebView;
315            webView->setPage(webPage);
316
317            if (arguments.argc()>1) webView->load(QUrl(arguments[1]));
318            else webView->load(QUrl("http://www.youtube.com/"));
319
320            widget = webView;
321        }
322        else
323        {
324            widget = new QWidget;
325            widget->setLayout(new QVBoxLayout);
326
327            QString text("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque velit turpis, euismod ac ultrices et, molestie non nisi. Nullam egestas dignissim enim, quis placerat nulla suscipit sed. Donec molestie elementum risus sit amet sodales. Nunc consectetur congue neque, at viverra massa pharetra fringilla. Integer vitae mi sem. Donec dapibus semper elit nec sollicitudin. Vivamus egestas ultricies felis, in mollis mi facilisis quis. Nam suscipit bibendum eros sed cursus. Suspendisse mollis suscipit hendrerit. Etiam magna eros, convallis non congue vel, faucibus ac augue. Integer ante ante, porta in ornare ullamcorper, congue nec nibh. Etiam congue enim vitae enim sollicitudin fringilla. Mauris mattis, urna in fringilla dapibus, ipsum sem feugiat purus, ac hendrerit felis arcu sed sapien. Integer id velit quam, sit amet dignissim tortor. Sed mi tortor, placerat ac luctus id, tincidunt et urna. Nulla sed nunc ante.Sed ut sodales enim. Ut sollicitudin ultricies magna, vel ultricies ante venenatis id. Cras luctus mi in lectus rhoncus malesuada. Sed ac sollicitudin nisi. Nunc venenatis congue quam, et suscipit diam consectetur id. Donec vel enim ac enim elementum bibendum ut quis augue. Nulla posuere suscipit dolor, id convallis tortor congue eu. Vivamus sagittis consectetur dictum. Duis a ante quis dui varius fermentum. In hac habitasse platea dictumst. Nam dapibus dolor eu felis eleifend in scelerisque dolor ultrices. Donec arcu lectus, fringilla ut interdum non, tristique id dolor. Morbi sagittis sagittis volutpat. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Duis venenatis ultrices euismod.Nam sit amet convallis libero. Integer lectus urna, eleifend et sollicitudin non, porttitor vel erat. Vestibulum pulvinar egestas leo, a porttitor turpis ullamcorper et. Vestibulum in ornare turpis. Ut nec libero a sem mattis iaculis quis id purus. Praesent ante neque, dictum vitae pretium vel, iaculis luctus dui. Etiam luctus tellus vel nunc suscipit a ullamcorper nisl semper. Nunc dapibus, eros in sodales dignissim, orci lectus egestas felis, sit amet vehicula tortor dolor eu quam. Vivamus pellentesque convallis quam aliquet pellentesque. Phasellus facilisis arcu ac orci fringilla aliquet. Donec sed euismod augue. Duis eget orci sit amet neque tempor fringilla. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; In hac habitasse platea dictumst. Duis sollicitudin, lacus ac pellentesque lacinia, lacus magna pulvinar purus, pulvinar porttitor est nibh quis augue.Duis eleifend, massa sit amet mattis fringilla, elit turpis venenatis libero, sed convallis turpis diam sit amet ligula. Morbi non dictum turpis. Integer porttitor condimentum elit, sit amet sagittis nibh ultrices sit amet. Mauris ac arcu augue, id aliquet mauris. Donec ultricies urna id enim accumsan at pharetra dui adipiscing. Nunc luctus rutrum molestie. Curabitur libero ipsum, viverra at pulvinar ut, porttitor et neque. Aliquam sit amet dolor et purus sagittis adipiscing. Nam sit amet hendrerit sem. Etiam varius, ligula non ultricies dignissim, sapien dui commodo urna, eu vehicula enim nunc molestie augue. Fusce euismod, erat vitae pharetra tempor, quam eros tincidunt lorem, ut iaculis ligula erat vitae nibh. Aenean eu ultricies dolor. Curabitur suscipit viverra bibendum.Sed egestas adipiscing mi in egestas. Proin in neque in nibh blandit consequat nec quis tortor. Vestibulum sed interdum justo. Sed volutpat velit vitae elit pulvinar aliquam egestas elit rutrum. Proin lorem nibh, bibendum vitae sollicitudin condimentum, pulvinar ut turpis. Maecenas iaculis, mauris in consequat ultrices, ante erat blandit mi, vel fermentum lorem turpis eget sem. Integer ultrices tristique erat sit amet volutpat. In sit amet diam et nunc congue pellentesque at in dolor. Mauris eget orci orci. Integer posuere augue ornare tortor tempus elementum. Quisque iaculis, nunc ac cursus fringilla, magna elit cursus eros, id feugiat diam eros et tellus. Etiam consectetur ultrices erat quis rhoncus. Mauris eu lacinia neque. Curabitur suscipit feugiat tellus in dictum. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Sed aliquam tempus ante a tempor. Praesent viverra erat quis sapien pretium rutrum. Praesent dictum scelerisque venenatis.Proin bibendum lectus eget nisl lacinia porta. Morbi eu erat in sapien malesuada vulputate. Cras non elit quam. Ut dictum urna quis nisl feugiat ac sollicitudin libero luctus. Donec leo mauris, varius at luctus eget, placerat quis arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Etiam tristique, mauris ut lacinia elementum, mauris erat consequat massa, ac gravida nisi tellus vitae purus. Curabitur consectetur ultricies commodo. Cras pulvinar orci nec enim adipiscing tristique. Ut ornare orci id est fringilla sit amet blandit libero pellentesque. Vestibulum tincidunt sapien ut enim venenatis vestibulum ultricies ipsum tristique. Mauris tempus eleifend varius. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse vitae dui ac quam gravida semper. In ac enim ac ligula rutrum porttitor.Integer dictum sagittis leo, at convallis sapien facilisis eget. Etiam cursus bibendum tortor, faucibus aliquam lectus ullamcorper sed. Nulla pulvinar posuere quam, ut sagittis ligula tincidunt ut. Nulla convallis velit ut enim condimentum pulvinar. Quisque gravida accumsan scelerisque. Proin pellentesque nisi cursus tortor aliquet dapibus. Duis vel eros orci. Sed eget purus ligula. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec ullamcorper porta congue. Nunc id velit ut neque malesuada consequat in eu nisi. Nulla facilisi. Quisque pellentesque magna vitae nisl euismod ac accumsan tellus feugiat.Nulla facilisi. Integer quis orci lectus, non aliquam nisi. Vivamus varius porta est, ac porttitor orci blandit mattis. Sed dapibus facilisis dapibus. Duis tincidunt leo ac tortor faucibus hendrerit. Morbi sit amet sapien risus, vel luctus enim. Aliquam sagittis nunc id purus aliquam lobortis. Duis posuere viverra dui, sit amet convallis sem vulputate at. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque pellentesque, lectus id imperdiet commodo, diam diam faucibus lectus, sit amet vestibulum tortor lacus viverra eros.Maecenas nec augue lectus. Duis nec arcu eget lorem tempus sollicitudin suscipit vitae arcu. Nullam vitae mauris lectus. Vivamus id risus neque, dignissim vehicula diam. Cras rhoncus velit sed velit iaculis ac dignissim turpis luctus. Suspendisse potenti. Sed vitae ligula a ligula ornare rutrum sit amet ut quam. Duis tincidunt, nibh vitae iaculis adipiscing, dolor orci cursus arcu, vel congue tortor quam eget arcu. Suspendisse tellus felis, blandit ac accumsan vitae, fringilla id lorem. Duis tempor lorem mollis est congue ut imperdiet velit laoreet. Nullam interdum cursus mollis. Pellentesque non mauris accumsan elit laoreet viverra ut at risus. Proin rutrum sollicitudin sem, vitae ultricies augue sagittis vel. Cras quis vehicula neque. Aliquam erat volutpat. Aliquam erat volutpat. Praesent non est erat, accumsan rutrum lacus. Pellentesque tristique molestie aliquet. Cras ullamcorper facilisis faucibus. In non lorem quis velit lobortis pulvinar.Phasellus non sem ipsum. Praesent ut libero quis turpis viverra semper. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. In hac habitasse platea dictumst. Donec at velit tellus. Fusce commodo pharetra tincidunt. Proin lacus enim, fringilla a fermentum ut, vestibulum ut nibh. Duis commodo dolor vel felis vehicula at egestas neque bibendum. Phasellus malesuada dictum ante in aliquam. Curabitur interdum semper urna, nec placerat justo gravida in. Praesent quis mauris massa. Pellentesque porttitor lacinia tincidunt. Phasellus egestas viverra elit vel blandit. Sed dapibus nisi et lectus pharetra dignissim. Mauris hendrerit lectus nec purus dapibus condimentum. Sed ac eros nulla. Aenean semper sapien a nibh aliquam lobortis. Aliquam elementum euismod sapien, in dapibus leo dictum et. Pellentesque augue neque, ultricies non viverra eu, tincidunt ac arcu. Morbi ut porttitor lectus.");
328
329            if (useLabel)
330            {
331                QLabel* label = new QLabel(text);
332                label->setWordWrap(true);
333                label->setTextInteractionFlags(Qt::TextEditorInteraction);
334
335                QPalette palette = label->palette();
336                palette.setColor(QPalette::Highlight, Qt::darkBlue);
337                palette.setColor(QPalette::HighlightedText, Qt::white);
338                label->setPalette(palette);
339
340                QScrollArea* scrollArea = new QScrollArea;
341                scrollArea->setWidget(label);
342
343                widget->layout()->addWidget(scrollArea);
344            }
345            else
346            {
347                QTextEdit* textEdit = new QTextEdit(text);
348                textEdit->setReadOnly(false);
349                textEdit->setTextInteractionFlags(Qt::TextEditable);
350
351                QPalette palette = textEdit->palette();
352                palette.setColor(QPalette::Highlight, Qt::darkBlue);
353                palette.setColor(QPalette::HighlightedText, Qt::white);
354                textEdit->setPalette(palette);
355
356                widget->layout()->addWidget(textEdit);
357            }
358
359            QPushButton* button = new MyPushButton("Button");
360            widget->layout()->addWidget(button);
361
362            widget->setGeometry(0, 0, 800, 600);
363        }
364
365        QGraphicsScene* graphicsScene = 0;
366
367        if (!sanityCheck)
368        {
369            osg::ref_ptr<osgQt::QWidgetImage> widgetImage = new osgQt::QWidgetImage(widget);
370#if (QT_VERSION >= QT_VERSION_CHECK(4, 5, 0))
371            widgetImage->getQWidget()->setAttribute(Qt::WA_TranslucentBackground);
372#endif
373            widgetImage->getQGraphicsViewAdapter()->setBackgroundColor(QColor(0, 0, 0, 0));
374            //widgetImage->getQGraphicsViewAdapter()->resize(800, 600);
375            graphicsScene = widgetImage->getQGraphicsViewAdapter()->getQGraphicsScene();
376
377            osg::Camera* camera = 0;        // Will stay NULL in the inScene case.
378            osg::Geometry* quad = osg::createTexturedQuadGeometry(osg::Vec3(0,0,0), osg::Vec3(1,0,0), osg::Vec3(0,1,0), 1, 1);
379            osg::Geode* geode = new osg::Geode;
380            geode->addDrawable(quad);
381
382            osg::MatrixTransform* mt = new osg::MatrixTransform;
383
384            osg::Texture2D* texture = new osg::Texture2D(widgetImage.get());
385            texture->setResizeNonPowerOfTwoHint(false);
386            texture->setFilter(osg::Texture::MIN_FILTER,osg::Texture::LINEAR);
387            texture->setWrap(osg::Texture::WRAP_S, osg::Texture::CLAMP_TO_EDGE);
388            texture->setWrap(osg::Texture::WRAP_T, osg::Texture::CLAMP_TO_EDGE);
389            mt->getOrCreateStateSet()->setTextureAttributeAndModes(0, texture, osg::StateAttribute::ON);
390
391            osgViewer::InteractiveImageHandler* handler;
392            if (inScene)
393            {
394                mt->setMatrix(osg::Matrix::rotate(osg::Vec3(0,1,0), osg::Vec3(0,0,1)));
395                mt->addChild(geode);
396
397                handler = new osgViewer::InteractiveImageHandler(widgetImage.get());
398            }
399            else    // fullscreen
400            {
401                // The HUD camera's viewport needs to follow the size of the
402                // window. MyInteractiveImageHandler will make sure of this.
403                // As for the quad and the camera's projection, setting the
404                // projection resize policy to FIXED takes care of them, so
405                // they can stay the same: (0,1,0,1) with a quad that fits.
406
407                // Set the HUD camera's projection and viewport to match the screen.
408                camera = new osg::Camera;
409                camera->setProjectionResizePolicy(osg::Camera::FIXED);
410                camera->setProjectionMatrix(osg::Matrix::ortho2D(0,1,0,1));
411                camera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
412                camera->setViewMatrix(osg::Matrix::identity());
413                camera->setClearMask(GL_DEPTH_BUFFER_BIT);
414                camera->setRenderOrder(osg::Camera::POST_RENDER);
415                camera->addChild(geode);
416                camera->setViewport(0, 0, 1024, 768);
417
418                mt->addChild(camera);
419
420                handler = new osgViewer::InteractiveImageHandler(widgetImage.get(), texture, camera);
421            }
422
423            mt->getOrCreateStateSet()->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
424            mt->getOrCreateStateSet()->setMode(GL_BLEND, osg::StateAttribute::ON);
425            mt->getOrCreateStateSet()->setRenderingHint(osg::StateSet::TRANSPARENT_BIN);
426            mt->getOrCreateStateSet()->setAttribute(new osg::Program);
427
428            osg::Group* overlay = new osg::Group;
429            overlay->addChild(mt);
430
431            root->addChild(overlay);
432           
433            quad->setEventCallback(handler);
434            quad->setCullCallback(handler);
435        }
436        else
437        {
438            // Sanity check, do the same thing as QWidgetImage and
439            // QGraphicsViewAdapter but in a separate Qt window.
440
441            graphicsScene = new QGraphicsScene;
442            graphicsScene->addWidget(widget);
443
444            QGraphicsView* graphicsView = new QGraphicsView;
445            graphicsView->setScene(graphicsScene);
446
447            QMainWindow* mainWindow = new QMainWindow;
448            mainWindow->setCentralWidget(graphicsView);
449            mainWindow->setGeometry(50, 50, 1024, 768);
450            mainWindow->show();
451            mainWindow->raise();
452        }
453
454        // Add numFloatingWindows windows to the graphicsScene.
455        for (unsigned int i = 0; i < (unsigned int)numFloatingWindows; ++i)
456        {
457            QWidget* window = new QWidget(0, Qt::Window);
458            window->setWindowTitle(QString("Window %1").arg(i));
459            window->setLayout(new QVBoxLayout);
460            window->layout()->addWidget(new QLabel(QString("This window %1").arg(i)));
461            window->layout()->addWidget(new MyPushButton(QString("Button in window %1").arg(i)));
462            window->setGeometry(100, 100, 300, 300);
463
464            QGraphicsProxyWidget *proxy = new QGraphicsProxyWidget(0, Qt::Window);
465            proxy->setWidget(window);
466            proxy->setFlag(QGraphicsItem::ItemIsMovable, true);
467
468            graphicsScene->addItem(proxy);
469        }
470
471    }
472
473    root->addChild(osgDB::readNodeFile("cow.osg.(15,0,5).trans.(0.1,0.1,0.1).scale"));
474
475    osg::ref_ptr<osgViewer::Viewer> viewer = new osgViewer::Viewer(arguments);
476    viewer->setSceneData(root.get());
477    viewer->setCameraManipulator(new osgGA::TrackballManipulator());
478    viewer->addEventHandler(new osgGA::StateSetManipulator(root->getOrCreateStateSet()));
479    viewer->addEventHandler(new osgViewer::StatsHandler);
480    viewer->addEventHandler(new osgViewer::WindowSizeHandler);
481
482    viewer->setUpViewInWindow(50, 50, 1024, 768);
483    viewer->getEventQueue()->windowResize(0, 0, 1024, 768);
484
485    if (useFrameLoopThread)
486    {
487        // create a thread to run the viewer's frame loop
488        ViewerFrameThread viewerThread(viewer.get(), true);
489        viewerThread.startThread();
490
491        // now start the standard Qt event loop, then exists when the viewerThead sends the QApplication::exit() signal.
492        return QApplication::exec();
493
494    }
495    else
496    {
497        // run the frame loop, interleaving Qt and the main OSG frame loop
498        while(!viewer->done())
499        {
500            // process Qt events - this handles both events and paints the browser image
501            QCoreApplication::processEvents(QEventLoop::AllEvents, 100);
502
503            viewer->frame();
504        }
505
506        return 0;
507    }
508}
Note: See TracBrowser for help on using the browser.