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