Debian Codegraph @

src/Gui/View3DInventorViewer.cpp

raw
1 /***************************************************************************
2 * Copyright (c) 2004 Jürgen Riegel <[email protected]> *
3 * *
4 * This file is part of the FreeCAD CAx development system. *
5 * *
6 * This library is free software; you can redistribute it and/or *
7 * modify it under the terms of the GNU Library General Public *
8 * License as published by the Free Software Foundation; either *
9 * version 2 of the License, or (at your option) any later version. *
10 * *
11 * This library is distributed in the hope that it will be useful, *
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
14 * GNU Library General Public License for more details. *
15 * *
16 * You should have received a copy of the GNU Library General Public *
17 * License along with this library; see the file COPYING.LIB. If not, *
18 * write to the Free Software Foundation, Inc., 59 Temple Place, *
19 * Suite 330, Boston, MA 02111-1307, USA *
20 * *
21 ***************************************************************************/
22
23 #include <FCConfig.h>
24
25 #include <Inventor/SoFCPlacementIndicatorKit.h>
26
27 #ifdef FC_OS_WIN32
28 # include <windows.h>
29 #endif
30 #ifdef FC_OS_MACOSX
31 # include <OpenGL/gl.h>
32 #else
33 # include <GL/gl.h>
34 # include <GL/glext.h>
35 # include <GL/glu.h>
36 #endif
37
38 #include <fmt/format.h>
39
40 #include <Inventor/SbBox.h>
41 #include <Inventor/SoEventManager.h>
42 #include <Inventor/SoPickedPoint.h>
43 #include <Inventor/actions/SoGetBoundingBoxAction.h>
44 #include <Inventor/actions/SoGetMatrixAction.h>
45 #include <Inventor/actions/SoHandleEventAction.h>
46 #include <Inventor/actions/SoRayPickAction.h>
47 #include <Inventor/annex/HardCopy/SoVectorizePSAction.h>
48 #include <Inventor/annex/Profiler/SoProfiler.h>
49 #include <Inventor/annex/Profiler/elements/SoProfilerElement.h>
50 #include <Inventor/details/SoDetail.h>
51 #include <Inventor/elements/SoLightModelElement.h>
52 #include <Inventor/elements/SoOverrideElement.h>
53 #include <Inventor/elements/SoViewportRegionElement.h>
54 #include <Inventor/errors/SoDebugError.h>
55 #include <Inventor/events/SoEvent.h>
56 #include <Inventor/events/SoKeyboardEvent.h>
57 #include <Inventor/events/SoMotion3Event.h>
58 #include <Inventor/manips/SoClipPlaneManip.h>
59 #include <Inventor/nodes/SoAnnotation.h>
60 #include <Inventor/nodes/SoBaseColor.h>
61 #include <Inventor/nodes/SoCallback.h>
62 #include <Inventor/nodes/SoCube.h>
63 #include <Inventor/nodes/SoDirectionalLight.h>
64 #include <Inventor/nodes/SoEventCallback.h>
65 #include <Inventor/nodes/SoLightModel.h>
66 #include <Inventor/nodes/SoMaterial.h>
67 #include <Inventor/nodes/SoOrthographicCamera.h>
68 #include <Inventor/nodes/SoPerspectiveCamera.h>
69 #include <Inventor/nodes/SoPickStyle.h>
70 #include <Inventor/nodes/SoScale.h>
71 #include <Inventor/nodes/SoSelection.h>
72 #include <Inventor/nodes/SoSeparator.h>
73 #include <Inventor/nodes/SoSphere.h>
74 #include <Inventor/nodes/SoSwitch.h>
75 #include <Inventor/nodes/SoTransform.h>
76 #include <Inventor/nodes/SoTranslation.h>
77 #include <QBitmap>
78 #include <QEventLoop>
79 #if defined(Q_OS_LINUX) && QT_VERSION < QT_VERSION_CHECK(6, 6, 0)
80 # include <QGuiApplication>
81 # define HAS_QTBUG_95434
82 #endif
83 #include <QKeyEvent>
84 #include <QMessageBox>
85 #include <QMimeData>
86 #include <QOpenGLFramebufferObject>
87 #include <QOpenGLWidget>
88 #include <QSurfaceFormat>
89 #include <QTimer>
90 #include <QVariantAnimation>
91 #include <QWheelEvent>
92
93 #include <App/Document.h>
94 #include <App/GeoFeatureGroupExtension.h>
95 #include <Base/Console.h>
96 #include <Base/FileInfo.h>
97 #include <Base/Sequencer.h>
98 #include <Base/Profiler.h>
99 #include <Base/Tools.h>
100 #include <Base/UnitsApi.h>
101 #include <Base/Tools2D.h>
102 #include <Quarter/devices/InputDevice.h>
103 #include <Quarter/eventhandlers/EventFilter.h>
104 #include <Gui/BitmapFactory.h>
105
106 #include "View3DInventorViewer.h"
107 #include "Application.h"
108 #include "Command.h"
109 #include "Document.h"
110 #include "GLPainter.h"
111 #include "Inventor/SoAxisCrossKit.h"
112 #include "Inventor/SoFCBackgroundGradient.h"
113 #include "Inventor/SoFCBoundingBox.h"
114 #include "MainWindow.h"
115 #include "Multisample.h"
116 #include "NaviCube.h"
117 #include "Navigation/NavigationStyle.h"
118 #include "Navigation/GestureNavigationStyle.h"
119 #include "Navigation/SiemensNXNavigationStyle.h"
120 #include "Selection.h"
121 #include "SoDevicePixelRatioElement.h"
122 #include "SoFCDB.h"
123 #include "SoFCInteractiveElement.h"
124 #include "SoFCOffscreenRenderer.h"
125 #include "SoFCSelection.h"
126 #include "SoFCSelectionAction.h"
127 #include "SoFCUnifiedSelection.h"
128 #include "SoFCVectorizeSVGAction.h"
129 #include "SoFCVectorizeU3DAction.h"
130 #include "SoTouchEvents.h"
131 #include "SpaceballEvent.h"
132 #include "View3DInventorRiftViewer.h"
133 #include "View3DViewerPy.h"
134 #include "ViewParams.h"
135 #include "ViewProvider.h"
136 #include "ViewProviderDocumentObject.h"
137 #include "ViewProviderLink.h"
138 #include "Navigation/NavigationAnimator.h"
139 #include "Navigation/NavigationAnimation.h"
140 #include "Utilities.h"
141
142 #include <Inventor/nodes/SoRotation.h>
143 #include <Inventor/nodes/SoTransformSeparator.h>
144 #include <Inventor/So3DAnnotation.h>
145
146
147 FC_LOG_LEVEL_INIT("3DViewer", true, true)
148
149 // #define FC_LOGGING_CB
150
151 using namespace Gui;
152
153 /*!
154 As ProgressBar has no chance to control the incoming Qt events of Quarter so we need to stop
155 the event handling to prevent the scenegraph from being selected or deselected
156 while the progress bar is running.
157 */
158 class Gui::ViewerEventFilter: public QObject
159 {
160 public:
161 ViewerEventFilter()
162 : longPressTimer(new QTimer(this))
163 {
164 longPressTimer->setSingleShot(true);
165 connect(longPressTimer, &QTimer::timeout, [this]() {
166 if (currentViewer) {
167 triggerClarifySelection();
168 }
169 });
170 }
171 ~ViewerEventFilter() override = default;
172
173 private:
174 void triggerClarifySelection()
175 {
176 // reset navigation state so button1down doesn't stay stuck ie. gh issue #29090
177 // (the blocking QMenu::exec in ClarifySelection steals the LMB release)
178 if (currentViewer) {
179 if (auto* nav = currentViewer->navigationStyle()) {
180 nav->resetButtonState();
181 }
182 }
183 Gui::Command::runCommand(Gui::Command::Gui, "Gui.runCommand('Std_ClarifySelection')");
184 }
185
186 bool shouldEnableLongPress(View3DInventorViewer* viewer, const QPoint& pos, bool ctrlPressed) const
187 {
188 bool enabled = App::GetApplication()
189 .GetParameterGroupByPath("User parameter:BaseApp/Preferences/View")
190 ->GetBool("EnableLongPressClarifySelection", true);
191 if (!enabled) {
192 return false;
193 }
194
195 // check edit mode and view provider editing (for example transform manipulator)
196 if (viewer->isEditing() || viewer->isEditingViewProvider()) {
197 return false;
198 }
199
200 if (auto* navStyle = viewer->navigationStyle()) {
201 // reject if navigation style requires ctrl and it's not pressed or we're under a dragger
202 if ((navStyle->clarifySelectionMode() == NavigationStyle::ClarifySelectionMode::Ctrl
203 && !ctrlPressed)
204 || navStyle->isDraggerUnderCursor(SbVec2s(pos.x(), pos.y()))) {
205 return false;
206 }
207 }
208
209 return true;
210 }
211
212 QTimer* longPressTimer;
213 QPoint pressPosition;
214 View3DInventorViewer* currentViewer = nullptr;
215
216 public:
217 bool eventFilter(QObject* obj, QEvent* event) override
218 {
219 // Bug #0000607: Some mice also support horizontal scrolling which however might
220 // lead to some unwanted zooming when pressing the MMB for panning.
221 // Thus, we filter out horizontal scrolling.
222 if (event->type() == QEvent::Wheel) {
223 auto we = static_cast<QWheelEvent*>(event); // NOLINT
224 if (qAbs(we->angleDelta().x()) > qAbs(we->angleDelta().y())) {
225 return true;
226 }
227 }
228 else if (event->type() == QEvent::KeyPress) {
229 auto ke = static_cast<QKeyEvent*>(event); // NOLINT
230 if (ke->matches(QKeySequence::SelectAll)) {
231 auto* viewer3d = static_cast<View3DInventorViewer*>(obj);
232 auto* editingVP = viewer3d->getEditingViewProvider();
233 if (!editingVP || !editingVP->selectAll()) {
234 viewer3d->selectAll();
235 }
236 return true;
237 }
238 }
239
240 if (Base::Sequencer().isRunning() && Base::Sequencer().isBlocking()) {
241 return false;
242 }
243
244 if (event->type() == Spaceball::ButtonEvent::ButtonEventType) {
245 auto buttonEvent = static_cast<Spaceball::ButtonEvent*>(event); // NOLINT
246 if (!buttonEvent) {
247 Base::Console().log("invalid spaceball button event\n");
248 return true;
249 }
250 }
251 else if (event->type() == Spaceball::MotionEvent::MotionEventType) {
252 auto motionEvent = static_cast<Spaceball::MotionEvent*>(event); // NOLINT
253 if (!motionEvent) {
254 Base::Console().log("invalid spaceball motion event\n");
255 return true;
256 }
257 }
258
259 if (event->type() == QEvent::MouseButtonPress) {
260 auto mouseEvent = static_cast<QMouseEvent*>(event);
261 if (mouseEvent->button() == Qt::LeftButton) {
262 currentViewer = static_cast<View3DInventorViewer*>(obj);
263 pressPosition = mouseEvent->pos();
264 bool ctrlPressed = (mouseEvent->modifiers() & Qt::ControlModifier) != 0;
265
266 if (shouldEnableLongPress(currentViewer, pressPosition, ctrlPressed)) {
267 double longPressTimeout = App::GetApplication()
268 .GetParameterGroupByPath(
269 "User parameter:BaseApp/Preferences/View"
270 )
271 ->GetFloat("LongPressTimeout", 1.0);
272 longPressTimer->setInterval(static_cast<int>(longPressTimeout * 1000));
273 longPressTimer->start();
274 }
275 }
276 }
277 else if (event->type() == QEvent::MouseButtonRelease) {
278 auto mouseEvent = static_cast<QMouseEvent*>(event);
279 if (mouseEvent->button() == Qt::LeftButton) {
280 longPressTimer->stop();
281 currentViewer = nullptr;
282 }
283 }
284 else if (event->type() == QEvent::MouseMove) {
285 if (longPressTimer->isActive()) {
286 auto mouseEvent = static_cast<QMouseEvent*>(event);
287 // cancel long press if mouse moved too far (more than 5 pixels)
288 if ((mouseEvent->pos() - pressPosition).manhattanLength() > 5) {
289 longPressTimer->stop();
290 currentViewer = nullptr;
291 }
292 }
293 }
294
295 return false;
296 }
297 };
298
299 class SpaceNavigatorDevice: public Quarter::InputDevice
300 {
301 public:
302 SpaceNavigatorDevice()
303 : InputDevice(nullptr)
304 {}
305 ~SpaceNavigatorDevice() override = default;
306 const SoEvent* translateEvent(QEvent* event) override
307 {
308
309 if (event->type() == Spaceball::MotionEvent::MotionEventType) {
310 auto motionEvent = static_cast<Spaceball::MotionEvent*>(event); // NOLINT
311 if (!motionEvent) {
312 Base::Console().log("invalid spaceball motion event\n");
313 return nullptr;
314 }
315
316 motionEvent->setHandled(true);
317
318 float xTrans {};
319 float yTrans {};
320 float zTrans {};
321 xTrans = static_cast<float>(motionEvent->translationX());
322 yTrans = static_cast<float>(motionEvent->translationY());
323 zTrans = static_cast<float>(motionEvent->translationZ());
324 SbVec3f translationVector(xTrans, yTrans, zTrans);
325
326 constexpr const float rotationConstant(.0001F);
327 SbRotation xRot;
328 SbRotation yRot;
329 SbRotation zRot;
330 xRot.setValue(
331 SbVec3f(1.0, 0.0, 0.0),
332 static_cast<float>(motionEvent->rotationX()) * rotationConstant
333 );
334 yRot.setValue(
335 SbVec3f(0.0, 1.0, 0.0),
336 static_cast<float>(motionEvent->rotationY()) * rotationConstant
337 );
338 zRot.setValue(
339 SbVec3f(0.0, 0.0, 1.0),
340 static_cast<float>(motionEvent->rotationZ()) * rotationConstant
341 );
342
343 auto motion3Event = new SoMotion3Event;
344 motion3Event->setTranslation(translationVector);
345 motion3Event->setRotation(xRot * yRot * zRot);
346 motion3Event->setPosition(this->mousepos);
347
348 return motion3Event;
349 }
350
351 return nullptr;
352 }
353 };
354
355 /** \defgroup View3D 3D Viewer
356 * \ingroup GUI
357 *
358 * The 3D Viewer is one of the major components in a CAD/CAE systems.
359 * Therefore an overview and some remarks to the FreeCAD 3D viewing system.
360 *
361 * \section overview Overview
362 * \todo Overview and complements for the 3D Viewer
363 *
364 * \section trouble Troubleshooting
365 * When it's needed to capture OpenGL function calls then the utility apitrace
366 * can be very useful: https://github.com/apitrace/apitrace/blob/master/docs/USAGE.markdown
367 *
368 * To better locate the problematic code it's possible to add custom log messages.
369 * For the prerequisites check:
370 * https://github.com/apitrace/apitrace/blob/master/docs/USAGE.markdown#
371 * emitting-annotations-to-the-trace
372 * \code
373 * #include <GL/glext.h>
374 * #include <Inventor/C/glue/gl.h>
375 *
376 * void GLRender(SoGLRenderAction* glra)
377 * {
378 * int context = glra->getCacheContext();
379 * const cc_glglue * glue = cc_glglue_instance(context);
380 *
381 * PFNGLPUSHDEBUGGROUPPROC glPushDebugGroup = (PFNGLPUSHDEBUGGROUPPROC)
382 * cc_glglue_getprocaddress(glue, "glPushDebugGroup");
383 * PFNGLDEBUGMESSAGEINSERTARBPROC glDebugMessageInsert = (PFNGLDEBUGMESSAGEINSERTARBPROC)
384 * cc_glglue_getprocaddress(glue, "glDebugMessageInsert");
385 * PFNGLPOPDEBUGGROUPPROC glPopDebugGroup = (PFNGLPOPDEBUGGROUPPROC)
386 * cc_glglue_getprocaddress(glue, "glPopDebugGroup");
387 *
388 * glPushDebugGroup(GL_DEBUG_SOURCE_APPLICATION, 0, -1, __FUNCTION__);
389 * ...
390 * glDebugMessageInsert(GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_OTHER,
391 * 0, GL_DEBUG_SEVERITY_MEDIUM, -1, "begin_blabla");
392 * ...
393 * glDebugMessageInsert(GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_OTHER,
394 * 0, GL_DEBUG_SEVERITY_MEDIUM, -1, "end_blabla");
395 * ...
396 * glPopDebugGroup();
397 * }
398 * \endcode
399 */
400
401
402 // *************************************************************************
403
404 View3DInventorViewer::View3DInventorViewer(QWidget* parent, const QOpenGLWidget* sharewidget)
405 : Quarter::SoQTQuarterAdaptor(parent, sharewidget)
406 , SelectionObserver(false, ResolveMode::NoResolve)
407 , editViewProvider(nullptr)
408 , objectGroup(nullptr)
409 , navigation(nullptr)
410 , renderType(Native)
411 , framebuffer(nullptr)
412 , axisCross(nullptr)
413 , axisGroup(nullptr)
414 , rotationCenterGroup(nullptr)
415 , editing(false)
416 , redirected(false)
417 , allowredir(false)
418 , overrideMode("As Is")
419 , _viewerPy(nullptr)
420 {
421 init();
422 }
423
424 View3DInventorViewer::View3DInventorViewer(
425 const QSurfaceFormat& format,
426 QWidget* parent,
427 const QOpenGLWidget* sharewidget
428 )
429 : Quarter::SoQTQuarterAdaptor(format, parent, sharewidget)
430 , SelectionObserver(false, ResolveMode::NoResolve)
431 , editViewProvider(nullptr)
432 , objectGroup(nullptr)
433 , navigation(nullptr)
434 , renderType(Native)
435 , framebuffer(nullptr)
436 , axisCross(nullptr)
437 , axisGroup(nullptr)
438 , rotationCenterGroup(nullptr)
439 , editing(false)
440 , redirected(false)
441 , allowredir(false)
442 , overrideMode("As Is")
443 , _viewerPy(nullptr)
444 {
445 init();
446 }
447
448 void View3DInventorViewer::init()
449 {
450 static bool _cacheModeInited;
451 if (!_cacheModeInited) {
452 _cacheModeInited = true;
453 pcViewProviderRoot = nullptr;
454 setRenderCache(-1);
455 }
456
457 shading = true;
458 fpsEnabled = false;
459 vboEnabled = false;
460
461 attachSelection();
462
463 // Coin should not clear the pixel-buffer, so the background image
464 // is not removed.
465 this->setClearWindow(false);
466
467 // setting up the defaults for the spin rotation
468 initialize();
469
470 #ifdef TRACY_ENABLE
471 SoProfiler::init();
472 SoProfiler::enable(TRUE);
473 #endif
474
475 // NOLINTBEGIN
476 auto cam = new SoOrthographicCamera;
477 cam->position = SbVec3f(0, 0, 1);
478 cam->height = 1;
479 cam->nearDistance = 0.5;
480 cam->farDistance = 1.5;
481 // NOLINTEND
482
483 // setup light sources
484 SoDirectionalLight* hl = this->getHeadlight();
485
486 environment = new SoEnvironment();
487 environment->ref();
488 environment->setName("environment");
489
490 backlight = new SoDirectionalLight();
491 backlight->ref();
492 backlight->setName("backlight");
493 backlight->direction.setValue(-hl->direction.getValue());
494 backlight->on.setValue(false); // by default off
495
496 fillLight = new SoDirectionalLight();
497 fillLight->ref();
498 fillLight->setName("filllight");
499 fillLight->direction.setValue(-0.60F, -0.35F, -0.79F);
500 fillLight->intensity.setValue(0.6F);
501 fillLight->color.setValue(0.95F, 0.95F, 1.0F);
502 fillLight->on.setValue(false); // by default off
503
504 // Set up background scenegraph with image in it.
505 backgroundroot = new SoSeparator;
506 backgroundroot->ref();
507 this->backgroundroot->addChild(cam);
508 this->backgroundroot->setName("backgroundroot");
509
510 // Background stuff
511 pcBackGround = new SoFCBackgroundGradient;
512 pcBackGround->ref();
513
514 // Set up foreground, overlaid scenegraph.
515 this->foregroundroot = new SoSeparator;
516 this->foregroundroot->ref();
517 this->foregroundroot->setName("foregroundroot");
518
519 auto lm = new SoLightModel;
520 lm->model = SoLightModel::BASE_COLOR;
521
522 auto bc = new SoBaseColor;
523 bc->rgb = SbColor(1, 1, 0);
524
525 // NOLINTBEGIN
526 cam = new SoOrthographicCamera;
527 cam->position = SbVec3f(0, 0, 5);
528 cam->height = 10;
529 cam->nearDistance = 0;
530 cam->farDistance = 10;
531 // NOLINTEND
532
533 lightRotation = new SoRotation;
534 lightRotation->ref();
535 lightRotation->rotation.connectFrom(&cam->orientation);
536
537 this->foregroundroot->addChild(cam);
538 this->foregroundroot->addChild(lm);
539 this->foregroundroot->addChild(bc);
540
541 auto threePointLightingSeparator = new SoTransformSeparator;
542 threePointLightingSeparator->addChild(lightRotation);
543 threePointLightingSeparator->addChild(this->fillLight);
544
545 this->foregroundroot->addChild(cam);
546
547 // NOTE: For every mouse click event the SoFCUnifiedSelection searches for the picked
548 // point which causes a certain slow-down because for all objects the primitives
549 // must be created. Using an SoSeparator avoids this drawback.
550 selectionRoot = new Gui::SoFCUnifiedSelection();
551 selectionRoot->applySettings();
552
553 // set the ViewProvider root node
554 pcViewProviderRoot = selectionRoot;
555 pcViewProviderRoot->addChild(threePointLightingSeparator);
556 pcViewProviderRoot->addChild(environment);
557
558 // add a global hidden anchor object to ensure transparent objects work correctly
559 // in empty scenes - OpenInventor's two-pass transparency rendering requires at least
560 // one opaque object to properly initialize the depth buffer. so this fixes transparency
561 // issues for image planes, planes, and other transparent geometry.
562 // wrap in SoSkipBoundingGroup to exclude from bounding box calculations
563 // check #15192 #24003
564 auto hiddenAnchor = new SoSkipBoundingGroup();
565 hiddenAnchor->mode = SoSkipBoundingGroup::EXCLUDE_BBOX;
566 auto hiddenSep = new SoSeparator();
567 auto hiddenScale = new SoScale();
568 hiddenScale->scaleFactor = SbVec3f(0, 0, 0);
569 auto hiddenCube = new SoCube();
570 hiddenSep->addChild(hiddenScale);
571 hiddenSep->addChild(hiddenCube);
572 hiddenAnchor->addChild(hiddenSep);
573 pcViewProviderRoot->addChild(hiddenAnchor);
574
575 // increase refcount before passing it to setScenegraph(), to avoid
576 // premature destruction
577 pcViewProviderRoot->ref();
578 setSceneGraph(pcViewProviderRoot);
579 // Event callback node
580 pEventCallback = new SoEventCallback();
581 pEventCallback->setUserData(this);
582 pEventCallback->ref();
583 pcViewProviderRoot->addChild(pEventCallback);
584 pEventCallback->addEventCallback(SoEvent::getClassTypeId(), handleEventCB, this);
585
586 dimensionRoot = new SoSwitch(SO_SWITCH_NONE);
587 dimensionRoot->setName("RootDimensions");
588 pcViewProviderRoot->addChild(dimensionRoot);
589 auto dimensions3d = new SoSwitch();
590 dimensions3d->setName("_3dDimensions");
591 dimensionRoot->addChild(dimensions3d); // first one will be for the 3d dimensions.
592 auto dimensionsDelta = new SoSwitch();
593 dimensionsDelta->setName("DeltaDimensions");
594 dimensionRoot->addChild(dimensionsDelta); // second one for the delta dimensions.
595
596 // This is a callback node that logs all action that traverse the Inventor tree.
597 #if defined(FC_DEBUG) && defined(FC_LOGGING_CB)
598 SoCallback* cb = new SoCallback;
599 cb->setCallback(interactionLoggerCB, this);
600 pcViewProviderRoot->addChild(cb);
601 #endif
602
603 inventorSelection = std::make_unique<View3DInventorSelection>(selectionRoot);
604
605 pcClipPlane = nullptr;
606
607 pcEditingRoot = new SoSeparator;
608 pcEditingRoot->ref();
609 pcEditingRoot->setName("EditingRoot");
610 pcEditingTransform = new SoTransform;
611 pcEditingTransform->ref();
612 pcEditingTransform->setName("EditingTransform");
613 restoreEditingRoot = false;
614 pcEditingRoot->addChild(pcEditingTransform);
615 pcViewProviderRoot->addChild(pcEditingRoot);
616
617 // Create group for the physical object
618 objectGroup = new SoGroup();
619 objectGroup->ref();
620 objectGroup->setName("ObjectGroup");
621 pcViewProviderRoot->addChild(objectGroup);
622
623 // Set our own render action which show a bounding box if
624 // the SoFCSelection::BOX style is set
625 //
626 // Important note:
627 // When creating a new GL render action we have to copy over the cache context id
628 // because otherwise we may get strange rendering behaviour. For more details see
629 // https://forum.freecad.org/viewtopic.php?f=10&t=7486&start=120#p74398 and for
630 // the fix and some details what happens behind the scene have a look at this
631 // https://forum.freecad.org/viewtopic.php?f=10&t=7486&p=74777#p74736
632 uint32_t id = this->getSoRenderManager()->getGLRenderAction()->getCacheContext();
633 auto boxSelectionAction = new SoBoxSelectionRenderAction;
634 this->getSoRenderManager()->setGLRenderAction(boxSelectionAction);
635 this->getSoRenderManager()->getGLRenderAction()->setCacheContext(id);
636
637 #ifdef TRACY_ENABLE
638 boxSelectionAction->enableElement(
639 SoProfilerElement::getClassTypeId(),
640 SoProfilerElement::getClassStackIndex()
641 );
642 #endif
643
644 // set the transparency and antialiasing settings
645 getSoRenderManager()->getGLRenderAction()->setTransparencyType(
646 SoGLRenderAction::SORTED_OBJECT_SORTED_TRIANGLE_BLEND
647 );
648
649 // Settings
650 setSeekTime(0.4F); // NOLINT
651
652 if (!isSeekValuePercentage()) {
653 setSeekValueAsPercentage(true);
654 }
655
656 setSeekDistance(100); // NOLINT
657 setViewing(false);
658
659 setBackgroundColor(QColor(25, 25, 25)); // NOLINT
660 setGradientBackground(Background::LinearGradient);
661
662 // set some callback functions for user interaction
663 addStartCallback(interactionStartCB);
664 addFinishCallback(interactionFinishCB);
665
666 // filter a few qt events
667 viewerEventFilter = new ViewerEventFilter;
668 installEventFilter(viewerEventFilter);
669 #if defined(USE_3DCONNEXION_NAVLIB)
670 ParameterGrp::handle hViewGrp = App::GetApplication().GetParameterGroupByPath(
671 "User parameter:BaseApp/Preferences/View"
672 );
673 if (hViewGrp->GetBool("LegacySpaceMouseDevices", false)) {
674 getEventFilter()->registerInputDevice(new SpaceNavigatorDevice);
675 }
676 #else
677 getEventFilter()->registerInputDevice(new SpaceNavigatorDevice);
678 #endif
679 getEventFilter()->registerInputDevice(new GesturesDevice(this));
680
681 try {
682 this->grabGesture(Qt::PanGesture);
683 this->grabGesture(Qt::PinchGesture);
684 }
685 catch (Base::Exception& e) {
686 Base::Console().warning("Failed to set up gestures. Error: %s\n", e.what());
687 }
688 catch (...) {
689 Base::Console().warning("Failed to set up gestures. Unknown error.\n");
690 }
691
692 // create the cursors
693 createStandardCursors();
694 connect(
695 this,
696 &View3DInventorViewer::devicePixelRatioChanged,
697 this,
698 &View3DInventorViewer::createStandardCursors
699 );
700
701 naviCube = new NaviCube(this);
702 naviCubeEnabled = true;
703
704 updateColors();
705 }
706
707 View3DInventorViewer::~View3DInventorViewer()
708 {
709 // to prevent following OpenGL error message: "Texture is not valid in the current context.
710 // Texture has not been destroyed"
711 aboutToDestroyGLContext();
712
713 // It can happen that a document has several MDI views and when the about to be
714 // closed 3D view is in edit mode the corresponding view provider must be restored
715 // because otherwise it might be left in a broken state
716 // See https://forum.freecad.org/viewtopic.php?f=3&t=39720
717 if (restoreEditingRoot) {
718 resetEditingRoot(false);
719 }
720
721 // cleanup
722 this->backgroundroot->unref();
723 this->backgroundroot = nullptr;
724 this->foregroundroot->unref();
725 this->foregroundroot = nullptr;
726 this->pcBackGround->unref();
727 this->pcBackGround = nullptr;
728
729 setSceneGraph(nullptr);
730 this->pEventCallback->unref();
731 this->pEventCallback = nullptr;
732 // Note: It can happen that there is still someone who references
733 // the root node but isn't destroyed when closing this viewer so
734 // that it prevents all children from being deleted. To reduce this
735 // likelihood we explicitly remove all child nodes now.
736 coinRemoveAllChildren(this->pcViewProviderRoot);
737 this->pcViewProviderRoot->unref();
738 this->pcViewProviderRoot = nullptr;
739 this->objectGroup->unref();
740 this->objectGroup = nullptr;
741 this->backlight->unref();
742 this->backlight = nullptr;
743 this->fillLight->unref();
744 this->fillLight = nullptr;
745 this->environment->unref();
746 this->environment = nullptr;
747
748 inventorSelection.reset(nullptr);
749
750 this->pcEditingRoot->unref();
751 this->pcEditingTransform->unref();
752
753 if (this->pcClipPlane) {
754 this->pcClipPlane->unref();
755 }
756
757 delete this->navigation;
758
759 // Note: When closing the application the main window doesn't exist any more.
760 if (getMainWindow()) {
761 getMainWindow()->setPaneText(2, QLatin1String(""));
762 }
763
764 detachSelection();
765
766 removeEventFilter(viewerEventFilter);
767 delete viewerEventFilter;
768
769 if (_viewerPy) {
770 static_cast<View3DInventorViewerPy*>(_viewerPy)->_viewer = nullptr;
771 Py_DECREF(_viewerPy);
772 }
773
774 // In the init() function we have overridden the default SoGLRenderAction with our
775 // own instance of SoBoxSelectionRenderAction and SoRenderManager destroyed the default.
776 // But it does this only once so that now we have to explicitly destroy our instance in
777 // order to free the memory.
778 SoGLRenderAction* glAction = this->getSoRenderManager()->getGLRenderAction();
779 this->getSoRenderManager()->setGLRenderAction(nullptr);
780 delete glAction;
781 }
782
783 void View3DInventorViewer::createStandardCursors()
784 {
785 QPixmap panPixmap = BitmapFactory().pixmapFromSvg("cursor-pan", QSize(16, 16));
786 QPixmap spinPixmap = BitmapFactory().pixmapFromSvg("cursor-rotate", QSize(16, 16));
787 QPixmap zoomPixmap = BitmapFactory().pixmapFromSvg("cursor-zoom", QSize(16, 16));
788
789 this->panCursor = QCursor(panPixmap, 8, 8);
790 this->spinCursor = QCursor(spinPixmap, 8, 8);
791 this->zoomCursor = QCursor(zoomPixmap, 8, 8);
792 }
793
794 void View3DInventorViewer::aboutToDestroyGLContext()
795 {
796 if (naviCube) {
797 if (auto gl = qobject_cast<QOpenGLWidget*>(this->viewport())) {
798 gl->makeCurrent();
799 }
800 delete naviCube;
801 naviCube = nullptr;
802 naviCubeEnabled = false;
803 }
804 }
805
806 void View3DInventorViewer::setDocument(Gui::Document* pcDocument)
807 {
808 // write the document the viewer belongs to the selection node
809 guiDocument = pcDocument;
810 selectionRoot->pcDocument = pcDocument;
811 inventorSelection->setDocument(pcDocument);
812
813 if (pcDocument) {
814 const auto& sels
815 = Selection().getSelection(pcDocument->getDocument()->getName(), ResolveMode::NoResolve);
816 for (auto& sel : sels) {
817 SelectionChanges Chng(SelectionChanges::ShowSelection, sel.DocName, sel.FeatName, sel.SubName);
818 onSelectionChanged(Chng);
819 }
820 }
821 }
822
823 Document* View3DInventorViewer::getDocument()
824 {
825 return guiDocument;
826 }
827
828
829 void View3DInventorViewer::initialize()
830 {
831 navigation = new CADNavigationStyle();
832 navigation->setViewer(this);
833
834 this->axiscrossEnabled = true;
835 this->axiscrossSize = 10; // NOLINT
836 }
837
838 /// @cond DOXERR
839 void View3DInventorViewer::onSelectionChanged(const SelectionChanges& reason)
840 {
841 if (!getDocument()) {
842 return;
843 }
844
845 SelectionChanges Reason(reason);
846
847 if (Reason.pDocName && *Reason.pDocName
848 && strcmp(getDocument()->getDocument()->getName(), Reason.pDocName) != 0) {
849 return;
850 }
851
852 switch (Reason.Type) {
853 case SelectionChanges::ShowSelection:
854 case SelectionChanges::HideSelection:
855 if (Reason.Type == SelectionChanges::ShowSelection) {
856 Reason.Type = SelectionChanges::AddSelection;
857 }
858 else {
859 Reason.Type = SelectionChanges::RmvSelection;
860 }
861 // fall through
862 case SelectionChanges::SetPreselect:
863 if (Reason.SubType != SelectionChanges::MsgSource::TreeView) {
864 break;
865 }
866 // fall through
867 case SelectionChanges::RmvPreselect:
868 case SelectionChanges::RmvPreselectSignal:
869 case SelectionChanges::SetSelection:
870 case SelectionChanges::AddSelection:
871 case SelectionChanges::RmvSelection:
872 case SelectionChanges::ClrSelection:
873 inventorSelection->checkGroupOnTop(Reason);
874 break;
875 case SelectionChanges::SetPreselectSignal:
876 break;
877 default:
878 return;
879 }
880
881 if (Reason.Type == SelectionChanges::RmvPreselect
882 || Reason.Type == SelectionChanges::RmvPreselectSignal
883 || Reason.Type == SelectionChanges::SetPreselect) {
884 SoFCPreselectionAction preselectionAction(Reason);
885 preselectionAction.apply(pcViewProviderRoot);
886 }
887 else {
888 SoFCSelectionAction selectionAction(Reason);
889 selectionAction.apply(pcViewProviderRoot);
890 }
891 }
892 /// @endcond
893
894 bool View3DInventorViewer::searchNode(SoNode* node) const
895 {
896 SoSearchAction searchAction;
897 searchAction.setNode(node);
898 searchAction.setInterest(SoSearchAction::FIRST);
899 searchAction.apply(this->getSceneGraph());
900 SoPath* selectionPath = searchAction.getPath();
901 return selectionPath != nullptr;
902 }
903
904 bool View3DInventorViewer::hasViewProvider(ViewProvider* pcProvider) const
905 {
906 return _ViewProviderSet.find(pcProvider) != _ViewProviderSet.end();
907 }
908
909 bool View3DInventorViewer::containsViewProvider(const ViewProvider* vp) const
910 {
911 SoSearchAction sa;
912 sa.setNode(vp->getRoot());
913 sa.setSearchingAll(false);
914 sa.apply(getSoRenderManager()->getSceneGraph());
915 return sa.getPath() != nullptr;
916 }
917
918 /// adds an ViewProvider to the view, e.g. from a feature
919 void View3DInventorViewer::addViewProvider(ViewProvider* pcProvider)
920 {
921 SoSeparator* root = pcProvider->getRoot();
922
923 if (root) {
924 if (pcProvider->canAddToSceneGraph()) {
925 // Add to the physical object group if related to the physical object otherwise add to
926 // the scene graph
927 if (pcProvider->isPartOfPhysicalObject()) {
928 objectGroup->addChild(root);
929 }
930 else {
931 pcViewProviderRoot->addChild(root);
932 }
933 }
934 _ViewProviderMap[root] = pcProvider;
935 }
936
937 if (SoSeparator* fore = pcProvider->getFrontRoot()) {
938 foregroundroot->addChild(fore);
939 }
940
941 if (SoSeparator* back = pcProvider->getBackRoot()) {
942 backgroundroot->addChild(back);
943 }
944
945 pcProvider->setOverrideMode(this->getOverrideMode());
946 _ViewProviderSet.insert(pcProvider);
947 }
948
949 void View3DInventorViewer::removeViewProvider(ViewProvider* pcProvider)
950 {
951 if (this->editViewProvider == pcProvider) {
952 resetEditingViewProvider();
953 }
954
955 SoSeparator* root = pcProvider->getRoot();
956
957 if (root) {
958 int index = objectGroup->findChild(root);
959 if (index >= 0) {
960 objectGroup->removeChild(index);
961 }
962
963 index = pcViewProviderRoot->findChild(root);
964 if (index >= 0) {
965 pcViewProviderRoot->removeChild(index);
966 }
967 _ViewProviderMap.erase(root);
968 }
969
970 if (SoSeparator* fore = pcProvider->getFrontRoot()) {
971 foregroundroot->removeChild(fore);
972 }
973
974 if (SoSeparator* back = pcProvider->getBackRoot()) {
975 backgroundroot->removeChild(back);
976 }
977
978 _ViewProviderSet.erase(pcProvider);
979 }
980
981 void View3DInventorViewer::setEditingTransform(const Base::Matrix4D& mat)
982 {
983 // NOLINTBEGIN
984 if (pcEditingTransform) {
985 double dMtrx[16];
986 mat.getGLMatrix(dMtrx);
987 pcEditingTransform->setMatrix(SbMatrix(
988 dMtrx[0],
989 dMtrx[1],
990 dMtrx[2],
991 dMtrx[3],
992 dMtrx[4],
993 dMtrx[5],
994 dMtrx[6],
995 dMtrx[7],
996 dMtrx[8],
997 dMtrx[9],
998 dMtrx[10],
999 dMtrx[11],
1000 dMtrx[12],
1001 dMtrx[13],
1002 dMtrx[14],
1003 dMtrx[15]
1004 ));
1005 }
1006 // NOLINTEND
1007 }
1008
1009 SoNode* View3DInventorViewer::getEditingRoot() const
1010 {
1011 return pcEditingRoot;
1012 }
1013
1014 void View3DInventorViewer::setupEditingRoot(SoNode* node, const Base::Matrix4D* mat)
1015 {
1016 if (!editViewProvider) {
1017 return;
1018 }
1019
1020 resetEditingRoot(false);
1021 if (mat) {
1022 setEditingTransform(*mat);
1023 }
1024 else {
1025 setEditingTransform(getDocument()->getEditingTransform());
1026 }
1027 if (node) {
1028 restoreEditingRoot = false;
1029 pcEditingRoot->addChild(node);
1030 return;
1031 }
1032 restoreEditingRoot = true;
1033 auto root = editViewProvider->getRoot();
1034 for (int i = 0, count = root->getNumChildren(); i < count; ++i) {
1035 SoNode* node = root->getChild(i);
1036 if (node != editViewProvider->getTransformNode()) {
1037 pcEditingRoot->addChild(node);
1038 }
1039 }
1040 coinRemoveAllChildren(root);
1041 ViewProviderLink::updateLinks(editViewProvider);
1042 }
1043
1044 void View3DInventorViewer::resetEditingRoot(bool updateLinks)
1045 {
1046 if (!editViewProvider || pcEditingRoot->getNumChildren() <= 1) {
1047 return;
1048 }
1049 if (!restoreEditingRoot) {
1050 pcEditingRoot->getChildren()->truncate(1);
1051 return;
1052 }
1053 restoreEditingRoot = false;
1054 auto root = editViewProvider->getRoot();
1055 if (root->getNumChildren()) {
1056 FC_ERR("WARNING!!! Editing view provider root node is tampered");
1057 }
1058 root->addChild(editViewProvider->getTransformNode());
1059 for (int i = 1, count = pcEditingRoot->getNumChildren(); i < count; ++i) {
1060 root->addChild(pcEditingRoot->getChild(i));
1061 }
1062 pcEditingRoot->getChildren()->truncate(1);
1063
1064 // handle exceptions eventually raised by ViewProviderLink
1065 try {
1066 if (updateLinks) {
1067 ViewProviderLink::updateLinks(editViewProvider);
1068 }
1069 }
1070 catch (const Py::Exception& e) {
1071 /* coverity[UNCAUGHT_EXCEPT] Uncaught exception */
1072 // Coverity created several reports when removeViewProvider()
1073 // is used somewhere in a destructor which indirectly invokes
1074 // resetEditingRoot().
1075 // Now theoretically Py::type can throw an exception which nowhere
1076 // will be handled and thus terminates the application. So, add an
1077 // extra try/catch block here.
1078 try {
1079 Py::Object py = Py::type(e);
1080 if (py.isString()) {
1081 Py::String str(py);
1082 Base::Console().warning("%s\n", str.as_std_string("utf-8").c_str());
1083 }
1084 else {
1085 Py::String str(py.repr());
1086 Base::Console().warning("%s\n", str.as_std_string("utf-8").c_str());
1087 }
1088 // Prints message to console window if we are in interactive mode
1089 PyErr_Print();
1090 }
1091 catch (Py::Exception& e) {
1092 e.clear();
1093 Base::Console().error(
1094 "Unexpected exception raised in View3DInventorViewer::resetEditingRoot\n"
1095 );
1096 }
1097 }
1098 }
1099
1100 SoPickedPoint* View3DInventorViewer::getPointOnRay(const SbVec2s& pos, const ViewProvider* vp) const
1101 {
1102 SoPath* path {};
1103 if (vp == editViewProvider && pcEditingRoot->getNumChildren() > 1) {
1104 path = new SoPath(1);
1105 path->ref();
1106 path->append(pcEditingRoot);
1107 }
1108 else {
1109 // first get the path to this node and calculate the current transformation
1110 SoSearchAction sa;
1111 sa.setNode(vp->getRoot());
1112 sa.setSearchingAll(true);
1113 sa.apply(getSoRenderManager()->getSceneGraph());
1114 path = sa.getPath();
1115 if (!path) {
1116 return nullptr;
1117 }
1118 path->ref();
1119 }
1120 SoGetMatrixAction gm(getSoRenderManager()->getViewportRegion());
1121 gm.apply(path);
1122
1123 auto trans = new SoTransform;
1124 trans->setMatrix(gm.getMatrix());
1125 trans->ref();
1126
1127 // build a temporary scenegraph only keeping this viewproviders nodes and the accumulated
1128 // transformation
1129 auto root = new SoSeparator;
1130 root->ref();
1131 root->addChild(getSoRenderManager()->getCamera());
1132 root->addChild(trans);
1133 root->addChild(path->getTail());
1134
1135 // get the picked point
1136 SoRayPickAction rp(getSoRenderManager()->getViewportRegion());
1137 rp.setPoint(pos);
1138 rp.setRadius(getPickRadius());
1139 rp.apply(root);
1140 root->unref();
1141 trans->unref();
1142 path->unref();
1143
1144 SoPickedPoint* pick = rp.getPickedPoint();
1145 return (pick ? new SoPickedPoint(*pick) : nullptr);
1146 }
1147
1148 SoPickedPoint* View3DInventorViewer::getPointOnRay(
1149 const SbVec3f& pos,
1150 const SbVec3f& dir,
1151 const ViewProvider* vp
1152 ) const
1153 {
1154 // Note: There seems to be a bug with setRay() which causes SoRayPickAction
1155 // to fail to get intersections between the ray and a line
1156
1157 SoPath* path {};
1158 if (vp == editViewProvider && pcEditingRoot->getNumChildren() > 1) {
1159 path = new SoPath(1);
1160 path->ref();
1161 path->append(pcEditingRoot);
1162 }
1163 else {
1164 // first get the path to this node and calculate the current setTransformation
1165 SoSearchAction sa;
1166 sa.setNode(vp->getRoot());
1167 sa.setSearchingAll(true);
1168 sa.apply(getSoRenderManager()->getSceneGraph());
1169 path = sa.getPath();
1170 if (!path) {
1171 return nullptr;
1172 }
1173 path->ref();
1174 }
1175 SoGetMatrixAction gm(getSoRenderManager()->getViewportRegion());
1176 gm.apply(path);
1177
1178 // build a temporary scenegraph only keeping this viewproviders nodes and the accumulated
1179 // transformation
1180 auto trans = new SoTransform;
1181 trans->ref();
1182 trans->setMatrix(gm.getMatrix());
1183
1184 auto root = new SoSeparator;
1185 root->ref();
1186 root->addChild(getSoRenderManager()->getCamera());
1187 root->addChild(trans);
1188 root->addChild(path->getTail());
1189
1190 // get the picked point
1191 SoRayPickAction rp(getSoRenderManager()->getViewportRegion());
1192 rp.setRay(pos, dir);
1193 rp.setRadius(getPickRadius());
1194 rp.apply(root);
1195 root->unref();
1196 trans->unref();
1197 path->unref();
1198
1199 // returns a copy of the point
1200 SoPickedPoint* pick = rp.getPickedPoint();
1201 // return (pick ? pick->copy() : 0); // needs the same instance of CRT under MS Windows
1202 return (pick ? new SoPickedPoint(*pick) : nullptr);
1203 }
1204
1205 void View3DInventorViewer::setEditingViewProvider(Gui::ViewProvider* vp, int ModNum)
1206 {
1207 this->editViewProvider = vp;
1208 this->editViewProvider->setEditViewer(this, ModNum);
1209
1210 #if (COIN_MAJOR_VERSION * 100 + COIN_MINOR_VERSION * 10 + COIN_MICRO_VERSION < 403)
1211 this->navigation->findBoundingSphere();
1212 #endif
1213
1214 addEventCallback(SoEvent::getClassTypeId(), Gui::ViewProvider::eventCallback, this->editViewProvider);
1215 }
1216
1217 /// reset from edit mode
1218 void View3DInventorViewer::resetEditingViewProvider()
1219 {
1220 if (this->editViewProvider) {
1221
1222 // In case the event action still has grabbed a node when leaving edit mode
1223 // force to release it now
1224 SoEventManager* mgr = getSoEventManager();
1225 SoHandleEventAction* heaction = mgr->getHandleEventAction();
1226 if (heaction && heaction->getGrabber()) {
1227 heaction->releaseGrabber();
1228 }
1229
1230 resetEditingRoot();
1231
1232 this->editViewProvider->unsetEditViewer(this);
1233 removeEventCallback(
1234 SoEvent::getClassTypeId(),
1235 Gui::ViewProvider::eventCallback,
1236 this->editViewProvider
1237 );
1238 this->editViewProvider = nullptr;
1239 }
1240 }
1241
1242 /// reset from edit mode
1243 bool View3DInventorViewer::isEditingViewProvider() const
1244 {
1245 return this->editViewProvider != nullptr;
1246 }
1247
1248 /// return currently editing view provider
1249 ViewProvider* View3DInventorViewer::getEditingViewProvider() const
1250 {
1251 return this->editViewProvider;
1252 }
1253
1254 /// display override mode
1255 void View3DInventorViewer::setOverrideMode(const std::string& mode)
1256 {
1257 if (mode == overrideMode) {
1258 return;
1259 }
1260
1261 overrideMode = mode;
1262
1263 auto document = getDocument();
1264 if (!document) {
1265 return;
1266 }
1267
1268 auto views = document->getViewProvidersOfType(Gui::ViewProvider::getClassTypeId());
1269 if (mode == "No Shading") {
1270 this->shading = false;
1271 std::string flatLines = "Flat Lines";
1272 for (auto view : views) {
1273 view->setOverrideMode(flatLines);
1274 }
1275 this->getSoRenderManager()->setRenderMode(SoRenderManager::AS_IS);
1276 }
1277 else if (mode == "Hidden Line") {
1278 this->shading = true;
1279 std::string shaded = "Shaded";
1280 for (auto view : views) {
1281 view->setOverrideMode(shaded);
1282 }
1283 this->getSoRenderManager()->setRenderMode(SoRenderManager::HIDDEN_LINE);
1284 }
1285 else {
1286 this->shading = true;
1287 for (auto view : views) {
1288 view->setOverrideMode(mode);
1289 }
1290 this->getSoRenderManager()->setRenderMode(SoRenderManager::AS_IS);
1291 }
1292 }
1293
1294 /// update override mode. doesn't affect providers
1295 void View3DInventorViewer::updateOverrideMode(const std::string& mode)
1296 {
1297 if (mode == overrideMode) {
1298 return;
1299 }
1300
1301 overrideMode = mode;
1302
1303 if (mode == "No Shading") {
1304 this->shading = false;
1305 this->getSoRenderManager()->setRenderMode(SoRenderManager::AS_IS);
1306 }
1307 else if (mode == "Hidden Line") {
1308 this->shading = true;
1309 this->getSoRenderManager()->setRenderMode(SoRenderManager::HIDDEN_LINE);
1310 }
1311 else {
1312 this->shading = true;
1313 this->getSoRenderManager()->setRenderMode(SoRenderManager::AS_IS);
1314 }
1315 }
1316
1317 void View3DInventorViewer::setViewportCB(void* ud, SoAction* action)
1318 {
1319 Q_UNUSED(ud)
1320 // Make sure to override the value set inside SoOffscreenRenderer::render()
1321 if (action->isOfType(SoGLRenderAction::getClassTypeId())) {
1322 SoFCOffscreenRenderer& renderer = SoFCOffscreenRenderer::instance();
1323 const SbViewportRegion& vp = renderer.getViewportRegion();
1324 SoViewportRegionElement::set(action->getState(), vp);
1325 static_cast<SoGLRenderAction*>(action)->setViewportRegion(vp); // NOLINT
1326 }
1327 }
1328
1329 void View3DInventorViewer::clearBufferCB(void* ud, SoAction* action)
1330 {
1331 Q_UNUSED(ud)
1332 if (action->isOfType(SoGLRenderAction::getClassTypeId())) {
1333 // do stuff specific for GL rendering here.
1334 glClear(GL_DEPTH_BUFFER_BIT);
1335 }
1336 }
1337
1338 void View3DInventorViewer::setGLWidgetCB(void* userdata, SoAction* action)
1339 {
1340 // FIXME: This causes the Coin error message:
1341 // Coin error in SoNode::GLRenderS(): GL error: 'GL_STACK_UNDERFLOW', nodetype:
1342 // Separator (set envvar COIN_GLERROR_DEBUGGING=1 and re-run to get more information)
1343 if (action->isOfType(SoGLRenderAction::getClassTypeId())) {
1344 auto gl = static_cast<QWidget*>(userdata);
1345 SoGLWidgetElement::set(action->getState(), qobject_cast<QOpenGLWidget*>(gl));
1346 }
1347 }
1348
1349 void View3DInventorViewer::handleEventCB(void* userdata, SoEventCallback* n)
1350 {
1351 auto that = static_cast<View3DInventorViewer*>(userdata);
1352 SoGLRenderAction* glra = that->getSoRenderManager()->getGLRenderAction();
1353 SoAction* action = n->getAction();
1354 SoGLRenderActionElement::set(action->getState(), glra);
1355 SoGLWidgetElement::set(action->getState(), qobject_cast<QOpenGLWidget*>(that->getGLWidget()));
1356 }
1357
1358 void View3DInventorViewer::setGradientBackground(View3DInventorViewer::Background grad)
1359 {
1360 switch (grad) {
1361 case Background::NoGradient:
1362 if (backgroundroot->findChild(pcBackGround) != -1) {
1363 backgroundroot->removeChild(pcBackGround);
1364 }
1365 break;
1366 case Background::LinearGradient:
1367 pcBackGround->setGradient(SoFCBackgroundGradient::LINEAR);
1368 if (backgroundroot->findChild(pcBackGround) == -1) {
1369 backgroundroot->addChild(pcBackGround);
1370 }
1371 break;
1372 case Background::RadialGradient:
1373 pcBackGround->setGradient(SoFCBackgroundGradient::RADIAL);
1374 if (backgroundroot->findChild(pcBackGround) == -1) {
1375 backgroundroot->addChild(pcBackGround);
1376 }
1377 break;
1378 }
1379 }
1380
1381 View3DInventorViewer::Background View3DInventorViewer::getGradientBackground() const
1382 {
1383 if (backgroundroot->findChild(pcBackGround) == -1) {
1384 return Background::NoGradient;
1385 }
1386
1387 if (pcBackGround->getGradient() == SoFCBackgroundGradient::LINEAR) {
1388 return Background::LinearGradient;
1389 }
1390
1391 return Background::RadialGradient;
1392 }
1393
1394 void View3DInventorViewer::setGradientBackgroundColor(const SbColor& fromColor, const SbColor& toColor)
1395 {
1396 pcBackGround->setColorGradient(fromColor, toColor);
1397 }
1398
1399 void View3DInventorViewer::setGradientBackgroundColor(
1400 const SbColor& fromColor,
1401 const SbColor& toColor,
1402 const SbColor& midColor
1403 )
1404 {
1405 pcBackGround->setColorGradient(fromColor, toColor, midColor);
1406 }
1407
1408 void View3DInventorViewer::setEnabledFPSCounter(bool on)
1409 {
1410 fpsEnabled = on;
1411 if (on) {
1412 if (!fpsCounter) {
1413 fpsCounter = new QLabel(this);
1414 fpsCounter->setAttribute(Qt::WA_TransparentForMouseEvents);
1415 }
1416 fpsCounter->show();
1417 }
1418 else if (fpsCounter) {
1419 fpsCounter->hide();
1420 }
1421 }
1422
1423
1424 void View3DInventorViewer::setEnabledVBO(bool on)
1425 {
1426 vboEnabled = on;
1427 }
1428
1429 bool View3DInventorViewer::isEnabledVBO() const
1430 {
1431 return vboEnabled;
1432 }
1433
1434 void View3DInventorViewer::setRenderCache(int mode)
1435 {
1436 static int canAutoCache = -1;
1437
1438 if (mode < 0) {
1439 // Work around coin bug of unmatched call of
1440 // SoGLLazyElement::begin/endCaching() when on top rendering
1441 // transparent object with SORTED_OBJECT_SORTED_TRIANGLE_BLEND
1442 // transparency type.
1443 //
1444 // For more details see:
1445 // https://forum.freecad.org/viewtopic.php?f=18&t=43305&start=10#p412537
1446 coin_setenv("COIN_AUTO_CACHING", "0", TRUE);
1447
1448 int setting = ViewParams::instance()->getRenderCache();
1449 if (mode == -2) {
1450 if (pcViewProviderRoot && setting != 1) {
1451 pcViewProviderRoot->renderCaching = SoSeparator::ON;
1452 }
1453 mode = 2;
1454 }
1455 else {
1456 if (pcViewProviderRoot) {
1457 pcViewProviderRoot->renderCaching = SoSeparator::AUTO;
1458 }
1459 mode = setting;
1460 }
1461 }
1462
1463 if (canAutoCache < 0) {
1464 const char* env = coin_getenv("COIN_AUTO_CACHING");
1465 canAutoCache = env ? atoi(env) : 1;
1466 }
1467
1468 // If coin auto cache is disabled, do not use 'Auto' render cache mode, but
1469 // fallback to 'Distributed' mode.
1470 if (!canAutoCache && mode != 2) {
1471 mode = 1;
1472 }
1473
1474 auto caching = mode == 0 ? SoSeparator::AUTO : (mode == 1 ? SoSeparator::ON : SoSeparator::OFF);
1475
1476 SoFCSeparator::setCacheMode(caching);
1477 }
1478
1479 void View3DInventorViewer::setEnabledNaviCube(bool on)
1480 {
1481 naviCubeEnabled = on;
1482 }
1483
1484 bool View3DInventorViewer::isEnabledNaviCube() const
1485 {
1486 return naviCubeEnabled;
1487 }
1488
1489 void View3DInventorViewer::setNaviCubeCorner(int cc)
1490 {
1491 if (naviCube) {
1492 naviCube->setCorner(static_cast<NaviCube::Corner>(cc));
1493 }
1494 }
1495
1496 NaviCube* View3DInventorViewer::getNaviCube() const
1497 {
1498 return naviCube;
1499 }
1500
1501 void View3DInventorViewer::setAxisCross(bool on)
1502 {
1503 SoNode* scene = getSceneGraph();
1504 auto sep = static_cast<SoSeparator*>(scene); // NOLINT
1505
1506 if (on) {
1507 if (!axisGroup) {
1508 using enum SoFCPlacementIndicatorKit::Part;
1509
1510 constexpr float axisCrossLength = 2.0F;
1511
1512 auto axisCrossKit = new Gui::SoFCPlacementIndicatorKit();
1513 axisCrossKit->axisLength = axisCrossLength;
1514
1515 auto annotation = new So3DAnnotation();
1516 annotation->addChild(axisCrossKit);
1517
1518 axisGroup = new SoSkipBoundingGroup;
1519 axisGroup->addChild(annotation);
1520
1521 sep->addChild(axisGroup);
1522 }
1523 }
1524 else {
1525 if (axisGroup) {
1526 sep->removeChild(axisGroup);
1527 axisGroup = nullptr;
1528 }
1529 }
1530 }
1531
1532 bool View3DInventorViewer::hasAxisCross()
1533 {
1534 return axisGroup;
1535 }
1536
1537 void View3DInventorViewer::showRotationCenter(bool show)
1538 {
1539 SoNode* scene = getSceneGraph();
1540 if (!scene) {
1541 return;
1542 }
1543
1544 auto sep = static_cast<SoSeparator*>(scene); // NOLINT
1545
1546 bool showEnabled = App::GetApplication()
1547 .GetParameterGroupByPath("User parameter:BaseApp/Preferences/View")
1548 ->GetBool("ShowRotationCenter", true);
1549
1550 if (show && showEnabled) {
1551 SbBool found {};
1552 SbVec3f center = navigation->getRotationCenter(found);
1553
1554 if (!found) {
1555 return;
1556 }
1557
1558 if (!rotationCenterGroup) {
1559 float size = App::GetApplication()
1560 .GetParameterGroupByPath("User parameter:BaseApp/Preferences/View")
1561 ->GetFloat("RotationCenterSize", 5.0); // NOLINT
1562
1563 unsigned long rotationCenterColor
1564 = App::GetApplication()
1565 .GetParameterGroupByPath("User parameter:BaseApp/Preferences/View")
1566 ->GetUnsigned("RotationCenterColor", 4278190131); // NOLINT
1567
1568 QColor color = Base::Color::fromPackedRGBA<QColor>(rotationCenterColor);
1569
1570 rotationCenterGroup = new SoSkipBoundingGroup();
1571
1572 auto sphere = new SoSphere();
1573 auto complexity = new SoComplexity();
1574 complexity->value = 1;
1575
1576 auto material = new SoMaterial();
1577 material->emissiveColor
1578 = SbColor(float(color.redF()), float(color.greenF()), float(color.blueF()));
1579 material->transparency = 1.0F - float(color.alphaF());
1580
1581 auto translation = new SoTranslation();
1582 translation->setName("translation");
1583 translation->translation.setValue(center);
1584
1585 auto annotation = new SoAnnotation();
1586 annotation->addChild(complexity);
1587 annotation->addChild(material);
1588 annotation->addChild(sphere);
1589
1590 auto scaledSphere = new SoShapeScale();
1591 scaledSphere->setPart("shape", annotation);
1592 scaledSphere->scaleFactor = size;
1593
1594 rotationCenterGroup->addChild(translation);
1595 rotationCenterGroup->addChild(scaledSphere);
1596
1597 sep->addChild(rotationCenterGroup);
1598 }
1599 }
1600 else {
1601 if (rotationCenterGroup) {
1602 sep->removeChild(rotationCenterGroup);
1603 rotationCenterGroup = nullptr;
1604 }
1605 }
1606 }
1607
1608 // Changes the position of the rotation center indicator
1609 void View3DInventorViewer::changeRotationCenterPosition(const SbVec3f& newCenter)
1610 {
1611 if (!rotationCenterGroup) {
1612 return;
1613 }
1614
1615 SoTranslation* translation = dynamic_cast<SoTranslation*>(
1616 rotationCenterGroup->getByName("translation")
1617 );
1618 if (!translation) {
1619 return;
1620 }
1621
1622 translation->translation = newCenter;
1623 }
1624
1625 void View3DInventorViewer::setNavigationType(Base::Type type)
1626 {
1627 if (this->navigation && this->navigation->getTypeId() == type) {
1628 return; // nothing to do
1629 }
1630
1631 Base::Type navtype
1632 = Base::Type::getTypeIfDerivedFrom(type.getName(), NavigationStyle::getClassTypeId());
1633 auto ns = static_cast<NavigationStyle*>(navtype.createInstance());
1634 // createInstance could return a null pointer
1635 if (!ns) {
1636 #if FC_DEBUG
1637 SoDebugError::postWarning(
1638 "View3DInventorViewer::setNavigationType",
1639 "Navigation object must be of type NavigationStyle."
1640 );
1641 #endif // FC_DEBUG
1642 return;
1643 }
1644
1645 if (this->navigation) {
1646 ns->operator=(*this->navigation);
1647 delete this->navigation;
1648 }
1649 this->navigation = ns;
1650 this->navigation->setViewer(this);
1651 }
1652
1653 NavigationStyle* View3DInventorViewer::navigationStyle() const
1654 {
1655 return this->navigation;
1656 }
1657
1658 SoDirectionalLight* View3DInventorViewer::getBacklight() const
1659 {
1660 return this->backlight;
1661 }
1662
1663 void View3DInventorViewer::setBacklightEnabled(bool on)
1664 {
1665 this->backlight->on = on;
1666 }
1667
1668 bool View3DInventorViewer::isBacklightEnabled() const
1669 {
1670 return this->backlight->on.getValue();
1671 }
1672
1673 SoDirectionalLight* View3DInventorViewer::getFillLight() const
1674 {
1675 return this->fillLight;
1676 }
1677
1678 void View3DInventorViewer::setFillLightEnabled(bool on)
1679 {
1680 this->fillLight->on = on;
1681 }
1682
1683 bool View3DInventorViewer::isFillLightEnabled() const
1684 {
1685 return this->fillLight->on.getValue();
1686 }
1687 SoEnvironment* View3DInventorViewer::getEnvironment() const
1688 {
1689 return this->environment;
1690 }
1691
1692 void View3DInventorViewer::setSceneGraph(SoNode* root)
1693 {
1694 inherited::setSceneGraph(root);
1695 if (!root) {
1696 _ViewProviderSet.clear();
1697 _ViewProviderMap.clear();
1698 editViewProvider = nullptr;
1699 }
1700
1701 SoSearchAction sa;
1702 sa.setNode(this->backlight);
1703 // we want the rendered scene with all lights and cameras, viewer->getSceneGraph would return
1704 // the geometry scene only
1705 SoNode* scene = this->getSoRenderManager()->getSceneGraph();
1706 if (scene && scene->getTypeId().isDerivedFrom(SoSeparator::getClassTypeId())) {
1707 sa.apply(scene);
1708 if (!sa.getPath()) {
1709 static_cast<SoSeparator*>(scene)->insertChild(this->backlight, 0);
1710 }
1711 }
1712
1713 #if (COIN_MAJOR_VERSION * 100 + COIN_MINOR_VERSION * 10 + COIN_MICRO_VERSION < 403)
1714 navigation->findBoundingSphere();
1715 #endif
1716 }
1717
1718 void View3DInventorViewer::savePicture(int width, int height, int sample, const QColor& bg, QImage& img) const
1719 {
1720 // Save picture methods:
1721 // FramebufferObject -- viewer renders into FBO (no offscreen)
1722 // CoinOffscreenRenderer -- Coin's offscreen rendering method
1723 // Otherwise (Default) -- Qt's FBO used for offscreen rendering
1724 std::string saveMethod = App::GetApplication()
1725 .GetParameterGroupByPath("User parameter:BaseApp/Preferences/View")
1726 ->GetASCII("SavePicture");
1727
1728 bool useFramebufferObject = false;
1729 bool useGrabFramebuffer = false;
1730 bool useCoinOffscreenRenderer = false;
1731 if (saveMethod == "FramebufferObject") {
1732 useFramebufferObject = true;
1733 }
1734 else if (saveMethod == "GrabFramebuffer") {
1735 useGrabFramebuffer = true;
1736 }
1737 else if (saveMethod == "CoinOffscreenRenderer") {
1738 useCoinOffscreenRenderer = true;
1739 }
1740
1741 if (useFramebufferObject) {
1742 auto self = const_cast<View3DInventorViewer*>(this); // NOLINT
1743 self->imageFromFramebuffer(width, height, sample, bg, img);
1744 return;
1745 }
1746
1747 if (useGrabFramebuffer) {
1748 auto self = const_cast<View3DInventorViewer*>(this); // NOLINT
1749 img = self->grabFramebuffer();
1750 img = img.mirrored();
1751 img = img.scaledToWidth(width);
1752 return;
1753 }
1754
1755 // if no valid color use the current background
1756 bool useBackground = false;
1757 SbViewportRegion vp(getSoRenderManager()->getViewportRegion());
1758
1759 if (width > 0 && height > 0) {
1760 vp.setWindowSize(short(width), short(height));
1761 }
1762
1763 // NOTE: To support pixels per inch we must use SbViewportRegion::setPixelsPerInch( ppi );
1764 // The default value is 72.0.
1765 // If we need to support grayscale images with must either use SoOffscreenRenderer::LUMINANCE or
1766 // SoOffscreenRenderer::LUMINANCE_TRANSPARENCY.
1767
1768 SoCallback* cb = nullptr;
1769
1770 // for an invalid color use the viewer's current background color
1771 QColor bgColor;
1772 if (!bg.isValid()) {
1773 if (backgroundroot->findChild(pcBackGround) == -1) {
1774 bgColor = this->backgroundColor();
1775 }
1776 else {
1777 useBackground = true;
1778 cb = new SoCallback;
1779 cb->setCallback(clearBufferCB);
1780 }
1781 }
1782 else {
1783 bgColor = bg;
1784 }
1785
1786 auto root = new SoSeparator;
1787 root->ref();
1788
1789 if (useCoinOffscreenRenderer) {
1790 auto cbvp = new SoCallback;
1791 cbvp->setCallback(setViewportCB);
1792 root->addChild(cbvp);
1793 }
1794
1795 SoCamera* camera = getSoRenderManager()->getCamera();
1796
1797 if (useBackground) {
1798 root->addChild(backgroundroot);
1799 root->addChild(cb);
1800 }
1801
1802 if (!this->shading) {
1803 auto lm = new SoLightModel;
1804 lm->model = SoLightModel::BASE_COLOR;
1805 root->addChild(lm);
1806 }
1807
1808 root->addChild(getHeadlight());
1809 root->addChild(getBacklight());
1810 root->addChild(getFillLight());
1811 root->addChild(camera);
1812 auto gl = new SoCallback;
1813 gl->setCallback(setGLWidgetCB, this->getGLWidget());
1814 root->addChild(gl);
1815 root->addChild(pcViewProviderRoot);
1816 root->addChild(foregroundroot);
1817
1818 try {
1819 // render the scene
1820 if (!useCoinOffscreenRenderer) {
1821 SoQtOffscreenRenderer renderer(vp);
1822 renderer.setNumPasses(sample);
1823 renderer.setInternalTextureFormat(getInternalTextureFormat());
1824 if (bgColor.isValid()) {
1825 renderer.setBackgroundColor(SbColor4f(
1826 float(bgColor.redF()),
1827 float(bgColor.greenF()),
1828 float(bgColor.blueF()),
1829 float(bgColor.alphaF())
1830 ));
1831 }
1832 if (!renderer.render(root)) {
1833 throw Base::RuntimeError("Offscreen rendering failed");
1834 }
1835
1836 renderer.writeToImage(img);
1837 root->unref();
1838 }
1839 else {
1840 SoFCOffscreenRenderer& renderer = SoFCOffscreenRenderer::instance();
1841 renderer.setViewportRegion(vp);
1842 renderer.getGLRenderAction()->setSmoothing(true);
1843 renderer.getGLRenderAction()->setNumPasses(sample);
1844 renderer.getGLRenderAction()->setTransparencyType(
1845 SoGLRenderAction::SORTED_OBJECT_SORTED_TRIANGLE_BLEND
1846 );
1847 if (bgColor.isValid()) {
1848 renderer.setBackgroundColor(
1849 SbColor(float(bgColor.redF()), float(bgColor.greenF()), float(bgColor.blueF()))
1850 );
1851 }
1852 if (!renderer.render(root)) {
1853 throw Base::RuntimeError("Offscreen rendering failed");
1854 }
1855
1856 renderer.writeToImage(img);
1857 root->unref();
1858 }
1859
1860 if (!bgColor.isValid() || bgColor.alphaF() == 1.0) {
1861 QImage image(img.width(), img.height(), QImage::Format_RGB32);
1862 QPainter painter(&image);
1863 painter.fillRect(image.rect(), Qt::black);
1864 painter.drawImage(0, 0, img);
1865 painter.end();
1866 img = image;
1867 }
1868 }
1869 catch (...) {
1870 root->unref();
1871 throw; // re-throw exception
1872 }
1873 }
1874
1875 void View3DInventorViewer::saveGraphic(int pagesize, const QColor& bgcolor, SoVectorizeAction* va) const
1876 {
1877 if (bgcolor.isValid()) {
1878 va->setBackgroundColor(
1879 true,
1880 SbColor(float(bgcolor.redF()), float(bgcolor.greenF()), float(bgcolor.blueF()))
1881 );
1882 }
1883
1884 const float border = 10.0F;
1885 SbVec2s vpsize = this->getSoRenderManager()->getViewportRegion().getViewportSizePixels();
1886 float vpratio = ((float)vpsize[0]) / ((float)vpsize[1]);
1887
1888 if (vpratio > 1.0F) {
1889 va->setOrientation(SoVectorizeAction::LANDSCAPE);
1890 vpratio = 1.0F / vpratio;
1891 }
1892 else {
1893 va->setOrientation(SoVectorizeAction::PORTRAIT);
1894 }
1895
1896 va->beginStandardPage(SoVectorizeAction::PageSize(pagesize), border);
1897
1898 // try to fill as much "paper" as possible
1899 SbVec2f size = va->getPageSize();
1900
1901 float pageratio = size[0] / size[1];
1902 float xsize {};
1903 float ysize {};
1904
1905 if (pageratio < vpratio) {
1906 xsize = size[0];
1907 ysize = xsize / vpratio;
1908 }
1909 else {
1910 ysize = size[1];
1911 xsize = ysize * vpratio;
1912 }
1913
1914 float offx = border + (size[0] - xsize) * 0.5F; // NOLINT
1915 float offy = border + (size[1] - ysize) * 0.5F; // NOLINT
1916
1917 va->beginViewport(SbVec2f(offx, offy), SbVec2f(xsize, ysize));
1918 va->calibrate(this->getSoRenderManager()->getViewportRegion());
1919
1920 va->apply(this->getSoRenderManager()->getSceneGraph());
1921
1922 va->endViewport();
1923 va->endPage();
1924 }
1925
1926 void View3DInventorViewer::startSelection(View3DInventorViewer::SelectionMode mode)
1927 {
1928 navigation->startSelection(NavigationStyle::SelectionMode(mode));
1929 }
1930
1931 void View3DInventorViewer::abortSelection()
1932 {
1933 setCursorEnabled(true);
1934 navigation->abortSelection();
1935 }
1936
1937 void View3DInventorViewer::stopSelection()
1938 {
1939 setCursorEnabled(true);
1940 navigation->stopSelection();
1941 }
1942
1943 bool View3DInventorViewer::isSelecting() const
1944 {
1945 return navigation->isSelecting();
1946 }
1947
1948 const std::vector<SbVec2s>& View3DInventorViewer::getPolygon(SelectionRole* role) const
1949 {
1950 return navigation->getPolygon(role);
1951 }
1952
1953 void View3DInventorViewer::setSelectionEnabled(bool enable)
1954 {
1955 this->selectionRoot->selectionEnabled.setValue(enable); // NOLINT
1956 }
1957
1958 bool View3DInventorViewer::isSelectionEnabled() const
1959 {
1960 return this->selectionRoot->selectionEnabled.getValue(); // NOLINT
1961 }
1962
1963 SbVec2f View3DInventorViewer::screenCoordsOfPath(SoPath* path) const
1964 {
1965 // Generate a matrix (well, a SoGetMatrixAction) that
1966 // moves us to the picked object's coordinate space.
1967 SoGetMatrixAction gma(getSoRenderManager()->getViewportRegion());
1968 gma.apply(path);
1969
1970 // Use that matrix to translate the origin in the picked
1971 // object's coordinate space into object space
1972 SbVec3f imageCoords(0, 0, 0);
1973 SbMatrix mat = gma.getMatrix().transpose();
1974 mat.multMatrixVec(imageCoords, imageCoords);
1975
1976 // Now, project the object space coordinates of the object
1977 // into "normalized" screen coordinates.
1978 SbViewVolume vol = getSoRenderManager()->getCamera()->getViewVolume();
1979 vol.projectToScreen(imageCoords, imageCoords);
1980
1981 // Translate "normalized" screen coordinates to pixel coords.
1982 //
1983 // Note: for some reason, projectToScreen() doesn't seem to
1984 // handle non-square viewports properly. The X and Y are
1985 // scaled such that [0,1] fits within the smaller of the window
1986 // width or height. For instance, in a window that's 400px
1987 // tall and 800px wide, the Y will be within [0,1], but X can
1988 // vary within [-0.5,1.5]...
1989 int width = getGLWidget()->width();
1990 int height = getGLWidget()->height();
1991
1992 if (width >= height) {
1993 // "Landscape" orientation, to square
1994 imageCoords[0] *= height;
1995 imageCoords[0] += (width - height) / 2.0; // NOLINT
1996 imageCoords[1] *= height;
1997 }
1998 else {
1999 // "Portrait" orientation
2000 imageCoords[0] *= width;
2001 imageCoords[1] *= width;
2002 imageCoords[1] += (height - width) / 2.0; // NOLINT
2003 }
2004
2005 return {imageCoords[0], imageCoords[1]};
2006 }
2007
2008 std::vector<SbVec2f> View3DInventorViewer::getGLPolygon(const std::vector<SbVec2s>& pnts) const
2009 {
2010 const SbViewportRegion& vp = this->getSoRenderManager()->getViewportRegion();
2011 const SbVec2s& sp = vp.getViewportSizePixels();
2012 const SbVec2s& op = vp.getViewportOriginPixels();
2013 const SbVec2f& vpSize = vp.getViewportSize();
2014 float dX {};
2015 float dY {};
2016 vpSize.getValue(dX, dY);
2017 float fRatio = vp.getViewportAspectRatio();
2018
2019 std::vector<SbVec2f> poly;
2020 for (const auto& pnt : pnts) {
2021 SbVec2s loc = pnt - op;
2022 SbVec2f pos((float)loc[0] / (float)sp[0], (float)loc[1] / (float)sp[1]);
2023 float pX {};
2024 float pY {};
2025 pos.getValue(pX, pY);
2026
2027 // now calculate the real points respecting aspect ratio information
2028 //
2029 if (fRatio > 1.0F) {
2030 pX = (pX - 0.5F * dX) * fRatio + 0.5F * dX; // NOLINT
2031 pos.setValue(pX, pY);
2032 }
2033 else if (fRatio < 1.0F) {
2034 pY = (pY - 0.5F * dY) / fRatio + 0.5F * dY; // NOLINT
2035 pos.setValue(pX, pY);
2036 }
2037
2038 poly.push_back(pos);
2039 }
2040
2041 return poly;
2042 }
2043
2044 std::vector<SbVec2f> View3DInventorViewer::getGLPolygon(SelectionRole* role) const
2045 {
2046 const std::vector<SbVec2s>& pnts = navigation->getPolygon(role);
2047 return getGLPolygon(pnts);
2048 }
2049
2050 bool View3DInventorViewer::dumpToFile(SoNode* node, const char* filename, bool binary) const
2051 {
2052 bool ret = false;
2053 Base::FileInfo fi(filename);
2054
2055 if (fi.hasExtension({"idtf", "svg"})) {
2056 int ps = 4;
2057 QColor col = Qt::white;
2058 std::unique_ptr<SoVectorizeAction> vo;
2059
2060 if (fi.hasExtension("svg")) {
2061 vo = std::unique_ptr<SoVectorizeAction>(new SoFCVectorizeSVGAction());
2062 }
2063 else if (fi.hasExtension("idtf")) {
2064 vo = std::unique_ptr<SoVectorizeAction>(new SoFCVectorizeU3DAction());
2065 }
2066 else if (fi.hasExtension({"ps", "eps"})) {
2067 vo = std::unique_ptr<SoVectorizeAction>(new SoVectorizePSAction());
2068 }
2069 else {
2070 throw Base::ValueError("Not supported vector graphic");
2071 }
2072
2073 SoVectorOutput* out = vo->getOutput();
2074 if (!out || !out->openFile(filename)) {
2075 std::ostringstream a_out;
2076 a_out << "Cannot open file '" << filename << "'";
2077 throw Base::FileSystemError(a_out.str());
2078 }
2079
2080 saveGraphic(ps, col, vo.get());
2081 out->closeFile();
2082 }
2083 else {
2084 // Try VRML and Inventor format
2085 ret = SoFCDB::writeToFile(node, filename, binary);
2086 }
2087
2088 return ret;
2089 }
2090
2091 /**
2092 * Sets the SoFCInteractiveElement to \a true.
2093 */
2094 void View3DInventorViewer::interactionStartCB(void* ud, SoQTQuarterAdaptor* viewer)
2095 {
2096 Q_UNUSED(ud)
2097 SoGLRenderAction* glra = viewer->getSoRenderManager()->getGLRenderAction();
2098 SoFCInteractiveElement::set(glra->getState(), viewer->getSceneGraph(), true);
2099 }
2100
2101 /**
2102 * Sets the SoFCInteractiveElement to \a false and forces a redraw.
2103 */
2104 void View3DInventorViewer::interactionFinishCB(void* ud, SoQTQuarterAdaptor* viewer)
2105 {
2106 Q_UNUSED(ud)
2107 SoGLRenderAction* glra = viewer->getSoRenderManager()->getGLRenderAction();
2108 SoFCInteractiveElement::set(glra->getState(), viewer->getSceneGraph(), false);
2109 viewer->redraw();
2110 }
2111
2112 /**
2113 * Logs the type of the action that traverses the Inventor tree.
2114 */
2115 void View3DInventorViewer::interactionLoggerCB(void* ud, SoAction* action)
2116 {
2117 Q_UNUSED(ud)
2118 Base::Console().log("%s\n", action->getTypeId().getName().getString());
2119 }
2120
2121 void View3DInventorViewer::addGraphicsItem(GLGraphicsItem* item)
2122 {
2123 this->graphicsItems.push_back(item);
2124 }
2125
2126 void View3DInventorViewer::removeGraphicsItem(GLGraphicsItem* item)
2127 {
2128 this->graphicsItems.remove(item);
2129 }
2130
2131 std::list<GLGraphicsItem*> View3DInventorViewer::getGraphicsItems() const
2132 {
2133 return graphicsItems;
2134 }
2135
2136 std::list<GLGraphicsItem*> View3DInventorViewer::getGraphicsItemsOfType(const Base::Type& type) const
2137 {
2138 std::list<GLGraphicsItem*> items;
2139 for (auto it : this->graphicsItems) {
2140 if (it->isDerivedFrom(type)) {
2141 items.push_back(it);
2142 }
2143 }
2144
2145 return items;
2146 }
2147
2148 void View3DInventorViewer::clearGraphicsItems()
2149 {
2150 this->graphicsItems.clear();
2151 }
2152
2153 int View3DInventorViewer::getNumSamples()
2154 {
2155 Gui::AntiAliasing msaa = Multisample::readMSAAFromSettings();
2156 return Multisample::toSamples(msaa);
2157 }
2158
2159 GLenum View3DInventorViewer::getInternalTextureFormat()
2160 {
2161 ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath(
2162 "User parameter:BaseApp/Preferences/View"
2163 );
2164 std::string format = hGrp->GetASCII("InternalTextureFormat", "Default");
2165
2166 // NOLINTBEGIN
2167 if (format == "GL_RGB") {
2168 return GL_RGB;
2169 }
2170 else if (format == "GL_RGBA") {
2171 return GL_RGBA;
2172 }
2173 else if (format == "GL_RGB8") {
2174 return GL_RGB8;
2175 }
2176 else if (format == "GL_RGBA8") {
2177 return GL_RGBA8;
2178 }
2179 else if (format == "GL_RGB10") {
2180 return GL_RGB10;
2181 }
2182 else if (format == "GL_RGB10_A2") {
2183 return GL_RGB10_A2;
2184 }
2185 else if (format == "GL_RGB16") {
2186 return GL_RGB16;
2187 }
2188 else if (format == "GL_RGBA16") {
2189 return GL_RGBA16;
2190 }
2191 else if (format == "GL_RGB32F") {
2192 return GL_RGB32F_ARB;
2193 }
2194 else if (format == "GL_RGBA32F") {
2195 return GL_RGBA32F_ARB;
2196 }
2197 else {
2198 QOpenGLFramebufferObjectFormat fboFormat;
2199 return fboFormat.internalTextureFormat();
2200 }
2201 // NOLINTEND
2202 }
2203
2204 void View3DInventorViewer::setRenderType(RenderType type)
2205 {
2206 renderType = type;
2207
2208 glImage = QImage();
2209 if (type != Framebuffer) {
2210 delete framebuffer;
2211 framebuffer = nullptr;
2212 }
2213
2214 switch (type) {
2215 case Native:
2216 break;
2217 case Framebuffer:
2218 if (!framebuffer) {
2219 const SbViewportRegion vp = this->getSoRenderManager()->getViewportRegion();
2220 SbVec2s size = vp.getViewportSizePixels();
2221 int width = size[0];
2222 int height = size[1];
2223
2224 auto gl = static_cast<QOpenGLWidget*>(this->viewport()); // NOLINT
2225 gl->makeCurrent();
2226 QOpenGLFramebufferObjectFormat fboFormat;
2227 fboFormat.setSamples(getNumSamples());
2228 fboFormat.setAttachment(QOpenGLFramebufferObject::Depth);
2229 auto fbo = new QOpenGLFramebufferObject(width, height, fboFormat);
2230 if (fbo->format().samples() > 0) {
2231 renderToFramebuffer(fbo);
2232 framebuffer = new QOpenGLFramebufferObject(fbo->size());
2233 // this is needed to be able to render the texture later
2234 QOpenGLFramebufferObject::blitFramebuffer(framebuffer, fbo);
2235 delete fbo;
2236 }
2237 else {
2238 renderToFramebuffer(fbo);
2239 framebuffer = fbo;
2240 }
2241 }
2242 break;
2243 case Image: {
2244 glImage = grabFramebuffer();
2245 } break;
2246 }
2247 }
2248
2249 View3DInventorViewer::RenderType View3DInventorViewer::getRenderType() const
2250 {
2251 return this->renderType;
2252 }
2253
2254 QImage View3DInventorViewer::grabFramebuffer()
2255 {
2256 auto gl = static_cast<QOpenGLWidget*>(this->viewport()); // NOLINT
2257 gl->makeCurrent();
2258
2259 QImage res;
2260 const SbViewportRegion vp = this->getSoRenderManager()->getViewportRegion();
2261 SbVec2s size = vp.getViewportSizePixels();
2262 int width = size[0];
2263 int height = size[1];
2264
2265 int samples = getNumSamples();
2266 if (samples == 0) {
2267 // if anti-aliasing is off we can directly use glReadPixels
2268 QImage img(QSize(width, height), QImage::Format_RGB32);
2269 glReadPixels(0, 0, width, height, GL_BGRA, GL_UNSIGNED_BYTE, img.bits());
2270 res = img;
2271 }
2272 else {
2273 QOpenGLFramebufferObjectFormat fboFormat;
2274 fboFormat.setSamples(getNumSamples());
2275 fboFormat.setAttachment(QOpenGLFramebufferObject::Depth);
2276 fboFormat.setTextureTarget(GL_TEXTURE_2D);
2277 fboFormat.setInternalTextureFormat(getInternalTextureFormat());
2278
2279 QOpenGLFramebufferObject fbo(width, height, fboFormat);
2280 renderToFramebuffer(&fbo);
2281
2282 res = fbo.toImage(false);
2283
2284 QImage image(res.width(), res.height(), QImage::Format_RGB32);
2285 QPainter painter(&image);
2286 painter.fillRect(image.rect(), Qt::black);
2287 painter.drawImage(0, 0, res);
2288 painter.end();
2289 res = image;
2290 }
2291
2292 return res;
2293 }
2294
2295 void View3DInventorViewer::imageFromFramebuffer(
2296 int width,
2297 int height,
2298 int samples,
2299 const QColor& bgcolor,
2300 QImage& img
2301 )
2302 {
2303 auto gl = static_cast<QOpenGLWidget*>(this->viewport()); // NOLINT
2304 gl->makeCurrent();
2305
2306 const QOpenGLContext* context = QOpenGLContext::currentContext();
2307 if (!context) {
2308 Base::Console().warning("imageFromFramebuffer failed because no context is active\n");
2309 return;
2310 }
2311
2312 QOpenGLFramebufferObjectFormat fboFormat;
2313 fboFormat.setSamples(samples);
2314 fboFormat.setAttachment(QOpenGLFramebufferObject::Depth);
2315 // With enabled alpha a transparent background is supported but
2316 // at the same time breaks semi-transparent models. A workaround
2317 // is to use a certain background color using GL_RGB as texture
2318 // format and in the output image search for the above color and
2319 // replaces it with the color requested by the user.
2320 fboFormat.setInternalTextureFormat(getInternalTextureFormat());
2321
2322 QOpenGLFramebufferObject fbo(width, height, fboFormat);
2323
2324 const QColor col = backgroundColor();
2325 auto grad = getGradientBackground();
2326
2327 constexpr const int maxAlpha = 255;
2328 int alpha = maxAlpha;
2329 QColor bgopaque = bgcolor;
2330 if (bgopaque.isValid()) {
2331 // force an opaque background color
2332 alpha = bgopaque.alpha();
2333 if (alpha < maxAlpha) {
2334 bgopaque.setRgb(maxAlpha, maxAlpha, maxAlpha);
2335 }
2336 setBackgroundColor(bgopaque);
2337 setGradientBackground(Background::NoGradient);
2338 }
2339
2340 renderToFramebuffer(&fbo);
2341 setBackgroundColor(col);
2342 setGradientBackground(grad);
2343 img = fbo.toImage();
2344
2345 // if background color isn't opaque manipulate the image
2346 if (alpha < maxAlpha) {
2347 QImage image(img.constBits(), img.width(), img.height(), QImage::Format_ARGB32);
2348 img = image.copy();
2349 QRgb rgba = bgcolor.rgba();
2350 QRgb rgb = bgopaque.rgb();
2351 QRgb* bits = (QRgb*)img.bits();
2352 for (int yy = 0; yy < height; yy++) {
2353 for (int xx = 0; xx < width; xx++) {
2354 if (*bits == rgb) {
2355 *bits = rgba;
2356 }
2357 bits++; // NOLINT
2358 }
2359 }
2360 }
2361 else if (alpha == maxAlpha) {
2362 QImage image(img.width(), img.height(), QImage::Format_RGB32);
2363 QPainter painter(&image);
2364 painter.fillRect(image.rect(), Qt::black);
2365 painter.drawImage(0, 0, img);
2366 painter.end();
2367 img = image;
2368 }
2369 }
2370
2371 void View3DInventorViewer::renderToFramebuffer(QOpenGLFramebufferObject* fbo)
2372 {
2373 static_cast<QOpenGLWidget*>(this->viewport())->makeCurrent(); // NOLINT
2374 fbo->bind();
2375 int width = fbo->size().width();
2376 int height = fbo->size().height();
2377
2378 glDisable(GL_TEXTURE_2D);
2379 glEnable(GL_LIGHTING);
2380 glEnable(GL_DEPTH_TEST);
2381 glEnable(GL_LINE_SMOOTH);
2382
2383 const QColor col = this->backgroundColor();
2384 glViewport(0, 0, width, height);
2385 glClearColor(float(col.redF()), float(col.greenF()), float(col.blueF()), float(col.alphaF()));
2386 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
2387
2388 SoBoxSelectionRenderAction gl(SbViewportRegion(width, height));
2389 // When creating a new GL render action we have to copy over the cache context id
2390 // For further details see init().
2391 uint32_t id = this->getSoRenderManager()->getGLRenderAction()->getCacheContext();
2392 gl.setCacheContext(id);
2393 gl.setTransparencyType(SoGLRenderAction::SORTED_OBJECT_SORTED_TRIANGLE_BLEND);
2394
2395 if (!this->shading) {
2396 SoLightModelElement::set(gl.getState(), selectionRoot, SoLightModelElement::BASE_COLOR);
2397 SoOverrideElement::setLightModelOverride(gl.getState(), selectionRoot, true);
2398 }
2399
2400 gl.apply(this->backgroundroot);
2401 // The render action of the render manager has set the depth function to GL_LESS
2402 // while creating a new render action has it set to GL_LEQUAL. So, in order to get
2403 // the exact same result set it explicitly to GL_LESS.
2404 glDepthFunc(GL_LESS);
2405 gl.apply(this->getSoRenderManager()->getSceneGraph());
2406 gl.apply(this->foregroundroot);
2407
2408 if (this->axiscrossEnabled) {
2409 this->drawAxisCross();
2410 }
2411
2412 fbo->release();
2413 }
2414
2415 void View3DInventorViewer::actualRedraw()
2416 {
2417 switch (renderType) {
2418 case Native:
2419 renderScene();
2420 break;
2421 case Framebuffer:
2422 renderFramebuffer();
2423 break;
2424 case Image:
2425 renderGLImage();
2426 break;
2427 }
2428 }
2429
2430 void View3DInventorViewer::renderFramebuffer()
2431 {
2432 const SbViewportRegion vp = this->getSoRenderManager()->getViewportRegion();
2433 SbVec2s size = vp.getViewportSizePixels();
2434
2435 glPushAttrib(GL_ALL_ATTRIB_BITS);
2436 glDisable(GL_LIGHTING);
2437 glViewport(0, 0, size[0], size[1]);
2438 glMatrixMode(GL_PROJECTION);
2439 glLoadIdentity();
2440 glMatrixMode(GL_MODELVIEW);
2441 glLoadIdentity();
2442 glDisable(GL_DEPTH_TEST);
2443
2444 glClear(GL_COLOR_BUFFER_BIT);
2445 glEnable(GL_TEXTURE_2D);
2446 glBindTexture(GL_TEXTURE_2D, this->framebuffer->texture());
2447 glColor3f(1.0, 1.0, 1.0);
2448
2449 glBegin(GL_QUADS);
2450 glTexCoord2f(0.0F, 0.0F);
2451 glVertex2f(-1.0, -1.0F);
2452 glTexCoord2f(1.0F, 0.0F);
2453 glVertex2f(1.0F, -1.0F);
2454 glTexCoord2f(1.0F, 1.0F);
2455 glVertex2f(1.0F, 1.0F);
2456 glTexCoord2f(0.0F, 1.0F);
2457 glVertex2f(-1.0F, 1.0F);
2458 glEnd();
2459
2460 printDimension();
2461
2462 for (auto it : this->graphicsItems) {
2463 it->paintGL();
2464 }
2465
2466 if (naviCubeEnabled) {
2467 naviCube->drawNaviCube();
2468 }
2469
2470 glPopAttrib();
2471 }
2472
2473 void View3DInventorViewer::renderGLImage()
2474 {
2475 const SbViewportRegion vp = this->getSoRenderManager()->getViewportRegion();
2476 SbVec2s size = vp.getViewportSizePixels();
2477
2478 glPushAttrib(GL_ALL_ATTRIB_BITS);
2479 glDisable(GL_LIGHTING);
2480 glViewport(0, 0, size[0], size[1]);
2481 glMatrixMode(GL_PROJECTION);
2482 glLoadIdentity();
2483 glOrtho(0, size[0], 0, size[1], 0, 100); // NOLINT
2484 glMatrixMode(GL_MODELVIEW);
2485 glLoadIdentity();
2486
2487 glDisable(GL_DEPTH_TEST);
2488 glClear(GL_COLOR_BUFFER_BIT);
2489
2490 glRasterPos2f(0, 0);
2491 glDrawPixels(glImage.width(), glImage.height(), GL_BGRA, GL_UNSIGNED_BYTE, glImage.bits());
2492
2493 printDimension();
2494
2495 for (auto it : this->graphicsItems) {
2496 it->paintGL();
2497 }
2498
2499 if (naviCubeEnabled) {
2500 naviCube->drawNaviCube();
2501 }
2502
2503 glPopAttrib();
2504 }
2505
2506 // #define ENABLE_GL_DEPTH_RANGE
2507 // The calls of glDepthRange inside renderScene() causes problems with transparent objects
2508 // so that's why it is disabled now:
2509 // https://forum.freecad.org/viewtopic.php?f=3&t=6037&hilit=transparency
2510
2511 // Documented in superclass. Overrides this method to be able to draw
2512 // the axis cross, if selected, and to keep a continuous animation
2513 // upon spin.
2514 void View3DInventorViewer::renderScene()
2515 {
2516 ZoneScoped;
2517
2518 // Must set up the OpenGL viewport manually, as upon resize
2519 // operations, Coin won't set it up until the SoGLRenderAction is
2520 // applied again. And since we need to do glClear() before applying
2521 // the action..
2522 const SbViewportRegion vp = this->getSoRenderManager()->getViewportRegion();
2523 SbVec2s origin = vp.getViewportOriginPixels();
2524 SbVec2s size = vp.getViewportSizePixels();
2525 glViewport(origin[0], origin[1], size[0], size[1]);
2526
2527 const QColor col = this->backgroundColor();
2528 glClearColor(float(col.redF()), float(col.greenF()), float(col.blueF()), 0.0F);
2529 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
2530 glEnable(GL_DEPTH_TEST);
2531
2532 #if defined(ENABLE_GL_DEPTH_RANGE)
2533 // using 90% of the z-buffer for the background and the main node
2534 glDepthRange(0.1, 1.0);
2535 #endif
2536
2537 SoGLRenderAction* glra = this->getSoRenderManager()->getGLRenderAction();
2538 SoState* state = glra->getState();
2539
2540 // Render our scenegraph with the image.
2541 {
2542 ZoneScopedN("Background");
2543 SoDevicePixelRatioElement::set(state, devicePixelRatio());
2544 SoGLWidgetElement::set(state, qobject_cast<QOpenGLWidget*>(this->getGLWidget()));
2545 SoGLRenderActionElement::set(state, glra);
2546 SoGLVBOActivatedElement::set(state, this->vboEnabled);
2547 drawSingleBackground(col);
2548 glra->apply(this->backgroundroot);
2549 }
2550
2551 if (!this->shading) {
2552 state->push();
2553 SoLightModelElement::set(state, selectionRoot, SoLightModelElement::BASE_COLOR);
2554 SoOverrideElement::setLightModelOverride(state, selectionRoot, true);
2555 }
2556
2557 try {
2558 // Render normal scenegraph.
2559 inherited::actualRedraw();
2560
2561 So3DAnnotation::render = true;
2562 glClear(GL_DEPTH_BUFFER_BIT);
2563
2564 // process delayed paths with priority support
2565 if (Gui::Selection().isClarifySelectionActive()) {
2566 Gui::SoDelayedAnnotationsElement::processDelayedPathsWithPriority(state, glra);
2567 }
2568 else {
2569 // standard processing for normal delayed annotations
2570 glra->apply(Gui::SoDelayedAnnotationsElement::getDelayedPaths(state));
2571 }
2572
2573 So3DAnnotation::render = false;
2574 }
2575 catch (const Base::MemoryException&) {
2576 // FIXME: If this exception appears then the background and camera position get broken
2577 // somehow. (Werner 2006-02-01)
2578 for (auto it : _ViewProviderSet) {
2579 it->hide();
2580 }
2581
2582 inherited::actualRedraw();
2583 QMessageBox::warning(
2584 parentWidget(),
2585 QObject::tr("Out of memory"),
2586 QObject::tr("Not enough memory available to display the data.")
2587 );
2588 }
2589
2590 if (!this->shading) {
2591 state->pop();
2592 }
2593
2594 #if defined(ENABLE_GL_DEPTH_RANGE)
2595 // using 10% of the z-buffer for the foreground node
2596 glDepthRange(0.0, 0.1);
2597 #endif
2598
2599 // Render overlay front scenegraph.
2600 {
2601 ZoneScopedN("Foreground");
2602 glra->apply(this->foregroundroot);
2603 }
2604
2605 if (this->axiscrossEnabled) {
2606 this->drawAxisCross();
2607 }
2608
2609 #if defined(ENABLE_GL_DEPTH_RANGE)
2610 // using the main portion of z-buffer again (for frontbuffer highlighting)
2611 glDepthRange(0.1, 1.0);
2612 #endif
2613
2614 // Immediately reschedule to get continuous animation.
2615 if (this->isAnimating()) {
2616 this->getSoRenderManager()->scheduleRedraw();
2617 }
2618
2619 printDimension();
2620
2621 {
2622 ZoneScopedN("Graphics items");
2623 for (auto it : this->graphicsItems) {
2624 it->paintGL();
2625 }
2626 }
2627
2628 if (fpsEnabled && fpsCounter) {
2629 std::stringstream stream;
2630 stream.precision(1);
2631 stream.setf(std::ios::fixed | std::ios::showpoint);
2632 stream << framesPerSecond[0] << " ms / " << framesPerSecond[1] << " fps";
2633
2634 ParameterGrp::handle hGrpView = App::GetApplication().GetParameterGroupByPath(
2635 "User parameter:BaseApp/Preferences/View"
2636 );
2637 unsigned long axisLetterColor = hGrpView->GetUnsigned("AxisLetterColor", 4294902015);
2638 if (axisLetterColor != previousAxisLetterColor) {
2639 previousAxisLetterColor = axisLetterColor;
2640 Base::Color c(static_cast<uint32_t>(axisLetterColor));
2641 fpsCounter->setStyleSheet(
2642 QString::fromLatin1("color: rgb(%1,%2,%3); background: transparent;")
2643 .arg(int(c.r * 255))
2644 .arg(int(c.g * 255))
2645 .arg(int(c.b * 255))
2646 );
2647 }
2648
2649 fpsCounter->setText(QString::fromStdString(stream.str()));
2650 fpsCounter->adjustSize();
2651
2652 ParameterGrp::handle hGrpOverlayL = App::GetApplication().GetParameterGroupByPath(
2653 "User parameter:BaseApp/MainWindow/DockWindows/OverlayLeft"
2654 );
2655 int xOffset = hGrpOverlayL->GetASCII("Widgets", "").empty() ? 10 : fpsCounter->width() + 20;
2656 fpsCounter->move(xOffset, height() - fpsCounter->height() - 5);
2657 }
2658
2659 if (naviCubeEnabled) {
2660 naviCube->drawNaviCube();
2661 }
2662
2663 // Workaround for inconsistent QT behavior related to handling custom OpenGL widgets that
2664 // leave non opaque alpha values in final output.
2665 // On wayland that can cause window to become transparent or blurry trail effect in the
2666 // parts that contain partially transparent objects.
2667 //
2668 // At the end of rendering clear alpha value, so that it doesn't matter how rest of the
2669 // compositing stack at QT and desktop level would interpret transparent pixels.
2670 //
2671 // Related issues:
2672 // https://bugreports.qt.io/browse/QTBUG-110014
2673 // https://bugreports.qt.io/browse/QTBUG-132197
2674 // https://bugreports.qt.io/browse/QTBUG-119214
2675 // https://github.com/FreeCAD/FreeCAD/issues/8341
2676 // https://github.com/FreeCAD/FreeCAD/issues/6177
2677 glPushAttrib(GL_COLOR_BUFFER_BIT);
2678 glColorMask(false, false, false, true);
2679 glClearColor(0, 0, 0, 1);
2680 glClear(GL_COLOR_BUFFER_BIT);
2681 glPopAttrib();
2682 }
2683
2684 void View3DInventorViewer::setSeekMode(bool on)
2685 {
2686 // Overrides this method to make sure any animations are stopped
2687 // before we go into seek mode.
2688
2689 // Note: this method is almost identical to the setSeekMode() in the
2690 // SoQtFlyViewer and SoQtPlaneViewer, so migrate any changes.
2691
2692 if (this->isAnimating()) {
2693 this->stopAnimating();
2694 }
2695
2696 inherited::setSeekMode(on);
2697 navigation->setViewingMode(
2698 on ? NavigationStyle::SEEK_WAIT_MODE
2699 : (this->isViewing() ? NavigationStyle::IDLE : NavigationStyle::INTERACT)
2700 );
2701 }
2702
2703 SbVec3f View3DInventorViewer::getCenterPointOnFocalPlane() const
2704 {
2705 SoCamera* cam = getSoRenderManager()->getCamera();
2706 if (!cam) {
2707 return {0., 0., 0.};
2708 }
2709
2710 SbVec3f direction;
2711 cam->orientation.getValue().multVec(SbVec3f(0, 0, -1), direction);
2712 return cam->position.getValue() + cam->focalDistance.getValue() * direction;
2713 }
2714
2715 float View3DInventorViewer::getMaxDimension() const
2716 {
2717 float fHeight = -1.0;
2718 float fWidth = -1.0;
2719 getDimensions(fHeight, fWidth);
2720 return std::max(fHeight, fWidth);
2721 }
2722
2723 void View3DInventorViewer::getDimensions(float& fHeight, float& fWidth) const
2724 {
2725 SoCamera* camera = getSoRenderManager()->getCamera();
2726 if (!camera) {
2727 // no camera there
2728 return;
2729 }
2730
2731 float aspectRatio = getViewportRegion().getViewportAspectRatio();
2732
2733 SoType type = camera->getTypeId();
2734 if (type.isDerivedFrom(SoOrthographicCamera::getClassTypeId())) {
2735 // NOLINTBEGIN
2736 fHeight = static_cast<SoOrthographicCamera*>(camera)->height.getValue();
2737 fWidth = fHeight;
2738 // NOLINTEND
2739 }
2740 else if (type.isDerivedFrom(SoPerspectiveCamera::getClassTypeId())) {
2741 // NOLINTBEGIN
2742 float fHeightAngle = static_cast<SoPerspectiveCamera*>(camera)->heightAngle.getValue();
2743 fHeight = std::tan(fHeightAngle / 2.0) * 2.0 * camera->focalDistance.getValue();
2744 fWidth = fHeight;
2745 // NOLINTEND
2746 }
2747
2748 if (aspectRatio > 1.0) {
2749 fWidth *= aspectRatio;
2750 }
2751 else {
2752 fHeight *= aspectRatio;
2753 }
2754 }
2755
2756 void View3DInventorViewer::printDimension() const
2757 {
2758 float fHeight = -1.0;
2759 float fWidth = -1.0;
2760 getDimensions(fHeight, fWidth);
2761
2762 std::string dim;
2763
2764 if (fWidth >= 0.0 && fHeight >= 0.0) {
2765 // Translate screen units into user's unit schema
2766 Base::Quantity qWidth(Base::Quantity::MilliMetre);
2767 Base::Quantity qHeight(Base::Quantity::MilliMetre);
2768 qWidth.setValue(fWidth);
2769 qHeight.setValue(fHeight);
2770 auto wStr = Base::UnitsApi::schemaTranslate(qWidth);
2771 auto hStr = Base::UnitsApi::schemaTranslate(qHeight);
2772
2773 // Create final string and update window
2774 dim = fmt::format("{} x {}", wStr, hStr);
2775 }
2776
2777 getMainWindow()->setPaneText(2, QString::fromStdString(dim));
2778 }
2779
2780 void View3DInventorViewer::selectAll()
2781 {
2782 std::vector<App::DocumentObject*> objs;
2783
2784 for (auto it : _ViewProviderSet) {
2785 if (it->isDerivedFrom<ViewProviderDocumentObject>()) {
2786 auto vp = static_cast<ViewProviderDocumentObject*>(it); // NOLINT
2787 App::DocumentObject* obj = vp->getObject();
2788
2789 if (obj) {
2790 objs.push_back(obj);
2791 }
2792 }
2793 }
2794
2795 if (!objs.empty()) {
2796 Gui::Selection().setSelection(objs.front()->getDocument()->getName(), objs);
2797 }
2798 }
2799
2800 bool View3DInventorViewer::processSoEvent(const SoEvent* ev)
2801 {
2802 ZoneScoped;
2803
2804 if (naviCubeEnabled && naviCube->processSoEvent(ev)) {
2805 return true;
2806 }
2807 if (isRedirectedToSceneGraph()) {
2808 bool processed = inherited::processSoEvent(ev);
2809
2810 if (!processed) {
2811 processed = navigation->processEvent(ev);
2812 }
2813
2814 return processed;
2815 }
2816
2817 if (ev->getTypeId().isDerivedFrom(SoKeyboardEvent::getClassTypeId())) {
2818 // filter out 'Q' and 'ESC' keys
2819 const auto ke = static_cast<const SoKeyboardEvent*>(ev); // NOLINT
2820
2821 switch (ke->getKey()) {
2822 case SoKeyboardEvent::ESCAPE:
2823 case SoKeyboardEvent::Q: // ignore 'Q' keys (to prevent app from being closed)
2824 return inherited::processSoEvent(ev);
2825 default:
2826 break;
2827 }
2828 }
2829
2830 return navigation->processEvent(ev);
2831 }
2832
2833 bool View3DInventorViewer::processSoEventBase(const SoEvent* const ev)
2834 {
2835 return inherited::processSoEvent(ev);
2836 }
2837
2838 SbVec3f View3DInventorViewer::getViewDirection() const
2839 {
2840 SoCamera* cam = this->getSoRenderManager()->getCamera();
2841
2842 if (!cam) {
2843 // this is the default
2844 return {0, 0, -1};
2845 }
2846
2847 SbVec3f projDir = cam->getViewVolume().getProjectionDirection();
2848 return projDir;
2849 }
2850
2851 void View3DInventorViewer::setViewDirection(SbVec3f dir)
2852 {
2853 if (SoCamera* cam = this->getSoRenderManager()->getCamera()) {
2854 cam->orientation.setValue(SbRotation(SbVec3f(0, 0, -1), dir));
2855 }
2856 }
2857
2858 SbVec3f View3DInventorViewer::getUpDirection() const
2859 {
2860 SoCamera* cam = this->getSoRenderManager()->getCamera();
2861
2862 if (!cam) {
2863 return {0, 1, 0};
2864 }
2865
2866 SbRotation camrot = cam->orientation.getValue();
2867 SbVec3f upvec(0, 1, 0); // init to default up vector
2868 camrot.multVec(upvec, upvec);
2869 return upvec;
2870 }
2871
2872 SbRotation View3DInventorViewer::getCameraOrientation() const
2873 {
2874 SoCamera* cam = this->getSoRenderManager()->getCamera();
2875
2876 if (!cam) {
2877 // this is the default
2878 return {0, 0, 0, 1};
2879 }
2880
2881 return cam->orientation.getValue();
2882 }
2883
2884 SbVec2f View3DInventorViewer::getNormalizedPosition(const SbVec2s& pnt) const
2885 {
2886 const SbViewportRegion& vp = this->getSoRenderManager()->getViewportRegion();
2887
2888 short xpos {};
2889 short ypos {};
2890 pnt.getValue(xpos, ypos);
2891 SbVec2f siz = vp.getViewportSize();
2892 float dX {};
2893 float dY {};
2894 siz.getValue(dX, dY);
2895
2896 float fRatio = vp.getViewportAspectRatio();
2897 float pX = float(xpos) / float(vp.getViewportSizePixels()[0]);
2898 float pY = float(ypos) / float(vp.getViewportSizePixels()[1]);
2899
2900 // now calculate the real points respecting aspect ratio information
2901 //
2902 // NOLINTBEGIN
2903 if (fRatio > 1.0F) {
2904 pX = (pX - 0.5F * dX) * fRatio + 0.5F * dX;
2905 }
2906 else if (fRatio < 1.0F) {
2907 pY = (pY - 0.5F * dY) / fRatio + 0.5F * dY;
2908 }
2909 // NOLINTEND
2910
2911 return {pX, pY};
2912 }
2913
2914 Base::BoundBox2d View3DInventorViewer::getViewportOnXYPlaneOfPlacement(Base::Placement plc) const
2915 {
2916 auto projBBox = Base::BoundBox3d();
2917 projBBox.SetVoid();
2918
2919 SoCamera* pCam = this->getSoRenderManager()->getCamera();
2920
2921 if (!pCam) {
2922 // Return empty box.
2923 return Base::BoundBox2d(0, 0, 0, 0);
2924 }
2925
2926 Base::Vector3d pos = plc.getPosition();
2927 Base::Rotation rot = plc.getRotation();
2928
2929 // Transform the plane LCS into the global one.
2930 Base::Vector3d zAxis(0, 0, 1);
2931 rot.multVec(zAxis, zAxis);
2932
2933 // Get the position and convert Base::Vector3d to SbVec3f
2934 SbVec3f planeNormal(zAxis.x, zAxis.y, zAxis.z);
2935 SbVec3f planePosition(pos.x, pos.y, pos.z);
2936 SbPlane xyPlane(planeNormal, planePosition);
2937
2938 const SbViewportRegion& vp = this->getSoRenderManager()->getViewportRegion();
2939 SbViewVolume vol = pCam->getViewVolume();
2940
2941 float fRatio = vp.getViewportAspectRatio();
2942 float dX, dY;
2943 vp.getViewportSize().getValue(dX, dY);
2944
2945 // Projects a pair of normalized coordinates on the XY plane.
2946 auto projectPoint = [&](float x, float y) {
2947 if (fRatio > 1.f) {
2948 x = (x - 0.5f * dX) * fRatio + 0.5f * dX;
2949 }
2950 else if (fRatio < 1.f) {
2951 y = (y - 0.5f * dY) / fRatio + 0.5f * dY;
2952 }
2953
2954 SbLine line;
2955 vol.projectPointToLine(SbVec2f(x, y), line);
2956
2957 SbVec3f pt;
2958 // Intersection point on the XY plane.
2959 if (!xyPlane.intersect(line, pt)) {
2960 return;
2961 }
2962
2963 projBBox.Add(Base::convertTo<Base::Vector3d>(pt));
2964 };
2965
2966 // Project the four corners of the viewport plane.
2967 projectPoint(0.f, 0.f);
2968 projectPoint(1.f, 0.f);
2969 projectPoint(0.f, 1.f);
2970 projectPoint(1.f, 1.f);
2971
2972 if (!projBBox.IsValid()) {
2973 // Return empty box.
2974 return Base::BoundBox2d(0, 0, 0, 0);
2975 }
2976
2977 plc.invert();
2978 Base::ViewOrthoProjMatrix proj(plc.toMatrix());
2979 return projBBox.ProjectBox(&proj);
2980 }
2981
2982 SbVec3f View3DInventorViewer::getPointOnXYPlaneOfPlacement(
2983 const SbVec2s& pnt,
2984 const Base::Placement& plc
2985 ) const
2986 {
2987 SbVec2f pnt2d = getNormalizedPosition(pnt);
2988 SoCamera* pCam = this->getSoRenderManager()->getCamera();
2989
2990 if (!pCam) {
2991 throw Base::RuntimeError("No camera node found");
2992 }
2993
2994 SbViewVolume vol = pCam->getViewVolume();
2995 SbLine line;
2996 vol.projectPointToLine(pnt2d, line);
2997
2998 // Calculate the plane using plc
2999 Base::Rotation rot = plc.getRotation();
3000 Base::Vector3d normalVector = rot.multVec(Base::Vector3d(0, 0, 1));
3001 SbVec3f planeNormal = Base::convertTo<SbVec3f>(normalVector);
3002
3003 // Get the position and convert Base::Vector3d to SbVec3f
3004 Base::Vector3d pos = plc.getPosition();
3005 SbVec3f planePosition = Base::convertTo<SbVec3f>(pos);
3006 SbPlane xyPlane(planeNormal, planePosition);
3007
3008 SbVec3f pt;
3009 if (xyPlane.intersect(line, pt)) {
3010 return pt; // Intersection point on the XY plane
3011 }
3012
3013 throw Base::RuntimeError("No intersection found");
3014 }
3015
3016 SbVec3f projectPointOntoPlane(const SbVec3f& point, const SbPlane& plane)
3017 {
3018 SbVec3f planeNormal = plane.getNormal();
3019 float d = plane.getDistanceFromOrigin();
3020 float distance = planeNormal.dot(point) + d;
3021 return point - planeNormal * distance;
3022 }
3023
3024 // Project a line onto a plane
3025 SbLine projectLineOntoPlane(const SbVec3f& p1, const SbVec3f& p2, const SbPlane& plane)
3026 {
3027 SbVec3f projectedPoint1 = projectPointOntoPlane(p1, plane);
3028 SbVec3f projectedPoint2 = projectPointOntoPlane(p2, plane);
3029 return SbLine(projectedPoint1, projectedPoint2);
3030 }
3031
3032 SbVec3f intersection(const SbVec3f& p11, const SbVec3f& p12, const SbVec3f& p21, const SbVec3f& p22)
3033 {
3034 SbVec3f da = p12 - p11;
3035 SbVec3f db = p22 - p21;
3036 SbVec3f dc = p21 - p11;
3037
3038 double s = (dc.cross(db)).dot(da.cross(db)) / da.cross(db).sqrLength();
3039 return p11 + da * s;
3040 }
3041
3042 SbVec3f View3DInventorViewer::getPointOnLine(
3043 const SbVec2s& pnt,
3044 const SbVec3f& axisCenter,
3045 const SbVec3f& axis
3046 ) const
3047 {
3048 SbVec2f pnt2d = getNormalizedPosition(pnt);
3049 SoCamera* pCam = this->getSoRenderManager()->getCamera();
3050
3051 if (!pCam) {
3052 // return invalid point
3053 return {};
3054 }
3055
3056 // First we get pnt projection on the focal plane
3057 SbViewVolume vol = pCam->getViewVolume();
3058
3059 float nearDist = pCam->nearDistance.getValue();
3060 float farDist = pCam->farDistance.getValue();
3061 float focalDist = pCam->focalDistance.getValue();
3062
3063 if (focalDist < nearDist || focalDist > farDist) {
3064 focalDist = 0.5F * (nearDist + farDist); // NOLINT
3065 }
3066
3067 SbLine line;
3068 SbVec3f pt, ptOnFocalPlaneAndOnLine, ptOnFocalPlane;
3069 SbPlane focalPlane = vol.getPlane(focalDist);
3070 vol.projectPointToLine(pnt2d, line);
3071 focalPlane.intersect(line, ptOnFocalPlane);
3072
3073 // Check if line is orthogonal to the focal plane
3074 SbVec3f focalPlaneNormal = focalPlane.getNormal();
3075 float dotProduct = fabs(axis.dot(focalPlaneNormal));
3076 if (dotProduct > (1.0 - 1e-6)) {
3077 return ptOnFocalPlane;
3078 }
3079
3080 SbLine projectedLine = projectLineOntoPlane(axisCenter, axisCenter + axis, focalPlane);
3081 ptOnFocalPlaneAndOnLine = projectedLine.getClosestPoint(ptOnFocalPlane);
3082
3083 // now we need the intersection point between
3084 // - the line passing by ptOnFocalPlaneAndOnLine normal to focalPlane
3085 // - The line (axisCenter, axisCenter + axis)
3086
3087 // Line normal to focal plane through ptOnFocalPlaneAndOnLine
3088 SbLine normalLine(ptOnFocalPlaneAndOnLine, ptOnFocalPlaneAndOnLine + focalPlaneNormal);
3089 SbLine axisLine(axisCenter, axisCenter + axis);
3090 pt = intersection(
3091 ptOnFocalPlaneAndOnLine,
3092 ptOnFocalPlaneAndOnLine + focalPlaneNormal,
3093 axisCenter,
3094 axisCenter + axis
3095 );
3096
3097 return pt;
3098 }
3099
3100 SbVec3f View3DInventorViewer::getPointOnFocalPlane(const SbVec2s& pnt) const
3101 {
3102 SbVec2f pnt2d = getNormalizedPosition(pnt);
3103 SoCamera* pCam = this->getSoRenderManager()->getCamera();
3104
3105 if (!pCam) {
3106 // return invalid point
3107 return {};
3108 }
3109
3110 SbViewVolume vol = pCam->getViewVolume();
3111
3112 float nearDist = pCam->nearDistance.getValue();
3113 float farDist = pCam->farDistance.getValue();
3114 float focalDist = pCam->focalDistance.getValue();
3115
3116 if (focalDist < nearDist || focalDist > farDist) {
3117 focalDist = 0.5F * (nearDist + farDist); // NOLINT
3118 }
3119
3120 SbLine line;
3121 SbVec3f pt;
3122 SbPlane focalPlane = vol.getPlane(focalDist);
3123 vol.projectPointToLine(pnt2d, line);
3124 focalPlane.intersect(line, pt);
3125
3126 return pt;
3127 }
3128
3129 SbVec2s View3DInventorViewer::getPointOnViewport(const SbVec3f& pnt) const
3130 {
3131 const SbViewportRegion& vp = this->getSoRenderManager()->getViewportRegion();
3132 float fRatio = vp.getViewportAspectRatio();
3133 const SbVec2s& sp = vp.getViewportSizePixels();
3134 SbViewVolume vv = this->getSoRenderManager()->getCamera()->getViewVolume(fRatio);
3135
3136 SbVec3f pt(pnt);
3137 vv.projectToScreen(pt, pt);
3138
3139 auto xpos = short(std::roundf(pt[0] * sp[0])); // NOLINT
3140 auto ypos = short(std::roundf(pt[1] * sp[1])); // NOLINT
3141
3142 return {xpos, ypos};
3143 }
3144
3145 QPoint View3DInventorViewer::toQPoint(const SbVec2s& pnt) const
3146 {
3147 const SbViewportRegion& vp = this->getSoRenderManager()->getViewportRegion();
3148 const SbVec2s& vps = vp.getViewportSizePixels();
3149 int xpos = pnt[0];
3150 int ypos = vps[1] - pnt[1] - 1;
3151
3152 qreal dev_pix_ratio = devicePixelRatio();
3153 xpos = int(std::roundf(xpos / dev_pix_ratio));
3154 ypos = int(std::roundf(ypos / dev_pix_ratio));
3155
3156 return {xpos, ypos};
3157 }
3158
3159 SbVec2s View3DInventorViewer::fromQPoint(const QPoint& pnt) const
3160 {
3161 const SbViewportRegion& vp = this->getSoRenderManager()->getViewportRegion();
3162 const SbVec2s& vps = vp.getViewportSizePixels();
3163 int xpos = pnt.x();
3164 int ypos = pnt.y();
3165
3166 qreal dev_pix_ratio = devicePixelRatio();
3167 xpos = int(std::roundf(xpos * dev_pix_ratio));
3168 ypos = int(std::roundf(ypos * dev_pix_ratio));
3169
3170 return SbVec2s(short(xpos), vps[1] - short(ypos) - 1);
3171 }
3172
3173 void View3DInventorViewer::getNearPlane(SbVec3f& rcPt, SbVec3f& rcNormal) const
3174 {
3175 SoCamera* pCam = getSoRenderManager()->getCamera();
3176 if (!pCam) {
3177 // just do nothing
3178 return;
3179 }
3180
3181 SbViewVolume vol = pCam->getViewVolume();
3182
3183 // get the normal of the front clipping plane
3184 SbPlane nearPlane = vol.getPlane(vol.nearDist);
3185 float dist = nearPlane.getDistanceFromOrigin();
3186 rcNormal = nearPlane.getNormal();
3187 rcNormal.normalize();
3188 float nx {};
3189 float ny {};
3190 float nz {};
3191 rcNormal.getValue(nx, ny, nz);
3192 rcPt.setValue(dist * rcNormal[0], dist * rcNormal[1], dist * rcNormal[2]);
3193 }
3194
3195 void View3DInventorViewer::getFarPlane(SbVec3f& rcPt, SbVec3f& rcNormal) const
3196 {
3197 SoCamera* pCam = getSoRenderManager()->getCamera();
3198 if (!pCam) {
3199 // just do nothing
3200 return;
3201 }
3202
3203 SbViewVolume vol = pCam->getViewVolume();
3204
3205 // get the normal of the back clipping plane
3206 SbPlane farPlane = vol.getPlane(vol.nearDist + vol.nearToFar);
3207 float dist = farPlane.getDistanceFromOrigin();
3208 rcNormal = farPlane.getNormal();
3209 rcNormal.normalize();
3210 float nx {};
3211 float ny {};
3212 float nz {};
3213 rcNormal.getValue(nx, ny, nz);
3214 rcPt.setValue(dist * rcNormal[0], dist * rcNormal[1], dist * rcNormal[2]);
3215 }
3216
3217 SbVec3f View3DInventorViewer::projectOnNearPlane(const SbVec2f& pt) const
3218 {
3219 SbVec3f pt1;
3220 SbVec3f pt2;
3221 SoCamera* cam = this->getSoRenderManager()->getCamera();
3222
3223 // return invalid point
3224 if (!cam) {
3225 return {};
3226 }
3227
3228 SbViewVolume vol = cam->getViewVolume();
3229 vol.projectPointToLine(pt, pt1, pt2);
3230 return pt1;
3231 }
3232
3233 SbVec3f View3DInventorViewer::projectOnFarPlane(const SbVec2f& pt) const
3234 {
3235 SbVec3f pt1;
3236 SbVec3f pt2;
3237 SoCamera* cam = this->getSoRenderManager()->getCamera();
3238
3239 // return invalid point
3240 if (!cam) {
3241 return {};
3242 }
3243
3244 SbViewVolume vol = cam->getViewVolume();
3245 vol.projectPointToLine(pt, pt1, pt2);
3246 return pt2;
3247 }
3248
3249 void View3DInventorViewer::projectPointToLine(const SbVec2s& pt, SbVec3f& pt1, SbVec3f& pt2) const
3250 {
3251 SbVec2f pnt2d = getNormalizedPosition(pt);
3252 SoCamera* pCam = this->getSoRenderManager()->getCamera();
3253
3254 if (!pCam) {
3255 return;
3256 }
3257
3258 SbViewVolume vol = pCam->getViewVolume();
3259 vol.projectPointToLine(pnt2d, pt1, pt2);
3260 }
3261
3262 void View3DInventorViewer::toggleClippingPlane(
3263 int toggle,
3264 bool beforeEditing,
3265 bool noManip,
3266 const Base::Placement& pla
3267 )
3268 {
3269 if (pcClipPlane) {
3270 if (toggle <= 0) {
3271 pcViewProviderRoot->removeChild(pcClipPlane);
3272 pcClipPlane->unref();
3273 pcClipPlane = nullptr;
3274 }
3275 return;
3276 }
3277
3278 if (toggle == 0) {
3279 return;
3280 }
3281
3282 Base::Vector3d dir;
3283 pla.getRotation().multVec(Base::Vector3d(0, 0, -1), dir);
3284 Base::Vector3d base = pla.getPosition();
3285
3286 if (!noManip) {
3287 auto clip = new SoClipPlaneManip;
3288 pcClipPlane = clip;
3289 SbBox3f box = getBoundingBox();
3290
3291 if (!box.isEmpty()) {
3292 // adjust to overall bounding box of the scene
3293 clip->setValue(box, Base::convertTo<SbVec3f>(dir), 1.0F);
3294 }
3295 }
3296 else {
3297 pcClipPlane = new SoClipPlane;
3298 }
3299
3300 pcClipPlane->plane.setValue(SbPlane(Base::convertTo<SbVec3f>(dir), Base::convertTo<SbVec3f>(base)));
3301 pcClipPlane->ref();
3302 if (beforeEditing) {
3303 pcViewProviderRoot->insertChild(pcClipPlane, 0);
3304 }
3305 else {
3306 pcViewProviderRoot->insertChild(pcClipPlane, pcViewProviderRoot->findChild(pcEditingRoot) + 1);
3307 }
3308 }
3309
3310 bool View3DInventorViewer::hasClippingPlane() const
3311 {
3312 return pcClipPlane != nullptr;
3313 }
3314
3315 /**
3316 * This method picks the closest point to the camera in the underlying scenegraph
3317 * and returns its location and normal.
3318 * If no point was picked false is returned.
3319 */
3320 bool View3DInventorViewer::pickPoint(const SbVec2s& pos, SbVec3f& point, SbVec3f& norm) const
3321 {
3322 // attempting raypick in the event_cb() callback method
3323 SoRayPickAction rp(getSoRenderManager()->getViewportRegion());
3324 rp.setPoint(pos);
3325 rp.apply(getSoRenderManager()->getSceneGraph());
3326 SoPickedPoint* Point = rp.getPickedPoint();
3327
3328 if (Point) {
3329 point = Point->getObjectPoint();
3330 norm = Point->getObjectNormal();
3331 return true;
3332 }
3333
3334 return false;
3335 }
3336
3337 /**
3338 * This method is provided for convenience and does basically the same as method
3339 * above unless that it returns an SoPickedPoint object with additional information.
3340 * \note It is in the response of the client programmer to delete the returned
3341 * SoPickedPoint object.
3342 */
3343 SoPickedPoint* View3DInventorViewer::pickPoint(const SbVec2s& pos) const
3344 {
3345 SoRayPickAction rp(getSoRenderManager()->getViewportRegion());
3346 rp.setPoint(pos);
3347 rp.apply(getSoRenderManager()->getSceneGraph());
3348
3349 // returns a copy of the point
3350 SoPickedPoint* pick = rp.getPickedPoint();
3351 // return (pick ? pick->copy() : 0); // needs the same instance of CRT under MS Windows
3352 return (pick ? new SoPickedPoint(*pick) : nullptr);
3353 }
3354
3355 const SoPickedPoint* View3DInventorViewer::getPickedPoint(SoEventCallback* n) const
3356 {
3357 if (selectionRoot) {
3358 auto ret = selectionRoot->getPickedList(n->getAction(), true);
3359 if (!ret.empty()) {
3360 return ret[0].pp;
3361 }
3362 return nullptr;
3363 }
3364 return n->getPickedPoint();
3365 }
3366
3367 bool View3DInventorViewer::pubSeekToPoint(const SbVec2s& pos)
3368 {
3369 return this->seekToPoint(pos);
3370 }
3371
3372 void View3DInventorViewer::pubSeekToPoint(const SbVec3f& pos)
3373 {
3374 this->seekToPoint(pos);
3375 }
3376
3377 std::shared_ptr<NavigationAnimation> View3DInventorViewer::setCameraOrientation(
3378 const SbRotation& orientation,
3379 const bool moveToCenter
3380 ) const
3381 {
3382 return navigation->setCameraOrientation(orientation, moveToCenter);
3383 }
3384
3385 void View3DInventorViewer::setCameraType(SoType type)
3386 {
3387 inherited::setCameraType(type);
3388
3389 SoCamera* cam = this->getSoRenderManager()->getCamera();
3390
3391 if (!cam) {
3392 return;
3393 }
3394
3395 if (type.isDerivedFrom(SoPerspectiveCamera::getClassTypeId())) {
3396 // When doing a viewAll() for an orthographic camera and switching
3397 // to perspective the scene looks completely strange because of the
3398 // heightAngle. Setting it to 45 deg also causes an issue with a too
3399 // close camera but we don't have this other ugly effect.
3400
3401 static_cast<SoPerspectiveCamera*>(cam)->heightAngle = (float)(std::numbers::pi / 4.0); // NOLINT
3402 }
3403
3404 lightRotation->rotation.connectFrom(&cam->orientation);
3405 }
3406
3407 void View3DInventorViewer::moveCameraTo(const SbRotation& orientation, const SbVec3f& position, int duration)
3408 {
3409 SoCamera* camera = getCamera();
3410 if (!camera) {
3411 return;
3412 }
3413
3414 if (isAnimationEnabled()) {
3415 startAnimation(
3416 orientation,
3417 camera->position.getValue(),
3418 position - camera->position.getValue(),
3419 duration,
3420 true
3421 );
3422 }
3423
3424 camera->orientation.setValue(orientation);
3425 camera->position.setValue(position);
3426 }
3427
3428 void View3DInventorViewer::animatedViewAll(int steps, int ms)
3429 {
3430 SoCamera* cam = this->getSoRenderManager()->getCamera();
3431 if (!cam) {
3432 return;
3433 }
3434
3435 SbVec3f campos = cam->position.getValue();
3436 SbRotation camrot = cam->orientation.getValue();
3437 SbViewportRegion vp = this->getSoRenderManager()->getViewportRegion();
3438 SbBox3f box = getBoundingBox();
3439
3440 float aspectRatio = vp.getViewportAspectRatio();
3441
3442 if (box.isEmpty()) {
3443 return;
3444 }
3445
3446 SbSphere sphere;
3447 sphere.circumscribe(box);
3448 if (sphere.getRadius() == 0) {
3449 return;
3450 }
3451
3452 SbVec3f direction;
3453 SbVec3f pos(0.0F, 0.0F, 0.0F);
3454 camrot.multVec(SbVec3f(0, 0, -1), direction);
3455
3456 bool isOrthographic = false;
3457 float height = 0;
3458 float diff = 0;
3459
3460 if (cam->isOfType(SoOrthographicCamera::getClassTypeId())) {
3461 isOrthographic = true;
3462 height = static_cast<SoOrthographicCamera*>(cam)->height.getValue(); // NOLINT
3463 if (aspectRatio < 1.0F) {
3464 diff = sphere.getRadius() * 2 - height * aspectRatio;
3465 }
3466 else {
3467 diff = sphere.getRadius() * 2 - height;
3468 }
3469 pos = (box.getCenter() - direction * sphere.getRadius());
3470 }
3471 else if (cam->isOfType(SoPerspectiveCamera::getClassTypeId())) {
3472 // NOLINTBEGIN
3473 float movelength = sphere.getRadius()
3474 / float(tan(static_cast<SoPerspectiveCamera*>(cam)->heightAngle.getValue() / 2.0));
3475 // NOLINTEND
3476 pos = box.getCenter() - direction * movelength;
3477 }
3478
3479 QEventLoop loop;
3480 QTimer timer;
3481 timer.setSingleShot(true);
3482 QObject::connect(&timer, &QTimer::timeout, &loop, &QEventLoop::quit);
3483
3484 for (int i = 0; i < steps; i++) {
3485 float par = float(i) / float(steps);
3486
3487 if (isOrthographic) {
3488 float camHeight = height + diff * par;
3489 static_cast<SoOrthographicCamera*>(cam)->height.setValue(camHeight); // NOLINT
3490 }
3491
3492 SbVec3f curpos = campos * (1.0F - par) + pos * par;
3493 cam->position.setValue(curpos);
3494 timer.start(Base::clamp<int>(ms, 0, 5000)); // NOLINT
3495 loop.exec(QEventLoop::ExcludeUserInputEvents);
3496 }
3497 }
3498
3499 #if BUILD_VR
3500 extern View3DInventorRiftViewer* oculusStart(void);
3501 extern bool oculusUp(void);
3502 extern void oculusStop(void);
3503 void oculusSetTestScene(View3DInventorRiftViewer* window);
3504 #endif
3505
3506 void View3DInventorViewer::viewVR()
3507 {
3508 #if BUILD_VR
3509 if (oculusUp()) {
3510 oculusStop();
3511 }
3512 else {
3513 View3DInventorRiftViewer* riftWin = oculusStart();
3514 riftWin->setSceneGraph(pcViewProviderRoot);
3515 }
3516 #endif
3517 }
3518
3519 void View3DInventorViewer::boxZoom(const SbBox2s& box)
3520 {
3521 navigation->boxZoom(box);
3522 }
3523 void View3DInventorViewer::scale(float factor)
3524 {
3525 navigation->scale(factor);
3526 }
3527
3528 SbBox3f View3DInventorViewer::getBoundingBox() const
3529 {
3530 SbViewportRegion vp = this->getSoRenderManager()->getViewportRegion();
3531 SoGetBoundingBoxAction action(vp);
3532 action.apply(this->getSoRenderManager()->getSceneGraph());
3533 return action.getBoundingBox();
3534 }
3535
3536 void View3DInventorViewer::viewAll()
3537 {
3538 // in the scene graph we may have objects which we want to exclude
3539 // when doing a fit all. Such objects must be part of the group
3540 // SoSkipBoundingGroup.
3541 SoSearchAction sa;
3542 sa.setType(SoSkipBoundingGroup::getClassTypeId());
3543 sa.setInterest(SoSearchAction::ALL);
3544 sa.apply(this->getSoRenderManager()->getSceneGraph());
3545 const SoPathList& pathlist = sa.getPaths();
3546
3547 for (int i = 0; i < pathlist.getLength(); i++) {
3548 SoPath* path = pathlist[i];
3549 auto group = static_cast<SoSkipBoundingGroup*>(path->getTail()); // NOLINT
3550 group->mode = SoSkipBoundingGroup::EXCLUDE_BBOX;
3551 }
3552
3553 SbBox3f box = getBoundingBox();
3554
3555 if (!box.isEmpty()) {
3556 SbSphere sphere;
3557 sphere.circumscribe(box);
3558 if (sphere.getRadius() != 0) {
3559 // Set the height angle to 45 deg
3560 SoCamera* cam = this->getSoRenderManager()->getCamera();
3561
3562 if (cam && cam->getTypeId().isDerivedFrom(SoPerspectiveCamera::getClassTypeId())) {
3563 static_cast<SoPerspectiveCamera*>(cam)->heightAngle = (float)(std::numbers::pi
3564 / 4.0); // NOLINT
3565 }
3566
3567 if (isAnimationEnabled()) {
3568 animatedViewAll(10, 20); // NOLINT
3569 }
3570
3571 // make sure everything is visible
3572 if (cam) {
3573 cam->viewAll(
3574 getSoRenderManager()->getSceneGraph(),
3575 this->getSoRenderManager()->getViewportRegion()
3576 );
3577 }
3578 }
3579 }
3580
3581 for (int i = 0; i < pathlist.getLength(); i++) {
3582 SoPath* path = pathlist[i];
3583 auto group = static_cast<SoSkipBoundingGroup*>(path->getTail()); // NOLINT
3584 group->mode = SoSkipBoundingGroup::INCLUDE_BBOX;
3585 }
3586 }
3587
3588 void View3DInventorViewer::viewAll(float factor)
3589 {
3590 SoCamera* cam = this->getSoRenderManager()->getCamera();
3591 if (!cam) {
3592 return;
3593 }
3594
3595 if (factor <= 0.0F) {
3596 return;
3597 }
3598
3599 if (factor != 1.0F) {
3600 SoSearchAction sa;
3601 sa.setType(SoSkipBoundingGroup::getClassTypeId());
3602 sa.setInterest(SoSearchAction::ALL);
3603 sa.apply(this->getSoRenderManager()->getSceneGraph());
3604 const SoPathList& pathlist = sa.getPaths();
3605
3606 for (int i = 0; i < pathlist.getLength(); i++) {
3607 SoPath* path = pathlist[i];
3608 auto group = static_cast<SoSkipBoundingGroup*>(path->getTail()); // NOLINT
3609 group->mode = SoSkipBoundingGroup::EXCLUDE_BBOX;
3610 }
3611
3612 SbBox3f box = getBoundingBox();
3613 float minx {};
3614 float miny {};
3615 float minz {};
3616 float maxx {};
3617 float maxy {};
3618 float maxz {};
3619 box.getBounds(minx, miny, minz, maxx, maxy, maxz);
3620
3621 for (int i = 0; i < pathlist.getLength(); i++) {
3622 SoPath* path = pathlist[i];
3623 auto group = static_cast<SoSkipBoundingGroup*>(path->getTail()); // NOLINT
3624 group->mode = SoSkipBoundingGroup::INCLUDE_BBOX;
3625 }
3626
3627 auto cube = new SoCube();
3628 cube->width = factor * (maxx - minx);
3629 cube->height = factor * (maxy - miny);
3630 cube->depth = factor * (maxz - minz);
3631
3632 // fake a scenegraph with the desired bounding size
3633 auto graph = new SoSeparator();
3634 graph->ref();
3635 auto tr = new SoTranslation();
3636 tr->translation.setValue(box.getCenter());
3637
3638 graph->addChild(tr);
3639 graph->addChild(cube);
3640 cam->viewAll(graph, this->getSoRenderManager()->getViewportRegion());
3641 graph->unref();
3642 }
3643 else {
3644 viewAll();
3645 }
3646 }
3647
3648 void View3DInventorViewer::viewSelection()
3649 {
3650 Base::BoundBox3d bbox;
3651 for (auto& sel : Selection().getSelection(nullptr, ResolveMode::NoResolve)) {
3652 auto vp = Application::Instance->getViewProvider(sel.pObject);
3653 if (!vp) {
3654 continue;
3655 }
3656 bbox.Add(vp->getBoundingBox(sel.SubName, true));
3657 }
3658
3659 SoCamera* cam = this->getSoRenderManager()->getCamera();
3660 if (cam && bbox.IsValid()) {
3661 SbBox3f box(
3662 float(bbox.MinX),
3663 float(bbox.MinY),
3664 float(bbox.MinZ),
3665 float(bbox.MaxX),
3666 float(bbox.MaxY),
3667 float(bbox.MaxZ)
3668 );
3669 float aspectratio = getSoRenderManager()->getViewportRegion().getViewportAspectRatio();
3670 switch (cam->viewportMapping.getValue()) {
3671 case SoCamera::CROP_VIEWPORT_FILL_FRAME:
3672 case SoCamera::CROP_VIEWPORT_LINE_FRAME:
3673 case SoCamera::CROP_VIEWPORT_NO_FRAME:
3674 aspectratio = 1.0F;
3675 break;
3676 default:
3677 break;
3678 }
3679 cam->viewBoundingBox(box, aspectratio, 1.0);
3680 }
3681 }
3682
3683 void View3DInventorViewer::alignToSelection()
3684 {
3685 if (!getCamera()) {
3686 return;
3687 }
3688
3689 const auto selection = Selection().getSelection(nullptr, ResolveMode::NoResolve);
3690
3691 // Empty selection
3692 if (selection.empty()) {
3693 return;
3694 }
3695
3696 // Too much selections
3697 if (selection.size() > 1) {
3698 return;
3699 }
3700
3701 // Get the geo feature
3702 App::GeoFeature* geoFeature = nullptr;
3703 App::ElementNamePair elementName;
3704 App::GeoFeature::resolveElement(
3705 selection[0].pObject,
3706 selection[0].SubName,
3707 elementName,
3708 true,
3709 App::GeoFeature::ElementNameType::Normal,
3710 nullptr,
3711 nullptr,
3712 &geoFeature
3713 );
3714 if (!geoFeature) {
3715 return;
3716 }
3717
3718 const auto globalPlacement = App::GeoFeature::getGlobalPlacement(
3719 selection[0].pResolvedObject,
3720 selection[0].pObject,
3721 elementName.oldName
3722 );
3723 const auto globalRotation = globalPlacement.getRotation()
3724 * geoFeature->Placement.getValue().getRotation().inverse();
3725 const auto splitSubName = Base::Tools::splitSubName(elementName.oldName);
3726 const auto geoFeatureSubName = !splitSubName.empty() ? splitSubName.back() : "";
3727
3728 Base::Vector3d alignmentZ;
3729 Base::Vector3d alignmentX(0, 0, 0);
3730 if (geoFeature->getCameraAlignmentDirection(alignmentZ, alignmentX, geoFeatureSubName.c_str())) {
3731
3732 // Find a x alignment if the geoFeature did not suggest any
3733 if (alignmentX == Base::Vector3d(0, 0, 0)) {
3734 Base::Rotation(-Base::Vector3d::UnitZ, alignmentZ).multVec(Base::Vector3d::UnitX, alignmentX);
3735 }
3736
3737 // Convert to global coordinates
3738 globalRotation.multVec(alignmentZ, alignmentZ);
3739 globalRotation.multVec(alignmentX, alignmentX);
3740
3741 const auto cameraOrientation = getCameraOrientation();
3742
3743 auto directionZ = Base::convertTo<SbVec3f>(alignmentZ);
3744 auto directionX = Base::convertTo<SbVec3f>(alignmentX);
3745
3746 SbVec3f cameraZ;
3747 cameraOrientation.multVec(SbVec3f(0, 0, 1), cameraZ);
3748
3749 // Negate if the camera is closer to the opposite direction
3750 if (cameraZ.dot(directionZ) < 0) {
3751 directionZ.negate();
3752 }
3753
3754 // Rotate the camera to align with directionZ by the smallest angle to align the z-axis
3755 const SbRotation intermediateOrientation = cameraOrientation
3756 * SbRotation(cameraZ, directionZ);
3757
3758 SbVec3f intermediateX;
3759 intermediateOrientation.multVec(SbVec3f(1, 0, 0), intermediateX);
3760
3761 // Find angle between directionX and intermediateX
3762 const SbRotation rotation(directionX, intermediateX);
3763 SbVec3f axis;
3764 float angle;
3765 rotation.getValue(axis, angle);
3766
3767 // Flip the sign of the angle if axis and directionZ are in opposite direction
3768 if (axis.dot(directionZ) < 0 && angle != 0) {
3769 angle *= -1;
3770 }
3771
3772 constexpr auto pi = std::numbers::pi_v<float>;
3773
3774 // Make angle positive
3775 if (angle < 0) {
3776 angle += 2 * pi;
3777 }
3778
3779 // Find the angle to rotate to the nearest horizontal or vertical alignment with directionX.
3780 // f is a small value used to get more deterministic behavior when the camera is at
3781 // directionX +- 45 degrees.
3782 const float f = 0.00001F;
3783
3784 if (angle <= pi / 4 + f) {
3785 angle = 0;
3786 }
3787 else if (angle <= 3 * pi / 4 + f) {
3788 angle = pi / 2;
3789 }
3790 else if (angle < pi + pi / 4 - f) {
3791 angle = pi;
3792 }
3793 else if (angle < pi + 3 * pi / 4 - f) {
3794 angle = pi + pi / 2;
3795 }
3796 else {
3797 angle = 0;
3798 }
3799
3800 SbRotation(directionZ, angle).multVec(directionX, directionX);
3801
3802 const SbVec3f directionY = directionZ.cross(directionX);
3803
3804 const auto orientation = SbRotation(SbMatrix(
3805 directionX[0],
3806 directionX[1],
3807 directionX[2],
3808 0,
3809 directionY[0],
3810 directionY[1],
3811 directionY[2],
3812 0,
3813 directionZ[0],
3814 directionZ[1],
3815 directionZ[2],
3816 0,
3817 0,
3818 0,
3819 0,
3820 1
3821 ));
3822
3823 setCameraOrientation(orientation);
3824 }
3825 }
3826
3827 /**
3828 * @brief Decide if it should be possible to start any animation
3829 *
3830 * If the enable flag is false and we're currently animating, the animation will be stopped
3831 */
3832 void View3DInventorViewer::setAnimationEnabled(bool enable)
3833 {
3834 navigation->setAnimationEnabled(enable);
3835 }
3836
3837 /**
3838 * @brief Decide if it should be possible to start a spin animation of the model in the viewer by
3839 * releasing the mouse button while dragging
3840 *
3841 * If the enable flag is false and we're currently animating, the spin animation will be stopped
3842 */
3843 void View3DInventorViewer::setSpinningAnimationEnabled(bool enable)
3844 {
3845 navigation->setSpinningAnimationEnabled(enable);
3846 }
3847
3848 /**
3849 * @return Whether or not it is possible to start any animation
3850 */
3851 bool View3DInventorViewer::isAnimationEnabled() const
3852 {
3853 return navigation->isAnimationEnabled();
3854 }
3855
3856 /**
3857 * @return Whether or not it is possible to start a spinning animation e.g. after dragging
3858 */
3859 bool View3DInventorViewer::isSpinningAnimationEnabled() const
3860 {
3861 return navigation->isSpinningAnimationEnabled();
3862 }
3863
3864 /**
3865 * @return Whether or not any animation is currently active
3866 */
3867 bool View3DInventorViewer::isAnimating() const
3868 {
3869 return navigation->isAnimating();
3870 }
3871
3872 /**
3873 * @return Whether or not a spinning animation is currently active e.g. after a user drag
3874 */
3875 bool View3DInventorViewer::isSpinning() const
3876 {
3877 return navigation->isSpinning();
3878 }
3879
3880 /**
3881 * @brief Change the camera pose with an animation
3882 *
3883 * @param orientation The new orientation
3884 * @param rotationCenter The rotation center
3885 * @param translation An additional translation on top of the translation caused by the rotation
3886 * around the rotation center
3887 * @param duration The duration in milliseconds
3888 * @param wait When false, start the animation and continue (asynchronous). When true, start the
3889 * animation and wait for the animation to finish (synchronous)
3890 *
3891 * @return The started @class NavigationAnimation
3892 */
3893 std::shared_ptr<NavigationAnimation> View3DInventorViewer::startAnimation(
3894 const SbRotation& orientation,
3895 const SbVec3f& rotationCenter,
3896 const SbVec3f& translation,
3897 int duration,
3898 const bool wait
3899 ) const
3900 {
3901 // Currently starts a FixedTimeAnimation. If there is going to be an additional animation like
3902 // FixedVelocityAnimation, check the animation type from a parameter and start the right animation
3903
3904 // Duration was not set or is invalid so use the AnimationDuration parameter as default
3905 if (duration < 0) {
3906 duration = App::GetApplication()
3907 .GetParameterGroupByPath("User parameter:BaseApp/Preferences/View")
3908 ->GetInt("AnimationDuration", 500);
3909 }
3910
3911 QEasingCurve::Type easingCurve = static_cast<QEasingCurve::Type>(
3912 App::GetApplication()
3913 .GetParameterGroupByPath("User parameter:BaseApp/Preferences/View")
3914 ->GetInt("NavigationAnimationEasingCurve", QEasingCurve::Type::InOutCubic)
3915 );
3916
3917 auto animation = std::make_shared<FixedTimeAnimation>(
3918 navigation,
3919 orientation,
3920 rotationCenter,
3921 translation,
3922 duration,
3923 easingCurve
3924 );
3925
3926 navigation->startAnimating(animation, wait);
3927
3928 return animation;
3929 }
3930
3931 /**
3932 * @brief Start an infinite spin animation
3933 *
3934 * @param axis The rotation axis in screen coordinates
3935 * @param velocity The angular velocity in radians per second
3936 */
3937 void View3DInventorViewer::startSpinningAnimation(const SbVec3f& axis, float velocity)
3938 {
3939 auto animation = std::make_shared<SpinningAnimation>(navigation, axis, velocity);
3940 navigation->startAnimating(animation);
3941 }
3942
3943 void View3DInventorViewer::stopAnimating()
3944 {
3945 navigation->stopAnimating();
3946 }
3947
3948 void View3DInventorViewer::setPopupMenuEnabled(bool on)
3949 {
3950 navigation->setPopupMenuEnabled(on);
3951 }
3952
3953 bool View3DInventorViewer::isPopupMenuEnabled() const
3954 {
3955 return navigation->isPopupMenuEnabled();
3956 }
3957
3958 /*!
3959 Set the flag deciding whether or not to show the axis cross.
3960 */
3961
3962 void View3DInventorViewer::setFeedbackVisibility(bool enable)
3963 {
3964 if (enable == this->axiscrossEnabled) {
3965 return;
3966 }
3967
3968 this->axiscrossEnabled = enable;
3969
3970 if (this->isViewing()) {
3971 this->getSoRenderManager()->scheduleRedraw();
3972 }
3973 }
3974
3975 /*!
3976 Check if the feedback axis cross is visible.
3977 */
3978
3979 bool View3DInventorViewer::isFeedbackVisible() const
3980 {
3981 return this->axiscrossEnabled;
3982 }
3983
3984 /*!
3985 Set the size of the feedback axiscross. The value is interpreted as
3986 an approximate percentage chunk of the dimensions of the total
3987 canvas.
3988 */
3989 void View3DInventorViewer::setFeedbackSize(int size)
3990 {
3991 if (size < 1) {
3992 return;
3993 }
3994
3995 this->axiscrossSize = size;
3996
3997 if (this->isFeedbackVisible() && this->isViewing()) {
3998 this->getSoRenderManager()->scheduleRedraw();
3999 }
4000 }
4001
4002 /*!
4003 Return the size of the feedback axis cross. Default is 10.
4004 */
4005
4006 int View3DInventorViewer::getFeedbackSize() const
4007 {
4008 return this->axiscrossSize;
4009 }
4010
4011 /*!
4012 Decide whether or not the mouse pointer cursor should be visible in
4013 the rendering canvas.
4014 */
4015 void View3DInventorViewer::setCursorEnabled(bool /*enable*/)
4016 {
4017 this->setCursorRepresentation(navigation->getViewingMode());
4018 }
4019
4020 void View3DInventorViewer::afterRealizeHook()
4021 {
4022 inherited::afterRealizeHook();
4023 this->setCursorRepresentation(navigation->getViewingMode());
4024 }
4025
4026 // Documented in superclass. This method overridden from parent class
4027 // to make sure the mouse pointer cursor is updated.
4028 void View3DInventorViewer::setViewing(bool enable)
4029 {
4030 if (this->isViewing() == enable) {
4031 return;
4032 }
4033
4034 navigation->setViewingMode(enable ? NavigationStyle::IDLE : NavigationStyle::INTERACT);
4035 inherited::setViewing(enable);
4036 }
4037
4038 unsigned char View3DInventorViewer::XPM_pixel_data[XPM_WIDTH * XPM_HEIGHT * XPM_BYTES_PER_PIXEL + 1]
4039 = {};
4040 unsigned char View3DInventorViewer::YPM_pixel_data[YPM_WIDTH * YPM_HEIGHT * YPM_BYTES_PER_PIXEL + 1]
4041 = {};
4042 unsigned char View3DInventorViewer::ZPM_pixel_data[ZPM_WIDTH * ZPM_HEIGHT * ZPM_BYTES_PER_PIXEL + 1]
4043 = {};
4044
4045 void View3DInventorViewer::setAxisLetterColor(const SbColor& color)
4046 {
4047 unsigned packed = color.getPackedValue();
4048
4049 auto recolor = [&](const unsigned char* mask,
4050 unsigned char* data,
4051 unsigned width,
4052 unsigned height,
4053 unsigned bitdepth) {
4054 for (unsigned y = 0; y < height; y++) {
4055 for (unsigned x = 0; x < width; x++) {
4056 unsigned offset = (y * width + x) * bitdepth;
4057
4058 const unsigned char* src = &mask[offset];
4059 unsigned char* dst = &data[offset];
4060
4061 dst[0] = (packed >> 24) & 0xFF; // RR - from color
4062 dst[1] = (packed >> 16) & 0xFF; // GG - from color
4063 dst[2] = (packed >> 8) & 0xFF; // BB - from color
4064 dst[3] = src[3]; // AA - from mask
4065 }
4066 }
4067 };
4068
4069 recolor(XPM_PIXEL_MASK, XPM_pixel_data, XPM_WIDTH, XPM_HEIGHT, XPM_BYTES_PER_PIXEL);
4070 recolor(YPM_PIXEL_MASK, YPM_pixel_data, YPM_WIDTH, YPM_HEIGHT, YPM_BYTES_PER_PIXEL);
4071 recolor(ZPM_PIXEL_MASK, ZPM_pixel_data, ZPM_WIDTH, ZPM_HEIGHT, ZPM_BYTES_PER_PIXEL);
4072 }
4073
4074 void View3DInventorViewer::updateColors()
4075 {
4076 unsigned long colorLong;
4077
4078 colorLong = Gui::ViewParams::instance()->getAxisXColor();
4079 m_xColor = Base::Color(static_cast<uint32_t>(colorLong));
4080 colorLong = Gui::ViewParams::instance()->getAxisYColor();
4081 m_yColor = Base::Color(static_cast<uint32_t>(colorLong));
4082 colorLong = Gui::ViewParams::instance()->getAxisZColor();
4083 m_zColor = Base::Color(static_cast<uint32_t>(colorLong));
4084
4085 naviCube->updateColors();
4086
4087 if (hasAxisCross()) {
4088 setAxisCross(false); // Force redraw
4089 setAxisCross(true);
4090 }
4091 }
4092
4093 void View3DInventorViewer::drawAxisCross()
4094 {
4095 // NOLINTBEGIN
4096 // FIXME: convert this to a superimposition scenegraph instead of
4097 // OpenGL calls. 20020603 mortene.
4098
4099 // Store GL state.
4100 glPushAttrib(GL_ALL_ATTRIB_BITS);
4101 GLfloat depthrange[2];
4102 glGetFloatv(GL_DEPTH_RANGE, depthrange);
4103 GLdouble projectionmatrix[16];
4104 glGetDoublev(GL_PROJECTION_MATRIX, projectionmatrix);
4105
4106 glDepthFunc(GL_ALWAYS);
4107 glDepthMask(GL_TRUE);
4108 glDepthRange(0, 0);
4109 glEnable(GL_DEPTH_TEST);
4110 glDisable(GL_LIGHTING);
4111 glEnable(GL_COLOR_MATERIAL);
4112 glDisable(GL_BLEND); // Kills transparency.
4113
4114 // Set the viewport in the OpenGL canvas. Dimensions are calculated
4115 // as a percentage of the total canvas size.
4116 SbVec2s view = this->getSoRenderManager()->getSize();
4117 const int pixelarea = int(float(this->axiscrossSize) / 100.0F * std::min(view[0], view[1]));
4118 SbVec2s origin(view[0] - pixelarea, 0);
4119 glViewport(origin[0], origin[1], pixelarea, pixelarea);
4120
4121 // Set up the projection matrix.
4122 glMatrixMode(GL_PROJECTION);
4123 glLoadIdentity();
4124
4125 const float NEARVAL = 0.1F;
4126 const float FARVAL = 10.0F;
4127 const float dim = NEARVAL * float(tan(std::numbers::pi / 8.0)); // FOV is 45 deg (45/360 = 1/8)
4128 glFrustum(-dim, dim, -dim, dim, NEARVAL, FARVAL);
4129
4130
4131 // Set up the model matrix.
4132 glMatrixMode(GL_MODELVIEW);
4133 glPushMatrix();
4134 SbMatrix mx;
4135 SoCamera* cam = this->getSoRenderManager()->getCamera();
4136
4137 // If there is no camera (like for an empty scene, for instance),
4138 // just use an identity rotation.
4139 if (cam) {
4140 mx = cam->orientation.getValue();
4141 }
4142 else {
4143 mx = SbMatrix::identity();
4144 }
4145
4146 mx = mx.inverse();
4147 mx[3][2] = -3.5; // Translate away from the projection point (along z axis).
4148 glLoadMatrixf((float*)mx);
4149
4150
4151 // Find unit vector end points.
4152 SbMatrix px;
4153 glGetFloatv(GL_PROJECTION_MATRIX, (float*)px);
4154 SbMatrix comb = mx.multRight(px); // clazy:exclude=rule-of-two-soft
4155
4156 SbVec3f xpos;
4157 comb.multVecMatrix(SbVec3f(1, 0, 0), xpos);
4158 xpos[0] = (1 + xpos[0]) * view[0] / 2;
4159 xpos[1] = (1 + xpos[1]) * view[1] / 2;
4160 SbVec3f ypos;
4161 comb.multVecMatrix(SbVec3f(0, 1, 0), ypos);
4162 ypos[0] = (1 + ypos[0]) * view[0] / 2;
4163 ypos[1] = (1 + ypos[1]) * view[1] / 2;
4164 SbVec3f zpos;
4165 comb.multVecMatrix(SbVec3f(0, 0, 1), zpos);
4166 zpos[0] = (1 + zpos[0]) * view[0] / 2;
4167 zpos[1] = (1 + zpos[1]) * view[1] / 2;
4168
4169
4170 // Render the cross.
4171 {
4172 glLineWidth(2.0);
4173
4174 enum
4175 {
4176 XAXIS,
4177 YAXIS,
4178 ZAXIS
4179 };
4180 int idx[3] = {XAXIS, YAXIS, ZAXIS};
4181 float val[3] = {xpos[2], ypos[2], zpos[2]};
4182
4183 // Bubble sort.. :-}
4184 if (val[0] < val[1]) {
4185 std::swap(val[0], val[1]);
4186 std::swap(idx[0], idx[1]);
4187 }
4188
4189 if (val[1] < val[2]) {
4190 std::swap(val[1], val[2]);
4191 std::swap(idx[1], idx[2]);
4192 }
4193
4194 if (val[0] < val[1]) {
4195 std::swap(val[0], val[1]);
4196 std::swap(idx[0], idx[1]);
4197 }
4198
4199 assert((val[0] >= val[1]) && (val[1] >= val[2])); // Just checking..
4200
4201 for (const int& i : idx) {
4202 glPushMatrix();
4203
4204 if (i == XAXIS) { // X axis.
4205 if (stereoMode() != Quarter::SoQTQuarterAdaptor::MONO) { // What is this
4206 glColor3f(0.500F, 0.5F, 0.5F); // Why different colors??
4207 }
4208 else {
4209 glColor3f(m_xColor.r, m_xColor.g, m_xColor.b);
4210 }
4211 }
4212 else if (i == YAXIS) { // Y axis.
4213 glRotatef(90, 0, 0, 1);
4214
4215 if (stereoMode() != Quarter::SoQTQuarterAdaptor::MONO) {
4216 glColor3f(0.400F, 0.4F, 0.4F);
4217 }
4218 else {
4219 glColor3f(m_yColor.r, m_yColor.g, m_yColor.b);
4220 }
4221 }
4222 else { // Z axis.
4223 glRotatef(-90, 0, 1, 0);
4224
4225 if (stereoMode() != Quarter::SoQTQuarterAdaptor::MONO) {
4226 glColor3f(0.300F, 0.3F, 0.3F);
4227 }
4228 else {
4229 glColor3f(m_zColor.r, m_zColor.g, m_zColor.b);
4230 }
4231 }
4232
4233 drawArrow();
4234 glPopMatrix();
4235 }
4236 }
4237
4238 // Render axis notation letters ("X", "Y", "Z").
4239 glMatrixMode(GL_PROJECTION);
4240 glLoadIdentity();
4241 glOrtho(0, view[0], 0, view[1], -1, 1);
4242
4243 glMatrixMode(GL_MODELVIEW);
4244 glLoadIdentity();
4245
4246 GLint unpack {};
4247 glGetIntegerv(GL_UNPACK_ALIGNMENT, &unpack);
4248 glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
4249
4250 if (stereoMode() != Quarter::SoQTQuarterAdaptor::MONO) {
4251 glColor3fv(SbVec3f(1.0F, 1.0F, 1.0F).getValue());
4252 }
4253 else {
4254 glColor3fv(SbVec3f(0.0F, 0.0F, 0.0F).getValue());
4255 }
4256
4257 glEnable(GL_BLEND);
4258 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
4259 glPixelZoom((float)axiscrossSize / 30, (float)axiscrossSize / 30); // 30 = 3 (character pixmap
4260 // ratio) * 10 (default
4261 // axiscrossSize)
4262 glRasterPos2d(xpos[0], xpos[1]);
4263 glDrawPixels(XPM_WIDTH, XPM_HEIGHT, GL_RGBA, GL_UNSIGNED_BYTE, XPM_pixel_data);
4264 glRasterPos2d(ypos[0], ypos[1]);
4265 glDrawPixels(YPM_WIDTH, YPM_HEIGHT, GL_RGBA, GL_UNSIGNED_BYTE, YPM_pixel_data);
4266 glRasterPos2d(zpos[0], zpos[1]);
4267 glDrawPixels(ZPM_WIDTH, ZPM_HEIGHT, GL_RGBA, GL_UNSIGNED_BYTE, ZPM_pixel_data);
4268
4269 glPixelStorei(GL_UNPACK_ALIGNMENT, unpack);
4270 glPopMatrix();
4271
4272 // Reset original state.
4273
4274 // FIXME: are these 3 lines really necessary, as we push
4275 // GL_ALL_ATTRIB_BITS at the start? 20000604 mortene.
4276 glDepthRange(depthrange[0], depthrange[1]);
4277 glMatrixMode(GL_PROJECTION);
4278 glLoadMatrixd(projectionmatrix);
4279
4280 glPopAttrib();
4281 // NOLINTEND
4282 }
4283
4284 // Draw an arrow for the axis representation directly through OpenGL.
4285 void View3DInventorViewer::drawArrow()
4286 {
4287 // NOLINTBEGIN
4288 glDisable(GL_CULL_FACE);
4289 glBegin(GL_QUADS);
4290 glVertex3f(0.0F, -0.02F, 0.02F);
4291 glVertex3f(0.0F, 0.02F, 0.02F);
4292 glVertex3f(1.0F - 1.0F / 3.0F, 0.02F, 0.02F);
4293 glVertex3f(1.0F - 1.0F / 3.0F, -0.02F, 0.02F);
4294
4295 glVertex3f(0.0F, -0.02F, -0.02F);
4296 glVertex3f(0.0F, 0.02F, -0.02F);
4297 glVertex3f(1.0F - 1.0F / 3.0F, 0.02F, -0.02F);
4298 glVertex3f(1.0F - 1.0F / 3.0F, -0.02F, -0.02F);
4299
4300 glVertex3f(0.0F, -0.02F, 0.02F);
4301 glVertex3f(0.0F, -0.02F, -0.02F);
4302 glVertex3f(1.0F - 1.0F / 3.0F, -0.02F, -0.02F);
4303 glVertex3f(1.0F - 1.0F / 3.0F, -0.02F, 0.02F);
4304
4305 glVertex3f(0.0F, 0.02F, 0.02F);
4306 glVertex3f(0.0F, 0.02F, -0.02F);
4307 glVertex3f(1.0F - 1.0F / 3.0F, 0.02F, -0.02F);
4308 glVertex3f(1.0F - 1.0F / 3.0F, 0.02F, 0.02F);
4309
4310 glVertex3f(0.0F, 0.02F, 0.02F);
4311 glVertex3f(0.0F, 0.02F, -0.02F);
4312 glVertex3f(0.0F, -0.02F, -0.02F);
4313 glVertex3f(0.0F, -0.02F, 0.02F);
4314 glEnd();
4315 glBegin(GL_TRIANGLES);
4316 glVertex3f(1.0F, 0.0F, 0.0F);
4317 glVertex3f(1.0F - 1.0F / 3.0F, +0.5F / 4.0F, 0.0F);
4318 glVertex3f(1.0F - 1.0F / 3.0F, -0.5F / 4.0F, 0.0F);
4319 glVertex3f(1.0F, 0.0F, 0.0F);
4320 glVertex3f(1.0F - 1.0F / 3.0F, 0.0F, +0.5F / 4.0F);
4321 glVertex3f(1.0F - 1.0F / 3.0F, 0.0F, -0.5F / 4.0F);
4322 glEnd();
4323 glBegin(GL_QUADS);
4324 glVertex3f(1.0F - 1.0F / 3.0F, +0.5F / 4.0F, 0.0F);
4325 glVertex3f(1.0F - 1.0F / 3.0F, 0.0F, +0.5F / 4.0F);
4326 glVertex3f(1.0F - 1.0F / 3.0F, -0.5F / 4.0F, 0.0F);
4327 glVertex3f(1.0F - 1.0F / 3.0F, 0.0F, -0.5F / 4.0F);
4328 glEnd();
4329 // NOLINTEND
4330 }
4331
4332 void View3DInventorViewer::drawSingleBackground(const QColor& col)
4333 {
4334 // Note: After changing the NaviCube code the content of an image plane may appear black.
4335 // A workaround is this function.
4336 // See also: https://github.com/FreeCAD/FreeCAD/pull/9356#issuecomment-1529521654
4337 glMatrixMode(GL_PROJECTION);
4338 glPushMatrix();
4339 glLoadIdentity();
4340 glOrtho(-1, 1, -1, 1, -1, 1);
4341 glMatrixMode(GL_MODELVIEW);
4342 glPushMatrix();
4343 glLoadIdentity();
4344 glPushAttrib(GL_ENABLE_BIT);
4345 glDisable(GL_DEPTH_TEST);
4346 glDisable(GL_LIGHTING);
4347 glDisable(GL_TEXTURE_2D);
4348 glBegin(GL_TRIANGLE_STRIP);
4349 glColor3f(float(col.redF()), float(col.greenF()), float(col.blueF()));
4350 glVertex2f(-1, 1);
4351 glColor3f(float(col.redF()), float(col.greenF()), float(col.blueF()));
4352 glVertex2f(-1, -1);
4353 glColor3f(float(col.redF()), float(col.greenF()), float(col.blueF()));
4354 glVertex2f(1, 1);
4355 glColor3f(float(col.redF()), float(col.greenF()), float(col.blueF()));
4356 glVertex2f(1, -1);
4357 glEnd();
4358 glPopAttrib();
4359 glPopMatrix();
4360 glMatrixMode(GL_PROJECTION);
4361 glPopMatrix();
4362 glMatrixMode(GL_MODELVIEW);
4363 }
4364
4365 // ************************************************************************
4366
4367 // Set cursor graphics according to mode.
4368 void View3DInventorViewer::setCursorRepresentation(int modearg)
4369 {
4370 // There is a synchronization problem between Qt and SoQt which
4371 // happens when popping up a context-menu. In this case the
4372 // Qt::WA_UnderMouse attribute is reset and never set again
4373 // even if the mouse is still in the canvas. Thus, the cursor
4374 // won't be changed as long as the user doesn't leave and enter
4375 // the canvas. To fix this we explicitly set Qt::WA_UnderMouse
4376 // if the mouse is inside the canvas.
4377 QWidget* glWindow = this->getGLWidget();
4378
4379 // When a widget is added to the QGraphicsScene and the user
4380 // hovered over it the 'WA_SetCursor' attribute is set to the
4381 // GL widget but never reset and thus would cause that the
4382 // cursor on this widget won't be set.
4383 if (glWindow) {
4384 glWindow->setAttribute(Qt::WA_SetCursor, false);
4385 }
4386
4387 if (glWindow && glWindow->rect().contains(QCursor::pos())) {
4388 glWindow->setAttribute(Qt::WA_UnderMouse);
4389 }
4390
4391 switch (modearg) {
4392 case NavigationStyle::IDLE:
4393 case NavigationStyle::INTERACT:
4394 if (isEditing()) {
4395 this->getWidget()->setCursor(this->editCursor);
4396 }
4397 else {
4398 this->getWidget()->setCursor(QCursor(Qt::ArrowCursor));
4399 }
4400 break;
4401
4402 case NavigationStyle::DRAGGING:
4403 case NavigationStyle::SPINNING:
4404 this->getWidget()->setCursor(spinCursor);
4405 break;
4406
4407 case NavigationStyle::ZOOMING:
4408 this->getWidget()->setCursor(zoomCursor);
4409 break;
4410
4411 case NavigationStyle::SEEK_MODE:
4412 case NavigationStyle::SEEK_WAIT_MODE:
4413 case NavigationStyle::BOXZOOM:
4414 this->getWidget()->setCursor(Qt::CrossCursor);
4415 break;
4416
4417 case NavigationStyle::PANNING:
4418 this->getWidget()->setCursor(panCursor);
4419 break;
4420
4421 case NavigationStyle::SELECTION:
4422 this->getWidget()->setCursor(Qt::PointingHandCursor);
4423 break;
4424
4425 default:
4426 assert(0);
4427 break;
4428 }
4429 }
4430
4431 void View3DInventorViewer::setEditing(bool edit)
4432 {
4433 this->editing = edit;
4434 this->getWidget()->setCursor(QCursor(Qt::ArrowCursor));
4435 this->editCursor = QCursor();
4436 }
4437
4438 void View3DInventorViewer::setComponentCursor(const QCursor& cursor)
4439 {
4440 this->getWidget()->setCursor(cursor);
4441 }
4442
4443 void View3DInventorViewer::setEditingCursor(const QCursor& cursor)
4444 {
4445 this->getWidget()->setCursor(cursor);
4446 this->editCursor = this->getWidget()->cursor();
4447 }
4448
4449 void View3DInventorViewer::selectCB(void* viewer, SoPath* path)
4450 {
4451 ViewProvider* vp = static_cast<View3DInventorViewer*>(viewer)->getViewProviderByPath(path);
4452 if (vp && vp->useNewSelectionModel()) {
4453 // do nothing here
4454 }
4455 }
4456
4457 void View3DInventorViewer::deselectCB(void* viewer, SoPath* path)
4458 {
4459 ViewProvider* vp = static_cast<View3DInventorViewer*>(viewer)->getViewProviderByPath(path);
4460 if (vp && vp->useNewSelectionModel()) {
4461 // do nothing here
4462 }
4463 }
4464
4465 SoPath* View3DInventorViewer::pickFilterCB(void* viewer, const SoPickedPoint* pp)
4466 {
4467 ViewProvider* vp = static_cast<View3DInventorViewer*>(viewer)->getViewProviderByPath(pp->getPath());
4468 if (vp && vp->useNewSelectionModel()) {
4469 std::string str = vp->getElement(pp->getDetail());
4470 vp->getSelectionShape(str.c_str());
4471 static char buf[513];
4472 snprintf(
4473 buf,
4474 sizeof(buf),
4475 "Hovered: %s (%f,%f,%f)",
4476 str.c_str(),
4477 pp->getPoint()[0],
4478 pp->getPoint()[1],
4479 pp->getPoint()[2]
4480 );
4481
4482 getMainWindow()->showMessage(QString::fromLatin1(buf), 3000);
4483 }
4484
4485 return pp->getPath();
4486 }
4487
4488 void View3DInventorViewer::addEventCallback(SoType eventtype, SoEventCallbackCB* cb, void* userdata)
4489 {
4490 pEventCallback->addEventCallback(eventtype, cb, userdata);
4491 }
4492
4493 void View3DInventorViewer::removeEventCallback(SoType eventtype, SoEventCallbackCB* cb, void* userdata)
4494 {
4495 pEventCallback->removeEventCallback(eventtype, cb, userdata);
4496 }
4497
4498 ViewProvider* View3DInventorViewer::getViewProviderByPath(SoPath* path) const
4499 {
4500 if (!guiDocument) {
4501 Base::Console().warning("View3DInventorViewer::getViewProviderByPath: No document set\n");
4502 return nullptr;
4503 }
4504 return guiDocument->getViewProviderByPathFromHead(path);
4505 }
4506
4507 ViewProvider* View3DInventorViewer::getViewProviderByPathFromTail(SoPath* path) const
4508 {
4509 if (!guiDocument) {
4510 Base::Console().warning(
4511 "View3DInventorViewer::getViewProviderByPathFromTail: No document set\n"
4512 );
4513 return nullptr;
4514 }
4515 return guiDocument->getViewProviderByPathFromTail(path);
4516 }
4517
4518 std::vector<ViewProvider*> View3DInventorViewer::getViewProvidersOfType(const Base::Type& typeId) const
4519 {
4520 if (!guiDocument) {
4521 Base::Console().warning("View3DInventorViewer::getViewProvidersOfType: No document set\n");
4522 return {};
4523 }
4524 return guiDocument->getViewProvidersOfType(typeId);
4525 }
4526
4527 void View3DInventorViewer::turnAllDimensionsOn()
4528 {
4529 dimensionRoot->whichChild = SO_SWITCH_ALL;
4530 }
4531
4532 void View3DInventorViewer::turnAllDimensionsOff()
4533 {
4534 dimensionRoot->whichChild = SO_SWITCH_NONE;
4535 }
4536
4537 void View3DInventorViewer::eraseAllDimensions()
4538 {
4539 coinRemoveAllChildren(static_cast<SoSwitch*>(dimensionRoot->getChild(0))); // NOLINT
4540 coinRemoveAllChildren(static_cast<SoSwitch*>(dimensionRoot->getChild(1))); // NOLINT
4541 }
4542
4543 void View3DInventorViewer::turn3dDimensionsOn()
4544 {
4545 static_cast<SoSwitch*>(dimensionRoot->getChild(0))->whichChild = SO_SWITCH_ALL; // NOLINT
4546 }
4547
4548 void View3DInventorViewer::turn3dDimensionsOff()
4549 {
4550 static_cast<SoSwitch*>(dimensionRoot->getChild(0))->whichChild = SO_SWITCH_NONE; // NOLINT
4551 }
4552
4553 void View3DInventorViewer::addDimension3d(SoNode* node)
4554 {
4555 static_cast<SoSwitch*>(dimensionRoot->getChild(0))->addChild(node); // NOLINT
4556 }
4557
4558 void View3DInventorViewer::addDimensionDelta(SoNode* node)
4559 {
4560 static_cast<SoSwitch*>(dimensionRoot->getChild(1))->addChild(node); // NOLINT
4561 }
4562
4563 void View3DInventorViewer::turnDeltaDimensionsOn()
4564 {
4565 static_cast<SoSwitch*>(dimensionRoot->getChild(1))->whichChild = SO_SWITCH_ALL; // NOLINT
4566 }
4567
4568 void View3DInventorViewer::turnDeltaDimensionsOff()
4569 {
4570 static_cast<SoSwitch*>(dimensionRoot->getChild(1))->whichChild = SO_SWITCH_NONE; // NOLINT
4571 }
4572
4573 PyObject* View3DInventorViewer::getPyObject()
4574 {
4575 if (!_viewerPy) {
4576 _viewerPy = new View3DInventorViewerPy(this);
4577 }
4578
4579 Py_INCREF(_viewerPy);
4580 return _viewerPy;
4581 }
4582
4583 /**
4584 * Drops the event \a e and loads the files into the given document.
4585 */
4586 void View3DInventorViewer::dropEvent(QDropEvent* ev)
4587 {
4588 const QMimeData* data = ev->mimeData();
4589 if (data->hasUrls() && selectionRoot && selectionRoot->pcDocument) {
4590 getMainWindow()->loadUrls(selectionRoot->pcDocument->getDocument(), data->urls());
4591 }
4592 else {
4593 inherited::dropEvent(ev);
4594 }
4595 }
4596
4597 void View3DInventorViewer::dragEnterEvent(QDragEnterEvent* ev)
4598 {
4599 // Here we must allow uri drags and check them in dropEvent
4600 const QMimeData* data = ev->mimeData();
4601 if (data->hasUrls()) {
4602 ev->accept();
4603 }
4604 else {
4605 inherited::dragEnterEvent(ev);
4606 }
4607 }
4608
4609 void View3DInventorViewer::dragMoveEvent(QDragMoveEvent* ev)
4610 {
4611 const QMimeData* data = ev->mimeData();
4612 if (data->hasUrls() && selectionRoot && selectionRoot->pcDocument) {
4613 ev->accept();
4614 }
4615 else {
4616 inherited::dragMoveEvent(ev);
4617 }
4618 }
4619
4620 void View3DInventorViewer::dragLeaveEvent(QDragLeaveEvent* ev)
4621 {
4622 inherited::dragLeaveEvent(ev);
4623 }
4624
4625 #include "moc_View3DInventorViewer.cpp" // NOLINT