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