/
ViewProviderSketch.cpp
6860 lines (5851 loc) · 315 KB
/
ViewProviderSketch.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) 2009 Juergen 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 <Standard_math.hxx>
# include <Poly_Polygon3D.hxx>
# include <Geom_BSplineCurve.hxx>
# include <Geom_Circle.hxx>
# include <Geom_Ellipse.hxx>
# include <Geom_TrimmedCurve.hxx>
# include <Inventor/actions/SoGetBoundingBoxAction.h>
# include <Inventor/SoPath.h>
# include <Inventor/SbBox3f.h>
# include <Inventor/SbImage.h>
# include <Inventor/SoPickedPoint.h>
# include <Inventor/details/SoLineDetail.h>
# include <Inventor/details/SoPointDetail.h>
# include <Inventor/nodes/SoBaseColor.h>
# include <Inventor/nodes/SoCoordinate3.h>
# include <Inventor/nodes/SoDrawStyle.h>
# include <Inventor/nodes/SoImage.h>
# include <Inventor/nodes/SoInfo.h>
# include <Inventor/nodes/SoLineSet.h>
# include <Inventor/nodes/SoPointSet.h>
# include <Inventor/nodes/SoMarkerSet.h>
# include <Inventor/nodes/SoMaterial.h>
# include <Inventor/nodes/SoAsciiText.h>
# include <Inventor/nodes/SoTransform.h>
# include <Inventor/nodes/SoSeparator.h>
# include <Inventor/nodes/SoAnnotation.h>
# include <Inventor/nodes/SoVertexProperty.h>
# include <Inventor/nodes/SoTranslation.h>
# include <Inventor/nodes/SoText2.h>
# include <Inventor/nodes/SoFont.h>
# include <Inventor/nodes/SoPickStyle.h>
# include <Inventor/nodes/SoCamera.h>
# include <Inventor/SbTime.h>
/// Qt Include Files
# include <QAction>
# include <QApplication>
# include <QColor>
# include <QDialog>
# include <QFont>
# include <QImage>
# include <QMenu>
# include <QMessageBox>
# include <QPainter>
# include <QTextStream>
# include <QKeyEvent>
# include <boost_bind_bind.hpp>
# include <boost/scoped_ptr.hpp>
#endif
/// Here the FreeCAD includes sorted by Base,App,Gui......
#include <Base/Converter.h>
#include <Base/Tools.h>
#include <Base/Parameter.h>
#include <Base/Console.h>
#include <Base/Vector3D.h>
#include <Base/Interpreter.h>
#include <Base/UnitsSchema.h>
#include <Base/UnitsApi.h>
#include <Gui/Application.h>
#include <Gui/BitmapFactory.h>
#include <Gui/Document.h>
#include <Gui/CommandT.h>
#include <Gui/Control.h>
#include <Gui/Selection.h>
#include <Gui/Tools.h>
#include <Gui/Utilities.h>
#include <Gui/MainWindow.h>
#include <Gui/MenuManager.h>
#include <Gui/View3DInventor.h>
#include <Gui/View3DInventorViewer.h>
#include <Gui/DlgEditFileIncludePropertyExternal.h>
#include <Gui/SoFCBoundingBox.h>
#include <Gui/SoFCUnifiedSelection.h>
#include <Gui/Inventor/MarkerBitmaps.h>
#include <Gui/Inventor/SmSwitchboard.h>
#include <Mod/Part/App/Geometry.h>
#include <Mod/Part/App/BodyBase.h>
#include <Mod/Sketcher/App/SketchObject.h>
#include <Mod/Sketcher/App/Sketch.h>
#include <Mod/Sketcher/App/GeometryFacade.h>
#include "SoZoomTranslation.h"
#include "SoDatumLabel.h"
#include "EditDatumDialog.h"
#include "ViewProviderSketch.h"
#include "DrawSketchHandler.h"
#include "TaskDlgEditSketch.h"
#include "TaskSketcherValidation.h"
#include "CommandConstraints.h"
#include "ViewProviderSketchGeometryExtension.h"
FC_LOG_LEVEL_INIT("Sketch",true,true)
// The first is used to point at a SoDatumLabel for some
// constraints, and at a SoMaterial for others...
#define CONSTRAINT_SEPARATOR_INDEX_MATERIAL_OR_DATUMLABEL 0
#define CONSTRAINT_SEPARATOR_INDEX_FIRST_TRANSLATION 1
#define CONSTRAINT_SEPARATOR_INDEX_FIRST_ICON 2
#define CONSTRAINT_SEPARATOR_INDEX_FIRST_CONSTRAINTID 3
#define CONSTRAINT_SEPARATOR_INDEX_SECOND_TRANSLATION 4
#define CONSTRAINT_SEPARATOR_INDEX_SECOND_ICON 5
#define CONSTRAINT_SEPARATOR_INDEX_SECOND_CONSTRAINTID 6
// Macros to define information layer node child positions within type
#define GEOINFO_BSPLINE_DEGREE_POS 0
#define GEOINFO_BSPLINE_DEGREE_TEXT 3
#define GEOINFO_BSPLINE_POLYGON 1
using namespace SketcherGui;
using namespace Sketcher;
namespace bp = boost::placeholders;
SbColor ViewProviderSketch::VertexColor (1.0f,0.149f,0.0f); // #FF2600 -> (255, 38, 0)
SbColor ViewProviderSketch::CurveColor (1.0f,1.0f,1.0f); // #FFFFFF -> (255,255,255)
SbColor ViewProviderSketch::CurveDraftColor (0.0f,0.0f,0.86f); // #0000DC -> ( 0, 0,220)
SbColor ViewProviderSketch::CurveExternalColor (0.8f,0.2f,0.6f); // #CC3399 -> (204, 51,153)
SbColor ViewProviderSketch::CrossColorH (0.8f,0.4f,0.4f); // #CC6666 -> (204,102,102)
SbColor ViewProviderSketch::CrossColorV (0.4f,0.8f,0.4f); // #66CC66 -> (102,204,102)
SbColor ViewProviderSketch::FullyConstrainedColor (0.0f,1.0f,0.0f); // #00FF00 -> ( 0,255, 0)
SbColor ViewProviderSketch::ConstrDimColor (1.0f,0.149f,0.0f); // #FF2600 -> (255, 38, 0)
SbColor ViewProviderSketch::ConstrIcoColor (1.0f,0.149f,0.0f); // #FF2600 -> (255, 38, 0)
SbColor ViewProviderSketch::NonDrivingConstrDimColor (0.0f,0.149f,1.0f); // #0026FF -> ( 0, 38,255)
SbColor ViewProviderSketch::ExprBasedConstrDimColor (1.0f,0.5f,0.149f); // #FF7F26 -> (255, 127, 38)
SbColor ViewProviderSketch::InformationColor (0.0f,1.0f,0.0f); // #00FF00 -> ( 0,255, 0)
SbColor ViewProviderSketch::PreselectColor (0.88f,0.88f,0.0f); // #E1E100 -> (225,225, 0)
SbColor ViewProviderSketch::SelectColor (0.11f,0.68f,0.11f); // #1CAD1C -> ( 28,173, 28)
SbColor ViewProviderSketch::PreselectSelectedColor (0.36f,0.48f,0.11f); // #5D7B1C -> ( 93,123, 28)
SbColor ViewProviderSketch::CreateCurveColor (0.8f,0.8f,0.8f); // #CCCCCC -> (204,204,204)
SbColor ViewProviderSketch::DeactivatedConstrDimColor (0.8f,0.8f,0.8f); // #CCCCCC -> (204,204,204)
SbColor ViewProviderSketch::InternalAlignedGeoColor (0.7f,0.7f,0.5f); // #B2B27F -> (178,178,127)
// Variables for holding previous click
SbTime ViewProviderSketch::prvClickTime;
SbVec2s ViewProviderSketch::prvClickPos;
SbVec2s ViewProviderSketch::prvCursorPos;
SbVec2s ViewProviderSketch::newCursorPos;
//**************************************************************************
// Edit data structure
/// Data structure while editing the sketch
struct EditData {
EditData():
sketchHandler(0),
buttonPress(false),
handleEscapeButton(false),
DragPoint(-1),
DragCurve(-1),
PreselectPoint(-1),
PreselectCurve(-1),
PreselectCross(-1),
MarkerSize(7),
blockedPreselection(false),
FullyConstrained(false),
//ActSketch(0), // if you are wondering, it went to SketchObject, accessible via getSketchObject()->getSolvedSketch()
EditRoot(0),
PointsMaterials(0),
CurvesMaterials(0),
RootCrossMaterials(0),
EditCurvesMaterials(0),
PointsCoordinate(0),
CurvesCoordinate(0),
RootCrossCoordinate(0),
EditCurvesCoordinate(0),
CurveSet(0),
RootCrossSet(0),
EditCurveSet(0),
PointSet(0),
textX(0),
textPos(0),
constrGroup(0),
infoGroup(0),
pickStyleAxes(0)
{}
// pointer to the active handler for new sketch objects
DrawSketchHandler *sketchHandler;
bool buttonPress;
bool handleEscapeButton;
// dragged point
int DragPoint;
// dragged curve
int DragCurve;
// dragged constraints
std::set<int> DragConstraintSet;
SbColor PreselectOldColor;
int PreselectPoint;
int PreselectCurve;
int PreselectCross;
int MarkerSize;
std::set<int> PreselectConstraintSet;
bool blockedPreselection;
bool FullyConstrained;
// container to track our own selected parts
std::set<int> SelPointSet;
std::set<int> SelCurvSet; // also holds cross axes at -1 and -2
std::set<int> SelConstraintSet;
std::vector<int> CurvIdToGeoId; // conversion of SoLineSet index to GeoId
std::vector<int> PointIdToGeoId; // conversion of SoCoordinate3 index to GeoId
// helper data structures for the constraint rendering
std::vector<ConstraintType> vConstrType;
// For each of the combined constraint icons drawn, also create a vector
// of bounding boxes and associated constraint IDs, to go from the icon's
// pixel coordinates to the relevant constraint IDs.
//
// The outside map goes from a string representation of a set of constraint
// icons (like the one used by the constraint IDs we insert into the Coin
// rendering tree) to a vector of those bounding boxes paired with relevant
// constraint IDs.
std::map<QString, ViewProviderSketch::ConstrIconBBVec> combinedConstrBoxes;
// nodes for the visuals
SoSeparator *EditRoot;
SoMaterial *PointsMaterials;
SoMaterial *CurvesMaterials;
SoMaterial *RootCrossMaterials;
SoMaterial *EditCurvesMaterials;
SoCoordinate3 *PointsCoordinate;
SoCoordinate3 *CurvesCoordinate;
SoCoordinate3 *RootCrossCoordinate;
SoCoordinate3 *EditCurvesCoordinate;
SoLineSet *CurveSet;
SoLineSet *RootCrossSet;
SoLineSet *EditCurveSet;
SoMarkerSet *PointSet;
SoText2 *textX;
SoTranslation *textPos;
SmSwitchboard *constrGroup;
SoGroup *infoGroup;
SoPickStyle *pickStyleAxes;
};
// this function is used to simulate cyclic periodic negative geometry indices (for external geometry)
const Part::Geometry* GeoById(const std::vector<Part::Geometry*> GeoList, int Id)
{
if (Id >= 0)
return GeoList[Id];
else
return GeoList[GeoList.size()+Id];
}
//**************************************************************************
// Construction/Destruction
/* TRANSLATOR SketcherGui::ViewProviderSketch */
PROPERTY_SOURCE(SketcherGui::ViewProviderSketch, PartGui::ViewProvider2DObjectGrid)
ViewProviderSketch::ViewProviderSketch()
: SelectionObserver(false),
edit(0),
Mode(STATUS_NONE),
visibleInformationChanged(true),
combrepscalehyst(0),
isShownVirtualSpace(false),
listener(0)
{
ADD_PROPERTY_TYPE(Autoconstraints,(true),"Auto Constraints",(App::PropertyType)(App::Prop_None),"Create auto constraints");
ADD_PROPERTY_TYPE(AvoidRedundant,(true),"Auto Constraints",(App::PropertyType)(App::Prop_None),"Avoid redundant autoconstraint");
ADD_PROPERTY_TYPE(TempoVis,(Py::None()),"Visibility automation",(App::PropertyType)(App::Prop_None),"Object that handles hiding and showing other objects when entering/leaving sketch.");
ADD_PROPERTY_TYPE(HideDependent,(true),"Visibility automation",(App::PropertyType)(App::Prop_None),"If true, all objects that depend on the sketch are hidden when opening editing.");
ADD_PROPERTY_TYPE(ShowLinks,(true),"Visibility automation",(App::PropertyType)(App::Prop_None),"If true, all objects used in links to external geometry are shown when opening sketch.");
ADD_PROPERTY_TYPE(ShowSupport,(true),"Visibility automation",(App::PropertyType)(App::Prop_None),"If true, all objects this sketch is attached to are shown when opening sketch.");
ADD_PROPERTY_TYPE(RestoreCamera,(true),"Visibility automation",(App::PropertyType)(App::Prop_None),"If true, camera position before entering sketch is remembered, and restored after closing it.");
ADD_PROPERTY_TYPE(EditingWorkbench,("SketcherWorkbench"),"Visibility automation",(App::PropertyType)(App::Prop_None),"Name of the workbench to activate when editing this sketch.");
{//visibility automation: update defaults to follow preferences
ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher/General");
this->HideDependent.setValue(hGrp->GetBool("HideDependent", true));
this->ShowLinks.setValue(hGrp->GetBool("ShowLinks", true));
this->ShowSupport.setValue(hGrp->GetBool("ShowSupport", true));
this->RestoreCamera.setValue(hGrp->GetBool("RestoreCamera", true));
// well it is not visibility automation but a good place nevertheless
this->ShowGrid.setValue(hGrp->GetBool("ShowGrid", false));
this->GridSize.setValue(Base::Quantity::parse(QString::fromLatin1(hGrp->GetGroup("GridSize")->GetASCII("Hist0", "10.0").c_str())).getValue());
this->GridSnap.setValue(hGrp->GetBool("GridSnap", false));
this->Autoconstraints.setValue(hGrp->GetBool("AutoConstraints", true));
this->AvoidRedundant.setValue(hGrp->GetBool("AvoidRedundantAutoconstraints", true));
this->GridAutoSize.setValue(false); //Grid size is managed by this class
}
sPixmap = "Sketcher_Sketch";
LineColor.setValue(1,1,1);
PointColor.setValue(1,1,1);
PointSize.setValue(4);
zCross=0.001f;
zEdit=0.001f;
zInfo=0.004f;
zLowLines=0.005f;
//zLines=0.005f; // ZLines removed in favour of 3 height groups intended for NormalLines, ConstructionLines, ExternalLines
zMidLines=0.006f;
zHighLines=0.007f; // Lines that are somehow selected to be in the high position (higher than other line categories)
zHighLine=0.008f; // highlighted line (of any group)
zConstr=0.009f; // constraint not construction
//zPoints=0.010f;
zLowPoints = 0.010f;
zHighPoints = 0.011f;
zHighlight=0.012f;
zText=0.012f;
xInit=0;
yInit=0;
relative=false;
unsigned long color;
ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/View");
// edge color
App::Color edgeColor = LineColor.getValue();
color = (unsigned long)(edgeColor.getPackedValue());
color = hGrp->GetUnsigned("SketchEdgeColor", color);
edgeColor.setPackedValue((uint32_t)color);
LineColor.setValue(edgeColor);
// vertex color
App::Color vertexColor = PointColor.getValue();
color = (unsigned long)(vertexColor.getPackedValue());
color = hGrp->GetUnsigned("SketchVertexColor", color);
vertexColor.setPackedValue((uint32_t)color);
PointColor.setValue(vertexColor);
//rubberband selection
rubberband = new Gui::Rubberband();
}
ViewProviderSketch::~ViewProviderSketch()
{
delete rubberband;
}
void ViewProviderSketch::slotUndoDocument(const Gui::Document& /*doc*/)
{
// Note 1: this slot is only operative during edit mode (see signal connection/disconnection)
// Note 2: ViewProviderSketch::UpdateData does not generate updates during undo/redo
// transactions as mid-transaction data may not be in a valid state (e.g. constraints
// may reference invalid geometry). However undo/redo notify SketchObject after the undo/redo
// and before this slot is called.
// Note 3: Note that recomputes are no longer inhibited during the call to this slot.
forceUpdateData();
}
void ViewProviderSketch::slotRedoDocument(const Gui::Document& /*doc*/)
{
// Note 1: this slot is only operative during edit mode (see signal connection/disconnection)
// Note 2: ViewProviderSketch::UpdateData does not generate updates during undo/redo
// transactions as mid-transaction data may not be in a valid state (e.g. constraints
// may reference invalid geometry). However undo/redo notify SketchObject after the undo/redo
// and before this slot is called.
// Note 3: Note that recomputes are no longer inhibited during the call to this slot.
forceUpdateData();
}
void ViewProviderSketch::forceUpdateData()
{
if(!getSketchObject()->noRecomputes) { // the sketch was already solved in SketchObject in onUndoRedoFinished
Gui::Command::updateActive();
}
}
// handler management ***************************************************************
void ViewProviderSketch::activateHandler(DrawSketchHandler *newHandler)
{
assert(edit);
assert(edit->sketchHandler == 0);
edit->sketchHandler = newHandler;
Mode = STATUS_SKETCH_UseHandler;
edit->sketchHandler->sketchgui = this;
edit->sketchHandler->activated(this);
// make sure receiver has focus so immediately pressing Escape will be handled by
// ViewProviderSketch::keyPressed() and dismiss the active handler, and not the entire
// sketcher editor
Gui::MDIView *mdi = Gui::Application::Instance->activeDocument()->getActiveView();
mdi->setFocus();
}
void ViewProviderSketch::deactivateHandler()
{
assert(edit);
if(edit->sketchHandler != 0){
std::vector<Base::Vector2d> editCurve;
editCurve.clear();
drawEdit(editCurve); // erase any line
resetPositionText();
edit->sketchHandler->deactivated(this);
edit->sketchHandler->unsetCursor();
delete(edit->sketchHandler);
}
edit->sketchHandler = 0;
Mode = STATUS_NONE;
}
/// removes the active handler
void ViewProviderSketch::purgeHandler(void)
{
deactivateHandler();
Gui::Selection().clearSelection();
// ensure that we are in sketch only selection mode
Gui::MDIView *mdi = Gui::Application::Instance->editDocument()->getActiveView();
Gui::View3DInventorViewer *viewer;
viewer = static_cast<Gui::View3DInventor *>(mdi)->getViewer();
SoNode* root = viewer->getSceneGraph();
static_cast<Gui::SoFCUnifiedSelection*>(root)->selectionRole.setValue(false);
}
void ViewProviderSketch::setAxisPickStyle(bool on)
{
assert(edit);
if (on)
edit->pickStyleAxes->style = SoPickStyle::SHAPE;
else
edit->pickStyleAxes->style = SoPickStyle::UNPICKABLE;
}
// **********************************************************************************
bool ViewProviderSketch::keyPressed(bool pressed, int key)
{
switch (key)
{
case SoKeyboardEvent::ESCAPE:
{
// make the handler quit but not the edit mode
if (edit && edit->sketchHandler) {
if (!pressed)
edit->sketchHandler->quit();
return true;
}
if (edit && (edit->DragConstraintSet.empty() == false)) {
if (!pressed) {
edit->DragConstraintSet.clear();
}
return true;
}
if (edit && edit->DragCurve >= 0) {
if (!pressed) {
getSketchObject()->movePoint(edit->DragCurve, Sketcher::none, Base::Vector3d(0,0,0), true);
edit->DragCurve = -1;
resetPositionText();
Mode = STATUS_NONE;
}
return true;
}
if (edit && edit->DragPoint >= 0) {
if (!pressed) {
int GeoId;
Sketcher::PointPos PosId;
getSketchObject()->getGeoVertexIndex(edit->DragPoint, GeoId, PosId);
getSketchObject()->movePoint(GeoId, PosId, Base::Vector3d(0,0,0), true);
edit->DragPoint = -1;
resetPositionText();
Mode = STATUS_NONE;
}
return true;
}
if (edit) {
// #0001479: 'Escape' key dismissing dialog cancels Sketch editing
// If we receive a button release event but not a press event before
// then ignore this one.
if (!pressed && !edit->buttonPress)
return true;
edit->buttonPress = pressed;
// More control over Sketcher edit mode Esc key behavior
// https://forum.freecadweb.org/viewtopic.php?f=3&t=42207
return edit->handleEscapeButton;
}
return false;
}
default:
{
if (edit && edit->sketchHandler)
edit->sketchHandler->registerPressedKey(pressed,key);
}
}
return true; // handle all other key events
}
void ViewProviderSketch::snapToGrid(double &x, double &y)
{
if (GridSnap.getValue() && ShowGrid.getValue()) {
// Snap Tolerance in pixels
const double snapTol = GridSize.getValue() / 5;
double tmpX = x, tmpY = y;
// Find Nearest Snap points
tmpX = tmpX / GridSize.getValue();
tmpX = tmpX < 0.0 ? ceil(tmpX - 0.5) : floor(tmpX + 0.5);
tmpX *= GridSize.getValue();
tmpY = tmpY / GridSize.getValue();
tmpY = tmpY < 0.0 ? ceil(tmpY - 0.5) : floor(tmpY + 0.5);
tmpY *= GridSize.getValue();
// Check if x within snap tolerance
if (x < tmpX + snapTol && x > tmpX - snapTol)
x = tmpX; // Snap X Mouse Position
// Check if y within snap tolerance
if (y < tmpY + snapTol && y > tmpY - snapTol)
y = tmpY; // Snap Y Mouse Position
}
}
void ViewProviderSketch::getProjectingLine(const SbVec2s& pnt, const Gui::View3DInventorViewer *viewer, SbLine& line) const
{
const SbViewportRegion& vp = viewer->getSoRenderManager()->getViewportRegion();
short x,y; pnt.getValue(x,y);
SbVec2f siz = vp.getViewportSize();
float dX, dY; siz.getValue(dX, dY);
float fRatio = vp.getViewportAspectRatio();
float pX = (float)x / float(vp.getViewportSizePixels()[0]);
float pY = (float)y / float(vp.getViewportSizePixels()[1]);
// now calculate the real points respecting aspect ratio information
//
if (fRatio > 1.0f) {
pX = (pX - 0.5f*dX) * fRatio + 0.5f*dX;
}
else if (fRatio < 1.0f) {
pY = (pY - 0.5f*dY) / fRatio + 0.5f*dY;
}
SoCamera* pCam = viewer->getSoRenderManager()->getCamera();
if (!pCam) return;
SbViewVolume vol = pCam->getViewVolume();
vol.projectPointToLine(SbVec2f(pX,pY), line);
}
Base::Placement ViewProviderSketch::getEditingPlacement() const {
auto doc = Gui::Application::Instance->editDocument();
if(!doc || doc->getInEdit()!=this)
return getSketchObject()->globalPlacement();
// TODO: won't work if there is scale. Hmm... what to do...
return Base::Placement(doc->getEditingTransform());
}
void ViewProviderSketch::getCoordsOnSketchPlane(double &u, double &v,const SbVec3f &point, const SbVec3f &normal)
{
// Plane form
Base::Vector3d R0(0,0,0),RN(0,0,1),RX(1,0,0),RY(0,1,0);
// move to position of Sketch
Base::Placement Plz = getEditingPlacement();
R0 = Plz.getPosition() ;
Base::Rotation tmp(Plz.getRotation());
tmp.multVec(RN,RN);
tmp.multVec(RX,RX);
tmp.multVec(RY,RY);
Plz.setRotation(tmp);
// line
Base::Vector3d R1(point[0],point[1],point[2]),RA(normal[0],normal[1],normal[2]);
if (fabs(RN*RA) < FLT_EPSILON)
throw Base::DivisionByZeroError("View direction is parallel to sketch plane");
// intersection point on plane
Base::Vector3d S = R1 + ((RN * (R0-R1))/(RN*RA))*RA;
// distance to x Axle of the sketch
S.TransformToCoordinateSystem(R0,RX,RY);
u = S.x;
v = S.y;
}
bool ViewProviderSketch::mouseButtonPressed(int Button, bool pressed, const SbVec2s &cursorPos,
const Gui::View3DInventorViewer *viewer)
{
assert(edit);
// Calculate 3d point to the mouse position
SbLine line;
getProjectingLine(cursorPos, viewer, line);
SbVec3f point = line.getPosition();
SbVec3f normal = line.getDirection();
// use scoped_ptr to make sure that instance gets deleted in all cases
boost::scoped_ptr<SoPickedPoint> pp(this->getPointOnRay(cursorPos, viewer));
// Radius maximum to allow double click event
const int dblClickRadius = 5;
double x,y;
SbVec3f pos = point;
if (pp) {
const SoDetail *detail = pp->getDetail();
if (detail && detail->getTypeId() == SoPointDetail::getClassTypeId()) {
pos = pp->getPoint();
}
}
try {
getCoordsOnSketchPlane(x,y,pos,normal);
snapToGrid(x, y);
}
catch (const Base::DivisionByZeroError&) {
return false;
}
// Left Mouse button ****************************************************
if (Button == 1) {
if (pressed) {
// Do things depending on the mode of the user interaction
switch (Mode) {
case STATUS_NONE:{
bool done=false;
if (edit->PreselectPoint != -1) {
//Base::Console().Log("start dragging, point:%d\n",this->DragPoint);
Mode = STATUS_SELECT_Point;
done = true;
} else if (edit->PreselectCurve != -1) {
//Base::Console().Log("start dragging, point:%d\n",this->DragPoint);
Mode = STATUS_SELECT_Edge;
done = true;
} else if (edit->PreselectCross != -1) {
//Base::Console().Log("start dragging, point:%d\n",this->DragPoint);
Mode = STATUS_SELECT_Cross;
done = true;
} else if (edit->PreselectConstraintSet.empty() != true) {
//Base::Console().Log("start dragging, point:%d\n",this->DragPoint);
Mode = STATUS_SELECT_Constraint;
done = true;
}
// Double click events variables
float dci = (float) QApplication::doubleClickInterval()/1000.0f;
if (done &&
SbVec2f(cursorPos - prvClickPos).length() < dblClickRadius &&
(SbTime::getTimeOfDay() - prvClickTime).getValue() < dci) {
// Double Click Event Occurred
editDoubleClicked();
// Reset Double Click Static Variables
prvClickTime = SbTime();
prvClickPos = SbVec2s(-16000,-16000); //certainly far away from any clickable place, to avoid re-trigger of double-click if next click happens fast.
Mode = STATUS_NONE;
} else {
prvClickTime = SbTime::getTimeOfDay();
prvClickPos = cursorPos;
prvCursorPos = cursorPos;
newCursorPos = cursorPos;
if (!done)
Mode = STATUS_SKETCH_StartRubberBand;
}
return done;
}
case STATUS_SKETCH_UseHandler:
return edit->sketchHandler->pressButton(Base::Vector2d(x,y));
default:
return false;
}
} else { // Button 1 released
// Do things depending on the mode of the user interaction
switch (Mode) {
case STATUS_SELECT_Point:
if (pp) {
//Base::Console().Log("Select Point:%d\n",this->DragPoint);
// Do selection
std::stringstream ss;
ss << "Vertex" << edit->PreselectPoint + 1;
#define SEL_PARAMS editDocName.c_str(),editObjName.c_str(),\
(editSubName+ss.str()).c_str()
if (Gui::Selection().isSelected(SEL_PARAMS) ) {
Gui::Selection().rmvSelection(SEL_PARAMS);
} else {
Gui::Selection().addSelection2(SEL_PARAMS
,pp->getPoint()[0]
,pp->getPoint()[1]
,pp->getPoint()[2]);
this->edit->DragPoint = -1;
this->edit->DragCurve = -1;
this->edit->DragConstraintSet.clear();
}
}
Mode = STATUS_NONE;
return true;
case STATUS_SELECT_Edge:
if (pp) {
//Base::Console().Log("Select Point:%d\n",this->DragPoint);
std::stringstream ss;
if (edit->PreselectCurve >= 0)
ss << "Edge" << edit->PreselectCurve + 1;
else // external geometry
ss << "ExternalEdge" << -edit->PreselectCurve - 2;
// If edge already selected move from selection
if (Gui::Selection().isSelected(SEL_PARAMS) ) {
Gui::Selection().rmvSelection(SEL_PARAMS);
} else {
// Add edge to the selection
Gui::Selection().addSelection2(SEL_PARAMS
,pp->getPoint()[0]
,pp->getPoint()[1]
,pp->getPoint()[2]);
this->edit->DragPoint = -1;
this->edit->DragCurve = -1;
this->edit->DragConstraintSet.clear();
}
}
Mode = STATUS_NONE;
return true;
case STATUS_SELECT_Cross:
if (pp) {
//Base::Console().Log("Select Point:%d\n",this->DragPoint);
std::stringstream ss;
switch(edit->PreselectCross){
case 0: ss << "RootPoint" ; break;
case 1: ss << "H_Axis" ; break;
case 2: ss << "V_Axis" ; break;
}
// If cross already selected move from selection
if (Gui::Selection().isSelected(SEL_PARAMS) ) {
Gui::Selection().rmvSelection(SEL_PARAMS);
} else {
// Add cross to the selection
Gui::Selection().addSelection2(SEL_PARAMS
,pp->getPoint()[0]
,pp->getPoint()[1]
,pp->getPoint()[2]);
this->edit->DragPoint = -1;
this->edit->DragCurve = -1;
this->edit->DragConstraintSet.clear();
}
}
Mode = STATUS_NONE;
return true;
case STATUS_SELECT_Constraint:
if (pp) {
auto sels = edit->PreselectConstraintSet;
for(int id : sels) {
std::stringstream ss;
ss << Sketcher::PropertyConstraintList::getConstraintName(id);
// If the constraint already selected remove
if (Gui::Selection().isSelected(SEL_PARAMS) ) {
Gui::Selection().rmvSelection(SEL_PARAMS);
} else {
// Add constraint to current selection
Gui::Selection().addSelection2(SEL_PARAMS
,pp->getPoint()[0]
,pp->getPoint()[1]
,pp->getPoint()[2]);
this->edit->DragPoint = -1;
this->edit->DragCurve = -1;
this->edit->DragConstraintSet.clear();
}
}
}
Mode = STATUS_NONE;
return true;
case STATUS_SKETCH_DragPoint:
if (edit->DragPoint != -1) {
int GeoId;
Sketcher::PointPos PosId;
getSketchObject()->getGeoVertexIndex(edit->DragPoint, GeoId, PosId);
if (GeoId != Sketcher::Constraint::GeoUndef && PosId != Sketcher::none) {
getDocument()->openCommand(QT_TRANSLATE_NOOP("Command", "Drag Point"));
try {
Gui::cmdAppObjectArgs(getObject(), "movePoint(%i,%i,App.Vector(%f,%f,0),%i)"
,GeoId, PosId, x-xInit, y-yInit, 0);
getDocument()->commitCommand();
tryAutoRecomputeIfNotSolve(getSketchObject());
}
catch (const Base::Exception& e) {
getDocument()->abortCommand();
Base::Console().Error("Drag point: %s\n", e.what());
}
}
setPreselectPoint(edit->DragPoint);
edit->DragPoint = -1;
//updateColor();
}
resetPositionText();
Mode = STATUS_NONE;
return true;
case STATUS_SKETCH_DragCurve:
if (edit->DragCurve != -1) {
const Part::Geometry *geo = getSketchObject()->getGeometry(edit->DragCurve);
if (geo->getTypeId() == Part::GeomLineSegment::getClassTypeId() ||
geo->getTypeId() == Part::GeomArcOfCircle::getClassTypeId() ||
geo->getTypeId() == Part::GeomCircle::getClassTypeId() ||
geo->getTypeId() == Part::GeomEllipse::getClassTypeId()||
geo->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId()||
geo->getTypeId() == Part::GeomArcOfParabola::getClassTypeId()||
geo->getTypeId() == Part::GeomArcOfHyperbola::getClassTypeId()||
geo->getTypeId() == Part::GeomBSplineCurve::getClassTypeId()) {
getDocument()->openCommand(QT_TRANSLATE_NOOP("Command", "Drag Curve"));
auto geo = getSketchObject()->getGeometry(edit->DragCurve);
auto gf = GeometryFacade::getFacade(geo);
Base::Vector3d vec(x-xInit,y-yInit,0);
// BSpline weights have a radius corresponding to the weight value
// However, in order for them proportional to the B-Spline size,
// the scenograph has a size scalefactor times the weight
// This code normalizes the information sent to the solver.
if(gf->getInternalType() == InternalType::BSplineControlPoint) {
auto circle = static_cast<const Part::GeomCircle *>(geo);
Base::Vector3d center = circle->getCenter();
Base::Vector3d dir = vec - center;
double scalefactor = 1.0;
if(circle->hasExtension(SketcherGui::ViewProviderSketchGeometryExtension::getClassTypeId()))
{
auto vpext = std::static_pointer_cast<const SketcherGui::ViewProviderSketchGeometryExtension>(
circle->getExtension(SketcherGui::ViewProviderSketchGeometryExtension::getClassTypeId()).lock());
scalefactor = vpext->getRepresentationFactor();
}
vec = center + dir / scalefactor;
}
try {
Gui::cmdAppObjectArgs(getObject(), "movePoint(%i,%i,App.Vector(%f,%f,0),%i)"
,edit->DragCurve, Sketcher::none, vec.x, vec.y, relative ? 1 : 0);
getDocument()->commitCommand();
tryAutoRecomputeIfNotSolve(getSketchObject());
}
catch (const Base::Exception& e) {
getDocument()->abortCommand();
Base::Console().Error("Drag curve: %s\n", e.what());
}
}
edit->PreselectCurve = edit->DragCurve;
edit->DragCurve = -1;
//updateColor();
}
resetPositionText();
Mode = STATUS_NONE;
return true;
case STATUS_SKETCH_DragConstraint:
if (edit->DragConstraintSet.empty() == false) {
getDocument()->openCommand(QT_TRANSLATE_NOOP("Command", "Drag Constraint"));
auto idset = edit->DragConstraintSet;
for(int id : idset) {
moveConstraint(id, Base::Vector2d(x, y));
//updateColor();
}
edit->PreselectConstraintSet = edit->DragConstraintSet;
edit->DragConstraintSet.clear();
getDocument()->commitCommand();
}
Mode = STATUS_NONE;
return true;
case STATUS_SKETCH_StartRubberBand: // a single click happened, so clear selection
Mode = STATUS_NONE;
Gui::Selection().clearSelection();
return true;
case STATUS_SKETCH_UseRubberBand:
doBoxSelection(prvCursorPos, cursorPos, viewer);
rubberband->setWorking(false);
//disable framebuffer drawing in viewer
const_cast<Gui::View3DInventorViewer *>(viewer)->setRenderType(Gui::View3DInventorViewer::Native);
// a redraw is required in order to clear the rubberband
draw(true,false);
const_cast<Gui::View3DInventorViewer*>(viewer)->redraw();
Mode = STATUS_NONE;
return true;
case STATUS_SKETCH_UseHandler: {
return edit->sketchHandler->releaseButton(Base::Vector2d(x,y));
}
case STATUS_NONE:
default:
return false;
}
}
}
// Right mouse button ****************************************************
else if (Button == 2) {
if (!pressed) {
switch (Mode) {
case STATUS_SKETCH_UseHandler:
// make the handler quit
edit->sketchHandler->quit();
return true;
case STATUS_NONE:
{
// A right click shouldn't change the Edit Mode
if (edit->PreselectPoint != -1) {
return true;
} else if (edit->PreselectCurve != -1) {
return true;
} else if (edit->PreselectConstraintSet.empty() != true) {
return true;
} else {
Gui::MenuItem geom;
geom.setCommand("Sketcher geoms");
geom << "Sketcher_CreatePoint"
<< "Sketcher_CreateArc"
<< "Sketcher_Create3PointArc"
<< "Sketcher_CreateCircle"
<< "Sketcher_Create3PointCircle"
<< "Sketcher_CreateLine"
<< "Sketcher_CreatePolyline"
<< "Sketcher_CreateRectangle"
<< "Sketcher_CreateHexagon"
<< "Sketcher_CreateFillet"
<< "Sketcher_Trimming"
<< "Sketcher_Extend"
<< "Sketcher_External"
<< "Sketcher_ToggleConstruction"
/*<< "Sketcher_CreateText"*/
/*<< "Sketcher_CreateDraftLine"*/
<< "Separator";
Gui::Application::Instance->setupContextMenu("View", &geom);
//Create the Context Menu using the Main View Qt Widget
QMenu contextMenu(viewer->getGLWidget());
Gui::MenuManager::getInstance()->setupContextMenu(&geom, contextMenu);
contextMenu.exec(QCursor::pos());
return true;
}
}
case STATUS_SELECT_Point:
break;
case STATUS_SELECT_Edge:
{
Gui::MenuItem geom;
geom.setCommand("Sketcher constraints");
geom << "Sketcher_ConstrainVertical"
<< "Sketcher_ConstrainHorizontal";
// Gets a selection vector
std::vector<Gui::SelectionObject> selection = Gui::Selection().getSelectionEx();
bool rightClickOnSelectedLine = false;
/*
* Add Multiple Line Constraints to the menu
*/
// only one sketch with its subelements are allowed to be selected
if (selection.size() == 1) {
// get the needed lists and objects
const std::vector<std::string> &SubNames = selection[0].getSubNames();