forked from FreeCAD/FreeCAD
/
View3DInventorViewer.cpp
3552 lines (3003 loc) · 109 KB
/
View3DInventorViewer.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/***************************************************************************
* Copyright (c) 2004 Jürgen Riegel <juergen.riegel@web.de> *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
# include <cfloat>
# ifdef FC_OS_WIN32
# include <windows.h>
# endif
# ifdef FC_OS_MACOSX
# include <OpenGL/gl.h>
# else
# include <GL/gl.h>
# include <GL/glext.h>
# include <GL/glu.h>
# endif
# include <Inventor/SbBox.h>
# include <Inventor/SoEventManager.h>
# include <Inventor/SoPickedPoint.h>
# include <Inventor/actions/SoGetBoundingBoxAction.h>
# include <Inventor/actions/SoGetMatrixAction.h>
# include <Inventor/actions/SoHandleEventAction.h>
# include <Inventor/actions/SoRayPickAction.h>
# include <Inventor/annex/HardCopy/SoVectorizePSAction.h>
# include <Inventor/details/SoDetail.h>
# include <Inventor/elements/SoLightModelElement.h>
# include <Inventor/elements/SoOverrideElement.h>
# include <Inventor/elements/SoViewportRegionElement.h>
# include <Inventor/errors/SoDebugError.h>
# include <Inventor/events/SoEvent.h>
# include <Inventor/events/SoKeyboardEvent.h>
# include <Inventor/events/SoMotion3Event.h>
# include <Inventor/manips/SoClipPlaneManip.h>
# include <Inventor/nodes/SoBaseColor.h>
# include <Inventor/nodes/SoCallback.h>
# include <Inventor/nodes/SoCube.h>
# include <Inventor/nodes/SoDirectionalLight.h>
# include <Inventor/nodes/SoEventCallback.h>
# include <Inventor/nodes/SoLightModel.h>
# include <Inventor/nodes/SoMaterial.h>
# include <Inventor/nodes/SoOrthographicCamera.h>
# include <Inventor/nodes/SoPerspectiveCamera.h>
# include <Inventor/nodes/SoPickStyle.h>
# include <Inventor/nodes/SoSelection.h>
# include <Inventor/nodes/SoSeparator.h>
# include <Inventor/nodes/SoSwitch.h>
# include <Inventor/nodes/SoTransform.h>
# include <Inventor/nodes/SoTranslation.h>
# include <QBitmap>
# include <QEventLoop>
# include <QKeyEvent>
# include <QMessageBox>
# include <QMimeData>
# include <QTimer>
# include <QVariantAnimation>
# include <QWheelEvent>
#endif
#include <App/Document.h>
#include <App/GeoFeatureGroupExtension.h>
#include <Base/Console.h>
#include <Base/FileInfo.h>
#include <Base/Sequencer.h>
#include <Base/Tools.h>
#include <Base/UnitsApi.h>
#include <Quarter/devices/InputDevice.h>
#include <Quarter/eventhandlers/EventFilter.h>
#include "View3DInventorViewer.h"
#include "Application.h"
#include "CornerCrossLetters.h"
#include "Document.h"
#include "GLPainter.h"
#include "MainWindow.h"
#include "NaviCube.h"
#include "NavigationStyle.h"
#include "Selection.h"
#include "SoAxisCrossKit.h"
#include "SoFCBackgroundGradient.h"
#include "SoFCBoundingBox.h"
#include "SoFCDB.h"
#include "SoFCInteractiveElement.h"
#include "SoFCOffscreenRenderer.h"
#include "SoFCSelection.h"
#include "View3DInventorOpenVRViewer.h"
#include "View3DInventorXRViewer.h"
#include "SoFCSelectionAction.h"
#include "SoFCUnifiedSelection.h"
#include "SoFCVectorizeSVGAction.h"
#include "SoFCVectorizeU3DAction.h"
#include "SoTouchEvents.h"
#include "SpaceballEvent.h"
#include "View3DInventorRiftViewer.h"
#include "View3DViewerPy.h"
#include "ViewParams.h"
#include "ViewProvider.h"
#include "ViewProviderDocumentObject.h"
#include "ViewProviderLink.h"
FC_LOG_LEVEL_INIT("3DViewer",true,true)
//#define FC_LOGGING_CB
using namespace Gui;
/*** zoom-style cursor ******/
#define ZOOM_WIDTH 16
#define ZOOM_HEIGHT 16
#define ZOOM_BYTES ((ZOOM_WIDTH + 7) / 8) * ZOOM_HEIGHT
#define ZOOM_HOT_X 5
#define ZOOM_HOT_Y 7
static unsigned char zoom_bitmap[ZOOM_BYTES] =
{
0x00, 0x0f, 0x80, 0x1c, 0x40, 0x38, 0x20, 0x70,
0x90, 0xe4, 0xc0, 0xcc, 0xf0, 0xfc, 0x00, 0x0c,
0x00, 0x0c, 0xf0, 0xfc, 0xc0, 0xcc, 0x90, 0xe4,
0x20, 0x70, 0x40, 0x38, 0x80, 0x1c, 0x00, 0x0f
};
static unsigned char zoom_mask_bitmap[ZOOM_BYTES] =
{
0x00,0x0f,0x80,0x1f,0xc0,0x3f,0xe0,0x7f,0xf0,0xff,0xf0,0xff,0xf0,0xff,0x00,
0x0f,0x00,0x0f,0xf0,0xff,0xf0,0xff,0xf0,0xff,0xe0,0x7f,0xc0,0x3f,0x80,0x1f,
0x00,0x0f
};
/*** pan-style cursor *******/
#define PAN_WIDTH 16
#define PAN_HEIGHT 16
#define PAN_BYTES ((PAN_WIDTH + 7) / 8) * PAN_HEIGHT
#define PAN_HOT_X 7
#define PAN_HOT_Y 7
static unsigned char pan_bitmap[PAN_BYTES] =
{
0xc0, 0x03, 0x60, 0x02, 0x20, 0x04, 0x10, 0x08,
0x68, 0x16, 0x54, 0x2a, 0x73, 0xce, 0x01, 0x80,
0x01, 0x80, 0x73, 0xce, 0x54, 0x2a, 0x68, 0x16,
0x10, 0x08, 0x20, 0x04, 0x40, 0x02, 0xc0, 0x03
};
static unsigned char pan_mask_bitmap[PAN_BYTES] =
{
0xc0,0x03,0xe0,0x03,0xe0,0x07,0xf0,0x0f,0xe8,0x17,0xdc,0x3b,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xdc,0x3b,0xe8,0x17,0xf0,0x0f,0xe0,0x07,0xc0,0x03,
0xc0,0x03
};
/*** rotate-style cursor ****/
#define ROTATE_WIDTH 16
#define ROTATE_HEIGHT 16
#define ROTATE_BYTES ((ROTATE_WIDTH + 7) / 8) * ROTATE_HEIGHT
#define ROTATE_HOT_X 6
#define ROTATE_HOT_Y 8
static unsigned char rotate_bitmap[ROTATE_BYTES] = {
0xf0, 0xef, 0x18, 0xb8, 0x0c, 0x90, 0xe4, 0x83,
0x34, 0x86, 0x1c, 0x83, 0x00, 0x81, 0x00, 0xff,
0xff, 0x00, 0x81, 0x00, 0xc1, 0x38, 0x61, 0x2c,
0xc1, 0x27, 0x09, 0x30, 0x1d, 0x18, 0xf7, 0x0f
};
static unsigned char rotate_mask_bitmap[ROTATE_BYTES] = {
0xf0,0xef,0xf8,0xff,0xfc,0xff,0xfc,0xff,0x3c,0xfe,0x1c,0xff,0x00,0xff,0x00,
0xff,0xff,0x00,0xff,0x00,0xff,0x38,0x7f,0x3c,0xff,0x3f,0xff,0x3f,0xff,0x1f,
0xf7,0x0f
};
/*!
As ProgressBar has no chance to control the incoming Qt events of Quarter so we need to stop
the event handling to prevent the scenegraph from being selected or deselected
while the progress bar is running.
*/
class Gui::ViewerEventFilter : public QObject
{
public:
ViewerEventFilter() {}
~ViewerEventFilter() override {}
bool eventFilter(QObject* obj, QEvent* event) override {
// Bug #0000607: Some mice also support horizontal scrolling which however might
// lead to some unwanted zooming when pressing the MMB for panning.
// Thus, we filter out horizontal scrolling.
if (event->type() == QEvent::Wheel) {
auto we = static_cast<QWheelEvent*>(event);
if (qAbs(we->angleDelta().x()) > qAbs(we->angleDelta().y()))
return true;
}
else if (event->type() == QEvent::KeyPress) {
auto ke = static_cast<QKeyEvent*>(event);
if (ke->matches(QKeySequence::SelectAll)) {
static_cast<View3DInventorViewer*>(obj)->selectAll();
return true;
}
}
if (Base::Sequencer().isRunning() && Base::Sequencer().isBlocking())
return false;
if (event->type() == Spaceball::ButtonEvent::ButtonEventType) {
auto buttonEvent = static_cast<Spaceball::ButtonEvent*>(event);
if (!buttonEvent) {
Base::Console().Log("invalid spaceball button event\n");
return true;
}
}
else if (event->type() == Spaceball::MotionEvent::MotionEventType) {
auto motionEvent = static_cast<Spaceball::MotionEvent*>(event);
if (!motionEvent) {
Base::Console().Log("invalid spaceball motion event\n");
return true;
}
}
return false;
}
};
class SpaceNavigatorDevice : public Quarter::InputDevice {
public:
SpaceNavigatorDevice() {}
~SpaceNavigatorDevice() override {}
const SoEvent* translateEvent(QEvent* event) override {
if (event->type() == Spaceball::MotionEvent::MotionEventType) {
auto motionEvent = static_cast<Spaceball::MotionEvent*>(event);
if (!motionEvent) {
Base::Console().Log("invalid spaceball motion event\n");
return nullptr;
}
motionEvent->setHandled(true);
float xTrans, yTrans, zTrans;
xTrans = static_cast<float>(motionEvent->translationX());
yTrans = static_cast<float>(motionEvent->translationY());
zTrans = static_cast<float>(motionEvent->translationZ());
SbVec3f translationVector(xTrans, yTrans, zTrans);
static float rotationConstant(.0001f);
SbRotation xRot, yRot, zRot;
xRot.setValue(SbVec3f(1.0, 0.0, 0.0), static_cast<float>(motionEvent->rotationX()) * rotationConstant);
yRot.setValue(SbVec3f(0.0, 1.0, 0.0), static_cast<float>(motionEvent->rotationY()) * rotationConstant);
zRot.setValue(SbVec3f(0.0, 0.0, 1.0), static_cast<float>(motionEvent->rotationZ()) * rotationConstant);
auto motion3Event = new SoMotion3Event;
motion3Event->setTranslation(translationVector);
motion3Event->setRotation(xRot * yRot * zRot);
motion3Event->setPosition(this->mousepos);
return motion3Event;
}
return nullptr;
}
};
/** \defgroup View3D 3D Viewer
* \ingroup GUI
*
* The 3D Viewer is one of the major components in a CAD/CAE systems.
* Therefore an overview and some remarks to the FreeCAD 3D viewing system.
*
* \section overview Overview
* \todo Overview and complements for the 3D Viewer
*/
// *************************************************************************
View3DInventorViewer::View3DInventorViewer(QWidget* parent, const QtGLWidget* sharewidget)
: Quarter::SoQTQuarterAdaptor(parent, sharewidget)
, SelectionObserver(false, ResolveMode::NoResolve)
, editViewProvider(nullptr)
, navigation(nullptr)
, renderType(Native)
, framebuffer(nullptr)
, axisCross(nullptr)
, axisGroup(nullptr)
, editing(false)
, redirected(false)
, allowredir(false)
, overrideMode("As Is")
, _viewerPy(nullptr)
{
init();
}
View3DInventorViewer::View3DInventorViewer(const QtGLFormat& format, QWidget* parent, const QtGLWidget* sharewidget)
: Quarter::SoQTQuarterAdaptor(format, parent, sharewidget)
, SelectionObserver(false, ResolveMode::NoResolve)
, editViewProvider(nullptr)
, navigation(nullptr)
, renderType(Native)
, framebuffer(nullptr)
, axisCross(nullptr)
, axisGroup(nullptr)
, editing(false)
, redirected(false)
, allowredir(false)
, overrideMode("As Is")
, _viewerPy(nullptr)
{
init();
}
void View3DInventorViewer::init()
{
static bool _cacheModeInited;
if(!_cacheModeInited) {
_cacheModeInited = true;
pcViewProviderRoot = nullptr;
setRenderCache(-1);
}
shading = true;
fpsEnabled = false;
vboEnabled = false;
attachSelection();
// Coin should not clear the pixel-buffer, so the background image
// is not removed.
this->setClearWindow(false);
// setting up the defaults for the spin rotation
initialize();
auto cam = new SoOrthographicCamera;
cam->position = SbVec3f(0, 0, 1);
cam->height = 1;
cam->nearDistance = 0.5;
cam->farDistance = 1.5;
// setup light sources
SoDirectionalLight* hl = this->getHeadlight();
backlight = new SoDirectionalLight();
backlight->ref();
backlight->setName("backlight");
backlight->direction.setValue(-hl->direction.getValue());
backlight->on.setValue(false); // by default off
// Set up background scenegraph with image in it.
backgroundroot = new SoSeparator;
backgroundroot->ref();
this->backgroundroot->addChild(cam);
// Background stuff
pcBackGround = new SoFCBackgroundGradient;
pcBackGround->ref();
// Set up foreground, overlaid scenegraph.
this->foregroundroot = new SoSeparator;
this->foregroundroot->ref();
auto lm = new SoLightModel;
lm->model = SoLightModel::BASE_COLOR;
auto bc = new SoBaseColor;
bc->rgb = SbColor(1, 1, 0);
cam = new SoOrthographicCamera;
cam->position = SbVec3f(0, 0, 5);
cam->height = 10;
cam->nearDistance = 0;
cam->farDistance = 10;
this->foregroundroot->addChild(cam);
this->foregroundroot->addChild(lm);
this->foregroundroot->addChild(bc);
// NOTE: For every mouse click event the SoFCUnifiedSelection searches for the picked
// point which causes a certain slow-down because for all objects the primitives
// must be created. Using an SoSeparator avoids this drawback.
selectionRoot = new Gui::SoFCUnifiedSelection();
selectionRoot->applySettings();
// set the ViewProvider root node
pcViewProviderRoot = selectionRoot;
// increase refcount before passing it to setScenegraph(), to avoid
// premature destruction
pcViewProviderRoot->ref();
// is not really working with Coin3D.
//redrawOverlayOnSelectionChange(pcSelection);
setSceneGraph(pcViewProviderRoot);
// Event callback node
pEventCallback = new SoEventCallback();
pEventCallback->setUserData(this);
pEventCallback->ref();
pcViewProviderRoot->addChild(pEventCallback);
pEventCallback->addEventCallback(SoEvent::getClassTypeId(), handleEventCB, this);
dimensionRoot = new SoSwitch(SO_SWITCH_NONE);
pcViewProviderRoot->addChild(dimensionRoot);
dimensionRoot->addChild(new SoSwitch()); //first one will be for the 3d dimensions.
dimensionRoot->addChild(new SoSwitch()); //second one for the delta dimensions.
// This is a callback node that logs all action that traverse the Inventor tree.
#if defined (FC_DEBUG) && defined(FC_LOGGING_CB)
SoCallback* cb = new SoCallback;
cb->setCallback(interactionLoggerCB, this);
pcViewProviderRoot->addChild(cb);
#endif
inventorSelection = std::make_unique<View3DInventorSelection>(selectionRoot);
pcClipPlane = nullptr;
pcEditingRoot = new SoSeparator;
pcEditingRoot->ref();
pcEditingRoot->setName("EditingRoot");
pcEditingTransform = new SoTransform;
pcEditingTransform->ref();
pcEditingTransform->setName("EditingTransform");
restoreEditingRoot = false;
pcEditingRoot->addChild(pcEditingTransform);
pcViewProviderRoot->addChild(pcEditingRoot);
// Set our own render action which show a bounding box if
// the SoFCSelection::BOX style is set
//
// Important note:
// When creating a new GL render action we have to copy over the cache context id
// because otherwise we may get strange rendering behaviour. For more details see
// http://forum.freecadweb.org/viewtopic.php?f=10&t=7486&start=120#p74398 and for
// the fix and some details what happens behind the scene have a look at this
// http://forum.freecadweb.org/viewtopic.php?f=10&t=7486&p=74777#p74736
uint32_t id = this->getSoRenderManager()->getGLRenderAction()->getCacheContext();
this->getSoRenderManager()->setGLRenderAction(new SoBoxSelectionRenderAction);
this->getSoRenderManager()->getGLRenderAction()->setCacheContext(id);
// set the transparency and antialiasing settings
getSoRenderManager()->getGLRenderAction()->setTransparencyType(SoGLRenderAction::SORTED_OBJECT_SORTED_TRIANGLE_BLEND);
// Settings
setSeekTime(0.4f);
if (!isSeekValuePercentage())
setSeekValueAsPercentage(true);
setSeekDistance(100);
setViewing(false);
setBackgroundColor(QColor(25, 25, 25));
setGradientBackground(true);
// set some callback functions for user interaction
addStartCallback(interactionStartCB);
addFinishCallback(interactionFinishCB);
//filter a few qt events
viewerEventFilter = new ViewerEventFilter;
installEventFilter(viewerEventFilter);
getEventFilter()->registerInputDevice(new SpaceNavigatorDevice);
getEventFilter()->registerInputDevice(new GesturesDevice(this));
try{
this->grabGesture(Qt::PanGesture);
this->grabGesture(Qt::PinchGesture);
} catch (Base::Exception &e) {
Base::Console().Warning("Failed to set up gestures. Error: %s\n", e.what());
} catch (...) {
Base::Console().Warning("Failed to set up gestures. Unknown error.\n");
}
//create the cursors
createStandardCursors(devicePixelRatio());
connect(this, &View3DInventorViewer::devicePixelRatioChanged,
this, &View3DInventorViewer::createStandardCursors);
naviCube = new NaviCube(this);
naviCubeEnabled = true;
}
View3DInventorViewer::~View3DInventorViewer()
{
// to prevent following OpenGL error message: "Texture is not valid in the current context. Texture has not been destroyed"
aboutToDestroyGLContext();
// It can happen that a document has several MDI views and when the about to be
// closed 3D view is in edit mode the corresponding view provider must be restored
// because otherwise it might be left in a broken state
// See https://forum.freecadweb.org/viewtopic.php?f=3&t=39720
if (restoreEditingRoot) {
resetEditingRoot(false);
}
// cleanup
this->backgroundroot->unref();
this->backgroundroot = nullptr;
this->foregroundroot->unref();
this->foregroundroot = nullptr;
this->pcBackGround->unref();
this->pcBackGround = nullptr;
setSceneGraph(nullptr);
this->pEventCallback->unref();
this->pEventCallback = nullptr;
// Note: It can happen that there is still someone who references
// the root node but isn't destroyed when closing this viewer so
// that it prevents all children from being deleted. To reduce this
// likelihood we explicitly remove all child nodes now.
coinRemoveAllChildren(this->pcViewProviderRoot);
this->pcViewProviderRoot->unref();
this->pcViewProviderRoot = nullptr;
this->backlight->unref();
this->backlight = nullptr;
inventorSelection.reset(nullptr);
this->pcEditingRoot->unref();
this->pcEditingTransform->unref();
if (this->pcClipPlane)
this->pcClipPlane->unref();
delete this->navigation;
// Note: When closing the application the main window doesn't exist any more.
if (getMainWindow())
getMainWindow()->setPaneText(2, QLatin1String(""));
detachSelection();
removeEventFilter(viewerEventFilter);
delete viewerEventFilter;
if (_viewerPy) {
static_cast<View3DInventorViewerPy*>(_viewerPy)->_viewer = nullptr;
Py_DECREF(_viewerPy);
}
// In the init() function we have overridden the default SoGLRenderAction with our
// own instance of SoBoxSelectionRenderAction and SoRenderManager destroyed the default.
// But it does this only once so that now we have to explicitly destroy our instance in
// order to free the memory.
SoGLRenderAction* glAction = this->getSoRenderManager()->getGLRenderAction();
this->getSoRenderManager()->setGLRenderAction(nullptr);
delete glAction;
}
void View3DInventorViewer::createStandardCursors(double dpr)
{
QBitmap cursor = QBitmap::fromData(QSize(ROTATE_WIDTH, ROTATE_HEIGHT), rotate_bitmap);
QBitmap mask = QBitmap::fromData(QSize(ROTATE_WIDTH, ROTATE_HEIGHT), rotate_mask_bitmap);
#if defined(Q_OS_WIN32)
cursor.setDevicePixelRatio(dpr);
mask.setDevicePixelRatio(dpr);
#else
Q_UNUSED(dpr)
#endif
spinCursor = QCursor(cursor, mask, ROTATE_HOT_X, ROTATE_HOT_Y);
cursor = QBitmap::fromData(QSize(ZOOM_WIDTH, ZOOM_HEIGHT), zoom_bitmap);
mask = QBitmap::fromData(QSize(ZOOM_WIDTH, ZOOM_HEIGHT), zoom_mask_bitmap);
#if defined(Q_OS_WIN32)
cursor.setDevicePixelRatio(dpr);
mask.setDevicePixelRatio(dpr);
#endif
zoomCursor = QCursor(cursor, mask, ZOOM_HOT_X, ZOOM_HOT_Y);
cursor = QBitmap::fromData(QSize(PAN_WIDTH, PAN_HEIGHT), pan_bitmap);
mask = QBitmap::fromData(QSize(PAN_WIDTH, PAN_HEIGHT), pan_mask_bitmap);
#if defined(Q_OS_WIN32)
cursor.setDevicePixelRatio(dpr);
mask.setDevicePixelRatio(dpr);
#endif
panCursor = QCursor(cursor, mask, PAN_HOT_X, PAN_HOT_Y);
}
void View3DInventorViewer::aboutToDestroyGLContext()
{
if (naviCube) {
auto gl = qobject_cast<QtGLWidget*>(this->viewport());
if (gl)
gl->makeCurrent();
delete naviCube;
naviCube = nullptr;
naviCubeEnabled = false;
}
}
void View3DInventorViewer::setDocument(Gui::Document* pcDocument)
{
// write the document the viewer belongs to the selection node
guiDocument = pcDocument;
selectionRoot->pcDocument = pcDocument;
inventorSelection->setDocument(pcDocument);
if(pcDocument) {
const auto &sels = Selection().getSelection(pcDocument->getDocument()->getName(), ResolveMode::NoResolve);
for(auto &sel : sels) {
SelectionChanges Chng(SelectionChanges::ShowSelection,
sel.DocName,sel.FeatName,sel.SubName);
onSelectionChanged(Chng);
}
}
}
Document* View3DInventorViewer::getDocument() {
return guiDocument;
}
void View3DInventorViewer::initialize()
{
navigation = new CADNavigationStyle();
navigation->setViewer(this);
this->axiscrossEnabled = true;
this->axiscrossSize = 10;
}
/// @cond DOXERR
void View3DInventorViewer::onSelectionChanged(const SelectionChanges &_Reason)
{
if(!getDocument())
return;
SelectionChanges Reason(_Reason);
if(Reason.pDocName && *Reason.pDocName &&
strcmp(getDocument()->getDocument()->getName(),Reason.pDocName)!=0)
return;
switch(Reason.Type) {
case SelectionChanges::ShowSelection:
case SelectionChanges::HideSelection:
if(Reason.Type == SelectionChanges::ShowSelection)
Reason.Type = SelectionChanges::AddSelection;
else
Reason.Type = SelectionChanges::RmvSelection;
// fall through
case SelectionChanges::SetPreselect:
if(Reason.SubType != SelectionChanges::MsgSource::TreeView)
break;
// fall through
case SelectionChanges::RmvPreselect:
case SelectionChanges::RmvPreselectSignal:
case SelectionChanges::SetSelection:
case SelectionChanges::AddSelection:
case SelectionChanges::RmvSelection:
case SelectionChanges::ClrSelection:
inventorSelection->checkGroupOnTop(Reason);
break;
case SelectionChanges::SetPreselectSignal:
break;
default:
return;
}
if(Reason.Type == SelectionChanges::RmvPreselect ||
Reason.Type == SelectionChanges::RmvPreselectSignal)
{
//Hint: do not create a tmp. instance of SelectionChanges
SelectionChanges selChanges(SelectionChanges::RmvPreselect);
SoFCHighlightAction cAct(selChanges);
cAct.apply(pcViewProviderRoot);
} else {
SoFCSelectionAction cAct(Reason);
cAct.apply(pcViewProviderRoot);
}
}
/// @endcond
SbBool View3DInventorViewer::searchNode(SoNode* node) const
{
SoSearchAction searchAction;
searchAction.setNode(node);
searchAction.setInterest(SoSearchAction::FIRST);
searchAction.apply(this->getSceneGraph());
SoPath* selectionPath = searchAction.getPath();
return selectionPath ? true : false;
}
SbBool View3DInventorViewer::hasViewProvider(ViewProvider* pcProvider) const
{
return _ViewProviderSet.find(pcProvider) != _ViewProviderSet.end();
}
SbBool View3DInventorViewer::containsViewProvider(const ViewProvider* vp) const
{
SoSearchAction sa;
sa.setNode(vp->getRoot());
sa.setSearchingAll(false);
sa.apply(getSoRenderManager()->getSceneGraph());
return sa.getPath() != nullptr;
}
/// adds an ViewProvider to the view, e.g. from a feature
void View3DInventorViewer::addViewProvider(ViewProvider* pcProvider)
{
SoSeparator* root = pcProvider->getRoot();
if (root) {
if(pcProvider->canAddToSceneGraph())
pcViewProviderRoot->addChild(root);
_ViewProviderMap[root] = pcProvider;
}
SoSeparator* fore = pcProvider->getFrontRoot();
if (fore)
foregroundroot->addChild(fore);
SoSeparator* back = pcProvider->getBackRoot();
if (back)
backgroundroot->addChild(back);
pcProvider->setOverrideMode(this->getOverrideMode());
_ViewProviderSet.insert(pcProvider);
}
void View3DInventorViewer::removeViewProvider(ViewProvider* pcProvider)
{
if (this->editViewProvider == pcProvider)
resetEditingViewProvider();
SoSeparator* root = pcProvider->getRoot();
if (root) {
int index = pcViewProviderRoot->findChild(root);
if(index>=0)
pcViewProviderRoot->removeChild(index);
_ViewProviderMap.erase(root);
}
SoSeparator* fore = pcProvider->getFrontRoot();
if (fore)
foregroundroot->removeChild(fore);
SoSeparator* back = pcProvider->getBackRoot();
if (back)
backgroundroot->removeChild(back);
_ViewProviderSet.erase(pcProvider);
}
void View3DInventorViewer::setEditingTransform(const Base::Matrix4D &mat) {
if(pcEditingTransform) {
double dMtrx[16];
mat.getGLMatrix(dMtrx);
pcEditingTransform->setMatrix(SbMatrix(
dMtrx[0], dMtrx[1], dMtrx[2], dMtrx[3],
dMtrx[4], dMtrx[5], dMtrx[6], dMtrx[7],
dMtrx[8], dMtrx[9], dMtrx[10], dMtrx[11],
dMtrx[12],dMtrx[13],dMtrx[14], dMtrx[15]));
}
}
void View3DInventorViewer::setupEditingRoot(SoNode *node, const Base::Matrix4D *mat) {
if(!editViewProvider)
return;
resetEditingRoot(false);
if(mat)
setEditingTransform(*mat);
else
setEditingTransform(getDocument()->getEditingTransform());
if(node) {
restoreEditingRoot = false;
pcEditingRoot->addChild(node);
return;
}
restoreEditingRoot = true;
auto root = editViewProvider->getRoot();
for(int i=0,count=root->getNumChildren();i<count;++i) {
SoNode *node = root->getChild(i);
if(node != editViewProvider->getTransformNode())
pcEditingRoot->addChild(node);
}
coinRemoveAllChildren(root);
ViewProviderLink::updateLinks(editViewProvider);
}
void View3DInventorViewer::resetEditingRoot(bool updateLinks)
{
if(!editViewProvider || pcEditingRoot->getNumChildren()<=1)
return;
if(!restoreEditingRoot) {
pcEditingRoot->getChildren()->truncate(1);
return;
}
restoreEditingRoot = false;
auto root = editViewProvider->getRoot();
if(root->getNumChildren())
FC_ERR("WARNING!!! Editing view provider root node is tampered");
root->addChild(editViewProvider->getTransformNode());
for(int i=1,count=pcEditingRoot->getNumChildren();i<count;++i)
root->addChild(pcEditingRoot->getChild(i));
pcEditingRoot->getChildren()->truncate(1);
// handle exceptions eventually raised by ViewProviderLink
try {
if (updateLinks)
ViewProviderLink::updateLinks(editViewProvider);
}
catch (const Py::Exception& e) {
/* coverity[UNCAUGHT_EXCEPT] Uncaught exception */
// Coverity created several reports when removeViewProvider()
// is used somewhere in a destructor which indirectly invokes
// resetEditingRoot().
// Now theoretically Py::type can throw an exception which nowhere
// will be handled and thus terminates the application. So, add an
// extra try/catch block here.
try {
Py::Object o = Py::type(e);
if (o.isString()) {
Py::String s(o);
Base::Console().Warning("%s\n", s.as_std_string("utf-8").c_str());
}
else {
Py::String s(o.repr());
Base::Console().Warning("%s\n", s.as_std_string("utf-8").c_str());
}
// Prints message to console window if we are in interactive mode
PyErr_Print();
}
catch (Py::Exception& e) {
e.clear();
Base::Console().Error("Unexpected exception raised in View3DInventorViewer::resetEditingRoot\n");
}
}
}
SoPickedPoint* View3DInventorViewer::getPointOnRay(const SbVec2s& pos, const ViewProvider* vp) const
{
SoPath *path;
if (vp == editViewProvider && pcEditingRoot->getNumChildren() > 1) {
path = new SoPath(1);
path->ref();
path->append(pcEditingRoot);
}
else {
//first get the path to this node and calculate the current transformation
SoSearchAction sa;
sa.setNode(vp->getRoot());
sa.setSearchingAll(true);
sa.apply(getSoRenderManager()->getSceneGraph());
path = sa.getPath();
if (!path)
return nullptr;
path->ref();
}
SoGetMatrixAction gm(getSoRenderManager()->getViewportRegion());
gm.apply(path);
auto trans = new SoTransform;
trans->setMatrix(gm.getMatrix());
trans->ref();
// build a temporary scenegraph only keeping this viewproviders nodes and the accumulated
// transformation
auto root = new SoSeparator;
root->ref();
root->addChild(getSoRenderManager()->getCamera());
root->addChild(trans);
root->addChild(path->getTail());
//get the picked point
SoRayPickAction rp(getSoRenderManager()->getViewportRegion());
rp.setPoint(pos);
rp.setRadius(getPickRadius());
rp.apply(root);
root->unref();
trans->unref();
path->unref();
SoPickedPoint* pick = rp.getPickedPoint();
return (pick ? new SoPickedPoint(*pick) : nullptr);
}
SoPickedPoint* View3DInventorViewer::getPointOnRay(const SbVec3f& pos, const SbVec3f& dir, const ViewProvider* vp) const
{
// Note: There seems to be a bug with setRay() which causes SoRayPickAction
// to fail to get intersections between the ray and a line
SoPath *path;
if (vp == editViewProvider && pcEditingRoot->getNumChildren() > 1) {
path = new SoPath(1);
path->ref();
path->append(pcEditingRoot);
}
else {
//first get the path to this node and calculate the current setTransformation
SoSearchAction sa;
sa.setNode(vp->getRoot());
sa.setSearchingAll(true);
sa.apply(getSoRenderManager()->getSceneGraph());
path = sa.getPath();
if (!path)
return nullptr;
path->ref();
}
SoGetMatrixAction gm(getSoRenderManager()->getViewportRegion());
gm.apply(path);
// build a temporary scenegraph only keeping this viewproviders nodes and the accumulated
// transformation
auto trans = new SoTransform;
trans->ref();
trans->setMatrix(gm.getMatrix());
auto root = new SoSeparator;
root->ref();
root->addChild(getSoRenderManager()->getCamera());
root->addChild(trans);
root->addChild(path->getTail());
//get the picked point
SoRayPickAction rp(getSoRenderManager()->getViewportRegion());
rp.setRay(pos,dir);
rp.setRadius(getPickRadius());
rp.apply(root);
root->unref();
trans->unref();
path->unref();
// returns a copy of the point
SoPickedPoint* pick = rp.getPickedPoint();
//return (pick ? pick->copy() : 0); // needs the same instance of CRT under MS Windows
return (pick ? new SoPickedPoint(*pick) : nullptr);
}
void View3DInventorViewer::setEditingViewProvider(Gui::ViewProvider* p, int ModNum)
{
this->editViewProvider = p;
this->editViewProvider->setEditViewer(this, ModNum);
addEventCallback(SoEvent::getClassTypeId(), Gui::ViewProvider::eventCallback,this->editViewProvider);
}
/// reset from edit mode
void View3DInventorViewer::resetEditingViewProvider()
{
if (this->editViewProvider) {
// In case the event action still has grabbed a node when leaving edit mode
// force to release it now
SoEventManager* mgr = getSoEventManager();
SoHandleEventAction* heaction = mgr->getHandleEventAction();
if (heaction && heaction->getGrabber())
heaction->releaseGrabber();
resetEditingRoot();
this->editViewProvider->unsetEditViewer(this);
removeEventCallback(SoEvent::getClassTypeId(), Gui::ViewProvider::eventCallback,this->editViewProvider);
this->editViewProvider = nullptr;
}
}
/// reset from edit mode
SbBool View3DInventorViewer::isEditingViewProvider() const
{
return this->editViewProvider ? true : false;
}
/// display override mode
void View3DInventorViewer::setOverrideMode(const std::string& mode)
{
if (mode == overrideMode)
return;
overrideMode = mode;
auto views = getDocument()->getViewProvidersOfType(Gui::ViewProvider::getClassTypeId());
if (mode == "No Shading") {
this->shading = false;
std::string flatLines = "Flat Lines";
for (auto view : views)
view->setOverrideMode(flatLines);
this->getSoRenderManager()->setRenderMode(SoRenderManager::AS_IS);
}
else if (mode == "Hidden Line") {
this->shading = true;