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