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