Salome HOME
7fa3cbe52f1bd7cc67b8111467ad5c259c2a6857
[modules/geom.git] / GEOMImpl_Fillet1dDriver.cxx
1 // Copyright (C) 2007-2015  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, 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 <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   if (!GEOMUtils::CheckShape(aResult, true) &&
255       !GEOMUtils::FixShapeTolerance(aResult)) {
256     Standard_ConstructionError::Raise("Non valid shape result");
257   }
258
259   aFunction->SetValue(aResult);
260   log.SetTouched(Label());
261
262   return 1;
263 }
264
265 //=======================================================================
266 //function : MakeFillet
267 //purpose  :
268 //=======================================================================
269 bool GEOMImpl_Fillet1dDriver::MakeFillet(const TopoDS_Wire& aWire,
270                                          const TopTools_ListOfShape& aVertexList,
271                                          const Standard_Real rad,
272                                          bool isFinalPass,
273                                          TopoDS_Wire& aResult) const
274 {
275   // this variable is needed to break execution
276   // in case of fillet failure and try to fuse edges
277   bool isAllStepsOk = true;
278
279   //INFO: this algorithm implemented in assumption that user can select both
280   //  vertices of some edges to make fillet. In this case we should remember
281   //  already modified initial edges to take care in next fillet step
282   TopTools_DataMapOfShapeShape anEdgeToEdgeMap;
283
284   //iterates on vertices, and make fillet on each couple of edges
285   //collect result fillet edges in list
286   TopTools_ListOfShape aListOfNewEdge;
287   // remember relation between initial and modified map
288   TopTools_IndexedDataMapOfShapeListOfShape aMapVToEdges;
289   TopExp::MapShapesAndAncestors( aWire, TopAbs_VERTEX, TopAbs_EDGE, aMapVToEdges );
290   TopTools_ListIteratorOfListOfShape anIt( aVertexList );
291   for ( ; anIt.More(); anIt.Next() ) {
292     TopoDS_Vertex aV = TopoDS::Vertex( anIt.Value() );
293     if ( aV.IsNull() || !aMapVToEdges.Contains( aV ) )
294       continue;
295     const TopTools_ListOfShape& aVertexEdges = aMapVToEdges.FindFromKey( aV );
296     if ( aVertexEdges.Extent() != 2 )
297       continue; // no input data to make fillet
298     TopoDS_Edge anEdge1 = TopoDS::Edge( aVertexEdges.First() );
299     TopoDS_Edge anEdge2 = TopoDS::Edge( aVertexEdges.Last() );
300     // check if initial edges already modified in previous fillet operation
301     if ( anEdgeToEdgeMap.IsBound( anEdge1 ) ) anEdge1 = TopoDS::Edge(anEdgeToEdgeMap.Find( anEdge1 ));
302     if ( anEdgeToEdgeMap.IsBound( anEdge2 ) ) anEdge2 = TopoDS::Edge(anEdgeToEdgeMap.Find( anEdge2 ));
303     if ( anEdge1.IsNull() || anEdge2.IsNull() || anEdge1.IsSame( anEdge2 ) )
304       continue; //no input data to make fillet
305
306     // create plane on 2 edges
307     gp_Pln aPlane;
308     if ( !takePlane(anEdge1, anEdge2, aV, aPlane) )
309       continue; // seems edges does not belong to same plane or parallel (fillet can not be build)
310
311     GEOMImpl_Fillet1d aFilletAlgo (anEdge1, anEdge2, aPlane);
312     if (!aFilletAlgo.Perform(rad)) {
313       if (isFinalPass)
314         continue; // can not create fillet with given radius
315       else {
316         isAllStepsOk = false;
317         break; // can not create fillet with given radius
318       }
319     }
320
321     // take fillet result in given vertex
322     TopoDS_Edge aModifE1, aModifE2;
323     TopoDS_Edge aNewE = aFilletAlgo.Result(BRep_Tool::Pnt(aV), aModifE1, aModifE2);
324     if (aNewE.IsNull()) {
325       if (isFinalPass)
326         continue; // no result found
327       else {
328         isAllStepsOk = false;
329         break; // no result found
330       }
331     }
332
333     // add  new created edges and take modified edges
334     aListOfNewEdge.Append(aNewE);
335
336     // check if wire edges modified,
337     // if yes, then map to original edges (from vertex-edges list), because edges can be modified before
338     if (aModifE1.IsNull() || !anEdge1.IsSame( aModifE1 ))
339       addEdgeRelation( anEdgeToEdgeMap, TopoDS::Edge(aVertexEdges.First()), aModifE1 );
340     if (aModifE2.IsNull() || !anEdge2.IsSame( aModifE2 ))
341       addEdgeRelation( anEdgeToEdgeMap, TopoDS::Edge(aVertexEdges.Last()), aModifE2 );
342   }
343
344   if (anEdgeToEdgeMap.IsEmpty() && aListOfNewEdge.IsEmpty()) {
345     if (isFinalPass)
346       StdFail_NotDone::Raise("1D Fillet can't be computed on the given shape with the given radius");
347     else
348       isAllStepsOk = false;
349   }
350
351   if (!isAllStepsOk)
352     return false;
353
354   // create new wire instead of original
355   for (TopExp_Explorer anExp (aWire, TopAbs_EDGE); anExp.More(); anExp.Next()) {
356     TopoDS_Shape anEdge = anExp.Current();
357     if (!anEdgeToEdgeMap.IsBound(anEdge))
358       aListOfNewEdge.Append(anEdge);
359     else if (!anEdgeToEdgeMap.Find(anEdge).IsNull())
360       aListOfNewEdge.Append(anEdgeToEdgeMap.Find(anEdge));
361   }
362
363   GEOMUtils::SortShapes(aListOfNewEdge);
364
365   BRepBuilderAPI_MakeWire aWireTool;
366   aWireTool.Add(aListOfNewEdge);
367   aWireTool.Build();
368   if (!aWireTool.IsDone())
369     return 0;
370
371   aResult = aWireTool.Wire();
372
373   return isAllStepsOk;
374 }
375 //================================================================================
376 /*!
377  * \brief Returns a name of creation operation and names and values of creation parameters
378  */
379 //================================================================================
380
381 bool GEOMImpl_Fillet1dDriver::
382 GetCreationInformation(std::string&             theOperationName,
383                        std::vector<GEOM_Param>& theParams)
384 {
385   if (Label().IsNull()) return 0;
386   Handle(GEOM_Function) function = GEOM_Function::GetFunction(Label());
387
388   GEOMImpl_IFillet1d aCI( function );
389   Standard_Integer aType = function->GetType();
390
391   theOperationName = "FILLET_1D";
392
393   switch ( aType ) {
394   case GEOM_FILLET_1D:
395     AddParam( theParams, "Wire", aCI.GetShape() );
396     AddParam( theParams, "Vertexes");
397     if ( aCI.GetLength() > 1 )
398       theParams[1] << aCI.GetLength() << " vertexes: ";
399     for (int i = 1; i <= aCI.GetLength(); ++i )
400       theParams[1] << aCI.GetVertex( i ) << " ";
401     AddParam( theParams, "Radius", aCI.GetR() );
402     AddParam( theParams, "Fuse collinear edges", aCI.GetFlag() );
403     break;
404   default:
405     return false;
406   }
407   
408   return true;
409 }
410
411 IMPLEMENT_STANDARD_HANDLE (GEOMImpl_Fillet1dDriver,GEOM_BaseDriver);
412 IMPLEMENT_STANDARD_RTTIEXT (GEOMImpl_Fillet1dDriver,GEOM_BaseDriver);