Salome HOME
d6baade6e733544a5ae4135770cd4e1669930085
[modules/shaper.git] / src / GeomAlgoAPI / GeomAlgoAPI_ShapeTools.cpp
1 // Copyright (C) 2014-2022  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 email : webmaster.salome@opencascade.com
18 //
19
20 #include "GeomAlgoAPI_ShapeTools.h"
21
22 #include "GeomAlgoAPI_SketchBuilder.h"
23
24 #include <GeomAPI_Ax1.h>
25 #include <GeomAPI_Edge.h>
26 #include <GeomAPI_Dir.h>
27 #include <GeomAPI_Face.h>
28 #include <GeomAPI_Pln.h>
29 #include <GeomAPI_Pnt.h>
30 #include <GeomAPI_Wire.h>
31
32 #include <Approx_CurvilinearParameter.hxx>
33
34 #include <Bnd_Box.hxx>
35
36 #include <BRep_Tool.hxx>
37 #include <BRep_Builder.hxx>
38 #include <BRepAlgo.hxx>
39 #include <BRepAlgo_FaceRestrictor.hxx>
40 #include <BRepAdaptor_Curve.hxx>
41 #include <BRepBndLib.hxx>
42 #include <BRepBuilderAPI_Copy.hxx>
43 #include <BRepBuilderAPI_FindPlane.hxx>
44 #include <BRepBuilderAPI_MakeEdge.hxx>
45 #include <BRepBuilderAPI_MakeFace.hxx>
46 #include <BRepBuilderAPI_MakeVertex.hxx>
47 #include <BRepBuilderAPI_MakeWire.hxx>
48 #include <BRepCheck_Analyzer.hxx>
49 #include <BRepExtrema_DistShapeShape.hxx>
50 #include <BRepExtrema_ExtCF.hxx>
51 #include <BRepGProp.hxx>
52 #include <BRepTools.hxx>
53 #include <BRepTools_WireExplorer.hxx>
54 #include <BRepTopAdaptor_FClass2d.hxx>
55 #include <BRepClass_FaceClassifier.hxx>
56 #include <BRepLib_CheckCurveOnSurface.hxx>
57 #include <BRepLProp.hxx>
58
59 #include <BOPAlgo_Builder.hxx>
60
61 #include <Geom2d_Curve.hxx>
62 #include <Geom2d_Curve.hxx>
63
64 #include <Geom_BSplineCurve.hxx>
65 #include <Geom_CylindricalSurface.hxx>
66 #include <Geom_Line.hxx>
67 #include <Geom_Plane.hxx>
68 #include <Geom_RectangularTrimmedSurface.hxx>
69
70 #include <GeomAdaptor_HCurve.hxx>
71
72 #include <GeomAPI_ProjectPointOnCurve.hxx>
73 #include <GeomAPI_ShapeIterator.h>
74
75 #include <GeomLib_IsPlanarSurface.hxx>
76 #include <GeomLib_Tool.hxx>
77 #include <GeomAPI_IntCS.hxx>
78
79 #include <gp_Pln.hxx>
80 #include <GProp_GProps.hxx>
81
82 #include <IntAna_IntConicQuad.hxx>
83 #include <IntAna_Quadric.hxx>
84
85 #include <ShapeAnalysis.hxx>
86 #include <ShapeAnalysis_Surface.hxx>
87
88 #include <TopoDS.hxx>
89 #include <TopoDS_Edge.hxx>
90 #include <TopoDS_Face.hxx>
91 #include <TopoDS_Shape.hxx>
92 #include <TopoDS_Shell.hxx>
93 #include <TopoDS_Vertex.hxx>
94 #include <TopoDS_Builder.hxx>
95
96 #include <TopExp.hxx>
97 #include <TopExp_Explorer.hxx>
98
99 #include <TopTools_ListIteratorOfListOfShape.hxx>
100
101 #include <NCollection_Vector.hxx>
102
103 #include <LocalAnalysis_SurfaceContinuity.hxx>
104 #include<array>
105
106 //==================================================================================================
107 static GProp_GProps props(const TopoDS_Shape& theShape)
108 {
109   GProp_GProps aGProps;
110
111   if (theShape.ShapeType() == TopAbs_EDGE || theShape.ShapeType() == TopAbs_WIRE)
112   {
113     BRepGProp::LinearProperties(theShape, aGProps);
114   }
115   else if (theShape.ShapeType() == TopAbs_FACE || theShape.ShapeType() == TopAbs_SHELL)
116   {
117     const Standard_Real anEps = 1.e-6;
118     BRepGProp::SurfaceProperties(theShape, aGProps, anEps);
119   }
120   else if (theShape.ShapeType() == TopAbs_SOLID || theShape.ShapeType() == TopAbs_COMPSOLID)
121   {
122     BRepGProp::VolumeProperties(theShape, aGProps);
123   }
124   else if (theShape.ShapeType() == TopAbs_COMPOUND)
125   {
126     for (TopoDS_Iterator anIt(theShape); anIt.More(); anIt.Next())
127     {
128       aGProps.Add(props(anIt.Value()));
129     }
130   }
131
132   return aGProps;
133 }
134
135 //==================================================================================================
136 double GeomAlgoAPI_ShapeTools::length(const std::shared_ptr<GeomAPI_Shape> theShape)
137 {
138   GProp_GProps aGProps;
139   if (!theShape.get()) {
140     return 0.0;
141   }
142   const TopoDS_Shape& aShape = theShape->impl<TopoDS_Shape>();
143   if (aShape.IsNull()) {
144     return 0.0;
145   }
146
147   BRepGProp::LinearProperties(aShape, aGProps, Standard_True);
148   return  aGProps.Mass();
149 }
150
151 //==================================================================================================
152 double GeomAlgoAPI_ShapeTools::volume(const std::shared_ptr<GeomAPI_Shape> theShape)
153 {
154   if (!theShape.get()) {
155     return 0.0;
156   }
157   const TopoDS_Shape& aShape = theShape->impl<TopoDS_Shape>();
158   if (aShape.IsNull()) {
159     return 0.0;
160   }
161   const Standard_Real anEps = 1.e-6;
162   double aVolume = 0.0;
163   for (TopExp_Explorer anExp(aShape, TopAbs_SOLID); anExp.More(); anExp.Next()) {
164     GProp_GProps aGProps;
165     BRepGProp::VolumeProperties(anExp.Current(), aGProps, anEps);
166     aVolume += aGProps.Mass();
167   }
168   return aVolume;
169 }
170
171 //==================================================================================================
172 double GeomAlgoAPI_ShapeTools::area (const std::shared_ptr<GeomAPI_Shape> theShape)
173 {
174   GProp_GProps aGProps;
175   if (!theShape.get()) {
176     return 0.0;
177   }
178   const TopoDS_Shape& aShape = theShape->impl<TopoDS_Shape>();
179   if (aShape.IsNull()) {
180     return 0.0;
181   }
182   const Standard_Real anEps = 1.e-6;
183
184   BRepGProp::SurfaceProperties(aShape, aGProps, anEps);
185   return aGProps.Mass();
186 }
187
188 //==================================================================================================
189 bool GeomAlgoAPI_ShapeTools::isContinuousFaces(const GeomShapePtr& theFace1,
190                                                const GeomShapePtr& theFace2,
191                                                const GeomPointPtr& thePoint,
192                                                const double & theAngle,
193                                                std::string& theError)
194 {
195
196   #ifdef _DEBUG
197   std::cout << "isContinuousFaces " << std::endl;
198   #endif
199
200   if (!thePoint.get()) {
201       theError = "isContinuousFaces : An invalid argument";
202       return false;
203   }
204   const gp_Pnt& aPoint = thePoint->impl<gp_Pnt>();
205
206   // Getting base shape.
207   if (!theFace1.get()) {
208     theError = "isContinuousFaces : An invalid argument";
209     return false;
210   }
211
212   TopoDS_Shape aShape1 = theFace1->impl<TopoDS_Shape>();
213
214   if (aShape1.IsNull()) {
215     theError = "isContinuousFaces : An invalid argument";
216     return false;
217   }
218
219   // Getting base shape.
220   if (!theFace2.get()) {
221     theError = "isContinuousFaces : An invalid argument";
222     return false;
223   }
224
225   TopoDS_Shape aShape2 = theFace2->impl<TopoDS_Shape>();
226
227   if (aShape2.IsNull()) {
228     theError = "isContinuousFaces : An invalid argument";
229     return false;
230   }
231
232   TopoDS_Face aFace1 = TopoDS::Face(aShape1);
233   if (aFace1.IsNull()) {
234     theError = "isContinuousFaces : An invalid argument";
235     return false;
236   }
237
238   Handle(Geom_Surface) aSurf1 = BRep_Tool::Surface(aFace1);
239   if (aSurf1.IsNull()) {
240     theError = "isContinuousFaces : An invalid surface";
241     return false;
242   }
243
244   ShapeAnalysis_Surface aSAS1(aSurf1);
245   gp_Pnt2d aPointOnFace1 = aSAS1.ValueOfUV(aPoint, Precision::Confusion());
246
247   TopoDS_Face aFace2 = TopoDS::Face(aShape2);
248   if (aFace2.IsNull()) {
249     theError = "isContinuousFaces : An invalid argument";
250     return false;
251   }
252
253   Handle(Geom_Surface) aSurf2 = BRep_Tool::Surface(aFace2);
254   if (aSurf2.IsNull()) {
255     theError = "isContinuousFaces : An invalid surface";
256     return false;
257   }
258
259   ShapeAnalysis_Surface aSAS2(aSurf2);
260   gp_Pnt2d aPointOnFace2= aSAS2.ValueOfUV(aPoint, Precision::Confusion());
261
262   bool aRes = false;
263   try {
264     OCC_CATCH_SIGNALS;
265     LocalAnalysis_SurfaceContinuity aLocAnal(aSurf1,
266                                              aPointOnFace1.X(),
267                                              aPointOnFace1.Y(),
268                                              aSurf2,
269                                              aPointOnFace2.X(),
270                                              aPointOnFace2.Y(),
271                                              GeomAbs_Shape::GeomAbs_G1, // Order
272                                              0.001, // EpsNul
273                                              0.001, // EpsC0
274                                              0.001, // EpsC1
275                                              0.001, // EpsC2
276                                              theAngle * M_PI / 180.0); //EpsG1
277     aRes = aLocAnal.IsG1();
278   }
279   catch (Standard_Failure const& anException) {
280     theError = "LocalAnalysis_SurfaceContinuity error :";
281     theError += anException.GetMessageString();
282   }
283
284   return aRes;
285 }
286
287 //==================================================================================================
288 std::shared_ptr<GeomAPI_Pnt>
289   GeomAlgoAPI_ShapeTools::centreOfMass(const std::shared_ptr<GeomAPI_Shape> theShape)
290 {
291   GProp_GProps aGProps;
292   if (!theShape) {
293     return std::shared_ptr<GeomAPI_Pnt>();
294   }
295   const TopoDS_Shape& aShape = theShape->impl<TopoDS_Shape>();
296   if (aShape.IsNull()) {
297     return std::shared_ptr<GeomAPI_Pnt>();
298   }
299   gp_Pnt aCentre;
300   if (aShape.ShapeType() == TopAbs_VERTEX) {
301     aCentre = BRep_Tool::Pnt(TopoDS::Vertex(aShape));
302   } else {
303     aGProps = props(aShape);
304     aCentre = aGProps.CentreOfMass();
305   }
306
307   return std::shared_ptr<GeomAPI_Pnt>(new GeomAPI_Pnt(aCentre.X(), aCentre.Y(), aCentre.Z()));
308 }
309
310 //==================================================================================================
311 double GeomAlgoAPI_ShapeTools::radius(const std::shared_ptr<GeomAPI_Face>& theCylinder)
312 {
313   double aRadius = -1.0;
314   if (theCylinder->isCylindrical()) {
315     const TopoDS_Shape& aShape = theCylinder->impl<TopoDS_Shape>();
316     Handle(Geom_Surface) aSurf = BRep_Tool::Surface(TopoDS::Face(aShape));
317     Handle(Geom_CylindricalSurface) aCyl = Handle(Geom_CylindricalSurface)::DownCast(aSurf);
318     if (!aCyl.IsNull())
319       aRadius = aCyl->Radius();
320   }
321   return aRadius;
322 }
323
324 //==================================================================================================
325 namespace {
326
327 auto getExtemaDistShape = [](const GeomShapePtr& theShape1,
328     const GeomShapePtr& theShape2) -> BRepExtrema_DistShapeShape
329 {
330   const TopoDS_Shape& aShape1 = theShape1->impl<TopoDS_Shape>();
331   const TopoDS_Shape& aShape2 = theShape2->impl<TopoDS_Shape>();
332
333   BRepExtrema_DistShapeShape aDist(aShape1, aShape2);
334   aDist.Perform();
335   return aDist;
336 };
337 }
338
339 double GeomAlgoAPI_ShapeTools::minimalDistance(const GeomShapePtr& theShape1,
340                                                const GeomShapePtr& theShape2)
341 {
342   BRepExtrema_DistShapeShape aDist = getExtemaDistShape(theShape1, theShape2);
343   return aDist.IsDone() ? aDist.Value() : Precision::Infinite();
344 }
345
346 double GeomAlgoAPI_ShapeTools::minimalDistance(const GeomShapePtr& theShape1,
347                                                const GeomShapePtr& theShape2,
348                                                std::array<double, 3> & fromShape1To2)
349 {
350   BRepExtrema_DistShapeShape aDist = getExtemaDistShape(theShape1, theShape2);
351   const auto & pt1 = aDist.PointOnShape1(1);
352   const auto & pt2 = aDist.PointOnShape2(1) ;
353   fromShape1To2[0] = pt2.X() - pt1.X();
354   fromShape1To2[1] = pt2.Y() - pt1.Y();
355   fromShape1To2[2] = pt2.Z() - pt1.Z();
356   return aDist.IsDone() ? aDist.Value() : Precision::Infinite();
357 }
358
359 //==================================================================================================
360 std::shared_ptr<GeomAPI_Shape> GeomAlgoAPI_ShapeTools::combineShapes(
361   const std::shared_ptr<GeomAPI_Shape> theCompound,
362   const GeomAPI_Shape::ShapeType theType,
363   ListOfShape& theResuts)
364 {
365
366   ListOfShape aResCombinedShapes;
367   ListOfShape aResFreeShapes;
368
369   GeomShapePtr aResult = theCompound;
370
371   if (!theCompound.get()) {
372     return aResult;
373   }
374
375   if (theType != GeomAPI_Shape::SHELL && theType != GeomAPI_Shape::COMPSOLID) {
376     return aResult;
377   }
378
379   TopAbs_ShapeEnum aTS = TopAbs_EDGE;
380   TopAbs_ShapeEnum aTA = TopAbs_FACE;
381   if (theType == GeomAPI_Shape::COMPSOLID) {
382     aTS = TopAbs_FACE;
383     aTA = TopAbs_SOLID;
384   }
385
386   // map from the resulting shapes to minimal index of the used shape from theCompound list
387   std::map<GeomShapePtr, int> anInputOrder;
388   // map from ancestors-shapes to the index of shapes in theCompound
389   NCollection_DataMap<TopoDS_Shape, int> anAncestorsOrder;
390
391   // Get free shapes.
392   int anOrder = 0;
393   const TopoDS_Shape& aShapesComp = theCompound->impl<TopoDS_Shape>();
394   for (TopoDS_Iterator anIter(aShapesComp); anIter.More(); anIter.Next(), anOrder++) {
395     const TopoDS_Shape& aShape = anIter.Value();
396     if (aShape.ShapeType() > aTA) {
397       std::shared_ptr<GeomAPI_Shape> aGeomShape(new GeomAPI_Shape);
398       aGeomShape->setImpl<TopoDS_Shape>(new TopoDS_Shape(aShape));
399       aResFreeShapes.push_back(aGeomShape);
400       anInputOrder[aGeomShape] = anOrder;
401     } else {
402       for (TopExp_Explorer anExp(aShape, aTA); anExp.More(); anExp.Next()) {
403         anAncestorsOrder.Bind(anExp.Current(), anOrder);
404       }
405     }
406   }
407
408   // Map sub-shapes and shapes.
409   TopTools_IndexedDataMapOfShapeListOfShape aMapSA;
410   TopExp::MapShapesAndAncestors(aShapesComp, aTS, aTA, aMapSA);
411   if (aMapSA.IsEmpty()) {
412     return aResult;
413   }
414   theResuts.clear();
415
416   // Get all shapes with common sub-shapes and free shapes.
417   NCollection_Map<TopoDS_Shape> aFreeShapes;
418   NCollection_Vector<NCollection_Map<TopoDS_Shape>> aShapesWithCommonSubshapes;
419   for (TopTools_IndexedDataMapOfShapeListOfShape::Iterator
420       anIter(aMapSA); anIter.More(); anIter.Next()) {
421     TopTools_ListOfShape& aListOfShape = anIter.ChangeValue();
422     if (aListOfShape.IsEmpty()) {
423       continue;
424     }
425     else if (aListOfShape.Size() == 1) {
426       const TopoDS_Shape& aF = aListOfShape.First();
427       aFreeShapes.Add(aF);
428       aListOfShape.Clear();
429     } else {
430       NCollection_List<TopoDS_Shape> aTempList;
431       NCollection_Map<TopoDS_Shape> aTempMap;
432       for (TopTools_ListOfShape::Iterator aListIt(aListOfShape); aListIt.More(); aListIt.Next()) {
433         aTempList.Append(aListIt.Value());
434         aTempMap.Add(aListIt.Value());
435         aFreeShapes.Remove(aListIt.Value());
436       }
437       aListOfShape.Clear();
438       for (NCollection_List<TopoDS_Shape>::Iterator
439           aTempIter(aTempList); aTempIter.More(); aTempIter.Next()) {
440         const TopoDS_Shape& aTempShape = aTempIter.Value();
441         for (TopTools_IndexedDataMapOfShapeListOfShape::Iterator
442             anIter2(aMapSA); anIter2.More(); anIter2.Next()) {
443           TopTools_ListOfShape& aTempListOfShape = anIter2.ChangeValue();
444           if (aTempListOfShape.IsEmpty()) {
445             continue;
446           } else if (aTempListOfShape.Size() == 1 && aTempListOfShape.First() == aTempShape) {
447             aTempListOfShape.Clear();
448           } else if (aTempListOfShape.Size() > 1) {
449             TopTools_ListOfShape::Iterator anIt1(aTempListOfShape);
450             for (; anIt1.More(); anIt1.Next()) {
451               if (anIt1.Value() == aTempShape) {
452                 TopTools_ListOfShape::Iterator anIt2(aTempListOfShape);
453                 for (; anIt2.More(); anIt2.Next())
454                 {
455                   if (anIt2.Value() != anIt1.Value()) {
456                     if (aTempMap.Add(anIt2.Value())) {
457                       aTempList.Append(anIt2.Value());
458                       aFreeShapes.Remove(anIt2.Value());
459                     }
460                   }
461                 }
462                 aTempListOfShape.Clear();
463                 break;
464               }
465             }
466           }
467         }
468       }
469       aShapesWithCommonSubshapes.Append(aTempMap);
470     }
471   }
472
473   // Combine shapes with common sub-shapes.
474   for (NCollection_Vector<NCollection_Map<TopoDS_Shape>>::Iterator
475       anIter(aShapesWithCommonSubshapes); anIter.More(); anIter.Next()) {
476     TopoDS_Shell aShell;
477     TopoDS_CompSolid aCSolid;
478     TopoDS_Builder aBuilder;
479     anOrder = -1;
480     theType ==
481       GeomAPI_Shape::COMPSOLID ? aBuilder.MakeCompSolid(aCSolid) : aBuilder.MakeShell(aShell);
482     NCollection_Map<TopoDS_Shape>& aShapesMap = anIter.ChangeValue();
483     for (TopExp_Explorer anExp(aShapesComp, aTA); anExp.More(); anExp.Next()) {
484       const TopoDS_Shape& aShape = anExp.Current();
485       if (aShapesMap.Contains(aShape)) {
486         theType ==
487           GeomAPI_Shape::COMPSOLID ? aBuilder.Add(aCSolid, aShape) : aBuilder.Add(aShell, aShape);
488         aShapesMap.Remove(aShape);
489         int aThisOrder = anAncestorsOrder.Find(aShape);
490         if (anOrder == -1 || aThisOrder < anOrder)
491           anOrder = aThisOrder; // take the minimum order position
492       }
493     }
494     std::shared_ptr<GeomAPI_Shape> aGeomShape(new GeomAPI_Shape);
495     TopoDS_Shape* aSh = theType == GeomAPI_Shape::COMPSOLID ? new TopoDS_Shape(aCSolid) :
496                                                               new TopoDS_Shape(aShell);
497     aGeomShape->setImpl<TopoDS_Shape>(aSh);
498     aResCombinedShapes.push_back(aGeomShape);
499     anInputOrder[aGeomShape] = anOrder;
500   }
501
502   // Adding free shapes.
503   for (TopExp_Explorer anExp(aShapesComp, aTA); anExp.More(); anExp.Next()) {
504     const TopoDS_Shape& aShape = anExp.Current();
505     if (aFreeShapes.Contains(aShape)) {
506       std::shared_ptr<GeomAPI_Shape> aGeomShape(new GeomAPI_Shape);
507       aGeomShape->setImpl<TopoDS_Shape>(new TopoDS_Shape(aShape));
508       aResFreeShapes.push_back(aGeomShape);
509       anInputOrder[aGeomShape] = anAncestorsOrder.Find(aShape);
510     }
511   }
512
513   if (aResCombinedShapes.size() == 1 && aResFreeShapes.size() == 0) {
514     aResult = aResCombinedShapes.front();
515     theResuts.push_back(aResult);
516   } else if (aResCombinedShapes.size() == 0 && aResFreeShapes.size() == 1) {
517     aResult = aResFreeShapes.front();
518     theResuts.push_back(aResult);
519   } else {
520     TopoDS_Compound aResultComp;
521     TopoDS_Builder aBuilder;
522     aBuilder.MakeCompound(aResultComp);
523     // put to result compound and result list in accordance to the order numbers
524     std::map<GeomShapePtr, int>::iterator anInputIter = anInputOrder.begin();
525     std::map<int, GeomShapePtr> aNums;
526     for (; anInputIter != anInputOrder.end(); anInputIter++)
527       aNums[anInputIter->second] = anInputIter->first;
528     std::map<int, GeomShapePtr>::iterator aNumsIter = aNums.begin();
529     for (; aNumsIter != aNums.end(); aNumsIter++) {
530       aBuilder.Add(aResultComp, (aNumsIter->second)->impl<TopoDS_Shape>());
531       theResuts.push_back(aNumsIter->second);
532     }
533     aResult->setImpl(new TopoDS_Shape(aResultComp));
534   }
535
536   return aResult;
537 }
538
539 //==================================================================================================
540 static void addSimpleShapeToList(const TopoDS_Shape& theShape,
541                                  NCollection_List<TopoDS_Shape>& theList)
542 {
543   if (theShape.IsNull()) {
544     return;
545   }
546
547   if (theShape.ShapeType() == TopAbs_COMPOUND) {
548     for (TopoDS_Iterator anIt(theShape); anIt.More(); anIt.Next()) {
549       addSimpleShapeToList(anIt.Value(), theList);
550     }
551   } else {
552     theList.Append(theShape);
553   }
554 }
555
556 //==================================================================================================
557 static TopoDS_Compound makeCompound(const NCollection_List<TopoDS_Shape> theShapes)
558 {
559   TopoDS_Compound aCompound;
560
561   BRep_Builder aBuilder;
562   aBuilder.MakeCompound(aCompound);
563
564   for (NCollection_List<TopoDS_Shape>::Iterator anIt(theShapes); anIt.More(); anIt.Next()) {
565     aBuilder.Add(aCompound, anIt.Value());
566   }
567
568   return aCompound;
569 }
570
571 //==================================================================================================
572 std::shared_ptr<GeomAPI_Shape> GeomAlgoAPI_ShapeTools::groupSharedTopology(
573   const std::shared_ptr<GeomAPI_Shape> theCompound)
574 {
575   GeomShapePtr aResult = theCompound;
576
577   if (!theCompound.get()) {
578     return aResult;
579   }
580
581   TopoDS_Shape anInShape = aResult->impl<TopoDS_Shape>();
582   NCollection_List<TopoDS_Shape> anUngroupedShapes, aStillUngroupedShapes;
583   addSimpleShapeToList(anInShape, anUngroupedShapes);
584
585   // Iterate over all shapes and find shapes with shared vertices.
586   TopTools_ListOfShape allVertices;
587   TopTools_DataMapOfShapeListOfShape aVertexShapesMap;
588   for (NCollection_List<TopoDS_Shape>::Iterator aShapesIt(anUngroupedShapes);
589     aShapesIt.More();
590     aShapesIt.Next()) {
591     const TopoDS_Shape& aShape = aShapesIt.Value();
592     for (TopExp_Explorer aShapeExp(aShape, TopAbs_VERTEX);
593       aShapeExp.More();
594       aShapeExp.Next()) {
595       const TopoDS_Shape& aVertex = aShapeExp.Current();
596       if (!aVertexShapesMap.IsBound(aVertex)) {
597         NCollection_List<TopoDS_Shape> aList;
598         aList.Append(aShape);
599         allVertices.Append(aVertex);
600         aVertexShapesMap.Bind(aVertex, aList);
601       }
602       else {
603         if (!aVertexShapesMap.ChangeFind(aVertex).Contains(aShape)) {
604           aVertexShapesMap.ChangeFind(aVertex).Append(aShape);
605         }
606       }
607     }
608   }
609
610   // Iterate over the map and group shapes.
611   NCollection_Vector<TopTools_MapOfShape> aGroups; // groups of shapes connected by vertices
612   while (!allVertices.IsEmpty()) {
613     // Get first group of shapes in map, and then unbind it.
614     const TopoDS_Shape& aKey = allVertices.First();
615     TopTools_ListOfShape aConnectedShapes = aVertexShapesMap.Find(aKey);
616     aVertexShapesMap.UnBind(aKey);
617     allVertices.Remove(aKey);
618     // Iterate over shapes in this group and add to it shapes from groups in map.
619     for (TopTools_ListOfShape::Iterator aConnectedIt(aConnectedShapes);
620       aConnectedIt.More(); aConnectedIt.Next()) {
621       const TopoDS_Shape& aConnected = aConnectedIt.Value();
622       TopTools_ListOfShape aKeysToUnbind;
623       for (TopTools_ListOfShape::Iterator aKeysIt(allVertices);
624         aKeysIt.More();
625         aKeysIt.Next()) {
626         const TopTools_ListOfShape& anOtherConnected = aVertexShapesMap(aKeysIt.Value());
627         if (!anOtherConnected.Contains(aConnected)) {
628           // Other connected group does not contain shape from our connected group
629           continue;
630         }
631         // Other is connected to our, so add them to our connected
632         for (TopTools_ListOfShape::Iterator anOtherIt(anOtherConnected);
633           anOtherIt.More();
634           anOtherIt.Next()) {
635           const TopoDS_Shape& aShape = anOtherIt.Value();
636           if (!aConnectedShapes.Contains(aShape)) {
637             aConnectedShapes.Append(aShape);
638           }
639         }
640         // Save key to unbind from this map.
641         aKeysToUnbind.Append(aKeysIt.Value());
642       }
643       // Unbind groups from map that we added to our group.
644       for (TopTools_ListOfShape::Iterator aKeysIt(aKeysToUnbind);
645         aKeysIt.More();
646         aKeysIt.Next()) {
647         aVertexShapesMap.UnBind(aKeysIt.Value());
648         allVertices.Remove(aKeysIt.Value());
649       }
650     }
651     // Sort shapes from the most complicated to the simplest ones
652     TopTools_MapOfShape aSortedGroup;
653     for (int aST = TopAbs_COMPOUND; aST <= TopAbs_SHAPE; ++aST) {
654       TopTools_ListOfShape::Iterator anIt(aConnectedShapes);
655       while (anIt.More()) {
656         if (anIt.Value().ShapeType() == aST) {
657           aSortedGroup.Add(anIt.Value());
658           aConnectedShapes.Remove(anIt);
659         }
660         else {
661           anIt.Next();
662         }
663       }
664     }
665     aGroups.Append(aSortedGroup);
666   }
667
668   TopoDS_Compound aCompound;
669   BRep_Builder aBuilder;
670   aBuilder.MakeCompound(aCompound);
671   ListOfShape aSolids;
672   for (NCollection_Vector<TopTools_MapOfShape>::Iterator anIt(aGroups); anIt.More(); anIt.Next()) {
673     const TopTools_MapOfShape& aGroup = anIt.ChangeValue();
674     GeomShapePtr aGeomShape(new GeomAPI_Shape());
675     if (aGroup.Size() == 1) {
676       TopTools_MapOfShape::Iterator aOneShapeIter(aGroup);
677       aGeomShape->setImpl(new TopoDS_Shape(aOneShapeIter.Value()));
678     } else {
679       // make sub-shapes in the group have order same as in original shape
680       TopTools_ListOfShape anOrderedGoup;
681       NCollection_List<TopoDS_Shape>::Iterator anUngrouped(anUngroupedShapes);
682       for (; anUngrouped.More(); anUngrouped.Next()) {
683         if (aGroup.Contains(anUngrouped.Value()))
684           anOrderedGoup.Append(anUngrouped.Value());
685       }
686       aGeomShape->setImpl(new TopoDS_Shape(makeCompound(anOrderedGoup)));
687       aGeomShape = GeomAlgoAPI_ShapeTools::combineShapes(aGeomShape,
688                                                          GeomAPI_Shape::COMPSOLID,
689                                                          aSolids);
690     }
691     aBuilder.Add(aCompound, aGeomShape->impl<TopoDS_Shape>());
692   }
693
694   if (!aCompound.IsNull()) {
695     aResult->setImpl(new TopoDS_Shape(aCompound));
696   }
697
698   return aResult;
699 }
700
701 //==================================================================================================
702 bool GeomAlgoAPI_ShapeTools::hasSharedTopology(const ListOfShape& theShapes,
703                                                const GeomAPI_Shape::ShapeType theShapeType)
704 {
705   TopTools_IndexedMapOfShape aSubs;
706   for (ListOfShape::const_iterator anIt = theShapes.begin(); anIt != theShapes.end(); ++anIt) {
707     TopTools_IndexedMapOfShape aCurSubs;
708     TopExp::MapShapes((*anIt)->impl<TopoDS_Shape>(), (TopAbs_ShapeEnum)theShapeType, aCurSubs);
709     for (TopTools_IndexedMapOfShape::Iterator aSubIt(aCurSubs); aSubIt.More(); aSubIt.Next()) {
710       if (aSubs.Contains(aSubIt.Value()))
711         return true;
712       else
713         aSubs.Add(aSubIt.Value());
714     }
715   }
716   return false;
717 }
718
719 //==================================================================================================
720 std::list<std::shared_ptr<GeomAPI_Pnt> >
721   GeomAlgoAPI_ShapeTools::getBoundingBox(const ListOfShape& theShapes, const double theEnlarge)
722 {
723   // Bounding box of all objects.
724   Bnd_Box aBndBox;
725
726   // Getting box.
727   for (ListOfShape::const_iterator
728     anObjectsIt = theShapes.begin(); anObjectsIt != theShapes.end(); anObjectsIt++) {
729     const TopoDS_Shape& aShape = (*anObjectsIt)->impl<TopoDS_Shape>();
730     BRepBndLib::Add(aShape, aBndBox);
731   }
732
733   if (theEnlarge != 0.0) {
734     // We enlarge bounding box just to be sure that plane will be large enough to cut all objects.
735     aBndBox.Enlarge(theEnlarge);
736   }
737
738   Standard_Real aXArr[2] = {aBndBox.CornerMin().X(), aBndBox.CornerMax().X()};
739   Standard_Real aYArr[2] = {aBndBox.CornerMin().Y(), aBndBox.CornerMax().Y()};
740   Standard_Real aZArr[2] = {aBndBox.CornerMin().Z(), aBndBox.CornerMax().Z()};
741   std::list<std::shared_ptr<GeomAPI_Pnt> > aResultPoints;
742   for (int i = 0; i < 2; i++) {
743     for (int j = 0; j < 2; j++) {
744       for (int k = 0; k < 2; k++) {
745         std::shared_ptr<GeomAPI_Pnt> aPnt(new GeomAPI_Pnt(aXArr[i], aYArr[j], aZArr[k]));
746         aResultPoints.push_back(aPnt);
747       }
748     }
749   }
750
751   return aResultPoints;
752 }
753
754 //==================================================================================================
755 std::shared_ptr<GeomAPI_Face> GeomAlgoAPI_ShapeTools::fitPlaneToBox(
756   const std::shared_ptr<GeomAPI_Shape> thePlane,
757   const std::list<std::shared_ptr<GeomAPI_Pnt> >& thePoints)
758 {
759   std::shared_ptr<GeomAPI_Face> aResultFace;
760
761   if (!thePlane.get()) {
762     return aResultFace;
763   }
764
765   const TopoDS_Shape& aShape = thePlane->impl<TopoDS_Shape>();
766   if (aShape.ShapeType() != TopAbs_FACE) {
767     return aResultFace;
768   }
769
770   TopoDS_Face aFace = TopoDS::Face(aShape);
771   Handle(Geom_Surface) aSurf = BRep_Tool::Surface(aFace);
772   if (aSurf.IsNull()) {
773     return aResultFace;
774   }
775
776   GeomLib_IsPlanarSurface isPlanar(aSurf);
777   if (!isPlanar.IsPlanar()) {
778     return aResultFace;
779   }
780
781   if (thePoints.size() != 8) {
782     return aResultFace;
783   }
784
785   const gp_Pln& aFacePln = isPlanar.Plan();
786   Handle(Geom_Plane) aFacePlane = new Geom_Plane(aFacePln);
787   IntAna_Quadric aQuadric(aFacePln);
788   Standard_Real UMin, UMax, VMin, VMax;
789   UMin = UMax = VMin = VMax = 0;
790   for (std::list<std::shared_ptr<GeomAPI_Pnt> >::const_iterator
791        aPointsIt = thePoints.begin(); aPointsIt != thePoints.end(); aPointsIt++) {
792     const gp_Pnt& aPnt = (*aPointsIt)->impl<gp_Pnt>();
793     gp_Lin aLin(aPnt, aFacePln.Axis().Direction());
794     IntAna_IntConicQuad anIntAna(aLin, aQuadric);
795     const gp_Pnt& aPntOnFace = anIntAna.Point(1);
796     Standard_Real aPntU(0), aPntV(0);
797     GeomLib_Tool::Parameters(aFacePlane, aPntOnFace, Precision::Confusion(), aPntU, aPntV);
798     if (aPntU < UMin) UMin = aPntU;
799     if (aPntU > UMax) UMax = aPntU;
800     if (aPntV < VMin) VMin = aPntV;
801     if (aPntV > VMax) VMax = aPntV;
802   }
803   aResultFace.reset(new GeomAPI_Face());
804   aResultFace->setImpl(new TopoDS_Face(BRepLib_MakeFace(aFacePln, UMin, UMax, VMin, VMax).Face()));
805
806   return aResultFace;
807 }
808
809 //==================================================================================================
810 void GeomAlgoAPI_ShapeTools::findBounds(const std::shared_ptr<GeomAPI_Shape> theShape,
811                                         std::shared_ptr<GeomAPI_Vertex>& theV1,
812                                         std::shared_ptr<GeomAPI_Vertex>& theV2)
813 {
814   static GeomVertexPtr aVertex;
815   if (!aVertex) {
816     aVertex = GeomVertexPtr(new GeomAPI_Vertex);
817     aVertex->setImpl(new TopoDS_Vertex());
818   }
819
820   theV1 = aVertex;
821   theV2 = aVertex;
822
823   if (theShape) {
824     const TopoDS_Shape& aShape = theShape->impl<TopoDS_Shape>();
825     TopoDS_Vertex aV1, aV2;
826     ShapeAnalysis::FindBounds(aShape, aV1, aV2);
827
828     std::shared_ptr<GeomAPI_Vertex> aGeomV1(new GeomAPI_Vertex()), aGeomV2(new GeomAPI_Vertex());
829     aGeomV1->setImpl(new TopoDS_Vertex(aV1));
830     aGeomV2->setImpl(new TopoDS_Vertex(aV2));
831     theV1 = aGeomV1;
832     theV2 = aGeomV2;
833   }
834 }
835
836 //==================================================================================================
837 void GeomAlgoAPI_ShapeTools::makeFacesWithHoles(const std::shared_ptr<GeomAPI_Pnt> theOrigin,
838                                                 const std::shared_ptr<GeomAPI_Dir> theDirection,
839                                                 const ListOfShape& theWires,
840                                                 ListOfShape& theFaces)
841 {
842   BRepBuilderAPI_MakeFace aMKFace(gp_Pln(theOrigin->impl<gp_Pnt>(),
843                                           theDirection->impl<gp_Dir>()));
844   TopoDS_Face aFace = aMKFace.Face();
845
846   BRepAlgo_FaceRestrictor aFRestrictor;
847   aFRestrictor.Init(aFace, Standard_False, Standard_True);
848   for (ListOfShape::const_iterator anIt = theWires.cbegin();
849       anIt != theWires.cend();
850       ++anIt) {
851     TopoDS_Wire aWire = TopoDS::Wire((*anIt)->impl<TopoDS_Shape>());
852     aFRestrictor.Add(aWire);
853   }
854
855   aFRestrictor.Perform();
856
857   if (!aFRestrictor.IsDone()) {
858     return;
859   }
860
861   for (; aFRestrictor.More(); aFRestrictor.Next()) {
862     GeomShapePtr aShape(new GeomAPI_Shape());
863     aShape->setImpl(new TopoDS_Shape(aFRestrictor.Current()));
864     theFaces.push_back(aShape);
865   }
866 }
867
868 //==================================================================================================
869 std::shared_ptr<GeomAPI_Pln> GeomAlgoAPI_ShapeTools::findPlane(const ListOfShape& theShapes)
870 {
871   TopoDS_Compound aCompound;
872   BRep_Builder aBuilder;
873   aBuilder.MakeCompound(aCompound);
874
875   for (ListOfShape::const_iterator anIt = theShapes.cbegin(); anIt != theShapes.cend(); ++anIt) {
876     aBuilder.Add(aCompound, (*anIt)->impl<TopoDS_Shape>());
877   }
878   BRepBuilderAPI_FindPlane aFindPlane(aCompound);
879
880   if (aFindPlane.Found() != Standard_True) {
881     return std::shared_ptr<GeomAPI_Pln>();
882   }
883
884   Handle(Geom_Plane) aPlane = aFindPlane.Plane();
885   gp_Pnt aLoc = aPlane->Location();
886   gp_Dir aDir = aPlane->Axis().Direction();
887
888   std::shared_ptr<GeomAPI_Pnt> aGeomPnt(new GeomAPI_Pnt(aLoc.X(), aLoc.Y(), aLoc.Z()));
889   std::shared_ptr<GeomAPI_Dir> aGeomDir(new GeomAPI_Dir(aDir.X(), aDir.Y(), aDir.Z()));
890
891   std::shared_ptr<GeomAPI_Pln> aPln(new GeomAPI_Pln(aGeomPnt, aGeomDir));
892
893   return aPln;
894 }
895
896 //==================================================================================================
897 bool GeomAlgoAPI_ShapeTools::isSubShapeInsideShape(
898   const std::shared_ptr<GeomAPI_Shape> theSubShape,
899   const std::shared_ptr<GeomAPI_Shape> theBaseShape)
900 {
901   if (!theSubShape.get() || !theBaseShape.get()) {
902     return false;
903   }
904
905   const TopoDS_Shape& aSubShape = theSubShape->impl<TopoDS_Shape>();
906   const TopoDS_Shape& aBaseShape = theBaseShape->impl<TopoDS_Shape>();
907
908   if (aSubShape.ShapeType() == TopAbs_VERTEX) {
909     // If sub-shape is a vertex check distance to shape. If it is <= Precision::Confusion() then OK.
910     BRepExtrema_DistShapeShape aDist(aBaseShape, aSubShape);
911     aDist.Perform();
912     if (!aDist.IsDone() || aDist.Value() > Precision::Confusion()) {
913       return false;
914     }
915   } else if (aSubShape.ShapeType() == TopAbs_EDGE) {
916     if (aBaseShape.ShapeType() == TopAbs_FACE) {
917       // Check that edge is on face surface.
918       TopoDS_Face aFace = TopoDS::Face(aBaseShape);
919       TopoDS_Edge anEdge = TopoDS::Edge(aSubShape);
920       BRepLib_CheckCurveOnSurface aCheck(anEdge, aFace);
921       aCheck.Perform();
922       if (!aCheck.IsDone() || aCheck.MaxDistance() > Precision::Confusion()) {
923         return false;
924       }
925
926       // Check intersections.
927       TopoDS_Vertex aV1, aV2;
928       ShapeAnalysis::FindBounds(anEdge, aV1, aV2);
929       gp_Pnt aPnt1 = BRep_Tool::Pnt(aV1);
930       gp_Pnt aPnt2 = BRep_Tool::Pnt(aV2);
931       for (TopExp_Explorer anExp(aBaseShape, TopAbs_EDGE); anExp.More(); anExp.Next()) {
932         const TopoDS_Shape& anEdgeOnFace = anExp.Current();
933         BRepExtrema_DistShapeShape aDist(anEdgeOnFace, anEdge);
934         aDist.Perform();
935         if (aDist.IsDone() && aDist.Value() <= Precision::Confusion()) {
936           // Edge intersect face bound. Check that it is not on edge begin or end.
937           for (Standard_Integer anIndex = 1; anIndex <= aDist.NbSolution(); ++anIndex) {
938             gp_Pnt aPntOnSubShape = aDist.PointOnShape2(anIndex);
939             if (aPntOnSubShape.Distance(aPnt1) > Precision::Confusion()
940                 && aPntOnSubShape.Distance(aPnt2) > Precision::Confusion()) {
941               return false;
942             }
943           }
944         }
945       }
946
947       // No intersections found. Edge is inside or outside face. Check it.
948       BRepAdaptor_Curve aCurveAdaptor(anEdge);
949       gp_Pnt aPointToCheck =
950         aCurveAdaptor.Value((aCurveAdaptor.FirstParameter() +
951                               aCurveAdaptor.LastParameter()) / 2.0);
952       Handle(Geom_Surface) aSurface = BRep_Tool::Surface(aFace);
953       ShapeAnalysis_Surface aSAS(aSurface);
954       gp_Pnt2d aPointOnFace = aSAS.ValueOfUV(aPointToCheck, Precision::Confusion());
955       BRepTopAdaptor_FClass2d aFClass2d(aFace, Precision::Confusion());
956       if (aFClass2d.Perform(aPointOnFace) == TopAbs_OUT) {
957         return false;
958       }
959
960     } else {
961       return false;
962     }
963   } else {
964     return false;
965   }
966
967   return true;
968 }
969
970 //==================================================================================================
971 bool GeomAlgoAPI_ShapeTools::isShapeValid(const std::shared_ptr<GeomAPI_Shape> theShape)
972 {
973   if (!theShape.get()) {
974     return false;
975   }
976
977   BRepCheck_Analyzer aChecker(theShape->impl<TopoDS_Shape>());
978   return (aChecker.IsValid() == Standard_True);
979 }
980
981 //==================================================================================================
982 std::shared_ptr<GeomAPI_Shape>
983   GeomAlgoAPI_ShapeTools::getFaceOuterWire(const std::shared_ptr<GeomAPI_Shape> theFace)
984 {
985   GeomShapePtr anOuterWire;
986
987   if (!theFace.get() || !theFace->isFace()) {
988     return anOuterWire;
989   }
990
991   TopoDS_Face aFace = TopoDS::Face(theFace->impl<TopoDS_Shape>());
992   TopoDS_Wire aWire = BRepTools::OuterWire(aFace);
993
994   anOuterWire.reset(new GeomAPI_Shape());
995   anOuterWire->setImpl(new TopoDS_Shape(aWire));
996
997   return anOuterWire;
998 }
999
1000 //==================================================================================================
1001 static bool boundaryOfEdge(const std::shared_ptr<GeomAPI_Edge> theEdge,
1002                           const std::shared_ptr<GeomAPI_Vertex> theVertex,
1003                           double& theParam)
1004 {
1005   GeomPointPtr aPoint = theVertex->point();
1006   GeomPointPtr aFirstPnt = theEdge->firstPoint();
1007   double aFirstPntTol = theEdge->firstPointTolerance();
1008   GeomPointPtr aLastPnt = theEdge->lastPoint();
1009   double aLastPntTol = theEdge->lastPointTolerance();
1010
1011   double aFirst, aLast;
1012   theEdge->getRange(aFirst, aLast);
1013
1014   bool isFirst = aPoint->distance(aFirstPnt) <= aFirstPntTol;
1015   bool isLast = aPoint->distance(aLastPnt) <= aLastPntTol;
1016   if (isFirst)
1017     theParam = aFirst;
1018   else if (isLast)
1019     theParam = aLast;
1020
1021   return isFirst != isLast;
1022 }
1023
1024 bool GeomAlgoAPI_ShapeTools::isTangent(const std::shared_ptr<GeomAPI_Edge> theEdge1,
1025                                        const std::shared_ptr<GeomAPI_Edge> theEdge2,
1026                                        const std::shared_ptr<GeomAPI_Vertex> theTgPoint)
1027 {
1028   double aParE1 = 0, aParE2 = 0;
1029   if (!boundaryOfEdge(theEdge1, theTgPoint, aParE1) ||
1030       !boundaryOfEdge(theEdge2, theTgPoint, aParE2))
1031     return false;
1032
1033   BRepAdaptor_Curve aC1(theEdge1->impl<TopoDS_Edge>());
1034   BRepAdaptor_Curve aC2(theEdge2->impl<TopoDS_Edge>());
1035   return BRepLProp::Continuity(aC1, aC2, aParE1, aParE2) >= GeomAbs_G1;
1036 }
1037
1038 //==================================================================================================
1039 bool GeomAlgoAPI_ShapeTools::isParallel(const std::shared_ptr<GeomAPI_Edge> theEdge,
1040                                         const std::shared_ptr<GeomAPI_Face> theFace)
1041 {
1042   if (!theEdge.get() || !theFace.get()) {
1043     return false;
1044   }
1045
1046   TopoDS_Edge anEdge = TopoDS::Edge(theEdge->impl<TopoDS_Shape>());
1047   TopoDS_Face aFace  = TopoDS::Face(theFace->impl<TopoDS_Shape>());
1048
1049   BRepExtrema_ExtCF anExt(anEdge, aFace);
1050   return anExt.IsParallel() == Standard_True;
1051 }
1052
1053 //==================================================================================================
1054 std::list<std::shared_ptr<GeomAPI_Vertex> > GeomAlgoAPI_ShapeTools::intersect(
1055   const std::shared_ptr<GeomAPI_Edge> theEdge, const std::shared_ptr<GeomAPI_Face> theFace)
1056 {
1057   std::list<std::shared_ptr<GeomAPI_Vertex> > aResult;
1058   if (!theEdge.get() || !theFace.get()) {
1059     return aResult;
1060   }
1061
1062   TopoDS_Edge anEdge = TopoDS::Edge(theEdge->impl<TopoDS_Shape>());
1063   double aFirstOnCurve, aLastOnCurve;
1064   Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirstOnCurve, aLastOnCurve);
1065
1066   TopoDS_Face aFace  = TopoDS::Face(theFace->impl<TopoDS_Shape>());
1067   Handle(Geom_Surface) aSurf = BRep_Tool::Surface(aFace);
1068
1069   GeomAPI_IntCS anIntAlgo(aCurve, aSurf);
1070   if (!anIntAlgo.IsDone())
1071     return aResult;
1072   // searching for points-intersection
1073   for (int anIntNum = 1; anIntNum <= anIntAlgo.NbPoints() + anIntAlgo.NbSegments(); anIntNum++) {
1074     gp_Pnt anInt;
1075     if (anIntNum <= anIntAlgo.NbPoints()) {
1076       anInt = anIntAlgo.Point(anIntNum);
1077     } else { // take the middle point on the segment of the intersection
1078       Handle(Geom_Curve) anIntCurve = anIntAlgo.Segment(anIntNum - anIntAlgo.NbPoints());
1079       anIntCurve->D0((anIntCurve->FirstParameter() + anIntCurve->LastParameter()) / 2., anInt);
1080     }
1081     aResult.push_back(std::shared_ptr<GeomAPI_Vertex>(
1082       new GeomAPI_Vertex(anInt.X(), anInt.Y(), anInt.Z())));
1083   }
1084   return aResult;
1085 }
1086
1087 //==================================================================================================
1088 void GeomAlgoAPI_ShapeTools::splitShape(const std::shared_ptr<GeomAPI_Shape>& theBaseShape,
1089                                       const GeomAlgoAPI_ShapeTools::PointToRefsMap& thePointsInfo,
1090                                       std::set<std::shared_ptr<GeomAPI_Shape> >& theShapes)
1091 {
1092   // to split shape at least one point should be presented in the points container
1093   if (thePointsInfo.empty())
1094     return;
1095
1096     // General Fuse to split edge by vertices
1097   BOPAlgo_Builder aBOP;
1098   TopoDS_Edge aBaseEdge = theBaseShape->impl<TopoDS_Edge>();
1099   // Rebuild closed edge to place vertex to one of split points.
1100   // This will prevent edge to be split on same vertex.
1101   if (BRep_Tool::IsClosed(aBaseEdge))
1102   {
1103     Standard_Real aFirst, aLast;
1104     Handle(Geom_Curve) aCurve = BRep_Tool::Curve(aBaseEdge, aFirst, aLast);
1105
1106     PointToRefsMap::const_iterator aPIt = thePointsInfo.begin();
1107     std::shared_ptr<GeomAPI_Pnt> aPnt = aPIt->first;
1108     gp_Pnt aPoint(aPnt->x(), aPnt->y(), aPnt->z());
1109
1110     TopAbs_Orientation anOrientation = aBaseEdge.Orientation();
1111     aBaseEdge = BRepBuilderAPI_MakeEdge(aCurve, aPoint, aPoint).Edge();
1112     aBaseEdge.Orientation(anOrientation);
1113   }
1114   aBOP.AddArgument(aBaseEdge);
1115
1116   PointToRefsMap::const_iterator aPIt = thePointsInfo.begin();
1117   for (; aPIt != thePointsInfo.end(); ++aPIt) {
1118     std::shared_ptr<GeomAPI_Pnt> aPnt = aPIt->first;
1119     TopoDS_Vertex aV = BRepBuilderAPI_MakeVertex(gp_Pnt(aPnt->x(), aPnt->y(), aPnt->z()));
1120     aBOP.AddArgument(aV);
1121   }
1122
1123   aBOP.Perform();
1124   if (aBOP.HasErrors())
1125     return;
1126
1127   // Collect splits
1128   const TopTools_ListOfShape& aSplits = aBOP.Modified(aBaseEdge);
1129   TopTools_ListIteratorOfListOfShape anIt(aSplits);
1130   for (; anIt.More(); anIt.Next()) {
1131     std::shared_ptr<GeomAPI_Shape> anEdge(new GeomAPI_Shape);
1132     anEdge->setImpl(new TopoDS_Shape(anIt.Value()));
1133     theShapes.insert(anEdge);
1134   }
1135 }
1136
1137 //==================================================================================================
1138 void GeomAlgoAPI_ShapeTools::splitShape_p(const std::shared_ptr<GeomAPI_Shape>& theBaseShape,
1139                                           const std::list<std::shared_ptr<GeomAPI_Pnt> >& thePoints,
1140                                           std::set<std::shared_ptr<GeomAPI_Shape> >& theShapes)
1141 {
1142   // General Fuse to split edge by vertices
1143   BOPAlgo_Builder aBOP;
1144   TopoDS_Edge aBaseEdge = theBaseShape->impl<TopoDS_Edge>();
1145   // Rebuild closed edge to place vertex to one of split points.
1146   // This will prevent edge to be split on seam vertex.
1147   if (BRep_Tool::IsClosed(aBaseEdge))
1148   {
1149     Standard_Real aFirst, aLast;
1150     Handle(Geom_Curve) aCurve = BRep_Tool::Curve(aBaseEdge, aFirst, aLast);
1151
1152     std::list<std::shared_ptr<GeomAPI_Pnt> >::const_iterator aPIt = thePoints.begin();
1153     gp_Pnt aPoint((*aPIt)->x(), (*aPIt)->y(), (*aPIt)->z());
1154
1155     TopAbs_Orientation anOrientation = aBaseEdge.Orientation();
1156     aBaseEdge = BRepBuilderAPI_MakeEdge(aCurve, aPoint, aPoint).Edge();
1157     aBaseEdge.Orientation(anOrientation);
1158   }
1159   aBOP.AddArgument(aBaseEdge);
1160
1161   std::list<std::shared_ptr<GeomAPI_Pnt> >::const_iterator aPtIt = thePoints.begin();
1162   for (; aPtIt != thePoints.end(); ++aPtIt) {
1163     std::shared_ptr<GeomAPI_Pnt> aPnt = *aPtIt;
1164     TopoDS_Vertex aV = BRepBuilderAPI_MakeVertex(gp_Pnt(aPnt->x(), aPnt->y(), aPnt->z()));
1165     aBOP.AddArgument(aV);
1166   }
1167
1168   aBOP.Perform();
1169   if (aBOP.HasErrors())
1170     return;
1171
1172   // Collect splits
1173   const TopTools_ListOfShape& aSplits = aBOP.Modified(aBaseEdge);
1174   TopTools_ListIteratorOfListOfShape anIt(aSplits);
1175   for (; anIt.More(); anIt.Next()) {
1176     std::shared_ptr<GeomAPI_Shape> anEdge(new GeomAPI_Shape);
1177     anEdge->setImpl(new TopoDS_Shape(anIt.Value()));
1178     theShapes.insert(anEdge);
1179   }
1180 }
1181
1182 //==================================================================================================
1183 std::shared_ptr<GeomAPI_Shape> GeomAlgoAPI_ShapeTools::findShape(
1184                                   const std::list<std::shared_ptr<GeomAPI_Pnt> >& thePoints,
1185                                   const std::set<std::shared_ptr<GeomAPI_Shape> >& theShapes)
1186 {
1187   std::shared_ptr<GeomAPI_Shape> aResultShape;
1188
1189   if (thePoints.size() == 2) {
1190     std::list<std::shared_ptr<GeomAPI_Pnt> >::const_iterator aPntIt = thePoints.begin();
1191     std::shared_ptr<GeomAPI_Pnt> aFirstPoint = *aPntIt;
1192     aPntIt++;
1193     std::shared_ptr<GeomAPI_Pnt> aLastPoint = *aPntIt;
1194
1195     std::set<std::shared_ptr<GeomAPI_Shape> >::const_iterator anIt = theShapes.begin(),
1196                                                               aLast = theShapes.end();
1197     for (; anIt != aLast; anIt++) {
1198       GeomShapePtr aShape = *anIt;
1199       std::shared_ptr<GeomAPI_Edge> anEdge(new GeomAPI_Edge(aShape));
1200       if (anEdge.get()) {
1201         std::shared_ptr<GeomAPI_Pnt> anEdgeFirstPoint = anEdge->firstPoint();
1202         std::shared_ptr<GeomAPI_Pnt> anEdgeLastPoint = anEdge->lastPoint();
1203         if (anEdgeFirstPoint->isEqual(aFirstPoint) &&
1204             anEdgeLastPoint->isEqual(aLastPoint))
1205             aResultShape = aShape;
1206       }
1207     }
1208   }
1209
1210   return aResultShape;
1211 }
1212
1213 //==================================================================================================
1214 #ifdef FEATURE_MULTIROTATION_TWO_DIRECTIONS
1215 std::shared_ptr<GeomAPI_Dir> GeomAlgoAPI_ShapeTools::buildDirFromAxisAndShape(
1216                                     const std::shared_ptr<GeomAPI_Shape> theBaseShape,
1217                                     const std::shared_ptr<GeomAPI_Ax1> theAxis)
1218 {
1219   gp_Pnt aCentreOfMassPoint =
1220     GeomAlgoAPI_ShapeTools::centreOfMass(theBaseShape)->impl<gp_Pnt>();
1221   Handle(Geom_Line) aLine = new Geom_Line(theAxis->impl<gp_Ax1>());
1222   GeomAPI_ProjectPointOnCurve aPrjTool(aCentreOfMassPoint, aLine);
1223   gp_Pnt aPoint = aPrjTool.NearestPoint();
1224
1225   std::shared_ptr<GeomAPI_Dir> aDir(new GeomAPI_Dir(aCentreOfMassPoint.X()-aPoint.X(),
1226                                                     aCentreOfMassPoint.Y()-aPoint.Y(),
1227                                                     aCentreOfMassPoint.Z()-aPoint.Z()));
1228   return aDir;
1229 }
1230 #endif
1231
1232 //==================================================================================================
1233 static TopoDS_Wire fixParametricGaps(const TopoDS_Wire& theWire)
1234 {
1235   TopoDS_Wire aFixedWire;
1236   Handle(Geom_Curve) aPrevCurve;
1237   double aPrevLastParam = -Precision::Infinite();
1238
1239   BRep_Builder aBuilder;
1240   aBuilder.MakeWire(aFixedWire);
1241
1242   BRepTools_WireExplorer aWExp(theWire);
1243   for (; aWExp.More(); aWExp.Next()) {
1244     TopoDS_Edge anEdge = aWExp.Current();
1245     double aFirst, aLast;
1246     Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
1247     if (aCurve == aPrevCurve && Abs(aFirst - aPrevLastParam) > Precision::Confusion()) {
1248       // if parametric gap occurs, create new edge based on the copied curve
1249       aCurve = Handle(Geom_Curve)::DownCast(aCurve->Copy());
1250       TopoDS_Vertex aV1, aV2;
1251       TopExp::Vertices(anEdge, aV1, aV2);
1252       anEdge = TopoDS::Edge(anEdge.EmptyCopied());
1253       aBuilder.UpdateEdge(anEdge, aCurve, BRep_Tool::Tolerance(anEdge));
1254       aBuilder.Add(anEdge, aV1);
1255       aBuilder.Add(anEdge, aV2);
1256     }
1257
1258     aBuilder.Add(aFixedWire, anEdge);
1259
1260     aPrevCurve = aCurve;
1261     aPrevLastParam = aLast;
1262   }
1263
1264   return aFixedWire;
1265 }
1266
1267 //==================================================================================================
1268 std::shared_ptr<GeomAPI_Edge> GeomAlgoAPI_ShapeTools::wireToEdge(
1269       const std::shared_ptr<GeomAPI_Wire>& theWire)
1270 {
1271   GeomEdgePtr anEdge;
1272   if (theWire) {
1273     TopoDS_Wire aWire = theWire->impl<TopoDS_Wire>();
1274     BRepTools_WireExplorer aWExp(aWire);
1275     TopoDS_Edge aNewEdge = aWExp.Current();
1276     aWExp.Next();
1277     if (aWExp.More()) {
1278       // Workaround for the closed wire to avoid jumping of its start point:
1279       // split this wire for two parts, convert them to edges, then compose together
1280       if (BRep_Tool::IsClosed(aWire)) {
1281         aWire = TopoDS::Wire(BRepBuilderAPI_Copy(aWire).Shape());
1282         aWExp.Init(aWire);
1283         aNewEdge = aWExp.Current();
1284
1285         BRep_Builder().Remove(aWire, aNewEdge);
1286         GeomWirePtr aSplitWire(new GeomAPI_Wire);
1287         aSplitWire->setImpl(new TopoDS_Wire(aWire));
1288         GeomEdgePtr aMergedEdge = wireToEdge(aSplitWire);
1289
1290         aWire = BRepBuilderAPI_MakeWire(aNewEdge, aMergedEdge->impl<TopoDS_Edge>());
1291       }
1292
1293       // Workaround: when concatenate a wire consisting of two edges based on the same B-spline
1294       // curve (non-periodic, but having equal start and end points), first of which is placed
1295       // at the end on the curve and second is placed at the start, this workaround copies
1296       // second curve to avoid treating these edges as a single curve by setting trim parameters.
1297       aWire = fixParametricGaps(aWire);
1298       aWire = BRepAlgo::ConcatenateWire(aWire, GeomAbs_G1); // join smooth parts of wire
1299       aNewEdge = BRepAlgo::ConcatenateWireC0(aWire); // join C0 parts of wire
1300
1301       // Reapproximate the result edge to have the parameter equal to curvilinear abscissa.
1302       static const int THE_MAX_DEGREE = 14;
1303       static const int THE_MAX_INTERVALS = 32;
1304       double aFirst, aLast;
1305       Handle(Geom_Curve) aCurve = BRep_Tool::Curve(aNewEdge, aFirst, aLast);
1306       Handle(GeomAdaptor_HCurve) aHCurve = new GeomAdaptor_HCurve(aCurve);
1307       Approx_CurvilinearParameter anApprox(aHCurve, Precision::Confusion(), aCurve->Continuity(),
1308                                            THE_MAX_DEGREE, THE_MAX_INTERVALS);
1309       if (anApprox.HasResult()) {
1310         Handle(Geom_BSplineCurve) aNewCurve = anApprox.Curve3d();
1311         TColStd_Array1OfReal aKnots = aNewCurve->Knots();
1312         BSplCLib::Reparametrize(aFirst, aLast, aKnots);
1313         aNewCurve->SetKnots(aKnots);
1314         BRep_Builder().UpdateEdge(aNewEdge, aNewCurve, BRep_Tool::Tolerance(aNewEdge));
1315       }
1316     }
1317     anEdge = GeomEdgePtr(new GeomAPI_Edge);
1318     anEdge->setImpl(new TopoDS_Edge(aNewEdge));
1319   }
1320   return anEdge;
1321 }
1322
1323 //==================================================================================================
1324 ListOfShape GeomAlgoAPI_ShapeTools::getLowLevelSubShapes(const GeomShapePtr& theShape)
1325 {
1326   ListOfShape aSubShapes;
1327
1328   if (!theShape->isCompound() && !theShape->isCompSolid() &&
1329       !theShape->isShell() && !theShape->isWire()) {
1330     return aSubShapes;
1331   }
1332
1333   for (GeomAPI_ShapeIterator anIt(theShape); anIt.more(); anIt.next()) {
1334     GeomShapePtr aSubShape = anIt.current();
1335     if (aSubShape->isVertex() || aSubShape->isEdge() ||
1336         aSubShape->isFace() || aSubShape->isSolid()) {
1337       aSubShapes.push_back(aSubShape);
1338     } else {
1339       aSubShapes.splice(aSubShapes.end(), getLowLevelSubShapes(aSubShape));
1340     }
1341   }
1342
1343   return aSubShapes;
1344 }
1345
1346 //==================================================================================================
1347 static void getMinMaxPointsOnLine(const std::list<std::shared_ptr<GeomAPI_Pnt> >& thePoints,
1348                                   const gp_Dir theDir,
1349                                   double& theMin, double& theMax)
1350 {
1351   theMin = RealLast();
1352   theMax = RealFirst();
1353   // Project bounding points on theDir
1354   for (std::list<std::shared_ptr<GeomAPI_Pnt> >::const_iterator
1355          aPointsIt = thePoints.begin(); aPointsIt != thePoints.end(); aPointsIt++) {
1356     const gp_Pnt& aPnt = (*aPointsIt)->impl<gp_Pnt>();
1357     gp_Dir aPntDir (aPnt.XYZ());
1358     Standard_Real proj = (theDir*aPntDir) * aPnt.XYZ().Modulus();
1359     if (proj < theMin) theMin = proj;
1360     if (proj > theMax) theMax = proj;
1361   }
1362 }
1363
1364 //==================================================================================================
1365 void GeomAlgoAPI_ShapeTools::computeThroughAll(const ListOfShape& theObjects,
1366                                                const ListOfShape& theBaseShapes,
1367                                                const std::shared_ptr<GeomAPI_Dir> theDir,
1368                                                double& theToSize, double& theFromSize)
1369 {
1370   // Bounding box of objects
1371   std::list<std::shared_ptr<GeomAPI_Pnt> > aBndObjs =
1372       GeomAlgoAPI_ShapeTools::getBoundingBox(theObjects);
1373   if (aBndObjs.size() != 8) {
1374     return;
1375   }
1376
1377   // the value to enlarge the bounding box of each object to make the extruded shape
1378   // a little bit larger than overall objects to get the correct result of Boolean CUT operation
1379   double anEnlargement = 0.1 * aBndObjs.front()->distance(aBndObjs.back());
1380
1381   // Prism direction
1382   if (theDir.get()) {
1383     // One direction for all prisms
1384     gp_Dir aDir = theDir->impl<gp_Dir>();
1385
1386     // Bounding box of the base
1387     std::list<std::shared_ptr<GeomAPI_Pnt> > aBndBases =
1388         GeomAlgoAPI_ShapeTools::getBoundingBox(theBaseShapes);
1389     if (aBndBases.size() != 8) {
1390       return;
1391     }
1392
1393     // Objects bounds
1394     Standard_Real lowBnd, upperBnd;
1395     getMinMaxPointsOnLine(aBndObjs, aDir, lowBnd, upperBnd);
1396
1397     // Base bounds
1398     Standard_Real lowBase, upperBase;
1399     getMinMaxPointsOnLine(aBndBases, aDir, lowBase, upperBase);
1400
1401     // ----------.-----.---------.--------------.-----------> theDir
1402     //       lowBnd   lowBase   upperBase    upperBnd
1403
1404     theToSize = upperBnd - lowBase;
1405     theFromSize = upperBase - lowBnd;
1406   } else {
1407     // Direction is a normal to each base shape (different normals to bases)
1408     // So we calculate own sizes for each base shape
1409     theToSize = 0.0;
1410     theFromSize = 0.0;
1411
1412     for (ListOfShape::const_iterator anIt = theBaseShapes.begin();
1413          anIt != theBaseShapes.end(); ++anIt) {
1414       const GeomShapePtr& aBaseShape_i = (*anIt);
1415       ListOfShape aBaseShapes_i;
1416       aBaseShapes_i.push_back(aBaseShape_i);
1417
1418       // Bounding box of the base
1419       std::list<std::shared_ptr<GeomAPI_Pnt> > aBndBases =
1420           GeomAlgoAPI_ShapeTools::getBoundingBox(aBaseShapes_i, anEnlargement);
1421       if (aBndBases.size() != 8) {
1422         return;
1423       }
1424
1425       // Direction (normal to aBaseShapes_i)
1426       // Code like in GeomAlgoAPI_Prism
1427       gp_Dir aDir;
1428       const TopoDS_Shape& aBaseShape = aBaseShape_i->impl<TopoDS_Shape>();
1429       BRepBuilderAPI_FindPlane aFindPlane(aBaseShape);
1430       if (aFindPlane.Found() == Standard_True) {
1431         Handle(Geom_Plane) aPlane;
1432         if (aBaseShape.ShapeType() == TopAbs_FACE || aBaseShape.ShapeType() == TopAbs_SHELL) {
1433           TopExp_Explorer anExp(aBaseShape, TopAbs_FACE);
1434           const TopoDS_Shape& aFace = anExp.Current();
1435           Handle(Geom_Surface) aSurface = BRep_Tool::Surface(TopoDS::Face(aFace));
1436           if (aSurface->DynamicType() == STANDARD_TYPE(Geom_RectangularTrimmedSurface)) {
1437             Handle(Geom_RectangularTrimmedSurface) aTrimSurface =
1438               Handle(Geom_RectangularTrimmedSurface)::DownCast(aSurface);
1439             aSurface = aTrimSurface->BasisSurface();
1440           }
1441           if (aSurface->DynamicType() != STANDARD_TYPE(Geom_Plane)) {
1442             return;
1443           }
1444           aPlane = Handle(Geom_Plane)::DownCast(aSurface);
1445         } else {
1446           aPlane = aFindPlane.Plane();
1447         }
1448         aDir = aPlane->Axis().Direction();
1449       } else {
1450         return;
1451       }
1452
1453       // Objects bounds
1454       Standard_Real lowBnd, upperBnd;
1455       getMinMaxPointsOnLine(aBndObjs, aDir, lowBnd, upperBnd);
1456
1457       // Base bounds
1458       Standard_Real lowBase, upperBase;
1459       getMinMaxPointsOnLine(aBndBases, aDir, lowBase, upperBase);
1460
1461       // ----------.-----.---------.--------------.-----------> theDir
1462       //       lowBnd   lowBase   upperBase    upperBnd
1463
1464       double aToSize_i = upperBnd - lowBase;
1465       double aFromSize_i = upperBase - lowBnd;
1466
1467       if (aToSize_i > theToSize) theToSize = aToSize_i;
1468       if (aFromSize_i > theFromSize) theFromSize = aFromSize_i;
1469     }
1470   }
1471 }