Salome HOME
Issue 2192: Partition very long
[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   // Iterate over all shapes and find shapes with shared vertices.
322   TopTools_ListOfShape aMapOrder;
323   BOPCol_DataMapOfShapeListOfShape aVertexShapesMap;
324   for(NCollection_List<TopoDS_Shape>::Iterator aShapesIt(anUngroupedShapes);
325       aShapesIt.More();
326       aShapesIt.Next()) {
327     const TopoDS_Shape& aShape = aShapesIt.Value();
328     for(TopExp_Explorer aShapeExp(aShape, TopAbs_VERTEX);
329         aShapeExp.More();
330         aShapeExp.Next()) {
331       const TopoDS_Shape& aVertex = aShapeExp.Current();
332       if (!aVertexShapesMap.IsBound(aVertex)) {
333         NCollection_List<TopoDS_Shape> aList;
334         aList.Append(aShape);
335         aMapOrder.Append(aVertex);
336         aVertexShapesMap.Bind(aVertex, aList);
337       } else {
338         if(!aVertexShapesMap.ChangeFind(aVertex).Contains(aShape)) {
339           aVertexShapesMap.ChangeFind(aVertex).Append(aShape);
340         }
341       }
342     }
343   }
344
345   // Iterate over the map and group shapes.
346   NCollection_Vector<TopTools_ListOfShape> aGroups;
347   while (!aMapOrder.IsEmpty()) {
348     // Get first group of shapes in map, and then unbind it.
349     const TopoDS_Shape& aKey = aMapOrder.First();
350     TopTools_ListOfShape aGroupedShapes = aVertexShapesMap.Find(aKey);
351     aVertexShapesMap.UnBind(aKey);
352     aMapOrder.Remove(aKey);
353     // Iterate over shapes in this group and add to it shapes from groups in map.
354     for(TopTools_ListOfShape::Iterator aGroupIt(aGroupedShapes);
355         aGroupIt.More(); aGroupIt.Next()) {
356       const TopoDS_Shape& aGroupedShape = aGroupIt.Value();
357       TopTools_ListOfShape aKeysToUnbind;
358       for(TopTools_ListOfShape::Iterator aKeysIt(aMapOrder);
359           aKeysIt.More();
360           aKeysIt.Next()) {
361         const TopTools_ListOfShape& aGroupInMap = aVertexShapesMap(aKeysIt.Value());
362         if(!aGroupInMap.Contains(aGroupedShape)) {
363           // Group in map does not containt shape from our group, so go to the next group in map.
364           continue;
365         }
366         // Iterate over shape in group in map, and add new shapes into our group.
367         for(TopTools_ListOfShape::Iterator aGroupInMapIt(aGroupInMap);
368             aGroupInMapIt.More();
369             aGroupInMapIt.Next()) {
370           const TopoDS_Shape& aShape = aGroupInMapIt.Value();
371           if (!aGroupedShapes.Contains(aShape)) {
372             aGroupedShapes.Append(aShape);
373           }
374         }
375         // Save key to unbind from this map.
376         aKeysToUnbind.Append(aKeysIt.Value());
377       }
378       // Unbind groups from map that we added to our group.
379       for(TopTools_ListOfShape::Iterator aKeysIt(aKeysToUnbind);
380           aKeysIt.More();
381           aKeysIt.Next()) {
382         aVertexShapesMap.UnBind(aKeysIt.Value());
383         aMapOrder.Remove(aKeysIt.Value());
384       }
385     }
386     // Sort shapes.
387     TopTools_ListOfShape aSortedGroup;
388     for(int aST = TopAbs_COMPOUND; aST <= TopAbs_SHAPE; ++aST) {
389       TopTools_ListOfShape::Iterator anIt(aGroupedShapes);
390       while (anIt.More()) {
391         if(anIt.Value().ShapeType() == aST) {
392           aSortedGroup.Append(anIt.Value());
393           aGroupedShapes.Remove(anIt);
394         } else {
395           anIt.Next();
396         }
397       }
398     }
399     aGroups.Append(aSortedGroup);
400   }
401
402   TopoDS_Compound aCompound;
403   BRep_Builder aBuilder;
404   aBuilder.MakeCompound(aCompound);
405   ListOfShape aCompSolids, aFreeSolids;
406   for(NCollection_Vector<NCollection_List<TopoDS_Shape>>::Iterator
407       anIt(aGroups); anIt.More(); anIt.Next()) {
408     NCollection_List<TopoDS_Shape> aGroup = anIt.Value();
409     GeomShapePtr aGeomShape(new GeomAPI_Shape());
410     if(aGroup.Size() == 1) {
411       aGeomShape->setImpl(new TopoDS_Shape(aGroup.First()));
412     } else {
413       aGeomShape->setImpl(new TopoDS_Shape(makeCompound(aGroup)));
414       aGeomShape = GeomAlgoAPI_ShapeTools::combineShapes(aGeomShape,
415                                                          GeomAPI_Shape::COMPSOLID,
416                                                          aCompSolids,
417                                                          aFreeSolids);
418     }
419     aBuilder.Add(aCompound, aGeomShape->impl<TopoDS_Shape>());
420   }
421
422   if(!aCompound.IsNull()) {
423     aResult->setImpl(new TopoDS_Shape(aCompound));
424   }
425
426   return aResult;
427 }
428
429 //==================================================================================================
430 std::list<std::shared_ptr<GeomAPI_Pnt> >
431   GeomAlgoAPI_ShapeTools::getBoundingBox(const ListOfShape& theShapes, const double theEnlarge)
432 {
433   // Bounding box of all objects.
434   Bnd_Box aBndBox;
435
436   // Getting box.
437   for (ListOfShape::const_iterator
438     anObjectsIt = theShapes.begin(); anObjectsIt != theShapes.end(); anObjectsIt++) {
439     const TopoDS_Shape& aShape = (*anObjectsIt)->impl<TopoDS_Shape>();
440     BRepBndLib::Add(aShape, aBndBox);
441   }
442
443   if(theEnlarge != 0.0) {
444     // We enlarge bounding box just to be sure that plane will be large enough to cut all objects.
445     aBndBox.Enlarge(theEnlarge);
446   }
447
448   Standard_Real aXArr[2] = {aBndBox.CornerMin().X(), aBndBox.CornerMax().X()};
449   Standard_Real aYArr[2] = {aBndBox.CornerMin().Y(), aBndBox.CornerMax().Y()};
450   Standard_Real aZArr[2] = {aBndBox.CornerMin().Z(), aBndBox.CornerMax().Z()};
451   std::list<std::shared_ptr<GeomAPI_Pnt> > aResultPoints;
452   int aNum = 0;
453   for(int i = 0; i < 2; i++) {
454     for(int j = 0; j < 2; j++) {
455       for(int k = 0; k < 2; k++) {
456         std::shared_ptr<GeomAPI_Pnt> aPnt(new GeomAPI_Pnt(aXArr[i], aYArr[j], aZArr[k]));
457         aResultPoints.push_back(aPnt);
458       }
459     }
460   }
461
462   return aResultPoints;
463 }
464
465 //==================================================================================================
466 std::shared_ptr<GeomAPI_Shape>
467   GeomAlgoAPI_ShapeTools::faceToInfinitePlane(const std::shared_ptr<GeomAPI_Shape> theFace)
468 {
469   if (!theFace.get())
470     return std::shared_ptr<GeomAPI_Shape>();
471
472   TopoDS_Face aPlaneFace = TopoDS::Face(theFace->impl<TopoDS_Shape>());
473   if (aPlaneFace.IsNull())
474     return std::shared_ptr<GeomAPI_Shape>();
475
476   Handle(Geom_Plane) aPlane = Handle(Geom_Plane)::DownCast(BRep_Tool::Surface(aPlaneFace));
477   if (aPlane.IsNull())
478     return std::shared_ptr<GeomAPI_Shape>();
479
480   // make an infinity face on the plane
481   TopoDS_Shape anInfiniteFace = BRepBuilderAPI_MakeFace(aPlane->Pln()).Shape();
482
483   std::shared_ptr<GeomAPI_Shape> aResult(new GeomAPI_Shape);
484   aResult->setImpl(new TopoDS_Shape(anInfiniteFace));
485   return aResult;
486 }
487
488 //==================================================================================================
489 std::shared_ptr<GeomAPI_Face> GeomAlgoAPI_ShapeTools::fitPlaneToBox(
490   const std::shared_ptr<GeomAPI_Shape> thePlane,
491   const std::list<std::shared_ptr<GeomAPI_Pnt> >& thePoints)
492 {
493   std::shared_ptr<GeomAPI_Face> aResultFace;
494
495   if(!thePlane.get()) {
496     return aResultFace;
497   }
498
499   const TopoDS_Shape& aShape = thePlane->impl<TopoDS_Shape>();
500   if(aShape.ShapeType() != TopAbs_FACE) {
501     return aResultFace;
502   }
503
504   TopoDS_Face aFace = TopoDS::Face(aShape);
505   Handle(Geom_Surface) aSurf = BRep_Tool::Surface(aFace);
506   if(aSurf.IsNull()) {
507     return aResultFace;
508   }
509
510   GeomLib_IsPlanarSurface isPlanar(aSurf);
511   if(!isPlanar.IsPlanar()) {
512     return aResultFace;
513   }
514
515   if(thePoints.size() != 8) {
516     return aResultFace;
517   }
518
519   const gp_Pln& aFacePln = isPlanar.Plan();
520   Handle(Geom_Plane) aFacePlane = new Geom_Plane(aFacePln);
521   IntAna_Quadric aQuadric(aFacePln);
522   Standard_Real UMin, UMax, VMin, VMax;
523   UMin = UMax = VMin = VMax = 0;
524   for (std::list<std::shared_ptr<GeomAPI_Pnt> >::const_iterator
525        aPointsIt = thePoints.begin(); aPointsIt != thePoints.end(); aPointsIt++) {
526     const gp_Pnt& aPnt = (*aPointsIt)->impl<gp_Pnt>();
527     gp_Lin aLin(aPnt, aFacePln.Axis().Direction());
528     IntAna_IntConicQuad anIntAna(aLin, aQuadric);
529     const gp_Pnt& aPntOnFace = anIntAna.Point(1);
530     Standard_Real aPntU(0), aPntV(0);
531     GeomLib_Tool::Parameters(aFacePlane, aPntOnFace, Precision::Confusion(), aPntU, aPntV);
532     if(aPntU < UMin) UMin = aPntU;
533     if(aPntU > UMax) UMax = aPntU;
534     if(aPntV < VMin) VMin = aPntV;
535     if(aPntV > VMax) VMax = aPntV;
536   }
537   aResultFace.reset(new GeomAPI_Face());
538   aResultFace->setImpl(new TopoDS_Face(BRepLib_MakeFace(aFacePln, UMin, UMax, VMin, VMax).Face()));
539
540   return aResultFace;
541 }
542
543 //==================================================================================================
544 void GeomAlgoAPI_ShapeTools::findBounds(const std::shared_ptr<GeomAPI_Shape> theShape,
545                                         std::shared_ptr<GeomAPI_Vertex>& theV1,
546                                         std::shared_ptr<GeomAPI_Vertex>& theV2)
547 {
548   if(!theShape.get()) {
549     std::shared_ptr<GeomAPI_Vertex> aVertex(new GeomAPI_Vertex);
550     aVertex->setImpl(new TopoDS_Vertex());
551     theV1 = aVertex;
552     theV2 = aVertex;
553     return;
554   }
555
556   const TopoDS_Shape& aShape = theShape->impl<TopoDS_Shape>();
557   TopoDS_Vertex aV1, aV2;
558   ShapeAnalysis::FindBounds(aShape, aV1, aV2);
559
560   std::shared_ptr<GeomAPI_Vertex> aGeomV1(new GeomAPI_Vertex()), aGeomV2(new GeomAPI_Vertex());
561   aGeomV1->setImpl(new TopoDS_Vertex(aV1));
562   aGeomV2->setImpl(new TopoDS_Vertex(aV2));
563   theV1 = aGeomV1;
564   theV2 = aGeomV2;
565 }
566
567 //==================================================================================================
568 void GeomAlgoAPI_ShapeTools::makeFacesWithHoles(const std::shared_ptr<GeomAPI_Pnt> theOrigin,
569                                                 const std::shared_ptr<GeomAPI_Dir> theDirection,
570                                                 const ListOfShape& theWires,
571                                                 ListOfShape& theFaces)
572 {
573   BRepBuilderAPI_MakeFace aMKFace(gp_Pln(theOrigin->impl<gp_Pnt>(),
574                                           theDirection->impl<gp_Dir>()));
575   TopoDS_Face aFace = aMKFace.Face();
576
577   BRepAlgo_FaceRestrictor aFRestrictor;
578   aFRestrictor.Init(aFace, Standard_False, Standard_True);
579   for(ListOfShape::const_iterator anIt = theWires.cbegin();
580       anIt != theWires.cend();
581       ++anIt) {
582     TopoDS_Wire aWire = TopoDS::Wire((*anIt)->impl<TopoDS_Shape>());
583     aFRestrictor.Add(aWire);
584   }
585
586   aFRestrictor.Perform();
587
588   if(!aFRestrictor.IsDone()) {
589     return;
590   }
591
592   for(; aFRestrictor.More(); aFRestrictor.Next()) {
593     GeomShapePtr aShape(new GeomAPI_Shape());
594     aShape->setImpl(new TopoDS_Shape(aFRestrictor.Current()));
595     theFaces.push_back(aShape);
596   }
597 }
598
599 //==================================================================================================
600 std::shared_ptr<GeomAPI_Pln> GeomAlgoAPI_ShapeTools::findPlane(const ListOfShape& theShapes)
601 {
602   TopoDS_Compound aCompound;
603   BRep_Builder aBuilder;
604   aBuilder.MakeCompound(aCompound);
605
606   for(ListOfShape::const_iterator anIt = theShapes.cbegin(); anIt != theShapes.cend(); ++anIt) {
607     aBuilder.Add(aCompound, (*anIt)->impl<TopoDS_Shape>());
608   }
609   BRepBuilderAPI_FindPlane aFindPlane(aCompound);
610
611   if(aFindPlane.Found() != Standard_True) {
612     return std::shared_ptr<GeomAPI_Pln>();
613   }
614
615   Handle(Geom_Plane) aPlane = aFindPlane.Plane();
616   gp_Pnt aLoc = aPlane->Location();
617   gp_Dir aDir = aPlane->Axis().Direction();
618
619   std::shared_ptr<GeomAPI_Pnt> aGeomPnt(new GeomAPI_Pnt(aLoc.X(), aLoc.Y(), aLoc.Z()));
620   std::shared_ptr<GeomAPI_Dir> aGeomDir(new GeomAPI_Dir(aDir.X(), aDir.Y(), aDir.Z()));
621
622   std::shared_ptr<GeomAPI_Pln> aPln(new GeomAPI_Pln(aGeomPnt, aGeomDir));
623
624   return aPln;
625 }
626
627 //==================================================================================================
628 bool GeomAlgoAPI_ShapeTools::isSubShapeInsideShape(
629   const std::shared_ptr<GeomAPI_Shape> theSubShape,
630   const std::shared_ptr<GeomAPI_Shape> theBaseShape)
631 {
632   if(!theSubShape.get() || !theBaseShape.get()) {
633     return false;
634   }
635
636   const TopoDS_Shape& aSubShape = theSubShape->impl<TopoDS_Shape>();
637   const TopoDS_Shape& aBaseShape = theBaseShape->impl<TopoDS_Shape>();
638
639   if(aSubShape.ShapeType() == TopAbs_VERTEX) {
640     // If sub-shape is a vertex check distance to shape. If it is <= Precision::Confusion() then OK.
641     BRepExtrema_DistShapeShape aDist(aBaseShape, aSubShape);
642     aDist.Perform();
643     if(!aDist.IsDone() || aDist.Value() > Precision::Confusion()) {
644       return false;
645     }
646   } else if (aSubShape.ShapeType() == TopAbs_EDGE) {
647     if(aBaseShape.ShapeType() == TopAbs_FACE) {
648       // Check that edge is on face surface.
649       TopoDS_Face aFace = TopoDS::Face(aBaseShape);
650       TopoDS_Edge anEdge = TopoDS::Edge(aSubShape);
651       BRepLib_CheckCurveOnSurface aCheck(anEdge, aFace);
652       aCheck.Perform();
653       if(!aCheck.IsDone() || aCheck.MaxDistance() > Precision::Confusion()) {
654         return false;
655       }
656
657       // Check intersections.
658       TopoDS_Vertex aV1, aV2;
659       ShapeAnalysis::FindBounds(anEdge, aV1, aV2);
660       gp_Pnt aPnt1 = BRep_Tool::Pnt(aV1);
661       gp_Pnt aPnt2 = BRep_Tool::Pnt(aV2);
662       for(TopExp_Explorer anExp(aBaseShape, TopAbs_EDGE); anExp.More(); anExp.Next()) {
663         const TopoDS_Shape& anEdgeOnFace = anExp.Current();
664         BRepExtrema_DistShapeShape aDist(anEdgeOnFace, anEdge);
665         aDist.Perform();
666         if(aDist.IsDone() && aDist.Value() <= Precision::Confusion()) {
667           // Edge intersect face bound. Check that it is not on edge begin or end.
668           for(Standard_Integer anIndex = 1; anIndex <= aDist.NbSolution(); ++anIndex) {
669             gp_Pnt aPntOnSubShape = aDist.PointOnShape2(anIndex);
670             if(aPntOnSubShape.Distance(aPnt1) > Precision::Confusion()
671                 && aPntOnSubShape.Distance(aPnt2) > Precision::Confusion()) {
672               return false;
673             }
674           }
675         }
676       }
677
678       // No intersections found. Edge is inside or outside face. Check it.
679       BRepAdaptor_Curve aCurveAdaptor(anEdge);
680       gp_Pnt aPointToCheck =
681         aCurveAdaptor.Value((aCurveAdaptor.FirstParameter() +
682                               aCurveAdaptor.LastParameter()) / 2.0);
683       Handle(Geom_Surface) aSurface = BRep_Tool::Surface(aFace);
684       ShapeAnalysis_Surface aSAS(aSurface);
685       gp_Pnt2d aPointOnFace = aSAS.ValueOfUV(aPointToCheck, Precision::Confusion());
686       BRepTopAdaptor_FClass2d aFClass2d(aFace, Precision::Confusion());
687       if(aFClass2d.Perform(aPointOnFace) == TopAbs_OUT) {
688         return false;
689       }
690
691     } else {
692       return false;
693     }
694   } else {
695     return false;
696   }
697
698   return true;
699 }
700
701 //==================================================================================================
702 bool GeomAlgoAPI_ShapeTools::isShapeValid(const std::shared_ptr<GeomAPI_Shape> theShape)
703 {
704   if(!theShape.get()) {
705     return false;
706   }
707
708   BRepCheck_Analyzer aChecker(theShape->impl<TopoDS_Shape>());
709   return (aChecker.IsValid() == Standard_True);
710 }
711
712 //==================================================================================================
713 std::shared_ptr<GeomAPI_Shape>
714   GeomAlgoAPI_ShapeTools::getFaceOuterWire(const std::shared_ptr<GeomAPI_Shape> theFace)
715 {
716   GeomShapePtr anOuterWire;
717
718   if(!theFace.get() || !theFace->isFace()) {
719     return anOuterWire;
720   }
721
722   TopoDS_Face aFace = TopoDS::Face(theFace->impl<TopoDS_Shape>());
723   TopoDS_Wire aWire = BRepTools::OuterWire(aFace);
724
725   anOuterWire.reset(new GeomAPI_Shape());
726   anOuterWire->setImpl(new TopoDS_Shape(aWire));
727
728   return anOuterWire;
729 }
730
731 //==================================================================================================
732 bool GeomAlgoAPI_ShapeTools::isParallel(const std::shared_ptr<GeomAPI_Edge> theEdge,
733                                         const std::shared_ptr<GeomAPI_Face> theFace)
734 {
735   if(!theEdge.get() || !theFace.get()) {
736     return false;
737   }
738
739   TopoDS_Edge anEdge = TopoDS::Edge(theEdge->impl<TopoDS_Shape>());
740   TopoDS_Face aFace  = TopoDS::Face(theFace->impl<TopoDS_Shape>());
741
742   BRepExtrema_ExtCF anExt(anEdge, aFace);
743   return anExt.IsParallel() == Standard_True;
744 }
745
746 //==================================================================================================
747 void GeomAlgoAPI_ShapeTools::splitShape(const std::shared_ptr<GeomAPI_Shape>& theBaseShape,
748                                       const GeomAlgoAPI_ShapeTools::PointToRefsMap& thePointsInfo,
749                                       std::set<std::shared_ptr<GeomAPI_Shape> >& theShapes)
750 {
751   // to split shape at least one point should be presented in the points container
752   if (thePointsInfo.empty())
753     return;
754
755     // General Fuse to split edge by vertices
756   BOPAlgo_Builder aBOP;
757   TopoDS_Edge aBaseEdge = theBaseShape->impl<TopoDS_Edge>();
758   // Rebuild closed edge to place vertex to one of split points.
759   // This will prevent edge to be split on same vertex.
760   if (BRep_Tool::IsClosed(aBaseEdge))
761   {
762     Standard_Real aFirst, aLast;
763     Handle(Geom_Curve) aCurve = BRep_Tool::Curve(aBaseEdge, aFirst, aLast);
764
765     PointToRefsMap::const_iterator aPIt = thePointsInfo.begin();
766     std::shared_ptr<GeomAPI_Pnt> aPnt = aPIt->first;
767     gp_Pnt aPoint(aPnt->x(), aPnt->y(), aPnt->z());
768
769     TopAbs_Orientation anOrientation = aBaseEdge.Orientation();
770     aBaseEdge = BRepBuilderAPI_MakeEdge(aCurve, aPoint, aPoint).Edge();
771     aBaseEdge.Orientation(anOrientation);
772   }
773   aBOP.AddArgument(aBaseEdge);
774
775   PointToRefsMap::const_iterator aPIt = thePointsInfo.begin();
776   for (; aPIt != thePointsInfo.end(); ++aPIt) {
777     std::shared_ptr<GeomAPI_Pnt> aPnt = aPIt->first;
778     TopoDS_Vertex aV = BRepBuilderAPI_MakeVertex(gp_Pnt(aPnt->x(), aPnt->y(), aPnt->z()));
779     aBOP.AddArgument(aV);
780   }
781
782   aBOP.Perform();
783   if (aBOP.ErrorStatus())
784     return;
785
786   // Collect splits
787   const TopTools_ListOfShape& aSplits = aBOP.Modified(aBaseEdge);
788   TopTools_ListIteratorOfListOfShape anIt(aSplits);
789   for (; anIt.More(); anIt.Next()) {
790     std::shared_ptr<GeomAPI_Shape> anEdge(new GeomAPI_Shape);
791     anEdge->setImpl(new TopoDS_Shape(anIt.Value()));
792     theShapes.insert(anEdge);
793   }
794 }
795
796 //==================================================================================================
797 void GeomAlgoAPI_ShapeTools::splitShape_p(const std::shared_ptr<GeomAPI_Shape>& theBaseShape,
798                                           const std::list<std::shared_ptr<GeomAPI_Pnt> >& thePoints,
799                                           std::set<std::shared_ptr<GeomAPI_Shape> >& theShapes)
800 {
801   // General Fuse to split edge by vertices
802   BOPAlgo_Builder aBOP;
803   TopoDS_Edge aBaseEdge = theBaseShape->impl<TopoDS_Edge>();
804   // Rebuild closed edge to place vertex to one of split points.
805   // This will prevent edge to be split on seam vertex.
806   if (BRep_Tool::IsClosed(aBaseEdge))
807   {
808     Standard_Real aFirst, aLast;
809     Handle(Geom_Curve) aCurve = BRep_Tool::Curve(aBaseEdge, aFirst, aLast);
810
811     std::list<std::shared_ptr<GeomAPI_Pnt> >::const_iterator aPIt = thePoints.begin();
812     gp_Pnt aPoint((*aPIt)->x(), (*aPIt)->y(), (*aPIt)->z());
813
814     TopAbs_Orientation anOrientation = aBaseEdge.Orientation();
815     aBaseEdge = BRepBuilderAPI_MakeEdge(aCurve, aPoint, aPoint).Edge();
816     aBaseEdge.Orientation(anOrientation);
817   }
818   aBOP.AddArgument(aBaseEdge);
819
820   std::list<std::shared_ptr<GeomAPI_Pnt> >::const_iterator aPtIt = thePoints.begin();
821   for (; aPtIt != thePoints.end(); ++aPtIt) {
822     std::shared_ptr<GeomAPI_Pnt> aPnt = *aPtIt;
823     TopoDS_Vertex aV = BRepBuilderAPI_MakeVertex(gp_Pnt(aPnt->x(), aPnt->y(), aPnt->z()));
824     aBOP.AddArgument(aV);
825   }
826
827   aBOP.Perform();
828   if (aBOP.ErrorStatus())
829     return;
830
831   // Collect splits
832   const TopTools_ListOfShape& aSplits = aBOP.Modified(aBaseEdge);
833   TopTools_ListIteratorOfListOfShape anIt(aSplits);
834   for (; anIt.More(); anIt.Next()) {
835     std::shared_ptr<GeomAPI_Shape> anEdge(new GeomAPI_Shape);
836     anEdge->setImpl(new TopoDS_Shape(anIt.Value()));
837     theShapes.insert(anEdge);
838   }
839 }
840
841 //==================================================================================================
842 std::shared_ptr<GeomAPI_Shape> GeomAlgoAPI_ShapeTools::findShape(
843                                   const std::list<std::shared_ptr<GeomAPI_Pnt> >& thePoints,
844                                   const std::set<std::shared_ptr<GeomAPI_Shape> >& theShapes)
845 {
846   std::shared_ptr<GeomAPI_Shape> aResultShape;
847
848   if (thePoints.size() == 2) {
849     std::list<std::shared_ptr<GeomAPI_Pnt> >::const_iterator aPntIt = thePoints.begin();
850     std::shared_ptr<GeomAPI_Pnt> aFirstPoint = *aPntIt;
851     aPntIt++;
852     std::shared_ptr<GeomAPI_Pnt> aLastPoint = *aPntIt;
853
854     std::set<std::shared_ptr<GeomAPI_Shape> >::const_iterator anIt = theShapes.begin(),
855                                                               aLast = theShapes.end();
856     for (; anIt != aLast; anIt++) {
857       GeomShapePtr aShape = *anIt;
858       std::shared_ptr<GeomAPI_Edge> anEdge(new GeomAPI_Edge(aShape));
859       if (anEdge.get()) {
860         std::shared_ptr<GeomAPI_Pnt> anEdgeFirstPoint = anEdge->firstPoint();
861         std::shared_ptr<GeomAPI_Pnt> anEdgeLastPoint = anEdge->lastPoint();
862         if (anEdgeFirstPoint->isEqual(aFirstPoint) &&
863             anEdgeLastPoint->isEqual(aLastPoint))
864             aResultShape = aShape;
865       }
866     }
867   }
868
869   return aResultShape;
870 }