Salome HOME
83f2f171afc1dbd7b6cdc04aec6484b697e448dd
[modules/geom.git] / src / ShHealOper / ShHealOper_CloseContour.cxx
1 // Copyright (C) 2007-2023  CEA/DEN, EDF R&D, OPEN CASCADE
2 //
3 // Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
5 //
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License, or (at your option) any later version.
10 //
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 // Lesser General Public License for more details.
15 //
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
19 //
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 //
22
23 // File:      ShHealOper_CloseContour.cxx
24 // Created:   20.04.04 11:36:01
25 // Author:    Galina KULIKOVA
26 //
27 #include <ShHealOper_CloseContour.hxx>
28 #include <ShapeExtend_WireData.hxx>
29 #include <ShapeFix_Wire.hxx>
30 #include <TopoDS_Face.hxx>
31 #include <ShapeFix_Edge.hxx>
32 #include <TopoDS_Iterator.hxx>
33 #include <ShapeAnalysis_Wire.hxx>
34 #include <TColStd_SequenceOfInteger.hxx>
35 #include <TopTools_IndexedMapOfShape.hxx>
36 #include <TopoDS_Edge.hxx>
37 #include <TopTools_ListOfShape.hxx>
38 #include <TopTools_ListIteratorOfListOfShape.hxx>
39 #include <TColStd_MapOfInteger.hxx>
40 #include <TopExp.hxx>
41 #include <TopoDS.hxx>
42 #include <TColStd_MapIteratorOfMapOfInteger.hxx>
43 #include <ShapeAnalysis_Edge.hxx>
44 #include <BRep_Builder.hxx>
45 #include <TopoDS_Edge.hxx>
46 #include <TopoDS_Vertex.hxx>
47 #include <BRepBuilderAPI_MakeVertex.hxx>
48 #include <ShapeAnalysis_Edge.hxx>
49 #include <gp_Pnt.hxx>
50 #include <gp_Vec2d.hxx>
51 #include <gp_Vec.hxx>
52 #include <Geom_Line.hxx>
53 #include <Geom2d_Line.hxx>
54 #include <TopoDS_Compound.hxx>
55 #include <BRep_Tool.hxx>
56 #include <ShapeBuild_Edge.hxx>
57 #include <TopExp_Explorer.hxx>
58
59 //=======================================================================
60 //function : ShHealOper_CloseContour()
61 //purpose  : Constructor
62 //=======================================================================
63 ShHealOper_CloseContour::ShHealOper_CloseContour (const TopoDS_Shape& theShape  ) 
64 {
65   Init(theShape);
66 }
67
68 //=======================================================================
69 //function : Init
70 //purpose  : 
71 //=======================================================================
72 void ShHealOper_CloseContour::Init(const TopoDS_Shape& theShape)
73 {
74   ShHealOper_Tool::Init(theShape);
75   myTolerance = Precision::Confusion();
76   myMaxTolerance = 1.0;
77   TopExp::MapShapesAndAncestors(theShape,TopAbs_EDGE,TopAbs_FACE,myMapEdgesFace);
78 }
79
80 //=======================================================================
81 //function : Perform
82 //purpose  : 
83 //=======================================================================
84 Standard_Boolean ShHealOper_CloseContour::Perform(const TopTools_SequenceOfShape& theSeqEdges,
85                                                   const Standard_Boolean theModeVertex,
86                                                   const Standard_Boolean theModeFixGapsCurves)
87 {
88   myFreeEdges.Clear();
89   myDone = Standard_False;
90   myErrorStatus =ShHealOper_NotError;
91   if(myInitShape.IsNull()) {
92     myErrorStatus = ShHealOper_InvalidParameters;
93     return myDone;
94   }
95   Handle(ShapeExtend_WireData) asewd = new ShapeExtend_WireData;
96   Standard_Integer i =1;
97   for ( ; i <= theSeqEdges.Length(); i++)
98     asewd->Add(theSeqEdges.Value(i));
99
100   myModeVertex = theModeVertex;
101   myModeFixGapsCurves = theModeFixGapsCurves;
102
103   build(asewd);
104   
105   return myDone;
106 }
107
108 //=======================================================================
109 //function : Perform
110 //purpose  : 
111 //=======================================================================
112 Standard_Boolean ShHealOper_CloseContour::Perform(const TopoDS_Wire& theWire,
113                                                   const Standard_Boolean theModeVertex,
114                                                   const Standard_Boolean theModeFixGapsCurves)
115 {
116   myFreeEdges.Clear();
117   myDone = Standard_False;
118   if(myInitShape.IsNull()) {
119     myErrorStatus = ShHealOper_InvalidParameters;
120     return myDone;
121   }
122   Handle(ShapeExtend_WireData) asewd = new ShapeExtend_WireData(theWire);
123   myModeVertex = theModeVertex;
124   myModeFixGapsCurves = theModeFixGapsCurves;
125   build(asewd);
126   return myDone;
127 }
128
129 //=======================================================================
130 //function : Build
131 //purpose  : 
132 //=======================================================================
133 void ShHealOper_CloseContour::build(Handle(ShapeExtend_WireData)& theSewd)
134 {
135   TopTools_SequenceOfShape aCommonFaces;
136   //checks that all specified edges belong the one face or not.
137   Standard_Boolean isOneFace = checkOneFace(theSewd,aCommonFaces);
138
139   //add edge or increase max tolerance in dependence on specified VertexMode.
140   //if all edges belong the one face that gap will be closed in the 2D by line
141   //else gap will be closed in the 3D by line.
142   myDone = fixGaps(theSewd,aCommonFaces);
143   updateWire(theSewd);
144   Handle(ShapeFix_Wire) sfw = new ShapeFix_Wire;
145   sfw->SetContext(myContext);
146   sfw->Load(theSewd);
147
148   sfw->ClosedWireMode() = Standard_True;
149   sfw->SetPrecision(myTolerance);
150   sfw->SetMaxTolerance(myMaxTolerance);
151   
152   if(isOneFace) {
153     Standard_Integer ii =1;
154     for( ; ii <= aCommonFaces.Length(); ii++) {
155       TopoDS_Face aFace = TopoDS::Face(aCommonFaces.Value(ii));
156       sfw->SetFace(aFace);
157       myDone = (sfw->Perform() || myDone);
158       //if Mode for fix gaps is equal to true that
159       //curve 3D and curve 2D will be pull to each other.
160       if(myModeFixGapsCurves) {
161         Standard_Boolean isFixgaps = Standard_False;
162         if(ii ==1) {
163           sfw->FixGaps3d();
164           isFixgaps = sfw->StatusGaps3d(ShapeExtend_DONE);
165           if(!isFixgaps && sfw->StatusGaps3d(ShapeExtend_FAIL))
166              myErrorStatus = ShHealOper_ErrorExecution;
167         }
168         if(sfw->FixGaps2d())
169           sfw->FixSelfIntersection();
170         else if(sfw->StatusGaps2d(ShapeExtend_FAIL))
171           myErrorStatus = ShHealOper_ErrorExecution;
172
173         isFixgaps = (isFixgaps || sfw->StatusGaps2d(ShapeExtend_DONE));
174         myDone = (myDone || isFixgaps);
175         if(isFixgaps) {
176           Handle(ShapeExtend_WireData) sbwd = sfw->WireData();
177           Handle(ShapeFix_Edge) sfe = new ShapeFix_Edge;
178           for (Standard_Integer iedge = 1; iedge <= sbwd->NbEdges(); iedge++) {
179             TopoDS_Edge aEdge = TopoDS::Edge(sbwd->Edge(iedge));
180             sfe->FixVertexTolerance(aEdge,aFace);
181             sfe->FixSameParameter(aEdge);
182           }
183         }
184       }
185     }
186   }
187   else {
188     myDone = (sfw->Perform() || myDone);
189     if(myModeFixGapsCurves) {
190       //if Mode for fix gaps is equal to true that
191       //curve 3D will be pull to each other.
192       if(sfw->FixGaps3d()) {
193         Handle(ShapeExtend_WireData) sbwd = sfw->WireData();
194         Handle(ShapeFix_Edge) sfe = new ShapeFix_Edge;
195         for (Standard_Integer iedge = 1; iedge <= sbwd->NbEdges(); iedge++) {
196           TopoDS_Edge aEdge = TopoDS::Edge(sbwd->Edge(iedge));
197           sfe->FixVertexTolerance(aEdge);
198           sfe->FixSameParameter(aEdge);
199         }
200       }
201       else if(sfw->StatusGaps3d(ShapeExtend_FAIL))
202         myErrorStatus = ShHealOper_ErrorExecution;
203       myDone = (sfw->StatusGaps3d(ShapeExtend_DONE) || myDone);
204     }
205   }
206
207   if(myDone) {
208     TopoDS_Shape aoldShape = myInitShape;
209     //if free edges were added they will be added to the result shape
210     //and type of result shape should be change if initial shape is not COMPOUND.
211     if( myFreeEdges.Length()) {
212       BRep_Builder aB;
213       TopoDS_Compound aComp;
214       aB.MakeCompound(aComp);
215       if(aoldShape.ShapeType() == TopAbs_COMPOUND) {
216         TopoDS_Iterator aIt(aoldShape);
217         for( ;aIt.More();aIt.Next() )
218            aB.Add(aComp,aIt.Value());
219       }
220       else
221         aB.Add(aComp,aoldShape);
222
223       Standard_Integer i=1;
224       for ( ; i <= myFreeEdges.Length(); i++ ) 
225         aB.Add(aComp,myFreeEdges.Value(i));
226       aoldShape = aComp;
227       
228     }
229     myResultShape = myContext->Apply(aoldShape);
230   }
231   return;
232 }
233
234 //=======================================================================
235 //function : checkGaps
236 //purpose  : 
237 //=======================================================================
238 Standard_Boolean ShHealOper_CloseContour::fixGaps(const Handle(ShapeExtend_WireData)& theWire,
239                                                   const TopTools_SequenceOfShape& theCommonFaces) 
240 {
241   Handle(ShapeAnalysis_Wire) asaw = new ShapeAnalysis_Wire;
242   asaw->Load(theWire);
243   
244   Standard_Integer i =1;
245   Standard_Boolean hasGaps = Standard_False;
246   for ( ; i <= asaw->NbEdges(); i++) {
247     if(asaw->CheckGap3d(i)) {
248       Standard_Real dist = asaw->MinDistance3d();
249       if(dist > myMaxTolerance) {
250         hasGaps = Standard_True;
251         Standard_Integer ind2 = (i ==0 ? theWire->NbEdges() :i);
252         Standard_Integer ind1 = (ind2 >1 ? ind2 -1 : theWire->NbEdges());
253         TopoDS_Edge aE1= theWire->Edge(ind1);
254         TopoDS_Edge aE2= theWire->Edge(ind2);
255         if(!myModeVertex) {
256           buildEdge(aE1,aE2,theCommonFaces);
257           myStatistics.AddModif("An edge added to close a wire");
258         }
259         else {
260           myMaxTolerance = RealLast();
261           myStatistics.AddModif("Tolerance of vertex increased to close a wire");
262         }
263         if(ind2 == ind1) break;
264       }
265     }
266     
267   }
268   return  hasGaps;
269 }
270
271 //=======================================================================
272 //function : checkOneFace
273 //purpose  : 
274 //=======================================================================
275 Standard_Boolean
276 ShHealOper_CloseContour::checkOneFace(const Handle(ShapeExtend_WireData)& theSewd,
277                                       TopTools_SequenceOfShape& theCommonFaces) const
278 {
279   TopTools_IndexedMapOfShape amapfaces;
280   TopoDS_Edge aEdge1 = theSewd->Edge(1);
281   Standard_Boolean isOneFace = myMapEdgesFace.Contains(aEdge1 );
282   if(!isOneFace)
283     return isOneFace;
284
285   //check that all specified edges belong to one face. 
286   const TopTools_ListOfShape& alfaces = myMapEdgesFace.FindFromKey(aEdge1);
287   isOneFace = isOneFace && (!alfaces.IsEmpty());
288   if(!isOneFace)
289     return Standard_False;
290
291   TopTools_ListIteratorOfListOfShape litr(alfaces);
292   for( ; litr.More();litr.Next() ) 
293     amapfaces.Add(litr.Value());
294   
295   TColStd_MapOfInteger amapIndex;
296   Standard_Integer ind  =0;
297   Standard_Integer i =2;
298   for( ; i <= theSewd->NbEdges() && isOneFace; i++) {
299     isOneFace = myMapEdgesFace.Contains(theSewd->Edge(i));
300     if(isOneFace) {
301       const TopTools_ListOfShape& alfaces1 = myMapEdgesFace.FindFromKey(theSewd->Edge(i));
302       
303         TColStd_MapOfInteger aTmpInd;
304         for(litr.Initialize(alfaces1) ; litr.More() ;litr.Next() ) {
305           if(amapfaces.Contains(litr.Value())) {
306             ind = amapfaces.FindIndex(litr.Value());
307             if( i == 2) 
308               amapIndex.Add(ind);
309             else 
310               aTmpInd.Add(ind);
311           }
312         }
313       if(i ==2) {
314         isOneFace = (amapIndex.Extent());
315         continue;
316       }
317       else {
318         TColStd_MapIteratorOfMapOfInteger aMi(amapIndex);
319         for( ;  aMi.More();aMi.Next()) {
320           if(!aTmpInd.Contains(aMi.Key()))
321             amapIndex.Remove(aMi.Key());
322         }
323         isOneFace = (amapIndex.Extent()); 
324         
325       }
326     }
327   }
328   if(theSewd->NbEdges() >1) {
329     Standard_Integer j =1;
330     for( ; j <= amapfaces.Extent(); j++) {
331       if(!amapIndex.Contains(j)) continue;
332       TopoDS_Shape aF = amapfaces.FindKey(j);
333       theCommonFaces.Append(aF);
334     }
335   }
336   return isOneFace;
337 }
338
339 //=======================================================================
340 //function : buildEdge
341 //purpose  : 
342 //=======================================================================
343 void ShHealOper_CloseContour::buildEdge(const TopoDS_Edge& aE1, 
344                                         const TopoDS_Edge& aE2,
345                                         const TopTools_SequenceOfShape& theCommonFaces) 
346 {
347   ShapeAnalysis_Edge asae;
348   TopoDS_Vertex aV1 = asae.LastVertex(aE1);
349   TopoDS_Vertex aV2 = asae.FirstVertex(aE2);
350   gp_Pnt p1 = BRep_Tool::Pnt(aV1);
351   gp_Pnt p2 = BRep_Tool::Pnt(aV2);
352   BRepBuilderAPI_MakeVertex mkver1( p1 );
353   TopoDS_Vertex newV1 = mkver1.Vertex();
354   
355   BRepBuilderAPI_MakeVertex mkver2( p2 );
356   TopoDS_Vertex newV2 = mkver2.Vertex();
357   BRep_Builder B;
358   B.UpdateVertex ( newV1,Precision::Confusion());
359   B.UpdateVertex ( newV2, Precision::Confusion());
360   Standard_Boolean isBuild = Standard_False;
361   TopoDS_Edge edge;
362   B.MakeEdge ( edge );
363   ShapeBuild_Edge sbe;
364   //if all edges belong to one face that gap will be closed in the 2D by line
365   //than 3D curve will be built by 2D curve
366   if(theCommonFaces.Length()) {
367     
368     TopoDS_Face aF1 = TopoDS::Face(theCommonFaces.Value(1));
369     Handle(Geom2d_Curve) c2d1,c2d2;
370     gp_Pnt2d p2d1,p2d2;
371     Standard_Real a1, b1,a2, b2;
372     if (  asae.PCurve ( aE1, aF1, c2d1, a1, b1, Standard_True )  && 
373         asae.PCurve ( aE2, aF1, c2d2, a2, b2, Standard_True )) {
374       
375       c2d1->D0 ( b1, p2d1);
376       c2d2->D0 ( a2, p2d2);
377       gp_Vec2d v12 ( p2d1, p2d2 );
378       
379       Handle(Geom2d_Line) aLine2d = new Geom2d_Line ( p2d1, gp_Dir2d ( v12 ) );
380       B.UpdateEdge ( edge, aLine2d, aF1, ::Precision::Confusion() );
381       B.Range ( edge, aF1, 0.0, v12.Magnitude() );
382       
383       isBuild = sbe.BuildCurve3d ( edge );
384     }
385   }
386   //else gap will be closed in the 3D by line.
387   if(!isBuild) {
388     gp_Vec v1 ( p1, p2 );
389     Handle(Geom_Line) aLine = new Geom_Line ( p1, gp_Dir ( v1 ) );
390     B.UpdateEdge ( edge, aLine, ::Precision::Confusion() );
391     B.Range ( edge,0.0, v1.Magnitude());
392   }
393   B.Add ( edge, newV1.Oriented ( TopAbs_FORWARD ) );
394   B.Add ( edge, newV2.Oriented ( TopAbs_REVERSED ) );
395   myContext->Replace(aV1, newV1.Oriented (aV1.Orientation()));
396   myContext->Replace(aV2, newV2.Oriented (aV2.Orientation()));
397   if(isBuild) {
398     newV1.Orientation(aV1.Orientation());
399     TopoDS_Edge newEdge = sbe.CopyReplaceVertices ( aE1,TopoDS_Vertex(), newV1);
400     TopoDS_Wire aw;
401     B.MakeWire(aw);
402     B.Add(aw,newEdge);
403     B.Add(aw,edge);
404     TopoDS_Shape anE1 = myContext->Apply(aE1);
405     myContext->Replace(anE1,aw);
406   }
407   else {
408     myFreeEdges.Append(edge);
409   }
410 }
411
412 //=======================================================================
413 //function : UpdateWire
414 //purpose  : 
415 //=======================================================================
416 void ShHealOper_CloseContour::updateWire (Handle(ShapeExtend_WireData)& sbwd) 
417 {
418   Standard_Integer i=1;
419   for ( ; i <= sbwd->NbEdges(); i++ ) {
420     TopoDS_Edge E = sbwd->Edge(i);
421     TopoDS_Shape S = myContext->Apply ( E );
422     if ( S == E ) continue;
423     for ( TopExp_Explorer exp(S,TopAbs_EDGE); exp.More(); exp.Next() )
424       sbwd->Add ( exp.Current(), i++ );
425     sbwd->Remove ( i-- );
426   }
427   for ( i =1; i <= myFreeEdges.Length(); i++ ) {
428     sbwd->Add(TopoDS::Edge(myFreeEdges.Value(i)));
429   }
430 }