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