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