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