Salome HOME
5e4586bed89df5e2216ee2f60c8e728b1f03a711
[modules/smesh.git] / src / StdMeshers / StdMeshers_Projection_2D.cxx
1 // Copyright (C) 2007-2014  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, or (at your option) any later version.
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 //  SMESH SMESH : implementaion of SMESH idl descriptions
24 // File      : StdMeshers_Projection_2D.cxx
25 // Module    : SMESH
26 // Created   : Fri Oct 20 11:37:07 2006
27 // Author    : Edward AGAPOV (eap)
28 //
29 #include "StdMeshers_Projection_2D.hxx"
30
31 #include "StdMeshers_ProjectionSource2D.hxx"
32 #include "StdMeshers_ProjectionUtils.hxx"
33 #include "StdMeshers_FaceSide.hxx"
34
35 #include "SMDS_EdgePosition.hxx"
36 #include "SMDS_FacePosition.hxx"
37 #include "SMESHDS_Hypothesis.hxx"
38 #include "SMESHDS_SubMesh.hxx"
39 #include "SMESH_Block.hxx"
40 #include "SMESH_Comment.hxx"
41 #include "SMESH_Gen.hxx"
42 #include "SMESH_Mesh.hxx"
43 #include "SMESH_MesherHelper.hxx"
44 #include "SMESH_Pattern.hxx"
45 #include "SMESH_subMesh.hxx"
46 #include "SMESH_subMeshEventListener.hxx"
47
48 #include "utilities.h"
49
50 #include <BRepAdaptor_Surface.hxx>
51 #include <BRep_Tool.hxx>
52 #include <Bnd_B2d.hxx>
53 #include <GeomAPI_ProjectPointOnSurf.hxx>
54 #include <GeomLib_IsPlanarSurface.hxx>
55 #include <TopExp.hxx>
56 #include <TopExp_Explorer.hxx>
57 #include <TopTools_DataMapIteratorOfDataMapOfShapeShape.hxx>
58 #include <TopTools_ListIteratorOfListOfShape.hxx>
59 #include <TopoDS.hxx>
60 #include <gp_Ax2.hxx>
61 #include <gp_Ax3.hxx>
62
63
64 using namespace std;
65
66 #define RETURN_BAD_RESULT(msg) { MESSAGE(")-: Error: " << msg); return false; }
67
68 namespace TAssocTool = StdMeshers_ProjectionUtils;
69 //typedef StdMeshers_ProjectionUtils TAssocTool;
70
71 //=======================================================================
72 //function : StdMeshers_Projection_2D
73 //purpose  : 
74 //=======================================================================
75
76 StdMeshers_Projection_2D::StdMeshers_Projection_2D(int hypId, int studyId, SMESH_Gen* gen)
77   :SMESH_2D_Algo(hypId, studyId, gen)
78 {
79   _name = "Projection_2D";
80   _compatibleHypothesis.push_back("ProjectionSource2D");
81   _sourceHypo = 0;
82 }
83
84 //================================================================================
85 /*!
86  * \brief Destructor
87  */
88 //================================================================================
89
90 StdMeshers_Projection_2D::~StdMeshers_Projection_2D()
91 {}
92
93 //=======================================================================
94 //function : CheckHypothesis
95 //purpose  : 
96 //=======================================================================
97
98 bool StdMeshers_Projection_2D::CheckHypothesis(SMESH_Mesh&                          theMesh,
99                                                const TopoDS_Shape&                  theShape,
100                                                SMESH_Hypothesis::Hypothesis_Status& theStatus)
101 {
102   list <const SMESHDS_Hypothesis * >::const_iterator itl;
103
104   const list <const SMESHDS_Hypothesis * >&hyps = GetUsedHypothesis(theMesh, theShape);
105   if ( hyps.size() == 0 )
106   {
107     theStatus = HYP_MISSING;
108     return false;  // can't work with no hypothesis
109   }
110
111   if ( hyps.size() > 1 )
112   {
113     theStatus = HYP_ALREADY_EXIST;
114     return false;
115   }
116
117   const SMESHDS_Hypothesis *theHyp = hyps.front();
118
119   string hypName = theHyp->GetName();
120
121   theStatus = HYP_OK;
122
123   if (hypName == "ProjectionSource2D")
124   {
125     _sourceHypo = static_cast<const StdMeshers_ProjectionSource2D *>(theHyp);
126
127     // Check hypo parameters
128
129     SMESH_Mesh* srcMesh = _sourceHypo->GetSourceMesh();
130     SMESH_Mesh* tgtMesh = & theMesh;
131     if ( !srcMesh )
132       srcMesh = tgtMesh;
133
134     // check vertices
135     if ( _sourceHypo->HasVertexAssociation() )
136     {
137       // source vertices
138       TopoDS_Shape edge = TAssocTool::GetEdgeByVertices
139         ( srcMesh, _sourceHypo->GetSourceVertex(1), _sourceHypo->GetSourceVertex(2) );
140       if ( edge.IsNull() ||
141            !SMESH_MesherHelper::IsSubShape( edge, srcMesh ) ||
142            !SMESH_MesherHelper::IsSubShape( edge, _sourceHypo->GetSourceFace() ))
143       {
144         theStatus = HYP_BAD_PARAMETER;
145         error("Invalid source vertices");
146         SCRUTE((edge.IsNull()));
147         SCRUTE((SMESH_MesherHelper::IsSubShape( edge, srcMesh )));
148         SCRUTE((SMESH_MesherHelper::IsSubShape( edge, _sourceHypo->GetSourceFace() )));
149       }
150       else
151       {
152         // target vertices
153         edge = TAssocTool::GetEdgeByVertices
154           ( tgtMesh, _sourceHypo->GetTargetVertex(1), _sourceHypo->GetTargetVertex(2) );
155         if ( edge.IsNull() || !SMESH_MesherHelper::IsSubShape( edge, tgtMesh ))
156         {
157           theStatus = HYP_BAD_PARAMETER;
158           error("Invalid target vertices");
159           SCRUTE((edge.IsNull()));
160           SCRUTE((SMESH_MesherHelper::IsSubShape( edge, tgtMesh )));
161         }
162         // PAL16203
163         else if ( !_sourceHypo->IsCompoundSource() &&
164                   !SMESH_MesherHelper::IsSubShape( edge, theShape ))
165         {
166           theStatus = HYP_BAD_PARAMETER;
167           error("Invalid target vertices");
168           SCRUTE((SMESH_MesherHelper::IsSubShape( edge, theShape )));
169         }
170       }
171     }
172     // check a source face
173     if ( !SMESH_MesherHelper::IsSubShape( _sourceHypo->GetSourceFace(), srcMesh ) ||
174          ( srcMesh == tgtMesh && theShape == _sourceHypo->GetSourceFace() ))
175     {
176       theStatus = HYP_BAD_PARAMETER;
177       error("Invalid source face");
178       SCRUTE((SMESH_MesherHelper::IsSubShape( _sourceHypo->GetSourceFace(), srcMesh )));
179       SCRUTE((srcMesh == tgtMesh));
180       SCRUTE(( theShape == _sourceHypo->GetSourceFace() ));
181     }
182   }
183   else
184   {
185     theStatus = HYP_INCOMPATIBLE;
186   }
187   return ( theStatus == HYP_OK );
188 }
189
190 namespace {
191
192   //================================================================================
193   /*!
194    * \brief define if a node is new or old
195    * \param node - node to check
196    * \retval bool - true if the node existed before Compute() is called
197    */
198   //================================================================================
199
200   bool isOldNode( const SMDS_MeshNode* node )
201   {
202     // old nodes are shared by edges and new ones are shared
203     // only by faces created by mapper
204     //if ( is1DComputed )
205     {
206       bool isOld = node->NbInverseElements(SMDSAbs_Edge) > 0;
207       return isOld;
208     }
209     // else
210     // {
211     //   SMDS_ElemIteratorPtr invFace = node->GetInverseElementIterator(SMDSAbs_Face);
212     //   bool isNew = invFace->more();
213     //   return !isNew;
214     // }
215   }
216
217   //================================================================================
218   /*!
219    * \brief Class to remove mesh built by pattern mapper on edges
220    * and vertices in the case of failure of projection algo.
221    * It does it's job at destruction
222    */
223   //================================================================================
224
225   class MeshCleaner {
226     SMESH_subMesh* sm;
227   public:
228     MeshCleaner( SMESH_subMesh* faceSubMesh ): sm(faceSubMesh) {}
229     ~MeshCleaner() { Clean(sm); }
230     void Release() { sm = 0; } // mesh will not be removed
231     static void Clean( SMESH_subMesh* sm, bool withSub=true )
232     {
233       if ( !sm || !sm->GetSubMeshDS() ) return;
234       // PAL16567, 18920. Remove face nodes as well
235 //       switch ( sm->GetSubShape().ShapeType() ) {
236 //       case TopAbs_VERTEX:
237 //       case TopAbs_EDGE: {
238         SMDS_NodeIteratorPtr nIt = sm->GetSubMeshDS()->GetNodes();
239         SMESHDS_Mesh* mesh = sm->GetFather()->GetMeshDS();
240         while ( nIt->more() ) {
241           const SMDS_MeshNode* node = nIt->next();
242           if ( !isOldNode( node ) )
243             mesh->RemoveNode( node );
244         }
245         // do not break but iterate over DependsOn()
246 //       }
247 //       default:
248         if ( !withSub ) return;
249         SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(false,false);
250         while ( smIt->more() )
251           Clean( smIt->next(), false );
252 //       }
253     }
254   };
255
256   //================================================================================
257   /*!
258    * \brief find new nodes belonging to one free border of mesh on face
259     * \param sm - submesh on edge or vertex containg nodes to choose from
260     * \param face - the face bound by the submesh
261     * \param u2nodes - map to fill with nodes
262     * \param seamNodes - set of found nodes
263     * \retval bool - is a success
264    */
265   //================================================================================
266
267   bool getBoundaryNodes ( SMESH_subMesh*                        sm,
268                           const TopoDS_Face&                    face,
269                           map< double, const SMDS_MeshNode* > & u2nodes,
270                           set< const SMDS_MeshNode* > &         seamNodes)
271   {
272     u2nodes.clear();
273     seamNodes.clear();
274     if ( !sm || !sm->GetSubMeshDS() )
275       RETURN_BAD_RESULT("Null submesh");
276
277     SMDS_NodeIteratorPtr nIt = sm->GetSubMeshDS()->GetNodes();
278     switch ( sm->GetSubShape().ShapeType() ) {
279
280     case TopAbs_VERTEX: {
281       while ( nIt->more() ) {
282         const SMDS_MeshNode* node = nIt->next();
283         if ( isOldNode( node ) ) continue;
284         u2nodes.insert( make_pair( 0., node ));
285         seamNodes.insert( node );
286         return true;
287       }
288       break;
289     }
290     case TopAbs_EDGE: {
291       
292       // Get submeshes of sub-vertices
293       const map< int, SMESH_subMesh * >& subSM = sm->DependsOn();
294       if ( subSM.size() != 2 )
295         RETURN_BAD_RESULT("there must be 2 submeshes of sub-vertices"
296                           " but we have " << subSM.size());
297       SMESH_subMesh* smV1 = subSM.begin()->second;
298       SMESH_subMesh* smV2 = subSM.rbegin()->second;
299       if ( !smV1->IsMeshComputed() || !smV2->IsMeshComputed() )
300         RETURN_BAD_RESULT("Empty vertex submeshes");
301
302       const SMDS_MeshNode* nV1 = 0;
303       const SMDS_MeshNode* nE = 0;
304
305       // Look for nV1 - a new node on V1
306       nIt = smV1->GetSubMeshDS()->GetNodes();
307       while ( nIt->more() && !nE ) {
308         const SMDS_MeshNode* node = nIt->next();
309         if ( isOldNode( node ) ) continue;
310         nV1 = node;
311
312         // Find nE - a new node connected to nV1 and belonging to edge submesh;
313         SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
314         SMDS_ElemIteratorPtr vElems = nV1->GetInverseElementIterator(SMDSAbs_Face);
315         while ( vElems->more() && !nE ) {
316           const SMDS_MeshElement* elem = vElems->next();
317           int nbNodes = elem->NbNodes();
318           if ( elem->IsQuadratic() )
319             nbNodes /= 2;
320           int iV1 = elem->GetNodeIndex( nV1 );
321           // try next after nV1
322           int iE = SMESH_MesherHelper::WrapIndex( iV1 + 1, nbNodes );
323           if ( smDS->Contains( elem->GetNode( iE ) ))
324             nE = elem->GetNode( iE );
325           if ( !nE ) {
326             // try node before nV1
327             iE = SMESH_MesherHelper::WrapIndex( iV1 - 1, nbNodes );
328             if ( smDS->Contains( elem->GetNode( iE )))
329               nE = elem->GetNode( iE );
330           }
331           if ( nE && elem->IsQuadratic() ) { // find medium node between nV1 and nE
332             if ( Abs( iV1 - iE ) == 1 )
333               nE = elem->GetNode( Min ( iV1, iE ) + nbNodes );
334             else
335               nE = elem->GetNode( elem->NbNodes() - 1 );
336           }
337         }
338       }
339       if ( !nV1 )
340         RETURN_BAD_RESULT("No new node found on V1");
341       if ( !nE )
342         RETURN_BAD_RESULT("new node on edge not found");
343
344       // Get the whole free border of a face
345       list< const SMDS_MeshNode* > bordNodes;
346       list< const SMDS_MeshElement* > bordFaces;
347       if ( !SMESH_MeshEditor::FindFreeBorder (nV1, nE, nV1, bordNodes, bordFaces ))
348         RETURN_BAD_RESULT("free border of a face not found by nodes " <<
349                           nV1->GetID() << " " << nE->GetID() );
350
351       // Insert nodes of the free border to the map until node on V2 encountered
352       SMESHDS_SubMesh* v2smDS = smV2->GetSubMeshDS();
353       list< const SMDS_MeshNode* >::iterator bordIt = bordNodes.begin();
354       bordIt++; // skip nV1
355       for ( ; bordIt != bordNodes.end(); ++bordIt ) {
356         const SMDS_MeshNode* node = *bordIt;
357         if ( v2smDS->Contains( node ))
358           break;
359         if ( node->GetPosition()->GetTypeOfPosition() != SMDS_TOP_EDGE )
360           RETURN_BAD_RESULT("Bad node position type: node " << node->GetID() <<
361                             " pos type " << node->GetPosition()->GetTypeOfPosition());
362         const SMDS_EdgePosition* pos =
363           static_cast<const SMDS_EdgePosition*>(node->GetPosition());
364         u2nodes.insert( make_pair( pos->GetUParameter(), node ));
365         seamNodes.insert( node );
366       }
367       if ( u2nodes.size() != seamNodes.size() )
368         RETURN_BAD_RESULT("Bad node params on edge " << sm->GetId() <<
369                           ", " << u2nodes.size() << " != " << seamNodes.size() );
370       return true;
371     }
372     default:;
373     }
374     RETURN_BAD_RESULT ("Unexpected submesh type");
375
376   } // bool getBoundaryNodes()
377
378   //================================================================================
379   /*!
380    * \brief Check if two consecutive EDGEs are connected in 2D
381    *  \param [in] E1 - a well oriented non-seam EDGE
382    *  \param [in] E2 - a possibly well oriented seam EDGE
383    *  \param [in] F - a FACE
384    *  \return bool - result
385    */
386   //================================================================================
387
388   bool are2dConnected( const TopoDS_Edge & E1,
389                        const TopoDS_Edge & E2,
390                        const TopoDS_Face & F )
391   {
392     double f,l;
393     Handle(Geom2d_Curve) c1 = BRep_Tool::CurveOnSurface( E1, F, f, l );
394     gp_Pnt2d uvLast1 = c1->Value( E1.Orientation() == TopAbs_REVERSED ? f : l );
395
396     Handle(Geom2d_Curve) c2 = BRep_Tool::CurveOnSurface( E2, F, f, l );
397     gp_Pnt2d uvFirst2 = c2->Value( f );
398     gp_Pnt2d uvLast2  = c2->Value( l );
399     double tol2 = 1e-5 * uvLast2.SquareDistance( uvFirst2 );
400
401     return (( uvLast1.SquareDistance( uvFirst2 ) < tol2 ) ||
402             ( uvLast1.SquareDistance( uvLast2 ) < tol2 ));
403   }
404
405   //================================================================================
406   /*!
407    * \brief Compose TSideVector for both FACEs keeping matching order of EDGEs
408    *        and fill src2tgtNodes map
409    */
410   //================================================================================
411
412   TError getWires(const TopoDS_Face&                 tgtFace,
413                   const TopoDS_Face&                 srcFace,
414                   SMESH_Mesh *                       tgtMesh,
415                   SMESH_Mesh *                       srcMesh,
416                   const TAssocTool::TShapeShapeMap&  shape2ShapeMap,
417                   TSideVector&                       srcWires,
418                   TSideVector&                       tgtWires,
419                   TAssocTool::TNodeNodeMap&          src2tgtNodes,
420                   bool&                              is1DComputed)
421   {
422     SMESHDS_Mesh* tgtMeshDS = tgtMesh->GetMeshDS();
423     SMESHDS_Mesh* srcMeshDS = srcMesh->GetMeshDS();
424
425     src2tgtNodes.clear();
426
427     // get ordered src EDGEs
428     TError err;
429     srcWires = StdMeshers_FaceSide::GetFaceWires( srcFace, *srcMesh,/*skipMediumNodes=*/0, err);
430     if ( err && !err->IsOK() )
431       return err;
432
433     // make corresponding sequence of tgt EDGEs
434     tgtWires.resize( srcWires.size() );
435     for ( size_t iW = 0; iW < srcWires.size(); ++iW )
436     {
437       list< TopoDS_Edge > tgtEdges;
438       StdMeshers_FaceSidePtr srcWire = srcWires[iW];
439       TopTools_IndexedMapOfShape edgeMap; // to detect seam edges
440       for ( int iE = 0; iE < srcWire->NbEdges(); ++iE )
441       {
442         TopoDS_Edge     srcE = srcWire->Edge( iE );
443         TopoDS_Edge     tgtE = TopoDS::Edge( shape2ShapeMap( srcE, /*isSrc=*/true));
444         TopoDS_Shape srcEbis = shape2ShapeMap( tgtE, /*isSrc=*/false );
445         if ( srcE.Orientation() != srcEbis.Orientation() )
446           tgtE.Reverse();
447         // reverse a seam edge encountered for the second time
448         const int index = edgeMap.Add( tgtE );
449         if ( index < edgeMap.Extent() ) // E is a seam
450         {
451           // check which of edges to reverse, E or one already being in tgtEdges
452           if ( are2dConnected( tgtEdges.back(), tgtE, tgtFace ))
453           {
454             list< TopoDS_Edge >::iterator eIt = tgtEdges.begin();
455             std::advance( eIt, index-1 );
456             eIt->Reverse();
457           }
458           else
459           {
460             tgtE.Reverse();
461           }
462         }
463         if ( srcWire->NbEdges() == 1 && tgtMesh == srcMesh ) // circle
464         {
465           // try to verify ori by propagation
466           pair<int,TopoDS_Edge> nE =
467             StdMeshers_ProjectionUtils::GetPropagationEdge( srcMesh, tgtE, srcE );
468           if ( !nE.second.IsNull() )
469             tgtE = nE.second;
470         }
471         tgtEdges.push_back( tgtE );
472
473
474         // Fill map of src to tgt nodes with nodes on edges
475
476         if ( srcMesh->GetSubMesh( srcE )->IsEmpty() ||
477              tgtMesh->GetSubMesh( tgtE )->IsEmpty() )
478         {
479           // add nodes on VERTEXes for a case of not meshes EDGEs
480           const TopoDS_Shape&  srcV = SMESH_MesherHelper::IthVertex( 0, srcE );
481           const TopoDS_Shape&  tgtV = shape2ShapeMap( srcV, /*isSrc=*/true );
482           const SMDS_MeshNode* srcN = SMESH_Algo::VertexNode( TopoDS::Vertex( srcV ), srcMeshDS );
483           const SMDS_MeshNode* tgtN = SMESH_Algo::VertexNode( TopoDS::Vertex( tgtV ), tgtMeshDS );
484           if ( srcN && tgtN )
485             src2tgtNodes.insert( make_pair( srcN, tgtN ));
486         }
487         else
488         {
489           map< double, const SMDS_MeshNode* > srcNodes, tgtNodes;
490           if (( ! SMESH_Algo::GetSortedNodesOnEdge( srcMeshDS, TopoDS::Edge( srcE ),
491                                                     /*ignoreMediumNodes = */true,
492                                                     srcNodes ))
493               ||
494               ( ! SMESH_Algo::GetSortedNodesOnEdge( tgtMeshDS, TopoDS::Edge( tgtE ),
495                                                     /*ignoreMediumNodes = */true,
496                                                     tgtNodes ))
497               )
498             return SMESH_ComputeError::New( COMPERR_BAD_INPUT_MESH,
499                                             "Invalid node parameters on edges");
500
501           if (( srcNodes.size() != tgtNodes.size() ) && tgtNodes.size() > 0 )
502             return SMESH_ComputeError::New( COMPERR_BAD_INPUT_MESH,
503                                             "Different number of nodes on edges");
504           if ( !tgtNodes.empty() )
505           {
506             map< double, const SMDS_MeshNode* >::iterator u_tn = tgtNodes.begin();
507             map< double, const SMDS_MeshNode* >::iterator u_sn = srcNodes.begin();
508             for ( ; u_tn != tgtNodes.end(); ++u_tn, ++u_sn)
509               src2tgtNodes.insert( make_pair( u_sn->second, u_tn->second ));
510
511             is1DComputed = true;
512           }
513         }
514       } // loop on EDGEs of a WIRE
515
516       tgtWires[ iW ].reset( new StdMeshers_FaceSide( tgtFace, tgtEdges, tgtMesh,
517                                                      /*theIsForward = */ true,
518                                                      /*theIgnoreMediumNodes = */false));
519     } // loop on WIREs
520
521     return TError();
522   }
523
524   //================================================================================
525   /*!
526    * \brief Preform projection in case if tgtFace.IsPartner( srcFace ) and in case
527    * if projection by 3D transformation is possible
528    */
529   //================================================================================
530
531   bool projectPartner(const TopoDS_Face&                 tgtFace,
532                       const TopoDS_Face&                 srcFace,
533                       const TSideVector&                 tgtWires,
534                       const TSideVector&                 srcWires,
535                       const TAssocTool::TShapeShapeMap&  shape2ShapeMap,
536                       TAssocTool::TNodeNodeMap&          src2tgtNodes,
537                       const bool                         is1DComputed)
538   {
539     SMESH_Mesh *    tgtMesh = tgtWires[0]->GetMesh();
540     SMESH_Mesh *    srcMesh = srcWires[0]->GetMesh();
541     SMESHDS_Mesh* tgtMeshDS = tgtMesh->GetMeshDS();
542     SMESHDS_Mesh* srcMeshDS = srcMesh->GetMeshDS();
543     SMESH_MesherHelper helper( *tgtMesh );
544
545     const double tol = 1.e-7 * srcMeshDS->getMaxDim();
546
547     // transformation to get location of target nodes from source ones
548     StdMeshers_ProjectionUtils::TrsfFinder3D trsf;
549     if ( tgtFace.IsPartner( srcFace ))
550     {
551       gp_Trsf srcTrsf = srcFace.Location();
552       gp_Trsf tgtTrsf = tgtFace.Location();
553       trsf.Set( srcTrsf.Inverted() * tgtTrsf );
554     }
555     else
556     {
557       // Try to find the 3D transformation
558
559       const int totNbSeg = 50;
560       vector< gp_XYZ > srcPnts, tgtPnts;
561       srcPnts.reserve( totNbSeg );
562       tgtPnts.reserve( totNbSeg );
563       for ( size_t iW = 0; iW < srcWires.size(); ++iW )
564       {
565         const double minSegLen = srcWires[iW]->Length() / totNbSeg;
566         for ( int iE = 0; iE < srcWires[iW]->NbEdges(); ++iE )
567         {
568           int nbSeg    = Max( 1, int( srcWires[iW]->EdgeLength( iE ) / minSegLen ));
569           double srcU  = srcWires[iW]->FirstParameter( iE );
570           double tgtU  = tgtWires[iW]->FirstParameter( iE );
571           double srcDu = ( srcWires[iW]->LastParameter( iE )- srcU ) / nbSeg;
572           double tgtDu = ( tgtWires[iW]->LastParameter( iE )- tgtU ) / nbSeg;
573           for ( size_t i = 0; i < nbSeg; ++i  )
574           {
575             srcPnts.push_back( srcWires[iW]->Value3d( srcU ).XYZ() );
576             tgtPnts.push_back( tgtWires[iW]->Value3d( tgtU ).XYZ() );
577             srcU += srcDu;
578             tgtU += tgtDu;
579           }
580         }
581       }
582       if ( !trsf.Solve( srcPnts, tgtPnts ))
583         return false;
584
585       // check trsf
586
587       bool trsfIsOK = true;
588       const int nbTestPnt = 20;
589       const size_t  iStep = Max( 1, int( srcPnts.size() / nbTestPnt ));
590       // check boundary
591       for ( size_t i = 0; ( i < srcPnts.size() && trsfIsOK ); i += iStep )
592       {
593         gp_Pnt trsfTgt = trsf.Transform( srcPnts[i] );
594         trsfIsOK = ( trsfTgt.SquareDistance( tgtPnts[i] ) < tol*tol );
595       }
596       // check an in-FACE point
597       if ( trsfIsOK )
598       {
599         BRepAdaptor_Surface srcSurf( srcFace );
600         gp_Pnt srcP =
601           srcSurf.Value( 0.5 * ( srcSurf.FirstUParameter() + srcSurf.LastUParameter() ),
602                          0.5 * ( srcSurf.FirstVParameter() + srcSurf.LastVParameter() ));
603         gp_Pnt tgtTrsfP = trsf.Transform( srcP );
604         TopLoc_Location loc;
605         GeomAPI_ProjectPointOnSurf& proj = helper.GetProjector( tgtFace, loc, 0.1*tol );
606         if ( !loc.IsIdentity() )
607           tgtTrsfP.Transform( loc.Transformation().Inverted() );
608         proj.Perform( tgtTrsfP );
609         trsfIsOK = ( proj.IsDone() &&
610                      proj.NbPoints() > 0 &&
611                      proj.LowerDistance() < tol );
612       }
613       if ( !trsfIsOK )
614         return false;
615     }
616
617     // Make new faces
618
619     // prepare the helper to adding quadratic elements if necessary
620     helper.SetSubShape( tgtFace );
621     helper.IsQuadraticSubMesh( tgtFace );
622
623     SMESHDS_SubMesh* srcSubDS = srcMeshDS->MeshElements( srcFace );
624     if ( !is1DComputed && srcSubDS->NbElements() )
625       helper.SetIsQuadratic( srcSubDS->GetElements()->next()->IsQuadratic() );
626
627     SMESH_MesherHelper srcHelper( *srcMesh );
628     srcHelper.SetSubShape( srcFace );
629
630     const SMDS_MeshNode* nullNode = 0;
631     TAssocTool::TNodeNodeMap::iterator srcN_tgtN;
632
633     // indices of nodes to create properly oriented faces
634     bool isReverse = ( !trsf.IsIdentity() );
635     int tri1 = 1, tri2 = 2, quad1 = 1, quad3 = 3;
636     if ( isReverse )
637       std::swap( tri1, tri2 ), std::swap( quad1, quad3 );
638
639     SMDS_ElemIteratorPtr elemIt = srcSubDS->GetElements();
640     vector< const SMDS_MeshNode* > tgtNodes;
641     while ( elemIt->more() ) // loop on all mesh faces on srcFace
642     {
643       const SMDS_MeshElement* elem = elemIt->next();
644       const int nbN = elem->NbCornerNodes(); 
645       tgtNodes.resize( nbN );
646       helper.SetElementsOnShape( false );
647       for ( int i = 0; i < nbN; ++i ) // loop on nodes of the source element
648       {
649         const SMDS_MeshNode* srcNode = elem->GetNode(i);
650         srcN_tgtN = src2tgtNodes.insert( make_pair( srcNode, nullNode )).first;
651         if ( srcN_tgtN->second == nullNode )
652         {
653           // create a new node
654           gp_Pnt tgtP = trsf.Transform( SMESH_TNodeXYZ( srcNode ));
655           SMDS_MeshNode* n = helper.AddNode( tgtP.X(), tgtP.Y(), tgtP.Z() );
656           srcN_tgtN->second = n;
657           switch ( srcNode->GetPosition()->GetTypeOfPosition() )
658           {
659           case SMDS_TOP_FACE:
660           {
661             gp_Pnt2d srcUV = srcHelper.GetNodeUV( srcFace, srcNode );
662             tgtMeshDS->SetNodeOnFace( n, helper.GetSubShapeID(), srcUV.X(), srcUV.Y() );
663             break;
664           }
665           case SMDS_TOP_EDGE:
666           {
667             const TopoDS_Shape & srcE = srcMeshDS->IndexToShape( srcNode->getshapeId() );
668             const TopoDS_Shape & tgtE = shape2ShapeMap( srcE, /*isSrc=*/true );
669             double srcU = srcHelper.GetNodeU( TopoDS::Edge( srcE ), srcNode );
670             tgtMeshDS->SetNodeOnEdge( n, TopoDS::Edge( tgtE ), srcU );
671             break;
672           }
673           case SMDS_TOP_VERTEX:
674           {
675             const TopoDS_Shape & srcV = srcMeshDS->IndexToShape( srcNode->getshapeId() );
676             const TopoDS_Shape & tgtV = shape2ShapeMap( srcV, /*isSrc=*/true );
677             tgtMeshDS->SetNodeOnVertex( n, TopoDS::Vertex( tgtV ));
678             break;
679           }
680           default:;
681           }
682         }
683         tgtNodes[i] = srcN_tgtN->second;
684       }
685       // create a new face
686       helper.SetElementsOnShape( true );
687       switch ( nbN )
688       {
689       case 3: helper.AddFace(tgtNodes[0], tgtNodes[tri1], tgtNodes[tri2]); break;
690       case 4: helper.AddFace(tgtNodes[0], tgtNodes[quad1], tgtNodes[2], tgtNodes[quad3]); break;
691       default:
692         if ( isReverse ) std::reverse( tgtNodes.begin(), tgtNodes.end() );
693         helper.AddPolygonalFace( tgtNodes );
694       }
695     }
696
697     // check node positions
698
699     if ( !tgtFace.IsPartner( srcFace ) )
700     {
701       int nbOkPos = 0;
702       const double tol2d = 1e-12;
703       srcN_tgtN = src2tgtNodes.begin();
704       for ( ; srcN_tgtN != src2tgtNodes.end(); ++srcN_tgtN )
705       {
706         const SMDS_MeshNode* n = srcN_tgtN->second;
707         switch ( n->GetPosition()->GetTypeOfPosition() )
708         {
709         case SMDS_TOP_FACE:
710         {
711           gp_XY uv = helper.GetNodeUV( tgtFace, n ), uvBis = uv;
712           if (( helper.CheckNodeUV( tgtFace, n, uv, tol )) &&
713               (( uv - uvBis ).SquareModulus() < tol2d )    &&
714               ( ++nbOkPos > 10 ))
715             return true;
716           else
717             nbOkPos = 0;
718           break;
719         }
720         case SMDS_TOP_EDGE:
721         {
722           const TopoDS_Edge & tgtE = TopoDS::Edge( tgtMeshDS->IndexToShape( n->getshapeId() ));
723           double u = helper.GetNodeU( tgtE, n ), uBis = u;
724           if (( !helper.CheckNodeU( tgtE, n, u, tol )) ||
725               (( u - uBis ) < tol2d ))
726             nbOkPos = 0;
727           break;
728         }
729         default:;
730         }
731       }
732     }
733
734     return true;
735
736   } //   bool projectPartner()
737
738   //================================================================================
739   /*!
740    * \brief Preform projection in case if the faces are similar in 2D space
741    */
742   //================================================================================
743
744   bool projectBy2DSimilarity(const TopoDS_Face&                 tgtFace,
745                              const TopoDS_Face&                 srcFace,
746                              const TSideVector&                 tgtWires,
747                              const TSideVector&                 srcWires,
748                              const TAssocTool::TShapeShapeMap&  shape2ShapeMap,
749                              TAssocTool::TNodeNodeMap&          src2tgtNodes,
750                              const bool                         is1DComputed)
751   {
752     SMESH_Mesh * tgtMesh = tgtWires[0]->GetMesh();
753     SMESH_Mesh * srcMesh = srcWires[0]->GetMesh();
754
755     // WARNING: we can have problems if the FACE is symmetrical in 2D,
756     // then the projection can be mirrored relating to what is expected
757
758     // 1) Find 2D transformation
759
760     StdMeshers_ProjectionUtils::TrsfFinder2D trsf;
761     {
762       // get 2 pairs of corresponding UVs
763       gp_Pnt2d srcP0 = srcWires[0]->Value2d(0.0);
764       gp_Pnt2d srcP1 = srcWires[0]->Value2d(0.333);
765       gp_Pnt2d tgtP0 = tgtWires[0]->Value2d(0.0);
766       gp_Pnt2d tgtP1 = tgtWires[0]->Value2d(0.333);
767
768       // make transformation
769       gp_Trsf2d fromTgtCS, toSrcCS; // from/to global CS
770       gp_Ax2d srcCS( srcP0, gp_Vec2d( srcP0, srcP1 ));
771       gp_Ax2d tgtCS( tgtP0, gp_Vec2d( tgtP0, tgtP1 ));
772       toSrcCS  .SetTransformation( srcCS );
773       fromTgtCS.SetTransformation( tgtCS );
774       fromTgtCS.Invert();
775       trsf.Set( fromTgtCS * toSrcCS );
776
777       // check transformation
778       bool trsfIsOK = true;
779       const double tol = 1e-5 * gp_Vec2d( srcP0, srcP1 ).Magnitude();
780       for ( double u = 0.12; ( u < 1. && trsfIsOK ); u += 0.1 )
781       {
782         gp_Pnt2d srcUV  = srcWires[0]->Value2d( u );
783         gp_Pnt2d tgtUV  = tgtWires[0]->Value2d( u );
784         gp_Pnt2d tgtUV2 = trsf.Transform( srcUV );
785         trsfIsOK = ( tgtUV.Distance( tgtUV2 ) < tol );
786       }
787
788       // Find trsf using a least-square approximation
789       if ( !trsfIsOK )
790       {
791         // find trsf
792         const int totNbSeg = 50;
793         vector< gp_XY > srcPnts, tgtPnts;
794         srcPnts.resize( totNbSeg );
795         tgtPnts.resize( totNbSeg );
796         for ( size_t iW = 0; iW < srcWires.size(); ++iW )
797         {
798           const double minSegLen = srcWires[iW]->Length() / totNbSeg;
799           for ( int iE = 0; iE < srcWires[iW]->NbEdges(); ++iE )
800           {
801             int nbSeg    = Max( 1, int( srcWires[iW]->EdgeLength( iE ) / minSegLen ));
802             double srcU  = srcWires[iW]->FirstParameter( iE );
803             double tgtU  = tgtWires[iW]->FirstParameter( iE );
804             double srcDu = ( srcWires[iW]->LastParameter( iE )- srcU ) / nbSeg;
805             double tgtDu = ( tgtWires[iW]->LastParameter( iE )- tgtU ) / nbSeg;
806             for ( size_t i = 0; i < nbSeg; ++i, srcU += srcDu, tgtU += tgtDu  )
807             {
808               srcPnts.push_back( srcWires[iW]->Value2d( srcU ).XY() );
809               tgtPnts.push_back( tgtWires[iW]->Value2d( tgtU ).XY() );
810             }
811           }
812         }
813         if ( !trsf.Solve( srcPnts, tgtPnts ))
814           return false;
815
816         // check trsf
817
818         trsfIsOK = true;
819         const int nbTestPnt = 10;
820         const size_t  iStep = Max( 1, int( srcPnts.size() / nbTestPnt ));
821         for ( size_t i = 0; ( i < srcPnts.size() && trsfIsOK ); i += iStep )
822         {
823           gp_Pnt2d trsfTgt = trsf.Transform( srcPnts[i] );
824           trsfIsOK = ( trsfTgt.Distance( tgtPnts[i] ) < tol );
825         }
826         if ( !trsfIsOK )
827           return false;
828       }
829     } // "Find transformation" block
830
831     // 2) Projection
832
833     SMESHDS_SubMesh* srcSubDS = srcMesh->GetMeshDS()->MeshElements( srcFace );
834
835     SMESH_MesherHelper helper( *tgtMesh );
836     helper.SetSubShape( tgtFace );
837     if ( is1DComputed )
838       helper.IsQuadraticSubMesh( tgtFace );
839     else
840       helper.SetIsQuadratic( srcSubDS->GetElements()->next()->IsQuadratic() );
841     helper.SetElementsOnShape( true );
842     Handle(Geom_Surface) tgtSurface = BRep_Tool::Surface( tgtFace );
843     SMESHDS_Mesh* tgtMeshDS = tgtMesh->GetMeshDS();
844
845     SMESH_MesherHelper srcHelper( *srcMesh );
846     srcHelper.SetSubShape( srcFace );
847
848     const SMDS_MeshNode* nullNode = 0;
849     TAssocTool::TNodeNodeMap::iterator srcN_tgtN;
850
851     SMDS_ElemIteratorPtr elemIt = srcSubDS->GetElements();
852     vector< const SMDS_MeshNode* > tgtNodes;
853     bool uvOK;
854     while ( elemIt->more() ) // loop on all mesh faces on srcFace
855     {
856       const SMDS_MeshElement* elem = elemIt->next();
857       const int nbN = elem->NbCornerNodes(); 
858       tgtNodes.resize( nbN );
859       for ( int i = 0; i < nbN; ++i ) // loop on nodes of the source element
860       {
861         const SMDS_MeshNode* srcNode = elem->GetNode(i);
862         srcN_tgtN = src2tgtNodes.insert( make_pair( srcNode, nullNode )).first;
863         if ( srcN_tgtN->second == nullNode )
864         {
865           // create a new node
866           gp_Pnt2d srcUV = srcHelper.GetNodeUV( srcFace, srcNode,
867                                                 elem->GetNode( helper.WrapIndex(i+1,nbN)), &uvOK);
868           gp_Pnt2d   tgtUV = trsf.Transform( srcUV );
869           gp_Pnt      tgtP = tgtSurface->Value( tgtUV.X(), tgtUV.Y() );
870           SMDS_MeshNode* n = tgtMeshDS->AddNode( tgtP.X(), tgtP.Y(), tgtP.Z() );
871           switch ( srcNode->GetPosition()->GetTypeOfPosition() )
872           {
873           case SMDS_TOP_FACE: {
874             tgtMeshDS->SetNodeOnFace( n, helper.GetSubShapeID(), tgtUV.X(), tgtUV.Y() );
875             break;
876           }
877           case SMDS_TOP_EDGE: {
878             TopoDS_Shape srcEdge = srcHelper.GetSubShapeByNode( srcNode, srcHelper.GetMeshDS() );
879             TopoDS_Edge  tgtEdge = TopoDS::Edge( shape2ShapeMap( srcEdge, /*isSrc=*/true ));
880             tgtMeshDS->SetNodeOnEdge( n, TopoDS::Edge( tgtEdge ));
881             double U = srcHelper.GetNodeU( TopoDS::Edge( srcEdge ), srcNode );
882             helper.CheckNodeU( tgtEdge, n, U, Precision::PConfusion());
883             n->SetPosition(SMDS_PositionPtr(new SMDS_EdgePosition( U )));
884             break;
885           }
886           case SMDS_TOP_VERTEX: {
887             TopoDS_Shape srcV = srcHelper.GetSubShapeByNode( srcNode, srcHelper.GetMeshDS() );
888             TopoDS_Shape tgtV = shape2ShapeMap( srcV, /*isSrc=*/true );
889             tgtMeshDS->SetNodeOnVertex( n, TopoDS::Vertex( tgtV ));
890             break;
891           }
892           }
893           srcN_tgtN->second = n;
894         }
895         tgtNodes[i] = srcN_tgtN->second;
896       }
897       // create a new face (with reversed orientation)
898       switch ( nbN )
899       {
900       case 3: helper.AddFace(tgtNodes[0], tgtNodes[2], tgtNodes[1]); break;
901       case 4: helper.AddFace(tgtNodes[0], tgtNodes[3], tgtNodes[2], tgtNodes[1]); break;
902       }
903     }
904     return true;
905
906   } // bool projectBy2DSimilarity(...)
907
908   //================================================================================
909   /*!
910    * \brief Fix bad faces by smoothing
911    */
912   //================================================================================
913
914   void fixDistortedFaces( SMESH_MesherHelper& helper,
915                           TSideVector&        )
916   {
917     // Detect bad faces
918
919     bool haveBadFaces = false;
920
921     const TopoDS_Face&  F = TopoDS::Face( helper.GetSubShape() );
922     SMESHDS_SubMesh* smDS = helper.GetMeshDS()->MeshElements( F );
923     if ( !smDS || smDS->NbElements() == 0 ) return;
924
925     SMDS_ElemIteratorPtr faceIt = smDS->GetElements();
926     double prevArea2D = 0;
927     vector< const SMDS_MeshNode* > nodes;
928     vector< gp_XY >                uv;
929     while ( faceIt->more() && !haveBadFaces )
930     {
931       const SMDS_MeshElement* face = faceIt->next();
932
933       // get nodes
934       nodes.resize( face->NbCornerNodes() );
935       SMDS_MeshElement::iterator n = face->begin_nodes();
936       for ( size_t i = 0; i < nodes.size(); ++n, ++i )
937         nodes[ i ] = *n;
938
939       // avoid elems on degenarate shapes as UV on them can be wrong
940       if ( helper.HasDegeneratedEdges() )
941       {
942         bool isOnDegen = false;
943         for ( size_t i = 0; ( i < nodes.size() && !isOnDegen ); ++i )
944           isOnDegen = helper.IsDegenShape( nodes[ i ]->getshapeId() );
945         if ( isOnDegen )
946           continue;
947       }
948       // prepare to getting UVs
949       const SMDS_MeshNode* inFaceNode = 0;
950       if ( helper.HasSeam() )
951         for ( size_t i = 0; ( i < nodes.size() && !inFaceNode ); ++i )
952           if ( !helper.IsSeamShape( nodes[ i ]->getshapeId() ))
953             inFaceNode = nodes[ i ];
954
955       // get UVs
956       uv.resize( nodes.size() );
957       for ( size_t i = 0; i < nodes.size(); ++i )
958         uv[ i ] = helper.GetNodeUV( F, nodes[ i ], inFaceNode );
959
960       // compare orientation of triangles
961       for ( int iT = 0, nbT = nodes.size()-2; iT < nbT; ++iT )
962       {
963         gp_XY v1 = uv[ iT+1 ] - uv[ 0 ];
964         gp_XY v2 = uv[ iT+2 ] - uv[ 0 ];
965         double area2D = v2 ^ v1;
966         if (( haveBadFaces = ( area2D * prevArea2D < 0 )))
967           break;
968         prevArea2D = area2D;
969       }
970     }
971
972     // Fix faces
973
974     if ( haveBadFaces )
975     {
976       SMESH_MeshEditor editor( helper.GetMesh() );
977
978       TIDSortedElemSet faces;
979       for ( faceIt = smDS->GetElements(); faceIt->more(); )
980         faces.insert( faces.end(), faceIt->next() );
981
982       // choose smoothing algo
983       //SMESH_MeshEditor:: SmoothMethod algo = SMESH_MeshEditor::CENTROIDAL;
984       bool isConcaveBoundary = false;
985       TError err;
986       TSideVector tgtWires =
987         StdMeshers_FaceSide::GetFaceWires( F, *helper.GetMesh(),/*skipMediumNodes=*/0, err);
988       for ( size_t iW = 0; iW < tgtWires.size() && !isConcaveBoundary; ++iW )
989       {
990         TopoDS_Edge prevEdge = tgtWires[iW]->Edge( tgtWires[iW]->NbEdges() - 1 );
991         for ( int iE = 0; iE < tgtWires[iW]->NbEdges() && !isConcaveBoundary; ++iE )
992         {
993           double angle = helper.GetAngle( prevEdge, tgtWires[iW]->Edge( iE ),
994                                           F,        tgtWires[iW]->FirstVertex( iE ));
995           isConcaveBoundary = ( angle < -5. * M_PI / 180. );
996
997           prevEdge = tgtWires[iW]->Edge( iE );
998         }
999       }
1000       SMESH_MeshEditor:: SmoothMethod algo =
1001         isConcaveBoundary ? SMESH_MeshEditor::CENTROIDAL : SMESH_MeshEditor::LAPLACIAN;
1002
1003       // smooth in 2D or 3D?
1004       TopLoc_Location loc;
1005       Handle(Geom_Surface) surface = BRep_Tool::Surface( F, loc );
1006       bool isPlanar = GeomLib_IsPlanarSurface( surface ).IsPlanar();
1007
1008       // smoothing
1009       set<const SMDS_MeshNode*> fixedNodes;
1010       editor.Smooth( faces, fixedNodes, algo, /*nbIterations=*/ 10,
1011                      /*theTgtAspectRatio=*/1.0, /*the2D=*/!isPlanar);
1012     }
1013   }
1014
1015 } // namespace
1016
1017
1018 //=======================================================================
1019 //function : Compute
1020 //purpose  :
1021 //=======================================================================
1022
1023 bool StdMeshers_Projection_2D::Compute(SMESH_Mesh& theMesh, const TopoDS_Shape& theShape)
1024 {
1025   _src2tgtNodes.clear();
1026
1027   MESSAGE("Projection_2D Compute");
1028   if ( !_sourceHypo )
1029     return false;
1030
1031   SMESH_Mesh * srcMesh = _sourceHypo->GetSourceMesh();
1032   SMESH_Mesh * tgtMesh = & theMesh;
1033   if ( !srcMesh )
1034     srcMesh = tgtMesh;
1035
1036   SMESHDS_Mesh * meshDS = theMesh.GetMeshDS();
1037
1038   // ---------------------------
1039   // Make sub-shapes association
1040   // ---------------------------
1041
1042   TopoDS_Face   tgtFace = TopoDS::Face( theShape.Oriented(TopAbs_FORWARD));
1043   TopoDS_Shape srcShape = _sourceHypo->GetSourceFace().Oriented(TopAbs_FORWARD);
1044
1045   TAssocTool::TShapeShapeMap shape2ShapeMap;
1046   TAssocTool::InitVertexAssociation( _sourceHypo, shape2ShapeMap );
1047   if ( !TAssocTool::FindSubShapeAssociation( tgtFace, tgtMesh, srcShape, srcMesh,
1048                                              shape2ShapeMap)  ||
1049        !shape2ShapeMap.IsBound( tgtFace ))
1050   {
1051     if ( srcShape.ShapeType() == TopAbs_FACE )
1052     {
1053       int nbE1 = SMESH_MesherHelper::Count( tgtFace, TopAbs_EDGE, /*ignoreSame=*/true );
1054       int nbE2 = SMESH_MesherHelper::Count( srcShape, TopAbs_EDGE, /*ignoreSame=*/true );
1055       if ( nbE1 != nbE2 )
1056         return error(COMPERR_BAD_SHAPE,
1057                      SMESH_Comment("Different number of edges in source and target faces: ")
1058                      << nbE2 << " and " << nbE1 );
1059     }
1060     return error(COMPERR_BAD_SHAPE,"Topology of source and target faces seems different" );
1061   }
1062   TopoDS_Face srcFace = TopoDS::Face( shape2ShapeMap( tgtFace ).Oriented(TopAbs_FORWARD));
1063
1064   // ----------------------------------------------
1065   // Assure that mesh on a source Face is computed
1066   // ----------------------------------------------
1067
1068   SMESH_subMesh* srcSubMesh = srcMesh->GetSubMesh( srcFace );
1069   SMESH_subMesh* tgtSubMesh = tgtMesh->GetSubMesh( tgtFace );
1070
1071   string srcMeshError;
1072   if ( tgtMesh == srcMesh ) {
1073     if ( !TAssocTool::MakeComputed( srcSubMesh ))
1074       srcMeshError = TAssocTool::SourceNotComputedError( srcSubMesh, this );
1075   }
1076   else {
1077     if ( !srcSubMesh->IsMeshComputed() )
1078       srcMeshError = TAssocTool::SourceNotComputedError();
1079   }
1080   if ( !srcMeshError.empty() )
1081     return error(COMPERR_BAD_INPUT_MESH, srcMeshError );
1082
1083   // ===========
1084   // Projection
1085   // ===========
1086
1087   // get ordered src and tgt EDGEs
1088   TSideVector srcWires, tgtWires;
1089   bool is1DComputed = false; // if any tgt EDGE is meshed
1090   TError err = getWires( tgtFace, srcFace, tgtMesh, srcMesh,
1091                          shape2ShapeMap, srcWires, tgtWires, _src2tgtNodes, is1DComputed );
1092   if ( err && !err->IsOK() )
1093     return error( err );
1094
1095   bool done = false;
1096
1097  if ( !done )
1098   {
1099     // try to project from the same face with different location
1100     done = projectPartner( tgtFace, srcFace, tgtWires, srcWires,
1101                            shape2ShapeMap, _src2tgtNodes, is1DComputed );
1102   }
1103   if ( !done )
1104   {
1105     // projection in case if the faces are similar in 2D space
1106     done = projectBy2DSimilarity( tgtFace, srcFace, tgtWires, srcWires,
1107                                   shape2ShapeMap, _src2tgtNodes, is1DComputed);
1108   }
1109
1110   SMESH_MesherHelper helper( theMesh );
1111   helper.SetSubShape( tgtFace );
1112
1113   if ( !done )
1114   {
1115     _src2tgtNodes.clear();
1116     // --------------------
1117     // Prepare to mapping 
1118     // --------------------
1119
1120     // Check if node projection to a face is needed
1121     Bnd_B2d uvBox;
1122     SMDS_ElemIteratorPtr faceIt = srcSubMesh->GetSubMeshDS()->GetElements();
1123     int nbFaceNodes = 0;
1124     for ( ; nbFaceNodes < 3 && faceIt->more();  ) {
1125       const SMDS_MeshElement* face = faceIt->next();
1126       SMDS_ElemIteratorPtr nodeIt = face->nodesIterator();
1127       while ( nodeIt->more() ) {
1128         const SMDS_MeshNode* node = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
1129         if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE ) {
1130           nbFaceNodes++;
1131           uvBox.Add( helper.GetNodeUV( srcFace, node ));
1132         }
1133       }
1134     }
1135     const bool toProjectNodes =
1136       ( nbFaceNodes > 0 && ( uvBox.IsVoid() || uvBox.SquareExtent() < DBL_MIN ));
1137
1138     // Find the corresponding source and target vertex
1139     // and <theReverse> flag needed to call mapper.Apply()
1140
1141     TopoDS_Vertex srcV1, tgtV1;
1142     bool reverse = false;
1143
1144     if ( _sourceHypo->HasVertexAssociation() ) {
1145       srcV1 = _sourceHypo->GetSourceVertex(1);
1146       tgtV1 = _sourceHypo->GetTargetVertex(1);
1147     } else {
1148       srcV1 = TopoDS::Vertex( TopExp_Explorer( srcFace, TopAbs_VERTEX ).Current() );
1149       tgtV1 = TopoDS::Vertex( shape2ShapeMap( srcV1, /*isSrc=*/true ));
1150     }
1151     list< TopoDS_Edge > tgtEdges, srcEdges;
1152     list< int > nbEdgesInWires;
1153     SMESH_Block::GetOrderedEdges( tgtFace, tgtEdges, nbEdgesInWires, tgtV1 );
1154     SMESH_Block::GetOrderedEdges( srcFace, srcEdges, nbEdgesInWires, srcV1 );
1155
1156     if ( nbEdgesInWires.front() > 1 ) // possible to find out orientation
1157     {
1158       TopoDS_Edge srcE1 = srcEdges.front(), tgtE1 = tgtEdges.front();
1159       TopoDS_Shape srcE1bis = shape2ShapeMap( tgtE1 );
1160       reverse = ( ! srcE1.IsSame( srcE1bis ));
1161       if ( reverse &&
1162            _sourceHypo->HasVertexAssociation() &&
1163            nbEdgesInWires.front() > 2 &&
1164            helper.IsRealSeam( tgtEdges.front() ))
1165       {
1166         // projection to a face with seam EDGE; pb is that GetOrderedEdges()
1167         // always puts a seam EDGE first (if possible) and as a result
1168         // we can't use only theReverse flag to correctly associate source
1169         // and target faces in the mapper. Thus we select srcV1 so that
1170         // GetOrderedEdges() to return EDGEs in a needed order
1171         list< TopoDS_Edge >::iterator edge = srcEdges.begin();
1172         for ( ; edge != srcEdges.end(); ++edge ) {
1173           if ( srcE1bis.IsSame( *edge )) {
1174             srcV1 = helper.IthVertex( 0, *edge );
1175             break;
1176           }
1177         }
1178       }
1179     }
1180     else if ( nbEdgesInWires.front() == 1 )
1181     {
1182       // TODO::Compare orientation of curves in a sole edge
1183       //RETURN_BAD_RESULT("Not implemented case");
1184     }
1185     else
1186     {
1187       RETURN_BAD_RESULT("Bad result from SMESH_Block::GetOrderedEdges()");
1188     }
1189
1190     // Load pattern from the source face
1191     SMESH_Pattern mapper;
1192     mapper.Load( srcMesh, srcFace, toProjectNodes, srcV1 );
1193     if ( mapper.GetErrorCode() != SMESH_Pattern::ERR_OK )
1194       return error(COMPERR_BAD_INPUT_MESH,"Can't load mesh pattern from the source face");
1195
1196     // --------------------
1197     // Perform 2D mapping
1198     // --------------------
1199
1200     // Compute mesh on a target face
1201
1202     mapper.Apply( tgtFace, tgtV1, reverse );
1203     if ( mapper.GetErrorCode() != SMESH_Pattern::ERR_OK )
1204       return error("Can't apply source mesh pattern to the face");
1205
1206     // Create the mesh
1207
1208     const bool toCreatePolygons = false, toCreatePolyedrs = false;
1209     mapper.MakeMesh( tgtMesh, toCreatePolygons, toCreatePolyedrs );
1210     if ( mapper.GetErrorCode() != SMESH_Pattern::ERR_OK )
1211       return error("Can't make mesh by source mesh pattern");
1212
1213     // it will remove mesh built by pattern mapper on edges and vertices
1214     // in failure case
1215     MeshCleaner cleaner( tgtSubMesh );
1216
1217     // -------------------------------------------------------------------------
1218     // mapper doesn't take care of nodes already existing on edges and vertices,
1219     // so we must merge nodes created by it with existing ones
1220     // -------------------------------------------------------------------------
1221
1222     SMESH_MeshEditor::TListOfListOfNodes groupsOfNodes;
1223
1224     // Make groups of nodes to merge
1225
1226     // loop on EDGE and VERTEX sub-meshes of a target FACE
1227     SMESH_subMeshIteratorPtr smIt = tgtSubMesh->getDependsOnIterator(/*includeSelf=*/false,
1228                                                                      /*complexShapeFirst=*/false);
1229     while ( smIt->more() )
1230     {
1231       SMESH_subMesh*     sm = smIt->next();
1232       SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
1233       if ( !smDS || smDS->NbNodes() == 0 )
1234         continue;
1235       //if ( !is1DComputed && sm->GetSubShape().ShapeType() == TopAbs_EDGE )
1236       //  break;
1237
1238       if ( helper.IsDegenShape( sm->GetId() ) ) // to merge all nodes on degenerated
1239       {
1240         if ( sm->GetSubShape().ShapeType() == TopAbs_EDGE )
1241         {
1242           groupsOfNodes.push_back( list< const SMDS_MeshNode* >() );
1243           SMESH_subMeshIteratorPtr smDegenIt
1244             = sm->getDependsOnIterator(/*includeSelf=*/true,/*complexShapeFirst=*/false);
1245           while ( smDegenIt->more() )
1246             if (( smDS = smDegenIt->next()->GetSubMeshDS() ))
1247             {
1248               SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
1249               while ( nIt->more() )
1250                 groupsOfNodes.back().push_back( nIt->next() );
1251             }
1252         }
1253         continue; // do not treat sm of degen VERTEX
1254       }
1255
1256       // Sort new and old nodes of a submesh separately
1257
1258       bool isSeam = helper.IsRealSeam( sm->GetId() );
1259
1260       enum { NEW_NODES = 0, OLD_NODES };
1261       map< double, const SMDS_MeshNode* > u2nodesMaps[2], u2nodesOnSeam;
1262       map< double, const SMDS_MeshNode* >::iterator u_oldNode, u_newNode, u_newOnSeam, newEnd;
1263       set< const SMDS_MeshNode* > seamNodes;
1264
1265       // mapper changed, no more "mapper puts on a seam edge nodes from 2 edges"
1266       if ( isSeam && ! getBoundaryNodes ( sm, tgtFace, u2nodesOnSeam, seamNodes ))
1267         ;//RETURN_BAD_RESULT("getBoundaryNodes() failed");
1268
1269       SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
1270       while ( nIt->more() )
1271       {
1272         const SMDS_MeshNode* node = nIt->next();
1273         bool isOld = isOldNode( node );
1274
1275         if ( !isOld && isSeam ) { // new node on a seam edge
1276           if ( seamNodes.count( node ) )
1277             continue; // node is already in the map
1278         }
1279
1280         // sort nodes on edges by their position
1281         map< double, const SMDS_MeshNode* > & pos2nodes = u2nodesMaps[isOld ? OLD_NODES : NEW_NODES];
1282         switch ( node->GetPosition()->GetTypeOfPosition() )
1283         {
1284         case  SMDS_TOP_VERTEX: {
1285           if ( !is1DComputed && !pos2nodes.empty() )
1286             u2nodesMaps[isOld ? NEW_NODES : OLD_NODES].insert( make_pair( 0, node ));
1287           else
1288             pos2nodes.insert( make_pair( 0, node ));
1289           break;
1290         }
1291         case  SMDS_TOP_EDGE:   {
1292           const SMDS_EdgePosition* pos =
1293             static_cast<const SMDS_EdgePosition*>(node->GetPosition());
1294           pos2nodes.insert( make_pair( pos->GetUParameter(), node ));
1295           break;
1296         }
1297         default:
1298           RETURN_BAD_RESULT("Wrong node position type: "<<
1299                             node->GetPosition()->GetTypeOfPosition());
1300         }
1301       }
1302       const bool mergeNewToOld =
1303         ( u2nodesMaps[ NEW_NODES ].size() == u2nodesMaps[ OLD_NODES ].size() );
1304       const bool mergeSeamToNew =
1305         ( u2nodesMaps[ NEW_NODES ].size() == u2nodesOnSeam.size() );
1306
1307       if ( !mergeNewToOld )
1308         if ( u2nodesMaps[ NEW_NODES ].size() > 0 &&
1309              u2nodesMaps[ OLD_NODES ].size() > 0 )
1310         {
1311           u_oldNode = u2nodesMaps[ OLD_NODES ].begin(); 
1312           newEnd    = u2nodesMaps[ OLD_NODES ].end();
1313           for ( ; u_oldNode != newEnd; ++u_oldNode )
1314             SMESH_Algo::addBadInputElement( u_oldNode->second );
1315           return error( COMPERR_BAD_INPUT_MESH,
1316                         SMESH_Comment( "Existing mesh mismatches the projected 2D mesh on " )
1317                         << ( sm->GetSubShape().ShapeType() == TopAbs_EDGE ? "edge" : "vertex" )
1318                         << " #" << sm->GetId() );
1319         }
1320       if ( isSeam && !mergeSeamToNew ) {
1321         const TopoDS_Shape& seam = sm->GetSubShape();
1322         if ( u2nodesMaps[ NEW_NODES ].size() > 0 &&
1323              u2nodesOnSeam.size()            > 0 &&
1324              seam.ShapeType() == TopAbs_EDGE )
1325         {
1326           int nbE1 = SMESH_MesherHelper::Count( tgtFace, TopAbs_EDGE, /*ignoreSame=*/true );
1327           int nbE2 = SMESH_MesherHelper::Count( srcFace, TopAbs_EDGE, /*ignoreSame=*/true );
1328           if ( nbE1 != nbE2 ) // 2 EDGEs are mapped to a seam EDGE
1329           {
1330             // find the 2 EDGEs of srcFace
1331             TopTools_DataMapIteratorOfDataMapOfShapeShape src2tgtIt( shape2ShapeMap._map2to1 );
1332             for ( ; src2tgtIt.More(); src2tgtIt.Next() )
1333               if ( seam.IsSame( src2tgtIt.Value() ))
1334                 SMESH_Algo::addBadInputElements
1335                   ( srcMesh->GetMeshDS()->MeshElements( src2tgtIt.Key() ));
1336             return error( COMPERR_BAD_INPUT_MESH,
1337                           "Different number of nodes on two edges projected to a seam edge" );
1338           }
1339         }
1340       }
1341
1342       // Make groups of nodes to merge
1343
1344       u_oldNode = u2nodesMaps[ OLD_NODES ].begin(); 
1345       u_newNode = u2nodesMaps[ NEW_NODES ].begin();
1346       newEnd    = u2nodesMaps[ NEW_NODES ].end();
1347       u_newOnSeam = u2nodesOnSeam.begin();
1348       if ( mergeNewToOld )
1349         for ( ; u_newNode != newEnd; ++u_newNode, ++u_oldNode )
1350         {
1351           groupsOfNodes.push_back( list< const SMDS_MeshNode* >() );
1352           groupsOfNodes.back().push_back( u_oldNode->second );
1353           groupsOfNodes.back().push_back( u_newNode->second );
1354           if ( mergeSeamToNew )
1355             groupsOfNodes.back().push_back( (u_newOnSeam++)->second );
1356         }
1357       else if ( mergeSeamToNew )
1358         for ( ; u_newNode != newEnd; ++u_newNode, ++u_newOnSeam )
1359         {
1360           groupsOfNodes.push_back( list< const SMDS_MeshNode* >() );
1361           groupsOfNodes.back().push_back( u_newNode->second );
1362           groupsOfNodes.back().push_back( u_newOnSeam->second );
1363         }
1364
1365     } // loop on EDGE and VERTEX submeshes of a target FACE
1366
1367     // Merge
1368
1369     SMESH_MeshEditor editor( tgtMesh );
1370     int nbFaceBeforeMerge = tgtSubMesh->GetSubMeshDS()->NbElements();
1371     editor.MergeNodes( groupsOfNodes );
1372     int nbFaceAtferMerge = tgtSubMesh->GetSubMeshDS()->NbElements();
1373     if ( nbFaceBeforeMerge != nbFaceAtferMerge && !helper.HasDegeneratedEdges() )
1374       return error(COMPERR_BAD_INPUT_MESH, "Probably invalid node parameters on geom faces");
1375
1376
1377     // ----------------------------------------------------------------
1378     // The mapper can create distorted faces by placing nodes out of the FACE
1379     // boundary -- fix bad faces by smoothing
1380     // ----------------------------------------------------------------
1381
1382     fixDistortedFaces( helper, tgtWires );
1383
1384     // ----------------------------------------------------------------
1385     // The mapper can't create quadratic elements, so convert if needed
1386     // ----------------------------------------------------------------
1387
1388     faceIt         = srcSubMesh->GetSubMeshDS()->GetElements();
1389     bool srcIsQuad = faceIt->next()->IsQuadratic();
1390     faceIt         = tgtSubMesh->GetSubMeshDS()->GetElements();
1391     bool tgtIsQuad = faceIt->next()->IsQuadratic();
1392     if ( srcIsQuad && !tgtIsQuad )
1393     {
1394       TIDSortedElemSet tgtFaces;
1395       faceIt = tgtSubMesh->GetSubMeshDS()->GetElements();
1396       while ( faceIt->more() )
1397         tgtFaces.insert( tgtFaces.end(), faceIt->next() );
1398
1399       editor.ConvertToQuadratic(/*theForce3d=*/false, tgtFaces, false);
1400     }
1401
1402     cleaner.Release(); // not to remove mesh
1403
1404   } // end of projection using Pattern mapping
1405
1406
1407   // ---------------------------
1408   // Check elements orientation
1409   // ---------------------------
1410
1411   TopoDS_Face face = TopoDS::Face( theShape );
1412   if ( !theMesh.IsMainShape( tgtFace ))
1413   {
1414     // find the main shape
1415     TopoDS_Shape mainShape = meshDS->ShapeToMesh();
1416     switch ( mainShape.ShapeType() ) {
1417     case TopAbs_SHELL:
1418     case TopAbs_SOLID: break;
1419     default:
1420       TopTools_ListIteratorOfListOfShape ancestIt = theMesh.GetAncestors( face );
1421       for ( ; ancestIt.More(); ancestIt.Next() ) {
1422         TopAbs_ShapeEnum type = ancestIt.Value().ShapeType();
1423         if ( type == TopAbs_SOLID ) {
1424           mainShape = ancestIt.Value();
1425           break;
1426         } else if ( type == TopAbs_SHELL ) {
1427           mainShape = ancestIt.Value();
1428         }
1429       }
1430     }
1431     // find tgtFace in the main solid or shell to know it's true orientation.
1432     TopExp_Explorer exp( mainShape, TopAbs_FACE );
1433     for ( ; exp.More(); exp.Next() ) {
1434       if ( tgtFace.IsSame( exp.Current() )) {
1435         face = TopoDS::Face( exp.Current() );
1436         break;
1437       }
1438     }
1439   }
1440   // Fix orientation
1441   if ( helper.IsReversedSubMesh( face ))
1442   {
1443     SMESH_MeshEditor editor( tgtMesh );
1444     SMDS_ElemIteratorPtr eIt = meshDS->MeshElements( face )->GetElements();
1445     while ( eIt->more() ) {
1446       const SMDS_MeshElement* e = eIt->next();
1447       if ( e->GetType() == SMDSAbs_Face && !editor.Reorient( e ))
1448         RETURN_BAD_RESULT("Pb of SMESH_MeshEditor::Reorient()");
1449     }
1450   }
1451
1452   return true;
1453 }
1454
1455
1456 //=======================================================================
1457 //function : Evaluate
1458 //purpose  : 
1459 //=======================================================================
1460
1461 bool StdMeshers_Projection_2D::Evaluate(SMESH_Mesh&         theMesh,
1462                                         const TopoDS_Shape& theShape,
1463                                         MapShapeNbElems&    aResMap)
1464 {
1465   if ( !_sourceHypo )
1466     return false;
1467
1468   SMESH_Mesh * srcMesh = _sourceHypo->GetSourceMesh();
1469   SMESH_Mesh * tgtMesh = & theMesh;
1470   if ( !srcMesh )
1471     srcMesh = tgtMesh;
1472
1473   // ---------------------------
1474   // Make sub-shapes association
1475   // ---------------------------
1476
1477   TopoDS_Face tgtFace = TopoDS::Face( theShape.Oriented(TopAbs_FORWARD));
1478   TopoDS_Shape srcShape = _sourceHypo->GetSourceFace().Oriented(TopAbs_FORWARD);
1479
1480   TAssocTool::TShapeShapeMap shape2ShapeMap;
1481   TAssocTool::InitVertexAssociation( _sourceHypo, shape2ShapeMap );
1482   if ( !TAssocTool::FindSubShapeAssociation( tgtFace, tgtMesh, srcShape, srcMesh,
1483                                              shape2ShapeMap)  ||
1484        !shape2ShapeMap.IsBound( tgtFace ))
1485     return error(COMPERR_BAD_SHAPE,"Topology of source and target faces seems different" );
1486
1487   TopoDS_Face srcFace = TopoDS::Face( shape2ShapeMap( tgtFace ).Oriented(TopAbs_FORWARD));
1488
1489   // -------------------------------------------------------
1490   // Assure that mesh on a source Face is computed/evaluated
1491   // -------------------------------------------------------
1492
1493   std::vector<int> aVec;
1494
1495   SMESH_subMesh* srcSubMesh = srcMesh->GetSubMesh( srcFace );
1496   if ( srcSubMesh->IsMeshComputed() )
1497   {
1498     aVec.resize( SMDSEntity_Last, 0 );
1499     aVec[SMDSEntity_Node] = srcSubMesh->GetSubMeshDS()->NbNodes();
1500
1501     SMDS_ElemIteratorPtr elemIt = srcSubMesh->GetSubMeshDS()->GetElements();
1502     while ( elemIt->more() )
1503       aVec[ elemIt->next()->GetEntityType() ]++;
1504   }
1505   else
1506   {
1507     MapShapeNbElems  tmpResMap;
1508     MapShapeNbElems& srcResMap = (srcMesh == tgtMesh) ? aResMap : tmpResMap;
1509     if ( !_gen->Evaluate( *srcMesh, srcShape, srcResMap ))
1510       return error(COMPERR_BAD_INPUT_MESH,"Source mesh not evaluatable");
1511     aVec = srcResMap[ srcSubMesh ];
1512     if ( aVec.empty() )
1513       return error(COMPERR_BAD_INPUT_MESH,"Source mesh is wrongly evaluated");
1514   }
1515
1516   SMESH_subMesh * sm = theMesh.GetSubMesh(theShape);
1517   aResMap.insert(std::make_pair(sm,aVec));
1518
1519   return true;
1520 }
1521
1522
1523 //=============================================================================
1524 /*!
1525  * \brief Sets a default event listener to submesh of the source face
1526   * \param subMesh - submesh where algo is set
1527  *
1528  * This method is called when a submesh gets HYP_OK algo_state.
1529  * After being set, event listener is notified on each event of a submesh.
1530  * Arranges that CLEAN event is translated from source submesh to
1531  * the submesh
1532  */
1533 //=============================================================================
1534
1535 void StdMeshers_Projection_2D::SetEventListener(SMESH_subMesh* subMesh)
1536 {
1537   TAssocTool::SetEventListener( subMesh,
1538                                 _sourceHypo->GetSourceFace(),
1539                                 _sourceHypo->GetSourceMesh() );
1540 }