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