Salome HOME
Patch modules/smesh.git for Doxygen typos/grammar + misc. typos
[modules/smesh.git] / src / StdMeshers / StdMeshers_Projection_2D.cxx
1 // Copyright (C) 2007-2016  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_Mesh.hxx"
39 #include "SMESHDS_SubMesh.hxx"
40 #include "SMESH_Block.hxx"
41 #include "SMESH_Comment.hxx"
42 #include "SMESH_Gen.hxx"
43 #include "SMESH_Mesh.hxx"
44 #include "SMESH_MeshAlgos.hxx"
45 #include "SMESH_MesherHelper.hxx"
46 #include "SMESH_Pattern.hxx"
47 #include "SMESH_subMesh.hxx"
48 #include "SMESH_subMeshEventListener.hxx"
49
50 #include <utilities.h>
51
52 #include <BRepAdaptor_Curve.hxx>
53 #include <BRepAdaptor_Surface.hxx>
54 #include <BRepMesh_Delaun.hxx>
55 #include <BRep_Tool.hxx>
56 #include <Bnd_B2d.hxx>
57 #include <GeomAPI_ProjectPointOnSurf.hxx>
58 #include <GeomLib_IsPlanarSurface.hxx>
59 #include <Precision.hxx>
60 #include <TopExp.hxx>
61 #include <TopExp_Explorer.hxx>
62 #include <TopTools_DataMapIteratorOfDataMapOfShapeShape.hxx>
63 #include <TopTools_ListIteratorOfListOfShape.hxx>
64 #include <TopTools_MapOfShape.hxx>
65 #include <TopoDS.hxx>
66 #include <TopoDS_Solid.hxx>
67 #include <gp_Ax2.hxx>
68 #include <gp_Ax3.hxx>
69 #include <gp_GTrsf.hxx>
70
71
72 using namespace std;
73
74 #define RETURN_BAD_RESULT(msg) { MESSAGE(")-: Error: " << msg); return false; }
75 #ifdef _DEBUG_
76 // enable printing algo + projection shapes while meshing
77 //#define PRINT_WHO_COMPUTE_WHAT
78 #endif
79
80 namespace TAssocTool = StdMeshers_ProjectionUtils;
81 //typedef StdMeshers_ProjectionUtils TAssocTool;
82
83 //=======================================================================
84 //function : StdMeshers_Projection_2D
85 //purpose  : 
86 //=======================================================================
87
88 StdMeshers_Projection_2D::StdMeshers_Projection_2D(int hypId, int studyId, SMESH_Gen* gen)
89   :SMESH_2D_Algo(hypId, studyId, gen)
90 {
91   _name = "Projection_2D";
92   _compatibleHypothesis.push_back("ProjectionSource2D");
93   _sourceHypo = 0;
94 }
95
96 //================================================================================
97 /*!
98  * \brief Destructor
99  */
100 //================================================================================
101
102 StdMeshers_Projection_2D::~StdMeshers_Projection_2D()
103 {}
104
105 //=======================================================================
106 //function : CheckHypothesis
107 //purpose  : 
108 //=======================================================================
109
110 bool StdMeshers_Projection_2D::CheckHypothesis(SMESH_Mesh&                          theMesh,
111                                                const TopoDS_Shape&                  theShape,
112                                                SMESH_Hypothesis::Hypothesis_Status& theStatus)
113 {
114   list <const SMESHDS_Hypothesis * >::const_iterator itl;
115
116   const list <const SMESHDS_Hypothesis * >&hyps = GetUsedHypothesis(theMesh, theShape);
117   if ( hyps.size() == 0 )
118   {
119     theStatus = HYP_MISSING;
120     return false;  // can't work with no hypothesis
121   }
122
123   if ( hyps.size() > 1 )
124   {
125     theStatus = HYP_ALREADY_EXIST;
126     return false;
127   }
128
129   const SMESHDS_Hypothesis *theHyp = hyps.front();
130
131   string hypName = theHyp->GetName();
132
133   theStatus = HYP_OK;
134
135   if (hypName == "ProjectionSource2D")
136   {
137     _sourceHypo = static_cast<const StdMeshers_ProjectionSource2D *>(theHyp);
138
139     // Check hypo parameters
140
141     SMESH_Mesh* srcMesh = _sourceHypo->GetSourceMesh();
142     SMESH_Mesh* tgtMesh = & theMesh;
143     if ( !srcMesh )
144       srcMesh = tgtMesh;
145
146     // check vertices
147     if ( _sourceHypo->HasVertexAssociation() )
148     {
149       // source vertices
150       TopoDS_Shape edge = TAssocTool::GetEdgeByVertices
151         ( srcMesh, _sourceHypo->GetSourceVertex(1), _sourceHypo->GetSourceVertex(2) );
152       if ( edge.IsNull() ||
153            !SMESH_MesherHelper::IsSubShape( edge, srcMesh ) ||
154            !SMESH_MesherHelper::IsSubShape( edge, _sourceHypo->GetSourceFace() ))
155       {
156         theStatus = HYP_BAD_PARAMETER;
157         error("Invalid source vertices");
158         SCRUTE((edge.IsNull()));
159         SCRUTE((SMESH_MesherHelper::IsSubShape( edge, srcMesh )));
160         SCRUTE((SMESH_MesherHelper::IsSubShape( edge, _sourceHypo->GetSourceFace() )));
161       }
162       else
163       {
164         // target vertices
165         edge = TAssocTool::GetEdgeByVertices
166           ( tgtMesh, _sourceHypo->GetTargetVertex(1), _sourceHypo->GetTargetVertex(2) );
167         if ( edge.IsNull() || !SMESH_MesherHelper::IsSubShape( edge, tgtMesh ))
168         {
169           theStatus = HYP_BAD_PARAMETER;
170           error("Invalid target vertices");
171           SCRUTE((edge.IsNull()));
172           SCRUTE((SMESH_MesherHelper::IsSubShape( edge, tgtMesh )));
173         }
174         // PAL16203
175         else if ( !_sourceHypo->IsCompoundSource() &&
176                   !SMESH_MesherHelper::IsSubShape( edge, theShape ))
177         {
178           theStatus = HYP_BAD_PARAMETER;
179           error("Invalid target vertices");
180           SCRUTE((SMESH_MesherHelper::IsSubShape( edge, theShape )));
181         }
182       }
183     }
184     // check a source face
185     if ( !SMESH_MesherHelper::IsSubShape( _sourceHypo->GetSourceFace(), srcMesh ) ||
186          ( srcMesh == tgtMesh && theShape == _sourceHypo->GetSourceFace() ))
187     {
188       theStatus = HYP_BAD_PARAMETER;
189       error("Invalid source face");
190       SCRUTE((SMESH_MesherHelper::IsSubShape( _sourceHypo->GetSourceFace(), srcMesh )));
191       SCRUTE((srcMesh == tgtMesh));
192       SCRUTE(( theShape == _sourceHypo->GetSourceFace() ));
193     }
194   }
195   else
196   {
197     theStatus = HYP_INCOMPATIBLE;
198   }
199   return ( theStatus == HYP_OK );
200 }
201
202 namespace {
203
204   //================================================================================
205   /*!
206    * \brief define if a node is new or old
207    * \param node - node to check
208    * \retval bool - true if the node existed before Compute() is called
209    */
210   //================================================================================
211
212   bool isOldNode( const SMDS_MeshNode* node )
213   {
214     // old nodes are shared by edges and new ones are shared
215     // only by faces created by mapper
216     //if ( is1DComputed )
217     {
218       bool isOld = node->NbInverseElements(SMDSAbs_Edge) > 0;
219       return isOld;
220     }
221     // else
222     // {
223     //   SMDS_ElemIteratorPtr invFace = node->GetInverseElementIterator(SMDSAbs_Face);
224     //   bool isNew = invFace->more();
225     //   return !isNew;
226     // }
227   }
228
229   //================================================================================
230   /*!
231    * \brief Class to remove mesh built by pattern mapper on edges
232    * and vertices in the case of failure of projection algo.
233    * It does it's job at destruction
234    */
235   //================================================================================
236
237   class MeshCleaner {
238     SMESH_subMesh* sm;
239   public:
240     MeshCleaner( SMESH_subMesh* faceSubMesh ): sm(faceSubMesh) {}
241     ~MeshCleaner() { Clean(sm); }
242     void Release() { sm = 0; } // mesh will not be removed
243     static void Clean( SMESH_subMesh* sm, bool withSub=true )
244     {
245       if ( !sm || !sm->GetSubMeshDS() ) return;
246       // PAL16567, 18920. Remove face nodes as well
247 //       switch ( sm->GetSubShape().ShapeType() ) {
248 //       case TopAbs_VERTEX:
249 //       case TopAbs_EDGE: {
250         SMDS_NodeIteratorPtr nIt = sm->GetSubMeshDS()->GetNodes();
251         SMESHDS_Mesh* mesh = sm->GetFather()->GetMeshDS();
252         while ( nIt->more() ) {
253           const SMDS_MeshNode* node = nIt->next();
254           if ( !isOldNode( node ) )
255             mesh->RemoveNode( node );
256         }
257         // do not break but iterate over DependsOn()
258 //       }
259 //       default:
260         if ( !withSub ) return;
261         SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(false,false);
262         while ( smIt->more() )
263           Clean( smIt->next(), false );
264 //       }
265     }
266   };
267
268   //================================================================================
269   /*!
270    * \brief find new nodes belonging to one free border of mesh on face
271     * \param sm - submesh on edge or vertex containing nodes to choose from
272     * \param face - the face bound by the submesh
273     * \param u2nodes - map to fill with nodes
274     * \param seamNodes - set of found nodes
275     * \retval bool - is a success
276    */
277   //================================================================================
278
279   bool getBoundaryNodes ( SMESH_subMesh*                        sm,
280                           const TopoDS_Face&                    face,
281                           map< double, const SMDS_MeshNode* > & u2nodes,
282                           set< const SMDS_MeshNode* > &         seamNodes)
283   {
284     u2nodes.clear();
285     seamNodes.clear();
286     if ( !sm || !sm->GetSubMeshDS() )
287       RETURN_BAD_RESULT("Null submesh");
288
289     SMDS_NodeIteratorPtr nIt = sm->GetSubMeshDS()->GetNodes();
290     switch ( sm->GetSubShape().ShapeType() ) {
291
292     case TopAbs_VERTEX: {
293       while ( nIt->more() ) {
294         const SMDS_MeshNode* node = nIt->next();
295         if ( isOldNode( node ) ) continue;
296         u2nodes.insert( make_pair( 0., node ));
297         seamNodes.insert( node );
298         return true;
299       }
300       break;
301     }
302     case TopAbs_EDGE: {
303       
304       // Get submeshes of sub-vertices
305       const map< int, SMESH_subMesh * >& subSM = sm->DependsOn();
306       if ( subSM.size() != 2 )
307         RETURN_BAD_RESULT("there must be 2 submeshes of sub-vertices"
308                           " but we have " << subSM.size());
309       SMESH_subMesh* smV1 = subSM.begin()->second;
310       SMESH_subMesh* smV2 = subSM.rbegin()->second;
311       if ( !smV1->IsMeshComputed() || !smV2->IsMeshComputed() )
312         RETURN_BAD_RESULT("Empty vertex submeshes");
313
314       const SMDS_MeshNode* nV1 = 0;
315       const SMDS_MeshNode* nE = 0;
316
317       // Look for nV1 - a new node on V1
318       nIt = smV1->GetSubMeshDS()->GetNodes();
319       while ( nIt->more() && !nE ) {
320         const SMDS_MeshNode* node = nIt->next();
321         if ( isOldNode( node ) ) continue;
322         nV1 = node;
323
324         // Find nE - a new node connected to nV1 and belonging to edge submesh;
325         SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
326         SMDS_ElemIteratorPtr vElems = nV1->GetInverseElementIterator(SMDSAbs_Face);
327         while ( vElems->more() && !nE ) {
328           const SMDS_MeshElement* elem = vElems->next();
329           int nbNodes = elem->NbNodes();
330           if ( elem->IsQuadratic() )
331             nbNodes /= 2;
332           int iV1 = elem->GetNodeIndex( nV1 );
333           // try next after nV1
334           int iE = SMESH_MesherHelper::WrapIndex( iV1 + 1, nbNodes );
335           if ( smDS->Contains( elem->GetNode( iE ) ))
336             nE = elem->GetNode( iE );
337           if ( !nE ) {
338             // try node before nV1
339             iE = SMESH_MesherHelper::WrapIndex( iV1 - 1, nbNodes );
340             if ( smDS->Contains( elem->GetNode( iE )))
341               nE = elem->GetNode( iE );
342           }
343           if ( nE && elem->IsQuadratic() ) { // find medium node between nV1 and nE
344             if ( Abs( iV1 - iE ) == 1 )
345               nE = elem->GetNode( Min ( iV1, iE ) + nbNodes );
346             else
347               nE = elem->GetNode( elem->NbNodes() - 1 );
348           }
349         }
350       }
351       if ( !nV1 )
352         RETURN_BAD_RESULT("No new node found on V1");
353       if ( !nE )
354         RETURN_BAD_RESULT("new node on edge not found");
355
356       // Get the whole free border of a face
357       list< const SMDS_MeshNode* > bordNodes;
358       list< const SMDS_MeshElement* > bordFaces;
359       if ( !SMESH_MeshEditor::FindFreeBorder (nV1, nE, nV1, bordNodes, bordFaces ))
360         RETURN_BAD_RESULT("free border of a face not found by nodes " <<
361                           nV1->GetID() << " " << nE->GetID() );
362
363       // Insert nodes of the free border to the map until node on V2 encountered
364       SMESHDS_SubMesh* v2smDS = smV2->GetSubMeshDS();
365       list< const SMDS_MeshNode* >::iterator bordIt = bordNodes.begin();
366       bordIt++; // skip nV1
367       for ( ; bordIt != bordNodes.end(); ++bordIt ) {
368         const SMDS_MeshNode* node = *bordIt;
369         if ( v2smDS->Contains( node ))
370           break;
371         if ( node->GetPosition()->GetTypeOfPosition() != SMDS_TOP_EDGE )
372           RETURN_BAD_RESULT("Bad node position type: node " << node->GetID() <<
373                             " pos type " << node->GetPosition()->GetTypeOfPosition());
374         const SMDS_EdgePosition* pos =
375           static_cast<const SMDS_EdgePosition*>(node->GetPosition());
376         u2nodes.insert( make_pair( pos->GetUParameter(), node ));
377         seamNodes.insert( node );
378       }
379       if ( u2nodes.size() != seamNodes.size() )
380         RETURN_BAD_RESULT("Bad node params on edge " << sm->GetId() <<
381                           ", " << u2nodes.size() << " != " << seamNodes.size() );
382       return true;
383     }
384     default:;
385     }
386     RETURN_BAD_RESULT ("Unexpected submesh type");
387
388   } // bool getBoundaryNodes()
389
390   //================================================================================
391   /*!
392    * \brief Check if two consecutive EDGEs are connected in 2D
393    *  \param [in] E1 - a well oriented non-seam EDGE
394    *  \param [in] E2 - a possibly well oriented seam EDGE
395    *  \param [in] F - a FACE
396    *  \return bool - result
397    */
398   //================================================================================
399
400   bool are2dConnected( const TopoDS_Edge & E1,
401                        const TopoDS_Edge & E2,
402                        const TopoDS_Face & F )
403   {
404     double f,l;
405     Handle(Geom2d_Curve) c1 = BRep_Tool::CurveOnSurface( E1, F, f, l );
406     gp_Pnt2d uvFirst1 = c1->Value( f );
407     gp_Pnt2d uvLast1  = c1->Value( l );
408
409     Handle(Geom2d_Curve) c2 = BRep_Tool::CurveOnSurface( E2, F, f, l );
410     gp_Pnt2d uvFirst2 = c2->Value( E2.Orientation() == TopAbs_REVERSED ? l : f );
411     double tol2 = Max( Precision::PConfusion() * Precision::PConfusion(),
412                        1e-5 * uvLast1.SquareDistance( uvFirst1 ));
413
414     return (( uvFirst2.SquareDistance( uvFirst1 ) < tol2 ) ||
415             ( uvFirst2.SquareDistance( uvLast1  ) < tol2 ));
416   }
417
418   //================================================================================
419   /*!
420    * \brief Compose TSideVector for both FACEs keeping matching order of EDGEs
421    *        and fill src2tgtNodes map
422    */
423   //================================================================================
424
425   TError getWires(const TopoDS_Face&                 tgtFace,
426                   const TopoDS_Face&                 srcFace,
427                   SMESH_Mesh *                       tgtMesh,
428                   SMESH_Mesh *                       srcMesh,
429                   const TAssocTool::TShapeShapeMap&  shape2ShapeMap,
430                   TSideVector&                       srcWires,
431                   TSideVector&                       tgtWires,
432                   TAssocTool::TNodeNodeMap&          src2tgtNodes,
433                   bool&                              is1DComputed)
434   {
435     src2tgtNodes.clear();
436
437     // get ordered src EDGEs
438     TError err;
439     srcWires = StdMeshers_FaceSide::GetFaceWires( srcFace, *srcMesh,/*skipMediumNodes=*/0, err);
440     if (( err && !err->IsOK() ) ||
441         ( srcWires.empty() ))
442       return err;
443 #ifdef PRINT_WHO_COMPUTE_WHAT
444     cout << "Projection_2D" <<  " F "
445          << tgtMesh->GetMeshDS()->ShapeToIndex( tgtFace ) << " <- "
446          << srcMesh->GetMeshDS()->ShapeToIndex( srcFace ) << endl;
447 #endif
448     SMESH_MesherHelper srcHelper( *srcMesh );
449     srcHelper.SetSubShape( srcFace );
450
451     // make corresponding sequence of tgt EDGEs
452     tgtWires.resize( srcWires.size() );
453     for ( size_t iW = 0; iW < srcWires.size(); ++iW )
454     {
455       StdMeshers_FaceSidePtr srcWire = srcWires[iW];
456
457       list< TopoDS_Edge > tgtEdges;
458       TopTools_IndexedMapOfShape edgeMap; // to detect seam edges
459       for ( int iE = 0; iE < srcWire->NbEdges(); ++iE )
460       {
461         TopoDS_Edge     srcE = srcWire->Edge( iE );
462         TopoDS_Edge     tgtE = TopoDS::Edge( shape2ShapeMap( srcE, /*isSrc=*/true));
463         TopoDS_Shape srcEbis = shape2ShapeMap( tgtE, /*isSrc=*/false );
464         if ( srcE.Orientation() != srcEbis.Orientation() )
465           tgtE.Reverse();
466         // reverse a seam edge encountered for the second time
467         const int index = edgeMap.Add( tgtE );
468         if ( index < edgeMap.Extent() ) // E is a seam
469         {
470           // check which of edges to reverse, E or one already being in tgtEdges
471           if ( are2dConnected( tgtEdges.back(), tgtE, tgtFace ))
472           {
473             list< TopoDS_Edge >::iterator eIt = tgtEdges.begin();
474             std::advance( eIt, index-1 );
475             if ( are2dConnected( tgtEdges.back(), *eIt, tgtFace ))
476               eIt->Reverse();
477           }
478           else
479           {
480             tgtE.Reverse();
481           }
482         }
483         if ( srcWire->NbEdges() == 1 && tgtMesh == srcMesh ) // circle
484         {
485           // try to verify ori by propagation
486           pair<int,TopoDS_Edge> nE =
487             StdMeshers_ProjectionUtils::GetPropagationEdge( srcMesh, tgtE, srcE );
488           if ( !nE.second.IsNull() )
489             tgtE = nE.second;
490         }
491         tgtEdges.push_back( tgtE );
492       }
493
494       tgtWires[ iW ].reset( new StdMeshers_FaceSide( tgtFace, tgtEdges, tgtMesh,
495                                                      /*theIsForward = */ true,
496                                                      /*theIgnoreMediumNodes = */false));
497       StdMeshers_FaceSidePtr tgtWire = tgtWires[ iW ];
498
499       // Fill map of src to tgt nodes with nodes on edges
500
501       for ( int iE = 0; iE < srcWire->NbEdges(); ++iE )
502       {
503 #ifdef PRINT_WHO_COMPUTE_WHAT
504         if ( tgtMesh->GetSubMesh( tgtWire->Edge(iE) )->IsEmpty() )
505           cout << "Projection_2D" <<  " E "
506                << tgtWire->EdgeID(iE) << " <- " << srcWire->EdgeID(iE) << endl;
507 #endif
508         if ( srcMesh->GetSubMesh( srcWire->Edge(iE) )->IsEmpty() ||
509              tgtMesh->GetSubMesh( tgtWire->Edge(iE) )->IsEmpty() )
510         {
511           // add nodes on VERTEXes for a case of not meshes EDGEs
512           const SMDS_MeshNode* srcN = srcWire->VertexNode( iE );
513           const SMDS_MeshNode* tgtN = tgtWire->VertexNode( iE );
514           if ( srcN && tgtN )
515             src2tgtNodes.insert( make_pair( srcN, tgtN ));
516         }
517         else
518         {
519           const bool skipMedium = true, isFwd = true;
520           StdMeshers_FaceSide srcEdge( srcFace, srcWire->Edge(iE), srcMesh, isFwd, skipMedium);
521           StdMeshers_FaceSide tgtEdge( tgtFace, tgtWire->Edge(iE), tgtMesh, isFwd, skipMedium);
522           
523           vector< const SMDS_MeshNode* > srcNodes = srcEdge.GetOrderedNodes();
524           vector< const SMDS_MeshNode* > tgtNodes = tgtEdge.GetOrderedNodes();
525
526           if (( srcNodes.size() != tgtNodes.size() ) && tgtNodes.size() > 0 )
527             return SMESH_ComputeError::New( COMPERR_BAD_INPUT_MESH,
528                                             "Different number of nodes on edges");
529           if ( !tgtNodes.empty() )
530           {
531             vector< const SMDS_MeshNode* >::iterator tn = tgtNodes.begin();
532             //if ( srcWire->Edge(iE).Orientation() == tgtWire->Edge(iE).Orientation() )
533             {
534               vector< const SMDS_MeshNode* >::iterator sn = srcNodes.begin();
535               for ( ; tn != tgtNodes.end(); ++tn, ++sn)
536                 src2tgtNodes.insert( make_pair( *sn, *tn ));
537             }
538             // else
539             // {
540             //   vector< const SMDS_MeshNode* >::reverse_iterator sn = srcNodes.rbegin();
541             //   for ( ; tn != tgtNodes.end(); ++tn, ++sn)
542             //     src2tgtNodes.insert( make_pair( *sn, *tn ));
543             // }
544             is1DComputed = true;
545           }
546         }
547       } // loop on EDGEs of a WIRE
548
549     } // loop on WIREs
550
551     return TError();
552   }
553
554   //================================================================================
555   /*!
556    * \brief Perform projection in case if tgtFace.IsPartner( srcFace ) and in case
557    * if projection by 3D transformation is possible
558    */
559   //================================================================================
560
561   bool projectPartner(const TopoDS_Face&                 tgtFace,
562                       const TopoDS_Face&                 srcFace,
563                       const TSideVector&                 tgtWires,
564                       const TSideVector&                 srcWires,
565                       const TAssocTool::TShapeShapeMap&  shape2ShapeMap,
566                       TAssocTool::TNodeNodeMap&          src2tgtNodes,
567                       const bool                         is1DComputed)
568   {
569     SMESH_Mesh *    tgtMesh = tgtWires[0]->GetMesh();
570     SMESH_Mesh *    srcMesh = srcWires[0]->GetMesh();
571     SMESHDS_Mesh* tgtMeshDS = tgtMesh->GetMeshDS();
572     SMESHDS_Mesh* srcMeshDS = srcMesh->GetMeshDS();
573     SMESH_MesherHelper helper( *tgtMesh );
574
575     const double tol = 1.e-7 * srcMeshDS->getMaxDim();
576
577     // transformation to get location of target nodes from source ones
578     StdMeshers_ProjectionUtils::TrsfFinder3D trsf;
579     bool trsfIsOK = false;
580     if ( tgtFace.IsPartner( srcFace ))
581     {
582       gp_GTrsf srcTrsf = srcFace.Location().Transformation();
583       gp_GTrsf tgtTrsf = tgtFace.Location().Transformation();
584       gp_GTrsf t = srcTrsf.Inverted().Multiplied( tgtTrsf );
585       trsf.Set( t );
586       // check
587       gp_Pnt srcP = BRep_Tool::Pnt( srcWires[0]->FirstVertex() );
588       gp_Pnt tgtP = BRep_Tool::Pnt( tgtWires[0]->FirstVertex() );
589       trsfIsOK = ( tgtP.Distance( trsf.Transform( srcP )) < tol );
590       if ( !trsfIsOK )
591       {
592         trsf.Set( tgtTrsf.Inverted().Multiplied( srcTrsf ));
593         trsfIsOK = ( tgtP.Distance( trsf.Transform( srcP )) < tol );
594       }
595     }
596     if ( !trsfIsOK )
597     {
598       // Try to find the 3D transformation
599
600       const int totNbSeg = 50;
601       vector< gp_XYZ > srcPnts, tgtPnts;
602       srcPnts.reserve( totNbSeg );
603       tgtPnts.reserve( totNbSeg );
604       gp_XYZ srcBC( 0,0,0 ), tgtBC( 0,0,0 );
605       for ( size_t iW = 0; iW < srcWires.size(); ++iW )
606       {
607         const double minSegLen = srcWires[iW]->Length() / totNbSeg;
608         for ( int iE = 0; iE < srcWires[iW]->NbEdges(); ++iE )
609         {
610           size_t nbSeg = Max( 1, int( srcWires[iW]->EdgeLength( iE ) / minSegLen ));
611           double srcU  = srcWires[iW]->FirstParameter( iE );
612           double tgtU  = tgtWires[iW]->FirstParameter( iE );
613           double srcDu = ( srcWires[iW]->LastParameter( iE )- srcU ) / nbSeg;
614           double tgtDu = ( tgtWires[iW]->LastParameter( iE )- tgtU ) / nbSeg;
615           for ( size_t i = 0; i < nbSeg; ++i  )
616           {
617             srcPnts.push_back( srcWires[iW]->Value3d( srcU ).XYZ() );
618             tgtPnts.push_back( tgtWires[iW]->Value3d( tgtU ).XYZ() );
619             srcU += srcDu;
620             tgtU += tgtDu;
621             srcBC += srcPnts.back();
622             tgtBC += tgtPnts.back();
623           }
624         }
625       }
626       if ( !trsf.Solve( srcPnts, tgtPnts ))
627         return false;
628
629       // check trsf
630
631       const int nbTestPnt = 20;
632       const size_t  iStep = Max( 1, int( srcPnts.size() / nbTestPnt ));
633       // check boundary
634       gp_Pnt trsfTgt = trsf.Transform( srcBC / srcPnts.size() );
635       trsfIsOK = ( trsfTgt.SquareDistance( tgtBC / tgtPnts.size() ) < tol*tol );
636       for ( size_t i = 0; ( i < srcPnts.size() && trsfIsOK ); i += iStep )
637       {
638         gp_Pnt trsfTgt = trsf.Transform( srcPnts[i] );
639         trsfIsOK = ( trsfTgt.SquareDistance( tgtPnts[i] ) < tol*tol );
640       }
641       // check an in-FACE point
642       if ( trsfIsOK )
643       {
644         BRepAdaptor_Surface srcSurf( srcFace );
645         gp_Pnt srcP =
646           srcSurf.Value( 0.321 * ( srcSurf.FirstUParameter() + srcSurf.LastUParameter() ),
647                          0.123 * ( srcSurf.FirstVParameter() + srcSurf.LastVParameter() ));
648         gp_Pnt tgtTrsfP = trsf.Transform( srcP );
649         TopLoc_Location loc;
650         GeomAPI_ProjectPointOnSurf& proj = helper.GetProjector( tgtFace, loc, 0.1*tol );
651         if ( !loc.IsIdentity() )
652           tgtTrsfP.Transform( loc.Transformation().Inverted() );
653         proj.Perform( tgtTrsfP );
654         trsfIsOK = ( proj.IsDone() &&
655                      proj.NbPoints() > 0 &&
656                      proj.LowerDistance() < tol );
657       }
658       if ( !trsfIsOK )
659         return false;
660     }
661
662     // Make new faces
663
664     // prepare the helper to adding quadratic elements if necessary
665     //helper.SetSubShape( tgtFace );
666     helper.IsQuadraticSubMesh( tgtFace );
667
668     SMESHDS_SubMesh* srcSubDS = srcMeshDS->MeshElements( srcFace );
669     if ( !is1DComputed && srcSubDS->NbElements() )
670       helper.SetIsQuadratic( srcSubDS->GetElements()->next()->IsQuadratic() );
671
672     SMESH_MesherHelper srcHelper( *srcMesh );
673     srcHelper.SetSubShape( srcFace );
674     SMESH_MesherHelper edgeHelper( *tgtMesh );
675     edgeHelper.ToFixNodeParameters( true );
676
677     const SMDS_MeshNode* nullNode = 0;
678     TAssocTool::TNodeNodeMap::iterator srcN_tgtN;
679
680     // indices of nodes to create properly oriented faces
681     bool isReverse = ( !trsf.IsIdentity() );
682     int tri1 = 1, tri2 = 2, quad1 = 1, quad3 = 3;
683     if ( isReverse )
684       std::swap( tri1, tri2 ), std::swap( quad1, quad3 );
685
686     SMDS_ElemIteratorPtr elemIt = srcSubDS->GetElements();
687     vector< const SMDS_MeshNode* > tgtNodes;
688     while ( elemIt->more() ) // loop on all mesh faces on srcFace
689     {
690       const SMDS_MeshElement* elem = elemIt->next();
691       const int nbN = elem->NbCornerNodes(); 
692       tgtNodes.resize( nbN );
693       helper.SetElementsOnShape( false );
694       for ( int i = 0; i < nbN; ++i ) // loop on nodes of the source element
695       {
696         const SMDS_MeshNode* srcNode = elem->GetNode(i);
697         srcN_tgtN = src2tgtNodes.insert( make_pair( srcNode, nullNode )).first;
698         if ( srcN_tgtN->second == nullNode )
699         {
700           // create a new node
701           gp_Pnt tgtP = trsf.Transform( SMESH_TNodeXYZ( srcNode ));
702           SMDS_MeshNode* n = helper.AddNode( tgtP.X(), tgtP.Y(), tgtP.Z() );
703           srcN_tgtN->second = n;
704           switch ( srcNode->GetPosition()->GetTypeOfPosition() )
705           {
706           case SMDS_TOP_FACE:
707           {
708             gp_Pnt2d srcUV = srcHelper.GetNodeUV( srcFace, srcNode );
709             tgtMeshDS->SetNodeOnFace( n, helper.GetSubShapeID(), srcUV.X(), srcUV.Y() );
710             break;
711           }
712           case SMDS_TOP_EDGE:
713           {
714             const TopoDS_Edge& srcE = TopoDS::Edge( srcMeshDS->IndexToShape( srcNode->getshapeId()));
715             const TopoDS_Edge& tgtE = TopoDS::Edge( shape2ShapeMap( srcE, /*isSrc=*/true ));
716             double srcU = srcHelper.GetNodeU( srcE, srcNode );
717             tgtMeshDS->SetNodeOnEdge( n, tgtE, srcU );
718             if ( !tgtFace.IsPartner( srcFace ))
719             {
720               edgeHelper.SetSubShape( tgtE );
721               double tol = BRep_Tool::Tolerance( tgtE );
722               bool isOk = edgeHelper.CheckNodeU( tgtE, n, srcU, 2 * tol, /*force=*/true );
723               if ( !isOk ) // projection of n to tgtE failed (23395)
724               {
725                 double sF, sL, tF, tL;
726                 BRep_Tool::Range( srcE, sF, sL );
727                 BRep_Tool::Range( tgtE, tF, tL );
728                 double srcR = ( srcU - sF ) / ( sL - sF );
729                 double tgtU  = tF + srcR * ( tL - tF );
730                 tgtMeshDS->SetNodeOnEdge( n, tgtE, tgtU );
731                 gp_Pnt newP = BRepAdaptor_Curve( tgtE ).Value( tgtU );
732                 double dist = newP.Distance( tgtP );
733                 if ( tol < dist && dist < 1000*tol )
734                   tgtMeshDS->MoveNode( n, newP.X(), newP.Y(), newP.Z() );
735               }
736             }
737             break;
738           }
739           case SMDS_TOP_VERTEX:
740           {
741             const TopoDS_Shape & srcV = srcMeshDS->IndexToShape( srcNode->getshapeId() );
742             const TopoDS_Shape & tgtV = shape2ShapeMap( srcV, /*isSrc=*/true );
743             tgtMeshDS->SetNodeOnVertex( n, TopoDS::Vertex( tgtV ));
744             break;
745           }
746           default:;
747           }
748         }
749         tgtNodes[i] = srcN_tgtN->second;
750       }
751       // create a new face
752       helper.SetElementsOnShape( true );
753       switch ( nbN )
754       {
755       case 3: helper.AddFace(tgtNodes[0], tgtNodes[tri1], tgtNodes[tri2]); break;
756       case 4: helper.AddFace(tgtNodes[0], tgtNodes[quad1], tgtNodes[2], tgtNodes[quad3]); break;
757       default:
758         if ( isReverse ) std::reverse( tgtNodes.begin(), tgtNodes.end() );
759         helper.AddPolygonalFace( tgtNodes );
760       }
761     }
762
763     // check node positions
764
765     if ( !tgtFace.IsPartner( srcFace ) )
766     {
767       helper.ToFixNodeParameters( true );
768
769       int nbOkPos = 0;
770       const double tol2d = 1e-12;
771       srcN_tgtN = src2tgtNodes.begin();
772       for ( ; srcN_tgtN != src2tgtNodes.end(); ++srcN_tgtN )
773       {
774         const SMDS_MeshNode* n = srcN_tgtN->second;
775         switch ( n->GetPosition()->GetTypeOfPosition() )
776         {
777         case SMDS_TOP_FACE:
778         {
779           if ( nbOkPos > 10 ) break;
780           gp_XY uv = helper.GetNodeUV( tgtFace, n ), uvBis = uv;
781           if (( helper.CheckNodeUV( tgtFace, n, uv, tol )) &&
782               (( uv - uvBis ).SquareModulus() < tol2d ))
783             ++nbOkPos;
784           else
785             nbOkPos = -((int) src2tgtNodes.size() );
786           break;
787         }
788         case SMDS_TOP_EDGE:
789         {
790           // const TopoDS_Edge & tgtE = TopoDS::Edge( tgtMeshDS->IndexToShape( n->getshapeId() ));
791           // edgeHelper.SetSubShape( tgtE );
792           // edgeHelper.GetNodeU( tgtE, n, 0, &toCheck );
793           break;
794         }
795         default:;
796         }
797       }
798     }
799
800     return true;
801
802   } //   bool projectPartner()
803
804   //================================================================================
805   /*!
806    * \brief Perform projection in case if the faces are similar in 2D space
807    */
808   //================================================================================
809
810   bool projectBy2DSimilarity(const TopoDS_Face&                 tgtFace,
811                              const TopoDS_Face&                 srcFace,
812                              const TSideVector&                 tgtWires,
813                              const TSideVector&                 srcWires,
814                              const TAssocTool::TShapeShapeMap&  shape2ShapeMap,
815                              TAssocTool::TNodeNodeMap&          src2tgtNodes,
816                              const bool                         is1DComputed)
817   {
818     SMESH_Mesh * tgtMesh = tgtWires[0]->GetMesh();
819     SMESH_Mesh * srcMesh = srcWires[0]->GetMesh();
820
821     // WARNING: we can have problems if the FACE is symmetrical in 2D,
822     // then the projection can be mirrored relating to what is expected
823
824     // 1) Find 2D transformation
825
826     StdMeshers_ProjectionUtils::TrsfFinder2D trsf;
827     {
828       // get 2 pairs of corresponding UVs
829       gp_Pnt2d srcP0 = srcWires[0]->Value2d(0.0);
830       gp_Pnt2d srcP1 = srcWires[0]->Value2d(0.333);
831       gp_Pnt2d tgtP0 = tgtWires[0]->Value2d(0.0);
832       gp_Pnt2d tgtP1 = tgtWires[0]->Value2d(0.333);
833
834       // make transformation
835       gp_Trsf2d fromTgtCS, toSrcCS; // from/to global CS
836       gp_Ax2d srcCS( srcP0, gp_Vec2d( srcP0, srcP1 ));
837       gp_Ax2d tgtCS( tgtP0, gp_Vec2d( tgtP0, tgtP1 ));
838       toSrcCS  .SetTransformation( srcCS );
839       fromTgtCS.SetTransformation( tgtCS );
840       fromTgtCS.Invert();
841       trsf.Set( fromTgtCS * toSrcCS );
842
843       // check transformation
844       bool trsfIsOK = true;
845       const double tol = 1e-5 * gp_Vec2d( srcP0, srcP1 ).Magnitude();
846       for ( double u = 0.12; ( u < 1. && trsfIsOK ); u += 0.1 )
847       {
848         gp_Pnt2d srcUV  = srcWires[0]->Value2d( u );
849         gp_Pnt2d tgtUV  = tgtWires[0]->Value2d( u );
850         gp_Pnt2d tgtUV2 = trsf.Transform( srcUV );
851         trsfIsOK = ( tgtUV.Distance( tgtUV2 ) < tol );
852       }
853
854       // Find trsf using a least-square approximation
855       if ( !trsfIsOK )
856       {
857         // find trsf
858         const int totNbSeg = 50;
859         vector< gp_XY > srcPnts, tgtPnts;
860         srcPnts.reserve( totNbSeg );
861         tgtPnts.reserve( totNbSeg );
862         for ( size_t iW = 0; iW < srcWires.size(); ++iW )
863         {
864           const double minSegLen = srcWires[iW]->Length() / totNbSeg;
865           for ( int iE = 0; iE < srcWires[iW]->NbEdges(); ++iE )
866           {
867             size_t nbSeg = Max( 1, int( srcWires[iW]->EdgeLength( iE ) / minSegLen ));
868             double srcU  = srcWires[iW]->FirstParameter( iE );
869             double tgtU  = tgtWires[iW]->FirstParameter( iE );
870             double srcDu = ( srcWires[iW]->LastParameter( iE )- srcU ) / nbSeg;
871             double tgtDu = ( tgtWires[iW]->LastParameter( iE )- tgtU ) / nbSeg;
872             for ( size_t i = 0; i < nbSeg; ++i, srcU += srcDu, tgtU += tgtDu  )
873             {
874               srcPnts.push_back( srcWires[iW]->Value2d( srcU ).XY() );
875               tgtPnts.push_back( tgtWires[iW]->Value2d( tgtU ).XY() );
876             }
877           }
878         }
879         if ( !trsf.Solve( srcPnts, tgtPnts ))
880           return false;
881
882         // check trsf
883
884         trsfIsOK = true;
885         const int nbTestPnt = 10;
886         const size_t  iStep = Max( 1, int( srcPnts.size() / nbTestPnt ));
887         for ( size_t i = 0; ( i < srcPnts.size() && trsfIsOK ); i += iStep )
888         {
889           gp_Pnt2d trsfTgt = trsf.Transform( srcPnts[i] );
890           trsfIsOK = ( trsfTgt.Distance( tgtPnts[i] ) < tol );
891         }
892         if ( !trsfIsOK )
893           return false;
894       }
895     } // "Find transformation" block
896
897     // 2) Projection
898
899     SMESHDS_SubMesh* srcSubDS = srcMesh->GetMeshDS()->MeshElements( srcFace );
900
901     SMESH_MesherHelper helper( *tgtMesh );
902     helper.SetSubShape( tgtFace );
903     if ( is1DComputed )
904       helper.IsQuadraticSubMesh( tgtFace );
905     else
906       helper.SetIsQuadratic( srcSubDS->GetElements()->next()->IsQuadratic() );
907     helper.SetElementsOnShape( true );
908     Handle(Geom_Surface) tgtSurface = BRep_Tool::Surface( tgtFace );
909     SMESHDS_Mesh* tgtMeshDS = tgtMesh->GetMeshDS();
910
911     SMESH_MesherHelper srcHelper( *srcMesh );
912     srcHelper.SetSubShape( srcFace );
913
914     const SMDS_MeshNode* nullNode = 0;
915     TAssocTool::TNodeNodeMap::iterator srcN_tgtN;
916
917     SMDS_ElemIteratorPtr elemIt = srcSubDS->GetElements();
918     vector< const SMDS_MeshNode* > tgtNodes;
919     bool uvOK;
920     while ( elemIt->more() ) // loop on all mesh faces on srcFace
921     {
922       const SMDS_MeshElement* elem = elemIt->next();
923       const int nbN = elem->NbCornerNodes(); 
924       tgtNodes.resize( nbN );
925       for ( int i = 0; i < nbN; ++i ) // loop on nodes of the source element
926       {
927         const SMDS_MeshNode* srcNode = elem->GetNode(i);
928         srcN_tgtN = src2tgtNodes.insert( make_pair( srcNode, nullNode )).first;
929         if ( srcN_tgtN->second == nullNode )
930         {
931           // create a new node
932           gp_Pnt2d srcUV = srcHelper.GetNodeUV( srcFace, srcNode,
933                                                 elem->GetNode( helper.WrapIndex(i+1,nbN)), &uvOK);
934           gp_Pnt2d   tgtUV = trsf.Transform( srcUV );
935           gp_Pnt      tgtP = tgtSurface->Value( tgtUV.X(), tgtUV.Y() );
936           SMDS_MeshNode* n = tgtMeshDS->AddNode( tgtP.X(), tgtP.Y(), tgtP.Z() );
937           switch ( srcNode->GetPosition()->GetTypeOfPosition() )
938           {
939           case SMDS_TOP_FACE: {
940             tgtMeshDS->SetNodeOnFace( n, helper.GetSubShapeID(), tgtUV.X(), tgtUV.Y() );
941             break;
942           }
943           case SMDS_TOP_EDGE: {
944             TopoDS_Shape srcEdge = srcHelper.GetSubShapeByNode( srcNode, srcHelper.GetMeshDS() );
945             TopoDS_Edge  tgtEdge = TopoDS::Edge( shape2ShapeMap( srcEdge, /*isSrc=*/true ));
946             double U = Precision::Infinite();
947             helper.CheckNodeU( tgtEdge, n, U, Precision::PConfusion());
948             tgtMeshDS->SetNodeOnEdge( n, TopoDS::Edge( tgtEdge ), U );
949             break;
950           }
951           case SMDS_TOP_VERTEX: {
952             TopoDS_Shape srcV = srcHelper.GetSubShapeByNode( srcNode, srcHelper.GetMeshDS() );
953             TopoDS_Shape tgtV = shape2ShapeMap( srcV, /*isSrc=*/true );
954             tgtMeshDS->SetNodeOnVertex( n, TopoDS::Vertex( tgtV ));
955             break;
956           }
957           default:;
958           }
959           srcN_tgtN->second = n;
960         }
961         tgtNodes[i] = srcN_tgtN->second;
962       }
963       // create a new face (with reversed orientation)
964       switch ( nbN )
965       {
966       case 3: helper.AddFace(tgtNodes[0], tgtNodes[2], tgtNodes[1]); break;
967       case 4: helper.AddFace(tgtNodes[0], tgtNodes[3], tgtNodes[2], tgtNodes[1]); break;
968       }
969     }  // loop on all mesh faces on srcFace
970
971     return true;
972   }
973
974   //================================================================================
975   /*!
976    * \brief Perform projection in case of quadrilateral faces
977    */
978   //================================================================================
979
980   bool projectQuads(const TopoDS_Face&                 tgtFace,
981                     const TopoDS_Face&                 srcFace,
982                     const TSideVector&                 tgtWires,
983                     const TSideVector&                 srcWires,
984                     const TAssocTool::TShapeShapeMap&  shape2ShapeMap,
985                     TAssocTool::TNodeNodeMap&          src2tgtNodes,
986                     const bool                         is1DComputed)
987   {
988     // SMESH_Mesh * tgtMesh = tgtWires[0]->GetMesh();
989     // SMESH_Mesh * srcMesh = srcWires[0]->GetMesh();
990     // //SMESHDS_Mesh * tgtMeshDS = tgtMesh->GetMeshDS();
991     // SMESHDS_Mesh * srcMeshDS = srcMesh->GetMeshDS();
992
993     // if ( srcWires[0]->NbEdges() != 4 )
994     //   return false;
995     // if ( !is1DComputed )
996     //   return false;
997     // for ( int iE = 0; iE < 4; ++iE )
998     // {
999     //   SMESHDS_SubMesh* sm = srcMeshDS->MeshElements( srcWires[0]->Edge( iE ));
1000     //   if ( !sm ) return false;
1001     //   if ( sm->NbNodes() + sm->NbElements() == 0 ) return false;
1002     // }
1003     // if ( BRepAdaptor_Surface( tgtFace ).GetType() != GeomAbs_Plane )
1004     //   return false;
1005     // // if ( BRepAdaptor_Surface( tgtFace ).GetType() == GeomAbs_Plane &&
1006     // //      BRepAdaptor_Surface( srcFace ).GetType() == GeomAbs_Plane )
1007     // //   return false; // too easy
1008
1009     // // load EDGEs to SMESH_Block
1010
1011     // SMESH_Block block;
1012     // TopTools_IndexedMapOfOrientedShape blockSubShapes;
1013     // {
1014     //   const TopoDS_Solid& box = srcMesh->PseudoShape();
1015     //   TopoDS_Shell shell = TopoDS::Shell( TopExp_Explorer( box, TopAbs_SHELL ).Current() );
1016     //   TopoDS_Vertex v;
1017     //   block.LoadBlockShapes( shell, v, v, blockSubShapes ); // fill all since operator[] is missing
1018     // }
1019     // const SMESH_Block::TShapeID srcFaceBID = SMESH_Block::ID_Fxy0;
1020     // const SMESH_Block::TShapeID tgtFaceBID = SMESH_Block::ID_Fxy1;
1021     // vector< int > edgeBID;
1022     // block.GetFaceEdgesIDs( srcFaceBID, edgeBID ); // u0, u1, 0v, 1v
1023     // blockSubShapes.Substitute( edgeBID[0], srcWires[0]->Edge(0) );
1024     // blockSubShapes.Substitute( edgeBID[1], srcWires[0]->Edge(2) );
1025     // blockSubShapes.Substitute( edgeBID[2], srcWires[0]->Edge(3) );
1026     // blockSubShapes.Substitute( edgeBID[3], srcWires[0]->Edge(1) );
1027     // block.GetFaceEdgesIDs( tgtFaceBID, edgeBID ); // u0, u1, 0v, 1v
1028     // blockSubShapes.Substitute( edgeBID[0], tgtWires[0]->Edge(0) );
1029     // blockSubShapes.Substitute( edgeBID[1], tgtWires[0]->Edge(2) );
1030     // blockSubShapes.Substitute( edgeBID[2], tgtWires[0]->Edge(3) );
1031     // blockSubShapes.Substitute( edgeBID[3], tgtWires[0]->Edge(1) );
1032     // block.LoadFace( srcFace, srcFaceBID, blockSubShapes );
1033     // block.LoadFace( tgtFace, tgtFaceBID, blockSubShapes );
1034
1035     // // remember connectivity of new faces in terms of ( node-or-XY )
1036
1037     // typedef std::pair< const SMDS_MeshNode*, gp_XYZ > TNodeOrXY; // node-or-XY
1038     // typedef std::vector< TNodeOrXY* >                 TFaceConn; // face connectivity
1039     // std::vector< TFaceConn >                    newFacesVec;     // connectivity of all faces
1040     // std::map< const SMDS_MeshNode*, TNodeOrXY > srcNode2tgtNXY;  // src node -> node-or-XY
1041
1042     // TAssocTool::TNodeNodeMap::iterator                                       srcN_tgtN;
1043     // std::map< const SMDS_MeshNode*, TNodeOrXY >::iterator                    srcN_tgtNXY;
1044     // std::pair< std::map< const SMDS_MeshNode*, TNodeOrXY >::iterator, bool > n2n_isNew;
1045     // TNodeOrXY nullNXY( (SMDS_MeshNode*)NULL, gp_XYZ(0,0,0) );
1046
1047     // SMESHDS_SubMesh* srcSubDS = srcMeshDS->MeshElements( srcFace );
1048     // newFacesVec.resize( srcSubDS->NbElements() );
1049     // int iFaceSrc = 0;
1050
1051     // SMDS_ElemIteratorPtr elemIt = srcSubDS->GetElements();
1052     // while ( elemIt->more() ) // loop on all mesh faces on srcFace
1053     // {
1054     //   const SMDS_MeshElement* elem = elemIt->next();
1055     //   TFaceConn& tgtNodes = newFacesVec[ iFaceSrc++ ];
1056
1057     //   const int nbN = elem->NbCornerNodes(); 
1058     //   tgtNodes.resize( nbN );
1059     //   for ( int i = 0; i < nbN; ++i ) // loop on nodes of the source element
1060     //   {
1061     //     const SMDS_MeshNode* srcNode = elem->GetNode(i);
1062     //     n2n_isNew = srcNode2tgtNXY.insert( make_pair( srcNode, nullNXY ));
1063     //     TNodeOrXY & tgtNodeOrXY = n2n_isNew.first->second;
1064     //     if ( n2n_isNew.second ) // new src node encounters
1065     //     {
1066     //       srcN_tgtN = src2tgtNodes.find( srcNode );
1067     //       if ( srcN_tgtN != src2tgtNodes.end() )
1068     //       {
1069     //         tgtNodeOrXY.first = srcN_tgtN->second; // tgt node exists
1070     //       }
1071     //       else 
1072     //       {
1073     //         // find XY of src node within the quadrilateral srcFace
1074     //         if ( !block.ComputeParameters( SMESH_TNodeXYZ( srcNode ),
1075     //                                        tgtNodeOrXY.second, srcFaceBID ))
1076     //           return false;
1077     //       }
1078     //     }
1079     //     tgtNodes[ i ] = & tgtNodeOrXY;
1080     //   }
1081     // }
1082
1083     // // as all XY are computed, create tgt nodes and faces
1084
1085     // SMESH_MesherHelper helper( *tgtMesh );
1086     // helper.SetSubShape( tgtFace );
1087     // if ( is1DComputed )
1088     //   helper.IsQuadraticSubMesh( tgtFace );
1089     // else
1090     //   helper.SetIsQuadratic( srcSubDS->GetElements()->next()->IsQuadratic() );
1091     // helper.SetElementsOnShape( true );
1092     // Handle(Geom_Surface) tgtSurface = BRep_Tool::Surface( tgtFace );
1093
1094     // SMESH_MesherHelper srcHelper( *srcMesh );
1095     // srcHelper.SetSubShape( srcFace );
1096
1097     // vector< const SMDS_MeshNode* > tgtNodes;
1098     // gp_XY uv;
1099
1100     // for ( size_t iFaceTgt = 0; iFaceTgt < newFacesVec.size(); ++iFaceTgt )
1101     // {
1102     //   TFaceConn& tgtConn = newFacesVec[ iFaceTgt ];
1103     //   tgtNodes.resize( tgtConn.size() );
1104     //   for ( size_t iN = 0; iN < tgtConn.size(); ++iN )
1105     //   {
1106     //     const SMDS_MeshNode* & tgtN = tgtConn[ iN ]->first;
1107     //     if ( !tgtN ) // create a node
1108     //     {
1109     //       if ( !block.FaceUV( tgtFaceBID, tgtConn[iN]->second, uv ))
1110     //         return false;
1111     //       gp_Pnt p = tgtSurface->Value( uv.X(), uv.Y() );
1112     //       tgtN = helper.AddNode( p.X(), p.Y(), p.Z(), uv.X(), uv.Y() );
1113     //     }
1114     //     tgtNodes[ tgtNodes.size() - iN - 1] = tgtN; // reversed orientation
1115     //   }
1116     //   switch ( tgtNodes.size() )
1117     //   {
1118     //   case 3: helper.AddFace(tgtNodes[0], tgtNodes[1], tgtNodes[2]); break;
1119     //   case 4: helper.AddFace(tgtNodes[0], tgtNodes[1], tgtNodes[2], tgtNodes[3]); break;
1120     //   default:
1121     //     if ( tgtNodes.size() > 4 )
1122     //       helper.AddPolygonalFace( tgtNodes );
1123     //   }
1124     // }
1125     return false; //true;
1126
1127   } // bool projectQuads(...)
1128
1129   //================================================================================
1130   /*!
1131    * \brief Fix bad faces by smoothing
1132    */
1133   //================================================================================
1134
1135   bool fixDistortedFaces( SMESH_MesherHelper& helper,
1136                           TSideVector&        tgtWires )
1137   {
1138     SMESH_subMesh* faceSM = helper.GetMesh()->GetSubMesh( helper.GetSubShape() );
1139
1140     if ( helper.IsDistorted2D( faceSM, /*checkUV=*/true ))
1141     {
1142       SMESH_MeshEditor editor( helper.GetMesh() );
1143       SMESHDS_SubMesh* smDS = faceSM->GetSubMeshDS();
1144       const TopoDS_Face&  F = TopoDS::Face( faceSM->GetSubShape() );
1145
1146       TIDSortedElemSet faces;
1147       SMDS_ElemIteratorPtr faceIt = smDS->GetElements();
1148       for ( faceIt = smDS->GetElements(); faceIt->more(); )
1149         faces.insert( faces.end(), faceIt->next() );
1150
1151       // choose smoothing algo
1152       //SMESH_MeshEditor:: SmoothMethod algo = SMESH_MeshEditor::CENTROIDAL;
1153       bool isConcaveBoundary = false;
1154       for ( size_t iW = 0; iW < tgtWires.size() && !isConcaveBoundary; ++iW )
1155       {
1156         TopoDS_Edge prevEdge = tgtWires[iW]->Edge( tgtWires[iW]->NbEdges() - 1 );
1157         for ( int iE = 0; iE < tgtWires[iW]->NbEdges() && !isConcaveBoundary; ++iE )
1158         {
1159           double angle = helper.GetAngle( prevEdge, tgtWires[iW]->Edge( iE ),
1160                                           F,        tgtWires[iW]->FirstVertex( iE ));
1161           isConcaveBoundary = ( angle < -5. * M_PI / 180. );
1162
1163           prevEdge = tgtWires[iW]->Edge( iE );
1164         }
1165       }
1166       SMESH_MeshEditor:: SmoothMethod algo =
1167         isConcaveBoundary ? SMESH_MeshEditor::CENTROIDAL : SMESH_MeshEditor::LAPLACIAN;
1168
1169       // smooth in 2D or 3D?
1170       TopLoc_Location loc;
1171       Handle(Geom_Surface) surface = BRep_Tool::Surface( F, loc );
1172       bool isPlanar = GeomLib_IsPlanarSurface( surface ).IsPlanar();
1173
1174       // smoothing
1175       set<const SMDS_MeshNode*> fixedNodes;
1176       editor.Smooth( faces, fixedNodes, algo, /*nbIterations=*/ 10,
1177                      /*theTgtAspectRatio=*/1.0, /*the2D=*/!isPlanar);
1178
1179       helper.ToFixNodeParameters( true );
1180
1181       return !helper.IsDistorted2D( faceSM, /*checkUV=*/true );
1182     }
1183     return true;
1184   }
1185
1186   typedef list< pair< const SMDS_MeshNode*, const BRepMesh_Triangle* > > TNodeTriaList;
1187
1188   //================================================================================
1189   /*!
1190    * \brief Add in-FACE nodes surrounding a given node to a queue
1191    */
1192   //================================================================================
1193
1194   void addCloseNodes( const SMDS_MeshNode*     srcNode,
1195                       const BRepMesh_Triangle* bmTria,
1196                       const int                srcFaceID,
1197                       TNodeTriaList &          noTriQueue )
1198   {
1199     // find in-FACE nodes
1200     SMDS_ElemIteratorPtr elems = srcNode->GetInverseElementIterator(SMDSAbs_Face);
1201     while ( elems->more() )
1202     {
1203       const SMDS_MeshElement* elem = elems->next();
1204       if ( elem->getshapeId() == srcFaceID )
1205       {
1206         for ( int i = 0, nb = elem->NbNodes(); i < nb; ++i )
1207         {
1208           const SMDS_MeshNode* n = elem->GetNode( i );
1209           if ( !n->isMarked() )
1210             noTriQueue.push_back( make_pair( n, bmTria ));
1211         }
1212       }
1213     }
1214   }
1215
1216   //================================================================================
1217   /*!
1218    * \brief Find a delauney triangle containing a given 2D point and return
1219    *        barycentric coordinates within the found triangle
1220    */
1221   //================================================================================
1222
1223   const BRepMesh_Triangle* findTriangle( const gp_XY&                            uv,
1224                                          const BRepMesh_Triangle*                bmTria,
1225                                          Handle(BRepMesh_DataStructureOfDelaun)& triaDS,
1226                                          double                                  bc[3] )
1227   {
1228     int   nodeIDs[3];
1229     gp_XY nodeUVs[3];
1230     int   linkIDs[3];
1231     Standard_Boolean ori[3];
1232
1233     while ( bmTria )
1234     {
1235       // check bmTria
1236
1237       triaDS->ElementNodes( *bmTria, nodeIDs );
1238       nodeUVs[0] = triaDS->GetNode( nodeIDs[0] ).Coord();
1239       nodeUVs[1] = triaDS->GetNode( nodeIDs[1] ).Coord();
1240       nodeUVs[2] = triaDS->GetNode( nodeIDs[2] ).Coord();
1241
1242       SMESH_MeshAlgos::GetBarycentricCoords( uv,
1243                                              nodeUVs[0], nodeUVs[1], nodeUVs[2],
1244                                              bc[0], bc[1] );
1245       if ( bc[0] >= 0 && bc[1] >= 0 && bc[0] + bc[1] <= 1 )
1246       {
1247         bc[2] = 1 - bc[0] - bc[1];
1248         return bmTria;
1249       }
1250
1251       // look for a neighbor triangle, which is adjacent to a link intersected
1252       // by a segment( triangle center -> uv )
1253
1254       gp_XY gc = ( nodeUVs[0] + nodeUVs[1] + nodeUVs[2] ) / 3.;
1255       gp_XY seg = uv - gc;
1256
1257       bmTria->Edges( linkIDs, ori );
1258       int triaID = triaDS->IndexOf( *bmTria );
1259       bmTria = 0;
1260
1261       for ( int i = 0; i < 3; ++i )
1262       {
1263         const BRepMesh_PairOfIndex & triIDs = triaDS->ElementsConnectedTo( linkIDs[i] );
1264         if ( triIDs.Extent() < 2 )
1265           continue; // no neighbor triangle
1266
1267         // check if a link intersects gc2uv
1268         const BRepMesh_Edge & link = triaDS->GetLink( linkIDs[i] );
1269         const BRepMesh_Vertex & n1 = triaDS->GetNode( link.FirstNode() );
1270         const BRepMesh_Vertex & n2 = triaDS->GetNode( link.LastNode() );
1271         gp_XY uv1 = n1.Coord();
1272         gp_XY lin = n2.Coord() - uv1; // link direction
1273
1274         double crossSegLin = seg ^ lin;
1275         if ( Abs( crossSegLin ) < std::numeric_limits<double>::min() )
1276           continue; // parallel
1277
1278         double uSeg = ( uv1 - gc ) ^ lin / crossSegLin;
1279         if ( 0. <= uSeg && uSeg <= 1. )
1280         {
1281           bmTria = & triaDS->GetElement( triIDs.Index( 1 + ( triIDs.Index(1) == triaID )));
1282           break;
1283         }
1284       }
1285     }
1286     return bmTria;
1287   }
1288
1289   //================================================================================
1290   /*!
1291    * \brief Morph mesh on the target face to lie within FACE boundary w/o distortion
1292    *
1293    * algo:
1294    * - make a CDT on the src FACE
1295    * - find a triangle containing a src node and get its barycentric coordinates
1296    * - move the node to a point with the same barycentric coordinates in a corresponding
1297    *   tgt triangle
1298    */
1299   //================================================================================
1300
1301   bool morph( SMESH_MesherHelper&             tgtHelper,
1302               const TopoDS_Face&              tgtFace,
1303               const TopoDS_Face&              srcFace,
1304               const TSideVector&              tgtWires,
1305               const TSideVector&              srcWires,
1306               const TAssocTool::TNodeNodeMap& src2tgtNodes )
1307   {
1308     if ( srcWires.size() != tgtWires.size() ) return false;
1309     if ( srcWires.size() == 1 ) return false; // tmp
1310
1311     // count boundary points
1312     int iP = 1, nbP = 0;
1313     for ( size_t iW = 0; iW < srcWires.size(); ++iW )
1314       nbP += srcWires[iW]->NbPoints() - 1; // 1st and last points coincide
1315
1316     // fill boundary points
1317     BRepMesh::Array1OfVertexOfDelaun srcVert( 1, 1 + nbP ), tgtVert( 1, 1 + nbP );
1318     vector< const SMDS_MeshNode* > bndSrcNodes( nbP + 1 ); bndSrcNodes[0] = 0;
1319     BRepMesh_Vertex v( 0, 0, BRepMesh_Frontier );
1320     for ( size_t iW = 0; iW < srcWires.size(); ++iW )
1321     {
1322       const UVPtStructVec& srcPnt = srcWires[iW]->GetUVPtStruct();
1323       const UVPtStructVec& tgtPnt = tgtWires[iW]->GetUVPtStruct();
1324       if ( srcPnt.size() != tgtPnt.size() ) return false;
1325
1326       for ( int i = 0, nb = srcPnt.size() - 1;  i < nb;  ++i, ++iP )
1327       {
1328         bndSrcNodes[ iP ]  = srcPnt[i].node;
1329         srcPnt[i].node->setIsMarked( true );
1330
1331         v.ChangeCoord() = srcPnt[i].UV();
1332         srcVert( iP )   = v;
1333         v.ChangeCoord() = tgtPnt[i].UV();
1334         tgtVert( iP )   = v;
1335       }
1336     }
1337     // triangulate the srcFace in 2D
1338     BRepMesh_Delaun delauney( srcVert );
1339     Handle(BRepMesh_DataStructureOfDelaun) triaDS = delauney.Result();
1340
1341     Handle(ShapeAnalysis_Surface) tgtSurface = tgtHelper.GetSurface( tgtFace );
1342     SMESHDS_Mesh* srcMesh = srcWires[0]->GetMesh()->GetMeshDS();
1343     SMESHDS_Mesh* tgtMesh = tgtHelper.GetMeshDS();
1344     const SMDS_MeshNode *srcNode, *tgtNode;
1345     const BRepMesh_Triangle *bmTria;
1346
1347     // un-mark internal src nodes; later we will mark moved nodes
1348     SMDS_NodeIteratorPtr nIt = srcMesh->MeshElements( srcFace )->GetNodes();
1349     if ( !nIt || !nIt->more() ) return true;
1350     while ( nIt->more() )
1351       ( srcNode = nIt->next() )->setIsMarked( false );
1352
1353     // initialize a queue of nodes with starting triangles
1354     const int srcFaceID = srcNode->getshapeId();
1355     TNodeTriaList noTriQueue;
1356     size_t iBndSrcN = 1;
1357     for ( ; iBndSrcN < bndSrcNodes.size() &&  noTriQueue.empty();  ++iBndSrcN )
1358     {
1359       // get a triangle
1360       const BRepMesh::ListOfInteger & linkIds = triaDS->LinksConnectedTo( iBndSrcN );
1361       const BRepMesh_PairOfIndex &    triaIds = triaDS->ElementsConnectedTo( linkIds.First() );
1362       const BRepMesh_Triangle&           tria = triaDS->GetElement( triaIds.Index(1) );
1363
1364       addCloseNodes( bndSrcNodes[ iBndSrcN ], &tria, srcFaceID, noTriQueue );
1365     }
1366
1367     // Move tgt nodes
1368
1369     double bc[3]; // barycentric coordinates
1370     int    nodeIDs[3];
1371     bool   checkUV = true;
1372     const SMDS_FacePosition* pos;
1373
1374     while ( !noTriQueue.empty() )
1375     {
1376       srcNode = noTriQueue.front().first;
1377       bmTria  = noTriQueue.front().second;
1378       noTriQueue.pop_front();
1379       if ( srcNode->isMarked() )
1380         continue;
1381       srcNode->setIsMarked( true );
1382
1383       // find a delauney triangle containing the src node
1384       gp_XY uv = tgtHelper.GetNodeUV( srcFace, srcNode, NULL, &checkUV );
1385       bmTria = findTriangle( uv, bmTria, triaDS, bc );
1386       if ( !bmTria )
1387         continue;
1388
1389       // compute new coordinates for a corresponding tgt node
1390       gp_XY uvNew( 0., 0. ), nodeUV;
1391       triaDS->ElementNodes( *bmTria, nodeIDs );
1392       for ( int i = 0; i < 3; ++i )
1393         uvNew += bc[i] * tgtVert( nodeIDs[i]).Coord();
1394       gp_Pnt xyz = tgtSurface->Value( uvNew );
1395
1396       // find and move tgt node
1397       TAssocTool::TNodeNodeMap::const_iterator n2n = src2tgtNodes.find( srcNode );
1398       if ( n2n == src2tgtNodes.end() ) continue;
1399       tgtNode = n2n->second;
1400       tgtMesh->MoveNode( tgtNode, xyz.X(), xyz.Y(), xyz.Z() );
1401
1402       if (( pos = dynamic_cast< const SMDS_FacePosition* >( tgtNode->GetPosition() )))
1403         const_cast<SMDS_FacePosition*>( pos )->SetParameters( uvNew.X(), uvNew.Y() );
1404
1405       addCloseNodes( srcNode, bmTria, srcFaceID, noTriQueue );
1406
1407       // assure that all src nodes are visited
1408       for ( ; iBndSrcN < bndSrcNodes.size() &&  noTriQueue.empty();  ++iBndSrcN )
1409       {
1410         const BRepMesh::ListOfInteger & linkIds = triaDS->LinksConnectedTo( iBndSrcN );
1411         const BRepMesh_PairOfIndex &    triaIds = triaDS->ElementsConnectedTo( linkIds.First() );
1412         const BRepMesh_Triangle&           tria = triaDS->GetElement( triaIds.Index(1) );
1413         addCloseNodes( bndSrcNodes[ iBndSrcN ], &tria, srcFaceID, noTriQueue );
1414       }
1415     }
1416
1417     return true;
1418   }
1419
1420   //=======================================================================
1421   /*
1422    * Set initial association of VERTEXes for the case of projection
1423    * from a quadrangle FACE to a closed FACE, where opposite src EDGEs
1424    * have different nb of segments
1425    */
1426   //=======================================================================
1427
1428   void initAssoc4Quad2Closed(const TopoDS_Shape&          tgtFace,
1429                              SMESH_MesherHelper&          tgtHelper,
1430                              const TopoDS_Shape&          srcFace,
1431                              SMESH_Mesh*                  srcMesh,
1432                              TAssocTool::TShapeShapeMap & assocMap)
1433   {
1434     if ( !tgtHelper.HasRealSeam() || srcFace.ShapeType() != TopAbs_FACE )
1435       return; // no seam edge
1436     list< TopoDS_Edge > tgtEdges, srcEdges;
1437     list< int > tgtNbEW, srcNbEW;
1438     int tgtNbW = SMESH_Block::GetOrderedEdges( TopoDS::Face( tgtFace ), tgtEdges, tgtNbEW );
1439     int srcNbW = SMESH_Block::GetOrderedEdges( TopoDS::Face( srcFace ), srcEdges, srcNbEW );
1440     if ( tgtNbW != 1 || srcNbW != 1 ||
1441          tgtNbEW.front() != 4 || srcNbEW.front() != 4 )
1442       return; // not quads
1443
1444     int srcNbSeg[4];
1445     list< TopoDS_Edge >::iterator edgeS = srcEdges.begin(), edgeT = tgtEdges.begin();
1446     for ( int i = 0; edgeS != srcEdges.end(); ++i, ++edgeS )
1447       if ( SMESHDS_SubMesh* sm = srcMesh->GetMeshDS()->MeshElements( *edgeS ))
1448         srcNbSeg[ i ] = sm->NbNodes();
1449       else
1450         return; // not meshed
1451     if ( srcNbSeg[0] == srcNbSeg[2] && srcNbSeg[1] == srcNbSeg[3] )
1452       return; // same nb segments
1453     if ( srcNbSeg[0] != srcNbSeg[2] && srcNbSeg[1] != srcNbSeg[3] )
1454       return; // all different nb segments
1455
1456     edgeS = srcEdges.begin();
1457     if ( srcNbSeg[0] != srcNbSeg[2] )
1458       ++edgeS;
1459     TAssocTool::InsertAssociation( tgtHelper.IthVertex( 0,*edgeT ),
1460                                    tgtHelper.IthVertex( 0,*edgeS ), assocMap );
1461     TAssocTool::InsertAssociation( tgtHelper.IthVertex( 1,*edgeT ),
1462                                    tgtHelper.IthVertex( 1,*edgeS ), assocMap );
1463   }
1464
1465 } // namespace
1466
1467
1468 //=======================================================================
1469 //function : Compute
1470 //purpose  :
1471 //=======================================================================
1472
1473 bool StdMeshers_Projection_2D::Compute(SMESH_Mesh& theMesh, const TopoDS_Shape& theShape)
1474 {
1475   _src2tgtNodes.clear();
1476
1477   if ( !_sourceHypo )
1478     return false;
1479
1480   SMESH_Mesh * srcMesh = _sourceHypo->GetSourceMesh();
1481   SMESH_Mesh * tgtMesh = & theMesh;
1482   if ( !srcMesh )
1483     srcMesh = tgtMesh;
1484
1485   SMESHDS_Mesh * meshDS = theMesh.GetMeshDS();
1486   SMESH_MesherHelper helper( theMesh );
1487
1488   // ---------------------------
1489   // Make sub-shapes association
1490   // ---------------------------
1491
1492   TopoDS_Face   tgtFace = TopoDS::Face( theShape.Oriented(TopAbs_FORWARD));
1493   TopoDS_Shape srcShape = _sourceHypo->GetSourceFace().Oriented(TopAbs_FORWARD);
1494
1495   helper.SetSubShape( tgtFace );
1496
1497   TAssocTool::TShapeShapeMap shape2ShapeMap;
1498   TAssocTool::InitVertexAssociation( _sourceHypo, shape2ShapeMap );
1499   if ( shape2ShapeMap.IsEmpty() )
1500     initAssoc4Quad2Closed( tgtFace, helper, srcShape, srcMesh, shape2ShapeMap );
1501   if ( !TAssocTool::FindSubShapeAssociation( tgtFace, tgtMesh, srcShape, srcMesh,
1502                                              shape2ShapeMap)  ||
1503        !shape2ShapeMap.IsBound( tgtFace ))
1504   {
1505     if ( srcShape.ShapeType() == TopAbs_FACE )
1506     {
1507       int nbE1 = helper.Count( tgtFace, TopAbs_EDGE, /*ignoreSame=*/true );
1508       int nbE2 = helper.Count( srcShape, TopAbs_EDGE, /*ignoreSame=*/true );
1509       if ( nbE1 != nbE2 )
1510         return error(COMPERR_BAD_SHAPE,
1511                      SMESH_Comment("Different number of edges in source and target faces: ")
1512                      << nbE2 << " and " << nbE1 );
1513     }
1514     return error(COMPERR_BAD_SHAPE,"Topology of source and target faces seems different" );
1515   }
1516   TopoDS_Face srcFace = TopoDS::Face( shape2ShapeMap( tgtFace ).Oriented(TopAbs_FORWARD));
1517
1518   // ----------------------------------------------
1519   // Assure that mesh on a source Face is computed
1520   // ----------------------------------------------
1521
1522   SMESH_subMesh* srcSubMesh = srcMesh->GetSubMesh( srcFace );
1523   SMESH_subMesh* tgtSubMesh = tgtMesh->GetSubMesh( tgtFace );
1524
1525   string srcMeshError;
1526   if ( tgtMesh == srcMesh ) {
1527     if ( !TAssocTool::MakeComputed( srcSubMesh ))
1528       srcMeshError = TAssocTool::SourceNotComputedError( srcSubMesh, this );
1529   }
1530   else {
1531     if ( !srcSubMesh->IsMeshComputed() )
1532       srcMeshError = TAssocTool::SourceNotComputedError();
1533   }
1534   if ( !srcMeshError.empty() )
1535     return error(COMPERR_BAD_INPUT_MESH, srcMeshError );
1536
1537   // ===========
1538   // Projection
1539   // ===========
1540
1541   // get ordered src and tgt EDGEs
1542   TSideVector srcWires, tgtWires;
1543   bool is1DComputed = false; // if any tgt EDGE is meshed
1544   TError err = getWires( tgtFace, srcFace, tgtMesh, srcMesh,
1545                          shape2ShapeMap, srcWires, tgtWires, _src2tgtNodes, is1DComputed );
1546   if ( err && !err->IsOK() )
1547     return error( err );
1548
1549   bool projDone = false;
1550
1551   if ( !projDone )
1552   {
1553     // try to project from the same face with different location
1554     projDone = projectPartner( tgtFace, srcFace, tgtWires, srcWires,
1555                                shape2ShapeMap, _src2tgtNodes, is1DComputed );
1556   }
1557   if ( !projDone )
1558   {
1559     // projection in case if the faces are similar in 2D space
1560     projDone = projectBy2DSimilarity( tgtFace, srcFace, tgtWires, srcWires,
1561                                       shape2ShapeMap, _src2tgtNodes, is1DComputed );
1562   }
1563   if ( !projDone )
1564   {
1565     // projection in case of quadrilateral faces
1566     // NOT IMPLEMENTED, returns false
1567     projDone = projectQuads( tgtFace, srcFace, tgtWires, srcWires,
1568                              shape2ShapeMap, _src2tgtNodes, is1DComputed);
1569   }
1570
1571   // it will remove mesh built on edges and vertices in failure case
1572   MeshCleaner cleaner( tgtSubMesh );
1573
1574   if ( !projDone )
1575   {
1576     _src2tgtNodes.clear();
1577     // --------------------
1578     // Prepare to mapping 
1579     // --------------------
1580
1581     // Check if node projection to a face is needed
1582     Bnd_B2d uvBox;
1583     SMDS_ElemIteratorPtr faceIt = srcSubMesh->GetSubMeshDS()->GetElements();
1584     set< const SMDS_MeshNode* > faceNodes;
1585     for ( ; faceNodes.size() < 3 && faceIt->more();  ) {
1586       const SMDS_MeshElement* face = faceIt->next();
1587       SMDS_ElemIteratorPtr nodeIt = face->nodesIterator();
1588       while ( nodeIt->more() ) {
1589         const SMDS_MeshNode* node = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
1590         if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE &&
1591              faceNodes.insert( node ).second )
1592           uvBox.Add( helper.GetNodeUV( srcFace, node ));
1593       }
1594     }
1595     bool toProjectNodes = false;
1596     if ( faceNodes.size() == 1 )
1597       toProjectNodes = ( uvBox.IsVoid() || uvBox.CornerMin().IsEqual( gp_XY(0,0), 1e-12 ));
1598     else if ( faceNodes.size() > 1 )
1599       toProjectNodes = ( uvBox.IsVoid() || uvBox.SquareExtent() < DBL_MIN );
1600
1601     // Find the corresponding source and target vertex
1602     // and <theReverse> flag needed to call mapper.Apply()
1603
1604     TopoDS_Vertex srcV1, tgtV1;
1605     bool reverse = false;
1606
1607     TopExp_Explorer vSrcExp( srcFace, TopAbs_VERTEX );
1608     srcV1 = TopoDS::Vertex( vSrcExp.Current() );
1609     tgtV1 = TopoDS::Vertex( shape2ShapeMap( srcV1, /*isSrc=*/true ));
1610
1611     list< TopoDS_Edge > tgtEdges, srcEdges;
1612     list< int > nbEdgesInWires;
1613     SMESH_Block::GetOrderedEdges( tgtFace, tgtEdges, nbEdgesInWires, tgtV1 );
1614     SMESH_Block::GetOrderedEdges( srcFace, srcEdges, nbEdgesInWires, srcV1 );
1615
1616     if ( nbEdgesInWires.front() > 1 ) // possible to find out orientation
1617     {
1618       TopoDS_Edge srcE1 = srcEdges.front(), tgtE1 = tgtEdges.front();
1619       TopoDS_Shape srcE1bis = shape2ShapeMap( tgtE1 );
1620       reverse = ( ! srcE1.IsSame( srcE1bis ));
1621       if ( reverse &&
1622            //_sourceHypo->HasVertexAssociation() &&
1623            nbEdgesInWires.front() > 2 &&
1624            helper.IsRealSeam( tgtEdges.front() ))
1625       {
1626         // projection to a face with seam EDGE; pb is that GetOrderedEdges()
1627         // always puts a seam EDGE first (if possible) and as a result
1628         // we can't use only theReverse flag to correctly associate source
1629         // and target faces in the mapper. Thus we select srcV1 so that
1630         // GetOrderedEdges() to return EDGEs in a needed order
1631         TopoDS_Face tgtFaceBis = tgtFace;
1632         TopTools_MapOfShape checkedVMap( tgtEdges.size() );
1633         checkedVMap.Add ( srcV1 );
1634         for ( vSrcExp.Next(); vSrcExp.More(); )
1635         {
1636           tgtFaceBis.Reverse();
1637           tgtEdges.clear();
1638           SMESH_Block::GetOrderedEdges( tgtFaceBis, tgtEdges, nbEdgesInWires, tgtV1 );
1639           bool ok = true;
1640           list< TopoDS_Edge >::iterator edgeS = srcEdges.begin(), edgeT = tgtEdges.begin();
1641           for ( ; edgeS != srcEdges.end() && ok ; ++edgeS, ++edgeT )
1642             ok = edgeT->IsSame( shape2ShapeMap( *edgeS, /*isSrc=*/true ));
1643           if ( ok )
1644             break; // FOUND!
1645
1646           reverse = !reverse;
1647           if ( reverse )
1648           {
1649             vSrcExp.Next();
1650             while ( vSrcExp.More() && !checkedVMap.Add( vSrcExp.Current() ))
1651               vSrcExp.Next();
1652           }
1653           else
1654           {
1655             srcV1 = TopoDS::Vertex( vSrcExp.Current() );
1656             tgtV1 = TopoDS::Vertex( shape2ShapeMap( srcV1, /*isSrc=*/true ));
1657             srcEdges.clear();
1658             SMESH_Block::GetOrderedEdges( srcFace, srcEdges, nbEdgesInWires, srcV1 );
1659           }
1660         }
1661       }
1662       // for the case: project to a closed face from a non-closed face w/o vertex assoc;
1663       // avoid projecting to a seam from two EDGEs with different nb nodes on them
1664       // ( test mesh_Projection_2D_01/B1 )
1665       if ( !_sourceHypo->HasVertexAssociation() &&
1666            nbEdgesInWires.front() > 2 &&
1667            helper.IsRealSeam( tgtEdges.front() ))
1668       {
1669         TopoDS_Shape srcEdge1 = shape2ShapeMap( tgtEdges.front() );
1670         list< TopoDS_Edge >::iterator srcEdge2 =
1671           std::find( srcEdges.begin(), srcEdges.end(), srcEdge1);
1672         list< TopoDS_Edge >::iterator srcEdge3 =
1673           std::find( srcEdges.begin(), srcEdges.end(), srcEdge1.Reversed());
1674         if ( srcEdge2 == srcEdges.end() || srcEdge3 == srcEdges.end() ) // srcEdge1 is not a seam
1675         {
1676           // find srcEdge2 which also will be projected to tgtEdges.front()
1677           for ( srcEdge2 = srcEdges.begin(); srcEdge2 != srcEdges.end(); ++srcEdge2 )
1678             if ( !srcEdge1.IsSame( *srcEdge2 ) &&
1679                  tgtEdges.front().IsSame( shape2ShapeMap( *srcEdge2, /*isSrc=*/true )))
1680               break;
1681           // compare nb nodes on srcEdge1 and srcEdge2
1682           if ( srcEdge2 != srcEdges.end() )
1683           {
1684             int nbN1 = 0, nbN2 = 0;
1685             if ( SMESHDS_SubMesh* sm = srcMesh->GetMeshDS()->MeshElements( srcEdge1 ))
1686               nbN1 = sm->NbNodes();
1687             if ( SMESHDS_SubMesh* sm = srcMesh->GetMeshDS()->MeshElements( *srcEdge2 ))
1688               nbN2 = sm->NbNodes();
1689             if ( nbN1 != nbN2 )
1690               srcV1 = helper.IthVertex( 1, srcEdges.front() );
1691           }
1692         }
1693       }
1694     }
1695     else if ( nbEdgesInWires.front() == 1 ) // a sole edge in a wire
1696     {
1697       TopoDS_Edge srcE1 = srcEdges.front(), tgtE1 = tgtEdges.front();
1698       for ( size_t iW = 0; iW < srcWires.size(); ++iW )
1699       {
1700         StdMeshers_FaceSidePtr srcWire = srcWires[iW];
1701         for ( int iE = 0; iE < srcWire->NbEdges(); ++iE )
1702           if ( srcE1.IsSame( srcWire->Edge( iE )))
1703           {
1704             reverse = ( tgtE1.Orientation() != tgtWires[iW]->Edge( iE ).Orientation() );
1705             break;
1706           }
1707       }
1708     }
1709     else
1710     {
1711       RETURN_BAD_RESULT("Bad result from SMESH_Block::GetOrderedEdges()");
1712     }
1713
1714     // Load pattern from the source face
1715     SMESH_Pattern mapper;
1716     mapper.Load( srcMesh, srcFace, toProjectNodes, srcV1, /*keepNodes=*/true );
1717     if ( mapper.GetErrorCode() != SMESH_Pattern::ERR_OK )
1718       return error(COMPERR_BAD_INPUT_MESH,"Can't load mesh pattern from the source face");
1719
1720     // --------------------
1721     // Perform 2D mapping
1722     // --------------------
1723
1724     // Compute mesh on a target face
1725
1726     mapper.Apply( tgtFace, tgtV1, reverse );
1727     if ( mapper.GetErrorCode() != SMESH_Pattern::ERR_OK ) {
1728       // std::ofstream file("/tmp/Pattern.smp" );
1729       // mapper.Save( file );
1730       return error("Can't apply source mesh pattern to the face");
1731     }
1732
1733     // Create the mesh
1734
1735     const bool toCreatePolygons = false, toCreatePolyedrs = false;
1736     mapper.MakeMesh( tgtMesh, toCreatePolygons, toCreatePolyedrs );
1737     if ( mapper.GetErrorCode() != SMESH_Pattern::ERR_OK )
1738       return error("Can't make mesh by source mesh pattern");
1739
1740     // fill _src2tgtNodes
1741     std::vector< const SMDS_MeshNode* > *srcNodes, *tgtNodes;
1742     mapper.GetInOutNodes( srcNodes, tgtNodes );
1743     size_t nbN = std::min( srcNodes->size(), tgtNodes->size() );
1744     for ( size_t i = 0; i < nbN; ++i )
1745       if ( (*srcNodes)[i] && (*tgtNodes)[i] )
1746         _src2tgtNodes.insert( make_pair( (*srcNodes)[i], (*tgtNodes)[i] ));
1747
1748
1749   } // end of projection using Pattern mapping
1750
1751   {
1752     // -------------------------------------------------------------------------
1753     // mapper doesn't take care of nodes already existing on edges and vertices,
1754     // so we must merge nodes created by it with existing ones
1755     // -------------------------------------------------------------------------
1756
1757     SMESH_MeshEditor::TListOfListOfNodes groupsOfNodes;
1758
1759     // Make groups of nodes to merge
1760
1761     // loop on EDGE and VERTEX sub-meshes of a target FACE
1762     SMESH_subMeshIteratorPtr smIt = tgtSubMesh->getDependsOnIterator(/*includeSelf=*/false,
1763                                                                      /*complexShapeFirst=*/false);
1764     while ( smIt->more() )
1765     {
1766       SMESH_subMesh*     sm = smIt->next();
1767       SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
1768       if ( !smDS || smDS->NbNodes() == 0 )
1769         continue;
1770       //if ( !is1DComputed && sm->GetSubShape().ShapeType() == TopAbs_EDGE )
1771       //  break;
1772
1773       if ( helper.IsDegenShape( sm->GetId() ) ) // to merge all nodes on degenerated
1774       {
1775         if ( sm->GetSubShape().ShapeType() == TopAbs_EDGE )
1776         {
1777           groupsOfNodes.push_back( list< const SMDS_MeshNode* >() );
1778           SMESH_subMeshIteratorPtr smDegenIt
1779             = sm->getDependsOnIterator(/*includeSelf=*/true,/*complexShapeFirst=*/false);
1780           while ( smDegenIt->more() )
1781             if (( smDS = smDegenIt->next()->GetSubMeshDS() ))
1782             {
1783               SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
1784               while ( nIt->more() )
1785                 groupsOfNodes.back().push_back( nIt->next() );
1786             }
1787         }
1788         continue; // do not treat sm of degen VERTEX
1789       }
1790
1791       // Sort new and old nodes of a sub-mesh separately
1792
1793       bool isSeam = helper.IsRealSeam( sm->GetId() );
1794
1795       enum { NEW_NODES = 0, OLD_NODES };
1796       map< double, const SMDS_MeshNode* > u2nodesMaps[2], u2nodesOnSeam;
1797       map< double, const SMDS_MeshNode* >::iterator u_oldNode, u_newNode, u_newOnSeam, newEnd;
1798       set< const SMDS_MeshNode* > seamNodes;
1799
1800       // mapper changed, no more "mapper puts on a seam edge nodes from 2 edges"
1801       if ( isSeam && ! getBoundaryNodes ( sm, tgtFace, u2nodesOnSeam, seamNodes ))
1802         ;//RETURN_BAD_RESULT("getBoundaryNodes() failed");
1803
1804       SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
1805       while ( nIt->more() )
1806       {
1807         const SMDS_MeshNode* node = nIt->next();
1808         bool isOld = isOldNode( node );
1809
1810         if ( !isOld && isSeam ) { // new node on a seam edge
1811           if ( seamNodes.count( node ) )
1812             continue; // node is already in the map
1813         }
1814
1815         // sort nodes on edges by their position
1816         map< double, const SMDS_MeshNode* > & pos2nodes = u2nodesMaps[isOld ? OLD_NODES : NEW_NODES];
1817         switch ( node->GetPosition()->GetTypeOfPosition() )
1818         {
1819         case  SMDS_TOP_VERTEX: {
1820           if ( !is1DComputed && !pos2nodes.empty() )
1821             u2nodesMaps[isOld ? NEW_NODES : OLD_NODES].insert( make_pair( 0, node ));
1822           else
1823             pos2nodes.insert( make_pair( 0, node ));
1824           break;
1825         }
1826         case  SMDS_TOP_EDGE:   {
1827           const SMDS_EdgePosition* pos =
1828             static_cast<const SMDS_EdgePosition*>(node->GetPosition());
1829           pos2nodes.insert( make_pair( pos->GetUParameter(), node ));
1830           break;
1831         }
1832         default:
1833           RETURN_BAD_RESULT("Wrong node position type: "<<
1834                             node->GetPosition()->GetTypeOfPosition());
1835         }
1836       }
1837       const bool mergeNewToOld =
1838         ( u2nodesMaps[ NEW_NODES ].size() == u2nodesMaps[ OLD_NODES ].size() );
1839       const bool mergeSeamToNew =
1840         ( u2nodesMaps[ NEW_NODES ].size() == u2nodesOnSeam.size() );
1841
1842       if ( !mergeNewToOld )
1843         if ( u2nodesMaps[ NEW_NODES ].size() > 0 &&
1844              u2nodesMaps[ OLD_NODES ].size() > 0 )
1845         {
1846           u_oldNode = u2nodesMaps[ OLD_NODES ].begin(); 
1847           newEnd    = u2nodesMaps[ OLD_NODES ].end();
1848           for ( ; u_oldNode != newEnd; ++u_oldNode )
1849             SMESH_Algo::addBadInputElement( u_oldNode->second );
1850           return error( COMPERR_BAD_INPUT_MESH,
1851                         SMESH_Comment( "Existing mesh mismatches the projected 2D mesh on " )
1852                         << ( sm->GetSubShape().ShapeType() == TopAbs_EDGE ? "edge" : "vertex" )
1853                         << " #" << sm->GetId() );
1854         }
1855       if ( isSeam && !mergeSeamToNew ) {
1856         const TopoDS_Shape& seam = sm->GetSubShape();
1857         if ( u2nodesMaps[ NEW_NODES ].size() > 0 &&
1858              u2nodesOnSeam.size()            > 0 &&
1859              seam.ShapeType() == TopAbs_EDGE )
1860         {
1861           int nbE1 = helper.Count( tgtFace, TopAbs_EDGE, /*ignoreSame=*/true );
1862           int nbE2 = helper.Count( srcFace, TopAbs_EDGE, /*ignoreSame=*/true );
1863           if ( nbE1 != nbE2 ) // 2 EDGEs are mapped to a seam EDGE
1864           {
1865             // find the 2 EDGEs of srcFace
1866             TopTools_DataMapIteratorOfDataMapOfShapeShape src2tgtIt( shape2ShapeMap._map2to1 );
1867             for ( ; src2tgtIt.More(); src2tgtIt.Next() )
1868               if ( seam.IsSame( src2tgtIt.Value() ))
1869                 SMESH_Algo::addBadInputElements
1870                   ( srcMesh->GetMeshDS()->MeshElements( src2tgtIt.Key() ));
1871             return error( COMPERR_BAD_INPUT_MESH,
1872                           "Different number of nodes on two edges projected to a seam edge" );
1873           }
1874         }
1875       }
1876
1877       // Make groups of nodes to merge
1878
1879       u_oldNode = u2nodesMaps[ OLD_NODES ].begin(); 
1880       u_newNode = u2nodesMaps[ NEW_NODES ].begin();
1881       newEnd    = u2nodesMaps[ NEW_NODES ].end();
1882       u_newOnSeam = u2nodesOnSeam.begin();
1883       if ( mergeNewToOld )
1884         for ( ; u_newNode != newEnd; ++u_newNode, ++u_oldNode )
1885         {
1886           groupsOfNodes.push_back( list< const SMDS_MeshNode* >() );
1887           groupsOfNodes.back().push_back( u_oldNode->second );
1888           groupsOfNodes.back().push_back( u_newNode->second );
1889           if ( mergeSeamToNew )
1890             groupsOfNodes.back().push_back( (u_newOnSeam++)->second );
1891         }
1892       else if ( mergeSeamToNew )
1893         for ( ; u_newNode != newEnd; ++u_newNode, ++u_newOnSeam )
1894         {
1895           groupsOfNodes.push_back( list< const SMDS_MeshNode* >() );
1896           groupsOfNodes.back().push_back( u_newNode->second );
1897           groupsOfNodes.back().push_back( u_newOnSeam->second );
1898         }
1899
1900     } // loop on EDGE and VERTEX submeshes of a target FACE
1901
1902     // Merge
1903
1904     SMESH_MeshEditor editor( tgtMesh );
1905     int nbFaceBeforeMerge = tgtSubMesh->GetSubMeshDS()->NbElements();
1906     editor.MergeNodes( groupsOfNodes );
1907     int nbFaceAtferMerge = tgtSubMesh->GetSubMeshDS()->NbElements();
1908     if ( nbFaceBeforeMerge != nbFaceAtferMerge && !helper.HasDegeneratedEdges() )
1909       return error(COMPERR_BAD_INPUT_MESH, "Probably invalid node parameters on geom faces");
1910
1911     // ----------------------------------------------------------------
1912     // The mapper can't create quadratic elements, so convert if needed
1913     // ----------------------------------------------------------------
1914
1915     SMDS_ElemIteratorPtr faceIt;
1916     faceIt         = srcSubMesh->GetSubMeshDS()->GetElements();
1917     bool srcIsQuad = faceIt->next()->IsQuadratic();
1918     faceIt         = tgtSubMesh->GetSubMeshDS()->GetElements();
1919     bool tgtIsQuad = faceIt->next()->IsQuadratic();
1920     if ( srcIsQuad && !tgtIsQuad )
1921     {
1922       TIDSortedElemSet tgtFaces;
1923       faceIt = tgtSubMesh->GetSubMeshDS()->GetElements();
1924       while ( faceIt->more() )
1925         tgtFaces.insert( tgtFaces.end(), faceIt->next() );
1926
1927       editor.ConvertToQuadratic(/*theForce3d=*/false, tgtFaces, false);
1928     }
1929   } // end of coincident nodes and quadratic elements treatment
1930
1931
1932   if ( !projDone || is1DComputed )
1933     // ----------------------------------------------------------------
1934     // The mapper can create distorted faces by placing nodes out of the FACE
1935     // boundary, also bad face can be created if EDGEs already discretized
1936     // --> fix bad faces by smoothing
1937     // ----------------------------------------------------------------
1938     if ( helper.IsDistorted2D( tgtSubMesh, /*checkUV=*/false ))
1939     {
1940       morph( helper, tgtFace, srcFace, tgtWires, srcWires, _src2tgtNodes );
1941
1942       if ( !fixDistortedFaces( helper, tgtWires ))
1943         return error("Invalid mesh generated");
1944     }
1945   // ---------------------------
1946   // Check elements orientation
1947   // ---------------------------
1948
1949   TopoDS_Face face = TopoDS::Face( theShape );
1950   if ( !theMesh.IsMainShape( tgtFace ))
1951   {
1952     // find the main shape
1953     TopoDS_Shape mainShape = meshDS->ShapeToMesh();
1954     switch ( mainShape.ShapeType() ) {
1955     case TopAbs_SHELL:
1956     case TopAbs_SOLID: break;
1957     default:
1958       TopTools_ListIteratorOfListOfShape ancestIt = theMesh.GetAncestors( face );
1959       for ( ; ancestIt.More(); ancestIt.Next() ) {
1960         TopAbs_ShapeEnum type = ancestIt.Value().ShapeType();
1961         if ( type == TopAbs_SOLID ) {
1962           mainShape = ancestIt.Value();
1963           break;
1964         } else if ( type == TopAbs_SHELL ) {
1965           mainShape = ancestIt.Value();
1966         }
1967       }
1968     }
1969     // find tgtFace in the main solid or shell to know it's true orientation.
1970     TopExp_Explorer exp( mainShape, TopAbs_FACE );
1971     for ( ; exp.More(); exp.Next() ) {
1972       if ( tgtFace.IsSame( exp.Current() )) {
1973         face = TopoDS::Face( exp.Current() );
1974         break;
1975       }
1976     }
1977   }
1978   // Fix orientation
1979   if ( helper.IsReversedSubMesh( face ))
1980   {
1981     SMESH_MeshEditor editor( tgtMesh );
1982     SMDS_ElemIteratorPtr eIt = meshDS->MeshElements( face )->GetElements();
1983     while ( eIt->more() ) {
1984       const SMDS_MeshElement* e = eIt->next();
1985       if ( e->GetType() == SMDSAbs_Face && !editor.Reorient( e ))
1986         RETURN_BAD_RESULT("Pb of SMESH_MeshEditor::Reorient()");
1987     }
1988   }
1989
1990   cleaner.Release(); // not to remove mesh
1991
1992   return true;
1993 }
1994
1995
1996 //=======================================================================
1997 //function : Evaluate
1998 //purpose  : 
1999 //=======================================================================
2000
2001 bool StdMeshers_Projection_2D::Evaluate(SMESH_Mesh&         theMesh,
2002                                         const TopoDS_Shape& theShape,
2003                                         MapShapeNbElems&    aResMap)
2004 {
2005   if ( !_sourceHypo )
2006     return false;
2007
2008   SMESH_Mesh * srcMesh = _sourceHypo->GetSourceMesh();
2009   SMESH_Mesh * tgtMesh = & theMesh;
2010   if ( !srcMesh )
2011     srcMesh = tgtMesh;
2012
2013   // ---------------------------
2014   // Make sub-shapes association
2015   // ---------------------------
2016
2017   TopoDS_Face tgtFace = TopoDS::Face( theShape.Oriented(TopAbs_FORWARD));
2018   TopoDS_Shape srcShape = _sourceHypo->GetSourceFace().Oriented(TopAbs_FORWARD);
2019
2020   TAssocTool::TShapeShapeMap shape2ShapeMap;
2021   TAssocTool::InitVertexAssociation( _sourceHypo, shape2ShapeMap );
2022   if ( !TAssocTool::FindSubShapeAssociation( tgtFace, tgtMesh, srcShape, srcMesh,
2023                                              shape2ShapeMap)  ||
2024        !shape2ShapeMap.IsBound( tgtFace ))
2025     return error(COMPERR_BAD_SHAPE,"Topology of source and target faces seems different" );
2026
2027   TopoDS_Face srcFace = TopoDS::Face( shape2ShapeMap( tgtFace ).Oriented(TopAbs_FORWARD));
2028
2029   // -------------------------------------------------------
2030   // Assure that mesh on a source Face is computed/evaluated
2031   // -------------------------------------------------------
2032
2033   std::vector<int> aVec;
2034
2035   SMESH_subMesh* srcSubMesh = srcMesh->GetSubMesh( srcFace );
2036   if ( srcSubMesh->IsMeshComputed() )
2037   {
2038     aVec.resize( SMDSEntity_Last, 0 );
2039     aVec[SMDSEntity_Node] = srcSubMesh->GetSubMeshDS()->NbNodes();
2040
2041     SMDS_ElemIteratorPtr elemIt = srcSubMesh->GetSubMeshDS()->GetElements();
2042     while ( elemIt->more() )
2043       aVec[ elemIt->next()->GetEntityType() ]++;
2044   }
2045   else
2046   {
2047     MapShapeNbElems  tmpResMap;
2048     MapShapeNbElems& srcResMap = (srcMesh == tgtMesh) ? aResMap : tmpResMap;
2049     if ( !_gen->Evaluate( *srcMesh, srcShape, srcResMap ))
2050       return error(COMPERR_BAD_INPUT_MESH,"Source mesh not evaluatable");
2051     aVec = srcResMap[ srcSubMesh ];
2052     if ( aVec.empty() )
2053       return error(COMPERR_BAD_INPUT_MESH,"Source mesh is wrongly evaluated");
2054   }
2055
2056   SMESH_subMesh * sm = theMesh.GetSubMesh(theShape);
2057   aResMap.insert(std::make_pair(sm,aVec));
2058
2059   return true;
2060 }
2061
2062
2063 //=============================================================================
2064 /*!
2065  * \brief Sets a default event listener to submesh of the source face
2066   * \param subMesh - submesh where algo is set
2067  *
2068  * This method is called when a submesh gets HYP_OK algo_state.
2069  * After being set, event listener is notified on each event of a submesh.
2070  * Arranges that CLEAN event is translated from source submesh to
2071  * the submesh
2072  */
2073 //=============================================================================
2074
2075 void StdMeshers_Projection_2D::SetEventListener(SMESH_subMesh* subMesh)
2076 {
2077   TAssocTool::SetEventListener( subMesh,
2078                                 _sourceHypo->GetSourceFace(),
2079                                 _sourceHypo->GetSourceMesh() );
2080 }