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