Salome HOME
f781f228eb4e41ad6e79a6a64fd69fe6cfb85bd0
[modules/geom.git] / src / GEOMImpl / GEOMImpl_Fillet1dDriver.cxx
1 // Copyright (C) 2007-2012  CEA/DEN, EDF R&D, OPEN CASCADE
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.
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 #include <Standard_Stream.hxx>
20
21 #include <GEOMImpl_Fillet1dDriver.hxx>
22
23 #include <GEOMImpl_Fillet1d.hxx>
24 #include <GEOMImpl_IFillet1d.hxx>
25 #include <GEOMImpl_Types.hxx>
26 #include <GEOMImpl_IShapesOperations.hxx>
27 #include <GEOMImpl_HealingDriver.hxx>
28 #include <GEOM_Function.hxx>
29
30 #include <ShapeFix_Wire.hxx>
31 #include <StdFail_NotDone.hxx>
32 #include <Standard_ConstructionError.hxx>
33
34 #include <TopAbs.hxx>
35 #include <TopoDS.hxx>
36 #include <TopoDS_Edge.hxx>
37 #include <TopoDS_Wire.hxx>
38 #include <TopoDS_Shape.hxx>
39 #include <TopExp.hxx>
40 #include <TopExp_Explorer.hxx>
41 #include <TopTools_DataMapOfShapeShape.hxx>
42 #include <TopTools_ListOfShape.hxx>
43 #include <TopTools_ListIteratorOfListOfShape.hxx>
44 #include <TopTools_IndexedDataMapOfShapeListOfShape.hxx>
45 #include <TopTools_IndexedMapOfShape.hxx>
46
47 #include <BRep_Tool.hxx>
48 #include <BRepTools.hxx>
49 #include <BRepBuilderAPI_MakeWire.hxx>
50 #include <BRepCheck_Analyzer.hxx>
51
52 #include <gp_Pln.hxx>
53 #include <gp_Dir.hxx>
54 #include <gp_XYZ.hxx>
55
56 #include <Precision.hxx>
57
58 //=======================================================================
59 //function : GetID
60 //purpose  :
61 //=======================================================================
62 const Standard_GUID& GEOMImpl_Fillet1dDriver::GetID()
63 {
64   static Standard_GUID aFillet1dDriver("FF60908B-AB2E-4b71-B098-5C256C37D961");
65   return aFillet1dDriver;
66 }
67
68 //=======================================================================
69 //function : GEOMImpl_Fillet1dDriver
70 //purpose  :
71 //=======================================================================
72 GEOMImpl_Fillet1dDriver::GEOMImpl_Fillet1dDriver()
73 {
74 }
75
76 //=======================================================================
77 //function : anotherVertex
78 //purpose  : local function to get vertex from edge
79 //=======================================================================
80 static TopoDS_Vertex anotherVertex( const TopoDS_Edge& theE,
81                                     const TopoDS_Vertex& theV )
82 {
83   // here is an assumption that edge has different vertices
84   TopoDS_Vertex aV;
85   TopExp_Explorer anExp( theE, TopAbs_VERTEX );
86   for ( ; anExp.More(); anExp.Next() )
87   {
88     if ( BRepTools::Compare(theV,TopoDS::Vertex(anExp.Current())) /*theV.IsSame(anExp.Current())*/ )
89       continue;
90     aV = TopoDS::Vertex( anExp.Current() );
91     break;
92   }
93   return aV;
94 }
95
96 //=======================================================================
97 //function : takePlane
98 //purpose  : local function returns plane of given edges
99 //=======================================================================
100 static Standard_Boolean takePlane( const TopoDS_Edge& theE1,
101                                    const TopoDS_Edge& theE2,
102                                    const TopoDS_Vertex& theV,
103                                    gp_Pln& thePlane )
104 {
105   TopoDS_Vertex aV12 = anotherVertex( theE1, theV );
106   TopoDS_Vertex aV22 = anotherVertex( theE2, theV );
107   // check can closed wire be created by two initial edges
108   if ( aV12.IsNull()  || aV22.IsNull() || aV12.IsSame( aV22 ) )
109     return false;
110
111   // create plane by 3 points
112   gp_XYZ aXYZ = BRep_Tool::Pnt( theV ).XYZ();
113   gp_XYZ aXYZ1 = BRep_Tool::Pnt( aV12 ).XYZ();
114   gp_XYZ aXYZ2 = BRep_Tool::Pnt( aV22 ).XYZ();
115   try {
116     gp_Dir aDir1( aXYZ - aXYZ1 );
117     gp_Dir aDir2( aXYZ2 - aXYZ );
118     Standard_Real anAngle = aDir1.Angle(aDir2);
119     if ( fabs(anAngle) <= gp::Resolution() ||
120          fabs(anAngle - M_PI) <= gp::Resolution() )
121       return false;
122     thePlane = gp_Pln( gp_Pnt(aXYZ), aDir1^ aDir2);
123   }
124   catch (Standard_Failure) {
125     return false;
126   }
127   return true;
128 }
129
130 //=======================================================================
131 //function : addEdgeRelation
132 //purpose  : local function to remember relation between initial and modified edge
133 //=======================================================================
134 static void addEdgeRelation(TopTools_DataMapOfShapeShape& theMap,
135                             const TopoDS_Edge& theInitE,
136                             const TopoDS_Edge& theResE)
137 {
138   if ( theMap.IsBound( theInitE ) )
139     theMap.ChangeFind( theInitE ) = theResE;
140   else
141     theMap.Bind( theInitE, theResE );
142 }
143
144 //=======================================================================
145 //function : Execute
146 //purpose  :
147 //=======================================================================
148 Standard_Integer GEOMImpl_Fillet1dDriver::Execute(TFunction_Logbook& log) const
149 {
150   if (Label().IsNull()) return 0;
151   Handle(GEOM_Function) aFunction = GEOM_Function::GetFunction(Label());
152
153   GEOMImpl_IFillet1d aCI (aFunction);
154
155   Handle(GEOM_Function) aRefShape = aCI.GetShape();
156   TopoDS_Shape aShape = aRefShape->GetValue();
157   if (aShape.IsNull())
158     return 0;
159   if (aShape.ShapeType() != TopAbs_WIRE)
160     Standard_ConstructionError::Raise("Wrong arguments: polyline as wire must be given");
161
162   TopoDS_Wire aWire = TopoDS::Wire(aShape);
163
164   bool doIgnoreSecantPoints = aCI.GetFlag();
165
166   double rad = aCI.GetR();
167   if (rad < Precision::Confusion())
168     return 0;
169
170   // collect vertices for make fillet
171   TopTools_ListOfShape aVertexList;
172   TopTools_IndexedMapOfShape anIndices;
173   TopExp::MapShapes(aWire, anIndices);
174   int aLen = aCI.GetLength();
175   if (aLen > 0) {
176     for (int ii = 1; ii <= aLen; ii++) {
177       int ind = aCI.GetVertex(ii);
178       if (1 <= ind && ind <= anIndices.Extent()) {
179         TopoDS_Shape aShapeVertex = anIndices.FindKey(ind);
180         if (aShapeVertex.ShapeType() == TopAbs_VERTEX)
181           aVertexList.Append(aShapeVertex);
182       }
183     }
184   }
185   else { // get all vertices from wire
186     TopTools_MapOfShape mapShape;
187     TopExp_Explorer anExp (aWire, TopAbs_VERTEX);
188     for (; anExp.More(); anExp.Next()) {
189       if (mapShape.Add(anExp.Current()))
190         aVertexList.Append(anExp.Current());
191     }
192   }
193   if (aVertexList.IsEmpty())
194     Standard_ConstructionError::Raise("Invalid input: no vertices to make fillet");
195
196   // at first we try to make fillet on the initial wire (without edges fusing)
197   bool isFinalPass = !doIgnoreSecantPoints;
198   TopoDS_Wire aResult;
199   bool isAllStepsOk = MakeFillet(aWire, aVertexList, rad, isFinalPass, aResult);
200
201   // try to fuse collinear edges to allow bigger radius
202   if (!isFinalPass && !isAllStepsOk) {
203     // 1. Fuse
204     TopoDS_Shape aShapeNew;
205     Handle(TColStd_HSequenceOfTransient) aVerts;
206     GEOMImpl_HealingDriver::FuseCollinearEdges(aWire, aVerts, aShapeNew);
207     TopoDS_Wire aWireNew = TopoDS::Wire(aShapeNew);
208
209     // 2. Rebuild the list of vertices (by coincidence)
210     Standard_Real tol, tolMax = Precision::Confusion();
211     for (TopExp_Explorer ExV (aWireNew, TopAbs_VERTEX); ExV.More(); ExV.Next()) {
212       TopoDS_Vertex Vertex = TopoDS::Vertex(ExV.Current());
213       tol = BRep_Tool::Tolerance(Vertex);
214       if (tol > tolMax)
215         tolMax = tol;
216     }
217
218     TopTools_ListOfShape aVertexListNew;
219     TopTools_IndexedMapOfShape anIndicesNew;
220     TopExp::MapShapes(aWireNew, anIndicesNew);
221     TopTools_ListIteratorOfListOfShape anIt (aVertexList);
222     for (; anIt.More(); anIt.Next()) {
223       TopoDS_Vertex aV = TopoDS::Vertex(anIt.Value());
224       if (anIndicesNew.Contains(aV))
225         aVertexListNew.Append(aV);
226       else {
227         // try to find by coords in the new wire
228         gp_Pnt aP = BRep_Tool::Pnt(aV);
229
230         bool isFound = false;
231         TopTools_MapOfShape mapShape;
232         TopExp_Explorer exp (aWireNew, TopAbs_VERTEX);
233         for (; exp.More() && !isFound; exp.Next()) {
234           if (mapShape.Add(exp.Current())) {
235             TopoDS_Vertex aVi = TopoDS::Vertex(exp.Current());
236             gp_Pnt aPi = BRep_Tool::Pnt(aVi);
237             if (aPi.Distance(aP) < tolMax) {
238               aVertexListNew.Append(aVi);
239               isFound = true;
240             }
241           }
242         }
243       }
244     }
245
246     // 3. Repeat the fillet algorithm
247     isFinalPass = true;
248     MakeFillet(aWireNew, aVertexListNew, rad, isFinalPass, aResult);
249   }
250
251   aFunction->SetValue(aResult);
252   log.SetTouched(Label());
253
254   return 1;
255 }
256
257 //=======================================================================
258 //function : MakeFillet
259 //purpose  :
260 //=======================================================================
261 bool GEOMImpl_Fillet1dDriver::MakeFillet(const TopoDS_Wire& aWire,
262                                          const TopTools_ListOfShape& aVertexList,
263                                          const Standard_Real rad,
264                                          bool isFinalPass,
265                                          TopoDS_Wire& aResult) const
266 {
267   // this variable is needed to break execution
268   // in case of fillet failure and try to fuse edges
269   bool isAllStepsOk = true;
270
271   //INFO: this algorithm implemented in assumption that user can select both
272   //  vertices of some edges to make fillet. In this case we should remember
273   //  already modified initial edges to take care in next fillet step
274   TopTools_DataMapOfShapeShape anEdgeToEdgeMap;
275
276   //iterates on vertices, and make fillet on each couple of edges
277   //collect result fillet edges in list
278   TopTools_ListOfShape aListOfNewEdge;
279   // remember relation between initial and modified map
280   TopTools_IndexedDataMapOfShapeListOfShape aMapVToEdges;
281   TopExp::MapShapesAndAncestors( aWire, TopAbs_VERTEX, TopAbs_EDGE, aMapVToEdges );
282   TopTools_ListIteratorOfListOfShape anIt( aVertexList );
283   for ( ; anIt.More(); anIt.Next() ) {
284     TopoDS_Vertex aV = TopoDS::Vertex( anIt.Value() );
285     if ( aV.IsNull() || !aMapVToEdges.Contains( aV ) )
286       continue;
287     const TopTools_ListOfShape& aVertexEdges = aMapVToEdges.FindFromKey( aV );
288     if ( aVertexEdges.Extent() != 2 )
289       continue; // no input data to make fillet
290     TopoDS_Edge anEdge1 = TopoDS::Edge( aVertexEdges.First() );
291     TopoDS_Edge anEdge2 = TopoDS::Edge( aVertexEdges.Last() );
292     // check if initial edges already modified in previous fillet operation
293     if ( anEdgeToEdgeMap.IsBound( anEdge1 ) ) anEdge1 = TopoDS::Edge(anEdgeToEdgeMap.Find( anEdge1 ));
294     if ( anEdgeToEdgeMap.IsBound( anEdge2 ) ) anEdge2 = TopoDS::Edge(anEdgeToEdgeMap.Find( anEdge2 ));
295     if ( anEdge1.IsNull() || anEdge2.IsNull() || anEdge1.IsSame( anEdge2 ) )
296       continue; //no input data to make fillet
297
298     // create plane on 2 edges
299     gp_Pln aPlane;
300     if ( !takePlane(anEdge1, anEdge2, aV, aPlane) )
301       continue; // seems edges does not belong to same plane or parallel (fillet can not be build)
302
303     GEOMImpl_Fillet1d aFilletAlgo (anEdge1, anEdge2, aPlane);
304     if (!aFilletAlgo.Perform(rad)) {
305       if (isFinalPass)
306         continue; // can not create fillet with given radius
307       else {
308         isAllStepsOk = false;
309         break; // can not create fillet with given radius
310       }
311     }
312
313     // take fillet result in given vertex
314     TopoDS_Edge aModifE1, aModifE2;
315     TopoDS_Edge aNewE = aFilletAlgo.Result(BRep_Tool::Pnt(aV), aModifE1, aModifE2);
316     if (aNewE.IsNull()) {
317       if (isFinalPass)
318         continue; // no result found
319       else {
320         isAllStepsOk = false;
321         break; // no result found
322       }
323     }
324
325     // add  new created edges and take modified edges
326     aListOfNewEdge.Append(aNewE);
327
328     // check if wire edges modified,
329     // if yes, then map to original edges (from vertex-edges list), because edges can be modified before
330     if (aModifE1.IsNull() || !anEdge1.IsSame( aModifE1 ))
331       addEdgeRelation( anEdgeToEdgeMap, TopoDS::Edge(aVertexEdges.First()), aModifE1 );
332     if (aModifE2.IsNull() || !anEdge2.IsSame( aModifE2 ))
333       addEdgeRelation( anEdgeToEdgeMap, TopoDS::Edge(aVertexEdges.Last()), aModifE2 );
334   }
335
336   if (anEdgeToEdgeMap.IsEmpty() && aListOfNewEdge.IsEmpty()) {
337     if (isFinalPass)
338       StdFail_NotDone::Raise("1D Fillet can't be computed on the given shape with the given radius");
339     else
340       isAllStepsOk = false;
341   }
342
343   if (!isAllStepsOk)
344     return false;
345
346   // create new wire instead of original
347   for (TopExp_Explorer anExp (aWire, TopAbs_EDGE); anExp.More(); anExp.Next()) {
348     TopoDS_Shape anEdge = anExp.Current();
349     if (!anEdgeToEdgeMap.IsBound(anEdge))
350       aListOfNewEdge.Append(anEdge);
351     else if (!anEdgeToEdgeMap.Find(anEdge).IsNull())
352       aListOfNewEdge.Append(anEdgeToEdgeMap.Find(anEdge));
353   }
354
355   GEOMImpl_IShapesOperations::SortShapes(aListOfNewEdge);
356
357   BRepBuilderAPI_MakeWire aWireTool;
358   aWireTool.Add(aListOfNewEdge);
359   aWireTool.Build();
360   if (!aWireTool.IsDone())
361     return 0;
362
363   aResult = aWireTool.Wire();
364
365   return isAllStepsOk;
366 }
367
368
369 //=======================================================================
370 //function :  GEOMImpl_Fillet1dDriver_Type_
371 //purpose  :
372 //=======================================================================
373 Standard_EXPORT Handle_Standard_Type& GEOMImpl_Fillet1dDriver_Type_()
374 {
375   static Handle_Standard_Type aType1 = STANDARD_TYPE(TFunction_Driver);
376   if ( aType1.IsNull()) aType1 = STANDARD_TYPE(TFunction_Driver);
377   static Handle_Standard_Type aType2 = STANDARD_TYPE(MMgt_TShared);
378   if ( aType2.IsNull()) aType2 = STANDARD_TYPE(MMgt_TShared);
379   static Handle_Standard_Type aType3 = STANDARD_TYPE(Standard_Transient);
380   if ( aType3.IsNull()) aType3 = STANDARD_TYPE(Standard_Transient);
381
382   static Handle_Standard_Transient _Ancestors[]= {aType1,aType2,aType3,NULL};
383   static Handle_Standard_Type _aType = new Standard_Type("GEOMImpl_Fillet1dDriver",
384                                                          sizeof(GEOMImpl_Fillet1dDriver),
385                                                          1,
386                                                          (Standard_Address)_Ancestors,
387                                                          (Standard_Address)NULL);
388
389   return _aType;
390 }
391
392 //=======================================================================
393 //function : DownCast
394 //purpose  :
395 //=======================================================================
396 const Handle(GEOMImpl_Fillet1dDriver) Handle(GEOMImpl_Fillet1dDriver)::DownCast(const Handle(Standard_Transient)& AnObject)
397 {
398   Handle(GEOMImpl_Fillet1dDriver) _anOtherObject;
399
400   if (!AnObject.IsNull()) {
401      if (AnObject->IsKind(STANDARD_TYPE(GEOMImpl_Fillet1dDriver))) {
402        _anOtherObject = Handle(GEOMImpl_Fillet1dDriver)((Handle(GEOMImpl_Fillet1dDriver)&)AnObject);
403      }
404   }
405
406   return _anOtherObject;
407 }