-
Notifications
You must be signed in to change notification settings - Fork 61
/
Copy pathOSGWidget.cpp
496 lines (395 loc) · 13.7 KB
/
OSGWidget.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
#include "OSGWidget.h"
#include "PickHandler.h"
#include <osg/Camera>
#include <osg/DisplaySettings>
#include <osg/Geode>
#include <osg/Material>
#include <osg/Shape>
#include <osg/ShapeDrawable>
#include <osg/StateSet>
#include <osgDB/WriteFile>
#include <osgGA/EventQueue>
#include <osgGA/TrackballManipulator>
#include <osgUtil/IntersectionVisitor>
#include <osgUtil/PolytopeIntersector>
#include <osgViewer/View>
#include <osgViewer/ViewerEventHandlers>
#include <cassert>
#include <stdexcept>
#include <vector>
#include <QDebug>
#include <QKeyEvent>
#include <QPainter>
#include <QWheelEvent>
namespace
{
#ifdef WITH_SELECTION_PROCESSING
QRect makeRectangle( const QPoint& first, const QPoint& second )
{
// Relative to the first point, the second point may be in either one of the
// four quadrants of an Euclidean coordinate system.
//
// We enumerate them in counter-clockwise order, starting from the lower-right
// quadrant that corresponds to the default case:
//
// |
// (3) | (4)
// |
// -------|-------
// |
// (2) | (1)
// |
if( second.x() >= first.x() && second.y() >= first.y() )
return QRect( first, second );
else if( second.x() < first.x() && second.y() >= first.y() )
return QRect( QPoint( second.x(), first.y() ), QPoint( first.x(), second.y() ) );
else if( second.x() < first.x() && second.y() < first.y() )
return QRect( second, first );
else if( second.x() >= first.x() && second.y() < first.y() )
return QRect( QPoint( first.x(), second.y() ), QPoint( second.x(), first.y() ) );
// Should never reach that point...
return QRect();
}
#endif
}
namespace osgWidget
{
void Viewer::setupThreading()
{
if( _threadingModel == SingleThreaded )
{
if(_threadsRunning)
stopThreading();
}
else
{
if(!_threadsRunning)
startThreading();
}
}
}
OSGWidget::OSGWidget( QWidget* parent,
Qt::WindowFlags f )
: QOpenGLWidget( parent,
f )
, graphicsWindow_( new osgViewer::GraphicsWindowEmbedded( this->x(),
this->y(),
this->width(),
this->height() ) )
, viewer_( new osgWidget::Viewer )
, selectionActive_( false )
, selectionFinished_( true )
{
osg::Sphere* sphere = new osg::Sphere( osg::Vec3( 0.f, 0.f, 0.f ), 0.25f );
osg::ShapeDrawable* sd = new osg::ShapeDrawable( sphere );
sd->setColor( osg::Vec4( 1.f, 0.f, 0.f, 1.f ) );
sd->setName( "A nice sphere" );
osg::Geode* geode = new osg::Geode;
geode->addDrawable( sd );
// Set material for basic lighting and enable depth tests. Else, the sphere
// will suffer from rendering errors.
{
osg::StateSet* stateSet = geode->getOrCreateStateSet();
osg::Material* material = new osg::Material;
material->setColorMode( osg::Material::AMBIENT_AND_DIFFUSE );
stateSet->setAttributeAndModes( material, osg::StateAttribute::ON );
stateSet->setMode( GL_DEPTH_TEST, osg::StateAttribute::ON );
}
float aspectRatio = static_cast<float>( this->width() / 2 ) / static_cast<float>( this->height() );
auto pixelRatio = this->devicePixelRatio();
osg::Camera* camera = new osg::Camera;
camera->setViewport( 0, 0, this->width() / 2 * pixelRatio, this->height() * pixelRatio );
camera->setClearColor( osg::Vec4( 0.f, 0.f, 1.f, 1.f ) );
camera->setProjectionMatrixAsPerspective( 30.f, aspectRatio, 1.f, 1000.f );
camera->setGraphicsContext( graphicsWindow_ );
osgViewer::View* view = new osgViewer::View;
view->setCamera( camera );
view->setSceneData( geode );
view->addEventHandler( new osgViewer::StatsHandler );
#ifdef WITH_PICK_HANDLER
view->addEventHandler( new PickHandler( this->devicePixelRatio() ) );
#endif
osgGA::TrackballManipulator* manipulator = new osgGA::TrackballManipulator;
manipulator->setAllowThrow( false );
view->setCameraManipulator( manipulator );
osg::Camera* sideCamera = new osg::Camera;
sideCamera->setViewport( this->width() /2 * pixelRatio, 0,
this->width() /2 * pixelRatio, this->height() * pixelRatio );
sideCamera->setClearColor( osg::Vec4( 0.f, 0.f, 1.f, 1.f ) );
sideCamera->setProjectionMatrixAsPerspective( 30.f, aspectRatio, 1.f, 1000.f );
sideCamera->setGraphicsContext( graphicsWindow_ );
osgViewer::View* sideView = new osgViewer::View;
sideView->setCamera( sideCamera );
sideView->setSceneData( geode );
sideView->addEventHandler( new osgViewer::StatsHandler );
sideView->setCameraManipulator( new osgGA::TrackballManipulator );
viewer_->addView( view );
viewer_->addView( sideView );
viewer_->setThreadingModel( osgViewer::CompositeViewer::SingleThreaded );
viewer_->realize();
// This ensures that the widget will receive keyboard events. This focus
// policy is not set by default. The default, Qt::NoFocus, will result in
// keyboard events that are ignored.
this->setFocusPolicy( Qt::StrongFocus );
this->setMinimumSize( 100, 100 );
// Ensures that the widget receives mouse move events even though no
// mouse button has been pressed. We require this in order to let the
// graphics window switch viewports properly.
this->setMouseTracking( true );
}
OSGWidget::~OSGWidget()
{
}
void OSGWidget::paintEvent( QPaintEvent* /* paintEvent */ )
{
this->makeCurrent();
QPainter painter( this );
painter.setRenderHint( QPainter::Antialiasing );
this->paintGL();
#ifdef WITH_SELECTION_PROCESSING
if( selectionActive_ && !selectionFinished_ )
{
painter.setPen( Qt::black );
painter.setBrush( Qt::transparent );
painter.drawRect( makeRectangle( selectionStart_, selectionEnd_ ) );
}
#endif
painter.end();
this->doneCurrent();
}
void OSGWidget::paintGL()
{
viewer_->frame();
}
void OSGWidget::resizeGL( int width, int height )
{
this->getEventQueue()->windowResize( this->x(), this->y(), width, height );
graphicsWindow_->resized( this->x(), this->y(), width, height );
this->onResize( width, height );
}
void OSGWidget::keyPressEvent( QKeyEvent* event )
{
QString keyString = event->text();
const char* keyData = keyString.toLocal8Bit().data();
if( event->key() == Qt::Key_S )
{
#ifdef WITH_SELECTION_PROCESSING
selectionActive_ = !selectionActive_;
#endif
// Further processing is required for the statistics handler here, so we do
// not return right away.
}
else if( event->key() == Qt::Key_D )
{
osgDB::writeNodeFile( *viewer_->getView(0)->getSceneData(),
"/tmp/sceneGraph.osg" );
return;
}
else if( event->key() == Qt::Key_H )
{
this->onHome();
return;
}
this->getEventQueue()->keyPress( osgGA::GUIEventAdapter::KeySymbol( *keyData ) );
}
void OSGWidget::keyReleaseEvent( QKeyEvent* event )
{
QString keyString = event->text();
const char* keyData = keyString.toLocal8Bit().data();
this->getEventQueue()->keyRelease( osgGA::GUIEventAdapter::KeySymbol( *keyData ) );
}
void OSGWidget::mouseMoveEvent( QMouseEvent* event )
{
// Note that we have to check the buttons mask in order to see whether the
// left button has been pressed. A call to `button()` will only result in
// `Qt::NoButton` for mouse move events.
if( selectionActive_ && event->buttons() & Qt::LeftButton )
{
selectionEnd_ = event->pos();
// Ensures that new paint events are created while the user moves the
// mouse.
this->update();
}
else
{
auto pixelRatio = this->devicePixelRatio();
this->getEventQueue()->mouseMotion( static_cast<float>( event->x() * pixelRatio ),
static_cast<float>( event->y() * pixelRatio ) );
}
}
void OSGWidget::mousePressEvent( QMouseEvent* event )
{
// Selection processing
if( selectionActive_ && event->button() == Qt::LeftButton )
{
selectionStart_ = event->pos();
selectionEnd_ = selectionStart_; // Deletes the old selection
selectionFinished_ = false; // As long as this is set, the rectangle will be drawn
}
// Normal processing
else
{
// 1 = left mouse button
// 2 = middle mouse button
// 3 = right mouse button
unsigned int button = 0;
switch( event->button() )
{
case Qt::LeftButton:
button = 1;
break;
case Qt::MiddleButton:
button = 2;
break;
case Qt::RightButton:
button = 3;
break;
default:
break;
}
auto pixelRatio = this->devicePixelRatio();
this->getEventQueue()->mouseButtonPress( static_cast<float>( event->x() * pixelRatio ),
static_cast<float>( event->y() * pixelRatio ),
button );
}
}
void OSGWidget::mouseReleaseEvent(QMouseEvent* event)
{
// Selection processing: Store end position and obtain selected objects
// through polytope intersection.
if( selectionActive_ && event->button() == Qt::LeftButton )
{
selectionEnd_ = event->pos();
selectionFinished_ = true; // Will force the painter to stop drawing the
// selection rectangle
this->processSelection();
}
// Normal processing
else
{
// 1 = left mouse button
// 2 = middle mouse button
// 3 = right mouse button
unsigned int button = 0;
switch( event->button() )
{
case Qt::LeftButton:
button = 1;
break;
case Qt::MiddleButton:
button = 2;
break;
case Qt::RightButton:
button = 3;
break;
default:
break;
}
auto pixelRatio = this->devicePixelRatio();
this->getEventQueue()->mouseButtonRelease( static_cast<float>( pixelRatio * event->x() ),
static_cast<float>( pixelRatio * event->y() ),
button );
}
}
void OSGWidget::wheelEvent( QWheelEvent* event )
{
// Ignore wheel events as long as the selection is active.
if( selectionActive_ )
return;
event->accept();
int delta = event->delta();
osgGA::GUIEventAdapter::ScrollingMotion motion = delta > 0 ? osgGA::GUIEventAdapter::SCROLL_UP
: osgGA::GUIEventAdapter::SCROLL_DOWN;
this->getEventQueue()->mouseScroll( motion );
}
bool OSGWidget::event( QEvent* event )
{
bool handled = QOpenGLWidget::event( event );
// This ensures that the OSG widget is always going to be repainted after the
// user performed some interaction. Doing this in the event handler ensures
// that we don't forget about some event and prevents duplicate code.
switch( event->type() )
{
case QEvent::KeyPress:
case QEvent::KeyRelease:
case QEvent::MouseButtonDblClick:
case QEvent::MouseButtonPress:
case QEvent::MouseButtonRelease:
case QEvent::MouseMove:
case QEvent::Wheel:
this->update();
break;
default:
break;
}
return handled;
}
void OSGWidget::onHome()
{
osgViewer::ViewerBase::Views views;
viewer_->getViews( views );
for( std::size_t i = 0; i < views.size(); i++ )
{
osgViewer::View* view = views.at(i);
view->home();
}
}
void OSGWidget::onResize( int width, int height )
{
std::vector<osg::Camera*> cameras;
viewer_->getCameras( cameras );
assert( cameras.size() == 2 );
auto pixelRatio = this->devicePixelRatio();
cameras[0]->setViewport( 0, 0, width / 2 * pixelRatio, height * pixelRatio );
cameras[1]->setViewport( width / 2 * pixelRatio, 0, width / 2 * pixelRatio, height * pixelRatio );
}
osgGA::EventQueue* OSGWidget::getEventQueue() const
{
osgGA::EventQueue* eventQueue = graphicsWindow_->getEventQueue();
if( eventQueue )
return eventQueue;
else
throw std::runtime_error( "Unable to obtain valid event queue");
}
void OSGWidget::processSelection()
{
#ifdef WITH_SELECTION_PROCESSING
QRect selectionRectangle = makeRectangle( selectionStart_, selectionEnd_ );
auto widgetHeight = this->height();
auto pixelRatio = this->devicePixelRatio();
double xMin = selectionRectangle.left();
double xMax = selectionRectangle.right();
double yMin = widgetHeight - selectionRectangle.bottom();
double yMax = widgetHeight - selectionRectangle.top();
xMin *= pixelRatio;
yMin *= pixelRatio;
xMax *= pixelRatio;
yMax *= pixelRatio;
osgUtil::PolytopeIntersector* polytopeIntersector
= new osgUtil::PolytopeIntersector( osgUtil::PolytopeIntersector::WINDOW,
xMin, yMin,
xMax, yMax );
// This limits the amount of intersections that are reported by the
// polytope intersector. Using this setting, a single drawable will
// appear at most once while calculating intersections. This is the
// preferred and expected behaviour.
polytopeIntersector->setIntersectionLimit( osgUtil::Intersector::LIMIT_ONE_PER_DRAWABLE );
osgUtil::IntersectionVisitor iv( polytopeIntersector );
for( unsigned int viewIndex = 0; viewIndex < viewer_->getNumViews(); viewIndex++ )
{
qDebug() << "View index:" << viewIndex;
osgViewer::View* view = viewer_->getView( viewIndex );
if( !view )
throw std::runtime_error( "Unable to obtain valid view for selection processing" );
osg::Camera* camera = view->getCamera();
if( !camera )
throw std::runtime_error( "Unable to obtain valid camera for selection processing" );
camera->accept( iv );
if( !polytopeIntersector->containsIntersections() )
continue;
auto intersections = polytopeIntersector->getIntersections();
for( auto&& intersection : intersections )
qDebug() << "Selected a drawable:" << QString::fromStdString( intersection.drawable->getName() );
}
#endif
}