FreeCAD

Форк
0
/
CrossSection.cpp 
323 строки · 12.6 Кб
1
/***************************************************************************
2
 *   Copyright (c) 2010 Werner Mayer <wmayer[at]users.sourceforge.net>     *
3
 *                                                                         *
4
 *   This file is part of the FreeCAD CAx development system.              *
5
 *                                                                         *
6
 *   This library is free software; you can redistribute it and/or         *
7
 *   modify it under the terms of the GNU Library General Public           *
8
 *   License as published by the Free Software Foundation; either          *
9
 *   version 2 of the License, or (at your option) any later version.      *
10
 *                                                                         *
11
 *   This library  is distributed in the hope that it will be useful,      *
12
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
13
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
14
 *   GNU Library General Public License for more details.                  *
15
 *                                                                         *
16
 *   You should have received a copy of the GNU Library General Public     *
17
 *   License along with this library; see the file COPYING.LIB. If not,    *
18
 *   write to the Free Software Foundation, Inc., 59 Temple Place,         *
19
 *   Suite 330, Boston, MA  02111-1307, USA                                *
20
 *                                                                         *
21
 ***************************************************************************/
22

23
#include "PreCompiled.h"
24
#ifndef _PreComp_
25
# include <algorithm>
26
# include <BRepAdaptor_Surface.hxx>
27
# include <BRepAlgoAPI_Common.hxx>
28
# include <BRepAlgoAPI_Cut.hxx>
29
# include <BRepAlgoAPI_Section.hxx>
30
# include <BRepBuilderAPI_MakeFace.hxx>
31
# include <BRepBuilderAPI_MakeWire.hxx>
32
# include <BRepPrimAPI_MakeHalfSpace.hxx>
33
# include <gp_Pln.hxx>
34
# include <Precision.hxx>
35
# include <ShapeAnalysis_FreeBounds.hxx>
36
# include <ShapeFix_Wire.hxx>
37
# include <TopExp.hxx>
38
# include <TopExp_Explorer.hxx>
39
# include <TopTools_HSequenceOfShape.hxx>
40
# include <TopTools_IndexedMapOfShape.hxx>
41
# include <TopoDS.hxx>
42
# include <TopoDS_Edge.hxx>
43
# include <TopoDS_Wire.hxx>
44
#endif
45

46
#include "CrossSection.h"
47
#include "TopoShapeOpCode.h"
48

49

50
using namespace Part;
51

52
CrossSection::CrossSection(double a, double b, double c, const TopoDS_Shape& s)
53
  : a(a), b(b), c(c), s(s)
54
{
55
}
56

57
std::list<TopoDS_Wire> CrossSection::slice(double d) const
58
{
59
    std::list<TopoDS_Wire> wires;
60
    // Fixes: 0001228: Cross section of Torus in Part Workbench fails or give wrong results
61
    // Fixes: 0001137: Incomplete slices when using Part.slice on a torus
62
    TopExp_Explorer xp;
63
    for (xp.Init(s, TopAbs_SOLID); xp.More(); xp.Next()) {
64
        sliceSolid(d, xp.Current(), wires);
65
    }
66
    for (xp.Init(s, TopAbs_SHELL, TopAbs_SOLID); xp.More(); xp.Next()) {
67
        sliceNonSolid(d, xp.Current(), wires);
68
    }
69
    for (xp.Init(s, TopAbs_FACE, TopAbs_SHELL); xp.More(); xp.Next()) {
70
        sliceNonSolid(d, xp.Current(), wires);
71
    }
72

73
    return removeDuplicates(wires);
74
}
75

76
std::list<TopoDS_Wire> CrossSection::removeDuplicates(const std::list<TopoDS_Wire>& wires) const
77
{
78
    std::list<TopoDS_Wire> wires_reduce;
79
    for (const auto& wire : wires) {
80
        TopTools_IndexedMapOfShape mapOfEdges1;
81
        TopExp::MapShapes(wire, TopAbs_EDGE, mapOfEdges1);
82

83
        // The wires are independent shapes but their edges might be shared
84
        auto it = std::find_if(wires_reduce.begin(), wires_reduce.end(), [&mapOfEdges1](const TopoDS_Wire& w) {
85
            // same TShape and same placement but different orientation
86
            TopTools_IndexedMapOfShape mapOfEdges2;
87
            TopExp::MapShapes(w, TopAbs_EDGE, mapOfEdges2);
88
            int numEdges1 = mapOfEdges1.Extent();
89
            int numEdges2 = mapOfEdges2.Extent();
90
            if (numEdges1 != numEdges2)
91
                return false;
92

93
            TopTools_IndexedMapOfShape::Iterator it1(mapOfEdges1);
94
            TopTools_IndexedMapOfShape::Iterator it2(mapOfEdges2);
95
            for (; it1.More() && it2.More(); it1.Next(), it2.Next()) {
96
                if (!it1.Value().IsSame(it2.Value()))
97
                    return false;
98
            }
99

100
            return true;
101
        });
102

103
        if (it == wires_reduce.end()) {
104
            wires_reduce.push_back(wire);
105
        }
106
    }
107
    return wires_reduce;
108
}
109

