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