Debian Codegraph @

src/Gui/Quarter/QuarterWidget.cpp

raw
1 /**************************************************************************\
2 * Copyright (c) Kongsberg Oil & Gas Technologies AS
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are
7 * met:
8 *
9 * Redistributions of source code must retain the above copyright notice,
10 * this list of conditions and the following disclaimer.
11 *
12 * Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 *
16 * Neither the name of the copyright holder nor the names of its
17 * contributors may be used to endorse or promote products derived from
18 * this software without specific prior written permission.
19 *
20 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24 * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31 \**************************************************************************/
32
33 /*!
34 \class SIM::Coin3D::Quarter::QuarterWidget QuarterWidget.h Quarter/QuarterWidget.h
35
36 \brief The QuarterWidget class is the main class in Quarter. It
37 provides a widget for Coin rendering. It provides scenegraph
38 management and event handling.
39
40 If you want to modify the GL format for an existing QuarterWidget, you can
41 set up a new GL context for the widget, e.g.:
42
43 \code
44 QGLContext * context = new QGLContext(QGLFormat(QGL::SampleBuffers), viewer);
45 if (context->create()) {
46 viewer->setContext(context);
47 }
48 \endcode
49 */
50
51 #ifdef _MSC_VER
52 #pragma warning(disable : 4267)
53 #endif
54
55 #include <cassert>
56
57 #if HAVE_CONFIG_H
58 # include <config.h>
59 # ifdef HAVE_GL_GL_H
60 # include <GL/gl.h>
61 # endif
62 #endif
63
64 #include <QAction>
65 #include <QApplication>
66 #include <QDebug>
67 #include <QEvent>
68 #include <QFile>
69 #include <QGuiApplication>
70 #include <QMetaObject>
71 #include <QOpenGLDebugLogger>
72 #include <QOpenGLDebugMessage>
73 #include <QOpenGLWidget>
74 #include <QPaintEvent>
75 #include <QResizeEvent>
76 #include <QWindow>
77
78 #include <Inventor/C/basic.h>
79 #include <Inventor/SbByteBuffer.h>
80
81 #include <Inventor/SbColor.h>
82 #include <Inventor/SbViewportRegion.h>
83 #include <Inventor/SoDB.h>
84 #include <Inventor/SoEventManager.h>
85 #include <Inventor/SoRenderManager.h>
86 #include <Inventor/nodes/SoCamera.h>
87 #include <Inventor/nodes/SoDirectionalLight.h>
88 #include <Inventor/nodes/SoNode.h>
89 #include <Inventor/nodes/SoPerspectiveCamera.h>
90 #include <Inventor/nodes/SoSeparator.h>
91 #include <Inventor/scxml/ScXML.h>
92 #include <Inventor/scxml/SoScXMLStateMachine.h>
93
94 #include <Base/Profiler.h>
95
96 #include "QuarterWidget.h"
97 #include "InteractionMode.h"
98 #include "QuarterP.h"
99 #include "QuarterWidgetP.h"
100 #include "eventhandlers/EventFilter.h"
101 #include "eventhandlers/DragDropHandler.h"
102
103
104 using namespace SIM::Coin3D::Quarter;
105
106 /*!
107 \enum SIM::Coin3D::Quarter::QuarterWidget::TransparencyType
108
109 Various settings for how to do rendering of transparent objects in
110 the scene. Some of the settings will provide faster rendering, while
111 others gives you better quality rendering.
112
113 See \ref SoGLRenderAction::TransparencyType for a full description of the modes
114 */
115
116 /*!
117 \enum SIM::Coin3D::Quarter::QuarterWidget::RenderMode
118
119 Sets how rendering of primitives is done.
120
121 See \ref SoRenderManager::RenderMode for a full description of the modes
122 */
123
124 /*!
125 \enum SIM::Coin3D::Quarter::QuarterWidget::StereoMode
126
127 Sets how stereo rendering is performed.
128
129 See \ref SoRenderManager::StereoMode for a full description of the modes
130 */
131
132 enum StereoMode {
133 MONO = SoRenderManager::MONO,
134 ANAGLYPH = SoRenderManager::ANAGLYPH,
135 QUAD_BUFFER = SoRenderManager::QUAD_BUFFER,
136 INTERLEAVED_ROWS = SoRenderManager::INTERLEAVED_ROWS,
137 INTERLEAVED_COLUMNS = SoRenderManager::INTERLEAVED_COLUMNS
138 };
139
140 #define PRIVATE(obj) obj->pimpl
141
142 #ifndef GL_MULTISAMPLE_BIT_EXT
143 #define GL_MULTISAMPLE_BIT_EXT 0x20000000
144 #endif
145
146 //We need to avoid buffer swapping when initializing a QPainter on this widget
147 class CustomGLWidget : public QOpenGLWidget {
148 public:
149 QSurfaceFormat myFormat;
150
151 CustomGLWidget(const QSurfaceFormat& format, QWidget* parent = nullptr, const QOpenGLWidget* shareWidget = nullptr, Qt::WindowFlags f = Qt::WindowFlags())
152 : QOpenGLWidget(parent, f), myFormat(format)
153 {
154 Q_UNUSED(shareWidget);
155 QSurfaceFormat surfaceFormat(format);
156 surfaceFormat.setSwapBehavior(QSurfaceFormat::DoubleBuffer);
157 // With the settings below we could determine deprecated OpenGL API
158 // but can't do this since otherwise it will complain about almost any
159 // OpenGL call in Coin3d
160 //surfaceFormat.setMajorVersion(3);
161 //surfaceFormat.setMinorVersion(2);
162 //surfaceFormat.setProfile(QSurfaceFormat::CoreProfile);
163
164 // On Wayland, we typically get a core profile unless we explicitly
165 // request a compatibility profile. On llvmpipe, this still seems to
166 // "just work" even if out of spec; on proprietary Nvidia drivers, it
167 // does not.
168 surfaceFormat.setRenderableType(QSurfaceFormat::OpenGL);
169 surfaceFormat.setProfile(QSurfaceFormat::CompatibilityProfile);
170 surfaceFormat.setOption(QSurfaceFormat::DeprecatedFunctions, true);
171
172 #if defined (_DEBUG) && 0
173 surfaceFormat.setOption(QSurfaceFormat::DebugContext);
174 #endif
175 setFormat(surfaceFormat);
176 }
177 ~CustomGLWidget() override = default;
178
179 void initializeGL() override
180 {
181 #if defined (_DEBUG) && 0
182 QOpenGLContext *context = QOpenGLContext::currentContext();
183 if (context && context->hasExtension(QByteArrayLiteral("GL_KHR_debug"))) {
184 QOpenGLDebugLogger *logger = new QOpenGLDebugLogger(this);
185 connect(logger, &QOpenGLDebugLogger::messageLogged, this, &CustomGLWidget::handleLoggedMessage);
186
187 if (logger->initialize())
188 logger->startLogging(QOpenGLDebugLogger::SynchronousLogging);
189 }
190 #endif
191
192 connect(this, &CustomGLWidget::resized, this, &CustomGLWidget::slotResized);
193 }
194 // paintGL() is invoked when e.g. using the method grabFramebuffer of this class
195 // \code
196 // from PySide import QtWidgets
197 // mw = Gui.getMainWindow()
198 // mdi = mw.findChild(QtWidgets.QMdiArea)
199 // gl = mdi.findChild(QtWidgets.QOpenGLWidget)
200 // img = gl.grabFramebuffer()
201 // \endcode
202 void paintGL() override
203 {
204 QuarterWidget* qw = qobject_cast<QuarterWidget*>(parentWidget());
205 if (qw) {
206 qw->redraw();
207 }
208 }
209
210 bool event(QEvent *e) override
211 {
212 // If a debug logger is activated then Qt's default implementation
213 // first releases the context before stopping the logger. However,
214 // the logger needs the active context and thus crashes because it's
215 // null.
216 if (e->type() == QEvent::WindowChangeInternal) {
217 if (!qApp->testAttribute(Qt::AA_ShareOpenGLContexts)) {
218 QOpenGLDebugLogger* logger = this->findChild<QOpenGLDebugLogger*>();
219 if (logger) {
220 logger->stopLogging();
221 delete logger;
222 }
223 }
224 }
225
226 return QOpenGLWidget::event(e);
227 }
228 void handleLoggedMessage(const QOpenGLDebugMessage &message)
229 {
230 qDebug() << message;
231 }
232 void showEvent(QShowEvent*) override
233 {
234 update(); // force update when changing window mode
235 }
236 void slotResized()
237 {
238 update(); // fixes flickering on some systems
239 }
240 };
241
242 /*! constructor */
243 QuarterWidget::QuarterWidget(const QSurfaceFormat & format, QWidget * parent, const QOpenGLWidget * sharewidget, Qt::WindowFlags f)
244 : inherited(parent)
245 {
246 Q_UNUSED(f);
247 this->constructor(format, sharewidget);
248 }
249
250 /*! constructor */
251 QuarterWidget::QuarterWidget(QWidget * parent, const QOpenGLWidget * sharewidget, Qt::WindowFlags f)
252 : inherited(parent)
253 {
254 Q_UNUSED(f);
255 this->constructor(QSurfaceFormat(), sharewidget);
256 }
257
258 /*! constructor */
259 QuarterWidget::QuarterWidget(QOpenGLContext * context, QWidget * parent, const QOpenGLWidget * sharewidget, Qt::WindowFlags f)
260 : inherited(parent)
261 {
262 Q_UNUSED(f);
263 this->constructor(context->format(), sharewidget);
264 }
265
266 void
267 QuarterWidget::constructor(const QSurfaceFormat & format, const QOpenGLWidget * sharewidget)
268 {
269 QGraphicsScene* scene = new QGraphicsScene(this);
270 setScene(scene);
271 setViewport(new CustomGLWidget(format, this, sharewidget));
272
273 setFrameStyle(QFrame::NoFrame);
274 setAutoFillBackground(false);
275 viewport()->setAutoFillBackground(false);
276 setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
277 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
278
279 PRIVATE(this) = new QuarterWidgetP(this, sharewidget);
280
281 PRIVATE(this)->sorendermanager = new SoRenderManager;
282 PRIVATE(this)->initialsorendermanager = true;
283 PRIVATE(this)->soeventmanager = new SoEventManager;
284 PRIVATE(this)->initialsoeventmanager = true;
285 PRIVATE(this)->processdelayqueue = true;
286
287 //Mind the order of initialization as the XML state machine uses
288 //callbacks which depends on other state being initialized
289 PRIVATE(this)->eventfilter = new EventFilter(this);
290 PRIVATE(this)->interactionmode = new InteractionMode(this);
291
292 PRIVATE(this)->currentStateMachine = nullptr;
293
294 PRIVATE(this)->headlight = new SoDirectionalLight;
295 PRIVATE(this)->headlight->ref();
296
297 PRIVATE(this)->sorendermanager->setAutoClipping(SoRenderManager::VARIABLE_NEAR_PLANE);
298 PRIVATE(this)->sorendermanager->setRenderCallback(QuarterWidgetP::rendercb, this);
299 PRIVATE(this)->sorendermanager->setBackgroundColor(SbColor4f(0.0f, 0.0f, 0.0f, 0.0f));
300 PRIVATE(this)->sorendermanager->activate();
301 PRIVATE(this)->sorendermanager->addPreRenderCallback(QuarterWidgetP::prerendercb, PRIVATE(this));
302 PRIVATE(this)->sorendermanager->addPostRenderCallback(QuarterWidgetP::postrendercb, PRIVATE(this));
303
304 PRIVATE(this)->soeventmanager->setNavigationState(SoEventManager::MIXED_NAVIGATION);
305
306 // set up a cache context for the default SoGLRenderAction
307 PRIVATE(this)->sorendermanager->getGLRenderAction()->setCacheContext(this->getCacheContextId());
308
309 this->setMouseTracking(true);
310
311 // Qt::StrongFocus means the widget will accept keyboard focus by
312 // both tabbing and clicking
313 this->setFocusPolicy(Qt::StrongFocus);
314
315 this->installEventFilter(PRIVATE(this)->eventfilter);
316 this->installEventFilter(PRIVATE(this)->interactionmode);
317
318 initialized = false;
319 }
320
321 void
322 QuarterWidget::replaceViewport()
323 {
324 CustomGLWidget* oldvp = static_cast<CustomGLWidget*>(viewport());
325 CustomGLWidget* newvp = new CustomGLWidget(oldvp->myFormat, this);
326 PRIVATE(this)->replaceGLWidget(newvp);
327 setViewport(newvp);
328
329 setAutoFillBackground(false);
330 viewport()->setAutoFillBackground(false);
331 }
332
333 /*! destructor */
334 QuarterWidget::~QuarterWidget()
335 {
336 if (PRIVATE(this)->currentStateMachine) {
337 this->removeStateMachine(PRIVATE(this)->currentStateMachine);
338 delete PRIVATE(this)->currentStateMachine;
339 }
340 PRIVATE(this)->headlight->unref();
341 PRIVATE(this)->headlight = nullptr;
342 this->setSceneGraph(nullptr);
343 this->setSoRenderManager(nullptr);
344 this->setSoEventManager(nullptr);
345 delete PRIVATE(this)->eventfilter;
346 delete PRIVATE(this);
347 }
348
349 /*!
350 You can set the cursor you want to use for a given navigation
351 state. See the Coin documentation on navigation for information
352 about available states
353 */
354 void
355 QuarterWidget::setStateCursor(const SbName & state, const QCursor & cursor)
356 {
357 assert(QuarterP::statecursormap);
358 // will overwrite the value of an existing item
359 QuarterP::statecursormap->insert(state, cursor);
360 }
361
362 /*!
363 Maps a state to a cursor
364
365 \param[in] state Named state in the statemachine
366 \retval Cursor corresponding to the given state
367 */
368 QCursor
369 QuarterWidget::stateCursor(const SbName & state)
370 {
371 assert(QuarterP::statecursormap);
372 return QuarterP::statecursormap->value(state);
373 }
374
375 /*!
376 \property QuarterWidget::headlightEnabled
377
378 \copydetails QuarterWidget::setHeadlightEnabled
379 */
380
381 /*!
382 Enable/disable the headlight. This will toggle the SoDirectionalLight::on
383 field (returned from getHeadlight()).
384 */
385 void
386 QuarterWidget::setHeadlightEnabled(bool onoff)
387 {
388 PRIVATE(this)->headlight->on = onoff;
389 }
390
391 /*!
392 Returns true if the headlight is on, false if it is off
393 */
394 bool
395 QuarterWidget::headlightEnabled() const
396 {
397 return PRIVATE(this)->headlight->on.getValue();
398 }
399
400 /*!
401 Returns the light used for the headlight.
402 */
403 SoDirectionalLight *
404 QuarterWidget::getHeadlight() const
405 {
406 return PRIVATE(this)->headlight;
407 }
408
409 /*!
410 \property QuarterWidget::clearZBuffer
411
412 \copydetails QuarterWidget::setClearZBuffer
413 */
414
415 /*!
416 Specify if you want the z buffer to be cleared before
417 redraw. This is on by default.
418 */
419 void
420 QuarterWidget::setClearZBuffer(bool onoff)
421 {
422 PRIVATE(this)->clearzbuffer = onoff;
423 }
424
425 /*!
426 Returns true if the z buffer is cleared before rendering.
427 */
428 bool
429 QuarterWidget::clearZBuffer() const
430 {
431 return PRIVATE(this)->clearzbuffer;
432 }
433
434 /*!
435 \property QuarterWidget::clearWindow
436
437 \copydetails QuarterWidget::setClearWindow
438 */
439
440 /*!
441 Specify if you want the rendering buffer to be cleared before
442 rendering. This is on by default.
443 */
444 void
445 QuarterWidget::setClearWindow(bool onoff)
446 {
447 PRIVATE(this)->clearwindow = onoff;
448 }
449
450 /*!
451 Returns true if the rendering buffer is cleared before rendering.
452 */
453 bool
454 QuarterWidget::clearWindow() const
455 {
456 return PRIVATE(this)->clearwindow;
457 }
458
459 /*!
460 \property QuarterWidget::interactionModeEnabled
461
462 \copydetails QuarterWidget::setInteractionModeEnabled
463 */
464
465 /*!
466 Enable/disable interaction mode.
467
468 Specifies whether you may use the alt-key to enter interaction mode.
469 */
470 void
471 QuarterWidget::setInteractionModeEnabled(bool onoff)
472 {
473 PRIVATE(this)->interactionmode->setEnabled(onoff);
474 }
475
476 /*!
477 Returns true if interaction mode is enabled, false otherwise.
478 */
479 bool
480 QuarterWidget::interactionModeEnabled() const
481 {
482 return PRIVATE(this)->interactionmode->enabled();
483 }
484
485 /*!
486 \property QuarterWidget::interactionModeOn
487
488 \copydetails QuarterWidget::setInteractionModeOn
489 */
490
491 /*!
492 Turn interaction mode on or off.
493 */
494 void
495 QuarterWidget::setInteractionModeOn(bool onoff)
496 {
497 PRIVATE(this)->interactionmode->setOn(onoff);
498 }
499
500 /*!
501 Returns true if interaction mode is on.
502 */
503 bool
504 QuarterWidget::interactionModeOn() const
505 {
506 return PRIVATE(this)->interactionmode->on();
507 }
508
509 /*!
510 Returns the Coin cache context id for this widget.
511 */
512 uint32_t
513 QuarterWidget::getCacheContextId() const
514 {
515 return PRIVATE(this)->getCacheContextId();
516 }
517
518 /*!
519 \property QuarterWidget::transparencyType
520
521 \copydetails QuarterWidget::setTransparencyType
522 */
523
524 /*!
525 Sets the transparency type to be used for the scene.
526 */
527 void
528 QuarterWidget::setTransparencyType(TransparencyType type)
529 {
530 assert(PRIVATE(this)->sorendermanager);
531 PRIVATE(this)->sorendermanager->getGLRenderAction()->setTransparencyType((SoGLRenderAction::TransparencyType)type);
532 PRIVATE(this)->sorendermanager->scheduleRedraw();
533 }
534
535 /*!
536 \retval The current \ref TransparencyType
537 */
538 QuarterWidget::TransparencyType
539 QuarterWidget::transparencyType() const
540 {
541 assert(PRIVATE(this)->sorendermanager);
542 SoGLRenderAction * action = PRIVATE(this)->sorendermanager->getGLRenderAction();
543 return static_cast<QuarterWidget::TransparencyType>(action->getTransparencyType());
544 }
545
546 /*!
547 \property QuarterWidget::renderMode
548
549 \copydetails QuarterWidget::setRenderMode
550 */
551
552 /*!
553 \copydoc RenderMode
554 */
555 void
556 QuarterWidget::setRenderMode(RenderMode mode)
557 {
558 assert(PRIVATE(this)->sorendermanager);
559 PRIVATE(this)->sorendermanager->setRenderMode(static_cast<SoRenderManager::RenderMode>(mode));
560 PRIVATE(this)->sorendermanager->scheduleRedraw();
561 }
562
563 /*!
564 \retval The current \ref RenderMode
565 */
566 QuarterWidget::RenderMode
567 QuarterWidget::renderMode() const
568 {
569 assert(PRIVATE(this)->sorendermanager);
570 return static_cast<RenderMode>(PRIVATE(this)->sorendermanager->getRenderMode());
571 }
572
573 /*!
574 \property QuarterWidget::stereoMode
575
576 \copydetails QuarterWidget::setStereoMode
577 */
578
579 /*!
580 \copydoc StereoMode
581 */
582 void
583 QuarterWidget::setStereoMode(StereoMode mode)
584 {
585 assert(PRIVATE(this)->sorendermanager);
586 PRIVATE(this)->sorendermanager->setStereoMode(static_cast<SoRenderManager::StereoMode>(mode));
587 PRIVATE(this)->sorendermanager->scheduleRedraw();
588 }
589
590
591 /*!
592 \retval The current \ref StereoMode
593 */
594 QuarterWidget::StereoMode
595 QuarterWidget::stereoMode() const
596 {
597 assert(PRIVATE(this)->sorendermanager);
598 return static_cast<StereoMode>(PRIVATE(this)->sorendermanager->getStereoMode());
599 }
600
601 /*!
602 \property QuarterWidget::devicePixelRatio
603
604 \copydetails QuarterWidget::devicePixelRatio
605 */
606
607 /*!
608 The ratio between logical and physical pixel sizes -- obtained from the window that
609 the widget is located within, and updated whenever any change occurs, emitting a devicePixelRatioChanged signal. Only available for version Qt 5.6 and above (will be 1.0 for all previous versions)
610 */
611
612 qreal
613 QuarterWidget::devicePixelRatio() const
614 {
615 return PRIVATE(this)->device_pixel_ratio;
616 }
617
618 /*!
619 Sets the Inventor scenegraph to be rendered
620 */
621 void
622 QuarterWidget::setSceneGraph(SoNode * node)
623 {
624 if (node == PRIVATE(this)->scene) {
625 return;
626 }
627
628 if (PRIVATE(this)->scene) {
629 PRIVATE(this)->scene->unref();
630 PRIVATE(this)->scene = nullptr;
631 }
632
633 SoCamera * camera = nullptr;
634 SoSeparator * superscene = nullptr;
635 bool viewall = false;
636
637 if (node) {
638 PRIVATE(this)->scene = node;
639 PRIVATE(this)->scene->ref();
640
641 superscene = new SoSeparator;
642 superscene->addChild(PRIVATE(this)->headlight);
643
644 // if the scene does not contain a camera, add one
645 if (!(camera = PRIVATE(this)->searchForCamera(node))) {
646 camera = new SoPerspectiveCamera;
647 superscene->addChild(camera);
648 viewall = true;
649 }
650
651 superscene->addChild(node);
652 }
653
654 PRIVATE(this)->soeventmanager->setCamera(camera);
655 PRIVATE(this)->sorendermanager->setCamera(camera);
656 PRIVATE(this)->soeventmanager->setSceneGraph(superscene);
657 PRIVATE(this)->sorendermanager->setSceneGraph(superscene);
658
659 if (viewall) { this->viewAll(); }
660 if (superscene) { superscene->touch(); }
661 }
662
663 /*!
664 Returns pointer to root of scene graph
665 */
666 SoNode *
667 QuarterWidget::getSceneGraph() const
668 {
669 return PRIVATE(this)->scene;
670 }
671
672 /*!
673 Set the render manager for the widget.
674 */
675 void
676 QuarterWidget::setSoRenderManager(SoRenderManager * manager)
677 {
678 bool carrydata = false;
679 SoNode * scene = nullptr;
680 SoCamera * camera = nullptr;
681 SbViewportRegion vp;
682 if (PRIVATE(this)->sorendermanager && manager) {
683 scene = PRIVATE(this)->sorendermanager->getSceneGraph();
684 camera = PRIVATE(this)->sorendermanager->getCamera();
685 vp = PRIVATE(this)->sorendermanager->getViewportRegion(); // clazy:exclude=rule-of-two-soft
686 carrydata = true;
687 }
688
689 // ref before deleting the old scene manager to avoid that the nodes are deleted
690 if (scene) scene->ref();
691 if (camera) camera->ref();
692
693 if (PRIVATE(this)->initialsorendermanager) {
694 delete PRIVATE(this)->sorendermanager;
695 PRIVATE(this)->initialsorendermanager = false;
696 }
697 PRIVATE(this)->sorendermanager = manager;
698 if (carrydata) {
699 PRIVATE(this)->sorendermanager->setSceneGraph(scene);
700 PRIVATE(this)->sorendermanager->setCamera(camera);
701 PRIVATE(this)->sorendermanager->setViewportRegion(vp);
702 }
703
704 if (scene) scene->unref();
705 if (camera) camera->unref();
706 }
707
708 /*!
709 Returns a pointer to the render manager.
710 */
711 SoRenderManager *
712 QuarterWidget::getSoRenderManager() const
713 {
714 return PRIVATE(this)->sorendermanager;
715 }
716
717 /*!
718 Set the Coin event manager for the widget.
719 */
720 void
721 QuarterWidget::setSoEventManager(SoEventManager * manager)
722 {
723 bool carrydata = false;
724 SoNode * scene = nullptr;
725 SoCamera * camera = nullptr;
726 SbViewportRegion vp;
727 if (PRIVATE(this)->soeventmanager && manager) {
728 scene = PRIVATE(this)->soeventmanager->getSceneGraph();
729 camera = PRIVATE(this)->soeventmanager->getCamera();
730 vp = PRIVATE(this)->soeventmanager->getViewportRegion(); // clazy:exclude=rule-of-two-soft
731 carrydata = true;
732 }
733
734 // ref before deleting the old scene manager to avoid that the nodes are deleted
735 if (scene) scene->ref();
736 if (camera) camera->ref();
737
738 if (PRIVATE(this)->initialsoeventmanager) {
739 delete PRIVATE(this)->soeventmanager;
740 PRIVATE(this)->initialsoeventmanager = false;
741 }
742 PRIVATE(this)->soeventmanager = manager;
743 if (carrydata) {
744 PRIVATE(this)->soeventmanager->setSceneGraph(scene);
745 PRIVATE(this)->soeventmanager->setCamera(camera);
746 PRIVATE(this)->soeventmanager->setViewportRegion(vp);
747 }
748
749 if (scene) scene->unref();
750 if (camera) camera->unref();
751 }
752
753 /*!
754 Returns a pointer to the event manager
755 */
756 SoEventManager *
757 QuarterWidget::getSoEventManager() const
758 {
759 return PRIVATE(this)->soeventmanager;
760 }
761
762 /*!
763 Returns a pointer to the event filter
764 */
765 EventFilter *
766 QuarterWidget::getEventFilter() const
767 {
768 return PRIVATE(this)->eventfilter;
769 }
770
771 /*!
772 Reposition the current camera to display the entire scene
773 */
774 void
775 QuarterWidget::viewAll()
776 {
777 const SbName viewallevent("sim.coin3d.coin.navigation.ViewAll");
778 for (int c = 0; c < PRIVATE(this)->soeventmanager->getNumSoScXMLStateMachines(); ++c) {
779 SoScXMLStateMachine * sostatemachine =
780 PRIVATE(this)->soeventmanager->getSoScXMLStateMachine(c);
781 if (sostatemachine->isActive()) {
782 sostatemachine->queueEvent(viewallevent);
783 sostatemachine->processEventQueue();
784 }
785 }
786 }
787
788 /*!
789 Sets the current camera in seek mode, if supported by the underlying navigation system.
790 Camera typically seeks towards what the mouse is pointing at.
791 */
792 void
793 QuarterWidget::seek()
794 {
795 const SbName seekevent("sim.coin3d.coin.navigation.Seek");
796 for (int c = 0; c < PRIVATE(this)->soeventmanager->getNumSoScXMLStateMachines(); ++c) {
797 SoScXMLStateMachine * sostatemachine =
798 PRIVATE(this)->soeventmanager->getSoScXMLStateMachine(c);
799 if (sostatemachine->isActive()) {
800 sostatemachine->queueEvent(seekevent);
801 sostatemachine->processEventQueue();
802 }
803 }
804 }
805
806 bool
807 QuarterWidget::updateDevicePixelRatio() {
808 qreal dev_pix_ratio = 1.0;
809 QWidget* winwidg = window();
810 QWindow* win = nullptr;
811 if(winwidg) {
812 win = winwidg->windowHandle();
813 }
814 if(win) {
815 dev_pix_ratio = win->devicePixelRatio();
816 }
817 else {
818 dev_pix_ratio = ((QGuiApplication*)QGuiApplication::instance())->devicePixelRatio();
819 }
820 if(PRIVATE(this)->device_pixel_ratio != dev_pix_ratio) {
821 PRIVATE(this)->device_pixel_ratio = dev_pix_ratio;
822 Q_EMIT devicePixelRatioChanged(dev_pix_ratio);
823 return true;
824 }
825 return false;
826 }
827
828 /*!
829 Overridden from QGLWidget to resize the Coin scenegraph
830 */
831 void QuarterWidget::resizeEvent(QResizeEvent* event)
832 {
833 updateDevicePixelRatio();
834 qreal dev_pix_ratio = devicePixelRatio();
835 int width = static_cast<int>(dev_pix_ratio * event->size().width());
836 int height = static_cast<int>(dev_pix_ratio * event->size().height());
837
838 SbViewportRegion vp(width, height);
839 PRIVATE(this)->sorendermanager->setViewportRegion(vp);
840 PRIVATE(this)->soeventmanager->setViewportRegion(vp);
841 if (scene())
842 scene()->setSceneRect(QRect(QPoint(0, 0), event->size()));
843 QGraphicsView::resizeEvent(event);
844 }
845
846 /*!
847 Overridden from QGLWidget to render the scenegraph
848 */
849 void QuarterWidget::paintEvent(QPaintEvent* event)
850 {
851 ZoneScoped;
852
853 if (updateDevicePixelRatio()) {
854 qreal dev_pix_ratio = devicePixelRatio();
855 int width = static_cast<int>(dev_pix_ratio * this->width());
856 int height = static_cast<int>(dev_pix_ratio * this->height());
857 SbViewportRegion vp(width, height);
858 PRIVATE(this)->sorendermanager->setViewportRegion(vp);
859 PRIVATE(this)->soeventmanager->setViewportRegion(vp);
860 }
861
862 if(!initialized) {
863 this->getSoRenderManager()->reinitialize();
864 initialized = true;
865 }
866
867 getSoRenderManager()->activate();
868
869 glMatrixMode(GL_PROJECTION);
870
871 QOpenGLWidget* w = static_cast<QOpenGLWidget*>(this->viewport());
872 if (!w->isValid()) {
873 qWarning() << "No valid GL context found!";
874 return;
875 }
876 //assert(w->isValid() && "No valid GL context found!");
877 // We might have to process the delay queue here since we don't know
878 // if paintGL() is called from Qt, and we might have some sensors
879 // waiting to trigger (the redraw sensor has a lower priority than a
880 // normal field sensor to guarantee that your sensor is processed
881 // before the next redraw). Disable autorendering while we do this
882 // to avoid recursive redraws.
883
884 // We set the PRIVATE(this)->processdelayqueue = false in redraw()
885 // to avoid processing the delay queue when paintGL() is triggered
886 // by us, and we don't want to process the delay queue in those
887 // cases
888
889 PRIVATE(this)->autoredrawenabled = false;
890
891 if(PRIVATE(this)->processdelayqueue && SoDB::getSensorManager()->isDelaySensorPending()) {
892 // processing the sensors might trigger a redraw in another
893 // context. Release this context temporarily
894 w->doneCurrent();
895 SoDB::getSensorManager()->processDelayQueue(false);
896 w->makeCurrent();
897 }
898
899 assert(w->isValid() && "No valid GL context found!");
900
901 // Causes an OpenGL error on resize
902 //glDrawBuffer(w->format().swapBehavior() == QSurfaceFormat::DoubleBuffer ? GL_BACK : GL_FRONT);
903
904 w->makeCurrent();
905 this->actualRedraw();
906
907 //start the standard graphics view processing for all widgets and graphic items. As
908 //QGraphicsView initaliizes a QPainter which changes the Opengl context in an unpredictable
909 //manner we need to store the context and recreate it after Qt is done.
910 glPushAttrib(GL_MULTISAMPLE_BIT_EXT);
911 inherited::paintEvent(event);
912 glPopAttrib();
913
914 // Causes an OpenGL error on resize
915 //if (w->format().swapBehavior() == QSurfaceFormat::DoubleBuffer)
916 // w->context()->swapBuffers(w->context()->surface());
917
918 PRIVATE(this)->autoredrawenabled = true;
919
920 // process the delay queue the next time we enter this function,
921 // unless we get here after a call to redraw().
922 PRIVATE(this)->processdelayqueue = true;
923 }
924
925 bool QuarterWidget::viewportEvent(QEvent* event)
926 {
927
928 // If no item is selected still let the graphics scene handle it but
929 // additionally handle it by this viewer. This is e.g. needed when
930 // resizing a widget item because the cursor may already be outside
931 // this widget.
932 if (event->type() == QEvent::MouseButtonDblClick ||
933 event->type() == QEvent::MouseButtonPress) {
934 QMouseEvent* mouse = static_cast<QMouseEvent*>(event);
935 QGraphicsItem *item = itemAt(mouse->pos());
936 if (!item) {
937 QGraphicsView::viewportEvent(event);
938 return false;
939 }
940 }
941 else if (event->type() == QEvent::MouseMove ||
942 event->type() == QEvent::MouseButtonRelease) {
943 QGraphicsScene* glScene = this->scene();
944 if (!(glScene && glScene->mouseGrabberItem())) {
945 QGraphicsView::viewportEvent(event);
946 return false;
947 }
948 }
949 else if (event->type() == QEvent::Wheel) {
950 auto wheel = static_cast<QWheelEvent*>(event);
951 QPoint pos = wheel->position().toPoint();
952 QGraphicsItem* item = itemAt(pos);
953 if (!item) {
954 QGraphicsView::viewportEvent(event);
955 return false;
956 }
957 }
958
959 return QGraphicsView::viewportEvent(event);
960 }
961
962 /*!
963 Used for rendering the scene. Usually Coin/Quarter will automatically redraw
964 the scene graph at regular intervals, after the scene is modified.
965
966 However, if you want to disable this functionality and gain full control over
967 when the scene is rendered yourself, you can turn off autoredraw in the
968 render manager and render the scene by calling this method.
969 */
970 void
971 QuarterWidget::redraw()
972 {
973 // we're triggering the next paintGL(). Set a flag to remember this
974 // to avoid that we process the delay queue in paintGL()
975 PRIVATE(this)->processdelayqueue = false;
976
977 // When stylesheet is used, there is recursive repaint warning caused by
978 // repaint() here. It happens when switching active documents. Based on call
979 // stacks, it happens like this, the repaint event first triggers a series
980 // calls of QWidgetPrivate::paintSiblingsRecrusive(), and then reaches one of
981 // the QuarterWidget. From its paintEvent(), it calls
982 // SoSensorManager::processDelayQueue(), which triggers redraw() of another
983 // QuarterWidget. And if repaint() is called here, it will trigger another
984 // series call of QWidgetPrivate::paintSiblingRecursive(), and eventually
985 // back to the first QuarterWidget, at which time the "Recursive repaint
986 // detected" Qt warning message will be printed.
987 //
988 // Note that, the recursive repaint is not infinite due to setting
989 // 'processdelayqueue = false' above. However, it does cause annoying
990 // flickering, and actually crash on Windows.
991 this->viewport()->update();
992 }
993
994 /*!
995 Overridden from QGLWidget to render the scenegraph
996 */
997 void
998 QuarterWidget::actualRedraw()
999 {
1000 ZoneScoped;
1001 PRIVATE(this)->sorendermanager->render(PRIVATE(this)->clearwindow,
1002 PRIVATE(this)->clearzbuffer);
1003 }
1004
1005
1006 /*!
1007 Passes an event to the event manager.
1008
1009 \param[in] event to pass
1010 \retval Returns true if the event was successfully processed
1011 */
1012 bool
1013 QuarterWidget::processSoEvent(const SoEvent * event)
1014 {
1015 return
1016 event &&
1017 PRIVATE(this)->soeventmanager &&
1018 PRIVATE(this)->soeventmanager->processEvent(event);
1019 }
1020
1021 /*!
1022 \property QuarterWidget::backgroundColor
1023 \copydoc QuarterWidget::setBackgroundColor
1024 */
1025
1026 /*!
1027 Set background color to a given QColor
1028
1029 Remember that QColors are given in integers between 0 and 255, as
1030 opposed to SbColor4f which is in [0, 1]. The default alpha value for
1031 a QColor is 255, but you'll probably want to set it to zero before
1032 using it as an OpenGL clear color.
1033 */
1034 void
1035 QuarterWidget::setBackgroundColor(const QColor & color)
1036 {
1037 SbColor4f bgcolor(SbClamp(color.red() / 255.0, 0.0, 1.0),
1038 SbClamp(color.green() / 255.0, 0.0, 1.0),
1039 SbClamp(color.blue() / 255.0, 0.0, 1.0),
1040 SbClamp(color.alpha() / 255.0, 0.0, 1.0));
1041
1042 PRIVATE(this)->sorendermanager->setBackgroundColor(bgcolor);
1043 PRIVATE(this)->sorendermanager->scheduleRedraw();
1044 }
1045
1046 /*!
1047 Returns color used for clearing the rendering area before
1048 rendering the scene.
1049 */
1050 QColor
1051 QuarterWidget::backgroundColor() const
1052 {
1053 SbColor4f bg = PRIVATE(this)->sorendermanager->getBackgroundColor();
1054
1055 return {SbClamp(int(bg[0] * 255.0), 0, 255),
1056 SbClamp(int(bg[1] * 255.0), 0, 255),
1057 SbClamp(int(bg[2] * 255.0), 0, 255),
1058 SbClamp(int(bg[3] * 255.0), 0, 255)};
1059 }
1060
1061 /*!
1062 Returns the context menu used by the widget.
1063 */
1064 QMenu *
1065 QuarterWidget::getContextMenu() const
1066 {
1067 return PRIVATE(this)->contextMenu();
1068 }
1069
1070 /*!
1071 \retval Is context menu enabled?
1072 */
1073 bool
1074 QuarterWidget::contextMenuEnabled() const
1075 {
1076 return PRIVATE(this)->contextmenuenabled;
1077 }
1078
1079 /*!
1080 \property QuarterWidget::contextMenuEnabled
1081
1082 \copydetails QuarterWidget::setContextMenuEnabled
1083 */
1084
1085 /*!
1086 Controls the display of the context menu
1087
1088 \param[in] yes Context menu on?
1089 */
1090 void
1091 QuarterWidget::setContextMenuEnabled(bool yes)
1092 {
1093 PRIVATE(this)->contextmenuenabled = yes;
1094 }
1095
1096 /*!
1097 Convenience method that adds a state machine to the current
1098 SoEventManager. It also initializes the scene graph
1099 root and active camera for the state machine, and finally it sets
1100 up the default Quarter cursor handling.
1101
1102 \sa removeStateMachine
1103 */
1104 void
1105 QuarterWidget::addStateMachine(SoScXMLStateMachine * statemachine)
1106 {
1107 SoEventManager * em = this->getSoEventManager();
1108 em->addSoScXMLStateMachine(statemachine);
1109 statemachine->setSceneGraphRoot(this->getSoRenderManager()->getSceneGraph());
1110 statemachine->setActiveCamera(this->getSoRenderManager()->getCamera());
1111 statemachine->addStateChangeCallback(QuarterWidgetP::statechangecb, PRIVATE(this));
1112 }
1113
1114 /*!
1115 Convenience method that removes a state machine from the current
1116 SoEventManager.
1117
1118 \sa addStateMachine
1119 */
1120 void
1121 QuarterWidget::removeStateMachine(SoScXMLStateMachine * statemachine)
1122 {
1123 SoEventManager * em = this->getSoEventManager();
1124 statemachine->setSceneGraphRoot(nullptr);
1125 statemachine->setActiveCamera(nullptr);
1126 em->removeSoScXMLStateMachine(statemachine);
1127 }
1128
1129 /*!
1130 See \ref QWidget::minimumSizeHint
1131 */
1132 QSize
1133 QuarterWidget::minimumSizeHint() const
1134 {
1135 return {50, 50};
1136 }
1137
1138 /*! Returns a list of grouped actions that corresponds to the
1139 TransparencyType enum. If you want to create a menu in your
1140 application that controls the transparency type used in
1141 QuarterWidget, add these actions to the menu.
1142 */
1143 QList<QAction *>
1144 QuarterWidget::transparencyTypeActions() const
1145 {
1146 return PRIVATE(this)->transparencyTypeActions();
1147 }
1148
1149 /*! Returns a list of grouped actions that corresponds to the
1150 StereoMode enum. If you want to create a menu in your
1151 application that controls the stereo mode used in
1152 QuarterWidget, add these actions to the menu.
1153 */
1154 QList<QAction *>
1155 QuarterWidget::stereoModeActions() const
1156 {
1157 return PRIVATE(this)->stereoModeActions();
1158 }
1159
1160 /*! Returns a list of grouped actions that corresponds to the
1161 RenderMode enum. If you want to create a menu in your
1162 application that controls the render mode type used in
1163 QuarterWidget, add these actions to the menu.
1164 */
1165 QList<QAction *>
1166 QuarterWidget::renderModeActions() const
1167 {
1168 return PRIVATE(this)->renderModeActions();
1169 }
1170
1171 /*!
1172 \property QuarterWidget::navigationModeFile
1173
1174 A url pointing to a navigation mode file which is a scxml file
1175 that defines the possible states for the Coin navigation system
1176
1177 Supports:
1178 \li \b coin for internal Coin resources
1179 \li \b file for file system path to resources
1180
1181 \sa scxml
1182 */
1183
1184 /*!
1185 Removes any navigationModeFile set.
1186 */
1187 void
1188 QuarterWidget::resetNavigationModeFile() {
1189 this->setNavigationModeFile(QUrl());
1190 }
1191
1192 /**
1193 * Sets up the default cursors for the widget.
1194 */
1195 void QuarterWidget::setupDefaultCursors()
1196 {
1197 this->setStateCursor("interact", Qt::ArrowCursor);
1198 this->setStateCursor("idle", Qt::OpenHandCursor);
1199 this->setStateCursor("rotate", Qt::ClosedHandCursor);
1200 this->setStateCursor("pan", Qt::SizeAllCursor);
1201 this->setStateCursor("zoom", Qt::SizeVerCursor);
1202 this->setStateCursor("dolly", Qt::SizeVerCursor);
1203 this->setStateCursor("seek", Qt::CrossCursor);
1204 this->setStateCursor("spin", Qt::OpenHandCursor);
1205 }
1206
1207 /*!
1208 Sets a navigation mode file. Supports the schemes "coin" and "file"
1209
1210 \param[in] url URL to the resource
1211 */
1212 void
1213 QuarterWidget::setNavigationModeFile(const QUrl & url)
1214 {
1215 QString filename;
1216
1217 if (url.scheme()=="coin") {
1218 filename = url.path();
1219
1220 //Workaround for differences between url scheme, and Coin internal
1221 //scheme in Coin 3.0.
1222 if (filename[0]=='/') {
1223 filename.remove(0,1);
1224 }
1225
1226 filename = url.scheme()+':'+filename;
1227 }
1228 else if (url.scheme()=="file")
1229 filename = url.toLocalFile();
1230 else if (url.isEmpty()) {
1231 if (PRIVATE(this)->currentStateMachine) {
1232 this->removeStateMachine(PRIVATE(this)->currentStateMachine);
1233 delete PRIVATE(this)->currentStateMachine;
1234 PRIVATE(this)->currentStateMachine = nullptr;
1235 PRIVATE(this)->navigationModeFile = url;
1236 }
1237 return;
1238 }
1239 else {
1240 qDebug()<<url.scheme()<<"is not recognized";
1241 return;
1242 }
1243
1244 QByteArray filenametmp = filename.toLocal8Bit();
1245 ScXMLStateMachine * stateMachine = nullptr;
1246
1247 if (filenametmp.startsWith("coin:")){
1248 stateMachine = ScXML::readFile(filenametmp.data());
1249 }
1250 else {
1251 //Use Qt to read the file in case it is a Qt resource
1252 QFile file(filenametmp);
1253 if (file.open(QIODevice::ReadOnly)){
1254 QByteArray fileContents = file.readAll();
1255 stateMachine = ScXML::readBuffer(SbByteBuffer(fileContents.size(), fileContents.constData()));
1256 file.close();
1257 }
1258 }
1259
1260 if (stateMachine &&
1261 stateMachine->isOfType(SoScXMLStateMachine::getClassTypeId())) {
1262 SoScXMLStateMachine * newsm =
1263 static_cast<SoScXMLStateMachine *>(stateMachine);
1264 if (PRIVATE(this)->currentStateMachine) {
1265 this->removeStateMachine(PRIVATE(this)->currentStateMachine);
1266 delete PRIVATE(this)->currentStateMachine;
1267 }
1268 this->addStateMachine(newsm);
1269 newsm->initialize();
1270 PRIVATE(this)->currentStateMachine = newsm;
1271 }
1272 else {
1273 delete stateMachine;
1274 stateMachine = nullptr;
1275 qDebug()<<filename;
1276 qDebug()<<"Unable to load"<<url;
1277 return;
1278 }
1279
1280 //If we have gotten this far, we have successfully loaded the
1281 //navigation file, so we set the property
1282 PRIVATE(this)->navigationModeFile = url;
1283
1284 if (QUrl(DEFAULT_NAVIGATIONFILE) == PRIVATE(this)->navigationModeFile ) {
1285
1286 // set up default cursors for the examiner navigation states
1287 //FIXME: It may be overly restrictive to not do this for arbitrary
1288 //navigation systems? - BFG 20090117
1289 setupDefaultCursors();
1290 }
1291 }
1292
1293 /*!
1294 \retval The current navigation mode file
1295 */
1296 const QUrl &
1297 QuarterWidget::navigationModeFile() const
1298 {
1299 return PRIVATE(this)->navigationModeFile;
1300 }
1301
1302 #undef PRIVATE