Salome HOME
0022353: EDF GEOM: Projection on a edge or a wire
[modules/geom.git] / src / GEOMImpl / GEOMImpl_ProjectionDriver.cxx
1 // Copyright (C) 2007-2013  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.
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 #include <Standard_Stream.hxx>
24
25 #include <GEOMImpl_ProjectionDriver.hxx>
26
27 #include <GEOMImpl_IMirror.hxx>
28 #include <GEOMImpl_IProjection.hxx>
29 #include <GEOMImpl_Types.hxx>
30 #include <GEOM_Function.hxx>
31
32 #include <BRep_Tool.hxx>
33 #include <BRepBuilderAPI_Transform.hxx>
34 #include <BRepBuilderAPI_MakeVertex.hxx>
35 #include <BRepClass_FaceClassifier.hxx>
36 #include <BRepExtrema_DistShapeShape.hxx>
37 #include <BRepOffsetAPI_NormalProjection.hxx>
38 #include <BRepTools.hxx>
39
40 #include <TopAbs.hxx>
41 #include <TopExp.hxx>
42 #include <TopoDS.hxx>
43 #include <TopoDS_Shape.hxx>
44 #include <TopoDS_Edge.hxx>
45 #include <TopoDS_Face.hxx>
46 #include <TopoDS_Vertex.hxx>
47 #include <TopTools_IndexedDataMapOfShapeListOfShape.hxx>
48
49 #include <GeomAPI_ProjectPointOnSurf.hxx>
50 #include <Geom_Curve.hxx>
51 #include <Geom_Plane.hxx>
52
53 #include <gp_Trsf.hxx>
54 #include <gp_Pnt.hxx>
55 #include <gp_Vec.hxx>
56
57 //=======================================================================
58 //function : GetID
59 //purpose  :
60 //======================================================================= 
61 const Standard_GUID& GEOMImpl_ProjectionDriver::GetID()
62 {
63   static Standard_GUID aProjectionDriver ("FF1BBB70-5D14-4df2-980B-3A668264EA16");
64   return aProjectionDriver; 
65 }
66
67
68 //=======================================================================
69 //function : GEOMImpl_ProjectionDriver
70 //purpose  : 
71 //=======================================================================
72
73 GEOMImpl_ProjectionDriver::GEOMImpl_ProjectionDriver() 
74 {
75 }
76
77 //=======================================================================
78 //function : Execute
79 //purpose  :
80 //======================================================================= 
81 Standard_Integer GEOMImpl_ProjectionDriver::Execute(TFunction_Logbook& log) const
82 {
83   if (Label().IsNull())  return 0;    
84   Handle(GEOM_Function) aFunction = GEOM_Function::GetFunction(Label());
85
86   if (aFunction.IsNull()) return 0;
87
88   Standard_Integer aType = aFunction->GetType();
89
90   if (aType == PROJECTION_COPY) {
91     // Projection
92     TopoDS_Shape aShape;
93     gp_Trsf aTrsf;
94
95     GEOMImpl_IMirror TI (aFunction);
96
97     Handle(GEOM_Function) anOriginalFunction = TI.GetOriginal();
98     if (anOriginalFunction.IsNull()) return 0;
99
100     TopoDS_Shape anOriginal = anOriginalFunction->GetValue();
101     if (anOriginal.IsNull()) return 0;
102
103     // Source shape (point, edge or wire)
104     if (anOriginal.ShapeType() != TopAbs_VERTEX &&
105         anOriginal.ShapeType() != TopAbs_EDGE &&
106         anOriginal.ShapeType() != TopAbs_WIRE) {
107       Standard_ConstructionError::Raise
108         ("Projection aborted : the source shape is neither a vertex, nor an edge or a wire");
109     }
110
111     // Target face
112     Handle(GEOM_Function) aTargetFunction = TI.GetPlane();
113     if (aTargetFunction.IsNull()) return 0;
114     TopoDS_Shape aFaceShape = aTargetFunction->GetValue();
115     //if (aFaceShape.IsNull() || aFaceShape.ShapeType() != TopAbs_FACE) {
116     //  Standard_ConstructionError::Raise
117     //    ("Projection aborted : the target shape is not a face");
118     //}
119
120     Standard_Real tol = 1.e-4;        
121
122     if (anOriginal.ShapeType() == TopAbs_VERTEX) {
123       if (aFaceShape.IsNull() || aFaceShape.ShapeType() != TopAbs_FACE) {
124         Standard_ConstructionError::Raise
125           ("Projection aborted : the target shape is not a face");
126       }
127       TopoDS_Face aFace = TopoDS::Face(aFaceShape);
128       Handle(Geom_Surface) surface = BRep_Tool::Surface(aFace);
129       double U1, U2, V1, V2;
130       //surface->Bounds(U1, U2, V1, V2);
131       BRepTools::UVBounds(aFace, U1, U2, V1, V2);
132
133       // projector
134       GeomAPI_ProjectPointOnSurf proj;
135       proj.Init(surface, U1, U2, V1, V2, tol);
136
137       gp_Pnt aPnt = BRep_Tool::Pnt(TopoDS::Vertex(anOriginal));
138       proj.Perform(aPnt);
139       if (!proj.IsDone()) {
140         Standard_ConstructionError::Raise
141           ("Projection aborted : the algorithm failed");
142       }
143       int nbPoints = proj.NbPoints();
144       if (nbPoints < 1) {
145         Standard_ConstructionError::Raise("No solution found");
146       }
147
148       Quantity_Parameter U, V;
149       proj.LowerDistanceParameters(U, V);
150       gp_Pnt2d aProjPnt (U, V);
151
152       // classifier
153       BRepClass_FaceClassifier aClsf (aFace, aProjPnt, tol);
154       if (aClsf.State() != TopAbs_IN && aClsf.State() != TopAbs_ON) {
155         bool isSol = false;
156         double minDist = RealLast();
157         for (int i = 1; i <= nbPoints; i++) {
158           Quantity_Parameter Ui, Vi;
159           proj.Parameters(i, Ui, Vi);
160           aProjPnt = gp_Pnt2d(Ui, Vi);
161           aClsf.Perform(aFace, aProjPnt, tol);
162           if (aClsf.State() == TopAbs_IN || aClsf.State() == TopAbs_ON) {
163             isSol = true;
164             double dist = proj.Distance(i);
165             if (dist < minDist) {
166               minDist = dist;
167               U = Ui;
168               V = Vi;
169             }
170           }
171         }
172         if (!isSol) {
173           Standard_ConstructionError::Raise("No solution found");
174         }
175       }
176
177       gp_Pnt surfPnt = surface->Value(U, V);
178
179       aShape = BRepBuilderAPI_MakeVertex(surfPnt).Shape();
180     }
181     else {
182       //see BRepTest_BasicCommands.cxx for example of BRepOffsetAPI_NormalProjection
183       BRepOffsetAPI_NormalProjection OrtProj (aFaceShape);
184       OrtProj.Add(anOriginal);
185
186       //Standard_Real tol = 1.e-4;        
187       //Standard_Real tol2d = Pow(tol, 2./3);
188       //GeomAbs_Shape Continuity = GeomAbs_C2;  
189       //Standard_Integer MaxDeg = 14;           
190       //Standard_Integer MaxSeg = 16;           
191       //OrtProj.SetParams(tol, tol2d, Continuity, MaxDeg, MaxSeg);
192       try {
193         OrtProj.Build();
194       } catch (Standard_Failure) {
195         Handle(Standard_Failure) aFail = Standard_Failure::Caught();
196         TCollection_AsciiString aMsg (aFail->GetMessageString());
197         if (!aMsg.Length())
198           aMsg = "Projection aborted : possibly the source shape intersects the cylinder's axis";
199         Standard_ConstructionError::Raise(aMsg.ToCString());
200       }
201       if (!OrtProj.IsDone()) {
202         Standard_ConstructionError::Raise
203           ("Projection aborted : BRepOffsetAPI_NormalProjection failed");
204       }
205
206       aShape = OrtProj.Shape();
207
208       // check that the result shape is an empty compound
209       // (IPAL22905: TC650: Projection on face dialog problems)
210       if( !aShape.IsNull() && aShape.ShapeType() == TopAbs_COMPOUND )
211       {
212         TopoDS_Iterator anIter( aShape );
213         if( !anIter.More() )
214           Standard_ConstructionError::Raise("Projection aborted : empty compound produced");
215       }
216     }
217
218     if (aShape.IsNull()) return 0;
219
220     aFunction->SetValue(aShape);
221     log.SetTouched(Label()); 
222   } else if (aType == PROJECTION_ON_WIRE) {
223     // Perform projection of point on a wire or an edge.
224     GEOMImpl_IProjection aProj (aFunction);
225     Handle(GEOM_Function) aPointFunction = aProj.GetPoint();
226     Handle(GEOM_Function) aShapeFunction = aProj.GetShape();
227
228     if (aPointFunction.IsNull() || aShapeFunction.IsNull()) {
229       return 0;
230     }
231
232     TopoDS_Shape aPoint = aPointFunction->GetValue();
233     TopoDS_Shape aShape = aShapeFunction->GetValue();
234
235     if (aPoint.IsNull() || aShape.IsNull()) {
236       return 0;
237     }
238
239     // Check shape types.
240     if (aPoint.ShapeType() != TopAbs_VERTEX) {
241       Standard_ConstructionError::Raise
242         ("Projection aborted : the point is not a vertex");
243     }
244
245     if (aShape.ShapeType() != TopAbs_EDGE &&
246         aShape.ShapeType() != TopAbs_WIRE) {
247       Standard_ConstructionError::Raise
248         ("Projection aborted : the shape is neither an edge nor a wire");
249     }
250
251     // Perform projection.
252     BRepExtrema_DistShapeShape aDistShSh(aPoint, aShape, Extrema_ExtFlag_MIN);
253
254     if (aDistShSh.IsDone() == Standard_False) {
255       Standard_ConstructionError::Raise("Projection not done");
256     }
257
258     Standard_Boolean hasValidSolution = Standard_False;
259     Standard_Integer aNbSolutions     = aDistShSh.NbSolution();
260     Standard_Integer i;
261     double           aParam   = 0.;
262     Standard_Real    aTolConf = BRep_Tool::Tolerance(TopoDS::Vertex(aPoint));
263     Standard_Real    aTolAng  = 1.e-4;        
264
265     for (i = 1; i <= aNbSolutions; i++) {
266       Standard_Boolean        isValid       = Standard_False;
267       BRepExtrema_SupportType aSupportType  = aDistShSh.SupportTypeShape2(i);
268       TopoDS_Shape            aSupportShape = aDistShSh.SupportOnShape2(i);
269
270       if (aSupportType == BRepExtrema_IsOnEdge) {
271         // Minimal distance inside edge is really a projection.
272         isValid = Standard_True;
273         aDistShSh.ParOnEdgeS2(i, aParam);
274       } else if (aSupportType == BRepExtrema_IsVertex) {
275         TopExp_Explorer anExp(aShape, TopAbs_EDGE);
276
277         if (aDistShSh.Value() <= aTolConf) {
278           // The point lies on the shape. This means this point
279           // is really a projection.
280           for (; anExp.More() && !isValid; anExp.Next()) {
281             TopoDS_Edge aCurEdge = TopoDS::Edge(anExp.Current());
282
283             if (aCurEdge.IsNull() == Standard_False) {
284               TopoDS_Vertex aVtx[2];
285                         
286               TopExp::Vertices(aCurEdge, aVtx[0], aVtx[1]);
287
288               for (int j = 0; j < 2; j++) {
289                 if (aSupportShape.IsSame(aVtx[j])) {
290                   // The current edge is a projection edge.
291                   isValid       = Standard_True;
292                   aSupportShape = aCurEdge;
293                   aParam        = BRep_Tool::Parameter(aVtx[j], aCurEdge);
294                   break;
295                 }
296               }
297             }
298           }
299         } else {
300           // Minimal distance to vertex is not always a real projection.
301           gp_Pnt aPnt    = BRep_Tool::Pnt(TopoDS::Vertex(aPoint));
302           gp_Pnt aPrjPnt = BRep_Tool::Pnt(TopoDS::Vertex(aSupportShape));
303           gp_Vec aDProjP(aPrjPnt, aPnt);
304
305           for (; anExp.More() && !isValid; anExp.Next()) {
306             TopoDS_Edge aCurEdge = TopoDS::Edge(anExp.Current());
307  
308             if (aCurEdge.IsNull() == Standard_False) {
309               TopoDS_Vertex aVtx[2];
310                           
311               TopExp::Vertices(aCurEdge, aVtx[0], aVtx[1]);
312  
313               for (int j = 0; j < 2; j++) {
314                 if (aSupportShape.IsSame(aVtx[j])) {
315                   // Check if the point is a projection to the current edge.
316                   Standard_Real      anEdgePars[2];
317                   Handle(Geom_Curve) aCurve =
318                     BRep_Tool::Curve(aCurEdge, anEdgePars[0], anEdgePars[1]);
319                   gp_Pnt             aVal;
320                   gp_Vec             aD1;
321
322                   aParam = BRep_Tool::Parameter(aVtx[j], aCurEdge);
323                   aCurve->D1(aParam, aVal, aD1);
324
325                   if (Abs(aD1.Dot(aDProjP)) <= aTolAng) {
326                     // The current edge is a projection edge.
327                     isValid       = Standard_True;
328                     aSupportShape = aCurEdge;
329                     break;
330                   }
331                 }
332               }
333             }
334           }
335         }
336       }
337       
338
339       if (isValid) {
340         if (hasValidSolution) {
341           Standard_ConstructionError::Raise
342             ("Projection aborted : multiple solutions");
343         }
344
345         // Store the valid solution.
346         hasValidSolution = Standard_True;
347         aProj.SetU(aParam);
348
349         // Compute edge index.
350         TopTools_IndexedMapOfShape anIndices;
351         TopExp::MapShapes(aShape, anIndices);
352         const int anIndex = anIndices.FindIndex(aSupportShape);
353
354         aProj.SetIndex(anIndex);
355
356         // Construct a projection vertex.
357         const gp_Pnt &aPntProj = aDistShSh.PointOnShape2(i);
358         TopoDS_Shape  aProj    = BRepBuilderAPI_MakeVertex(aPntProj).Shape();
359         
360         aFunction->SetValue(aProj);
361       }
362     }
363
364     if (!hasValidSolution) {
365       Standard_ConstructionError::Raise("Projection aborted : no projection");
366     }
367   }
368
369   return 1;
370 }
371
372 //================================================================================
373 /*!
374  * \brief Returns a name of creation operation and names and values of creation parameters
375  */
376 //================================================================================
377
378 bool GEOMImpl_ProjectionDriver::
379 GetCreationInformation(std::string&             theOperationName,
380                        std::vector<GEOM_Param>& theParams)
381 {
382   if (Label().IsNull()) return 0;
383   Handle(GEOM_Function) function = GEOM_Function::GetFunction(Label());
384
385   GEOMImpl_IMirror aCI( function );
386   Standard_Integer aType = function->GetType();
387
388   theOperationName = "PROJECTION";
389
390   switch ( aType ) {
391   case PROJECTION_COPY:
392     AddParam( theParams, "Source object", aCI.GetOriginal() );
393     AddParam( theParams, "Target face", aCI.GetPlane() );
394     break;
395   default:
396     return false;
397   }
398   
399   return true;
400 }
401
402 IMPLEMENT_STANDARD_HANDLE (GEOMImpl_ProjectionDriver,GEOM_BaseDriver);
403 IMPLEMENT_STANDARD_RTTIEXT (GEOMImpl_ProjectionDriver,GEOM_BaseDriver);