110
void CrossSection::sliceNonSolid(double d, const TopoDS_Shape& shape, std::list<TopoDS_Wire>& wires) const
111
{
112
    BRepAlgoAPI_Section cs(shape, gp_Pln(a,b,c,-d));
113
    if (cs.IsDone()) {
114
        std::list<TopoDS_Edge> edges;
115
        TopExp_Explorer xp;
116
        for (xp.Init(cs.Shape(), TopAbs_EDGE); xp.More(); xp.Next())
117
            edges.push_back(TopoDS::Edge(xp.Current()));
118
        connectEdges(edges, wires);
119
    }
120
}
121

122
void CrossSection::sliceSolid(double d, const TopoDS_Shape& shape, std::list<TopoDS_Wire>& wires) const
123
{
124
    gp_Pln slicePlane(a,b,c,-d);
125
    BRepBuilderAPI_MakeFace mkFace(slicePlane);
126
    TopoDS_Face face = mkFace.Face();
127

128
    // Make sure to choose a point that does not lie on the plane (fixes #0001228)
129
    gp_Vec tempVector(a,b,c);
130
    tempVector.Normalize();//just in case.
131
    tempVector *= (d+1.0);
132
    gp_Pnt refPoint(0.0, 0.0, 0.0);
133
    refPoint.Translate(tempVector);
134

135
    BRepPrimAPI_MakeHalfSpace mkSolid(face, refPoint);
136
    TopoDS_Solid solid = mkSolid.Solid();
137
    BRepAlgoAPI_Cut mkCut(shape, solid);
138

139
    if (mkCut.IsDone()) {
140
        TopTools_IndexedMapOfShape mapOfFaces;
141
        TopExp::MapShapes(mkCut.Shape(), TopAbs_FACE, mapOfFaces);
142
        for (int i=1; i<=mapOfFaces.Extent(); i++) {
143
            const TopoDS_Face& face = TopoDS::Face(mapOfFaces.FindKey(i));
144
            BRepAdaptor_Surface adapt(face);
145
            if (adapt.GetType() == GeomAbs_Plane) {
146
                gp_Pln plane = adapt.Plane();
147
                if (plane.Axis().IsParallel(slicePlane.Axis(), Precision::Confusion()) &&
148
                    plane.Distance(slicePlane.Location()) < Precision::Confusion()) {
149
                    // sort and repair the wires
150
                    TopTools_IndexedMapOfShape mapOfWires;
151
                    TopExp::MapShapes(face, TopAbs_WIRE, mapOfWires);
152
                    connectWires(mapOfWires, wires);
153
                }
154
            }
155
        }
156
    }
157
}
158

159
void CrossSection::connectEdges (const std::list<TopoDS_Edge>& edges, std::list<TopoDS_Wire>& wires) const
160
{
161
    // Hint: Use ShapeAnalysis_FreeBounds::ConnectEdgesToWires() as an alternative
162
    std::list<TopoDS_Edge> edge_list = edges;
163
    while (!edge_list.empty()) {
164
        BRepBuilderAPI_MakeWire mkWire;
165
        // add and erase first edge
166
        mkWire.Add(edge_list.front());
167
        edge_list.erase(edge_list.begin());
168

169
        TopoDS_Wire new_wire = mkWire.Wire();  // current new wire
170

171
        // try to connect each edge to the wire, the wire is complete if no more edges are connectible
172
        bool found = false;
173
        do {
174
            found = false;
175
            for (std::list<TopoDS_Edge>::iterator pE = edge_list.begin(); pE != edge_list.end();++pE) {
176
                mkWire.Add(*pE);
177
                if (mkWire.Error() != BRepBuilderAPI_DisconnectedWire) {
178
                    // edge added ==> remove it from list
179
                    found = true;
180
                    edge_list.erase(pE);
181
                    new_wire = mkWire.Wire();
182
                    break;
183
                }
184
            }
185
        }
186
        while (found);
187

188
        // Fix any topological issues of the wire
189
        wires.push_back(fixWire(new_wire));
190
    }
191
}
192

193
void CrossSection::connectWires (const TopTools_IndexedMapOfShape& wireMap, std::list<TopoDS_Wire>& wires) const
194
{
195
    Handle(TopTools_HSequenceOfShape) hWires = new TopTools_HSequenceOfShape();
196
    for (int i=1; i<=wireMap.Extent(); i++) {
197
        const TopoDS_Shape& wire = wireMap.FindKey(i);
198
        hWires->Append(wire);
199
    }
200

201
    Handle(TopTools_HSequenceOfShape) hSorted = new TopTools_HSequenceOfShape();
202
    ShapeAnalysis_FreeBounds::ConnectWiresToWires(hWires, Precision::Confusion(), false, hSorted);
203

204
    for (int i=1; i<=hSorted->Length(); i++) {
205
        const TopoDS_Wire& new_wire = TopoDS::Wire(hSorted->Value(i));
206
        // Fix any topological issues of the wire
207
        wires.push_back(fixWire(new_wire));
208
    }
209
}
210

