]> SALOME platform Git repositories - modules/shaper.git/blob - src/GeomAlgoAPI/GeomAlgoAPI_ShapeTools.cpp
Salome HOME
fix coding style
[modules/shaper.git] / src / GeomAlgoAPI / GeomAlgoAPI_ShapeTools.cpp
1 // Copyright (C) 2014-2020  CEA/DEN, EDF R&D
2 //
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 // Lesser General Public License for more details.
12 //
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16 //
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
18 //
19
20 #include "GeomAlgoAPI_ShapeTools.h"
21
22 #include "GeomAlgoAPI_SketchBuilder.h"
23
24 #include <GeomAPI_Ax1.h>
25 #include <GeomAPI_Edge.h>
26 #include <GeomAPI_Dir.h>
27 #include <GeomAPI_Face.h>
28 #include <GeomAPI_Pln.h>
29 #include <GeomAPI_Pnt.h>
30 #include <GeomAPI_Wire.h>
31
32 #include <Bnd_Box.hxx>
33
34 #include <BRep_Tool.hxx>
35 #include <BRep_Builder.hxx>
36 #include <BRepAlgo.hxx>
37 #include <BRepAlgo_FaceRestrictor.hxx>
38 #include <BRepAdaptor_Curve.hxx>
39 #include <BRepBndLib.hxx>
40 #include <BRepBuilderAPI_FindPlane.hxx>
41 #include <BRepBuilderAPI_MakeEdge.hxx>
42 #include <BRepBuilderAPI_MakeFace.hxx>
43 #include <BRepBuilderAPI_MakeVertex.hxx>
44 #include <BRepCheck_Analyzer.hxx>
45 #include <BRepExtrema_DistShapeShape.hxx>
46 #include <BRepExtrema_ExtCF.hxx>
47 #include <BRepGProp.hxx>
48 #include <BRepTools.hxx>
49 #include <BRepTools_WireExplorer.hxx>
50 #include <BRepTopAdaptor_FClass2d.hxx>
51 #include <BRepClass_FaceClassifier.hxx>
52 #include <BRepLib_CheckCurveOnSurface.hxx>
53 #include <BRepLProp.hxx>
54
55 #include <BOPAlgo_Builder.hxx>
56
57 #include <Geom2d_Curve.hxx>
58 #include <Geom2d_Curve.hxx>
59
60 #include <Geom_CylindricalSurface.hxx>
61 #include <Geom_Line.hxx>
62 #include <Geom_Plane.hxx>
63 #include <Geom_RectangularTrimmedSurface.hxx>
64
65 #include <GeomAPI_ProjectPointOnCurve.hxx>
66 #include <GeomAPI_ShapeIterator.h>
67
68 #include <GeomLib_IsPlanarSurface.hxx>
69 #include <GeomLib_Tool.hxx>
70 #include <GeomAPI_IntCS.hxx>
71
72 #include <gp_Pln.hxx>
73 #include <GProp_GProps.hxx>
74
75 #include <IntAna_IntConicQuad.hxx>
76 #include <IntAna_Quadric.hxx>
77
78 #include <ShapeAnalysis.hxx>
79 #include <ShapeAnalysis_Surface.hxx>
80
81 #include <TopoDS.hxx>
82 #include <TopoDS_Edge.hxx>
83 #include <TopoDS_Face.hxx>
84 #include <TopoDS_Shape.hxx>
85 #include <TopoDS_Shell.hxx>
86 #include <TopoDS_Vertex.hxx>
87 #include <TopoDS_Builder.hxx>
88
89 #include <TopExp.hxx>
90 #include <TopExp_Explorer.hxx>
91
92 #include <TopTools_ListIteratorOfListOfShape.hxx>
93
94 #include <NCollection_Vector.hxx>
95
96 //==================================================================================================
97 static GProp_GProps props(const TopoDS_Shape& theShape)
98 {
99   GProp_GProps aGProps;
100
101   if (theShape.ShapeType() == TopAbs_EDGE || theShape.ShapeType() == TopAbs_WIRE)
102   {
103     BRepGProp::LinearProperties(theShape, aGProps);
104   }
105   else if (theShape.ShapeType() == TopAbs_FACE || theShape.ShapeType() == TopAbs_SHELL)
106   {
107     const Standard_Real anEps = 1.e-6;
108     BRepGProp::SurfaceProperties(theShape, aGProps, anEps);
109   }
110   else if (theShape.ShapeType() == TopAbs_SOLID || theShape.ShapeType() == TopAbs_COMPSOLID)
111   {
112     BRepGProp::VolumeProperties(theShape, aGProps);
113   }
114   else if (theShape.ShapeType() == TopAbs_COMPOUND)
115   {
116     for (TopoDS_Iterator anIt(theShape); anIt.More(); anIt.Next())
117     {
118       aGProps.Add(props(anIt.Value()));
119     }
120   }
121
122   return aGProps;
123 }
124
125 //==================================================================================================
126 double GeomAlgoAPI_ShapeTools::volume(const std::shared_ptr<GeomAPI_Shape> theShape)
127 {
128   if(!theShape.get()) {
129     return 0.0;
130   }
131   const TopoDS_Shape& aShape = theShape->impl<TopoDS_Shape>();
132   if(aShape.IsNull()) {
133     return 0.0;
134   }
135   const Standard_Real anEps = 1.e-6;
136   TopExp_Explorer anExp(aShape, TopAbs_SOLID);
137   if (anExp.More()) { // return volume if there is at least one solid
138     double aVolume = 0.0;
139     for (; anExp.More(); anExp.Next()) {
140       GProp_GProps aGProps;
141       BRepGProp::VolumeProperties(anExp.Current(), aGProps, anEps);
142       aVolume += aGProps.Mass();
143     }
144     return aVolume;
145   }
146   // return surfaces area
147   GProp_GProps aGProps;
148   BRepGProp::SurfaceProperties(aShape, aGProps, anEps);
149   return aGProps.Mass();
150 }
151
152 //==================================================================================================
153 double GeomAlgoAPI_ShapeTools::area (const std::shared_ptr<GeomAPI_Shape> theShape)
154 {
155   GProp_GProps aGProps;
156   if(!theShape.get()) {
157     return 0.0;
158   }
159   const TopoDS_Shape& aShape = theShape->impl<TopoDS_Shape>();
160   if(aShape.IsNull()) {
161     return 0.0;
162   }
163   const Standard_Real anEps = 1.e-6;
164
165   BRepGProp::SurfaceProperties(aShape, aGProps, anEps);
166   return aGProps.Mass();
167 }
168
169 //==================================================================================================
170 std::shared_ptr<GeomAPI_Pnt>
171   GeomAlgoAPI_ShapeTools::centreOfMass(const std::shared_ptr<GeomAPI_Shape> theShape)
172 {
173   GProp_GProps aGProps;
174   if(!theShape) {
175     return std::shared_ptr<GeomAPI_Pnt>();
176   }
177   const TopoDS_Shape& aShape = theShape->impl<TopoDS_Shape>();
178   if(aShape.IsNull()) {
179     return std::shared_ptr<GeomAPI_Pnt>();
180   }
181   gp_Pnt aCentre;
182   if(aShape.ShapeType() == TopAbs_VERTEX) {
183     aCentre = BRep_Tool::Pnt(TopoDS::Vertex(aShape));
184   } else {
185     aGProps = props(aShape);
186     aCentre = aGProps.CentreOfMass();
187   }
188
189   return std::shared_ptr<GeomAPI_Pnt>(new GeomAPI_Pnt(aCentre.X(), aCentre.Y(), aCentre.Z()));
190 }
191
192 //==================================================================================================
193 double GeomAlgoAPI_ShapeTools::radius(const std::shared_ptr<GeomAPI_Face>& theCylinder)
194 {
195   double aRadius = -1.0;
196   if (theCylinder->isCylindrical()) {
197     const TopoDS_Shape& aShape = theCylinder->impl<TopoDS_Shape>();
198     Handle(Geom_Surface) aSurf = BRep_Tool::Surface(TopoDS::Face(aShape));
199     Handle(Geom_CylindricalSurface) aCyl = Handle(Geom_CylindricalSurface)::DownCast(aSurf);
200     if (!aCyl.IsNull())
201       aRadius = aCyl->Radius();
202   }
203   return aRadius;
204 }
205
206 //==================================================================================================
207 namespace {
208
209 auto getExtemaDistShape = [](const GeomShapePtr& theShape1,
210     const GeomShapePtr& theShape2) -> BRepExtrema_DistShapeShape
211 {
212   const TopoDS_Shape& aShape1 = theShape1->impl<TopoDS_Shape>();
213   const TopoDS_Shape& aShape2 = theShape2->impl<TopoDS_Shape>();
214
215   BRepExtrema_DistShapeShape aDist(aShape1, aShape2);
216   aDist.Perform();
217   return aDist;
218 };
219 }
220
221 double GeomAlgoAPI_ShapeTools::minimalDistance(const GeomShapePtr& theShape1,
222                                                const GeomShapePtr& theShape2)
223 {
224   BRepExtrema_DistShapeShape aDist = getExtemaDistShape(theShape1, theShape2);
225   return aDist.IsDone() ? aDist.Value() : Precision::Infinite();
226 }
227
228 double GeomAlgoAPI_ShapeTools::minimalDistance(const GeomShapePtr& theShape1,
229                                                const GeomShapePtr& theShape2,
230                                                std::array<double, 3> & fromShape1To2)
231 {
232   BRepExtrema_DistShapeShape aDist = getExtemaDistShape(theShape1, theShape2);
233   const auto & pt1 = aDist.PointOnShape1(1);
234   const auto & pt2 = aDist.PointOnShape2(1) ;
235   fromShape1To2[0] = pt2.X() - pt1.X();
236   fromShape1To2[1] = pt2.Y() - pt1.Y();
237   fromShape1To2[2] = pt2.Z() - pt1.Z();
238   return aDist.IsDone() ? aDist.Value() : Precision::Infinite();
239 }
240
241 //==================================================================================================
242 std::shared_ptr<GeomAPI_Shape> GeomAlgoAPI_ShapeTools::combineShapes(
243   const std::shared_ptr<GeomAPI_Shape> theCompound,
244   const GeomAPI_Shape::ShapeType theType,
245   ListOfShape& theResuts)
246 {
247
248   ListOfShape aResCombinedShapes;
249   ListOfShape aResFreeShapes;
250
251   GeomShapePtr aResult = theCompound;
252
253   if(!theCompound.get()) {
254     return aResult;
255   }
256
257   if(theType != GeomAPI_Shape::SHELL && theType != GeomAPI_Shape::COMPSOLID) {
258     return aResult;
259   }
260
261   TopAbs_ShapeEnum aTS = TopAbs_EDGE;
262   TopAbs_ShapeEnum aTA = TopAbs_FACE;
263   if(theType == GeomAPI_Shape::COMPSOLID) {
264     aTS = TopAbs_FACE;
265     aTA = TopAbs_SOLID;
266   }
267
268   // map from the resulting shapes to minimal index of the used shape from theCompound list
269   std::map<GeomShapePtr, int> anInputOrder;
270   // map from ancestors-shapes to the index of shapes in theCompound
271   NCollection_DataMap<TopoDS_Shape, int> anAncestorsOrder;
272
273   // Get free shapes.
274   int anOrder = 0;
275   const TopoDS_Shape& aShapesComp = theCompound->impl<TopoDS_Shape>();
276   for(TopoDS_Iterator anIter(aShapesComp); anIter.More(); anIter.Next(), anOrder++) {
277     const TopoDS_Shape& aShape = anIter.Value();
278     if(aShape.ShapeType() > aTA) {
279       std::shared_ptr<GeomAPI_Shape> aGeomShape(new GeomAPI_Shape);
280       aGeomShape->setImpl<TopoDS_Shape>(new TopoDS_Shape(aShape));
281       aResFreeShapes.push_back(aGeomShape);
282       anInputOrder[aGeomShape] = anOrder;
283     } else {
284       for(TopExp_Explorer anExp(aShape, aTA); anExp.More(); anExp.Next()) {
285         anAncestorsOrder.Bind(anExp.Current(), anOrder);
286       }
287     }
288   }
289
290   // Map sub-shapes and shapes.
291   TopTools_IndexedDataMapOfShapeListOfShape aMapSA;
292   TopExp::MapShapesAndAncestors(aShapesComp, aTS, aTA, aMapSA);
293   if(aMapSA.IsEmpty()) {
294     return aResult;
295   }
296   theResuts.clear();
297
298   // Get all shapes with common sub-shapes and free shapes.
299   NCollection_Map<TopoDS_Shape> aFreeShapes;
300   NCollection_Vector<NCollection_Map<TopoDS_Shape>> aShapesWithCommonSubshapes;
301   for(TopTools_IndexedDataMapOfShapeListOfShape::Iterator
302       anIter(aMapSA); anIter.More(); anIter.Next()) {
303     TopTools_ListOfShape& aListOfShape = anIter.ChangeValue();
304     if(aListOfShape.IsEmpty()) {
305       continue;
306     }
307     else if(aListOfShape.Size() == 1) {
308       const TopoDS_Shape& aF = aListOfShape.First();
309       aFreeShapes.Add(aF);
310       aListOfShape.Clear();
311     } else {
312       NCollection_List<TopoDS_Shape> aTempList;
313       NCollection_Map<TopoDS_Shape> aTempMap;
314       for (TopTools_ListOfShape::Iterator aListIt(aListOfShape); aListIt.More(); aListIt.Next()) {
315         aTempList.Append(aListIt.Value());
316         aTempMap.Add(aListIt.Value());
317         aFreeShapes.Remove(aListIt.Value());
318       }
319       aListOfShape.Clear();
320       for(NCollection_List<TopoDS_Shape>::Iterator
321           aTempIter(aTempList); aTempIter.More(); aTempIter.Next()) {
322         const TopoDS_Shape& aTempShape = aTempIter.Value();
323         for(TopTools_IndexedDataMapOfShapeListOfShape::Iterator
324             anIter2(aMapSA); anIter2.More(); anIter2.Next()) {
325           TopTools_ListOfShape& aTempListOfShape = anIter2.ChangeValue();
326           if(aTempListOfShape.IsEmpty()) {
327             continue;
328           } else if(aTempListOfShape.Size() == 1 && aTempListOfShape.First() == aTempShape) {
329             aTempListOfShape.Clear();
330           } else if(aTempListOfShape.Size() > 1) {
331             TopTools_ListOfShape::Iterator anIt1(aTempListOfShape);
332             for (; anIt1.More(); anIt1.Next()) {
333               if (anIt1.Value() == aTempShape) {
334                 TopTools_ListOfShape::Iterator anIt2(aTempListOfShape);
335                 for (; anIt2.More(); anIt2.Next())
336                 {
337                   if (anIt2.Value() != anIt1.Value()) {
338                     if (aTempMap.Add(anIt2.Value())) {
339                       aTempList.Append(anIt2.Value());
340                       aFreeShapes.Remove(anIt2.Value());
341                     }
342                   }
343                 }
344                 aTempListOfShape.Clear();
345                 break;
346               }
347             }
348           }
349         }
350       }
351       aShapesWithCommonSubshapes.Append(aTempMap);
352     }
353   }
354
355   // Combine shapes with common sub-shapes.
356   for(NCollection_Vector<NCollection_Map<TopoDS_Shape>>::Iterator
357       anIter(aShapesWithCommonSubshapes); anIter.More(); anIter.Next()) {
358     TopoDS_Shell aShell;
359     TopoDS_CompSolid aCSolid;
360     TopoDS_Builder aBuilder;
361     anOrder = -1;
362     theType ==
363       GeomAPI_Shape::COMPSOLID ? aBuilder.MakeCompSolid(aCSolid) : aBuilder.MakeShell(aShell);
364     NCollection_Map<TopoDS_Shape>& aShapesMap = anIter.ChangeValue();
365     for(TopExp_Explorer anExp(aShapesComp, aTA); anExp.More(); anExp.Next()) {
366       const TopoDS_Shape& aShape = anExp.Current();
367       if(aShapesMap.Contains(aShape)) {
368         theType ==
369           GeomAPI_Shape::COMPSOLID ? aBuilder.Add(aCSolid, aShape) : aBuilder.Add(aShell, aShape);
370         aShapesMap.Remove(aShape);
371         int aThisOrder = anAncestorsOrder.Find(aShape);
372         if (anOrder == -1 || aThisOrder < anOrder)
373           anOrder = aThisOrder; // take the minimum order position
374       }
375     }
376     std::shared_ptr<GeomAPI_Shape> aGeomShape(new GeomAPI_Shape);
377     TopoDS_Shape* aSh = theType == GeomAPI_Shape::COMPSOLID ? new TopoDS_Shape(aCSolid) :
378                                                               new TopoDS_Shape(aShell);
379     aGeomShape->setImpl<TopoDS_Shape>(aSh);
380     aResCombinedShapes.push_back(aGeomShape);
381     anInputOrder[aGeomShape] = anOrder;
382   }
383
384   // Adding free shapes.
385   for(TopExp_Explorer anExp(aShapesComp, aTA); anExp.More(); anExp.Next()) {
386     const TopoDS_Shape& aShape = anExp.Current();
387     if(aFreeShapes.Contains(aShape)) {
388       std::shared_ptr<GeomAPI_Shape> aGeomShape(new GeomAPI_Shape);
389       aGeomShape->setImpl<TopoDS_Shape>(new TopoDS_Shape(aShape));
390       aResFreeShapes.push_back(aGeomShape);
391       anInputOrder[aGeomShape] = anAncestorsOrder.Find(aShape);
392     }
393   }
394
395   if(aResCombinedShapes.size() == 1 && aResFreeShapes.size() == 0) {
396     aResult = aResCombinedShapes.front();
397     theResuts.push_back(aResult);
398   } else if(aResCombinedShapes.size() == 0 && aResFreeShapes.size() == 1) {
399     aResult = aResFreeShapes.front();
400     theResuts.push_back(aResult);
401   } else {
402     TopoDS_Compound aResultComp;
403     TopoDS_Builder aBuilder;
404     aBuilder.MakeCompound(aResultComp);
405     // put to result compound and result list in accordance to the order numbers
406     std::map<GeomShapePtr, int>::iterator anInputIter = anInputOrder.begin();
407     std::map<int, GeomShapePtr> aNums;
408     for(; anInputIter != anInputOrder.end(); anInputIter++)
409       aNums[anInputIter->second] = anInputIter->first;
410     std::map<int, GeomShapePtr>::iterator aNumsIter = aNums.begin();
411     for(; aNumsIter != aNums.end(); aNumsIter++) {
412       aBuilder.Add(aResultComp, (aNumsIter->second)->impl<TopoDS_Shape>());
413       theResuts.push_back(aNumsIter->second);
414     }
415     aResult->setImpl(new TopoDS_Shape(aResultComp));
416   }
417
418   return aResult;
419 }
420
421 //==================================================================================================
422 static void addSimpleShapeToList(const TopoDS_Shape& theShape,
423                                  NCollection_List<TopoDS_Shape>& theList)
424 {
425   if(theShape.IsNull()) {
426     return;
427   }
428
429   if(theShape.ShapeType() == TopAbs_COMPOUND) {
430     for(TopoDS_Iterator anIt(theShape); anIt.More(); anIt.Next()) {
431       addSimpleShapeToList(anIt.Value(), theList);
432     }
433   } else {
434     theList.Append(theShape);
435   }
436 }
437
438 //==================================================================================================
439 static TopoDS_Compound makeCompound(const NCollection_List<TopoDS_Shape> theShapes)
440 {
441   TopoDS_Compound aCompound;
442
443   BRep_Builder aBuilder;
444   aBuilder.MakeCompound(aCompound);
445
446   for(NCollection_List<TopoDS_Shape>::Iterator anIt(theShapes); anIt.More(); anIt.Next()) {
447     aBuilder.Add(aCompound, anIt.Value());
448   }
449
450   return aCompound;
451 }
452
453 //==================================================================================================
454 std::shared_ptr<GeomAPI_Shape> GeomAlgoAPI_ShapeTools::groupSharedTopology(
455   const std::shared_ptr<GeomAPI_Shape> theCompound)
456 {
457   GeomShapePtr aResult = theCompound;
458
459   if (!theCompound.get()) {
460     return aResult;
461   }
462
463   TopoDS_Shape anInShape = aResult->impl<TopoDS_Shape>();
464   NCollection_List<TopoDS_Shape> anUngroupedShapes, aStillUngroupedShapes;
465   addSimpleShapeToList(anInShape, anUngroupedShapes);
466
467   // Iterate over all shapes and find shapes with shared vertices.
468   TopTools_ListOfShape allVertices;
469   TopTools_DataMapOfShapeListOfShape aVertexShapesMap;
470   for (NCollection_List<TopoDS_Shape>::Iterator aShapesIt(anUngroupedShapes);
471     aShapesIt.More();
472     aShapesIt.Next()) {
473     const TopoDS_Shape& aShape = aShapesIt.Value();
474     for (TopExp_Explorer aShapeExp(aShape, TopAbs_VERTEX);
475       aShapeExp.More();
476       aShapeExp.Next()) {
477       const TopoDS_Shape& aVertex = aShapeExp.Current();
478       if (!aVertexShapesMap.IsBound(aVertex)) {
479         NCollection_List<TopoDS_Shape> aList;
480         aList.Append(aShape);
481         allVertices.Append(aVertex);
482         aVertexShapesMap.Bind(aVertex, aList);
483       }
484       else {
485         if (!aVertexShapesMap.ChangeFind(aVertex).Contains(aShape)) {
486           aVertexShapesMap.ChangeFind(aVertex).Append(aShape);
487         }
488       }
489     }
490   }
491
492   // Iterate over the map and group shapes.
493   NCollection_Vector<TopTools_MapOfShape> aGroups; // groups of shapes connected by vertices
494   while (!allVertices.IsEmpty()) {
495     // Get first group of shapes in map, and then unbind it.
496     const TopoDS_Shape& aKey = allVertices.First();
497     TopTools_ListOfShape aConnectedShapes = aVertexShapesMap.Find(aKey);
498     aVertexShapesMap.UnBind(aKey);
499     allVertices.Remove(aKey);
500     // Iterate over shapes in this group and add to it shapes from groups in map.
501     for (TopTools_ListOfShape::Iterator aConnectedIt(aConnectedShapes);
502       aConnectedIt.More(); aConnectedIt.Next()) {
503       const TopoDS_Shape& aConnected = aConnectedIt.Value();
504       TopTools_ListOfShape aKeysToUnbind;
505       for (TopTools_ListOfShape::Iterator aKeysIt(allVertices);
506         aKeysIt.More();
507         aKeysIt.Next()) {
508         const TopTools_ListOfShape& anOtherConnected = aVertexShapesMap(aKeysIt.Value());
509         if (!anOtherConnected.Contains(aConnected)) {
510           // Other connected group does not contain shape from our connected group
511           continue;
512         }
513         // Other is connected to our, so add them to our connected
514         for (TopTools_ListOfShape::Iterator anOtherIt(anOtherConnected);
515           anOtherIt.More();
516           anOtherIt.Next()) {
517           const TopoDS_Shape& aShape = anOtherIt.Value();
518           if (!aConnectedShapes.Contains(aShape)) {
519             aConnectedShapes.Append(aShape);
520           }
521         }
522         // Save key to unbind from this map.
523         aKeysToUnbind.Append(aKeysIt.Value());
524       }
525       // Unbind groups from map that we added to our group.
526       for (TopTools_ListOfShape::Iterator aKeysIt(aKeysToUnbind);
527         aKeysIt.More();
528         aKeysIt.Next()) {
529         aVertexShapesMap.UnBind(aKeysIt.Value());
530         allVertices.Remove(aKeysIt.Value());
531       }
532     }
533     // Sort shapes from the most complicated to the simplest ones
534     TopTools_MapOfShape aSortedGroup;
535     for (int aST = TopAbs_COMPOUND; aST <= TopAbs_SHAPE; ++aST) {
536       TopTools_ListOfShape::Iterator anIt(aConnectedShapes);
537       while (anIt.More()) {
538         if (anIt.Value().ShapeType() == aST) {
539           aSortedGroup.Add(anIt.Value());
540           aConnectedShapes.Remove(anIt);
541         }
542         else {
543           anIt.Next();
544         }
545       }
546     }
547     aGroups.Append(aSortedGroup);
548   }
549
550   TopoDS_Compound aCompound;
551   BRep_Builder aBuilder;
552   aBuilder.MakeCompound(aCompound);
553   ListOfShape aSolids;
554   for (NCollection_Vector<TopTools_MapOfShape>::Iterator anIt(aGroups); anIt.More(); anIt.Next()) {
555     const TopTools_MapOfShape& aGroup = anIt.ChangeValue();
556     GeomShapePtr aGeomShape(new GeomAPI_Shape());
557     if(aGroup.Size() == 1) {
558       TopTools_MapOfShape::Iterator aOneShapeIter(aGroup);
559       aGeomShape->setImpl(new TopoDS_Shape(aOneShapeIter.Value()));
560     } else {
561       // make sub-shapes in the group have order same as in original shape
562       TopTools_ListOfShape anOrderedGoup;
563       NCollection_List<TopoDS_Shape>::Iterator anUngrouped(anUngroupedShapes);
564       for (; anUngrouped.More(); anUngrouped.Next()) {
565         if (aGroup.Contains(anUngrouped.Value()))
566           anOrderedGoup.Append(anUngrouped.Value());
567       }
568       aGeomShape->setImpl(new TopoDS_Shape(makeCompound(anOrderedGoup)));
569       aGeomShape = GeomAlgoAPI_ShapeTools::combineShapes(aGeomShape,
570                                                          GeomAPI_Shape::COMPSOLID,
571                                                          aSolids);
572     }
573     aBuilder.Add(aCompound, aGeomShape->impl<TopoDS_Shape>());
574   }
575
576   if(!aCompound.IsNull()) {
577     aResult->setImpl(new TopoDS_Shape(aCompound));
578   }
579
580   return aResult;
581 }
582
583 //==================================================================================================
584 bool GeomAlgoAPI_ShapeTools::hasSharedTopology(const ListOfShape& theShapes,
585                                                const GeomAPI_Shape::ShapeType theShapeType)
586 {
587   TopTools_IndexedMapOfShape aSubs;
588   for (ListOfShape::const_iterator anIt = theShapes.begin(); anIt != theShapes.end(); ++anIt) {
589     TopTools_IndexedMapOfShape aCurSubs;
590     TopExp::MapShapes((*anIt)->impl<TopoDS_Shape>(), (TopAbs_ShapeEnum)theShapeType, aCurSubs);
591     for (TopTools_IndexedMapOfShape::Iterator aSubIt(aCurSubs); aSubIt.More(); aSubIt.Next()) {
592       if (aSubs.Contains(aSubIt.Value()))
593         return true;
594       else
595         aSubs.Add(aSubIt.Value());
596     }
597   }
598   return false;
599 }
600
601 //==================================================================================================
602 std::list<std::shared_ptr<GeomAPI_Pnt> >
603   GeomAlgoAPI_ShapeTools::getBoundingBox(const ListOfShape& theShapes, const double theEnlarge)
604 {
605   // Bounding box of all objects.
606   Bnd_Box aBndBox;
607
608   // Getting box.
609   for (ListOfShape::const_iterator
610     anObjectsIt = theShapes.begin(); anObjectsIt != theShapes.end(); anObjectsIt++) {
611     const TopoDS_Shape& aShape = (*anObjectsIt)->impl<TopoDS_Shape>();
612     BRepBndLib::Add(aShape, aBndBox);
613   }
614
615   if(theEnlarge != 0.0) {
616     // We enlarge bounding box just to be sure that plane will be large enough to cut all objects.
617     aBndBox.Enlarge(theEnlarge);
618   }
619
620   Standard_Real aXArr[2] = {aBndBox.CornerMin().X(), aBndBox.CornerMax().X()};
621   Standard_Real aYArr[2] = {aBndBox.CornerMin().Y(), aBndBox.CornerMax().Y()};
622   Standard_Real aZArr[2] = {aBndBox.CornerMin().Z(), aBndBox.CornerMax().Z()};
623   std::list<std::shared_ptr<GeomAPI_Pnt> > aResultPoints;
624   for(int i = 0; i < 2; i++) {
625     for(int j = 0; j < 2; j++) {
626       for(int k = 0; k < 2; k++) {
627         std::shared_ptr<GeomAPI_Pnt> aPnt(new GeomAPI_Pnt(aXArr[i], aYArr[j], aZArr[k]));
628         aResultPoints.push_back(aPnt);
629       }
630     }
631   }
632
633   return aResultPoints;
634 }
635
636 //==================================================================================================
637 std::shared_ptr<GeomAPI_Face> GeomAlgoAPI_ShapeTools::fitPlaneToBox(
638   const std::shared_ptr<GeomAPI_Shape> thePlane,
639   const std::list<std::shared_ptr<GeomAPI_Pnt> >& thePoints)
640 {
641   std::shared_ptr<GeomAPI_Face> aResultFace;
642
643   if(!thePlane.get()) {
644     return aResultFace;
645   }
646
647   const TopoDS_Shape& aShape = thePlane->impl<TopoDS_Shape>();
648   if(aShape.ShapeType() != TopAbs_FACE) {
649     return aResultFace;
650   }
651
652   TopoDS_Face aFace = TopoDS::Face(aShape);
653   Handle(Geom_Surface) aSurf = BRep_Tool::Surface(aFace);
654   if(aSurf.IsNull()) {
655     return aResultFace;
656   }
657
658   GeomLib_IsPlanarSurface isPlanar(aSurf);
659   if(!isPlanar.IsPlanar()) {
660     return aResultFace;
661   }
662
663   if(thePoints.size() != 8) {
664     return aResultFace;
665   }
666
667   const gp_Pln& aFacePln = isPlanar.Plan();
668   Handle(Geom_Plane) aFacePlane = new Geom_Plane(aFacePln);
669   IntAna_Quadric aQuadric(aFacePln);
670   Standard_Real UMin, UMax, VMin, VMax;
671   UMin = UMax = VMin = VMax = 0;
672   for (std::list<std::shared_ptr<GeomAPI_Pnt> >::const_iterator
673        aPointsIt = thePoints.begin(); aPointsIt != thePoints.end(); aPointsIt++) {
674     const gp_Pnt& aPnt = (*aPointsIt)->impl<gp_Pnt>();
675     gp_Lin aLin(aPnt, aFacePln.Axis().Direction());
676     IntAna_IntConicQuad anIntAna(aLin, aQuadric);
677     const gp_Pnt& aPntOnFace = anIntAna.Point(1);
678     Standard_Real aPntU(0), aPntV(0);
679     GeomLib_Tool::Parameters(aFacePlane, aPntOnFace, Precision::Confusion(), aPntU, aPntV);
680     if(aPntU < UMin) UMin = aPntU;
681     if(aPntU > UMax) UMax = aPntU;
682     if(aPntV < VMin) VMin = aPntV;
683     if(aPntV > VMax) VMax = aPntV;
684   }
685   aResultFace.reset(new GeomAPI_Face());
686   aResultFace->setImpl(new TopoDS_Face(BRepLib_MakeFace(aFacePln, UMin, UMax, VMin, VMax).Face()));
687
688   return aResultFace;
689 }
690
691 //==================================================================================================
692 void GeomAlgoAPI_ShapeTools::findBounds(const std::shared_ptr<GeomAPI_Shape> theShape,
693                                         std::shared_ptr<GeomAPI_Vertex>& theV1,
694                                         std::shared_ptr<GeomAPI_Vertex>& theV2)
695 {
696   static GeomVertexPtr aVertex;
697   if (!aVertex) {
698     aVertex = GeomVertexPtr(new GeomAPI_Vertex);
699     aVertex->setImpl(new TopoDS_Vertex());
700   }
701
702   theV1 = aVertex;
703   theV2 = aVertex;
704
705   if (theShape) {
706     const TopoDS_Shape& aShape = theShape->impl<TopoDS_Shape>();
707     TopoDS_Vertex aV1, aV2;
708     ShapeAnalysis::FindBounds(aShape, aV1, aV2);
709
710     std::shared_ptr<GeomAPI_Vertex> aGeomV1(new GeomAPI_Vertex()), aGeomV2(new GeomAPI_Vertex());
711     aGeomV1->setImpl(new TopoDS_Vertex(aV1));
712     aGeomV2->setImpl(new TopoDS_Vertex(aV2));
713     theV1 = aGeomV1;
714     theV2 = aGeomV2;
715   }
716 }
717
718 //==================================================================================================
719 void GeomAlgoAPI_ShapeTools::makeFacesWithHoles(const std::shared_ptr<GeomAPI_Pnt> theOrigin,
720                                                 const std::shared_ptr<GeomAPI_Dir> theDirection,
721                                                 const ListOfShape& theWires,
722                                                 ListOfShape& theFaces)
723 {
724   BRepBuilderAPI_MakeFace aMKFace(gp_Pln(theOrigin->impl<gp_Pnt>(),
725                                           theDirection->impl<gp_Dir>()));
726   TopoDS_Face aFace = aMKFace.Face();
727
728   BRepAlgo_FaceRestrictor aFRestrictor;
729   aFRestrictor.Init(aFace, Standard_False, Standard_True);
730   for(ListOfShape::const_iterator anIt = theWires.cbegin();
731       anIt != theWires.cend();
732       ++anIt) {
733     TopoDS_Wire aWire = TopoDS::Wire((*anIt)->impl<TopoDS_Shape>());
734     aFRestrictor.Add(aWire);
735   }
736
737   aFRestrictor.Perform();
738
739   if(!aFRestrictor.IsDone()) {
740     return;
741   }
742
743   for(; aFRestrictor.More(); aFRestrictor.Next()) {
744     GeomShapePtr aShape(new GeomAPI_Shape());
745     aShape->setImpl(new TopoDS_Shape(aFRestrictor.Current()));
746     theFaces.push_back(aShape);
747   }
748 }
749
750 //==================================================================================================
751 std::shared_ptr<GeomAPI_Pln> GeomAlgoAPI_ShapeTools::findPlane(const ListOfShape& theShapes)
752 {
753   TopoDS_Compound aCompound;
754   BRep_Builder aBuilder;
755   aBuilder.MakeCompound(aCompound);
756
757   for(ListOfShape::const_iterator anIt = theShapes.cbegin(); anIt != theShapes.cend(); ++anIt) {
758     aBuilder.Add(aCompound, (*anIt)->impl<TopoDS_Shape>());
759   }
760   BRepBuilderAPI_FindPlane aFindPlane(aCompound);
761
762   if(aFindPlane.Found() != Standard_True) {
763     return std::shared_ptr<GeomAPI_Pln>();
764   }
765
766   Handle(Geom_Plane) aPlane = aFindPlane.Plane();
767   gp_Pnt aLoc = aPlane->Location();
768   gp_Dir aDir = aPlane->Axis().Direction();
769
770   std::shared_ptr<GeomAPI_Pnt> aGeomPnt(new GeomAPI_Pnt(aLoc.X(), aLoc.Y(), aLoc.Z()));
771   std::shared_ptr<GeomAPI_Dir> aGeomDir(new GeomAPI_Dir(aDir.X(), aDir.Y(), aDir.Z()));
772
773   std::shared_ptr<GeomAPI_Pln> aPln(new GeomAPI_Pln(aGeomPnt, aGeomDir));
774
775   return aPln;
776 }
777
778 //==================================================================================================
779 bool GeomAlgoAPI_ShapeTools::isSubShapeInsideShape(
780   const std::shared_ptr<GeomAPI_Shape> theSubShape,
781   const std::shared_ptr<GeomAPI_Shape> theBaseShape)
782 {
783   if(!theSubShape.get() || !theBaseShape.get()) {
784     return false;
785   }
786
787   const TopoDS_Shape& aSubShape = theSubShape->impl<TopoDS_Shape>();
788   const TopoDS_Shape& aBaseShape = theBaseShape->impl<TopoDS_Shape>();
789
790   if(aSubShape.ShapeType() == TopAbs_VERTEX) {
791     // If sub-shape is a vertex check distance to shape. If it is <= Precision::Confusion() then OK.
792     BRepExtrema_DistShapeShape aDist(aBaseShape, aSubShape);
793     aDist.Perform();
794     if(!aDist.IsDone() || aDist.Value() > Precision::Confusion()) {
795       return false;
796     }
797   } else if (aSubShape.ShapeType() == TopAbs_EDGE) {
798     if(aBaseShape.ShapeType() == TopAbs_FACE) {
799       // Check that edge is on face surface.
800       TopoDS_Face aFace = TopoDS::Face(aBaseShape);
801       TopoDS_Edge anEdge = TopoDS::Edge(aSubShape);
802       BRepLib_CheckCurveOnSurface aCheck(anEdge, aFace);
803       aCheck.Perform();
804       if(!aCheck.IsDone() || aCheck.MaxDistance() > Precision::Confusion()) {
805         return false;
806       }
807
808       // Check intersections.
809       TopoDS_Vertex aV1, aV2;
810       ShapeAnalysis::FindBounds(anEdge, aV1, aV2);
811       gp_Pnt aPnt1 = BRep_Tool::Pnt(aV1);
812       gp_Pnt aPnt2 = BRep_Tool::Pnt(aV2);
813       for(TopExp_Explorer anExp(aBaseShape, TopAbs_EDGE); anExp.More(); anExp.Next()) {
814         const TopoDS_Shape& anEdgeOnFace = anExp.Current();
815         BRepExtrema_DistShapeShape aDist(anEdgeOnFace, anEdge);
816         aDist.Perform();
817         if(aDist.IsDone() && aDist.Value() <= Precision::Confusion()) {
818           // Edge intersect face bound. Check that it is not on edge begin or end.
819           for(Standard_Integer anIndex = 1; anIndex <= aDist.NbSolution(); ++anIndex) {
820             gp_Pnt aPntOnSubShape = aDist.PointOnShape2(anIndex);
821             if(aPntOnSubShape.Distance(aPnt1) > Precision::Confusion()
822                 && aPntOnSubShape.Distance(aPnt2) > Precision::Confusion()) {
823               return false;
824             }
825           }
826         }
827       }
828
829       // No intersections found. Edge is inside or outside face. Check it.
830       BRepAdaptor_Curve aCurveAdaptor(anEdge);
831       gp_Pnt aPointToCheck =
832         aCurveAdaptor.Value((aCurveAdaptor.FirstParameter() +
833                               aCurveAdaptor.LastParameter()) / 2.0);
834       Handle(Geom_Surface) aSurface = BRep_Tool::Surface(aFace);
835       ShapeAnalysis_Surface aSAS(aSurface);
836       gp_Pnt2d aPointOnFace = aSAS.ValueOfUV(aPointToCheck, Precision::Confusion());
837       BRepTopAdaptor_FClass2d aFClass2d(aFace, Precision::Confusion());
838       if(aFClass2d.Perform(aPointOnFace) == TopAbs_OUT) {
839         return false;
840       }
841
842     } else {
843       return false;
844     }
845   } else {
846     return false;
847   }
848
849   return true;
850 }
851
852 //==================================================================================================
853 bool GeomAlgoAPI_ShapeTools::isShapeValid(const std::shared_ptr<GeomAPI_Shape> theShape)
854 {
855   if(!theShape.get()) {
856     return false;
857   }
858
859   BRepCheck_Analyzer aChecker(theShape->impl<TopoDS_Shape>());
860   return (aChecker.IsValid() == Standard_True);
861 }
862
863 //==================================================================================================
864 std::shared_ptr<GeomAPI_Shape>
865   GeomAlgoAPI_ShapeTools::getFaceOuterWire(const std::shared_ptr<GeomAPI_Shape> theFace)
866 {
867   GeomShapePtr anOuterWire;
868
869   if(!theFace.get() || !theFace->isFace()) {
870     return anOuterWire;
871   }
872
873   TopoDS_Face aFace = TopoDS::Face(theFace->impl<TopoDS_Shape>());
874   TopoDS_Wire aWire = BRepTools::OuterWire(aFace);
875
876   anOuterWire.reset(new GeomAPI_Shape());
877   anOuterWire->setImpl(new TopoDS_Shape(aWire));
878
879   return anOuterWire;
880 }
881
882 //==================================================================================================
883 static bool boundaryOfEdge(const std::shared_ptr<GeomAPI_Edge> theEdge,
884                           const std::shared_ptr<GeomAPI_Vertex> theVertex,
885                           double& theParam)
886 {
887   GeomPointPtr aPoint = theVertex->point();
888   GeomPointPtr aFirstPnt = theEdge->firstPoint();
889   double aFirstPntTol = theEdge->firstPointTolerance();
890   GeomPointPtr aLastPnt = theEdge->lastPoint();
891   double aLastPntTol = theEdge->lastPointTolerance();
892
893   double aFirst, aLast;
894   theEdge->getRange(aFirst, aLast);
895
896   bool isFirst = aPoint->distance(aFirstPnt) <= aFirstPntTol;
897   bool isLast = aPoint->distance(aLastPnt) <= aLastPntTol;
898   if (isFirst)
899     theParam = aFirst;
900   else if (isLast)
901     theParam = aLast;
902
903   return isFirst != isLast;
904 }
905
906 bool GeomAlgoAPI_ShapeTools::isTangent(const std::shared_ptr<GeomAPI_Edge> theEdge1,
907                                        const std::shared_ptr<GeomAPI_Edge> theEdge2,
908                                        const std::shared_ptr<GeomAPI_Vertex> theTgPoint)
909 {
910   double aParE1 = 0, aParE2 = 0;
911   if (!boundaryOfEdge(theEdge1, theTgPoint, aParE1) ||
912       !boundaryOfEdge(theEdge2, theTgPoint, aParE2))
913     return false;
914
915   BRepAdaptor_Curve aC1(theEdge1->impl<TopoDS_Edge>());
916   BRepAdaptor_Curve aC2(theEdge2->impl<TopoDS_Edge>());
917   return BRepLProp::Continuity(aC1, aC2, aParE1, aParE2) >= GeomAbs_G1;
918 }
919
920 //==================================================================================================
921 bool GeomAlgoAPI_ShapeTools::isParallel(const std::shared_ptr<GeomAPI_Edge> theEdge,
922                                         const std::shared_ptr<GeomAPI_Face> theFace)
923 {
924   if(!theEdge.get() || !theFace.get()) {
925     return false;
926   }
927
928   TopoDS_Edge anEdge = TopoDS::Edge(theEdge->impl<TopoDS_Shape>());
929   TopoDS_Face aFace  = TopoDS::Face(theFace->impl<TopoDS_Shape>());
930
931   BRepExtrema_ExtCF anExt(anEdge, aFace);
932   return anExt.IsParallel() == Standard_True;
933 }
934
935 //==================================================================================================
936 std::list<std::shared_ptr<GeomAPI_Vertex> > GeomAlgoAPI_ShapeTools::intersect(
937   const std::shared_ptr<GeomAPI_Edge> theEdge, const std::shared_ptr<GeomAPI_Face> theFace)
938 {
939   std::list<std::shared_ptr<GeomAPI_Vertex> > aResult;
940   if(!theEdge.get() || !theFace.get()) {
941     return aResult;
942   }
943
944   TopoDS_Edge anEdge = TopoDS::Edge(theEdge->impl<TopoDS_Shape>());
945   double aFirstOnCurve, aLastOnCurve;
946   Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirstOnCurve, aLastOnCurve);
947
948   TopoDS_Face aFace  = TopoDS::Face(theFace->impl<TopoDS_Shape>());
949   Handle(Geom_Surface) aSurf = BRep_Tool::Surface(aFace);
950
951   GeomAPI_IntCS anIntAlgo(aCurve, aSurf);
952   if (!anIntAlgo.IsDone())
953     return aResult;
954   // searching for points-intersection
955   for(int anIntNum = 1; anIntNum <= anIntAlgo.NbPoints() + anIntAlgo.NbSegments(); anIntNum++) {
956     gp_Pnt anInt;
957     if (anIntNum <= anIntAlgo.NbPoints()) {
958       anInt = anIntAlgo.Point(anIntNum);
959     } else { // take the middle point on the segment of the intersection
960       Handle(Geom_Curve) anIntCurve = anIntAlgo.Segment(anIntNum - anIntAlgo.NbPoints());
961       anIntCurve->D0((anIntCurve->FirstParameter() + anIntCurve->LastParameter()) / 2., anInt);
962     }
963     aResult.push_back(std::shared_ptr<GeomAPI_Vertex>(
964       new GeomAPI_Vertex(anInt.X(), anInt.Y(), anInt.Z())));
965   }
966   return aResult;
967 }
968
969 //==================================================================================================
970 void GeomAlgoAPI_ShapeTools::splitShape(const std::shared_ptr<GeomAPI_Shape>& theBaseShape,
971                                       const GeomAlgoAPI_ShapeTools::PointToRefsMap& thePointsInfo,
972                                       std::set<std::shared_ptr<GeomAPI_Shape> >& theShapes)
973 {
974   // to split shape at least one point should be presented in the points container
975   if (thePointsInfo.empty())
976     return;
977
978     // General Fuse to split edge by vertices
979   BOPAlgo_Builder aBOP;
980   TopoDS_Edge aBaseEdge = theBaseShape->impl<TopoDS_Edge>();
981   // Rebuild closed edge to place vertex to one of split points.
982   // This will prevent edge to be split on same vertex.
983   if (BRep_Tool::IsClosed(aBaseEdge))
984   {
985     Standard_Real aFirst, aLast;
986     Handle(Geom_Curve) aCurve = BRep_Tool::Curve(aBaseEdge, aFirst, aLast);
987
988     PointToRefsMap::const_iterator aPIt = thePointsInfo.begin();
989     std::shared_ptr<GeomAPI_Pnt> aPnt = aPIt->first;
990     gp_Pnt aPoint(aPnt->x(), aPnt->y(), aPnt->z());
991
992     TopAbs_Orientation anOrientation = aBaseEdge.Orientation();
993     aBaseEdge = BRepBuilderAPI_MakeEdge(aCurve, aPoint, aPoint).Edge();
994     aBaseEdge.Orientation(anOrientation);
995   }
996   aBOP.AddArgument(aBaseEdge);
997
998   PointToRefsMap::const_iterator aPIt = thePointsInfo.begin();
999   for (; aPIt != thePointsInfo.end(); ++aPIt) {
1000     std::shared_ptr<GeomAPI_Pnt> aPnt = aPIt->first;
1001     TopoDS_Vertex aV = BRepBuilderAPI_MakeVertex(gp_Pnt(aPnt->x(), aPnt->y(), aPnt->z()));
1002     aBOP.AddArgument(aV);
1003   }
1004
1005   aBOP.Perform();
1006   if (aBOP.HasErrors())
1007     return;
1008
1009   // Collect splits
1010   const TopTools_ListOfShape& aSplits = aBOP.Modified(aBaseEdge);
1011   TopTools_ListIteratorOfListOfShape anIt(aSplits);
1012   for (; anIt.More(); anIt.Next()) {
1013     std::shared_ptr<GeomAPI_Shape> anEdge(new GeomAPI_Shape);
1014     anEdge->setImpl(new TopoDS_Shape(anIt.Value()));
1015     theShapes.insert(anEdge);
1016   }
1017 }
1018
1019 //==================================================================================================
1020 void GeomAlgoAPI_ShapeTools::splitShape_p(const std::shared_ptr<GeomAPI_Shape>& theBaseShape,
1021                                           const std::list<std::shared_ptr<GeomAPI_Pnt> >& thePoints,
1022                                           std::set<std::shared_ptr<GeomAPI_Shape> >& theShapes)
1023 {
1024   // General Fuse to split edge by vertices
1025   BOPAlgo_Builder aBOP;
1026   TopoDS_Edge aBaseEdge = theBaseShape->impl<TopoDS_Edge>();
1027   // Rebuild closed edge to place vertex to one of split points.
1028   // This will prevent edge to be split on seam vertex.
1029   if (BRep_Tool::IsClosed(aBaseEdge))
1030   {
1031     Standard_Real aFirst, aLast;
1032     Handle(Geom_Curve) aCurve = BRep_Tool::Curve(aBaseEdge, aFirst, aLast);
1033
1034     std::list<std::shared_ptr<GeomAPI_Pnt> >::const_iterator aPIt = thePoints.begin();
1035     gp_Pnt aPoint((*aPIt)->x(), (*aPIt)->y(), (*aPIt)->z());
1036
1037     TopAbs_Orientation anOrientation = aBaseEdge.Orientation();
1038     aBaseEdge = BRepBuilderAPI_MakeEdge(aCurve, aPoint, aPoint).Edge();
1039     aBaseEdge.Orientation(anOrientation);
1040   }
1041   aBOP.AddArgument(aBaseEdge);
1042
1043   std::list<std::shared_ptr<GeomAPI_Pnt> >::const_iterator aPtIt = thePoints.begin();
1044   for (; aPtIt != thePoints.end(); ++aPtIt) {
1045     std::shared_ptr<GeomAPI_Pnt> aPnt = *aPtIt;
1046     TopoDS_Vertex aV = BRepBuilderAPI_MakeVertex(gp_Pnt(aPnt->x(), aPnt->y(), aPnt->z()));
1047     aBOP.AddArgument(aV);
1048   }
1049
1050   aBOP.Perform();
1051   if (aBOP.HasErrors())
1052     return;
1053
1054   // Collect splits
1055   const TopTools_ListOfShape& aSplits = aBOP.Modified(aBaseEdge);
1056   TopTools_ListIteratorOfListOfShape anIt(aSplits);
1057   for (; anIt.More(); anIt.Next()) {
1058     std::shared_ptr<GeomAPI_Shape> anEdge(new GeomAPI_Shape);
1059     anEdge->setImpl(new TopoDS_Shape(anIt.Value()));
1060     theShapes.insert(anEdge);
1061   }
1062 }
1063
1064 //==================================================================================================
1065 std::shared_ptr<GeomAPI_Shape> GeomAlgoAPI_ShapeTools::findShape(
1066                                   const std::list<std::shared_ptr<GeomAPI_Pnt> >& thePoints,
1067                                   const std::set<std::shared_ptr<GeomAPI_Shape> >& theShapes)
1068 {
1069   std::shared_ptr<GeomAPI_Shape> aResultShape;
1070
1071   if (thePoints.size() == 2) {
1072     std::list<std::shared_ptr<GeomAPI_Pnt> >::const_iterator aPntIt = thePoints.begin();
1073     std::shared_ptr<GeomAPI_Pnt> aFirstPoint = *aPntIt;
1074     aPntIt++;
1075     std::shared_ptr<GeomAPI_Pnt> aLastPoint = *aPntIt;
1076
1077     std::set<std::shared_ptr<GeomAPI_Shape> >::const_iterator anIt = theShapes.begin(),
1078                                                               aLast = theShapes.end();
1079     for (; anIt != aLast; anIt++) {
1080       GeomShapePtr aShape = *anIt;
1081       std::shared_ptr<GeomAPI_Edge> anEdge(new GeomAPI_Edge(aShape));
1082       if (anEdge.get()) {
1083         std::shared_ptr<GeomAPI_Pnt> anEdgeFirstPoint = anEdge->firstPoint();
1084         std::shared_ptr<GeomAPI_Pnt> anEdgeLastPoint = anEdge->lastPoint();
1085         if (anEdgeFirstPoint->isEqual(aFirstPoint) &&
1086             anEdgeLastPoint->isEqual(aLastPoint))
1087             aResultShape = aShape;
1088       }
1089     }
1090   }
1091
1092   return aResultShape;
1093 }
1094
1095 //==================================================================================================
1096 #ifdef FEATURE_MULTIROTATION_TWO_DIRECTIONS
1097 std::shared_ptr<GeomAPI_Dir> GeomAlgoAPI_ShapeTools::buildDirFromAxisAndShape(
1098                                     const std::shared_ptr<GeomAPI_Shape> theBaseShape,
1099                                     const std::shared_ptr<GeomAPI_Ax1> theAxis)
1100 {
1101   gp_Pnt aCentreOfMassPoint =
1102     GeomAlgoAPI_ShapeTools::centreOfMass(theBaseShape)->impl<gp_Pnt>();
1103   Handle(Geom_Line) aLine = new Geom_Line(theAxis->impl<gp_Ax1>());
1104   GeomAPI_ProjectPointOnCurve aPrjTool(aCentreOfMassPoint, aLine);
1105   gp_Pnt aPoint = aPrjTool.NearestPoint();
1106
1107   std::shared_ptr<GeomAPI_Dir> aDir(new GeomAPI_Dir(aCentreOfMassPoint.X()-aPoint.X(),
1108                                                     aCentreOfMassPoint.Y()-aPoint.Y(),
1109                                                     aCentreOfMassPoint.Z()-aPoint.Z()));
1110   return aDir;
1111 }
1112 #endif
1113
1114 //==================================================================================================
1115 static TopoDS_Wire fixParametricGaps(const TopoDS_Wire& theWire)
1116 {
1117   TopoDS_Wire aFixedWire;
1118   Handle(Geom_Curve) aPrevCurve;
1119   double aPrevLastParam = -Precision::Infinite();
1120
1121   BRep_Builder aBuilder;
1122   aBuilder.MakeWire(aFixedWire);
1123
1124   BRepTools_WireExplorer aWExp(theWire);
1125   for (; aWExp.More(); aWExp.Next()) {
1126     TopoDS_Edge anEdge = aWExp.Current();
1127     double aFirst, aLast;
1128     Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
1129     if (aCurve == aPrevCurve && Abs(aFirst - aPrevLastParam) > Precision::Confusion()) {
1130       // if parametric gap occurs, create new edge based on the copied curve
1131       aCurve = Handle(Geom_Curve)::DownCast(aCurve->Copy());
1132       TopoDS_Vertex aV1, aV2;
1133       TopExp::Vertices(anEdge, aV1, aV2);
1134       anEdge = TopoDS::Edge(anEdge.EmptyCopied());
1135       aBuilder.UpdateEdge(anEdge, aCurve, BRep_Tool::Tolerance(anEdge));
1136       aBuilder.Add(anEdge, aV1);
1137       aBuilder.Add(anEdge, aV2);
1138     }
1139
1140     aBuilder.Add(aFixedWire, anEdge);
1141
1142     aPrevCurve = aCurve;
1143     aPrevLastParam = aLast;
1144   }
1145
1146   return aFixedWire;
1147 }
1148
1149 //==================================================================================================
1150 std::shared_ptr<GeomAPI_Edge> GeomAlgoAPI_ShapeTools::wireToEdge(
1151       const std::shared_ptr<GeomAPI_Wire>& theWire)
1152 {
1153   GeomEdgePtr anEdge;
1154   if (theWire) {
1155     TopoDS_Wire aWire = theWire->impl<TopoDS_Wire>();
1156     BRepTools_WireExplorer aWExp(aWire);
1157     TopoDS_Edge aNewEdge = aWExp.Current();
1158     aWExp.Next();
1159     if (aWExp.More()) {
1160       // Workaround: when concatenate a wire consisting of two edges based on the same B-spline
1161       // curve (non-periodic, but having equal start and end points), first of which is placed
1162       // at the end on the curve and second is placed at the start, this workaround copies
1163       // second curve to avoid treating these edges as a single curve by setting trim parameters.
1164       aWire = fixParametricGaps(aWire);
1165       aWire = BRepAlgo::ConcatenateWire(aWire, GeomAbs_G1); // join smooth parts of wire
1166       aNewEdge = BRepAlgo::ConcatenateWireC0(aWire); // join C0 parts of wire
1167     }
1168     anEdge = GeomEdgePtr(new GeomAPI_Edge);
1169     anEdge->setImpl(new TopoDS_Edge(aNewEdge));
1170   }
1171   return anEdge;
1172 }
1173
1174 //==================================================================================================
1175 ListOfShape GeomAlgoAPI_ShapeTools::getLowLevelSubShapes(const GeomShapePtr& theShape)
1176 {
1177   ListOfShape aSubShapes;
1178
1179   if (!theShape->isCompound() && !theShape->isCompSolid() &&
1180       !theShape->isShell() && !theShape->isWire()) {
1181     return aSubShapes;
1182   }
1183
1184   for (GeomAPI_ShapeIterator anIt(theShape); anIt.more(); anIt.next()) {
1185     GeomShapePtr aSubShape = anIt.current();
1186     if (aSubShape->isVertex() || aSubShape->isEdge() ||
1187         aSubShape->isFace() || aSubShape->isSolid()) {
1188       aSubShapes.push_back(aSubShape);
1189     } else {
1190       aSubShapes.splice(aSubShapes.end(), getLowLevelSubShapes(aSubShape));
1191     }
1192   }
1193
1194   return aSubShapes;
1195 }
1196
1197 //==================================================================================================
1198 static void getMinMaxPointsOnLine(const std::list<std::shared_ptr<GeomAPI_Pnt> >& thePoints,
1199                                   const gp_Dir theDir,
1200                                   double& theMin, double& theMax)
1201 {
1202   theMin = RealLast();
1203   theMax = RealFirst();
1204   // Project bounding points on theDir
1205   for (std::list<std::shared_ptr<GeomAPI_Pnt> >::const_iterator
1206          aPointsIt = thePoints.begin(); aPointsIt != thePoints.end(); aPointsIt++) {
1207     const gp_Pnt& aPnt = (*aPointsIt)->impl<gp_Pnt>();
1208     gp_Dir aPntDir (aPnt.XYZ());
1209     Standard_Real proj = (theDir*aPntDir) * aPnt.XYZ().Modulus();
1210     if (proj < theMin) theMin = proj;
1211     if (proj > theMax) theMax = proj;
1212   }
1213 }
1214
1215 //==================================================================================================
1216 void GeomAlgoAPI_ShapeTools::computeThroughAll(const ListOfShape& theObjects,
1217                                                const ListOfShape& theBaseShapes,
1218                                                const std::shared_ptr<GeomAPI_Dir> theDir,
1219                                                double& theToSize, double& theFromSize)
1220 {
1221   // Bounding box of objects
1222   std::list<std::shared_ptr<GeomAPI_Pnt> > aBndObjs =
1223       GeomAlgoAPI_ShapeTools::getBoundingBox(theObjects);
1224   if (aBndObjs.size() != 8) {
1225     return;
1226   }
1227
1228   // the value to enlarge the bounding box of each object to make the extruded shape
1229   // a little bit larger than overall objects to get the correct result of Boolean CUT operation
1230   double anEnlargement = 0.1 * aBndObjs.front()->distance(aBndObjs.back());
1231
1232   // Prism direction
1233   if (theDir.get()) {
1234     // One direction for all prisms
1235     gp_Dir aDir = theDir->impl<gp_Dir>();
1236
1237     // Bounding box of the base
1238     std::list<std::shared_ptr<GeomAPI_Pnt> > aBndBases =
1239         GeomAlgoAPI_ShapeTools::getBoundingBox(theBaseShapes);
1240     if (aBndBases.size() != 8) {
1241       return;
1242     }
1243
1244     // Objects bounds
1245     Standard_Real lowBnd, upperBnd;
1246     getMinMaxPointsOnLine(aBndObjs, aDir, lowBnd, upperBnd);
1247
1248     // Base bounds
1249     Standard_Real lowBase, upperBase;
1250     getMinMaxPointsOnLine(aBndBases, aDir, lowBase, upperBase);
1251
1252     // ----------.-----.---------.--------------.-----------> theDir
1253     //       lowBnd   lowBase   upperBase    upperBnd
1254
1255     theToSize = upperBnd - lowBase;
1256     theFromSize = upperBase - lowBnd;
1257   } else {
1258     // Direction is a normal to each base shape (different normals to bases)
1259     // So we calculate own sizes for each base shape
1260     theToSize = 0.0;
1261     theFromSize = 0.0;
1262
1263     for (ListOfShape::const_iterator anIt = theBaseShapes.begin();
1264          anIt != theBaseShapes.end(); ++anIt) {
1265       const GeomShapePtr& aBaseShape_i = (*anIt);
1266       ListOfShape aBaseShapes_i;
1267       aBaseShapes_i.push_back(aBaseShape_i);
1268
1269       // Bounding box of the base
1270       std::list<std::shared_ptr<GeomAPI_Pnt> > aBndBases =
1271           GeomAlgoAPI_ShapeTools::getBoundingBox(aBaseShapes_i, anEnlargement);
1272       if (aBndBases.size() != 8) {
1273         return;
1274       }
1275
1276       // Direction (normal to aBaseShapes_i)
1277       // Code like in GeomAlgoAPI_Prism
1278       gp_Dir aDir;
1279       const TopoDS_Shape& aBaseShape = aBaseShape_i->impl<TopoDS_Shape>();
1280       BRepBuilderAPI_FindPlane aFindPlane(aBaseShape);
1281       if (aFindPlane.Found() == Standard_True) {
1282         Handle(Geom_Plane) aPlane;
1283         if (aBaseShape.ShapeType() == TopAbs_FACE || aBaseShape.ShapeType() == TopAbs_SHELL) {
1284           TopExp_Explorer anExp(aBaseShape, TopAbs_FACE);
1285           const TopoDS_Shape& aFace = anExp.Current();
1286           Handle(Geom_Surface) aSurface = BRep_Tool::Surface(TopoDS::Face(aFace));
1287           if(aSurface->DynamicType() == STANDARD_TYPE(Geom_RectangularTrimmedSurface)) {
1288             Handle(Geom_RectangularTrimmedSurface) aTrimSurface =
1289               Handle(Geom_RectangularTrimmedSurface)::DownCast(aSurface);
1290             aSurface = aTrimSurface->BasisSurface();
1291           }
1292           if(aSurface->DynamicType() != STANDARD_TYPE(Geom_Plane)) {
1293             return;
1294           }
1295           aPlane = Handle(Geom_Plane)::DownCast(aSurface);
1296         } else {
1297           aPlane = aFindPlane.Plane();
1298         }
1299         aDir = aPlane->Axis().Direction();
1300       } else {
1301         return;
1302       }
1303
1304       // Objects bounds
1305       Standard_Real lowBnd, upperBnd;
1306       getMinMaxPointsOnLine(aBndObjs, aDir, lowBnd, upperBnd);
1307
1308       // Base bounds
1309       Standard_Real lowBase, upperBase;
1310       getMinMaxPointsOnLine(aBndBases, aDir, lowBase, upperBase);
1311
1312       // ----------.-----.---------.--------------.-----------> theDir
1313       //       lowBnd   lowBase   upperBase    upperBnd
1314
1315       double aToSize_i = upperBnd - lowBase;
1316       double aFromSize_i = upperBase - lowBnd;
1317
1318       if (aToSize_i > theToSize) theToSize = aToSize_i;
1319       if (aFromSize_i > theFromSize) theFromSize = aFromSize_i;
1320     }
1321   }
1322 }