/
AppPartPy.cpp
2395 lines (2213 loc) · 97.8 KB
/
AppPartPy.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) 2002 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 <BRep_Builder.hxx>
# include <BRep_Tool.hxx>
# include <BRepAdaptor_Curve.hxx>
# include <BRepBuilderAPI_MakeEdge.hxx>
# include <BRepBuilderAPI_MakeFace.hxx>
# include <BRepBuilderAPI_MakePolygon.hxx>
# include <BRepBuilderAPI_MakeSolid.hxx>
# include <BRepCheck_Analyzer.hxx>
# include <BRepFeat_SplitShape.hxx>
# include <BRepOffsetAPI_Sewing.hxx>
# include <BRepPrim_Wedge.hxx>
# include <BRepPrimAPI_MakeBox.hxx>
# include <BRepPrimAPI_MakeCone.hxx>
# include <BRepPrimAPI_MakeCylinder.hxx>
# include <BRepPrimAPI_MakeRevolution.hxx>
# include <BRepPrimAPI_MakeSphere.hxx>
# include <BRepPrimAPI_MakeTorus.hxx>
# include <BRepFill.hxx>
# include <BRepFill_Filling.hxx>
# include <BRepLib.hxx>
# include <BSplCLib.hxx>
# include <gp_Ax3.hxx>
# include <gp_Circ.hxx>
# include <gp_Pnt.hxx>
# include <Geom_BSplineSurface.hxx>
# include <Geom_Circle.hxx>
# include <Geom_Plane.hxx>
# include <GeomFill_AppSurf.hxx>
# include <GeomFill_Generator.hxx>
# include <GeomFill_Line.hxx>
# include <GeomFill_SectionGenerator.hxx>
# include <Interface_Static.hxx>
# include <NCollection_List.hxx>
# include <Precision.hxx>
# include <ShapeFix.hxx>
# include <ShapeBuild_ReShape.hxx>
# include <ShapeUpgrade_ShellSewing.hxx>
# include <Standard_DomainError.hxx>
# include <Standard_Version.hxx>
# include <TopExp_Explorer.hxx>
# include <TopoDS_Compound.hxx>
# include <TopoDS_Edge.hxx>
# include <TopoDS_Face.hxx>
# include <TopoDS_Shell.hxx>
# include <TopoDS_Solid.hxx>
# include <TopTools_ListIteratorOfListOfShape.hxx>
#endif
# include <BRepFill_Generator.hxx>
#include <App/Application.h>
#include <App/Document.h>
#include <App/DocumentObjectPy.h>
#include <Base/Console.h>
#include <Base/Exception.h>
#include <Base/FileInfo.h>
#include <Base/GeometryPyCXX.h>
#include <Base/Interpreter.h>
#include <Base/VectorPy.h>
#include "BSplineSurfacePy.h"
#include "edgecluster.h"
#include "FaceMaker.h"
#include "GeometryCurvePy.h"
#include "GeometryPy.h"
#include "ImportIges.h"
#include "ImportStep.h"
#include "Interface.h"
#include "modelRefine.h"
#include "OCCError.h"
#include "PartFeature.h"
#include "PartPyCXX.h"
#include "Tools.h"
#include "TopoShapeCompoundPy.h"
#include "TopoShapePy.h"
#include "TopoShapeEdgePy.h"
#include "TopoShapeFacePy.h"
#include "TopoShapeShellPy.h"
#include "TopoShapeSolidPy.h"
#include "TopoShapeWirePy.h"
#ifdef FCUseFreeType
# include "FT2FC.h"
#endif
extern const char* BRepBuilderAPI_FaceErrorText(BRepBuilderAPI_FaceError fe);
#ifndef M_PI
#define M_PI 3.14159265358979323846 /* pi */
#endif
#ifndef M_PI_2
#define M_PI_2 1.57079632679489661923 /* pi/2 */
#endif
namespace Part {
PartExport void getPyShapes(PyObject *obj, std::vector<TopoShape> &shapes) {
if(!obj)
return;
if(PyObject_TypeCheck(obj,&Part::TopoShapePy::Type))
shapes.push_back(*static_cast<TopoShapePy*>(obj)->getTopoShapePtr());
else if (PyObject_TypeCheck(obj, &GeometryPy::Type))
shapes.emplace_back(static_cast<GeometryPy*>(obj)->getGeometryPtr()->toShape());
else if(PySequence_Check(obj)) {
Py::Sequence list(obj);
for (Py::Sequence::iterator it = list.begin(); it != list.end(); ++it) {
if (PyObject_TypeCheck((*it).ptr(), &(Part::TopoShapePy::Type)))
shapes.push_back(*static_cast<TopoShapePy*>((*it).ptr())->getTopoShapePtr());
else if (PyObject_TypeCheck((*it).ptr(), &GeometryPy::Type))
shapes.emplace_back(static_cast<GeometryPy*>(
(*it).ptr())->getGeometryPtr()->toShape());
else
throw Py::TypeError("expect shape in sequence");
}
}else
throw Py::TypeError("expect shape or sequence of shapes");
}
PartExport std::vector<TopoShape> getPyShapes(PyObject *obj) {
std::vector<TopoShape> ret;
getPyShapes(obj,ret);
return ret;
}
struct EdgePoints {
gp_Pnt v1, v2;
std::list<TopoDS_Edge>::iterator it;
TopoDS_Edge edge;
};
PartExport std::list<TopoDS_Edge> sort_Edges(double tol3d, std::list<TopoDS_Edge>& edges)
{
tol3d = tol3d * tol3d;
std::list<EdgePoints> edge_points;
TopExp_Explorer xp;
for (std::list<TopoDS_Edge>::iterator it = edges.begin(); it != edges.end(); ++it) {
EdgePoints ep;
xp.Init(*it,TopAbs_VERTEX);
ep.v1 = BRep_Tool::Pnt(TopoDS::Vertex(xp.Current()));
xp.Next();
ep.v2 = BRep_Tool::Pnt(TopoDS::Vertex(xp.Current()));
ep.it = it;
ep.edge = *it;
edge_points.push_back(ep);
}
if (edge_points.empty())
return std::list<TopoDS_Edge>();
std::list<TopoDS_Edge> sorted;
gp_Pnt first, last;
first = edge_points.front().v1;
last = edge_points.front().v2;
sorted.push_back(edge_points.front().edge);
edges.erase(edge_points.front().it);
edge_points.erase(edge_points.begin());
while (!edge_points.empty()) {
// search for adjacent edge
std::list<EdgePoints>::iterator pEI;
for (pEI = edge_points.begin(); pEI != edge_points.end(); ++pEI) {
if (pEI->v1.SquareDistance(last) <= tol3d) {
last = pEI->v2;
sorted.push_back(pEI->edge);
edges.erase(pEI->it);
edge_points.erase(pEI);
pEI = edge_points.begin();
break;
}
else if (pEI->v2.SquareDistance(first) <= tol3d) {
first = pEI->v1;
sorted.push_front(pEI->edge);
edges.erase(pEI->it);
edge_points.erase(pEI);
pEI = edge_points.begin();
break;
}
else if (pEI->v2.SquareDistance(last) <= tol3d) {
last = pEI->v1;
Standard_Real first, last;
const Handle(Geom_Curve) & curve = BRep_Tool::Curve(pEI->edge, first, last);
first = curve->ReversedParameter(first);
last = curve->ReversedParameter(last);
TopoDS_Edge edgeReversed = BRepBuilderAPI_MakeEdge(curve->Reversed(), last, first);
sorted.push_back(edgeReversed);
edges.erase(pEI->it);
edge_points.erase(pEI);
pEI = edge_points.begin();
break;
}
else if (pEI->v1.SquareDistance(first) <= tol3d) {
first = pEI->v2;
Standard_Real first, last;
const Handle(Geom_Curve) & curve = BRep_Tool::Curve(pEI->edge, first, last);
first = curve->ReversedParameter(first);
last = curve->ReversedParameter(last);
TopoDS_Edge edgeReversed = BRepBuilderAPI_MakeEdge(curve->Reversed(), last, first);
sorted.push_front(edgeReversed);
edges.erase(pEI->it);
edge_points.erase(pEI);
pEI = edge_points.begin();
break;
}
}
if ((pEI == edge_points.end()) || (last.SquareDistance(first) <= tol3d)) {
// no adjacent edge found or polyline is closed
return sorted;
}
}
return sorted;
}
}
namespace Part {
class BRepFeatModule : public Py::ExtensionModule<BRepFeatModule>
{
public:
BRepFeatModule() : Py::ExtensionModule<BRepFeatModule>("BRepFeat")
{
initialize("This is a module working with the BRepFeat package."); // register with Python
}
~BRepFeatModule() override {}
};
class BRepOffsetAPIModule : public Py::ExtensionModule<BRepOffsetAPIModule>
{
public:
BRepOffsetAPIModule() : Py::ExtensionModule<BRepOffsetAPIModule>("BRepOffsetAPI")
{
initialize("This is a module working with the BRepOffsetAPI package."); // register with Python
}
~BRepOffsetAPIModule() override {}
};
class Geom2dModule : public Py::ExtensionModule<Geom2dModule>
{
public:
Geom2dModule() : Py::ExtensionModule<Geom2dModule>("Geom2d")
{
initialize("This is a module working with 2d geometries."); // register with Python
}
~Geom2dModule() override {}
};
class GeomPlateModule : public Py::ExtensionModule<GeomPlateModule>
{
public:
GeomPlateModule() : Py::ExtensionModule<GeomPlateModule>("GeomPlate")
{
initialize("This is a module working with the GeomPlate framework."); // register with Python
}
~GeomPlateModule() override {}
};
class HLRBRepModule : public Py::ExtensionModule<HLRBRepModule>
{
public:
HLRBRepModule() : Py::ExtensionModule<HLRBRepModule>("HLRBRep")
{
initialize("This is a module working with the HLRBRep framework."); // register with Python
}
~HLRBRepModule() override {}
};
class ShapeFixModule : public Py::ExtensionModule<ShapeFixModule>
{
public:
ShapeFixModule() : Py::ExtensionModule<ShapeFixModule>("ShapeFix")
{
add_varargs_method("sameParameter",&ShapeFixModule::sameParameter,
"sameParameter(shape, enforce, prec=0.0)"
);
add_varargs_method("encodeRegularity",&ShapeFixModule::encodeRegularity,
"encodeRegularity(shape, tolerance = 1e-10)\n"
);
add_varargs_method("removeSmallEdges",&ShapeFixModule::removeSmallEdges,
"removeSmallEdges(shape, tolerance, ReShapeContext)\n"
"Removes edges which are less than given tolerance from shape"
);
add_varargs_method("fixVertexPosition",&ShapeFixModule::fixVertexPosition,
"fixVertexPosition(shape, tolerance, ReShapeContext)\n"
"Fix position of the vertices having tolerance more tnan specified one"
);
add_varargs_method("leastEdgeSize",&ShapeFixModule::leastEdgeSize,
"leastEdgeSize(shape)\n"
"Calculate size of least edge"
);
initialize("This is a module working with the ShapeFix framework."); // register with Python
}
~ShapeFixModule() override {}
private:
Py::Object sameParameter(const Py::Tuple& args)
{
PyObject* shape;
PyObject* enforce;
double prec = 0.0;
if (!PyArg_ParseTuple(args.ptr(), "O!O!|d", &TopoShapePy::Type, &shape, &PyBool_Type, &enforce, &prec))
throw Py::Exception();
TopoDS_Shape sh = static_cast<TopoShapePy*>(shape)->getTopoShapePtr()->getShape();
bool ok = ShapeFix::SameParameter(sh, Base::asBoolean(enforce), prec);
return Py::Boolean(ok);
}
Py::Object encodeRegularity(const Py::Tuple& args)
{
PyObject* shape;
double tolang = 1.0e-10;
if (!PyArg_ParseTuple(args.ptr(), "O!|d", &TopoShapePy::Type, &shape, &tolang))
throw Py::Exception();
TopoDS_Shape sh = static_cast<TopoShapePy*>(shape)->getTopoShapePtr()->getShape();
ShapeFix::EncodeRegularity(sh, tolang);
return Py::None();
}
Py::Object removeSmallEdges(const Py::Tuple& args)
{
PyObject* shape;
double tol;
if (!PyArg_ParseTuple(args.ptr(), "O!d", &TopoShapePy::Type, &shape, &tol))
throw Py::Exception();
TopoDS_Shape sh = static_cast<TopoShapePy*>(shape)->getTopoShapePtr()->getShape();
Handle(ShapeBuild_ReShape) reshape = new ShapeBuild_ReShape();
TopoShape res = ShapeFix::RemoveSmallEdges(sh, tol, reshape);
return Py::asObject(res.getPyObject());
}
Py::Object fixVertexPosition(const Py::Tuple& args)
{
PyObject* shape;
double tol;
if (!PyArg_ParseTuple(args.ptr(), "O!d", &TopoShapePy::Type, &shape, &tol))
throw Py::Exception();
TopoDS_Shape sh = static_cast<TopoShapePy*>(shape)->getTopoShapePtr()->getShape();
Handle(ShapeBuild_ReShape) reshape = new ShapeBuild_ReShape();
bool ok = ShapeFix::FixVertexPosition(sh, tol, reshape);
return Py::Boolean(ok);
}
Py::Object leastEdgeSize(const Py::Tuple& args)
{
PyObject* shape;
if (!PyArg_ParseTuple(args.ptr(), "O!", &TopoShapePy::Type, &shape))
throw Py::Exception();
TopoDS_Shape sh = static_cast<TopoShapePy*>(shape)->getTopoShapePtr()->getShape();
double len = ShapeFix::LeastEdgeSize(sh);
return Py::Float(len);
}
};
class ShapeUpgradeModule : public Py::ExtensionModule<ShapeUpgradeModule>
{
public:
ShapeUpgradeModule() : Py::ExtensionModule<ShapeUpgradeModule>("ShapeUpgrade")
{
initialize("This is a module working with the ShapeUpgrade framework."); // register with Python
}
~ShapeUpgradeModule() override {}
};
class ChFi2dModule : public Py::ExtensionModule<ChFi2dModule>
{
public:
ChFi2dModule() : Py::ExtensionModule<ChFi2dModule>("ChFi2d")
{
initialize("This is a module working with the ChFi2d framework."); // register with Python
}
~ChFi2dModule() override {}
};
class Module : public Py::ExtensionModule<Module>
{
BRepFeatModule brepFeat;
BRepOffsetAPIModule brepOffsetApi;
Geom2dModule geom2d;
GeomPlateModule geomPlate;
HLRBRepModule HLRBRep;
ShapeFixModule shapeFix;
ShapeUpgradeModule shapeUpgrade;
ChFi2dModule chFi2d;
public:
Module() : Py::ExtensionModule<Module>("Part")
{
add_varargs_method("open",&Module::open,
"open(string) -- Create a new document and load the file into the document."
);
add_varargs_method("insert",&Module::insert,
"insert(string,string) -- Insert the file into the given document."
);
add_varargs_method("export",&Module::exporter,
"export(list,string) -- Export a list of objects into a single file."
);
add_varargs_method("read",&Module::read,
"read(string) -- Load the file and return the shape."
);
add_varargs_method("show",&Module::show,
"show(shape,[string]) -- Add the shape to the active document or create one if no document exists."
);
add_varargs_method("getFacets",&Module::getFacets,
"getFacets(shape): simplified mesh generation"
);
add_varargs_method("makeCompound",&Module::makeCompound,
"makeCompound(list) -- Create a compound out of a list of shapes."
);
add_varargs_method("makeShell",&Module::makeShell,
"makeShell(list) -- Create a shell out of a list of faces."
);
add_varargs_method("makeFace",&Module::makeFace,
"makeFace(list_of_shapes_or_compound, maker_class_name) -- Create a face (faces) using facemaker class.\n"
"maker_class_name is a string like 'Part::FaceMakerSimple'."
);
add_varargs_method("makeFilledSurface",&Module::makeFilledSurface,
"makeFilledSurface(list of curves, tolerance) -- Create a surface out of a list of curves."
);
add_varargs_method("makeFilledFace",&Module::makeFilledFace,
"makeFilledFace(list) -- Create a face out of a list of edges."
);
add_varargs_method("makeSolid",&Module::makeSolid,
"makeSolid(shape): Create a solid out of shells of shape. If shape is a compsolid, the overall volume solid is created."
);
add_varargs_method("makePlane",&Module::makePlane,
"makePlane(length,width,[pnt,dirZ,dirX]) -- Make a plane\n"
"By default pnt=Vector(0,0,0) and dirZ=Vector(0,0,1), dirX is ignored in this case"
);
add_varargs_method("makeBox",&Module::makeBox,
"makeBox(length,width,height,[pnt,dir]) -- Make a box located\n"
"in pnt with the dimensions (length,width,height)\n"
"By default pnt=Vector(0,0,0) and dir=Vector(0,0,1)"
);
add_varargs_method("makeWedge",&Module::makeWedge,
"makeWedge(xmin, ymin, zmin, z2min, x2min,\n"
"xmax, ymax, zmax, z2max, x2max,[pnt,dir])\n"
" -- Make a wedge located in pnt\n"
"By default pnt=Vector(0,0,0) and dir=Vector(0,0,1)"
);
add_varargs_method("makeLine",&Module::makeLine,
"makeLine(startpnt,endpnt) -- Make a line between two points\n"
"\n"
"Args:\n"
" startpnt (Vector or tuple): Vector or 3 element tuple \n"
" containing the x,y and z coordinates of the start point,\n"
" i.e. (x1,y1,z1).\n"
" endpnt (Vector or tuple): Vector or 3 element tuple \n"
" containing the x,y and z coordinates of the start point,\n"
" i.e. (x1,y1,z1).\n"
"\n"
"Returns:\n"
" Edge: Part.Edge object\n"
);
add_varargs_method("makePolygon",&Module::makePolygon,
"makePolygon(pntslist) -- Make a polygon from a list of points\n"
"\n"
"Args:\n"
" pntslist (list(Vector)): list of Vectors representing the \n"
" points of the polygon.\n"
"\n"
"Returns:\n"
" Wire: Part.Wire object. If the last point in the list is \n"
" not the same as the first point, the Wire will not be \n"
" closed and cannot be used to create a face.\n"
);
add_varargs_method("makeCircle",&Module::makeCircle,
"makeCircle(radius,[pnt,dir,angle1,angle2]) -- Make a circle with a given radius\n"
"By default pnt=Vector(0,0,0), dir=Vector(0,0,1), angle1=0 and angle2=360"
);
add_varargs_method("makeSphere",&Module::makeSphere,
"makeSphere(radius,[pnt, dir, angle1,angle2,angle3]) -- Make a sphere with a given radius\n"
"By default pnt=Vector(0,0,0), dir=Vector(0,0,1), angle1=0, angle2=90 and angle3=360"
);
add_varargs_method("makeCylinder",&Module::makeCylinder,
"makeCylinder(radius,height,[pnt,dir,angle]) -- Make a cylinder with a given radius and height\n"
"By default pnt=Vector(0,0,0),dir=Vector(0,0,1) and angle=360"
);
add_varargs_method("makeCone",&Module::makeCone,
"makeCone(radius1,radius2,height,[pnt,dir,angle]) -- Make a cone with given radii and height\n"
"By default pnt=Vector(0,0,0), dir=Vector(0,0,1) and angle=360"
);
add_varargs_method("makeTorus",&Module::makeTorus,
"makeTorus(radius1,radius2,[pnt,dir,angle1,angle2,angle]) -- Make a torus with a given radii and angles\n"
"By default pnt=Vector(0,0,0),dir=Vector(0,0,1),angle1=0,angle1=360 and angle=360"
);
add_varargs_method("makeHelix",&Module::makeHelix,
"makeHelix(pitch,height,radius,[angle]) -- Make a helix with a given pitch, height and radius\n"
"By default a cylindrical surface is used to create the helix. If the fourth parameter is set\n"
"(the apex given in degree) a conical surface is used instead"
);
add_varargs_method("makeLongHelix",&Module::makeLongHelix,
"makeLongHelix(pitch,height,radius,[angle],[hand]) -- Make a (multi-edge) helix with a given pitch, height and radius\n"
"By default a cylindrical surface is used to create the helix. If the fourth parameter is set\n"
"(the apex given in degree) a conical surface is used instead."
);
add_varargs_method("makeThread",&Module::makeThread,
"makeThread(pitch,depth,height,radius) -- Make a thread with a given pitch, depth, height and radius"
);
add_varargs_method("makeRevolution",&Module::makeRevolution,
"makeRevolution(Curve or Edge,[vmin,vmax,angle,pnt,dir,shapetype]) -- Make a revolved shape\n"
"by rotating the curve or a portion of it around an axis given by (pnt,dir).\n"
"By default vmin/vmax=bounds of the curve, angle=360, pnt=Vector(0,0,0),\n"
"dir=Vector(0,0,1) and shapetype=Part.Solid"
);
add_varargs_method("makeRuledSurface",&Module::makeRuledSurface,
"makeRuledSurface(Edge|Wire,Edge|Wire) -- Make a ruled surface\n"
"Create a ruled surface out of two edges or wires. If wires are used then"
"these must have the same number of edges."
);
add_varargs_method("makeShellFromWires",&Module::makeShellFromWires,
"makeShellFromWires(Wires) -- Make a shell from wires.\n"
"The wires must have the same number of edges."
);
add_varargs_method("makeTube",&Module::makeTube,
"makeTube(edge,radius,[continuity,max degree,max segments]) -- Create a tube.\n"
"continuity is a string which must be 'C0','C1','C2','C3','CN','G1' or 'G1',"
);
add_varargs_method("makeSweepSurface",&Module::makeSweepSurface,
"makeSweepSurface(edge(path),edge(profile),[float]) -- Create a profile along a path."
);
add_varargs_method("makeLoft",&Module::makeLoft,
"makeLoft(list of wires,[solid=False,ruled=False,closed=False,maxDegree=5]) -- Create a loft shape."
);
add_varargs_method("makeWireString",&Module::makeWireString,
"makeWireString(string,fontdir,fontfile,height,[track]) -- Make list of wires in the form of a string's characters."
);
add_varargs_method("makeSplitShape",&Module::makeSplitShape,
"makeSplitShape(shape, list of shape pairs,[check Interior=True]) -> two lists of shapes.\n"
"The following shape pairs are supported:\n"
"* Wire, Face\n"
"* Edge, Face\n"
"* Compound, Face\n"
"* Edge, Edge\n"
"* The face must be part of the specified shape and the edge, wire or compound must\n"
"lie on the face.\n"
"Output:\n"
"The first list contains the faces that are the left of the projected wires.\n"
"The second list contains the left part on the shape.\n\n"
"Example:\n"
"face = ...\n"
"edges = ...\n"
"split = [(edges[0],face),(edges[1],face)]\n"
"r = Part.makeSplitShape(face, split)\n"
"Part.show(r[0][0])\n"
"Part.show(r[1][0])\n"
);
add_varargs_method("exportUnits",&Module::exportUnits,
"exportUnits([string=MM|M|INCH|FT|MI|KM|MIL|UM|CM|UIN]) -- Set units for exporting STEP/IGES files and returns the units."
);
add_varargs_method("setStaticValue",&Module::setStaticValue,
"setStaticValue(string,string|int|float) -- Set a name to a value The value can be a string, int or float."
);
add_varargs_method("cast_to_shape",&Module::cast_to_shape,
"cast_to_shape(shape) -- Cast to the actual shape type"
);
add_varargs_method("getSortedClusters",&Module::getSortedClusters,
"getSortedClusters(list of edges) -- Helper method to sort and cluster a variety of edges"
);
add_varargs_method("__sortEdges__",&Module::sortEdges,
"__sortEdges__(list of edges) -- list of edges\n"
"Helper method to sort an unsorted list of edges so that afterwards\n"
"the start and end vertex of two consecutive edges are geometrically coincident.\n"
"It returns a single list of edges and the algorithm stops after the first set of\n"
"connected edges which means that the output list can be smaller than the input list.\n"
"The sorted list can be used to create a Wire."
);
add_varargs_method("sortEdges",&Module::sortEdges2,
"sortEdges(list of edges) -- list of lists of edges\n"
"It does basically the same as __sortEdges__ but sorts all input edges and thus returns\n"
"a list of lists of edges"
);
add_varargs_method("__toPythonOCC__",&Module::toPythonOCC,
"__toPythonOCC__(shape) -- Helper method to convert an internal shape to pythonocc shape"
);
add_varargs_method("__fromPythonOCC__",&Module::fromPythonOCC,
"__fromPythonOCC__(occ) -- Helper method to convert a pythonocc shape to an internal shape"
);
add_varargs_method("clearShapeCache",&Module::clearShapeCache,
"clearShapeCache() -- Clears internal shape cache"
);
add_keyword_method("getShape",&Module::getShape,
"getShape(obj,subname=None,mat=None,needSubElement=False,transform=True,retType=0):\n"
"Obtain the TopoShape of a given object with SubName reference\n\n"
"* obj: the input object\n"
"* subname: dot separated sub-object reference\n"
"* mat: the current transformation matrix\n"
"* needSubElement: if False, ignore the sub-element (e.g. Face1, Edge1) reference in 'subname'\n"
"* transform: if False, then skip obj's transformation. Use this if mat already include obj's\n"
" transformation matrix\n"
"* retType: 0: return TopoShape,\n"
" 1: return (shape,subObj,mat), where subObj is the object referenced in 'subname',\n"
" and 'mat' is the accumulated transformation matrix of that sub-object.\n"
" 2: same as 1, but make sure 'subObj' is resolved if it is a link.\n"
"* refine: refine the returned shape"
);
add_varargs_method("splitSubname",&Module::splitSubname,
"splitSubname(subname) -> list(sub,mapped,subElement)\n"
"Split the given subname into a list\n\n"
"sub: subname without any sub-element reference\n"
"mapped: mapped element name, or '' if none\n"
"subElement: old style element name, or '' if none"
);
add_varargs_method("joinSubname",&Module::joinSubname,
"joinSubname(sub,mapped,subElement) -> subname\n"
);
initialize("This is a module working with shapes."); // register with Python
PyModule_AddObject(m_module, "BRepFeat", brepFeat.module().ptr());
PyModule_AddObject(m_module, "BRepOffsetAPI", brepOffsetApi.module().ptr());
PyModule_AddObject(m_module, "Geom2d", geom2d.module().ptr());
PyModule_AddObject(m_module, "GeomPlate", geomPlate.module().ptr());
PyModule_AddObject(m_module, "HLRBRep", HLRBRep.module().ptr());
PyModule_AddObject(m_module, "ShapeFix", shapeFix.module().ptr());
PyModule_AddObject(m_module, "ShapeUpgrade", shapeUpgrade.module().ptr());
PyModule_AddObject(m_module, "ChFi2d", chFi2d.module().ptr());
}
~Module() override {}
private:
Py::Object invoke_method_keyword( void *method_def,
const Py::Tuple &args, const Py::Dict &keywords ) override
{
try {
return Py::ExtensionModule<Module>::invoke_method_keyword(method_def, args, keywords);
}
catch (const Standard_Failure &e) {
std::string str;
Standard_CString msg = e.GetMessageString();
str += typeid(e).name();
str += " ";
if (msg) {str += msg;}
else {str += "No OCCT Exception Message";}
Base::Console().Error("%s\n", str.c_str());
throw Py::Exception(Part::PartExceptionOCCError, str);
}
catch (const Base::Exception &e) {
std::string str;
str += "FreeCAD exception thrown (";
str += e.what();
str += ")";
e.ReportException();
throw Py::RuntimeError(str);
}
catch (const std::exception &e) {
std::string str;
str += "C++ exception thrown (";
str += e.what();
str += ")";
Base::Console().Error("%s\n", str.c_str());
throw Py::RuntimeError(str);
}
}
Py::Object invoke_method_varargs(void *method_def, const Py::Tuple &args) override
{
try {
return Py::ExtensionModule<Module>::invoke_method_varargs(method_def, args);
}
catch (const Standard_Failure &e) {
std::string str;
Standard_CString msg = e.GetMessageString();
str += typeid(e).name();
str += " ";
if (msg) {str += msg;}
else {str += "No OCCT Exception Message";}
Base::Console().Error("%s\n", str.c_str());
throw Py::Exception(Part::PartExceptionOCCError, str);
}
catch (const Base::Exception &e) {
std::string str;
str += "FreeCAD exception thrown (";
str += e.what();
str += ")";
e.ReportException();
throw Py::RuntimeError(str);
}
catch (const std::exception &e) {
std::string str;
str += "C++ exception thrown (";
str += e.what();
str += ")";
Base::Console().Error("%s\n", str.c_str());
throw Py::RuntimeError(str);
}
}
Py::Object open(const Py::Tuple& args)
{
char* Name;
if (!PyArg_ParseTuple(args.ptr(), "et","utf-8",&Name))
throw Py::Exception();
std::string EncodedName = std::string(Name);
PyMem_Free(Name);
//Base::Console().Log("Open in Part with %s",Name);
Base::FileInfo file(EncodedName.c_str());
// extract ending
if (file.extension().empty())
throw Py::RuntimeError("No file extension");
if (file.hasExtension("stp") || file.hasExtension("step")) {
// create new document and add Import feature
App::Document *pcDoc = App::GetApplication().newDocument();
#if 1
ImportStepParts(pcDoc,EncodedName.c_str());
#else
Part::ImportStep *pcFeature = (Part::ImportStep *)pcDoc->addObject("Part::ImportStep",file.fileNamePure().c_str());
pcFeature->FileName.setValue(Name);
#endif
pcDoc->recompute();
}
#if 1
else if (file.hasExtension("igs") || file.hasExtension("iges")) {
App::Document *pcDoc = App::GetApplication().newDocument();
ImportIgesParts(pcDoc,EncodedName.c_str());
pcDoc->recompute();
}
#endif
else {
TopoShape shape;
shape.read(EncodedName.c_str());
// create new document set loaded shape
App::Document *pcDoc = App::GetApplication().newDocument(file.fileNamePure().c_str());
Part::Feature *object = static_cast<Part::Feature *>(pcDoc->addObject
("Part::Feature",file.fileNamePure().c_str()));
object->Shape.setValue(shape);
pcDoc->recompute();
}
return Py::None();
}
Py::Object insert(const Py::Tuple& args)
{
char* Name;
const char* DocName;
if (!PyArg_ParseTuple(args.ptr(), "ets","utf-8",&Name,&DocName))
throw Py::Exception();
std::string EncodedName = std::string(Name);
PyMem_Free(Name);
//Base::Console().Log("Insert in Part with %s",Name);
Base::FileInfo file(EncodedName.c_str());
// extract ending
if (file.extension().empty())
throw Py::RuntimeError("No file extension");
App::Document *pcDoc = App::GetApplication().getDocument(DocName);
if (!pcDoc) {
pcDoc = App::GetApplication().newDocument(DocName);
}
if (file.hasExtension("stp") || file.hasExtension("step")) {
#if 1
ImportStepParts(pcDoc,EncodedName.c_str());
#else
// add Import feature
Part::ImportStep *pcFeature = (Part::ImportStep *)pcDoc->addObject("Part::ImportStep",file.fileNamePure().c_str());
pcFeature->FileName.setValue(Name);
#endif
pcDoc->recompute();
}
#if 1
else if (file.hasExtension("igs") || file.hasExtension("iges")) {
ImportIgesParts(pcDoc,EncodedName.c_str());
pcDoc->recompute();
}
#endif
else {
TopoShape shape;
shape.read(EncodedName.c_str());
Part::Feature *object = static_cast<Part::Feature *>(pcDoc->addObject
("Part::Feature",file.fileNamePure().c_str()));
object->Shape.setValue(shape);
pcDoc->recompute();
}
return Py::None();
}
Py::Object exporter(const Py::Tuple& args)
{
PyObject* object;
char* Name;
if (!PyArg_ParseTuple(args.ptr(), "Oet",&object,"utf-8",&Name))
throw Py::Exception();
std::string EncodedName = std::string(Name);
PyMem_Free(Name);
BRep_Builder builder;
TopoDS_Compound comp;
builder.MakeCompound(comp);
Py::Sequence list(object);
for (Py::Sequence::iterator it = list.begin(); it != list.end(); ++it) {
PyObject* item = (*it).ptr();
if (PyObject_TypeCheck(item, &(App::DocumentObjectPy::Type))) {
App::DocumentObject* obj = static_cast<App::DocumentObjectPy*>(item)->getDocumentObjectPtr();
if (obj->getTypeId().isDerivedFrom(Part::Feature::getClassTypeId())) {
Part::Feature* part = static_cast<Part::Feature*>(obj);
const TopoDS_Shape& shape = part->Shape.getValue();
if (!shape.IsNull())
builder.Add(comp, shape);
}
else {
Base::Console().Message("'%s' is not a shape, export will be ignored.\n", obj->Label.getValue());
}
}
}
TopoShape shape(comp);
shape.write(EncodedName.c_str());
return Py::None();
}
Py::Object read(const Py::Tuple& args)
{
char* Name;
if (!PyArg_ParseTuple(args.ptr(), "et","utf-8",&Name))
throw Py::Exception();
std::string EncodedName = std::string(Name);
PyMem_Free(Name);
TopoShape* shape = new TopoShape();
shape->read(EncodedName.c_str());
return Py::asObject(new TopoShapePy(shape));
}
Py::Object show(const Py::Tuple& args)
{
PyObject *pcObj = nullptr;
char *name = "Shape";
if (!PyArg_ParseTuple(args.ptr(), "O!|s", &(TopoShapePy::Type), &pcObj, &name))
throw Py::Exception();
App::Document *pcDoc = App::GetApplication().getActiveDocument();
if (!pcDoc)
pcDoc = App::GetApplication().newDocument();
TopoShapePy* pShape = static_cast<TopoShapePy*>(pcObj);
Part::Feature *pcFeature = static_cast<Part::Feature*>(pcDoc->addObject("Part::Feature", name));
// copy the data
pcFeature->Shape.setValue(pShape->getTopoShapePtr()->getShape());
pcDoc->recompute();
return Py::asObject(pcFeature->getPyObject());
}
Py::Object getFacets(const Py::Tuple& args)
{
PyObject *shape;
Py::List list;
if (!PyArg_ParseTuple(args.ptr(), "O", &shape))
throw Py::Exception();
auto theShape = static_cast<Part::TopoShapePy*>(shape)->getTopoShapePtr()->getShape();
for (TopExp_Explorer ex(theShape, TopAbs_FACE); ex.More(); ex.Next()) {
TopoDS_Face currentFace = TopoDS::Face(ex.Current());
std::vector<gp_Pnt> points;
std::vector<Poly_Triangle> facets;
if (Tools::getTriangulation(currentFace, points, facets)) {
for (const auto& it : facets) {
Standard_Integer n1,n2,n3;
it.Get(n1, n2, n3);
gp_Pnt p1 = points[n1];
gp_Pnt p2 = points[n2];
gp_Pnt p3 = points[n3];
// TODO: verify if tolerance should be hard coded
if (!p1.IsEqual(p2, 0.01) && !p2.IsEqual(p3, 0.01) && !p3.IsEqual(p1, 0.01)) {
PyObject *t1 = PyTuple_Pack(3, PyFloat_FromDouble(p1.X()), PyFloat_FromDouble(p1.Y()), PyFloat_FromDouble(p1.Z()));
PyObject *t2 = PyTuple_Pack(3, PyFloat_FromDouble(p2.X()), PyFloat_FromDouble(p2.Y()), PyFloat_FromDouble(p2.Z()));
PyObject *t3 = PyTuple_Pack(3, PyFloat_FromDouble(p3.X()), PyFloat_FromDouble(p3.Y()), PyFloat_FromDouble(p3.Z()));
list.append(Py::asObject(PyTuple_Pack(3, t1, t2, t3)));
}
}
}
}
return list;
}
Py::Object makeCompound(const Py::Tuple& args)
{
PyObject *pcObj;
if (!PyArg_ParseTuple(args.ptr(), "O", &pcObj))
throw Py::Exception();
BRep_Builder builder;
TopoDS_Compound Comp;
builder.MakeCompound(Comp);
PY_TRY {
for(auto &s : getPyShapes(pcObj)) {
const auto &sh = s.getShape();
if (!sh.IsNull())
builder.Add(Comp, sh);
}
} _PY_CATCH_OCC(throw Py::Exception())
return Py::asObject(new TopoShapeCompoundPy(new TopoShape(Comp)));
}
Py::Object makeShell(const Py::Tuple& args)
{
PyObject *obj;
if (!PyArg_ParseTuple(args.ptr(), "O", &obj))
throw Py::Exception();
BRep_Builder builder;
TopoDS_Shape shape;
TopoDS_Shell shell;
//BRepOffsetAPI_Sewing mkShell;
builder.MakeShell(shell);
try {
Py::Sequence list(obj);
for (Py::Sequence::iterator it = list.begin(); it != list.end(); ++it) {
if (PyObject_TypeCheck((*it).ptr(), &(Part::TopoShapeFacePy::Type))) {
const TopoDS_Shape& sh = static_cast<TopoShapeFacePy*>((*it).ptr())->
getTopoShapePtr()->getShape();
if (!sh.IsNull())
builder.Add(shell, sh);
}
}
shape = shell;
BRepCheck_Analyzer check(shell);
if (!check.IsValid()) {
ShapeUpgrade_ShellSewing sewShell;
shape = sewShell.ApplySewing(shell);
}
}
catch (Standard_Failure& e) {
throw Py::Exception(PartExceptionOCCError, e.GetMessageString());
}
return Py::asObject(new TopoShapeShellPy(new TopoShape(shape)));
}
Py::Object makeFace(const Py::Tuple& args)
{
try {
char* className = nullptr;
PyObject* pcPyShapeOrList = nullptr;
PyErr_Clear();
if (PyArg_ParseTuple(args.ptr(), "Os", &pcPyShapeOrList, &className)) {
std::unique_ptr<FaceMaker> fm = Part::FaceMaker::ConstructFromType(className);
//dump all supplied shapes to facemaker, no matter what type (let facemaker decide).
if (PySequence_Check(pcPyShapeOrList)){
Py::Sequence list(pcPyShapeOrList);
for (Py::Sequence::iterator it = list.begin(); it != list.end(); ++it) {
PyObject* item = (*it).ptr();
if (PyObject_TypeCheck(item, &(Part::TopoShapePy::Type))) {
const TopoDS_Shape& sh = static_cast<Part::TopoShapePy*>(item)->getTopoShapePtr()->getShape();
fm->addShape(sh);
} else {
throw Py::TypeError("Object is not a shape.");
}
}
} else if (PyObject_TypeCheck(pcPyShapeOrList, &(Part::TopoShapePy::Type))) {
const TopoDS_Shape& sh = static_cast<Part::TopoShapePy*>(pcPyShapeOrList)->getTopoShapePtr()->getShape();
if (sh.IsNull())
throw NullShapeException("Shape is null!");
if (sh.ShapeType() == TopAbs_COMPOUND)
fm->useCompound(TopoDS::Compound(sh));
else
fm->addShape(sh);