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