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