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