211
TopoDS_Wire CrossSection::fixWire(const TopoDS_Wire& wire) const
212
{
213
    // Fix any topological issues of the wire
214
    ShapeFix_Wire aFix;
215
    aFix.SetPrecision(Precision::Confusion());
216
    aFix.Load(wire);
217
    aFix.FixReorder();
218
    aFix.FixConnected();
219
    aFix.FixClosed();
220
    return aFix.Wire();
221
}
222

223
TopoCrossSection::TopoCrossSection(double a, double b, double c, const TopoShape& s, const char *op)
224
    : a(a), b(b), c(c), shape(s), op(op?op:Part::OpCodes::Slice)
225
{
226
}
227

228
void TopoCrossSection::slice(int idx, double d, std::vector<TopoShape>& wires) const
229
{
230
    // Fixes: 0001228: Cross section of Torus in Part Workbench fails or give wrong results
231
    // Fixes: 0001137: Incomplete slices when using Part.slice on a torus
232
    bool found = false;
233
    for (auto& s : shape.getSubTopoShapes(TopAbs_SOLID)) {
234
        sliceSolid(idx, d, s, wires);
235
        found = true;
236
    }
237
    if (!found) {
238
        for (auto& s : shape.getSubTopoShapes(TopAbs_SHELL)) {
239
            sliceNonSolid(idx, d, s, wires);
240
            found = true;
241
        }
242
        if (!found) {
243
            for (auto& s : shape.getSubTopoShapes(TopAbs_FACE)) {
244
                sliceNonSolid(idx, d, s, wires);
245
            }
246
        }
247
    }
248
}
249

250
TopoShape TopoCrossSection::slice(int idx, double d) const
251
{
252
    std::vector<TopoShape> wires;
253
    slice(idx, d, wires);
254
    return TopoShape().makeElementCompound(
255
        wires,
256
        0,
257
        TopoShape::SingleShapeCompoundCreationPolicy::returnShape);
258
}
259

260
void TopoCrossSection::sliceNonSolid(int idx,
261
                                     double d,
262
                                     const TopoShape& shape,
263
                                     std::vector<TopoShape>& wires) const
264
{
265
    BRepAlgoAPI_Section cs(shape.getShape(), gp_Pln(a, b, c, -d));
266
    if (cs.IsDone()) {
267
        std::string prefix(op);
268
        prefix += Data::indexSuffix(idx);
269
        auto res = TopoShape()
270
                       .makeElementShape(cs, shape, prefix.c_str())
271
                       .makeElementWires()
272
                       .getSubTopoShapes(TopAbs_WIRE);
273
        wires.insert(wires.end(), res.begin(), res.end());
274
    }
275
}
276

277
void TopoCrossSection::sliceSolid(int idx,
278
                                  double d,
279
                                  const TopoShape& shape,
280
                                  std::vector<TopoShape>& wires) const
281
{
282
    gp_Pln slicePlane(a, b, c, -d);
283
    BRepBuilderAPI_MakeFace mkFace(slicePlane);
284
    TopoShape face(idx);
285
    face.setShape(mkFace.Face());
286

287
    // Make sure to choose a point that does not lie on the plane (fixes #0001228)
288
    gp_Vec tempVector(a, b, c);
289
    tempVector.Normalize();  // just in case.
290
    tempVector *= (d + 1.0);
291
    gp_Pnt refPoint(0.0, 0.0, 0.0);
292
    refPoint.Translate(tempVector);
293

294
    BRepPrimAPI_MakeHalfSpace mkSolid(TopoDS::Face(face.getShape()), refPoint);
295
    TopoShape solid(idx);
296
    std::string prefix(op);
297
    prefix += Data::indexSuffix(idx);
298
    solid.makeElementShape(mkSolid, face, prefix.c_str());
299
    BRepAlgoAPI_Cut mkCut(shape.getShape(), solid.getShape());
300

301
    if (mkCut.IsDone()) {
302
        TopoShape res(shape.Tag, shape.Hasher);
303
        std::vector<TopoShape> shapes;
304
        shapes.push_back(shape);
305
        shapes.push_back(solid);
306
        res.makeElementShape(mkCut, shapes, prefix.c_str());
307
        for (auto& face : res.getSubTopoShapes(TopAbs_FACE)) {
308
            BRepAdaptor_Surface adapt(TopoDS::Face(face.getShape()));
309
            if (adapt.GetType() == GeomAbs_Plane) {
310
                gp_Pln plane = adapt.Plane();
311
                if (plane.Axis().IsParallel(slicePlane.Axis(), Precision::Confusion())
312
                    && plane.Distance(slicePlane.Location()) < Precision::Confusion()) {
313
                    auto repaired_wires = TopoShape(face.Tag)
314
                                              .makeElementWires(face.getSubTopoShapes(TopAbs_EDGE),
315
                                                                prefix.c_str(),
316
                                                                true)
317
                                              .getSubTopoShapes(TopAbs_WIRE);
318
                    wires.insert(wires.end(), repaired_wires.begin(), repaired_wires.end());
319
                }
320
            }
321
        }
322
    }
323
}
324

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.