Salome HOME
ed3bf8fec901edecef4e221c3a9f8b6c55a4a515
[modules/shaper.git] / src / GeomAlgoAPI / GeomAlgoAPI_SketchBuilder.cpp
1 // File:        GeomAlgoAPI_SketchBuilder.cpp
2 // Created:     02 Jun 2014
3 // Author:      Artem ZHIDKOV
4
5 #include <GeomAlgoAPI_SketchBuilder.h>
6
7 #include <set>
8
9 #include <gp_Dir.hxx>
10 #include <gp_Pln.hxx>
11
12 #include <BOPAlgo_Builder.hxx>
13 #include <BOPAlgo_Operation.hxx>
14 #include <BOPAlgo_PaveFiller.hxx>
15 #include <BOPTools.hxx>
16 #include <BRep_Builder.hxx>
17 #include <BRep_Curve3D.hxx>
18 #include <BRep_Tool.hxx>
19 #include <BRepAlgoAPI_Cut.hxx>
20 #include <BRepBuilderAPI_MakeFace.hxx>
21 #include <BRepClass_FaceClassifier.hxx>
22 #include <Geom_Curve.hxx>
23 #include <Geom_Plane.hxx>
24 #include <TopExp.hxx>
25 #include <TopExp_Explorer.hxx>
26 #include <TopoDS_Edge.hxx>
27 #include <TopoDS_Face.hxx>
28 #include <TopoDS_Vertex.hxx>
29 #include <TopoDS_Wire.hxx>
30
31 #include <Precision.hxx>
32
33 #include <assert.h>
34
35 #ifndef DBL_MAX
36 #define DBL_MAX 1.7976931348623158e+308 
37 #endif
38
39 const double tolerance = Precision::Confusion();
40 // This value helps to find direction on the boundaries of curve.
41 // It is not significant for lines, but is used for circles to avoid 
42 // wrong directions of movement (when two edges are tangent on the certain vertex)
43 const double shift = acos(1.0 - 3.0 * tolerance);
44
45 /// \brief Search first vertex - the vertex with lowest x coordinate, which is used in 2 edges at least
46 static const TopoDS_Vertex& findStartVertex(const BOPCol_IndexedDataMapOfShapeListOfShape& theMapVE,
47                                            const gp_Dir& theDirX, const gp_Dir& theDirY);
48
49 /// \brief Search the vertex on the sketch candidate to be the next one in the loop
50 static void findNextVertex(const TopoDS_Vertex& theStartVertex,
51                            const BOPCol_IndexedDataMapOfShapeListOfShape& theVertexEdgeMap,
52                            const gp_Dir& theStartDir, const gp_Dir& theNormal,
53                            TopoDS_Vertex& theNextVertex, TopoDS_Edge& theNextEdge,
54                            gp_Dir& theNextDir);
55
56 /// \brief Create planar face using the edges surrounding it
57 static void createFace(const TopoDS_Vertex& theStartVertex,
58                        const std::list<TopoDS_Edge>::iterator& theStartEdge,
59                        const std::list<TopoDS_Edge>::iterator& theEndOfEdges,
60                        const gp_Pln& thePlane, TopoDS_Face& theResFace);
61
62 /// \bief Create planar wire
63 static void createWireList(const TopoDS_Vertex& theStartVertex,
64                            const std::list<TopoDS_Edge>::iterator& theStartEdge,
65                            const std::list<TopoDS_Edge>::iterator& theEndOfEdges,
66                            const std::set<TopoDS_Edge*>& theEdgesInLoops,
67                            std::list<TopoDS_Wire>& theResWires);
68
69 /// \brief Calculate outer tengency on the edge in specified vertex
70 static gp_Dir getOuterEdgeDirection(const TopoDS_Edge& theEdge, const TopoDS_Vertex& theVertex);
71
72 /// \brief Unnecessary edges will be removed from the map.
73 ///        Positions of iterator will be updated
74 static void removeWasteEdges(std::list<TopoDS_Vertex>::iterator& theStartVertex,
75                              std::list<TopoDS_Edge>::iterator& theStartEdge,
76                              const std::list<TopoDS_Vertex>::iterator& theEndOfVertexes,
77                              const std::list<TopoDS_Edge>::iterator& theEndOfEdges,
78                              BOPCol_IndexedDataMapOfShapeListOfShape& theMapVE);
79
80
81 void GeomAlgoAPI_SketchBuilder::createFaces(
82     const boost::shared_ptr<GeomAPI_Pnt>& theOrigin, const boost::shared_ptr<GeomAPI_Dir>& theDirX,
83     const boost::shared_ptr<GeomAPI_Dir>& theDirY, const boost::shared_ptr<GeomAPI_Dir>& theNorm,
84     const std::list<boost::shared_ptr<GeomAPI_Shape> >& theFeatures,
85     std::list<boost::shared_ptr<GeomAPI_Shape> >& theResultFaces,
86     std::list<boost::shared_ptr<GeomAPI_Shape> >& theResultWires)
87 {
88   if (theFeatures.empty())
89     return;
90
91   // Create the list of edges with shared vertexes
92   BOPAlgo_Builder aBuilder;
93   BOPAlgo_PaveFiller aPF;
94   TopoDS_Shape aFeaturesCompound;
95
96   // Obtain only edges from the features list
97   std::list<boost::shared_ptr<GeomAPI_Shape> > anEdges;
98   std::list<boost::shared_ptr<GeomAPI_Shape> >::const_iterator aFeatIt = theFeatures.begin();
99   for (; aFeatIt != theFeatures.end(); aFeatIt++) {
100     boost::shared_ptr<GeomAPI_Shape> aShape(*aFeatIt);
101     const TopoDS_Edge& anEdge = aShape->impl<TopoDS_Edge>();
102     if (anEdge.ShapeType() == TopAbs_EDGE)
103       anEdges.push_back(aShape);
104   }
105
106   if (anEdges.size() == 1) {  // If there is only one feature, BOPAlgo_Builder will decline to work. Need to process it anyway
107     aFeaturesCompound = anEdges.front()->impl<TopoDS_Shape>();
108   } else {
109     std::list<boost::shared_ptr<GeomAPI_Shape> >::const_iterator anIt = anEdges.begin();
110     for (; anIt != anEdges.end(); anIt++) {
111       boost::shared_ptr<GeomAPI_Shape> aPreview(*anIt);
112       aBuilder.AddArgument(aPreview->impl<TopoDS_Edge>());
113     }
114     aPF.SetArguments(aBuilder.Arguments());
115     aPF.Perform();
116     int aErr = aPF.ErrorStatus();
117     if (aErr)
118       return;
119     aBuilder.PerformWithFiller(aPF);
120     aErr = aBuilder.ErrorStatus();
121     if (aErr)
122       return;
123     aFeaturesCompound = aBuilder.Shape();
124   }
125
126   BOPCol_IndexedDataMapOfShapeListOfShape aMapVE;  // map between vertexes and edges
127   BOPTools::MapShapesAndAncestors(aFeaturesCompound, TopAbs_VERTEX, TopAbs_EDGE, aMapVE);
128   if (aMapVE.IsEmpty())  // in case of not-initialized circle
129     return;
130
131   gp_Dir aDirX = theDirX->impl<gp_Dir>();
132   gp_Dir aDirY = theDirY->impl<gp_Dir>();
133   gp_Dir aNorm = theNorm->impl<gp_Dir>();
134
135   gp_Pln aPlane(theOrigin->impl<gp_Pnt>(), aNorm);
136
137   // Set of edges used in loops
138   std::set<TopoDS_Edge*> anEdgesInLoops;
139   // Lists for processed vertexes and edges
140   std::list<TopoDS_Vertex> aProcVertexes;
141   std::list<TopoDS_Edge> aProcEdges;
142
143   // Search the start vertex
144   TopoDS_Vertex aStartVertex = findStartVertex(aMapVE, aDirX, aDirY);
145   aProcVertexes.push_back(aStartVertex);
146
147   TopoDS_Vertex aCurVertex = aStartVertex;
148   gp_Dir aCurDir = aDirY.Reversed();
149   gp_Dir aCurNorm = aNorm.Reversed();
150
151   // Go through the edges and find loops
152   TopoDS_Vertex aNextVertex;
153   TopoDS_Edge aBindingEdge;
154   gp_Dir aNextDir;
155   while (aMapVE.Extent() > 0) {
156     if (aCurVertex.IsNull())
157       return;
158     findNextVertex(aCurVertex, aMapVE, aCurDir, aCurNorm, aNextVertex, aBindingEdge, aNextDir);
159     aCurNorm = aNorm;
160
161     // Try to find next vertex in the list of already processed
162     bool isLoopFound = false;
163     std::list<TopoDS_Vertex>::iterator aVertIter = aProcVertexes.begin();
164     std::list<TopoDS_Edge>::iterator anEdgeIter = aProcEdges.begin();
165     for (; aVertIter != aProcVertexes.end(); aVertIter++) {
166       if (aVertIter->IsSame(aNextVertex)) {
167         isLoopFound = true;
168         break;
169       }
170       if (anEdgeIter != aProcEdges.end())
171         anEdgeIter++;
172     }
173
174     bool isCircleFound = (isLoopFound && anEdgeIter == aProcEdges.end());
175     aProcVertexes.push_back(aNextVertex);
176     aProcEdges.push_back(aBindingEdge);
177
178     if (isLoopFound) {
179       // If the binding edge is a full circle, then it may be added recently. Need to update edge iterator
180       if (isCircleFound) {
181         anEdgeIter = aProcEdges.end();
182         anEdgeIter--;
183       }
184       else if (aVertIter != aProcVertexes.begin()) {
185         // Check the orientation of the loop
186         gp_Dir aCN = getOuterEdgeDirection(*anEdgeIter, *aVertIter);
187         gp_Dir aCP = getOuterEdgeDirection(aProcEdges.back(), *aVertIter);
188         aCN.Reverse();
189         aCP.Reverse();
190         if (aCN.DotCross(aCP, aNorm) < -tolerance) {
191           // The found loop has wrong orientation and may contain sub-loops.
192           // Need to check it once again with another initial direction.
193           aCurVertex = *aVertIter;
194           do {
195             aProcVertexes.pop_back();
196             aProcEdges.pop_back();
197           } while (aCurVertex != aProcVertexes.back());
198           aCurDir = aCN.Reversed();
199           aCurNorm = aNorm.Reversed();
200           continue;
201         }
202       }
203
204       if (!isCircleFound && anEdgeIter != aProcEdges.end() && 
205           anEdgeIter->IsSame(aProcEdges.back())) { // The loop on the same edge taken twice
206         aProcVertexes.pop_back();
207         aProcEdges.pop_back();
208         aCurVertex = aProcVertexes.back();
209         aCurDir = getOuterEdgeDirection(aProcEdges.back(), aCurVertex);
210         aCurNorm = aNorm.Reversed();
211         continue;
212       }
213
214       // When the orientation is correct or the edges looped through
215       // the first element, create new face and remove unnecessary edges.
216       TopoDS_Face aPatch;
217       createFace(*aVertIter, anEdgeIter, aProcEdges.end(), aPlane, aPatch);
218       if (!aPatch.IsNull()) {
219         boost::shared_ptr<GeomAPI_Shape> aFace(new GeomAPI_Shape);
220         aFace->setImpl(new TopoDS_Face(aPatch));
221         theResultFaces.push_back(aFace);
222       }
223       // push the edges used in the loop to the map
224       std::list<TopoDS_Edge>::iterator anIter;
225       for (anIter = anEdgeIter; anIter != aProcEdges.end(); anIter++)
226         anEdgesInLoops.insert(&(*anIter));
227       // remove unnecessary edges
228       std::list<TopoDS_Vertex>::iterator aCopyVLoop = aVertIter;
229       std::list<TopoDS_Edge>::iterator aCopyELoop = anEdgeIter;
230       removeWasteEdges(aVertIter, anEdgeIter, aProcVertexes.end(), aProcEdges.end(), aMapVE);
231
232       // revert the list of remaining edges
233       std::list<TopoDS_Vertex> aRemainVertexes;
234       for (; aVertIter != aProcVertexes.end(); aVertIter++)
235         aRemainVertexes.push_front(*aVertIter);
236       std::list<TopoDS_Edge> aRemainEdges;
237       for (; anEdgeIter != aProcEdges.end(); anEdgeIter++)
238         aRemainEdges.push_front(*anEdgeIter);
239       // remove edges and vertexes used in the loop and add remaining ones
240       aProcVertexes.erase(aCopyVLoop, aProcVertexes.end());
241       aProcVertexes.insert(aProcVertexes.end(), aRemainVertexes.begin(), aRemainVertexes.end());
242       aProcEdges.erase(aCopyELoop, aProcEdges.end());
243       aProcEdges.insert(aProcEdges.end(), aRemainEdges.begin(), aRemainEdges.end());
244
245       // Recalculate current vertex and current direction
246       if (!aProcVertexes.empty()) {
247         aNextVertex = aProcVertexes.back();
248         if (!aProcEdges.empty())
249           aNextDir = getOuterEdgeDirection(aProcEdges.back(), aNextVertex);
250         else
251           aNextDir = aDirY;
252       }
253     }
254
255     // if next vertex connected only to alone edge, this is a part of wire (not a closed loop),
256     // we need to go back through the list of already checked edges to find a branching vertex
257     if (!aMapVE.IsEmpty() && aMapVE.Contains(aNextVertex)
258         && aMapVE.FindFromKey(aNextVertex).Size() == 1) {
259       std::list<TopoDS_Vertex>::reverse_iterator aVRIter = aProcVertexes.rbegin();
260       std::list<TopoDS_Edge>::reverse_iterator aERIter = aProcEdges.rbegin();
261       if (aVRIter != aProcVertexes.rend())
262         aVRIter++;
263       if (aERIter != aProcEdges.rend())
264         aERIter++;
265
266       for (; aERIter != aProcEdges.rend(); aERIter++, aVRIter++)
267         if (aMapVE.FindFromKey(*aVRIter).Size() > 2)
268           break;
269       if (aERIter != aProcEdges.rend()
270           || (aVRIter != aProcVertexes.rend() && aMapVE.FindFromKey(*aVRIter).Size() == 1)) {  // the branching vertex was found or current list of edges is a wire without branches
271         std::list<TopoDS_Edge>::iterator aEIter;
272         TopoDS_Edge aCurEdge;
273         if (aERIter != aProcEdges.rend()) {
274           aEIter = aERIter.base();
275           aCurEdge = *aERIter;
276         } else
277           aEIter = aProcEdges.begin();
278         std::list<TopoDS_Wire> aTail;
279         createWireList(*aVRIter, aEIter, aProcEdges.end(), anEdgesInLoops, aTail);
280         std::list<TopoDS_Wire>::const_iterator aTailIter = aTail.begin();
281         for (; aTailIter != aTail.end(); aTailIter++)
282           if (!aTailIter->IsNull()) {
283             boost::shared_ptr<GeomAPI_Shape> aWire(new GeomAPI_Shape);
284             aWire->setImpl(new TopoDS_Shape(*aTailIter));
285             theResultWires.push_back(aWire);
286           }
287         std::list<TopoDS_Vertex>::iterator aVIter = aVRIter.base();
288         std::list<TopoDS_Edge>::iterator aEItCopy = aEIter;
289         removeWasteEdges(--aVIter, aEItCopy, aProcVertexes.end(), aProcEdges.end(), aMapVE);
290
291         aProcEdges.erase(aEIter, aProcEdges.end());
292         aVIter = aVRIter.base();
293         aProcVertexes.erase(aVIter, aProcVertexes.end());
294
295         if (!aProcVertexes.empty()) {
296           aNextVertex = aProcVertexes.back();
297           if (!aCurEdge.IsNull())
298             aNextDir = getOuterEdgeDirection(aCurEdge, aNextVertex);
299         }
300       } else {  // there is no branching vertex in the list of proceeded,
301                 // so we should revert the list and go the opposite way
302         aProcVertexes.reverse();
303         aProcEdges.reverse();
304         aNextVertex = aProcVertexes.back();
305         aNextDir =
306             aProcEdges.empty() ? aDirY : getOuterEdgeDirection(aProcEdges.back(), aNextVertex);
307       }
308     }
309
310     // When all edges of current component of connectivity are processed,
311     // we should repeat procedure for finding initial vertex in the remaining
312     if (!aMapVE.IsEmpty() && !aMapVE.Contains(aNextVertex)) {
313       aProcVertexes.clear();
314       aProcEdges.clear();
315
316       aStartVertex = findStartVertex(aMapVE, aDirX, aDirY);
317       aProcVertexes.push_back(aStartVertex);
318       aNextVertex = aStartVertex;
319       aNextDir = aDirY.Reversed();
320       aCurNorm = aNorm.Reversed();
321     }
322
323     aCurVertex = aNextVertex;
324     aCurDir = aNextDir;
325   }
326
327   if (theResultFaces.size() > 1)
328     fixIntersections(theResultFaces);
329 }
330
331 void GeomAlgoAPI_SketchBuilder::fixIntersections(
332     std::list<boost::shared_ptr<GeomAPI_Shape> >& theFaces)
333 {
334   BRepClass_FaceClassifier aClassifier;
335
336   std::list<boost::shared_ptr<GeomAPI_Shape> >::iterator anIter1 = theFaces.begin();
337   std::list<boost::shared_ptr<GeomAPI_Shape> >::iterator anIter2;
338   for (; anIter1 != theFaces.end(); anIter1++) {
339     anIter2 = anIter1;
340     for (++anIter2; anIter2 != theFaces.end(); anIter2++) {
341       const TopoDS_Face& aF1 = (*anIter1)->impl<TopoDS_Face>();
342       assert(aF1.ShapeType() == TopAbs_FACE);  // all items in result list should be faces
343       TopExp_Explorer aVert2((*anIter2)->impl<TopoDS_Shape>(), TopAbs_VERTEX);
344       for (; aVert2.More(); aVert2.Next()) {
345         const TopoDS_Vertex& aV = (const TopoDS_Vertex&)aVert2.Current();
346         aClassifier.Perform(aF1, BRep_Tool::Pnt(aV), tolerance);
347         if (aClassifier.State() != TopAbs_IN && aClassifier.State() != TopAbs_ON)
348           break;
349       }
350       if (aVert2.More()) {  // second shape is not inside first, change the shapes order and repeat comparision
351         const TopoDS_Face& aF2 = (*anIter2)->impl<TopoDS_Face>();
352         assert(aF2.ShapeType() == TopAbs_FACE);  // all items in result list should be faces
353         TopExp_Explorer aVert1((*anIter1)->impl<TopoDS_Shape>(), TopAbs_VERTEX);
354         for (; aVert1.More(); aVert1.Next()) {
355           const TopoDS_Vertex& aV = (const TopoDS_Vertex&)aVert2.Current();
356           aClassifier.Perform(aF2, BRep_Tool::Pnt(aV), tolerance);
357           if (aClassifier.State() != TopAbs_IN && aClassifier.State() != TopAbs_ON)
358             break;
359         }
360         if (!aVert1.More()) {  // first shape should be cut from the second
361           BRepAlgoAPI_Cut aCut((*anIter2)->impl<TopoDS_Shape>(), (*anIter1)->impl<TopoDS_Shape>());
362           aCut.Build();
363           TopExp_Explorer anExp(aCut.Shape(), TopAbs_FACE);
364           (*anIter2)->setImpl(new TopoDS_Shape(anExp.Current()));
365           for (anExp.Next(); anExp.More(); anExp.Next()) {
366             boost::shared_ptr<GeomAPI_Shape> aShape(new GeomAPI_Shape);
367             aShape->setImpl(new TopoDS_Shape(anExp.Current()));
368             theFaces.push_back(aShape);
369           }
370         }
371       } else {  // second shape should be cut from the first
372         BRepAlgoAPI_Cut aCut((*anIter1)->impl<TopoDS_Shape>(), (*anIter2)->impl<TopoDS_Shape>());
373         aCut.Build();
374         TopExp_Explorer anExp(aCut.Shape(), TopAbs_FACE);
375         (*anIter1)->setImpl(new TopoDS_Shape(anExp.Current()));
376         for (anExp.Next(); anExp.More(); anExp.Next()) {
377           boost::shared_ptr<GeomAPI_Shape> aShape(new GeomAPI_Shape);
378           aShape->setImpl(new TopoDS_Shape(anExp.Current()));
379           theFaces.push_back(aShape);
380         }
381       }
382     }
383   }
384 }
385
386 // =================== Auxiliary functions ====================================
387 const TopoDS_Vertex& findStartVertex(const BOPCol_IndexedDataMapOfShapeListOfShape& theMapVE,
388                                     const gp_Dir& theDirX, const gp_Dir& theDirY)
389 {
390   int aStartVertexInd = 1;
391   double aMaxX = -DBL_MAX;
392   double aMaxY = -DBL_MAX;
393   int aNbVert = theMapVE.Extent();
394   for (int i = 1; i <= aNbVert; i++) {
395     const TopoDS_Vertex& aV = (const TopoDS_Vertex&) theMapVE.FindKey(i);
396     const gp_Pnt& aVertPnt = BRep_Tool::Pnt(aV);
397
398     double aX = aVertPnt.XYZ().Dot(theDirX.XYZ());
399     double aY = aVertPnt.XYZ().Dot(theDirY.XYZ());
400     if ((aX > aMaxX || (fabs(aX - aMaxX) < tolerance && aY > aMaxY))
401         && theMapVE.FindFromIndex(i).Extent() > 1) {
402       aMaxX = aX;
403       aMaxY = aY;
404       aStartVertexInd = i;
405     }
406   }
407   return static_cast<const TopoDS_Vertex&>(theMapVE.FindKey(aStartVertexInd));
408 }
409
410 void findNextVertex(const TopoDS_Vertex& theStartVertex,
411                     const BOPCol_IndexedDataMapOfShapeListOfShape& theVertexEdgeMap,
412                     const gp_Dir& theStartDir, const gp_Dir& theNormal, TopoDS_Vertex& theNextVertex,
413                     TopoDS_Edge& theNextEdge, gp_Dir& theNextDir)
414 {
415   const BOPCol_ListOfShape& anEdgesList = theVertexEdgeMap.FindFromKey(theStartVertex);
416   BOPCol_ListOfShape::Iterator aEdIter(anEdgesList);
417   double aBestEdgeProj = DBL_MAX;
418   for (; aEdIter.More(); aEdIter.Next()) {
419     const TopoDS_Edge& anEdge = static_cast<const TopoDS_Edge&>(aEdIter.Value());
420     gp_Dir aTang = getOuterEdgeDirection(anEdge, theStartVertex);
421     aTang.Reverse();
422
423     // The projection is normalized in segment (-1, 1),
424     // where (-1, 0] corresponds to the angles (pi/2, 0] between theStartDir and aTang
425     // and [0, 1) corresponds to the angles [0, -pi/2)
426     double aProj = (aTang.Dot(theStartDir) - 1.0) * 0.5;
427     if (fabs(fabs(aProj) - 1) < tolerance)
428       continue;
429     if (theStartDir.DotCross(aTang, theNormal) < tolerance)
430       aProj *= -1.0;
431
432     if (aProj < aBestEdgeProj) {
433       aBestEdgeProj = aProj;
434       theNextEdge = anEdge;
435       TopExp_Explorer aVertExp(theNextEdge, TopAbs_VERTEX);
436       for (; aVertExp.More(); aVertExp.Next())
437         if (!aVertExp.Current().IsSame(theStartVertex)) {
438           theNextVertex = static_cast<const TopoDS_Vertex&>(aVertExp.Current());
439           theNextDir = getOuterEdgeDirection(anEdge, theNextVertex);
440           break;
441         }
442       if (!aVertExp.More()) {  // This edge is a full circle
443         TopoDS_Vertex aV1, aV2;
444         TopExp::Vertices(theNextEdge, aV1, aV2);
445         if (aV1.Orientation() == theStartVertex.Orientation())
446           theNextVertex = aV2;
447         else
448           theNextVertex = aV1;
449         theNextDir = getOuterEdgeDirection(anEdge, theNextVertex);
450       }
451     }
452   }
453 }
454
455 static void addEdgeToWire(const TopoDS_Edge& theEdge, const BRep_Builder& theBuilder,
456                           TopoDS_Shape& theSpliceVertex, TopoDS_Wire& theWire)
457 {
458   TopoDS_Edge anEdge = theEdge;
459   bool isCurVertChanged = false;
460   TopoDS_Shape aCurVertChanged;
461
462   TopExp_Explorer aVertExp(theEdge, TopAbs_VERTEX);
463   for (; aVertExp.More(); aVertExp.Next()) {
464     const TopoDS_Shape& aVertex = aVertExp.Current();
465     if (aVertex.IsSame(theSpliceVertex)
466         && aVertex.Orientation() != theEdge.Orientation()) {  // Current vertex is the last for the edge, so its orientation is wrong, need to revert the edge
467       anEdge.Reverse();
468       break;
469     }
470     if (!aVertex.IsSame(theSpliceVertex)) {
471       aCurVertChanged = aVertex;
472       isCurVertChanged = true;
473     }
474   }
475   theSpliceVertex = isCurVertChanged ? aCurVertChanged : aVertExp.Current();
476
477   theBuilder.Add(theWire, anEdge);
478 }
479
480 void createFace(const TopoDS_Vertex& theStartVertex,
481                 const std::list<TopoDS_Edge>::iterator& theStartEdge,
482                 const std::list<TopoDS_Edge>::iterator& theEndOfEdges,
483                 const gp_Pln& thePlane,
484                 TopoDS_Face& theResFace)
485 {
486   TopoDS_Wire aResWire;
487   BRep_Builder aBuilder;
488   aBuilder.MakeWire(aResWire);
489
490   TopoDS_Vertex aCurVertex = theStartVertex;
491   std::list<TopoDS_Edge>::const_iterator anEdgeIter = theStartEdge;
492   for (; anEdgeIter != theEndOfEdges; anEdgeIter++) {
493     if (!anEdgeIter->IsNull())
494       addEdgeToWire(*anEdgeIter, aBuilder, aCurVertex, aResWire);
495   }
496
497   BRepBuilderAPI_MakeFace aFaceBuilder(thePlane, aResWire);
498   if (aFaceBuilder.Error() == BRepBuilderAPI_FaceDone)
499     theResFace = aFaceBuilder.Face();
500 }
501
502 void createWireList(const TopoDS_Vertex& theStartVertex,
503                     const std::list<TopoDS_Edge>::iterator& theStartEdge,
504                     const std::list<TopoDS_Edge>::iterator& theEndOfEdges,
505                     const std::set<TopoDS_Edge*>& theEdgesInLoops,
506                     std::list<TopoDS_Wire>& theResWires)
507 {
508   BRep_Builder aBuilder;
509   bool needNewWire = true;
510   TopoDS_Vertex aCurVertex = theStartVertex;
511
512   std::list<TopoDS_Edge>::iterator anIter = theStartEdge;
513   while (anIter != theEndOfEdges) {
514     while (anIter != theEndOfEdges && needNewWire && theEdgesInLoops.count(&(*anIter)) != 0) {
515       TopExp_Explorer aVertExp(*anIter, TopAbs_VERTEX);
516       for (; aVertExp.More(); aVertExp.Next())
517         if (!aVertExp.Current().IsSame(aCurVertex)) {
518           aCurVertex = static_cast<const TopoDS_Vertex&>(aVertExp.Current());
519           break;
520         }
521       anIter++;
522     }
523     if (anIter == theEndOfEdges)
524       break;
525
526     if (needNewWire) {  // The new wire should be created
527       TopoDS_Wire aWire;
528       aBuilder.MakeWire(aWire);
529       theResWires.push_back(aWire);
530       needNewWire = false;
531     } else if (theEdgesInLoops.count(&(*anIter)) != 0) {  // There was found the edge already used in loop.
532                                                           // Current wire should be released and new one should started
533       needNewWire = true;
534       continue;
535     }
536
537     addEdgeToWire(*anIter, aBuilder, aCurVertex, theResWires.back());
538     anIter++;
539   }
540 }
541
542 gp_Dir getOuterEdgeDirection(const TopoDS_Edge& theEdge, const TopoDS_Vertex& theVertex)
543 {
544   gp_Pnt aVertexPnt = BRep_Tool::Pnt(theVertex);
545
546   // Convert the edge to the curve to calculate the tangency.
547   // There should be only one curve in the edge.
548   double aFirst, aLast;
549   Handle(Geom_Curve) aCurve = BRep_Tool::Curve(theEdge, aFirst, aLast);
550
551   gp_Pnt aPnt;
552   gp_Vec aTang;
553   // A direction is determined not in the boundary points but in the points with small shift.
554   // It was done to avoid tangency between circle and other edge in the shared vertex.
555   aCurve->D1(aFirst + shift > aLast ? aFirst : aFirst + shift, aPnt, aTang);
556   aCurve->D0(aFirst, aPnt);
557   if (aVertexPnt.IsEqual(aPnt, tolerance))
558     return gp_Dir(aTang.Reversed());
559
560   aCurve->D1(aLast - shift < aFirst ? aLast : aLast - shift, aPnt, aTang);
561   return gp_Dir(aTang);
562 }
563
564 void removeWasteEdges(std::list<TopoDS_Vertex>::iterator& theStartVertex,
565                       std::list<TopoDS_Edge>::iterator& theStartEdge,
566                       const std::list<TopoDS_Vertex>::iterator& theEndOfVertexes,
567                       const std::list<TopoDS_Edge>::iterator& theEndOfEdges,
568                       BOPCol_IndexedDataMapOfShapeListOfShape& theMapVE)
569 {
570   bool isVertStep = true;
571   while (theStartVertex != theEndOfVertexes && theStartEdge != theEndOfEdges) {
572     BOPCol_ListOfShape& aBunch = theMapVE.ChangeFromKey(*theStartVertex);
573     BOPCol_ListOfShape::Iterator anApprEdge(aBunch);
574     for (; anApprEdge.More(); anApprEdge.Next())
575       if (anApprEdge.Value().IsSame(*theStartEdge))
576         break;
577     if (anApprEdge.More())
578       aBunch.Remove(anApprEdge);
579
580     if (isVertStep)
581       theStartVertex++;
582     else {
583       theStartEdge++;
584       // check current vertex to be a branching point
585       // if so, it will be a new starting point to find a loop
586       if (aBunch.Size() > 1)
587         break;
588     }
589     isVertStep = !isVertStep;
590   }
591
592   // The map of vertex-edges may be changed
593   BOPCol_IndexedDataMapOfShapeListOfShape aMapVECopy;
594   BOPCol_IndexedDataMapOfShapeListOfShape::Iterator aMapIter(theMapVE);
595   for (int ind = 1; aMapIter.More(); aMapIter.Next(), ind++)
596     if (!aMapIter.Value().IsEmpty())
597       aMapVECopy.Add(theMapVE.FindKey(ind), aMapIter.Value());
598   theMapVE.Clear();
599   theMapVE.Exchange(aMapVECopy);
600 }
601