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