Salome HOME
Issue #1649: Added CPP High API for Plane feature;
[modules/shaper.git] / src / GeomAlgoAPI / GeomAlgoAPI_ShapeTools.cpp
1 // Copyright (C) 2014-20xx CEA/DEN, EDF R&D
2
3 // File:        GeomAlgoAPI_ShapeTools.h
4 // Created:     3 August 2015
5 // Author:      Dmitry Bobylev
6
7 #include "GeomAlgoAPI_ShapeTools.h"
8
9 #include "GeomAlgoAPI_SketchBuilder.h"
10
11 #include <GeomAPI_Edge.h>
12 #include <GeomAPI_Dir.h>
13 #include <GeomAPI_Face.h>
14 #include <GeomAPI_Pln.h>
15 #include <GeomAPI_Pnt.h>
16
17 #include <Bnd_Box.hxx>
18 #include <BOPTools.hxx>
19 #include <BRep_Builder.hxx>
20 #include <BRepAdaptor_Curve.hxx>
21 #include <BRepAlgo_FaceRestrictor.hxx>
22 #include <BRepBndLib.hxx>
23 #include <BRepBuilderAPI_FindPlane.hxx>
24 #include <BRepBuilderAPI_MakeEdge.hxx>
25 #include <BRepBuilderAPI_MakeFace.hxx>
26 #include <BRepCheck_Analyzer.hxx>
27 #include <BRepExtrema_DistShapeShape.hxx>
28 #include <BRepExtrema_ExtCF.hxx>
29 #include <BRepGProp.hxx>
30 #include <BRepTools.hxx>
31 #include <BRepTopAdaptor_FClass2d.hxx>
32 #include <Geom2d_Curve.hxx>
33 #include <Handle_Geom2d_Curve.hxx>
34 #include <BRepLib_CheckCurveOnSurface.hxx>
35 #include <BRep_Tool.hxx>
36 #include <Geom_Plane.hxx>
37 #include <GeomLib_IsPlanarSurface.hxx>
38 #include <GeomLib_Tool.hxx>
39 #include <gp_Pln.hxx>
40 #include <GProp_GProps.hxx>
41 #include <IntAna_IntConicQuad.hxx>
42 #include <IntAna_Quadric.hxx>
43 #include <NCollection_Vector.hxx>
44 #include <ShapeAnalysis.hxx>
45 #include <ShapeAnalysis_Surface.hxx>
46 #include <TopoDS_Builder.hxx>
47 #include <TopoDS_Edge.hxx>
48 #include <TopoDS_Face.hxx>
49 #include <TopoDS_Shape.hxx>
50 #include <TopoDS_Shell.hxx>
51 #include <TopoDS_Vertex.hxx>
52 #include <TopoDS.hxx>
53 #include <TopExp_Explorer.hxx>
54 #include <TopTools_ListIteratorOfListOfShape.hxx>
55
56 #include <BOPAlgo_Builder.hxx>
57 #include <BRepBuilderAPI_MakeVertex.hxx>
58 #include <TopoDS_Edge.hxx>
59
60 //==================================================================================================
61 double GeomAlgoAPI_ShapeTools::volume(const std::shared_ptr<GeomAPI_Shape> theShape)
62 {
63   GProp_GProps aGProps;
64   if(!theShape.get()) {
65     return 0.0;
66   }
67   const TopoDS_Shape& aShape = theShape->impl<TopoDS_Shape>();
68   if(aShape.IsNull()) {
69     return 0.0;
70   }
71   const Standard_Real anEps = 1.e-6;
72   BRepGProp::VolumeProperties(aShape, aGProps, anEps);
73   return aGProps.Mass();
74 }
75
76 //==================================================================================================
77 std::shared_ptr<GeomAPI_Pnt> GeomAlgoAPI_ShapeTools::centreOfMass(const std::shared_ptr<GeomAPI_Shape> theShape)
78 {
79   GProp_GProps aGProps;
80   if(!theShape) {
81     return std::shared_ptr<GeomAPI_Pnt>();
82   }
83   const TopoDS_Shape& aShape = theShape->impl<TopoDS_Shape>();
84   if(aShape.IsNull()) {
85     return std::shared_ptr<GeomAPI_Pnt>();
86   }
87   gp_Pnt aCentre;
88   if(aShape.ShapeType() == TopAbs_VERTEX) {
89     aCentre = BRep_Tool::Pnt(TopoDS::Vertex(aShape));
90   } else if(aShape.ShapeType() == TopAbs_EDGE || aShape.ShapeType() == TopAbs_WIRE) {
91     BRepGProp::LinearProperties(aShape, aGProps);
92     aCentre = aGProps.CentreOfMass();
93   } else {
94     BRepGProp::SurfaceProperties(aShape, aGProps);
95     aCentre = aGProps.CentreOfMass();
96   }
97   return std::shared_ptr<GeomAPI_Pnt>(new GeomAPI_Pnt(aCentre.X(), aCentre.Y(), aCentre.Z()));
98 }
99
100 //==================================================================================================
101 std::shared_ptr<GeomAPI_Shape> GeomAlgoAPI_ShapeTools::combineShapes(const std::shared_ptr<GeomAPI_Shape> theCompound,
102                                                                      const GeomAPI_Shape::ShapeType theType,
103                                                                      ListOfShape& theCombinedShapes,
104                                                                      ListOfShape& theFreeShapes)
105 {
106   GeomShapePtr aResult = theCompound;
107
108   if(!theCompound.get()) {
109     return aResult;
110   }
111
112   if(theType != GeomAPI_Shape::SHELL && theType != GeomAPI_Shape::COMPSOLID) {
113     return aResult;
114   }
115
116   TopAbs_ShapeEnum aTS = TopAbs_EDGE;
117   TopAbs_ShapeEnum aTA = TopAbs_FACE;
118   if(theType == GeomAPI_Shape::COMPSOLID) {
119     aTS = TopAbs_FACE;
120     aTA = TopAbs_SOLID;
121   }
122
123   theCombinedShapes.clear();
124   theFreeShapes.clear();
125
126   // Get free shapes.
127   const TopoDS_Shape& aShapesComp = theCompound->impl<TopoDS_Shape>();
128   for(TopoDS_Iterator anIter(aShapesComp); anIter.More(); anIter.Next() ) {
129     const TopoDS_Shape& aShape = anIter.Value();
130     if(aShape.ShapeType() > aTA) {
131       std::shared_ptr<GeomAPI_Shape> aGeomShape(new GeomAPI_Shape);
132       aGeomShape->setImpl<TopoDS_Shape>(new TopoDS_Shape(aShape));
133       theFreeShapes.push_back(aGeomShape);
134     }
135   }
136
137   // Map subshapes and shapes.
138   BOPCol_IndexedDataMapOfShapeListOfShape aMapSA;
139   BOPTools::MapShapesAndAncestors(aShapesComp, aTS, aTA, aMapSA);
140   if(aMapSA.IsEmpty()) {
141     return aResult;
142   }
143
144   // Get all shapes with common subshapes and free shapes.
145   NCollection_Map<TopoDS_Shape> aFreeShapes;
146   NCollection_Vector<NCollection_Map<TopoDS_Shape>> aShapesWithCommonSubshapes;
147   for(BOPCol_IndexedDataMapOfShapeListOfShape::Iterator anIter(aMapSA); anIter.More(); anIter.Next()) {
148     const TopoDS_Shape& aShape = anIter.Key();
149     BOPCol_ListOfShape& aListOfShape = anIter.ChangeValue();
150     if(aListOfShape.IsEmpty()) {
151       continue;
152     }
153     else if(aListOfShape.Size() == 1) {
154       const TopoDS_Shape& aF = aListOfShape.First();
155       aFreeShapes.Add(aF);
156       aListOfShape.Clear();
157     } else {
158       NCollection_List<TopoDS_Shape> aTempList;
159       NCollection_Map<TopoDS_Shape> aTempMap;
160       const TopoDS_Shape& aF = aListOfShape.First();
161       const TopoDS_Shape& aL = aListOfShape.Last();
162       aTempList.Append(aF);
163       aTempList.Append(aL);
164       aTempMap.Add(aF);
165       aTempMap.Add(aL);
166       aFreeShapes.Remove(aF);
167       aFreeShapes.Remove(aL);
168       aListOfShape.Clear();
169       for(NCollection_List<TopoDS_Shape>::Iterator aTempIter(aTempList); aTempIter.More(); aTempIter.Next()) {
170         const TopoDS_Shape& aTempShape = aTempIter.Value();
171         for(BOPCol_IndexedDataMapOfShapeListOfShape::Iterator anIter(aMapSA); anIter.More(); anIter.Next()) {
172           BOPCol_ListOfShape& aTempListOfShape = anIter.ChangeValue();
173           if(aTempListOfShape.IsEmpty()) {
174             continue;
175           } else if(aTempListOfShape.Size() == 1 && aTempListOfShape.First() == aTempShape) {
176             aTempListOfShape.Clear();
177           } else if(aTempListOfShape.Size() > 1) {
178             if(aTempListOfShape.First() == aTempShape) {
179               const TopoDS_Shape& aTL = aTempListOfShape.Last();
180               if(aTempMap.Add(aTL)) {
181                 aTempList.Append(aTL);
182                 aFreeShapes.Remove(aTL);
183               }
184               aTempListOfShape.Clear();
185             } else if(aTempListOfShape.Last() == aTempShape) {
186               const TopoDS_Shape& aTF = aTempListOfShape.First();
187               if(aTempMap.Add(aTF)) {
188                 aTempList.Append(aTF);
189                 aFreeShapes.Remove(aTF);
190               }
191               aTempListOfShape.Clear();
192             }
193           }
194         }
195       }
196       aShapesWithCommonSubshapes.Append(aTempMap);
197     }
198   }
199
200   // Combine shapes with common subshapes.
201   for(NCollection_Vector<NCollection_Map<TopoDS_Shape>>::Iterator anIter(aShapesWithCommonSubshapes); anIter.More(); anIter.Next()) {
202     TopoDS_Shell aShell;
203     TopoDS_CompSolid aCSolid;
204     TopoDS_Builder aBuilder;
205     theType == GeomAPI_Shape::COMPSOLID ? aBuilder.MakeCompSolid(aCSolid) : aBuilder.MakeShell(aShell);
206     NCollection_Map<TopoDS_Shape>& aShapesMap = anIter.ChangeValue();
207     for(TopExp_Explorer anExp(aShapesComp, aTA); anExp.More(); anExp.Next()) {
208       const TopoDS_Shape& aShape = anExp.Current();
209       if(aShapesMap.Contains(aShape)) {
210         theType == GeomAPI_Shape::COMPSOLID ? aBuilder.Add(aCSolid, aShape) : aBuilder.Add(aShell, aShape);
211         aShapesMap.Remove(aShape);
212       }
213     }
214     std::shared_ptr<GeomAPI_Shape> aGeomShape(new GeomAPI_Shape);
215     TopoDS_Shape* aSh = theType == GeomAPI_Shape::COMPSOLID ? new TopoDS_Shape(aCSolid) : new TopoDS_Shape(aShell);
216     aGeomShape->setImpl<TopoDS_Shape>(aSh);
217     theCombinedShapes.push_back(aGeomShape);
218   }
219
220   // Adding free shapes.
221   for(TopExp_Explorer anExp(aShapesComp, aTA); anExp.More(); anExp.Next()) {
222     const TopoDS_Shape& aShape = anExp.Current();
223     if(aFreeShapes.Contains(aShape)) {
224       std::shared_ptr<GeomAPI_Shape> aGeomShape(new GeomAPI_Shape);
225       aGeomShape->setImpl<TopoDS_Shape>(new TopoDS_Shape(aShape));
226       theFreeShapes.push_back(aGeomShape);
227     }
228   }
229
230   if(theCombinedShapes.size() == 1 && theFreeShapes.size() == 0) {
231     aResult = theCombinedShapes.front();
232   } else if(theCombinedShapes.size() == 0 && theFreeShapes.size() == 1) {
233     aResult = theFreeShapes.front();
234   } else {
235     TopoDS_Compound aResultComp;
236     TopoDS_Builder aBuilder;
237     aBuilder.MakeCompound(aResultComp);
238     for(ListOfShape::const_iterator anIter = theCombinedShapes.cbegin(); anIter != theCombinedShapes.cend(); anIter++) {
239       aBuilder.Add(aResultComp, (*anIter)->impl<TopoDS_Shape>());
240     }
241     for(ListOfShape::const_iterator anIter = theFreeShapes.cbegin(); anIter != theFreeShapes.cend(); anIter++) {
242       aBuilder.Add(aResultComp, (*anIter)->impl<TopoDS_Shape>());
243     }
244     aResult->setImpl(new TopoDS_Shape(aResultComp));
245   }
246
247   return aResult;
248 }
249
250 //==================================================================================================
251 static void addSimpleShapeToList(const TopoDS_Shape& theShape, NCollection_List<TopoDS_Shape>& theList)
252 {
253   if(theShape.IsNull()) {
254     return;
255   }
256
257   if(theShape.ShapeType() == TopAbs_COMPOUND) {
258     for(TopoDS_Iterator anIt(theShape); anIt.More(); anIt.Next()) {
259       addSimpleShapeToList(anIt.Value(), theList);
260     }
261   } else {
262     theList.Append(theShape);
263   }
264 }
265
266 //==================================================================================================
267 static TopoDS_Compound makeCompound(const NCollection_List<TopoDS_Shape> theShapes)
268 {
269   TopoDS_Compound aCompound;
270
271   BRep_Builder aBuilder;
272   aBuilder.MakeCompound(aCompound);
273
274   for(NCollection_List<TopoDS_Shape>::Iterator anIt(theShapes); anIt.More(); anIt.Next()) {
275     aBuilder.Add(aCompound, anIt.Value());
276   }
277
278   return aCompound;
279 }
280
281 //==================================================================================================
282 std::shared_ptr<GeomAPI_Shape> GeomAlgoAPI_ShapeTools::groupSharedTopology(const std::shared_ptr<GeomAPI_Shape> theCompound)
283 {
284   GeomShapePtr aResult = theCompound;
285
286   if(!theCompound.get()) {
287     return aResult;
288   }
289
290   TopoDS_Shape anInShape = aResult->impl<TopoDS_Shape>();
291   NCollection_List<TopoDS_Shape> anUngroupedShapes;
292   addSimpleShapeToList(anInShape, anUngroupedShapes);
293
294   NCollection_Vector<NCollection_List<TopoDS_Shape>> aGroups;
295   while(!anUngroupedShapes.IsEmpty()) {
296     NCollection_List<TopoDS_Shape> aGroupedShapes;
297     aGroupedShapes.Append(anUngroupedShapes.First());
298     anUngroupedShapes.RemoveFirst();
299     for(NCollection_List<TopoDS_Shape>::Iterator aGroupIt(aGroupedShapes); aGroupIt.More(); aGroupIt.Next()) {
300       const TopoDS_Shape& aGroupShape = aGroupIt.Value();
301       for(NCollection_List<TopoDS_Shape>::Iterator anUngroupedIt(anUngroupedShapes); anUngroupedIt.More(); anUngroupedIt.Next()) {
302         const TopoDS_Shape& anUngroupedShape = anUngroupedIt.Value();
303         bool isFound = false;
304         for(TopExp_Explorer aGroupShapeExp(aGroupShape, TopAbs_VERTEX); aGroupShapeExp.More(); aGroupShapeExp.Next()) {
305           const TopoDS_Shape& aVertex1 = aGroupShapeExp.Current();
306           for(TopExp_Explorer anUngroupedShapeExp(anUngroupedShape, TopAbs_VERTEX); anUngroupedShapeExp.More(); anUngroupedShapeExp.Next()) {
307             const TopoDS_Shape& aVertex2 = anUngroupedShapeExp.Current();
308             if(aVertex1.IsSame(aVertex2)) {
309               aGroupedShapes.Append(anUngroupedShape);
310               anUngroupedShapes.Remove(anUngroupedIt);
311               isFound = true;
312               break;
313             }
314           }
315           if(isFound) {
316             break;
317           }
318         }
319         if(!anUngroupedIt.More()) {
320           break;
321         }
322       }
323     }
324     aGroups.Append(aGroupedShapes);
325   }
326
327   if(aGroups.Size() == 1) {
328     NCollection_List<TopoDS_Shape> aGroup = aGroups.First();
329     GeomShapePtr aGeomShape(new GeomAPI_Shape());
330     aGeomShape->setImpl(new TopoDS_Shape(makeCompound(aGroup)));
331     ListOfShape aCompSolids, aFreeSolids;
332     aGeomShape = GeomAlgoAPI_ShapeTools::combineShapes(aGeomShape,
333                                                         GeomAPI_Shape::COMPSOLID,
334                                                         aCompSolids,
335                                                         aFreeSolids);
336     aResult = aGeomShape;
337   } else {
338     TopoDS_Compound aCompound;
339     BRep_Builder aBuilder;
340     aBuilder.MakeCompound(aCompound);
341     ListOfShape aCompSolids, aFreeSolids;
342     for(NCollection_Vector<NCollection_List<TopoDS_Shape>>::Iterator anIt(aGroups); anIt.More(); anIt.Next()) {
343       NCollection_List<TopoDS_Shape> aGroup = anIt.Value();
344       GeomShapePtr aGeomShape(new GeomAPI_Shape());
345       if(aGroup.Size() == 1) {
346         aGeomShape->setImpl(new TopoDS_Shape(aGroup.First()));
347       } else {
348         aGeomShape->setImpl(new TopoDS_Shape(makeCompound(aGroup)));
349         aGeomShape = GeomAlgoAPI_ShapeTools::combineShapes(aGeomShape,
350                                                            GeomAPI_Shape::COMPSOLID,
351                                                            aCompSolids,
352                                                            aFreeSolids);
353       }
354       aBuilder.Add(aCompound, aGeomShape->impl<TopoDS_Shape>());
355     }
356
357     if(!aCompound.IsNull()) {
358       aResult->setImpl(new TopoDS_Shape(aCompound));
359     }
360   }
361
362   return aResult;
363 }
364
365 //==================================================================================================
366 std::list<std::shared_ptr<GeomAPI_Pnt> > GeomAlgoAPI_ShapeTools::getBoundingBox(const ListOfShape& theShapes, const double theEnlarge)
367 {
368   // Bounding box of all objects.
369   Bnd_Box aBndBox;
370
371   // Getting box.
372   for (ListOfShape::const_iterator anObjectsIt = theShapes.begin(); anObjectsIt != theShapes.end(); anObjectsIt++) {
373     const TopoDS_Shape& aShape = (*anObjectsIt)->impl<TopoDS_Shape>();
374     BRepBndLib::Add(aShape, aBndBox);
375   }
376
377   if(theEnlarge != 0.0) {
378     // We enlarge bounding box just to be sure that plane will be large enough to cut all objects.
379     aBndBox.Enlarge(theEnlarge);
380   }
381
382   Standard_Real aXArr[2] = {aBndBox.CornerMin().X(), aBndBox.CornerMax().X()};
383   Standard_Real aYArr[2] = {aBndBox.CornerMin().Y(), aBndBox.CornerMax().Y()};
384   Standard_Real aZArr[2] = {aBndBox.CornerMin().Z(), aBndBox.CornerMax().Z()};
385   std::list<std::shared_ptr<GeomAPI_Pnt> > aResultPoints;
386   int aNum = 0;
387   for(int i = 0; i < 2; i++) {
388     for(int j = 0; j < 2; j++) {
389       for(int k = 0; k < 2; k++) {
390         std::shared_ptr<GeomAPI_Pnt> aPnt(new GeomAPI_Pnt(aXArr[i], aYArr[j], aZArr[k]));
391         aResultPoints.push_back(aPnt);
392       }
393     }
394   }
395
396   return aResultPoints;
397 }
398
399 //==================================================================================================
400 std::shared_ptr<GeomAPI_Shape> GeomAlgoAPI_ShapeTools::faceToInfinitePlane(const std::shared_ptr<GeomAPI_Shape> theFace)
401 {
402   if (!theFace.get())
403     return std::shared_ptr<GeomAPI_Shape>();
404
405   TopoDS_Face aPlaneFace = TopoDS::Face(theFace->impl<TopoDS_Shape>());
406   if (aPlaneFace.IsNull())
407     return std::shared_ptr<GeomAPI_Shape>();
408
409   Handle(Geom_Plane) aPlane = Handle(Geom_Plane)::DownCast(BRep_Tool::Surface(aPlaneFace));
410   if (aPlane.IsNull())
411     return std::shared_ptr<GeomAPI_Shape>();
412
413   // make an infinity face on the plane
414   TopoDS_Shape anInfiniteFace = BRepBuilderAPI_MakeFace(aPlane->Pln()).Shape();
415
416   std::shared_ptr<GeomAPI_Shape> aResult(new GeomAPI_Shape);
417   aResult->setImpl(new TopoDS_Shape(anInfiniteFace));
418   return aResult;
419 }
420
421 //==================================================================================================
422 std::shared_ptr<GeomAPI_Face> GeomAlgoAPI_ShapeTools::fitPlaneToBox(const std::shared_ptr<GeomAPI_Shape> thePlane,
423                                                                     const std::list<std::shared_ptr<GeomAPI_Pnt> >& thePoints)
424 {
425   std::shared_ptr<GeomAPI_Face> aResultFace;
426
427   if(!thePlane.get()) {
428     return aResultFace;
429   }
430
431   const TopoDS_Shape& aShape = thePlane->impl<TopoDS_Shape>();
432   if(aShape.ShapeType() != TopAbs_FACE) {
433     return aResultFace;
434   }
435
436   TopoDS_Face aFace = TopoDS::Face(aShape);
437   Handle(Geom_Surface) aSurf = BRep_Tool::Surface(aFace);
438   if(aSurf.IsNull()) {
439     return aResultFace;
440   }
441
442   GeomLib_IsPlanarSurface isPlanar(aSurf);
443   if(!isPlanar.IsPlanar()) {
444     return aResultFace;
445   }
446
447   if(thePoints.size() != 8) {
448     return aResultFace;
449   }
450
451   const gp_Pln& aFacePln = isPlanar.Plan();
452   Handle(Geom_Plane) aFacePlane = new Geom_Plane(aFacePln);
453   IntAna_Quadric aQuadric(aFacePln);
454   Standard_Real UMin, UMax, VMin, VMax;
455   UMin = UMax = VMin = VMax = 0;
456   for (std::list<std::shared_ptr<GeomAPI_Pnt> >::const_iterator aPointsIt = thePoints.begin(); aPointsIt != thePoints.end(); aPointsIt++) {
457     const gp_Pnt& aPnt = (*aPointsIt)->impl<gp_Pnt>();
458     gp_Lin aLin(aPnt, aFacePln.Axis().Direction());
459     IntAna_IntConicQuad anIntAna(aLin, aQuadric);
460     const gp_Pnt& aPntOnFace = anIntAna.Point(1);
461     Standard_Real aPntU(0), aPntV(0);
462     GeomLib_Tool::Parameters(aFacePlane, aPntOnFace, Precision::Confusion(), aPntU, aPntV);
463     if(aPntU < UMin) UMin = aPntU;
464     if(aPntU > UMax) UMax = aPntU;
465     if(aPntV < VMin) VMin = aPntV;
466     if(aPntV > VMax) VMax = aPntV;
467   }
468   aResultFace.reset(new GeomAPI_Face());
469   aResultFace->setImpl(new TopoDS_Face(BRepLib_MakeFace(aFacePln, UMin, UMax, VMin, VMax).Face()));
470
471   return aResultFace;
472 }
473
474 //==================================================================================================
475 void GeomAlgoAPI_ShapeTools::findBounds(const std::shared_ptr<GeomAPI_Shape> theShape,
476                                         std::shared_ptr<GeomAPI_Vertex>& theV1,
477                                         std::shared_ptr<GeomAPI_Vertex>& theV2)
478 {
479   if(!theShape.get()) {
480     std::shared_ptr<GeomAPI_Vertex> aVertex(new GeomAPI_Vertex);
481     aVertex->setImpl(new TopoDS_Vertex());
482     theV1 = aVertex;
483     theV2 = aVertex;
484     return;
485   }
486
487   const TopoDS_Shape& aShape = theShape->impl<TopoDS_Shape>();
488   TopoDS_Vertex aV1, aV2;
489   ShapeAnalysis::FindBounds(aShape, aV1, aV2);
490
491   std::shared_ptr<GeomAPI_Vertex> aGeomV1(new GeomAPI_Vertex()), aGeomV2(new GeomAPI_Vertex());
492   aGeomV1->setImpl(new TopoDS_Vertex(aV1));
493   aGeomV2->setImpl(new TopoDS_Vertex(aV2));
494   theV1 = aGeomV1;
495   theV2 = aGeomV2;
496 }
497
498 //==================================================================================================
499 void GeomAlgoAPI_ShapeTools::makeFacesWithHoles(const std::shared_ptr<GeomAPI_Pnt> theOrigin,
500                                                 const std::shared_ptr<GeomAPI_Dir> theDirection,
501                                                 const ListOfShape& theWires,
502                                                 ListOfShape& theFaces)
503 {
504   BRepBuilderAPI_MakeFace aMKFace(gp_Pln(theOrigin->impl<gp_Pnt>(),
505                                           theDirection->impl<gp_Dir>()));
506   TopoDS_Face aFace = aMKFace.Face();
507
508   BRepAlgo_FaceRestrictor aFRestrictor;
509   aFRestrictor.Init(aFace, Standard_False, Standard_True);
510   for(ListOfShape::const_iterator anIt = theWires.cbegin();
511       anIt != theWires.cend();
512       ++anIt) {
513     TopoDS_Wire aWire = TopoDS::Wire((*anIt)->impl<TopoDS_Shape>());
514     aFRestrictor.Add(aWire);
515   }
516
517   aFRestrictor.Perform();
518
519   if(!aFRestrictor.IsDone()) {
520     return;
521   }
522
523   for(; aFRestrictor.More(); aFRestrictor.Next()) {
524     GeomShapePtr aShape(new GeomAPI_Shape());
525     aShape->setImpl(new TopoDS_Shape(aFRestrictor.Current()));
526     theFaces.push_back(aShape);
527   }
528 }
529
530 //==================================================================================================
531 std::shared_ptr<GeomAPI_Pln> GeomAlgoAPI_ShapeTools::findPlane(const ListOfShape& theShapes)
532 {
533   TopoDS_Compound aCompound;
534   BRep_Builder aBuilder;
535   aBuilder.MakeCompound(aCompound);
536
537   for(ListOfShape::const_iterator anIt = theShapes.cbegin(); anIt != theShapes.cend(); ++anIt) {
538     aBuilder.Add(aCompound, (*anIt)->impl<TopoDS_Shape>());
539   }
540   BRepBuilderAPI_FindPlane aFindPlane(aCompound);
541
542   if(aFindPlane.Found() != Standard_True) {
543     return std::shared_ptr<GeomAPI_Pln>();
544   }
545
546   Handle(Geom_Plane) aPlane = aFindPlane.Plane();
547   gp_Pnt aLoc = aPlane->Location();
548   gp_Dir aDir = aPlane->Axis().Direction();
549
550   std::shared_ptr<GeomAPI_Pnt> aGeomPnt(new GeomAPI_Pnt(aLoc.X(), aLoc.Y(), aLoc.Z()));
551   std::shared_ptr<GeomAPI_Dir> aGeomDir(new GeomAPI_Dir(aDir.X(), aDir.Y(), aDir.Z()));
552
553   std::shared_ptr<GeomAPI_Pln> aPln(new GeomAPI_Pln(aGeomPnt, aGeomDir));
554
555   return aPln;
556 }
557
558 //==================================================================================================
559 bool GeomAlgoAPI_ShapeTools::isSubShapeInsideShape(const std::shared_ptr<GeomAPI_Shape> theSubShape,
560                                                    const std::shared_ptr<GeomAPI_Shape> theBaseShape)
561 {
562   if(!theSubShape.get() || !theBaseShape.get()) {
563     return false;
564   }
565
566   const TopoDS_Shape& aSubShape = theSubShape->impl<TopoDS_Shape>();
567   const TopoDS_Shape& aBaseShape = theBaseShape->impl<TopoDS_Shape>();
568
569   if(aSubShape.ShapeType() == TopAbs_VERTEX) {
570     // If sub-shape is a vertex check distance to shape. If it is <= Precision::Confusion() then OK.
571     BRepExtrema_DistShapeShape aDist(aBaseShape, aSubShape);
572     aDist.Perform();
573     if(!aDist.IsDone() || aDist.Value() > Precision::Confusion()) {
574       return false;
575     }
576   } else if (aSubShape.ShapeType() == TopAbs_EDGE) {
577     if(aBaseShape.ShapeType() == TopAbs_FACE) {
578       // Check that edge is on face surface.
579       TopoDS_Face aFace = TopoDS::Face(aBaseShape);
580       TopoDS_Edge anEdge = TopoDS::Edge(aSubShape);
581       BRepLib_CheckCurveOnSurface aCheck(anEdge, aFace);
582       aCheck.Perform();
583       if(!aCheck.IsDone() || aCheck.MaxDistance() > Precision::Confusion()) {
584         return false;
585       }
586
587       // Check intersections.
588       TopoDS_Vertex aV1, aV2;
589       ShapeAnalysis::FindBounds(anEdge, aV1, aV2);
590       gp_Pnt aPnt1 = BRep_Tool::Pnt(aV1);
591       gp_Pnt aPnt2 = BRep_Tool::Pnt(aV2);
592       for(TopExp_Explorer anExp(aBaseShape, TopAbs_EDGE); anExp.More(); anExp.Next()) {
593         const TopoDS_Shape& anEdgeOnFace = anExp.Current();
594         BRepExtrema_DistShapeShape aDist(anEdgeOnFace, anEdge);
595         aDist.Perform();
596         if(aDist.IsDone() && aDist.Value() <= Precision::Confusion()) {
597           // Edge intersect face bound. Check that it is not on edge begin or end.
598           for(Standard_Integer anIndex = 1; anIndex <= aDist.NbSolution(); ++anIndex) {
599             gp_Pnt aPntOnSubShape = aDist.PointOnShape2(anIndex);
600             if(aPntOnSubShape.Distance(aPnt1) > Precision::Confusion()
601                 && aPntOnSubShape.Distance(aPnt2) > Precision::Confusion()) {
602               return false;
603             }
604           }
605         }
606       }
607
608       // No intersections found. Edge is inside or outside face. Check it.
609       BRepAdaptor_Curve aCurveAdaptor(anEdge);
610       gp_Pnt aPointToCheck = aCurveAdaptor.Value((aCurveAdaptor.FirstParameter() + aCurveAdaptor.LastParameter()) / 2.0);
611       Handle(Geom_Surface) aSurface = BRep_Tool::Surface(aFace);
612       ShapeAnalysis_Surface aSAS(aSurface);
613       gp_Pnt2d aPointOnFace = aSAS.ValueOfUV(aPointToCheck, Precision::Confusion());
614       BRepTopAdaptor_FClass2d aFClass2d(aFace, Precision::Confusion());
615       if(aFClass2d.Perform(aPointOnFace) == TopAbs_OUT) {
616         return false;
617       }
618
619     } else {
620       return false;
621     }
622   } else {
623     return false;
624   }
625
626   return true;
627 }
628
629 //==================================================================================================
630 bool GeomAlgoAPI_ShapeTools::isShapeValid(const std::shared_ptr<GeomAPI_Shape> theShape)
631 {
632   if(!theShape.get()) {
633     return false;
634   }
635
636   BRepCheck_Analyzer aChecker(theShape->impl<TopoDS_Shape>());
637   return (aChecker.IsValid() == Standard_True);
638 }
639
640 //==================================================================================================
641 std::shared_ptr<GeomAPI_Shape> GeomAlgoAPI_ShapeTools::getFaceOuterWire(const std::shared_ptr<GeomAPI_Shape> theFace)
642 {
643   GeomShapePtr anOuterWire;
644
645   if(!theFace.get() || !theFace->isFace()) {
646     return anOuterWire;
647   }
648
649   TopoDS_Face aFace = TopoDS::Face(theFace->impl<TopoDS_Shape>());
650   TopoDS_Wire aWire = BRepTools::OuterWire(aFace);
651
652   anOuterWire.reset(new GeomAPI_Shape());
653   anOuterWire->setImpl(new TopoDS_Shape(aWire));
654
655   return anOuterWire;
656 }
657
658 //==================================================================================================
659 bool GeomAlgoAPI_ShapeTools::isParallel(const std::shared_ptr<GeomAPI_Edge> theEdge,
660                                         const std::shared_ptr<GeomAPI_Face> theFace)
661 {
662   if(!theEdge.get() || !theFace.get()) {
663     return false;
664   }
665
666   TopoDS_Edge anEdge = TopoDS::Edge(theEdge->impl<TopoDS_Shape>());
667   TopoDS_Face aFace  = TopoDS::Face(theFace->impl<TopoDS_Shape>());
668
669   BRepExtrema_ExtCF anExt(anEdge, aFace);
670   return anExt.IsParallel() == Standard_True;
671 }
672
673 //==================================================================================================
674 void GeomAlgoAPI_ShapeTools::splitShape(const std::shared_ptr<GeomAPI_Shape>& theBaseShape,
675                                         const std::set<std::shared_ptr<GeomAPI_Pnt> >& thePoints,
676                                         std::set<std::shared_ptr<GeomAPI_Shape> >& theShapes)
677 {
678   // General Fuse to split edge by vertices
679   BOPAlgo_Builder aBOP;
680   TopoDS_Edge aBaseEdge = theBaseShape->impl<TopoDS_Edge>();
681   // Rebuild closed edge to place vertex to one of split points.
682   // This will prevent edge to be split on seam vertex.
683   if (BRep_Tool::IsClosed(aBaseEdge))
684   {
685     Standard_Real aFirst, aLast;
686     Handle(Geom_Curve) aCurve = BRep_Tool::Curve(aBaseEdge, aFirst, aLast);
687
688     std::set<std::shared_ptr<GeomAPI_Pnt> >::const_iterator aPIt = thePoints.begin();
689     gp_Pnt aPoint((*aPIt)->x(), (*aPIt)->y(), (*aPIt)->z());
690
691     TopAbs_Orientation anOrientation = aBaseEdge.Orientation();
692     aBaseEdge = BRepBuilderAPI_MakeEdge(aCurve, aPoint, aPoint).Edge();
693     aBaseEdge.Orientation(anOrientation);
694   }
695   aBOP.AddArgument(aBaseEdge);
696
697   std::set<std::shared_ptr<GeomAPI_Pnt> >::const_iterator aPtIt = thePoints.begin();
698   for (; aPtIt != thePoints.end(); ++aPtIt) {
699     std::shared_ptr<GeomAPI_Pnt> aPnt = *aPtIt;
700     TopoDS_Vertex aV = BRepBuilderAPI_MakeVertex(gp_Pnt(aPnt->x(), aPnt->y(), aPnt->z()));
701     aBOP.AddArgument(aV);
702   }
703
704   aBOP.Perform();
705   if (aBOP.ErrorStatus())
706     return;
707   
708   // Collect splits
709   const TopTools_ListOfShape& aSplits = aBOP.Modified(aBaseEdge);
710   TopTools_ListIteratorOfListOfShape anIt(aSplits);
711   for (; anIt.More(); anIt.Next()) {
712     std::shared_ptr<GeomAPI_Shape> anEdge(new GeomAPI_Shape);
713     anEdge->setImpl(new TopoDS_Shape(anIt.Value()));
714     theShapes.insert(anEdge);
715   }
716 }