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