Salome HOME
901e257c61beb1d5bddea86a43f28dd9fd566af0
[modules/shaper.git] / src / GeomAlgoAPI / GeomAlgoAPI_ShapeTools.cpp
1 // Copyright (C) 2014-2017  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
18 // email : webmaster.salome@opencascade.com<mailto:webmaster.salome@opencascade.com>
19 //
20
21 #include "GeomAlgoAPI_ShapeTools.h"
22
23 #include "GeomAlgoAPI_SketchBuilder.h"
24
25 #include <GeomAPI_Ax1.h>
26 #include <GeomAPI_Edge.h>
27 #include <GeomAPI_Dir.h>
28 #include <GeomAPI_Face.h>
29 #include <GeomAPI_Pln.h>
30 #include <GeomAPI_Pnt.h>
31 #include <GeomAPI_Wire.h>
32
33 #include <Bnd_Box.hxx>
34 #include <BRep_Builder.hxx>
35 #include <BRepAdaptor_Curve.hxx>
36 #include <BRepAlgo.hxx>
37 #include <BRepAlgo_FaceRestrictor.hxx>
38 #include <BRepBndLib.hxx>
39 #include <BRepBuilderAPI_FindPlane.hxx>
40 #include <BRepBuilderAPI_MakeEdge.hxx>
41 #include <BRepBuilderAPI_MakeFace.hxx>
42 #include <BRepCheck_Analyzer.hxx>
43 #include <BRepExtrema_DistShapeShape.hxx>
44 #include <BRepExtrema_ExtCF.hxx>
45 #include <BRepGProp.hxx>
46 #include <BRepTools.hxx>
47 #include <BRepTools_WireExplorer.hxx>
48 #include <BRepTopAdaptor_FClass2d.hxx>
49 #include <BRepClass_FaceClassifier.hxx>
50 #include <Geom2d_Curve.hxx>
51 #include <Geom2d_Curve.hxx>
52 #include <BRepLib_CheckCurveOnSurface.hxx>
53 #include <BRep_Tool.hxx>
54 #include <Geom_Line.hxx>
55 #include <Geom_Plane.hxx>
56 #include <GeomAPI_ProjectPointOnCurve.hxx>
57 #include <GeomLib_IsPlanarSurface.hxx>
58 #include <GeomLib_Tool.hxx>
59 #include <GeomAPI_IntCS.hxx>
60 #include <gp_Pln.hxx>
61 #include <GProp_GProps.hxx>
62 #include <IntAna_IntConicQuad.hxx>
63 #include <IntAna_Quadric.hxx>
64 #include <NCollection_Vector.hxx>
65 #include <ShapeAnalysis.hxx>
66 #include <ShapeAnalysis_Surface.hxx>
67 #include <TopoDS_Builder.hxx>
68 #include <TopoDS_Edge.hxx>
69 #include <TopoDS_Face.hxx>
70 #include <TopoDS_Shape.hxx>
71 #include <TopoDS_Shell.hxx>
72 #include <TopoDS_Vertex.hxx>
73 #include <TopoDS.hxx>
74 #include <TopExp.hxx>
75 #include <TopExp_Explorer.hxx>
76 #include <TopTools_ListIteratorOfListOfShape.hxx>
77
78
79 #include <BOPAlgo_Builder.hxx>
80 #include <BRepBuilderAPI_MakeVertex.hxx>
81 #include <TopoDS_Edge.hxx>
82
83 //==================================================================================================
84 double GeomAlgoAPI_ShapeTools::volume(const std::shared_ptr<GeomAPI_Shape> theShape)
85 {
86   GProp_GProps aGProps;
87   if(!theShape.get()) {
88     return 0.0;
89   }
90   const TopoDS_Shape& aShape = theShape->impl<TopoDS_Shape>();
91   if(aShape.IsNull()) {
92     return 0.0;
93   }
94   const Standard_Real anEps = 1.e-6;
95   if (aShape.ShapeType() <= TopAbs_SOLID)
96     BRepGProp::VolumeProperties(aShape, aGProps, anEps);
97   else
98     BRepGProp::SurfaceProperties(aShape, aGProps, anEps);
99   return aGProps.Mass();
100 }
101
102 //==================================================================================================
103 double GeomAlgoAPI_ShapeTools::area (const std::shared_ptr<GeomAPI_Shape> theShape)
104 {
105   GProp_GProps aGProps;
106   if(!theShape.get()) {
107     return 0.0;
108   }
109   const TopoDS_Shape& aShape = theShape->impl<TopoDS_Shape>();
110   if(aShape.IsNull()) {
111     return 0.0;
112   }
113   const Standard_Real anEps = 1.e-6;
114
115   BRepGProp::SurfaceProperties(aShape, aGProps, anEps);
116   return aGProps.Mass();
117 }
118
119 //==================================================================================================
120 std::shared_ptr<GeomAPI_Pnt>
121   GeomAlgoAPI_ShapeTools::centreOfMass(const std::shared_ptr<GeomAPI_Shape> theShape)
122 {
123   GProp_GProps aGProps;
124   if(!theShape) {
125     return std::shared_ptr<GeomAPI_Pnt>();
126   }
127   const TopoDS_Shape& aShape = theShape->impl<TopoDS_Shape>();
128   if(aShape.IsNull()) {
129     return std::shared_ptr<GeomAPI_Pnt>();
130   }
131   gp_Pnt aCentre;
132   if(aShape.ShapeType() == TopAbs_VERTEX) {
133     aCentre = BRep_Tool::Pnt(TopoDS::Vertex(aShape));
134   } else if(aShape.ShapeType() == TopAbs_EDGE || aShape.ShapeType() == TopAbs_WIRE) {
135     BRepGProp::LinearProperties(aShape, aGProps);
136     aCentre = aGProps.CentreOfMass();
137   } else {
138     const Standard_Real anEps = 1.e-6;
139     BRepGProp::SurfaceProperties(aShape, aGProps, anEps);
140     aCentre = aGProps.CentreOfMass();
141   }
142   return std::shared_ptr<GeomAPI_Pnt>(new GeomAPI_Pnt(aCentre.X(), aCentre.Y(), aCentre.Z()));
143 }
144
145 //==================================================================================================
146 std::shared_ptr<GeomAPI_Shape> GeomAlgoAPI_ShapeTools::combineShapes(
147   const std::shared_ptr<GeomAPI_Shape> theCompound,
148   const GeomAPI_Shape::ShapeType theType,
149   ListOfShape& theCombinedShapes,
150   ListOfShape& theFreeShapes)
151 {
152   GeomShapePtr aResult = theCompound;
153
154   if(!theCompound.get()) {
155     return aResult;
156   }
157
158   if(theType != GeomAPI_Shape::SHELL && theType != GeomAPI_Shape::COMPSOLID) {
159     return aResult;
160   }
161
162   TopAbs_ShapeEnum aTS = TopAbs_EDGE;
163   TopAbs_ShapeEnum aTA = TopAbs_FACE;
164   if(theType == GeomAPI_Shape::COMPSOLID) {
165     aTS = TopAbs_FACE;
166     aTA = TopAbs_SOLID;
167   }
168
169   theCombinedShapes.clear();
170   theFreeShapes.clear();
171
172   // Get free shapes.
173   const TopoDS_Shape& aShapesComp = theCompound->impl<TopoDS_Shape>();
174   for(TopoDS_Iterator anIter(aShapesComp); anIter.More(); anIter.Next() ) {
175     const TopoDS_Shape& aShape = anIter.Value();
176     if(aShape.ShapeType() > aTA) {
177       std::shared_ptr<GeomAPI_Shape> aGeomShape(new GeomAPI_Shape);
178       aGeomShape->setImpl<TopoDS_Shape>(new TopoDS_Shape(aShape));
179       theFreeShapes.push_back(aGeomShape);
180     }
181   }
182
183   // Map subshapes and shapes.
184   TopTools_IndexedDataMapOfShapeListOfShape aMapSA;
185   TopExp::MapShapesAndAncestors(aShapesComp, aTS, aTA, aMapSA);
186   if(aMapSA.IsEmpty()) {
187     return aResult;
188   }
189
190   // Get all shapes with common subshapes and free shapes.
191   NCollection_Map<TopoDS_Shape> aFreeShapes;
192   NCollection_Vector<NCollection_Map<TopoDS_Shape>> aShapesWithCommonSubshapes;
193   for(TopTools_IndexedDataMapOfShapeListOfShape::Iterator
194       anIter(aMapSA); anIter.More(); anIter.Next()) {
195     const TopoDS_Shape& aShape = anIter.Key();
196     TopTools_ListOfShape& aListOfShape = anIter.ChangeValue();
197     if(aListOfShape.IsEmpty()) {
198       continue;
199     }
200     else if(aListOfShape.Size() == 1) {
201       const TopoDS_Shape& aF = aListOfShape.First();
202       aFreeShapes.Add(aF);
203       aListOfShape.Clear();
204     } else {
205       NCollection_List<TopoDS_Shape> aTempList;
206       NCollection_Map<TopoDS_Shape> aTempMap;
207       const TopoDS_Shape& aF = aListOfShape.First();
208       const TopoDS_Shape& aL = aListOfShape.Last();
209       aTempList.Append(aF);
210       aTempList.Append(aL);
211       aTempMap.Add(aF);
212       aTempMap.Add(aL);
213       aFreeShapes.Remove(aF);
214       aFreeShapes.Remove(aL);
215       aListOfShape.Clear();
216       for(NCollection_List<TopoDS_Shape>::Iterator
217           aTempIter(aTempList); aTempIter.More(); aTempIter.Next()) {
218         const TopoDS_Shape& aTempShape = aTempIter.Value();
219         for(TopTools_IndexedDataMapOfShapeListOfShape::Iterator
220             anIter(aMapSA); anIter.More(); anIter.Next()) {
221           TopTools_ListOfShape& aTempListOfShape = anIter.ChangeValue();
222           if(aTempListOfShape.IsEmpty()) {
223             continue;
224           } else if(aTempListOfShape.Size() == 1 && aTempListOfShape.First() == aTempShape) {
225             aTempListOfShape.Clear();
226           } else if(aTempListOfShape.Size() > 1) {
227             if(aTempListOfShape.First() == aTempShape) {
228               const TopoDS_Shape& aTL = aTempListOfShape.Last();
229               if(aTempMap.Add(aTL)) {
230                 aTempList.Append(aTL);
231                 aFreeShapes.Remove(aTL);
232               }
233               aTempListOfShape.Clear();
234             } else if(aTempListOfShape.Last() == aTempShape) {
235               const TopoDS_Shape& aTF = aTempListOfShape.First();
236               if(aTempMap.Add(aTF)) {
237                 aTempList.Append(aTF);
238                 aFreeShapes.Remove(aTF);
239               }
240               aTempListOfShape.Clear();
241             }
242           }
243         }
244       }
245       aShapesWithCommonSubshapes.Append(aTempMap);
246     }
247   }
248
249   // Combine shapes with common subshapes.
250   for(NCollection_Vector<NCollection_Map<TopoDS_Shape>>::Iterator
251       anIter(aShapesWithCommonSubshapes); anIter.More(); anIter.Next()) {
252     TopoDS_Shell aShell;
253     TopoDS_CompSolid aCSolid;
254     TopoDS_Builder aBuilder;
255     theType ==
256       GeomAPI_Shape::COMPSOLID ? aBuilder.MakeCompSolid(aCSolid) : aBuilder.MakeShell(aShell);
257     NCollection_Map<TopoDS_Shape>& aShapesMap = anIter.ChangeValue();
258     for(TopExp_Explorer anExp(aShapesComp, aTA); anExp.More(); anExp.Next()) {
259       const TopoDS_Shape& aShape = anExp.Current();
260       if(aShapesMap.Contains(aShape)) {
261         theType ==
262           GeomAPI_Shape::COMPSOLID ? aBuilder.Add(aCSolid, aShape) : aBuilder.Add(aShell, aShape);
263         aShapesMap.Remove(aShape);
264       }
265     }
266     std::shared_ptr<GeomAPI_Shape> aGeomShape(new GeomAPI_Shape);
267     TopoDS_Shape* aSh = theType == GeomAPI_Shape::COMPSOLID ? new TopoDS_Shape(aCSolid) :
268                                                               new TopoDS_Shape(aShell);
269     aGeomShape->setImpl<TopoDS_Shape>(aSh);
270     theCombinedShapes.push_back(aGeomShape);
271   }
272
273   // Adding free shapes.
274   for(TopExp_Explorer anExp(aShapesComp, aTA); anExp.More(); anExp.Next()) {
275     const TopoDS_Shape& aShape = anExp.Current();
276     if(aFreeShapes.Contains(aShape)) {
277       std::shared_ptr<GeomAPI_Shape> aGeomShape(new GeomAPI_Shape);
278       aGeomShape->setImpl<TopoDS_Shape>(new TopoDS_Shape(aShape));
279       theFreeShapes.push_back(aGeomShape);
280     }
281   }
282
283   if(theCombinedShapes.size() == 1 && theFreeShapes.size() == 0) {
284     aResult = theCombinedShapes.front();
285   } else if(theCombinedShapes.size() == 0 && theFreeShapes.size() == 1) {
286     aResult = theFreeShapes.front();
287   } else {
288     TopoDS_Compound aResultComp;
289     TopoDS_Builder aBuilder;
290     aBuilder.MakeCompound(aResultComp);
291     for(ListOfShape::const_iterator anIter = theCombinedShapes.cbegin();
292         anIter != theCombinedShapes.cend(); anIter++) {
293       aBuilder.Add(aResultComp, (*anIter)->impl<TopoDS_Shape>());
294     }
295     for(ListOfShape::const_iterator anIter = theFreeShapes.cbegin();
296         anIter != theFreeShapes.cend(); anIter++) {
297       aBuilder.Add(aResultComp, (*anIter)->impl<TopoDS_Shape>());
298     }
299     aResult->setImpl(new TopoDS_Shape(aResultComp));
300   }
301
302   return aResult;
303 }
304
305 //==================================================================================================
306 static void addSimpleShapeToList(const TopoDS_Shape& theShape,
307                                  NCollection_List<TopoDS_Shape>& theList)
308 {
309   if(theShape.IsNull()) {
310     return;
311   }
312
313   if(theShape.ShapeType() == TopAbs_COMPOUND) {
314     for(TopoDS_Iterator anIt(theShape); anIt.More(); anIt.Next()) {
315       addSimpleShapeToList(anIt.Value(), theList);
316     }
317   } else {
318     theList.Append(theShape);
319   }
320 }
321
322 //==================================================================================================
323 static TopoDS_Compound makeCompound(const NCollection_List<TopoDS_Shape> theShapes)
324 {
325   TopoDS_Compound aCompound;
326
327   BRep_Builder aBuilder;
328   aBuilder.MakeCompound(aCompound);
329
330   for(NCollection_List<TopoDS_Shape>::Iterator anIt(theShapes); anIt.More(); anIt.Next()) {
331     aBuilder.Add(aCompound, anIt.Value());
332   }
333
334   return aCompound;
335 }
336
337 //==================================================================================================
338 std::shared_ptr<GeomAPI_Shape> GeomAlgoAPI_ShapeTools::groupSharedTopology(
339   const std::shared_ptr<GeomAPI_Shape> theCompound)
340 {
341   GeomShapePtr aResult = theCompound;
342
343   if(!theCompound.get()) {
344     return aResult;
345   }
346
347   TopoDS_Shape anInShape = aResult->impl<TopoDS_Shape>();
348   NCollection_List<TopoDS_Shape> anUngroupedShapes, aStillUngroupedShapes;
349   addSimpleShapeToList(anInShape, anUngroupedShapes);
350
351   // Iterate over all shapes and find shapes with shared vertices.
352   TopTools_ListOfShape aMapOrder;
353   TopTools_DataMapOfShapeListOfShape aVertexShapesMap;
354   for(NCollection_List<TopoDS_Shape>::Iterator aShapesIt(anUngroupedShapes);
355       aShapesIt.More();
356       aShapesIt.Next()) {
357     const TopoDS_Shape& aShape = aShapesIt.Value();
358     for(TopExp_Explorer aShapeExp(aShape, TopAbs_VERTEX);
359         aShapeExp.More();
360         aShapeExp.Next()) {
361       const TopoDS_Shape& aVertex = aShapeExp.Current();
362       if (!aVertexShapesMap.IsBound(aVertex)) {
363         NCollection_List<TopoDS_Shape> aList;
364         aList.Append(aShape);
365         aMapOrder.Append(aVertex);
366         aVertexShapesMap.Bind(aVertex, aList);
367       } else {
368         if(!aVertexShapesMap.ChangeFind(aVertex).Contains(aShape)) {
369           aVertexShapesMap.ChangeFind(aVertex).Append(aShape);
370         }
371       }
372     }
373   }
374
375   // Iterate over the map and group shapes.
376   NCollection_Vector<TopTools_ListOfShape> aGroups;
377   while (!aMapOrder.IsEmpty()) {
378     // Get first group of shapes in map, and then unbind it.
379     const TopoDS_Shape& aKey = aMapOrder.First();
380     TopTools_ListOfShape aGroupedShapes = aVertexShapesMap.Find(aKey);
381     aVertexShapesMap.UnBind(aKey);
382     aMapOrder.Remove(aKey);
383     // Iterate over shapes in this group and add to it shapes from groups in map.
384     for(TopTools_ListOfShape::Iterator aGroupIt(aGroupedShapes);
385         aGroupIt.More(); aGroupIt.Next()) {
386       const TopoDS_Shape& aGroupedShape = aGroupIt.Value();
387       TopTools_ListOfShape aKeysToUnbind;
388       for(TopTools_ListOfShape::Iterator aKeysIt(aMapOrder);
389           aKeysIt.More();
390           aKeysIt.Next()) {
391         const TopTools_ListOfShape& aGroupInMap = aVertexShapesMap(aKeysIt.Value());
392         if(!aGroupInMap.Contains(aGroupedShape)) {
393           // Group in map does not containt shape from our group, so go to the next group in map.
394           continue;
395         }
396         // Iterate over shape in group in map, and add new shapes into our group.
397         for(TopTools_ListOfShape::Iterator aGroupInMapIt(aGroupInMap);
398             aGroupInMapIt.More();
399             aGroupInMapIt.Next()) {
400           const TopoDS_Shape& aShape = aGroupInMapIt.Value();
401           if (!aGroupedShapes.Contains(aShape)) {
402             aGroupedShapes.Append(aShape);
403           }
404         }
405         // Save key to unbind from this map.
406         aKeysToUnbind.Append(aKeysIt.Value());
407       }
408       // Unbind groups from map that we added to our group.
409       for(TopTools_ListOfShape::Iterator aKeysIt(aKeysToUnbind);
410           aKeysIt.More();
411           aKeysIt.Next()) {
412         aVertexShapesMap.UnBind(aKeysIt.Value());
413         aMapOrder.Remove(aKeysIt.Value());
414       }
415     }
416     // Sort shapes.
417     TopTools_ListOfShape aSortedGroup;
418     for(int aST = TopAbs_COMPOUND; aST <= TopAbs_SHAPE; ++aST) {
419       TopTools_ListOfShape::Iterator anIt(aGroupedShapes);
420       while (anIt.More()) {
421         if(anIt.Value().ShapeType() == aST) {
422           aSortedGroup.Append(anIt.Value());
423           aGroupedShapes.Remove(anIt);
424         } else {
425           anIt.Next();
426         }
427       }
428     }
429     aGroups.Append(aSortedGroup);
430   }
431
432   TopoDS_Compound aCompound;
433   BRep_Builder aBuilder;
434   aBuilder.MakeCompound(aCompound);
435   ListOfShape aCompSolids, aFreeSolids;
436   for(NCollection_Vector<NCollection_List<TopoDS_Shape>>::Iterator
437       anIt(aGroups); anIt.More(); anIt.Next()) {
438     NCollection_List<TopoDS_Shape> aGroup = anIt.Value();
439     GeomShapePtr aGeomShape(new GeomAPI_Shape());
440     if(aGroup.Size() == 1) {
441       aGeomShape->setImpl(new TopoDS_Shape(aGroup.First()));
442     } else {
443       aGeomShape->setImpl(new TopoDS_Shape(makeCompound(aGroup)));
444       aGeomShape = GeomAlgoAPI_ShapeTools::combineShapes(aGeomShape,
445                                                          GeomAPI_Shape::COMPSOLID,
446                                                          aCompSolids,
447                                                          aFreeSolids);
448     }
449     aBuilder.Add(aCompound, aGeomShape->impl<TopoDS_Shape>());
450   }
451
452   if(!aCompound.IsNull()) {
453     aResult->setImpl(new TopoDS_Shape(aCompound));
454   }
455
456   return aResult;
457 }
458
459 //==================================================================================================
460 std::list<std::shared_ptr<GeomAPI_Pnt> >
461   GeomAlgoAPI_ShapeTools::getBoundingBox(const ListOfShape& theShapes, const double theEnlarge)
462 {
463   // Bounding box of all objects.
464   Bnd_Box aBndBox;
465
466   // Getting box.
467   for (ListOfShape::const_iterator
468     anObjectsIt = theShapes.begin(); anObjectsIt != theShapes.end(); anObjectsIt++) {
469     const TopoDS_Shape& aShape = (*anObjectsIt)->impl<TopoDS_Shape>();
470     BRepBndLib::Add(aShape, aBndBox);
471   }
472
473   if(theEnlarge != 0.0) {
474     // We enlarge bounding box just to be sure that plane will be large enough to cut all objects.
475     aBndBox.Enlarge(theEnlarge);
476   }
477
478   Standard_Real aXArr[2] = {aBndBox.CornerMin().X(), aBndBox.CornerMax().X()};
479   Standard_Real aYArr[2] = {aBndBox.CornerMin().Y(), aBndBox.CornerMax().Y()};
480   Standard_Real aZArr[2] = {aBndBox.CornerMin().Z(), aBndBox.CornerMax().Z()};
481   std::list<std::shared_ptr<GeomAPI_Pnt> > aResultPoints;
482   int aNum = 0;
483   for(int i = 0; i < 2; i++) {
484     for(int j = 0; j < 2; j++) {
485       for(int k = 0; k < 2; k++) {
486         std::shared_ptr<GeomAPI_Pnt> aPnt(new GeomAPI_Pnt(aXArr[i], aYArr[j], aZArr[k]));
487         aResultPoints.push_back(aPnt);
488       }
489     }
490   }
491
492   return aResultPoints;
493 }
494
495 //==================================================================================================
496 std::shared_ptr<GeomAPI_Shape>
497   GeomAlgoAPI_ShapeTools::faceToInfinitePlane(const std::shared_ptr<GeomAPI_Shape> theFace)
498 {
499   if (!theFace.get())
500     return std::shared_ptr<GeomAPI_Shape>();
501
502   TopoDS_Face aPlaneFace = TopoDS::Face(theFace->impl<TopoDS_Shape>());
503   if (aPlaneFace.IsNull())
504     return std::shared_ptr<GeomAPI_Shape>();
505
506   Handle(Geom_Plane) aPlane = Handle(Geom_Plane)::DownCast(BRep_Tool::Surface(aPlaneFace));
507   if (aPlane.IsNull())
508     return std::shared_ptr<GeomAPI_Shape>();
509
510   // make an infinity face on the plane
511   TopoDS_Shape anInfiniteFace = BRepBuilderAPI_MakeFace(aPlane->Pln()).Shape();
512
513   std::shared_ptr<GeomAPI_Shape> aResult(new GeomAPI_Shape);
514   aResult->setImpl(new TopoDS_Shape(anInfiniteFace));
515   return aResult;
516 }
517
518 //==================================================================================================
519 std::shared_ptr<GeomAPI_Face> GeomAlgoAPI_ShapeTools::fitPlaneToBox(
520   const std::shared_ptr<GeomAPI_Shape> thePlane,
521   const std::list<std::shared_ptr<GeomAPI_Pnt> >& thePoints)
522 {
523   std::shared_ptr<GeomAPI_Face> aResultFace;
524
525   if(!thePlane.get()) {
526     return aResultFace;
527   }
528
529   const TopoDS_Shape& aShape = thePlane->impl<TopoDS_Shape>();
530   if(aShape.ShapeType() != TopAbs_FACE) {
531     return aResultFace;
532   }
533
534   TopoDS_Face aFace = TopoDS::Face(aShape);
535   Handle(Geom_Surface) aSurf = BRep_Tool::Surface(aFace);
536   if(aSurf.IsNull()) {
537     return aResultFace;
538   }
539
540   GeomLib_IsPlanarSurface isPlanar(aSurf);
541   if(!isPlanar.IsPlanar()) {
542     return aResultFace;
543   }
544
545   if(thePoints.size() != 8) {
546     return aResultFace;
547   }
548
549   const gp_Pln& aFacePln = isPlanar.Plan();
550   Handle(Geom_Plane) aFacePlane = new Geom_Plane(aFacePln);
551   IntAna_Quadric aQuadric(aFacePln);
552   Standard_Real UMin, UMax, VMin, VMax;
553   UMin = UMax = VMin = VMax = 0;
554   for (std::list<std::shared_ptr<GeomAPI_Pnt> >::const_iterator
555        aPointsIt = thePoints.begin(); aPointsIt != thePoints.end(); aPointsIt++) {
556     const gp_Pnt& aPnt = (*aPointsIt)->impl<gp_Pnt>();
557     gp_Lin aLin(aPnt, aFacePln.Axis().Direction());
558     IntAna_IntConicQuad anIntAna(aLin, aQuadric);
559     const gp_Pnt& aPntOnFace = anIntAna.Point(1);
560     Standard_Real aPntU(0), aPntV(0);
561     GeomLib_Tool::Parameters(aFacePlane, aPntOnFace, Precision::Confusion(), aPntU, aPntV);
562     if(aPntU < UMin) UMin = aPntU;
563     if(aPntU > UMax) UMax = aPntU;
564     if(aPntV < VMin) VMin = aPntV;
565     if(aPntV > VMax) VMax = aPntV;
566   }
567   aResultFace.reset(new GeomAPI_Face());
568   aResultFace->setImpl(new TopoDS_Face(BRepLib_MakeFace(aFacePln, UMin, UMax, VMin, VMax).Face()));
569
570   return aResultFace;
571 }
572
573 //==================================================================================================
574 void GeomAlgoAPI_ShapeTools::findBounds(const std::shared_ptr<GeomAPI_Shape> theShape,
575                                         std::shared_ptr<GeomAPI_Vertex>& theV1,
576                                         std::shared_ptr<GeomAPI_Vertex>& theV2)
577 {
578   if(!theShape.get()) {
579     std::shared_ptr<GeomAPI_Vertex> aVertex(new GeomAPI_Vertex);
580     aVertex->setImpl(new TopoDS_Vertex());
581     theV1 = aVertex;
582     theV2 = aVertex;
583     return;
584   }
585
586   const TopoDS_Shape& aShape = theShape->impl<TopoDS_Shape>();
587   TopoDS_Vertex aV1, aV2;
588   ShapeAnalysis::FindBounds(aShape, aV1, aV2);
589
590   std::shared_ptr<GeomAPI_Vertex> aGeomV1(new GeomAPI_Vertex()), aGeomV2(new GeomAPI_Vertex());
591   aGeomV1->setImpl(new TopoDS_Vertex(aV1));
592   aGeomV2->setImpl(new TopoDS_Vertex(aV2));
593   theV1 = aGeomV1;
594   theV2 = aGeomV2;
595 }
596
597 //==================================================================================================
598 void GeomAlgoAPI_ShapeTools::makeFacesWithHoles(const std::shared_ptr<GeomAPI_Pnt> theOrigin,
599                                                 const std::shared_ptr<GeomAPI_Dir> theDirection,
600                                                 const ListOfShape& theWires,
601                                                 ListOfShape& theFaces)
602 {
603   BRepBuilderAPI_MakeFace aMKFace(gp_Pln(theOrigin->impl<gp_Pnt>(),
604                                           theDirection->impl<gp_Dir>()));
605   TopoDS_Face aFace = aMKFace.Face();
606
607   BRepAlgo_FaceRestrictor aFRestrictor;
608   aFRestrictor.Init(aFace, Standard_False, Standard_True);
609   for(ListOfShape::const_iterator anIt = theWires.cbegin();
610       anIt != theWires.cend();
611       ++anIt) {
612     TopoDS_Wire aWire = TopoDS::Wire((*anIt)->impl<TopoDS_Shape>());
613     aFRestrictor.Add(aWire);
614   }
615
616   aFRestrictor.Perform();
617
618   if(!aFRestrictor.IsDone()) {
619     return;
620   }
621
622   for(; aFRestrictor.More(); aFRestrictor.Next()) {
623     GeomShapePtr aShape(new GeomAPI_Shape());
624     aShape->setImpl(new TopoDS_Shape(aFRestrictor.Current()));
625     theFaces.push_back(aShape);
626   }
627 }
628
629 //==================================================================================================
630 std::shared_ptr<GeomAPI_Pln> GeomAlgoAPI_ShapeTools::findPlane(const ListOfShape& theShapes)
631 {
632   TopoDS_Compound aCompound;
633   BRep_Builder aBuilder;
634   aBuilder.MakeCompound(aCompound);
635
636   for(ListOfShape::const_iterator anIt = theShapes.cbegin(); anIt != theShapes.cend(); ++anIt) {
637     aBuilder.Add(aCompound, (*anIt)->impl<TopoDS_Shape>());
638   }
639   BRepBuilderAPI_FindPlane aFindPlane(aCompound);
640
641   if(aFindPlane.Found() != Standard_True) {
642     return std::shared_ptr<GeomAPI_Pln>();
643   }
644
645   Handle(Geom_Plane) aPlane = aFindPlane.Plane();
646   gp_Pnt aLoc = aPlane->Location();
647   gp_Dir aDir = aPlane->Axis().Direction();
648
649   std::shared_ptr<GeomAPI_Pnt> aGeomPnt(new GeomAPI_Pnt(aLoc.X(), aLoc.Y(), aLoc.Z()));
650   std::shared_ptr<GeomAPI_Dir> aGeomDir(new GeomAPI_Dir(aDir.X(), aDir.Y(), aDir.Z()));
651
652   std::shared_ptr<GeomAPI_Pln> aPln(new GeomAPI_Pln(aGeomPnt, aGeomDir));
653
654   return aPln;
655 }
656
657 //==================================================================================================
658 bool GeomAlgoAPI_ShapeTools::isSubShapeInsideShape(
659   const std::shared_ptr<GeomAPI_Shape> theSubShape,
660   const std::shared_ptr<GeomAPI_Shape> theBaseShape)
661 {
662   if(!theSubShape.get() || !theBaseShape.get()) {
663     return false;
664   }
665
666   const TopoDS_Shape& aSubShape = theSubShape->impl<TopoDS_Shape>();
667   const TopoDS_Shape& aBaseShape = theBaseShape->impl<TopoDS_Shape>();
668
669   if(aSubShape.ShapeType() == TopAbs_VERTEX) {
670     // If sub-shape is a vertex check distance to shape. If it is <= Precision::Confusion() then OK.
671     BRepExtrema_DistShapeShape aDist(aBaseShape, aSubShape);
672     aDist.Perform();
673     if(!aDist.IsDone() || aDist.Value() > Precision::Confusion()) {
674       return false;
675     }
676   } else if (aSubShape.ShapeType() == TopAbs_EDGE) {
677     if(aBaseShape.ShapeType() == TopAbs_FACE) {
678       // Check that edge is on face surface.
679       TopoDS_Face aFace = TopoDS::Face(aBaseShape);
680       TopoDS_Edge anEdge = TopoDS::Edge(aSubShape);
681       BRepLib_CheckCurveOnSurface aCheck(anEdge, aFace);
682       aCheck.Perform();
683       if(!aCheck.IsDone() || aCheck.MaxDistance() > Precision::Confusion()) {
684         return false;
685       }
686
687       // Check intersections.
688       TopoDS_Vertex aV1, aV2;
689       ShapeAnalysis::FindBounds(anEdge, aV1, aV2);
690       gp_Pnt aPnt1 = BRep_Tool::Pnt(aV1);
691       gp_Pnt aPnt2 = BRep_Tool::Pnt(aV2);
692       for(TopExp_Explorer anExp(aBaseShape, TopAbs_EDGE); anExp.More(); anExp.Next()) {
693         const TopoDS_Shape& anEdgeOnFace = anExp.Current();
694         BRepExtrema_DistShapeShape aDist(anEdgeOnFace, anEdge);
695         aDist.Perform();
696         if(aDist.IsDone() && aDist.Value() <= Precision::Confusion()) {
697           // Edge intersect face bound. Check that it is not on edge begin or end.
698           for(Standard_Integer anIndex = 1; anIndex <= aDist.NbSolution(); ++anIndex) {
699             gp_Pnt aPntOnSubShape = aDist.PointOnShape2(anIndex);
700             if(aPntOnSubShape.Distance(aPnt1) > Precision::Confusion()
701                 && aPntOnSubShape.Distance(aPnt2) > Precision::Confusion()) {
702               return false;
703             }
704           }
705         }
706       }
707
708       // No intersections found. Edge is inside or outside face. Check it.
709       BRepAdaptor_Curve aCurveAdaptor(anEdge);
710       gp_Pnt aPointToCheck =
711         aCurveAdaptor.Value((aCurveAdaptor.FirstParameter() +
712                               aCurveAdaptor.LastParameter()) / 2.0);
713       Handle(Geom_Surface) aSurface = BRep_Tool::Surface(aFace);
714       ShapeAnalysis_Surface aSAS(aSurface);
715       gp_Pnt2d aPointOnFace = aSAS.ValueOfUV(aPointToCheck, Precision::Confusion());
716       BRepTopAdaptor_FClass2d aFClass2d(aFace, Precision::Confusion());
717       if(aFClass2d.Perform(aPointOnFace) == TopAbs_OUT) {
718         return false;
719       }
720
721     } else {
722       return false;
723     }
724   } else {
725     return false;
726   }
727
728   return true;
729 }
730
731 //==================================================================================================
732 bool GeomAlgoAPI_ShapeTools::isShapeValid(const std::shared_ptr<GeomAPI_Shape> theShape)
733 {
734   if(!theShape.get()) {
735     return false;
736   }
737
738   BRepCheck_Analyzer aChecker(theShape->impl<TopoDS_Shape>());
739   return (aChecker.IsValid() == Standard_True);
740 }
741
742 //==================================================================================================
743 std::shared_ptr<GeomAPI_Shape>
744   GeomAlgoAPI_ShapeTools::getFaceOuterWire(const std::shared_ptr<GeomAPI_Shape> theFace)
745 {
746   GeomShapePtr anOuterWire;
747
748   if(!theFace.get() || !theFace->isFace()) {
749     return anOuterWire;
750   }
751
752   TopoDS_Face aFace = TopoDS::Face(theFace->impl<TopoDS_Shape>());
753   TopoDS_Wire aWire = BRepTools::OuterWire(aFace);
754
755   anOuterWire.reset(new GeomAPI_Shape());
756   anOuterWire->setImpl(new TopoDS_Shape(aWire));
757
758   return anOuterWire;
759 }
760
761 //==================================================================================================
762 bool GeomAlgoAPI_ShapeTools::isParallel(const std::shared_ptr<GeomAPI_Edge> theEdge,
763                                         const std::shared_ptr<GeomAPI_Face> theFace)
764 {
765   if(!theEdge.get() || !theFace.get()) {
766     return false;
767   }
768
769   TopoDS_Edge anEdge = TopoDS::Edge(theEdge->impl<TopoDS_Shape>());
770   TopoDS_Face aFace  = TopoDS::Face(theFace->impl<TopoDS_Shape>());
771
772   BRepExtrema_ExtCF anExt(anEdge, aFace);
773   return anExt.IsParallel() == Standard_True;
774 }
775
776 //==================================================================================================
777 std::list<std::shared_ptr<GeomAPI_Vertex> > GeomAlgoAPI_ShapeTools::intersect(
778   const std::shared_ptr<GeomAPI_Edge> theEdge, const std::shared_ptr<GeomAPI_Face> theFace,
779   const bool thePointsOutsideFace)
780 {
781   std::list<std::shared_ptr<GeomAPI_Vertex> > aResult;
782   if(!theEdge.get() || !theFace.get()) {
783     return aResult;
784   }
785
786   TopoDS_Edge anEdge = TopoDS::Edge(theEdge->impl<TopoDS_Shape>());
787   double aFirstOnCurve, aLastOnCurve;
788   Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirstOnCurve, aLastOnCurve);
789
790   TopoDS_Face aFace  = TopoDS::Face(theFace->impl<TopoDS_Shape>());
791   Handle(Geom_Surface) aSurf = BRep_Tool::Surface(aFace);
792
793   GeomAPI_IntCS anIntAlgo(aCurve, aSurf);
794   if (!anIntAlgo.IsDone())
795     return aResult;
796   // searching for points-intersection
797   for(int anIntNum = 1; anIntNum <= anIntAlgo.NbPoints() + anIntAlgo.NbSegments(); anIntNum++) {
798     gp_Pnt anInt;
799     if (anIntNum <= anIntAlgo.NbPoints()) {
800       anInt = anIntAlgo.Point(anIntNum);
801     } else { // take the middle point on the segment of the intersection
802       Handle(Geom_Curve) anIntCurve = anIntAlgo.Segment(anIntNum - anIntAlgo.NbPoints());
803       anIntCurve->D0((anIntCurve->FirstParameter() + anIntCurve->LastParameter()) / 2., anInt);
804     }
805     aResult.push_back(std::shared_ptr<GeomAPI_Vertex>(
806       new GeomAPI_Vertex(anInt.X(), anInt.Y(), anInt.Z())));
807   }
808   return aResult;
809 }
810
811 //==================================================================================================
812 void GeomAlgoAPI_ShapeTools::splitShape(const std::shared_ptr<GeomAPI_Shape>& theBaseShape,
813                                       const GeomAlgoAPI_ShapeTools::PointToRefsMap& thePointsInfo,
814                                       std::set<std::shared_ptr<GeomAPI_Shape> >& theShapes)
815 {
816   // to split shape at least one point should be presented in the points container
817   if (thePointsInfo.empty())
818     return;
819
820     // General Fuse to split edge by vertices
821   BOPAlgo_Builder aBOP;
822   TopoDS_Edge aBaseEdge = theBaseShape->impl<TopoDS_Edge>();
823   // Rebuild closed edge to place vertex to one of split points.
824   // This will prevent edge to be split on same vertex.
825   if (BRep_Tool::IsClosed(aBaseEdge))
826   {
827     Standard_Real aFirst, aLast;
828     Handle(Geom_Curve) aCurve = BRep_Tool::Curve(aBaseEdge, aFirst, aLast);
829
830     PointToRefsMap::const_iterator aPIt = thePointsInfo.begin();
831     std::shared_ptr<GeomAPI_Pnt> aPnt = aPIt->first;
832     gp_Pnt aPoint(aPnt->x(), aPnt->y(), aPnt->z());
833
834     TopAbs_Orientation anOrientation = aBaseEdge.Orientation();
835     aBaseEdge = BRepBuilderAPI_MakeEdge(aCurve, aPoint, aPoint).Edge();
836     aBaseEdge.Orientation(anOrientation);
837   }
838   aBOP.AddArgument(aBaseEdge);
839
840   PointToRefsMap::const_iterator aPIt = thePointsInfo.begin();
841   for (; aPIt != thePointsInfo.end(); ++aPIt) {
842     std::shared_ptr<GeomAPI_Pnt> aPnt = aPIt->first;
843     TopoDS_Vertex aV = BRepBuilderAPI_MakeVertex(gp_Pnt(aPnt->x(), aPnt->y(), aPnt->z()));
844     aBOP.AddArgument(aV);
845   }
846
847   aBOP.Perform();
848   if (aBOP.HasErrors())
849     return;
850
851   // Collect splits
852   const TopTools_ListOfShape& aSplits = aBOP.Modified(aBaseEdge);
853   TopTools_ListIteratorOfListOfShape anIt(aSplits);
854   for (; anIt.More(); anIt.Next()) {
855     std::shared_ptr<GeomAPI_Shape> anEdge(new GeomAPI_Shape);
856     anEdge->setImpl(new TopoDS_Shape(anIt.Value()));
857     theShapes.insert(anEdge);
858   }
859 }
860
861 //==================================================================================================
862 void GeomAlgoAPI_ShapeTools::splitShape_p(const std::shared_ptr<GeomAPI_Shape>& theBaseShape,
863                                           const std::list<std::shared_ptr<GeomAPI_Pnt> >& thePoints,
864                                           std::set<std::shared_ptr<GeomAPI_Shape> >& theShapes)
865 {
866   // General Fuse to split edge by vertices
867   BOPAlgo_Builder aBOP;
868   TopoDS_Edge aBaseEdge = theBaseShape->impl<TopoDS_Edge>();
869   // Rebuild closed edge to place vertex to one of split points.
870   // This will prevent edge to be split on seam vertex.
871   if (BRep_Tool::IsClosed(aBaseEdge))
872   {
873     Standard_Real aFirst, aLast;
874     Handle(Geom_Curve) aCurve = BRep_Tool::Curve(aBaseEdge, aFirst, aLast);
875
876     std::list<std::shared_ptr<GeomAPI_Pnt> >::const_iterator aPIt = thePoints.begin();
877     gp_Pnt aPoint((*aPIt)->x(), (*aPIt)->y(), (*aPIt)->z());
878
879     TopAbs_Orientation anOrientation = aBaseEdge.Orientation();
880     aBaseEdge = BRepBuilderAPI_MakeEdge(aCurve, aPoint, aPoint).Edge();
881     aBaseEdge.Orientation(anOrientation);
882   }
883   aBOP.AddArgument(aBaseEdge);
884
885   std::list<std::shared_ptr<GeomAPI_Pnt> >::const_iterator aPtIt = thePoints.begin();
886   for (; aPtIt != thePoints.end(); ++aPtIt) {
887     std::shared_ptr<GeomAPI_Pnt> aPnt = *aPtIt;
888     TopoDS_Vertex aV = BRepBuilderAPI_MakeVertex(gp_Pnt(aPnt->x(), aPnt->y(), aPnt->z()));
889     aBOP.AddArgument(aV);
890   }
891
892   aBOP.Perform();
893   if (aBOP.HasErrors())
894     return;
895
896   // Collect splits
897   const TopTools_ListOfShape& aSplits = aBOP.Modified(aBaseEdge);
898   TopTools_ListIteratorOfListOfShape anIt(aSplits);
899   for (; anIt.More(); anIt.Next()) {
900     std::shared_ptr<GeomAPI_Shape> anEdge(new GeomAPI_Shape);
901     anEdge->setImpl(new TopoDS_Shape(anIt.Value()));
902     theShapes.insert(anEdge);
903   }
904 }
905
906 //==================================================================================================
907 std::shared_ptr<GeomAPI_Shape> GeomAlgoAPI_ShapeTools::findShape(
908                                   const std::list<std::shared_ptr<GeomAPI_Pnt> >& thePoints,
909                                   const std::set<std::shared_ptr<GeomAPI_Shape> >& theShapes)
910 {
911   std::shared_ptr<GeomAPI_Shape> aResultShape;
912
913   if (thePoints.size() == 2) {
914     std::list<std::shared_ptr<GeomAPI_Pnt> >::const_iterator aPntIt = thePoints.begin();
915     std::shared_ptr<GeomAPI_Pnt> aFirstPoint = *aPntIt;
916     aPntIt++;
917     std::shared_ptr<GeomAPI_Pnt> aLastPoint = *aPntIt;
918
919     std::set<std::shared_ptr<GeomAPI_Shape> >::const_iterator anIt = theShapes.begin(),
920                                                               aLast = theShapes.end();
921     for (; anIt != aLast; anIt++) {
922       GeomShapePtr aShape = *anIt;
923       std::shared_ptr<GeomAPI_Edge> anEdge(new GeomAPI_Edge(aShape));
924       if (anEdge.get()) {
925         std::shared_ptr<GeomAPI_Pnt> anEdgeFirstPoint = anEdge->firstPoint();
926         std::shared_ptr<GeomAPI_Pnt> anEdgeLastPoint = anEdge->lastPoint();
927         if (anEdgeFirstPoint->isEqual(aFirstPoint) &&
928             anEdgeLastPoint->isEqual(aLastPoint))
929             aResultShape = aShape;
930       }
931     }
932   }
933
934   return aResultShape;
935 }
936
937 //==================================================================================================
938 std::shared_ptr<GeomAPI_Dir> GeomAlgoAPI_ShapeTools::buildDirFromAxisAndShape(
939                                     const std::shared_ptr<GeomAPI_Shape> theBaseShape,
940                                     const std::shared_ptr<GeomAPI_Ax1> theAxis)
941 {
942   gp_Pnt aCentreOfMassPoint =
943     GeomAlgoAPI_ShapeTools::centreOfMass(theBaseShape)->impl<gp_Pnt>();
944   Handle(Geom_Line) aLine = new Geom_Line(theAxis->impl<gp_Ax1>());
945   GeomAPI_ProjectPointOnCurve aPrjTool(aCentreOfMassPoint, aLine);
946   gp_Pnt aPoint = aPrjTool.NearestPoint();
947
948   std::shared_ptr<GeomAPI_Dir> aDir(new GeomAPI_Dir(aCentreOfMassPoint.X()-aPoint.X(),
949                                                     aCentreOfMassPoint.Y()-aPoint.Y(),
950                                                     aCentreOfMassPoint.Z()-aPoint.Z()));
951   return aDir;
952 }
953
954 //==================================================================================================
955 static TopoDS_Wire fixParametricGaps(const TopoDS_Wire& theWire)
956 {
957   TopoDS_Wire aFixedWire;
958   Handle(Geom_Curve) aPrevCurve;
959   double aPrevLastParam = 0.0;
960
961   BRep_Builder aBuilder;
962   aBuilder.MakeWire(aFixedWire);
963
964   BRepTools_WireExplorer aWExp(theWire);
965   for (; aWExp.More(); aWExp.Next()) {
966     TopoDS_Edge anEdge = aWExp.Current();
967     double aFirst, aLast;
968     Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
969     if (aCurve == aPrevCurve) {
970       // if parametric gap occurs, create new edge based on the copied curve
971       aCurve = Handle(Geom_Curve)::DownCast(aCurve->Copy());
972       TopoDS_Vertex aV1, aV2;
973       TopExp::Vertices(anEdge, aV1, aV2);
974       anEdge = TopoDS::Edge(anEdge.EmptyCopied());
975       aBuilder.UpdateEdge(anEdge, aCurve, BRep_Tool::Tolerance(anEdge));
976       aBuilder.Add(anEdge, aV1);
977       aBuilder.Add(anEdge, aV2);
978     }
979
980     aBuilder.Add(aFixedWire, anEdge);
981
982     aPrevCurve = aCurve;
983     aPrevLastParam = aLast;
984   }
985
986   return aFixedWire;
987 }
988
989 std::shared_ptr<GeomAPI_Edge> GeomAlgoAPI_ShapeTools::wireToEdge(
990       const std::shared_ptr<GeomAPI_Wire>& theWire)
991 {
992   GeomEdgePtr anEdge;
993   if (theWire) {
994     TopoDS_Wire aWire = theWire->impl<TopoDS_Wire>();
995     // Workaround: when concatenate a wire consisting of two edges based on the same B-spline curve
996     // (non-periodic, but having equal start and end points), first of which is placed at the end
997     // on the curve and second is placed at the start, this workaround copies second curve to avoid
998     // treating these edges as a single curve by setting trim parameters.
999     aWire = fixParametricGaps(aWire);
1000     TopoDS_Edge aNewEdge = BRepAlgo::ConcatenateWireC0(aWire);
1001     anEdge = GeomEdgePtr(new GeomAPI_Edge);
1002     anEdge->setImpl(new TopoDS_Edge(aNewEdge));
1003   }
1004   return anEdge;
1005 }