Salome HOME
ea4fd94d35ec0f20301da65446145768fc368e0a
[modules/geom.git] / src / GEOMImpl / GEOMImpl_Fillet1dDriver.cxx
1 // Copyright (C) 2007-2014  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   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  * \brief Returns a name of creation operation and names and values of creation parameters
373  */
374 //================================================================================
375
376 bool GEOMImpl_Fillet1dDriver::
377 GetCreationInformation(std::string&             theOperationName,
378                        std::vector<GEOM_Param>& theParams)
379 {
380   if (Label().IsNull()) return 0;
381   Handle(GEOM_Function) function = GEOM_Function::GetFunction(Label());
382
383   GEOMImpl_IFillet1d aCI( function );
384   Standard_Integer aType = function->GetType();
385
386   theOperationName = "FILLET_1D";
387
388   switch ( aType ) {
389   case GEOM_FILLET_1D:
390     AddParam( theParams, "Wire", aCI.GetShape() );
391     AddParam( theParams, "Vertexes");
392     if ( aCI.GetLength() > 1 )
393       theParams[1] << aCI.GetLength() << " vertexes: ";
394     for (int i = 1; i <= aCI.GetLength(); ++i )
395       theParams[1] << aCI.GetVertex( i ) << " ";
396     AddParam( theParams, "Radius", aCI.GetR() );
397     AddParam( theParams, "Fuse collinear edges", aCI.GetFlag() );
398     break;
399   default:
400     return false;
401   }
402   
403   return true;
404 }
405
406 IMPLEMENT_STANDARD_HANDLE (GEOMImpl_Fillet1dDriver,GEOM_BaseDriver);
407 IMPLEMENT_STANDARD_RTTIEXT (GEOMImpl_Fillet1dDriver,GEOM_BaseDriver);