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