/
Attacher.cpp
2089 lines (1860 loc) · 78.3 KB
/
Attacher.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) Victor Titov (DeepSOIC) *
* (vv.titov@gmail.com) 2015 *
* *
* 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 <TopoDS_Shape.hxx>
# include <TopoDS_Face.hxx>
# include <TopoDS_Edge.hxx>
# include <TopoDS_Vertex.hxx>
# include <TopoDS_Iterator.hxx>
# include <TopoDS.hxx>
# include <BRep_Tool.hxx>
# include <gp_Pln.hxx>
# include <gp_Ax1.hxx>
# include <gp_Pnt.hxx>
# include <gp_Dir.hxx>
# include <gp_Elips.hxx>
# include <gp_Parab.hxx>
# include <gp_Hypr.hxx>
# include <GeomAPI_ProjectPointOnSurf.hxx>
# include <Geom_Plane.hxx>
# include <Geom2d_Curve.hxx>
# include <Geom2dAPI_InterCurveCurve.hxx>
# include <Geom2dAPI_ProjectPointOnCurve.hxx>
# include <GeomAPI.hxx>
# include <BRepAdaptor_Surface.hxx>
# include <BRepAdaptor_Curve.hxx>
# include <BRepBuilderAPI_MakeFace.hxx>
# include <BRepBuilderAPI_MakeEdge.hxx>
# include <BRepExtrema_DistShapeShape.hxx>
# include <TopTools_HSequenceOfShape.hxx>
# include <ShapeExtend_Explorer.hxx>
# include <GProp_GProps.hxx>
# include <GProp_PGProps.hxx>
# include <GProp_PrincipalProps.hxx>
# include <BRepGProp.hxx>
# include <GeomLib_IsPlanarSurface.hxx>
#endif
#include <BRepLProp_SLProps.hxx>
#include <GeomAPI_ProjectPointOnCurve.hxx>
#include "Attacher.h"
#include <Base/Console.h>
#include <App/OriginFeature.h>
#include <App/Application.h>
#include <App/Document.h>
using namespace Part;
using namespace Attacher;
//These strings are for mode list enum property.
const char* AttachEngine::eMapModeStrings[]= {
"Deactivated",
"Translate",
"ObjectXY",
"ObjectXZ",
"ObjectYZ",
"FlatFace",
"TangentPlane",
"NormalToEdge",
"FrenetNB",
"FrenetTN",
"FrenetTB",
"Concentric",
"SectionOfRevolution",
"ThreePointsPlane",
"ThreePointsNormal",
"Folding",
"ObjectX",
"ObjectY",
"ObjectZ",
"AxisOfCurvature",
"Directrix1",
"Directrix2",
"Asymptote1",
"Asymptote2",
"Tangent",
"Normal",
"Binormal",
"TangentU",
"TangentV",
"TwoPointLine",
"IntersectionLine",
"ProximityLine",
"ObjectOrigin",
"Focus1",
"Focus2",
"OnEdge",
"CenterOfCurvature",
"CenterOfMass",
"IntersectionPoint",
"Vertex",
"ProximityPoint1",
"ProximityPoint2",
"AxisOfInertia1",
"AxisOfInertia2",
"AxisOfInertia3",
"InertialCS",
"FaceNormal",
"OZX",
"OZY",
"OXY",
"OXZ",
"OYZ",
"OYX",
NULL};
//this list must be in sync with eRefType enum.
//These strings are used only by Py interface of Attacher. Strings for use in Gui are in Mod/Part/Gui/AttacherTexts.cpp
const char* AttachEngine::eRefTypeStrings[]= {
"Any",
"Vertex",
"Edge",
"Face",
"Line",
"Curve",
"Circle",
"Conic",
"Ellipse",
"Parabola",
"Hyperbola",
"Plane",
"Sphere",
"Revolve",
"Cylinder",
"Torus",
"Cone",
"Object",
"Solid",
"Wire",
NULL
};
TYPESYSTEM_SOURCE_ABSTRACT(Attacher::AttachEngine, Base::BaseClass);
AttachEngine::AttachEngine()
: mapMode(mmDeactivated), mapReverse(false), attachParameter(0.0),
surfU(0.0), surfV(0.0)
{
}
void AttachEngine::setUp(const App::PropertyLinkSubList &references,
eMapMode mapMode, bool mapReverse,
double attachParameter,
double surfU, double surfV,
const Base::Placement &attachmentOffset)
{
this->references.Paste(references);
this->mapMode = mapMode;
this->mapReverse = mapReverse;
this->attachParameter = attachParameter;
this->surfU = surfU;
this->surfV = surfV;
this->attachmentOffset = attachmentOffset;
}
void AttachEngine::setUp(const AttachEngine &another)
{
setUp(another.references,
another.mapMode,
another.mapReverse,
another.attachParameter,
another.surfU,
another.surfV,
another.attachmentOffset);
}
Base::Placement AttachEngine::placementFactory(const gp_Dir &ZAxis,
gp_Vec XAxis,
gp_Pnt Origin,
gp_Pnt refOrg,
bool useRefOrg_Line,
bool useRefOrg_Plane,
bool makeYVertical,
bool makeLegacyFlatFaceOrientation,
Base::Placement* placeOfRef) const
{
if(useRefOrg_Line){
//move Origin to projection of refOrg onto ZAxis
gp_Vec refOrgV = gp_Vec(refOrg.XYZ());
gp_Vec OriginV = gp_Vec(Origin.XYZ());
gp_Vec ZAxisV = gp_Vec(ZAxis);
Origin = gp_Pnt((
OriginV + ZAxisV*ZAxisV.Dot(refOrgV-OriginV)
).XYZ());
}
if(useRefOrg_Plane){
//move Origin to projection of refOrg onto plane (ZAxis, Origin)
gp_Vec refOrgV = gp_Vec(refOrg.XYZ());
gp_Vec OriginV = gp_Vec(Origin.XYZ());
gp_Vec ZAxisV = gp_Vec(ZAxis);
Origin = gp_Pnt((
refOrgV + ZAxisV*ZAxisV.Dot(OriginV-refOrgV)
).XYZ());
}
if (XAxis.Magnitude() < Precision::Confusion())
makeYVertical = true;
gp_Ax3 ax3;//OCC representation of the final placement
if (!makeYVertical) {
ax3 = gp_Ax3(Origin, ZAxis, XAxis);
} else if (makeYVertical && !makeLegacyFlatFaceOrientation) {
//align Y along Z, if possible
gp_Vec YAxis(0.0,0.0,1.0);
XAxis = YAxis.Crossed(gp_Vec(ZAxis));
if (XAxis.Magnitude() < Precision::Confusion()){
//ZAxis is along true ZAxis
XAxis = (gp_Vec(1,0,0)*ZAxis.Z()).Normalized();
}
ax3 = gp_Ax3(Origin, ZAxis, XAxis);
} else if (makeLegacyFlatFaceOrientation) {
//find out, to which axis of support Normal is closest to.
//The result will be written into pos variable (0..2 = X..Z)
if (!placeOfRef)
throw Base::Exception("AttachEngine::placementFactory: for Legacy mode, placement of the reference must be supplied. Got null instead!");
Base::Placement &Place = *placeOfRef;
Base::Vector3d dX,dY,dZ;//internal axes of support object, as they are in global space
Place.getRotation().multVec(Base::Vector3d(1,0,0),dX);
Place.getRotation().multVec(Base::Vector3d(0,1,0),dY);
Place.getRotation().multVec(Base::Vector3d(0,0,1),dZ);
gp_Dir dirX(dX.x, dX.y, dX.z);
gp_Dir dirY(dY.x, dY.y, dY.z);
gp_Dir dirZ(dZ.x, dZ.y, dZ.z);
double cosNX = ZAxis.Dot(dirX);
double cosNY = ZAxis.Dot(dirY);
double cosNZ = ZAxis.Dot(dirZ);
std::vector<double> cosXYZ;
cosXYZ.push_back(fabs(cosNX));
cosXYZ.push_back(fabs(cosNY));
cosXYZ.push_back(fabs(cosNZ));
int pos = std::max_element(cosXYZ.begin(), cosXYZ.end()) - cosXYZ.begin();
// +X/-X
if (pos == 0) {
if (cosNX > 0)
ax3 = gp_Ax3(Origin, ZAxis, dirY);
else
ax3 = gp_Ax3(Origin, ZAxis, -dirY);
}
// +Y/-Y
else if (pos == 1) {
if (cosNY > 0)
ax3 = gp_Ax3(Origin, ZAxis, -dirX);
else
ax3 = gp_Ax3(Origin, ZAxis, dirX);
}
// +Z/-Z
else {
ax3 = gp_Ax3(Origin, ZAxis, dirX);
}
}
if(this->mapReverse){
ax3.ZReverse();
ax3.XReverse();
}
//convert ax3 into Base::Placement
gp_Trsf Trf;
Trf.SetTransformation(ax3);
Trf.Invert();
Trf.SetScaleFactor(Standard_Real(1.0));
Base::Matrix4D mtrx;
TopoShape::convertToMatrix(Trf,mtrx);
return Base::Placement(mtrx);
}
void AttachEngine::suggestMapModes(SuggestResult &result) const
{
std::vector<eMapMode> &mlist = result.allApplicableModes;
mlist.clear();
mlist.reserve(mmDummy_NumberOfModes);
std::set<eRefType> &hints = result.nextRefTypeHint;
hints.clear();
std::map<eMapMode,refTypeStringList> &mlist_reachable = result.reachableModes;
mlist_reachable.clear();
result.message = SuggestResult::srLinkBroken;
result.bestFitMode = mmDeactivated;
std::vector<App::GeoFeature*> parts;
std::vector<const TopoDS_Shape*> shapes;
std::vector<TopoDS_Shape> shapeStorage;
std::vector<eRefType> typeStr;
try{
readLinks(this->references, parts, shapes, shapeStorage, typeStr);
} catch (Base::Exception &err) {
result.references_Types = typeStr;
result.message = SuggestResult::srLinkBroken;
result.error = err;
return;
}
result.references_Types = typeStr;
//search valid modes.
int bestMatchScore = -1;
result.message = SuggestResult::srNoModesFit;
for (std::size_t iMode = 0; iMode < this->modeRefTypes.size(); ++iMode) {
if (! this->modeEnabled[iMode])
continue;
const refTypeStringList &listStrings = modeRefTypes[iMode];
for (std::size_t iStr = 0; iStr < listStrings.size(); ++iStr) {
int score = 1; //-1 = topo incompatible, 0 = topo compatible, geom incompatible; 1+ = compatible (the higher - the more specific is the mode for the support)
const refTypeString &str = listStrings[iStr];
for (std::size_t iChr = 0; iChr < str.size() && iChr < typeStr.size(); ++iChr) {
int match = AttachEngine::isShapeOfType(typeStr[iChr], str[iChr]);
switch(match){
case -1:
score = -1;
break;
case 0:
score = 0;
break;
case 1:
//keep score
break;
default: //2 and above
if (score > 0)
score += match;
break;
}
}
if (score > 0 && str.size() > typeStr.size()){
//mode does not fit, but adding more references will make this mode fit.
hints.insert(str[typeStr.size()]);
//build string of references to be added to fit this mode
refTypeString extraRefs;
extraRefs.resize(str.size() - typeStr.size());
for (std::size_t iChr = typeStr.size(); iChr < str.size(); iChr++) {
extraRefs[iChr - typeStr.size()] = str[iChr];
}
//add reachable mode
auto it_r = mlist_reachable.find(eMapMode(iMode));
if (it_r == mlist_reachable.end()){
it_r = mlist_reachable.insert(std::pair<eMapMode,refTypeStringList>(eMapMode(iMode),refTypeStringList())).first;
}
refTypeStringList &list = it_r->second;
list.push_back(extraRefs);
}
//size check is last, because we needed to collect hints
if (str.size() != typeStr.size())
score = -1;
if (score > -1){//still output a best match, even if it is not completely compatible
if (score > bestMatchScore){
bestMatchScore = score;
result.bestFitMode = eMapMode(iMode);
result.message = score > 0 ? SuggestResult::srOK : SuggestResult::srIncompatibleGeometry;
}
}
if (score > 0){
if(mlist.size() == 0)
mlist.push_back(eMapMode(iMode));
else if (mlist.back() != eMapMode(iMode))
mlist.push_back(eMapMode(iMode));
}
}
}
}
void AttachEngine::EnableAllSupportedModes()
{
this->modeEnabled.resize(mmDummy_NumberOfModes,false);
assert(modeRefTypes.size() > 0);
for (std::size_t i = 0; i < this->modeEnabled.size(); i++) {
modeEnabled[i] = modeRefTypes[i].size() > 0;
}
}
eRefType AttachEngine::getShapeType(const TopoDS_Shape& sh)
{
if(sh.IsNull())
return rtAnything;
switch (sh.ShapeType()){
case TopAbs_SHAPE:
return rtAnything; //note: there's no rtPart detection here - not enough data!
break;
case TopAbs_SOLID:
return rtSolid;
break;
case TopAbs_COMPOUND:{
const TopoDS_Compound &cmpd = TopoDS::Compound(sh);
TopoDS_Iterator it (cmpd, Standard_False, Standard_False);//don't mess with placements, to hopefully increase speed
if (! it.More()) return rtAnything;//empty compound
const TopoDS_Shape &sh1 = it.Value();
it.Next();
if (it.More()){
//more than one object, a true compound
return rtAnything;
} else {
//just one object, let's take a look inside
return getShapeType(sh1);
}
}break;
case TopAbs_COMPSOLID:
case TopAbs_SHELL:
return rtAnything;
break;
case TopAbs_FACE:{
const TopoDS_Face &f = TopoDS::Face(sh);
BRepAdaptor_Surface surf(f, /*restriction=*/Standard_False);
switch(surf.GetType()) {
case GeomAbs_Plane:
return rtFlatFace;
case GeomAbs_Cylinder:
return rtCylindricalFace;
case GeomAbs_Cone:
return rtConicalFace;
case GeomAbs_Sphere:
return rtSphericalFace;
case GeomAbs_Torus:
return rtToroidalFace;
case GeomAbs_BezierSurface:
break;
case GeomAbs_BSplineSurface:
break;
case GeomAbs_SurfaceOfRevolution:
return rtSurfaceRev;
case GeomAbs_SurfaceOfExtrusion:
break;
case GeomAbs_OffsetSurface:
break;
case GeomAbs_OtherSurface:
break;
}
return rtFace;
}break;
case TopAbs_EDGE:{
const TopoDS_Edge &e = TopoDS::Edge(sh);
BRepAdaptor_Curve crv(e);
switch (crv.GetType()){
case GeomAbs_Line:
return rtLine;
case GeomAbs_Circle:
return rtCircle;
case GeomAbs_Ellipse:
return rtEllipse;
case GeomAbs_Hyperbola:
return rtHyperbola;
case GeomAbs_Parabola:
return rtParabola;
case GeomAbs_BezierCurve:
case GeomAbs_BSplineCurve:
case GeomAbs_OtherCurve:
#if OCC_VERSION_HEX >= 0x070000
case GeomAbs_OffsetCurve:
#endif
return rtCurve;
}
}break;
case TopAbs_WIRE:
return rtWire;
case TopAbs_VERTEX:
return rtVertex;
default:
throw Base::Exception("AttachEngine::getShapeType: unexpected TopoDS_Shape::ShapeType");
}//switch shapetype
return rtAnything;//shouldn't happen, it's here to shut up compiler warning
}
eRefType AttachEngine::getShapeType(const App::DocumentObject *obj, const std::string &subshape)
{
App::PropertyLinkSubList tmpLink;
//const_cast is worth here, to keep obj argument const. We are not going to write anything to obj through this temporary link.
tmpLink.setValue(const_cast<App::DocumentObject*>(obj), subshape.c_str());
std::vector<App::GeoFeature*> parts;
std::vector<const TopoDS_Shape*> shapes;
std::vector<TopoDS_Shape> copiedShapeStorage;
std::vector<eRefType> types;
readLinks(tmpLink, parts, shapes, copiedShapeStorage, types);
assert(types.size() == 1);
return types[0];
}
eRefType AttachEngine::downgradeType(eRefType type)
{
//get rid of hasplacement flags, to simplify the rest
type = eRefType(type & (rtFlagHasPlacement - 1));
//FIXME: reintroduce the flag when returning a value.
switch(type){
case rtVertex:
case rtEdge:
case rtFace:
return rtAnything;
case rtAnything:
return rtAnything;
case rtLine:
case rtCurve:
return rtEdge;
case rtConic:
case rtCircle:
return rtCurve;
case rtEllipse:
case rtParabola:
case rtHyperbola:
return rtConic;
case rtFlatFace:
case rtSphericalFace:
case rtSurfaceRev:
return rtFace;
case rtCylindricalFace:
case rtToroidalFace:
case rtConicalFace:
return rtSurfaceRev;
case rtSolid:
case rtWire:
return rtPart;
case rtPart:
return rtAnything;
default:
throw Base::Exception("AttachEngine::downgradeType: unknown type");
}
}
int AttachEngine::getTypeRank(eRefType type)
{
//get rid of hasplacement flags, to simplify the rest
type = eRefType(type & (rtFlagHasPlacement - 1));
int rank = 0;
while (type != rtAnything) {
type = downgradeType(type);
rank++;
assert(rank<8);//downgrading never yields rtAnything, something's wrong with downgrader.
}
return rank;
}
int AttachEngine::isShapeOfType(eRefType shapeType, eRefType requirement)
{
//first up, check for hasplacement flag
if (requirement & rtFlagHasPlacement) {
if(! (shapeType & rtFlagHasPlacement))
return -1;
}
//get rid of hasplacement flags, to simplify the rest
shapeType = eRefType(shapeType & (rtFlagHasPlacement - 1));
requirement = eRefType(requirement & (rtFlagHasPlacement - 1));
if (requirement == rtAnything)
return 1;
int reqRank = getTypeRank(requirement);
//test for valid match
eRefType shDeg = shapeType;
while(shDeg != rtAnything){
if (shDeg == requirement)
return reqRank;
shDeg = downgradeType(shDeg);
}
//test for slightly invalid match (e.g. requirement==line, shapeType == curve)
requirement = downgradeType(requirement);
if (requirement != rtAnything) {
eRefType shDeg = shapeType;
while(shDeg != rtAnything){
if (shDeg == requirement)
return 0;
shDeg = downgradeType(shDeg);
}
}
//complete mismatch!
return -1;
}
std::string AttachEngine::getModeName(eMapMode mmode)
{
if(mmode < 0 || mmode >= mmDummy_NumberOfModes)
throw Base::Exception("AttachEngine::getModeName: Attachment Mode index is out of range");
return std::string(AttachEngine::eMapModeStrings[mmode]);
}
eMapMode AttachEngine::getModeByName(const std::string &modeName)
{
for (int mmode = 0 ; mmode < mmDummy_NumberOfModes ; mmode++){
if (strcmp(eMapModeStrings[mmode],modeName.c_str())==0) {
return eMapMode(mmode);
}
}
std::stringstream errMsg;
errMsg << "AttachEngine::getModeByName: mode with this name doesn't exist: " << modeName;
throw Base::Exception(errMsg.str());
}
std::string AttachEngine::getRefTypeName(eRefType shapeType)
{
eRefType flagless = eRefType(shapeType & 0xFF);
if(flagless < 0 || flagless >= rtDummy_numberOfShapeTypes)
throw Base::Exception("eRefType value is out of range");
std::string result = std::string(eRefTypeStrings[flagless]);
if (shapeType & rtFlagHasPlacement){
result.append("|Placement");
}
return result;
}
eRefType AttachEngine::getRefTypeByName(const std::string& typeName)
{
std::string flagless;
std::string flags;
size_t seppos = typeName.find('|');
flagless = typeName.substr(0, seppos);
if(seppos != std::string::npos ){
flags = typeName.substr(seppos+1);
}
for(int irt = 0 ; irt < rtDummy_numberOfShapeTypes ; irt++){
if(strcmp(flagless.c_str(),eRefTypeStrings[irt]) == 0){
if(strcmp("Placement",flags.c_str()) == 0){
return eRefType(irt | rtFlagHasPlacement);
} else if (flags.length() == 0){
return eRefType(irt);
} else {
std::stringstream errmsg;
errmsg << "RefType flag not recognized: " << flags;
throw Base::Exception(errmsg.str());
}
}
}
std::stringstream errmsg;
errmsg << "RefType not recognized: " << typeName;
throw Base::Exception(errmsg.str());
}
GProp_GProps AttachEngine::getInertialPropsOfShape(const std::vector<const TopoDS_Shape*> &shapes)
{
//explode compounds
TopTools_HSequenceOfShape totalSeq;
for (const TopoDS_Shape* pSh: shapes){
ShapeExtend_Explorer xp;
totalSeq.Append( xp.SeqFromCompound(*pSh, /*recursive=*/true));
}
if (totalSeq.Length() == 0)
throw Base::Exception("AttachEngine::getInertialPropsOfShape: no geometry provided");
const TopoDS_Shape &sh0 = totalSeq.Value(1);
switch (sh0.ShapeType()){
case TopAbs_VERTEX:{
GProp_PGProps gpr;
for (int i = 0 ; i < totalSeq.Length() ; i++){
const TopoDS_Shape &sh = totalSeq.Value(i+1);
if (sh.ShapeType() != TopAbs_VERTEX)
throw Base::Exception("AttachEngine::getInertialPropsOfShape: provided shapes are incompatible (not only vertices)");
gpr.AddPoint(BRep_Tool::Pnt(TopoDS::Vertex(sh)));
}
return gpr;
} break;
case TopAbs_EDGE:
case TopAbs_WIRE:{
GProp_GProps gpr_acc;
GProp_GProps gpr;
for (int i = 0 ; i < totalSeq.Length() ; i++){
const TopoDS_Shape &sh = totalSeq.Value(i+1);
if (sh.ShapeType() != TopAbs_EDGE && sh.ShapeType() != TopAbs_WIRE)
throw Base::Exception("AttachEngine::getInertialPropsOfShape: provided shapes are incompatible (not only edges/wires)");
if (sh.Infinite())
throw Base::Exception("AttachEngine::getInertialPropsOfShape: infinite shape provided");
BRepGProp::LinearProperties(sh,gpr);
gpr_acc.Add(gpr);
}
return gpr_acc;
} break;
case TopAbs_FACE:
case TopAbs_SHELL:{
GProp_GProps gpr_acc;
GProp_GProps gpr;
for (int i = 0 ; i < totalSeq.Length() ; i++){
const TopoDS_Shape &sh = totalSeq.Value(i+1);
if (sh.ShapeType() != TopAbs_FACE && sh.ShapeType() != TopAbs_SHELL)
throw Base::Exception("AttachEngine::getInertialPropsOfShape: provided shapes are incompatible (not only faces/shells)");
if (sh.Infinite())
throw Base::Exception("AttachEngine::getInertialPropsOfShape: infinite shape provided");
BRepGProp::SurfaceProperties(sh,gpr);
gpr_acc.Add(gpr);
}
return gpr_acc;
} break;
case TopAbs_SOLID:
case TopAbs_COMPSOLID:{
GProp_GProps gpr_acc;
GProp_GProps gpr;
for (int i = 0 ; i < totalSeq.Length() ; i++){
const TopoDS_Shape &sh = totalSeq.Value(i+1);
if (sh.ShapeType() != TopAbs_SOLID && sh.ShapeType() != TopAbs_COMPSOLID)
throw Base::Exception("AttachEngine::getInertialPropsOfShape: provided shapes are incompatible (not only solids/compsolids)");
if (sh.Infinite())
throw Base::Exception("AttachEngine::getInertialPropsOfShape: infinite shape provided");
BRepGProp::VolumeProperties(sh,gpr);
gpr_acc.Add(gpr);
}
return gpr_acc;
} break;
default:
throw Base::Exception("AttachEngine::getInertialPropsOfShape: unexpected shape type");
}
}
/*!
* \brief AttachEngine3D::readLinks
* \param parts
* \param shapes
* \param storage is a buffer storing what some of the pointers in shapes point to. It is needed, since
* subshapes are copied in the process (but copying a whole shape of an object can potentially be slow).
*/
void AttachEngine::readLinks(const App::PropertyLinkSubList &references,
std::vector<App::GeoFeature*> &geofs,
std::vector<const TopoDS_Shape*> &shapes,
std::vector<TopoDS_Shape> &storage,
std::vector<eRefType> &types)
{
verifyReferencesAreSafe(references);
const std::vector<App::DocumentObject*> &objs = references.getValues();
const std::vector<std::string> &sub = references.getSubValues();
geofs.resize(objs.size());
storage.reserve(objs.size());
shapes.resize(objs.size());
types.resize(objs.size());
for (std::size_t i = 0; i < objs.size(); i++) {
if (!objs[i]->getTypeId().isDerivedFrom(App::GeoFeature::getClassTypeId())) {
throw Base::Exception("AttachEngine3D: link points to something that is not App::GeoFeature");
}
App::GeoFeature* geof = static_cast<App::GeoFeature*>(objs[i]);
geofs[i] = geof;
const Part::TopoShape* shape;
if (geof->isDerivedFrom(Part::Feature::getClassTypeId())){
shape = &(static_cast<Part::Feature*>(geof)->Shape.getShape());
if (shape->isNull()){
throw Base::Exception("AttachEngine3D: Part has null shape");
}
if (sub[i].length()>0){
try{
storage.push_back(shape->getSubShape(sub[i].c_str()));
} catch (Standard_Failure){
throw Base::Exception("AttachEngine3D: subshape not found");
}
if(storage[storage.size()-1].IsNull())
throw Base::Exception("AttachEngine3D: null subshape");
shapes[i] = &(storage[storage.size()-1]);
} else {
shapes[i] = &(shape->getShape());
}
} else if ( geof->isDerivedFrom(App::Plane::getClassTypeId()) ){
//obtain Z axis and origin of placement
Base::Vector3d norm;
geof->Placement.getValue().getRotation().multVec(Base::Vector3d(0.0,0.0,1.0),norm);
Base::Vector3d org;
geof->Placement.getValue().multVec(Base::Vector3d(),org);
//make shape - an local-XY plane infinite face
gp_Pln pl = gp_Pln(gp_Pnt(org.x, org.y, org.z), gp_Dir(norm.x, norm.y, norm.z));
BRepBuilderAPI_MakeFace builder(pl);
storage.push_back( builder.Shape() );
shapes[i] = &(storage[storage.size()-1]);
} else if ( geof->isDerivedFrom(App::Line::getClassTypeId()) ){
//obtain X axis and origin of placement
//note an inconsistency: App::Line is along local X, PartDesign::DatumLine is along local Z.
Base::Vector3d dir;
geof->Placement.getValue().getRotation().multVec(Base::Vector3d(1.0,0.0,0.0),dir);
Base::Vector3d org;
geof->Placement.getValue().multVec(Base::Vector3d(),org);
//make shape - an infinite line along local X axis
gp_Lin l = gp_Lin(gp_Pnt(org.x, org.y, org.z), gp_Dir(dir.x, dir.y, dir.z));
BRepBuilderAPI_MakeEdge builder(l);
storage.push_back( builder.Shape() );
shapes[i] = &(storage[storage.size()-1]);
} else {
Base::Console().Warning("Attacher: linked object %s is unexpected, assuming it has no shape.\n",geof->getNameInDocument());
storage.push_back(TopoDS_Shape());
shapes[i] = &(storage[storage.size()-1]);
}
//FIXME: unpack single-child compounds here? Compounds are not used so far, so it should be considered later, when the need arises.
types[i] = getShapeType(*(shapes[i]));
if (sub[i].length() == 0)
types[i] = eRefType(types[i] | rtFlagHasPlacement);
}
}
void AttachEngine::throwWrongMode(eMapMode mmode)
{
std::stringstream errmsg;
if (mmode >= 0 && mmode<mmDummy_NumberOfModes) {
if (AttachEngine::eMapModeStrings[mmode]) {
errmsg << "Attachment mode " << AttachEngine::eMapModeStrings[mmode] << " is not implemented." ;
} else {
errmsg << "Attachment mode " << int(mmode) << " is undefined." ;
}
} else {
errmsg << "Attachment mode index (" << int(mmode) << ") is out of range." ;
}
throw Base::ValueError(errmsg.str().c_str());
}
void AttachEngine::verifyReferencesAreSafe(const App::PropertyLinkSubList &references)
{
const std::vector<App::DocumentObject*> links = references.getValues();
const std::vector<App::Document*> docs = App::GetApplication().getDocuments();
for(App::DocumentObject* lnk : links){
bool found = false;
for(App::Document* doc : docs){
if(doc->isIn(lnk)){
found = true;
}
}
if (!found){
throw Base::Exception("AttachEngine: verifyReferencesAreSafe: references point to deleted object.");
}
}
}
//=================================================================================
TYPESYSTEM_SOURCE(Attacher::AttachEngine3D, Attacher::AttachEngine);
AttachEngine3D::AttachEngine3D()
{
//fill type lists for modes
modeRefTypes.resize(mmDummy_NumberOfModes);
refTypeString s;
refTypeStringList ss;
modeRefTypes[mmTranslate].push_back(cat(rtVertex));
ss.clear();
ss.push_back(cat(eRefType(rtAnything | rtFlagHasPlacement)));
ss.push_back(cat(rtConic));
modeRefTypes[mmObjectXY] = ss;
modeRefTypes[mmObjectXZ] = ss;
modeRefTypes[mmObjectYZ] = ss;
modeRefTypes[mmInertialCS].push_back(cat(rtAnything));
modeRefTypes[mmInertialCS].push_back(cat(rtAnything,rtAnything));
modeRefTypes[mmInertialCS].push_back(cat(rtAnything,rtAnything,rtAnything));
modeRefTypes[mmInertialCS].push_back(cat(rtAnything,rtAnything,rtAnything,rtAnything));
modeRefTypes[mmFlatFace].push_back(cat(rtFlatFace));
modeRefTypes[mmTangentPlane].push_back(cat(rtFace, rtVertex));
modeRefTypes[mmTangentPlane].push_back(cat(rtVertex, rtFace));
//---------Edge-driven
s=cat(rtEdge);
modeRefTypes[mmNormalToPath].push_back(s);
s = cat(rtCurve);
modeRefTypes[mmFrenetNB].push_back(s);
modeRefTypes[mmFrenetTN].push_back(s);
modeRefTypes[mmFrenetTB].push_back(s);
modeRefTypes[mmRevolutionSection].push_back(s);
modeRefTypes[mmConcentric].push_back(s);
s = cat(rtCircle);
modeRefTypes[mmRevolutionSection].push_back(s);//for this mode to get best score on circles
modeRefTypes[mmConcentric].push_back(s);
//-----------Edge-driven at vertex
s=cat(rtEdge, rtVertex);
modeRefTypes[mmNormalToPath].push_back(s);
s=cat(rtVertex, rtEdge);
modeRefTypes[mmNormalToPath].push_back(s);
s=cat(rtCurve, rtVertex);
modeRefTypes[mmFrenetNB].push_back(s);
modeRefTypes[mmFrenetTN].push_back(s);
modeRefTypes[mmFrenetTB].push_back(s);
modeRefTypes[mmRevolutionSection].push_back(s);
modeRefTypes[mmConcentric].push_back(s);
s = cat(rtCircle, rtVertex);
modeRefTypes[mmRevolutionSection].push_back(s);//for this mode to get best score on circles
modeRefTypes[mmConcentric].push_back(s);
s=cat(rtVertex, rtCurve);
modeRefTypes[mmFrenetNB].push_back(s);
modeRefTypes[mmFrenetTN].push_back(s);
modeRefTypes[mmFrenetTB].push_back(s);
modeRefTypes[mmRevolutionSection].push_back(s);
modeRefTypes[mmConcentric].push_back(s);
s = cat(rtVertex, rtCircle);
modeRefTypes[mmRevolutionSection].push_back(s);//for this mode to get best score on circles
modeRefTypes[mmConcentric].push_back(s);
//------------ThreePoints
s = cat(rtVertex, rtVertex, rtVertex);
modeRefTypes[mmThreePointsPlane].push_back(s);
modeRefTypes[mmThreePointsNormal].push_back(s);
s = cat(rtLine, rtVertex);
modeRefTypes[mmThreePointsPlane].push_back(s);
modeRefTypes[mmThreePointsNormal].push_back(s);
s = cat(rtVertex, rtLine);
modeRefTypes[mmThreePointsPlane].push_back(s);
modeRefTypes[mmThreePointsNormal].push_back(s);
s = cat(rtLine, rtLine);
modeRefTypes[mmThreePointsPlane].push_back(s);
modeRefTypes[mmThreePointsNormal].push_back(s);
//------------origin-axis-axis modes
for (int mmode = mmOZX; mmode <= mmOYX; ++mmode){
modeRefTypes[mmode].push_back(cat(rtVertex, rtVertex, rtVertex));
modeRefTypes[mmode].push_back(cat(rtVertex, rtVertex, rtLine));
modeRefTypes[mmode].push_back(cat(rtVertex, rtLine, rtVertex));
modeRefTypes[mmode].push_back(cat(rtVertex, rtLine, rtLine));
modeRefTypes[mmode].push_back(cat(rtVertex, rtVertex));
modeRefTypes[mmode].push_back(cat(rtVertex, rtLine));
}
modeRefTypes[mmFolding].push_back(cat(rtLine, rtLine, rtLine, rtLine));
this->EnableAllSupportedModes();
}
AttachEngine3D* AttachEngine3D::copy() const
{
AttachEngine3D* p = new AttachEngine3D;
p->setUp(*this);
return p;
}
Base::Placement AttachEngine3D::calculateAttachedPlacement(Base::Placement origPlacement) const
{
const eMapMode mmode = this->mapMode;
if (mmode == mmDeactivated)
throw ExceptionCancel();//to be handled in positionBySupport, to not do anything if disabled
std::vector<App::GeoFeature*> parts;
std::vector<const TopoDS_Shape*> shapes;
std::vector<TopoDS_Shape> copiedShapeStorage;
std::vector<eRefType> types;
readLinks(this->references, parts, shapes, copiedShapeStorage, types);
if (parts.size() == 0)
throw ExceptionCancel();
//common stuff for all map modes
gp_Pnt refOrg (0.0,0.0,0.0);//origin of linked object
Base::Placement Place = parts[0]->Placement.getValue();
refOrg = gp_Pnt(Place.getPosition().x, Place.getPosition().y, Place.getPosition().z);
//variables to derive the actual placement.
//They are to be set, depending on the mode:
//to the sketch
gp_Dir SketchNormal;//points at the user