Salome HOME
Merge V9_dev branch into master
[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 : 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_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, SMESH_Gen* gen)
89   :SMESH_2D_Algo(hypId, 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         SMDS_EdgePositionPtr pos = node->GetPosition();
375         u2nodes.insert( make_pair( pos->GetUParameter(), node ));
376         seamNodes.insert( node );
377       }
378       if ( u2nodes.size() != seamNodes.size() )
379         RETURN_BAD_RESULT("Bad node params on edge " << sm->GetId() <<
380                           ", " << u2nodes.size() << " != " << seamNodes.size() );
381       return true;
382     }
383     default:;
384     }
385     RETURN_BAD_RESULT ("Unexpected submesh type");
386
387   } // bool getBoundaryNodes()
388
389   //================================================================================
390   /*!
391    * \brief Check if two consecutive EDGEs are connected in 2D
392    *  \param [in] E1 - a well oriented non-seam EDGE
393    *  \param [in] E2 - a possibly well oriented seam EDGE
394    *  \param [in] F - a FACE
395    *  \return bool - result
396    */
397   //================================================================================
398
399   bool are2dConnected( const TopoDS_Edge & E1,
400                        const TopoDS_Edge & E2,
401                        const TopoDS_Face & F )
402   {
403     double f,l;
404     Handle(Geom2d_Curve) c1 = BRep_Tool::CurveOnSurface( E1, F, f, l );
405     gp_Pnt2d uvFirst1 = c1->Value( f );
406     gp_Pnt2d uvLast1  = c1->Value( l );
407
408     Handle(Geom2d_Curve) c2 = BRep_Tool::CurveOnSurface( E2, F, f, l );
409     gp_Pnt2d uvFirst2 = c2->Value( E2.Orientation() == TopAbs_REVERSED ? l : f );
410     double tol2 = Max( Precision::PConfusion() * Precision::PConfusion(),
411                        1e-5 * uvLast1.SquareDistance( uvFirst1 ));
412
413     return (( uvFirst2.SquareDistance( uvFirst1 ) < tol2 ) ||
414             ( uvFirst2.SquareDistance( uvLast1  ) < tol2 ));
415   }
416
417   //================================================================================
418   /*!
419    * \brief Compose TSideVector for both FACEs keeping matching order of EDGEs
420    *        and fill src2tgtNodes map
421    */
422   //================================================================================
423
424   TError getWires(const TopoDS_Face&                 tgtFace,
425                   const TopoDS_Face&                 srcFace,
426                   SMESH_Mesh *                       tgtMesh,
427                   SMESH_Mesh *                       srcMesh,
428                   SMESH_MesherHelper*                tgtHelper,
429                   const TAssocTool::TShapeShapeMap&  shape2ShapeMap,
430                   TSideVector&                       srcWires,
431                   TSideVector&                       tgtWires,
432                   TAssocTool::TNodeNodeMap&          src2tgtNodes,
433                   bool&                              is1DComputed)
434   {
435     src2tgtNodes.clear();
436
437     // get ordered src EDGEs
438     TError err;
439     srcWires = StdMeshers_FaceSide::GetFaceWires( srcFace, *srcMesh,/*skipMediumNodes=*/0, err );
440     if (( err && !err->IsOK() ) ||
441         ( srcWires.empty() ))
442       return err;
443 #ifdef PRINT_WHO_COMPUTE_WHAT
444     cout << "Projection_2D" <<  " F "
445          << tgtMesh->GetMeshDS()->ShapeToIndex( tgtFace ) << " <- "
446          << srcMesh->GetMeshDS()->ShapeToIndex( srcFace ) << endl;
447 #endif
448
449     // make corresponding sequence of tgt EDGEs
450     tgtWires.resize( srcWires.size() );
451     for ( size_t iW = 0; iW < srcWires.size(); ++iW )
452     {
453       StdMeshers_FaceSidePtr srcWire = srcWires[iW];
454
455       list< TopoDS_Edge > tgtEdges;
456       TopTools_IndexedMapOfShape edgeMap; // to detect seam edges
457       for ( int iE = 0; iE < srcWire->NbEdges(); ++iE )
458       {
459         TopoDS_Edge     srcE = srcWire->Edge( iE );
460         TopoDS_Edge     tgtE = TopoDS::Edge( shape2ShapeMap( srcE, /*isSrc=*/true));
461         TopoDS_Shape srcEbis = shape2ShapeMap( tgtE, /*isSrc=*/false );
462         if ( srcE.Orientation() != srcEbis.Orientation() )
463           tgtE.Reverse();
464         // reverse a seam edge encountered for the second time
465         const int index = edgeMap.Add( tgtE );
466         if ( index < edgeMap.Extent() ) // E is a seam
467         {
468           // check which of edges to reverse, E or one already being in tgtEdges
469           if ( are2dConnected( tgtEdges.back(), tgtE, tgtFace ))
470           {
471             list< TopoDS_Edge >::iterator eIt = tgtEdges.begin();
472             std::advance( eIt, index-1 );
473             if ( are2dConnected( tgtEdges.back(), *eIt, tgtFace ))
474               eIt->Reverse();
475           }
476           else
477           {
478             tgtE.Reverse();
479           }
480         }
481         if ( srcWire->NbEdges() == 1 && tgtMesh == srcMesh ) // circle
482         {
483           // try to verify ori by propagation
484           pair<int,TopoDS_Edge> nE =
485             StdMeshers_ProjectionUtils::GetPropagationEdge( srcMesh, tgtE, srcE );
486           if ( !nE.second.IsNull() )
487             tgtE = nE.second;
488         }
489         tgtEdges.push_back( tgtE );
490       }
491
492       tgtWires[ iW ].reset( new StdMeshers_FaceSide( tgtFace, tgtEdges, tgtMesh,
493                                                      /*theIsForward = */ true,
494                                                      /*theIgnoreMediumNodes = */false,
495                                                      tgtHelper ));
496       StdMeshers_FaceSidePtr tgtWire = tgtWires[ iW ];
497
498       // Fill map of src to tgt nodes with nodes on edges
499
500       for ( int iE = 0; iE < srcWire->NbEdges(); ++iE )
501       {
502 #ifdef PRINT_WHO_COMPUTE_WHAT
503         if ( tgtMesh->GetSubMesh( tgtWire->Edge(iE) )->IsEmpty() )
504           cout << "Projection_2D" <<  " E "
505                << tgtWire->EdgeID(iE) << " <- " << srcWire->EdgeID(iE) << endl;
506 #endif
507         if ( srcMesh->GetSubMesh( srcWire->Edge(iE) )->IsEmpty() ||
508              tgtMesh->GetSubMesh( tgtWire->Edge(iE) )->IsEmpty() )
509         {
510           // add nodes on VERTEXes for a case of not meshes EDGEs
511           const SMDS_MeshNode* srcN = srcWire->VertexNode( iE );
512           const SMDS_MeshNode* tgtN = tgtWire->VertexNode( iE );
513           if ( srcN && tgtN )
514             src2tgtNodes.insert( make_pair( srcN, tgtN ));
515         }
516         else
517         {
518           const bool skipMedium = true, isFwd = true;
519           StdMeshers_FaceSide srcEdge( srcFace, srcWire->Edge(iE),
520                                        srcMesh, isFwd, skipMedium, srcWires[0]->FaceHelper() );
521           StdMeshers_FaceSide tgtEdge( tgtFace, tgtWire->Edge(iE),
522                                        tgtMesh, isFwd, skipMedium, tgtHelper);
523
524           vector< const SMDS_MeshNode* > srcNodes = srcEdge.GetOrderedNodes();
525           vector< const SMDS_MeshNode* > tgtNodes = tgtEdge.GetOrderedNodes();
526
527           if (( srcNodes.size() != tgtNodes.size() ) && tgtNodes.size() > 0 )
528             return SMESH_ComputeError::New( COMPERR_BAD_INPUT_MESH,
529                                             "Different number of nodes on edges");
530           if ( !tgtNodes.empty() )
531           {
532             vector< const SMDS_MeshNode* >::iterator tn = tgtNodes.begin();
533             //if ( srcWire->Edge(iE).Orientation() == tgtWire->Edge(iE).Orientation() )
534             {
535               vector< const SMDS_MeshNode* >::iterator sn = srcNodes.begin();
536               for ( ; tn != tgtNodes.end(); ++tn, ++sn)
537                 src2tgtNodes.insert( make_pair( *sn, *tn ));
538             }
539             // else
540             // {
541             //   vector< const SMDS_MeshNode* >::reverse_iterator sn = srcNodes.rbegin();
542             //   for ( ; tn != tgtNodes.end(); ++tn, ++sn)
543             //     src2tgtNodes.insert( make_pair( *sn, *tn ));
544             // }
545             is1DComputed = true;
546           }
547         }
548       } // loop on EDGEs of a WIRE
549
550     } // loop on WIREs
551
552     return TError();
553   }
554
555   //================================================================================
556   /*!
557    * \brief Perform projection in case if tgtFace.IsPartner( srcFace ) and in case
558    * if projection by 3D transformation is possible
559    */
560   //================================================================================
561
562   bool projectPartner(const TopoDS_Face&                 tgtFace,
563                       const TopoDS_Face&                 srcFace,
564                       const TSideVector&                 tgtWires,
565                       const TSideVector&                 srcWires,
566                       const TAssocTool::TShapeShapeMap&  shape2ShapeMap,
567                       TAssocTool::TNodeNodeMap&          src2tgtNodes,
568                       const bool                         is1DComputed)
569   {
570     SMESH_Mesh *       tgtMesh = tgtWires[0]->GetMesh();
571     SMESH_Mesh *       srcMesh = srcWires[0]->GetMesh();
572     SMESHDS_Mesh*    tgtMeshDS = tgtMesh->GetMeshDS();
573     SMESHDS_Mesh*    srcMeshDS = srcMesh->GetMeshDS();
574     SMESH_MesherHelper* helper = tgtWires[0]->FaceHelper();
575
576     const double tol = 1.e-7 * srcMeshDS->getMaxDim();
577
578     // transformation to get location of target nodes from source ones
579     StdMeshers_ProjectionUtils::TrsfFinder3D trsf;
580     bool trsfIsOK = false;
581     if ( tgtFace.IsPartner( srcFace ))
582     {
583       gp_GTrsf srcTrsf = srcFace.Location().Transformation();
584       gp_GTrsf tgtTrsf = tgtFace.Location().Transformation();
585       gp_GTrsf t = srcTrsf.Inverted().Multiplied( tgtTrsf );
586       trsf.Set( t );
587       // check
588       gp_Pnt srcP = BRep_Tool::Pnt( srcWires[0]->FirstVertex() );
589       gp_Pnt tgtP = BRep_Tool::Pnt( tgtWires[0]->FirstVertex() );
590       trsfIsOK = ( tgtP.Distance( trsf.Transform( srcP )) < tol );
591       if ( !trsfIsOK )
592       {
593         trsf.Set( tgtTrsf.Inverted().Multiplied( srcTrsf ));
594         trsfIsOK = ( tgtP.Distance( trsf.Transform( srcP )) < tol );
595       }
596     }
597     if ( !trsfIsOK )
598     {
599       // Try to find the 3D transformation
600
601       const int totNbSeg = 50;
602       vector< gp_XYZ > srcPnts, tgtPnts;
603       srcPnts.reserve( totNbSeg );
604       tgtPnts.reserve( totNbSeg );
605       gp_XYZ srcBC( 0,0,0 ), tgtBC( 0,0,0 );
606       for ( size_t iW = 0; iW < srcWires.size(); ++iW )
607       {
608         const double minSegLen = srcWires[iW]->Length() / totNbSeg;
609         for ( int iE = 0; iE < srcWires[iW]->NbEdges(); ++iE )
610         {
611           size_t nbSeg = Max( 1, int( srcWires[iW]->EdgeLength( iE ) / minSegLen ));
612           double srcU  = srcWires[iW]->FirstParameter( iE );
613           double tgtU  = tgtWires[iW]->FirstParameter( iE );
614           double srcDu = ( srcWires[iW]->LastParameter( iE )- srcU ) / nbSeg;
615           double tgtDu = ( tgtWires[iW]->LastParameter( iE )- tgtU ) / nbSeg;
616           for ( size_t i = 0; i < nbSeg; ++i  )
617           {
618             srcPnts.push_back( srcWires[iW]->Value3d( srcU ).XYZ() );
619             tgtPnts.push_back( tgtWires[iW]->Value3d( tgtU ).XYZ() );
620             srcU += srcDu;
621             tgtU += tgtDu;
622             srcBC += srcPnts.back();
623             tgtBC += tgtPnts.back();
624           }
625         }
626       }
627       if ( !trsf.Solve( srcPnts, tgtPnts ))
628         return false;
629
630       // check trsf
631
632       const int nbTestPnt = 20;
633       const size_t  iStep = Max( 1, int( srcPnts.size() / nbTestPnt ));
634       // check boundary
635       gp_Pnt trsfTgt = trsf.Transform( srcBC / srcPnts.size() );
636       trsfIsOK = ( trsfTgt.SquareDistance( tgtBC / tgtPnts.size() ) < tol*tol );
637       for ( size_t i = 0; ( i < srcPnts.size() && trsfIsOK ); i += iStep )
638       {
639         gp_Pnt trsfTgt = trsf.Transform( srcPnts[i] );
640         trsfIsOK = ( trsfTgt.SquareDistance( tgtPnts[i] ) < tol*tol );
641       }
642       // check an in-FACE point
643       if ( trsfIsOK )
644       {
645         BRepAdaptor_Surface srcSurf( srcFace );
646         gp_Pnt srcP =
647           srcSurf.Value( 0.321 * ( srcSurf.FirstUParameter() + srcSurf.LastUParameter() ),
648                          0.123 * ( srcSurf.FirstVParameter() + srcSurf.LastVParameter() ));
649         gp_Pnt tgtTrsfP = trsf.Transform( srcP );
650         TopLoc_Location loc;
651         GeomAPI_ProjectPointOnSurf& proj = helper->GetProjector( tgtFace, loc, 0.1*tol );
652         if ( !loc.IsIdentity() )
653           tgtTrsfP.Transform( loc.Transformation().Inverted() );
654         proj.Perform( tgtTrsfP );
655         trsfIsOK = ( proj.IsDone() &&
656                      proj.NbPoints() > 0 &&
657                      proj.LowerDistance() < tol );
658       }
659       if ( !trsfIsOK )
660         return false;
661     }
662
663     // Make new faces
664
665     // prepare the helper to adding quadratic elements if necessary
666     helper->IsQuadraticSubMesh( tgtFace );
667
668     SMESHDS_SubMesh* srcSubDS = srcMeshDS->MeshElements( srcFace );
669     if ( !is1DComputed && srcSubDS->NbElements() )
670       helper->SetIsQuadratic( srcSubDS->GetElements()->next()->IsQuadratic() );
671
672     SMESH_MesherHelper* srcHelper = srcWires[0]->FaceHelper();
673     SMESH_MesherHelper  edgeHelper( *tgtMesh );
674     edgeHelper.ToFixNodeParameters( true );
675
676     const SMDS_MeshNode* nullNode = 0;
677     TAssocTool::TNodeNodeMap::iterator srcN_tgtN;
678
679     // indices of nodes to create properly oriented faces
680     bool isReverse = ( !trsf.IsIdentity() );
681     int tri1 = 1, tri2 = 2, quad1 = 1, quad3 = 3;
682     if ( isReverse )
683       std::swap( tri1, tri2 ), std::swap( quad1, quad3 );
684
685     SMDS_ElemIteratorPtr elemIt = srcSubDS->GetElements();
686     vector< const SMDS_MeshNode* > tgtNodes;
687     while ( elemIt->more() ) // loop on all mesh faces on srcFace
688     {
689       const SMDS_MeshElement* elem = elemIt->next();
690       const int nbN = elem->NbCornerNodes(); 
691       tgtNodes.resize( nbN );
692       helper->SetElementsOnShape( false );
693       for ( int i = 0; i < nbN; ++i ) // loop on nodes of the source element
694       {
695         const SMDS_MeshNode* srcNode = elem->GetNode(i);
696         srcN_tgtN = src2tgtNodes.insert( make_pair( srcNode, nullNode )).first;
697         if ( srcN_tgtN->second == nullNode )
698         {
699           // create a new node
700           gp_Pnt tgtP = trsf.Transform( SMESH_TNodeXYZ( srcNode ));
701           SMDS_MeshNode* n = helper->AddNode( tgtP.X(), tgtP.Y(), tgtP.Z() );
702           srcN_tgtN->second = n;
703           switch ( srcNode->GetPosition()->GetTypeOfPosition() )
704           {
705           case SMDS_TOP_FACE:
706           {
707             gp_Pnt2d srcUV = srcHelper->GetNodeUV( srcFace, srcNode );
708             tgtMeshDS->SetNodeOnFace( n, helper->GetSubShapeID(), srcUV.X(), srcUV.Y() );
709             break;
710           }
711           case SMDS_TOP_EDGE:
712           {
713             const TopoDS_Edge& srcE = TopoDS::Edge( srcMeshDS->IndexToShape( srcNode->getshapeId()));
714             const TopoDS_Edge& tgtE = TopoDS::Edge( shape2ShapeMap( srcE, /*isSrc=*/true ));
715             double srcU = srcHelper->GetNodeU( srcE, srcNode );
716             tgtMeshDS->SetNodeOnEdge( n, tgtE, srcU );
717             if ( !tgtFace.IsPartner( srcFace ))
718             {
719               edgeHelper.SetSubShape( tgtE );
720               double tol = BRep_Tool::Tolerance( tgtE );
721               bool isOk = edgeHelper.CheckNodeU( tgtE, n, srcU, 2 * tol, /*force=*/true );
722               if ( !isOk ) // projection of n to tgtE failed (23395)
723               {
724                 double sF, sL, tF, tL;
725                 BRep_Tool::Range( srcE, sF, sL );
726                 BRep_Tool::Range( tgtE, tF, tL );
727                 double srcR = ( srcU - sF ) / ( sL - sF );
728                 double tgtU  = tF + srcR * ( tL - tF );
729                 tgtMeshDS->SetNodeOnEdge( n, tgtE, tgtU );
730                 gp_Pnt newP = BRepAdaptor_Curve( tgtE ).Value( tgtU );
731                 double dist = newP.Distance( tgtP );
732                 if ( tol < dist && dist < 1000*tol )
733                   tgtMeshDS->MoveNode( n, newP.X(), newP.Y(), newP.Z() );
734               }
735             }
736             break;
737           }
738           case SMDS_TOP_VERTEX:
739           {
740             const TopoDS_Shape & srcV = srcMeshDS->IndexToShape( srcNode->getshapeId() );
741             const TopoDS_Shape & tgtV = shape2ShapeMap( srcV, /*isSrc=*/true );
742             tgtMeshDS->SetNodeOnVertex( n, TopoDS::Vertex( tgtV ));
743             break;
744           }
745           default:;
746           }
747         }
748         tgtNodes[i] = srcN_tgtN->second;
749       }
750       // create a new face
751       helper->SetElementsOnShape( true );
752       switch ( nbN )
753       {
754       case 3: helper->AddFace(tgtNodes[0], tgtNodes[tri1], tgtNodes[tri2]); break;
755       case 4: helper->AddFace(tgtNodes[0], tgtNodes[quad1], tgtNodes[2], tgtNodes[quad3]); break;
756       default:
757         if ( isReverse ) std::reverse( tgtNodes.begin(), tgtNodes.end() );
758         helper->AddPolygonalFace( tgtNodes );
759       }
760     }
761
762     // check node positions
763
764     if ( !tgtFace.IsPartner( srcFace ) )
765     {
766       helper->ToFixNodeParameters( true );
767
768       int nbOkPos = 0;
769       const double tol2d = 1e-12;
770       srcN_tgtN = src2tgtNodes.begin();
771       for ( ; srcN_tgtN != src2tgtNodes.end(); ++srcN_tgtN )
772       {
773         const SMDS_MeshNode* n = srcN_tgtN->second;
774         switch ( n->GetPosition()->GetTypeOfPosition() )
775         {
776         case SMDS_TOP_FACE:
777         {
778           if ( nbOkPos > 10 ) break;
779           gp_XY uv = helper->GetNodeUV( tgtFace, n ), uvBis = uv;
780           if (( helper->CheckNodeUV( tgtFace, n, uv, tol )) &&
781               (( uv - uvBis ).SquareModulus() < tol2d ))
782             ++nbOkPos;
783           else
784             nbOkPos = -((int) src2tgtNodes.size() );
785           break;
786         }
787         case SMDS_TOP_EDGE:
788         {
789           // const TopoDS_Edge & tgtE = TopoDS::Edge( tgtMeshDS->IndexToShape( n->getshapeId() ));
790           // edgeHelper.SetSubShape( tgtE );
791           // edgeHelper.GetNodeU( tgtE, n, 0, &toCheck );
792           break;
793         }
794         default:;
795         }
796       }
797     }
798
799     return true;
800
801   } //   bool projectPartner()
802
803   //================================================================================
804   /*!
805    * \brief Perform projection in case if the faces are similar in 2D space
806    */
807   //================================================================================
808
809   bool projectBy2DSimilarity(const TopoDS_Face&                 tgtFace,
810                              const TopoDS_Face&                 srcFace,
811                              const TSideVector&                 tgtWires,
812                              const TSideVector&                 srcWires,
813                              const TAssocTool::TShapeShapeMap&  shape2ShapeMap,
814                              TAssocTool::TNodeNodeMap&          src2tgtNodes,
815                              const bool                         is1DComputed)
816   {
817     SMESH_Mesh * tgtMesh = tgtWires[0]->GetMesh();
818     SMESH_Mesh * srcMesh = srcWires[0]->GetMesh();
819
820     // WARNING: we can have problems if the FACE is symmetrical in 2D,
821     // then the projection can be mirrored relating to what is expected
822
823     // 1) Find 2D transformation
824
825     StdMeshers_ProjectionUtils::TrsfFinder2D trsf;
826     {
827       // get 2 pairs of corresponding UVs
828       gp_Pnt2d srcP0 = srcWires[0]->Value2d(0.0);
829       gp_Pnt2d srcP1 = srcWires[0]->Value2d(0.333);
830       gp_Pnt2d tgtP0 = tgtWires[0]->Value2d(0.0);
831       gp_Pnt2d tgtP1 = tgtWires[0]->Value2d(0.333);
832
833       // make transformation
834       gp_Trsf2d fromTgtCS, toSrcCS; // from/to global CS
835       gp_Ax2d srcCS( srcP0, gp_Vec2d( srcP0, srcP1 ));
836       gp_Ax2d tgtCS( tgtP0, gp_Vec2d( tgtP0, tgtP1 ));
837       toSrcCS  .SetTransformation( srcCS );
838       fromTgtCS.SetTransformation( tgtCS );
839       fromTgtCS.Invert();
840       trsf.Set( fromTgtCS * toSrcCS );
841
842       // check transformation
843       bool trsfIsOK = true;
844       const double tol = 1e-5 * gp_Vec2d( srcP0, srcP1 ).Magnitude();
845       for ( double u = 0.12; ( u < 1. && trsfIsOK ); u += 0.1 )
846       {
847         gp_Pnt2d srcUV  = srcWires[0]->Value2d( u );
848         gp_Pnt2d tgtUV  = tgtWires[0]->Value2d( u );
849         gp_Pnt2d tgtUV2 = trsf.Transform( srcUV );
850         trsfIsOK = ( tgtUV.Distance( tgtUV2 ) < tol );
851       }
852
853       // Find trsf using a least-square approximation
854       if ( !trsfIsOK )
855       {
856         // find trsf
857         const int totNbSeg = 50;
858         vector< gp_XY > srcPnts, tgtPnts;
859         srcPnts.reserve( totNbSeg );
860         tgtPnts.reserve( totNbSeg );
861         for ( size_t iW = 0; iW < srcWires.size(); ++iW )
862         {
863           const double minSegLen = srcWires[iW]->Length() / totNbSeg;
864           for ( int iE = 0; iE < srcWires[iW]->NbEdges(); ++iE )
865           {
866             size_t nbSeg = Max( 1, int( srcWires[iW]->EdgeLength( iE ) / minSegLen ));
867             double srcU  = srcWires[iW]->FirstParameter( iE );
868             double tgtU  = tgtWires[iW]->FirstParameter( iE );
869             double srcDu = ( srcWires[iW]->LastParameter( iE )- srcU ) / nbSeg;
870             double tgtDu = ( tgtWires[iW]->LastParameter( iE )- tgtU ) / nbSeg;
871             for ( size_t i = 0; i < nbSeg; ++i, srcU += srcDu, tgtU += tgtDu  )
872             {
873               srcPnts.push_back( srcWires[iW]->Value2d( srcU ).XY() );
874               tgtPnts.push_back( tgtWires[iW]->Value2d( tgtU ).XY() );
875             }
876           }
877         }
878         if ( !trsf.Solve( srcPnts, tgtPnts ))
879           return false;
880
881         // check trsf
882
883         trsfIsOK = true;
884         const int nbTestPnt = 10;
885         const size_t  iStep = Max( 1, int( srcPnts.size() / nbTestPnt ));
886         for ( size_t i = 0; ( i < srcPnts.size() && trsfIsOK ); i += iStep )
887         {
888           gp_Pnt2d trsfTgt = trsf.Transform( srcPnts[i] );
889           trsfIsOK = ( trsfTgt.Distance( tgtPnts[i] ) < tol );
890         }
891         if ( !trsfIsOK )
892           return false;
893       }
894     } // "Find transformation" block
895
896     // 2) Projection
897
898     SMESHDS_SubMesh* srcSubDS = srcMesh->GetMeshDS()->MeshElements( srcFace );
899
900     SMESH_MesherHelper* helper = tgtWires[0]->FaceHelper();
901     if ( is1DComputed )
902       helper->IsQuadraticSubMesh( tgtFace );
903     else
904       helper->SetIsQuadratic( srcSubDS->GetElements()->next()->IsQuadratic() );
905     helper->SetElementsOnShape( true );
906     Handle(Geom_Surface) tgtSurface = BRep_Tool::Surface( tgtFace );
907     SMESHDS_Mesh* tgtMeshDS = tgtMesh->GetMeshDS();
908
909     SMESH_MesherHelper* srcHelper = srcWires[0]->FaceHelper();
910
911     const SMDS_MeshNode* nullNode = 0;
912     TAssocTool::TNodeNodeMap::iterator srcN_tgtN;
913
914     SMDS_ElemIteratorPtr elemIt = srcSubDS->GetElements();
915     vector< const SMDS_MeshNode* > tgtNodes;
916     bool uvOK;
917     while ( elemIt->more() ) // loop on all mesh faces on srcFace
918     {
919       const SMDS_MeshElement* elem = elemIt->next();
920       const int nbN = elem->NbCornerNodes();
921       tgtNodes.resize( nbN );
922       for ( int i = 0; i < nbN; ++i ) // loop on nodes of the source element
923       {
924         const SMDS_MeshNode* srcNode = elem->GetNode(i);
925         srcN_tgtN = src2tgtNodes.insert( make_pair( srcNode, nullNode )).first;
926         if ( srcN_tgtN->second == nullNode )
927         {
928           // create a new node
929           gp_Pnt2d srcUV = srcHelper->GetNodeUV( srcFace, srcNode,
930                                                  elem->GetNode( helper->WrapIndex(i+1,nbN)), &uvOK);
931           gp_Pnt2d   tgtUV = trsf.Transform( srcUV );
932           gp_Pnt      tgtP = tgtSurface->Value( tgtUV.X(), tgtUV.Y() );
933           SMDS_MeshNode* n = tgtMeshDS->AddNode( tgtP.X(), tgtP.Y(), tgtP.Z() );
934           switch ( srcNode->GetPosition()->GetTypeOfPosition() )
935           {
936           case SMDS_TOP_FACE: {
937             tgtMeshDS->SetNodeOnFace( n, helper->GetSubShapeID(), tgtUV.X(), tgtUV.Y() );
938             break;
939           }
940           case SMDS_TOP_EDGE: {
941             TopoDS_Shape srcEdge = srcHelper->GetSubShapeByNode( srcNode, srcHelper->GetMeshDS() );
942             TopoDS_Edge  tgtEdge = TopoDS::Edge( shape2ShapeMap( srcEdge, /*isSrc=*/true ));
943             double U = Precision::Infinite();
944             helper->CheckNodeU( tgtEdge, n, U, Precision::PConfusion());
945             tgtMeshDS->SetNodeOnEdge( n, TopoDS::Edge( tgtEdge ), U );
946             break;
947           }
948           case SMDS_TOP_VERTEX: {
949             TopoDS_Shape srcV = srcHelper->GetSubShapeByNode( srcNode, srcHelper->GetMeshDS() );
950             TopoDS_Shape tgtV = shape2ShapeMap( srcV, /*isSrc=*/true );
951             tgtMeshDS->SetNodeOnVertex( n, TopoDS::Vertex( tgtV ));
952             break;
953           }
954           default:;
955           }
956           srcN_tgtN->second = n;
957         }
958         tgtNodes[i] = srcN_tgtN->second;
959       }
960       // create a new face (with reversed orientation)
961       switch ( nbN )
962       {
963       case 3: helper->AddFace(tgtNodes[0], tgtNodes[2], tgtNodes[1]); break;
964       case 4: helper->AddFace(tgtNodes[0], tgtNodes[3], tgtNodes[2], tgtNodes[1]); break;
965       }
966     }  // loop on all mesh faces on srcFace
967
968     return true;
969   }
970
971   //================================================================================
972   /*!
973    * \brief Perform projection in case of quadrilateral faces
974    */
975   //================================================================================
976
977   bool projectQuads(const TopoDS_Face&                 tgtFace,
978                     const TopoDS_Face&                 srcFace,
979                     const TSideVector&                 tgtWires,
980                     const TSideVector&                 srcWires,
981                     const TAssocTool::TShapeShapeMap&  shape2ShapeMap,
982                     TAssocTool::TNodeNodeMap&          src2tgtNodes,
983                     const bool                         is1DComputed)
984   {
985     // SMESH_Mesh * tgtMesh = tgtWires[0]->GetMesh();
986     // SMESH_Mesh * srcMesh = srcWires[0]->GetMesh();
987     // //SMESHDS_Mesh * tgtMeshDS = tgtMesh->GetMeshDS();
988     // SMESHDS_Mesh * srcMeshDS = srcMesh->GetMeshDS();
989
990     // if ( srcWires[0]->NbEdges() != 4 )
991     //   return false;
992     // if ( !is1DComputed )
993     //   return false;
994     // for ( int iE = 0; iE < 4; ++iE )
995     // {
996     //   SMESHDS_SubMesh* sm = srcMeshDS->MeshElements( srcWires[0]->Edge( iE ));
997     //   if ( !sm ) return false;
998     //   if ( sm->NbNodes() + sm->NbElements() == 0 ) return false;
999     // }
1000     // if ( BRepAdaptor_Surface( tgtFace ).GetType() != GeomAbs_Plane )
1001     //   return false;
1002     // // if ( BRepAdaptor_Surface( tgtFace ).GetType() == GeomAbs_Plane &&
1003     // //      BRepAdaptor_Surface( srcFace ).GetType() == GeomAbs_Plane )
1004     // //   return false; // too easy
1005
1006     // // load EDGEs to SMESH_Block
1007
1008     // SMESH_Block block;
1009     // TopTools_IndexedMapOfOrientedShape blockSubShapes;
1010     // {
1011     //   const TopoDS_Solid& box = srcMesh->PseudoShape();
1012     //   TopoDS_Shell shell = TopoDS::Shell( TopExp_Explorer( box, TopAbs_SHELL ).Current() );
1013     //   TopoDS_Vertex v;
1014     //   block.LoadBlockShapes( shell, v, v, blockSubShapes ); // fill all since operator[] is missing
1015     // }
1016     // const SMESH_Block::TShapeID srcFaceBID = SMESH_Block::ID_Fxy0;
1017     // const SMESH_Block::TShapeID tgtFaceBID = SMESH_Block::ID_Fxy1;
1018     // vector< int > edgeBID;
1019     // block.GetFaceEdgesIDs( srcFaceBID, edgeBID ); // u0, u1, 0v, 1v
1020     // blockSubShapes.Substitute( edgeBID[0], srcWires[0]->Edge(0) );
1021     // blockSubShapes.Substitute( edgeBID[1], srcWires[0]->Edge(2) );
1022     // blockSubShapes.Substitute( edgeBID[2], srcWires[0]->Edge(3) );
1023     // blockSubShapes.Substitute( edgeBID[3], srcWires[0]->Edge(1) );
1024     // block.GetFaceEdgesIDs( tgtFaceBID, edgeBID ); // u0, u1, 0v, 1v
1025     // blockSubShapes.Substitute( edgeBID[0], tgtWires[0]->Edge(0) );
1026     // blockSubShapes.Substitute( edgeBID[1], tgtWires[0]->Edge(2) );
1027     // blockSubShapes.Substitute( edgeBID[2], tgtWires[0]->Edge(3) );
1028     // blockSubShapes.Substitute( edgeBID[3], tgtWires[0]->Edge(1) );
1029     // block.LoadFace( srcFace, srcFaceBID, blockSubShapes );
1030     // block.LoadFace( tgtFace, tgtFaceBID, blockSubShapes );
1031
1032     // // remember connectivity of new faces in terms of ( node-or-XY )
1033
1034     // typedef std::pair< const SMDS_MeshNode*, gp_XYZ > TNodeOrXY; // node-or-XY
1035     // typedef std::vector< TNodeOrXY* >                 TFaceConn; // face connectivity
1036     // std::vector< TFaceConn >                    newFacesVec;     // connectivity of all faces
1037     // std::map< const SMDS_MeshNode*, TNodeOrXY > srcNode2tgtNXY;  // src node -> node-or-XY
1038
1039     // TAssocTool::TNodeNodeMap::iterator                                       srcN_tgtN;
1040     // std::map< const SMDS_MeshNode*, TNodeOrXY >::iterator                    srcN_tgtNXY;
1041     // std::pair< std::map< const SMDS_MeshNode*, TNodeOrXY >::iterator, bool > n2n_isNew;
1042     // TNodeOrXY nullNXY( (SMDS_MeshNode*)NULL, gp_XYZ(0,0,0) );
1043
1044     // SMESHDS_SubMesh* srcSubDS = srcMeshDS->MeshElements( srcFace );
1045     // newFacesVec.resize( srcSubDS->NbElements() );
1046     // int iFaceSrc = 0;
1047
1048     // SMDS_ElemIteratorPtr elemIt = srcSubDS->GetElements();
1049     // while ( elemIt->more() ) // loop on all mesh faces on srcFace
1050     // {
1051     //   const SMDS_MeshElement* elem = elemIt->next();
1052     //   TFaceConn& tgtNodes = newFacesVec[ iFaceSrc++ ];
1053
1054     //   const int nbN = elem->NbCornerNodes(); 
1055     //   tgtNodes.resize( nbN );
1056     //   for ( int i = 0; i < nbN; ++i ) // loop on nodes of the source element
1057     //   {
1058     //     const SMDS_MeshNode* srcNode = elem->GetNode(i);
1059     //     n2n_isNew = srcNode2tgtNXY.insert( make_pair( srcNode, nullNXY ));
1060     //     TNodeOrXY & tgtNodeOrXY = n2n_isNew.first->second;
1061     //     if ( n2n_isNew.second ) // new src node encounters
1062     //     {
1063     //       srcN_tgtN = src2tgtNodes.find( srcNode );
1064     //       if ( srcN_tgtN != src2tgtNodes.end() )
1065     //       {
1066     //         tgtNodeOrXY.first = srcN_tgtN->second; // tgt node exists
1067     //       }
1068     //       else 
1069     //       {
1070     //         // find XY of src node within the quadrilateral srcFace
1071     //         if ( !block.ComputeParameters( SMESH_TNodeXYZ( srcNode ),
1072     //                                        tgtNodeOrXY.second, srcFaceBID ))
1073     //           return false;
1074     //       }
1075     //     }
1076     //     tgtNodes[ i ] = & tgtNodeOrXY;
1077     //   }
1078     // }
1079
1080     // // as all XY are computed, create tgt nodes and faces
1081
1082     // SMESH_MesherHelper helper = *tgtWires[0]->FaceHelper();
1083     // if ( is1DComputed )
1084     //   helper.IsQuadraticSubMesh( tgtFace );
1085     // else
1086     //   helper.SetIsQuadratic( srcSubDS->GetElements()->next()->IsQuadratic() );
1087     // helper.SetElementsOnShape( true );
1088     // Handle(Geom_Surface) tgtSurface = BRep_Tool::Surface( tgtFace );
1089
1090     // SMESH_MesherHelper srcHelper = *srcWires[0]->FaceHelper();
1091
1092     // vector< const SMDS_MeshNode* > tgtNodes;
1093     // gp_XY uv;
1094
1095     // for ( size_t iFaceTgt = 0; iFaceTgt < newFacesVec.size(); ++iFaceTgt )
1096     // {
1097     //   TFaceConn& tgtConn = newFacesVec[ iFaceTgt ];
1098     //   tgtNodes.resize( tgtConn.size() );
1099     //   for ( size_t iN = 0; iN < tgtConn.size(); ++iN )
1100     //   {
1101     //     const SMDS_MeshNode* & tgtN = tgtConn[ iN ]->first;
1102     //     if ( !tgtN ) // create a node
1103     //     {
1104     //       if ( !block.FaceUV( tgtFaceBID, tgtConn[iN]->second, uv ))
1105     //         return false;
1106     //       gp_Pnt p = tgtSurface->Value( uv.X(), uv.Y() );
1107     //       tgtN = helper.AddNode( p.X(), p.Y(), p.Z(), uv.X(), uv.Y() );
1108     //     }
1109     //     tgtNodes[ tgtNodes.size() - iN - 1] = tgtN; // reversed orientation
1110     //   }
1111     //   switch ( tgtNodes.size() )
1112     //   {
1113     //   case 3: helper.AddFace(tgtNodes[0], tgtNodes[1], tgtNodes[2]); break;
1114     //   case 4: helper.AddFace(tgtNodes[0], tgtNodes[1], tgtNodes[2], tgtNodes[3]); break;
1115     //   default:
1116     //     if ( tgtNodes.size() > 4 )
1117     //       helper.AddPolygonalFace( tgtNodes );
1118     //   }
1119     // }
1120     return false; //true;
1121
1122   } // bool projectQuads(...)
1123
1124   //================================================================================
1125   /*!
1126    * \brief Fix bad faces by smoothing
1127    */
1128   //================================================================================
1129
1130   bool fixDistortedFaces( SMESH_MesherHelper& helper,
1131                           TSideVector&        tgtWires )
1132   {
1133     SMESH_subMesh* faceSM = helper.GetMesh()->GetSubMesh( helper.GetSubShape() );
1134
1135     //if ( helper.IsDistorted2D( faceSM, /*checkUV=*/true ))
1136     {
1137       SMESH_MeshEditor editor( helper.GetMesh() );
1138       SMESHDS_SubMesh* smDS = faceSM->GetSubMeshDS();
1139       const TopoDS_Face&  F = TopoDS::Face( faceSM->GetSubShape() );
1140
1141       TIDSortedElemSet faces;
1142       SMDS_ElemIteratorPtr faceIt = smDS->GetElements();
1143       for ( faceIt = smDS->GetElements(); faceIt->more(); )
1144         faces.insert( faces.end(), faceIt->next() );
1145
1146       // choose smoothing algo
1147       //SMESH_MeshEditor:: SmoothMethod algo = SMESH_MeshEditor::CENTROIDAL;
1148       bool isConcaveBoundary = false;
1149       for ( size_t iW = 0; iW < tgtWires.size() && !isConcaveBoundary; ++iW )
1150       {
1151         TopoDS_Edge prevEdge = tgtWires[iW]->Edge( tgtWires[iW]->NbEdges() - 1 );
1152         for ( int iE = 0; iE < tgtWires[iW]->NbEdges() && !isConcaveBoundary; ++iE )
1153         {
1154           double angle = helper.GetAngle( prevEdge, tgtWires[iW]->Edge( iE ),
1155                                           F,        tgtWires[iW]->FirstVertex( iE ));
1156           isConcaveBoundary = ( angle < -5. * M_PI / 180. );
1157
1158           prevEdge = tgtWires[iW]->Edge( iE );
1159         }
1160       }
1161       SMESH_MeshEditor:: SmoothMethod algo =
1162         isConcaveBoundary ? SMESH_MeshEditor::CENTROIDAL : SMESH_MeshEditor::LAPLACIAN;
1163
1164       // smooth in 2D or 3D?
1165       TopLoc_Location loc;
1166       Handle(Geom_Surface) surface = BRep_Tool::Surface( F, loc );
1167       bool isPlanar = GeomLib_IsPlanarSurface( surface ).IsPlanar();
1168
1169       // smoothing
1170       set<const SMDS_MeshNode*> fixedNodes;
1171       editor.Smooth( faces, fixedNodes, algo, /*nbIterations=*/ 10,
1172                      /*theTgtAspectRatio=*/1.0, /*the2D=*/!isPlanar);
1173
1174       helper.ToFixNodeParameters( true );
1175
1176       return !helper.IsDistorted2D( faceSM, /*checkUV=*/true );
1177     }
1178     return true;
1179   }
1180
1181   //=======================================================================
1182   /*
1183    * Set initial association of VERTEXes for the case of projection
1184    * from a quadrangle FACE to a closed FACE, where opposite src EDGEs
1185    * have different nb of segments
1186    */
1187   //=======================================================================
1188
1189   void initAssoc4Quad2Closed(const TopoDS_Shape&          tgtFace,
1190                              SMESH_MesherHelper&          tgtHelper,
1191                              const TopoDS_Shape&          srcFace,
1192                              SMESH_Mesh*                  srcMesh,
1193                              TAssocTool::TShapeShapeMap & assocMap)
1194   {
1195     if ( !tgtHelper.HasRealSeam() || srcFace.ShapeType() != TopAbs_FACE )
1196       return; // no seam edge
1197     list< TopoDS_Edge > tgtEdges, srcEdges;
1198     list< int > tgtNbEW, srcNbEW;
1199     int tgtNbW = SMESH_Block::GetOrderedEdges( TopoDS::Face( tgtFace ), tgtEdges, tgtNbEW );
1200     int srcNbW = SMESH_Block::GetOrderedEdges( TopoDS::Face( srcFace ), srcEdges, srcNbEW );
1201     if ( tgtNbW != 1 || srcNbW != 1 ||
1202          tgtNbEW.front() != 4 || srcNbEW.front() != 4 )
1203       return; // not quads
1204
1205     int srcNbSeg[4];
1206     list< TopoDS_Edge >::iterator edgeS = srcEdges.begin(), edgeT = tgtEdges.begin();
1207     for ( int i = 0; edgeS != srcEdges.end(); ++i, ++edgeS )
1208       if ( SMESHDS_SubMesh* sm = srcMesh->GetMeshDS()->MeshElements( *edgeS ))
1209         srcNbSeg[ i ] = sm->NbNodes();
1210       else
1211         return; // not meshed
1212     if ( srcNbSeg[0] == srcNbSeg[2] && srcNbSeg[1] == srcNbSeg[3] )
1213       return; // same nb segments
1214     if ( srcNbSeg[0] != srcNbSeg[2] && srcNbSeg[1] != srcNbSeg[3] )
1215       return; // all different nb segments
1216
1217     edgeS = srcEdges.begin();
1218     if ( srcNbSeg[0] != srcNbSeg[2] )
1219       ++edgeS;
1220     TAssocTool::InsertAssociation( tgtHelper.IthVertex( 0,*edgeT ),
1221                                    tgtHelper.IthVertex( 0,*edgeS ), assocMap );
1222     TAssocTool::InsertAssociation( tgtHelper.IthVertex( 1,*edgeT ),
1223                                    tgtHelper.IthVertex( 1,*edgeS ), assocMap );
1224   }
1225
1226 } // namespace
1227
1228
1229 //=======================================================================
1230 //function : Compute
1231 //purpose  :
1232 //=======================================================================
1233
1234 bool StdMeshers_Projection_2D::Compute(SMESH_Mesh& theMesh, const TopoDS_Shape& theShape)
1235 {
1236   _src2tgtNodes.clear();
1237
1238   if ( !_sourceHypo )
1239     return false;
1240
1241   SMESH_Mesh * srcMesh = _sourceHypo->GetSourceMesh();
1242   SMESH_Mesh * tgtMesh = & theMesh;
1243   if ( !srcMesh )
1244     srcMesh = tgtMesh;
1245
1246   SMESHDS_Mesh * meshDS = theMesh.GetMeshDS();
1247   SMESH_MesherHelper helper( theMesh );
1248
1249   // ---------------------------
1250   // Make sub-shapes association
1251   // ---------------------------
1252
1253   TopoDS_Face   tgtFace = TopoDS::Face( theShape.Oriented(TopAbs_FORWARD));
1254   TopoDS_Shape srcShape = _sourceHypo->GetSourceFace().Oriented(TopAbs_FORWARD);
1255
1256   helper.SetSubShape( tgtFace );
1257
1258   TAssocTool::TShapeShapeMap shape2ShapeMap;
1259   TAssocTool::InitVertexAssociation( _sourceHypo, shape2ShapeMap );
1260   if ( shape2ShapeMap.IsEmpty() )
1261     initAssoc4Quad2Closed( tgtFace, helper, srcShape, srcMesh, shape2ShapeMap );
1262   if ( !TAssocTool::FindSubShapeAssociation( tgtFace, tgtMesh, srcShape, srcMesh,
1263                                              shape2ShapeMap)  ||
1264        !shape2ShapeMap.IsBound( tgtFace ))
1265   {
1266     if ( srcShape.ShapeType() == TopAbs_FACE )
1267     {
1268       int nbE1 = helper.Count( tgtFace, TopAbs_EDGE, /*ignoreSame=*/true );
1269       int nbE2 = helper.Count( srcShape, TopAbs_EDGE, /*ignoreSame=*/true );
1270       if ( nbE1 != nbE2 )
1271         return error(COMPERR_BAD_SHAPE,
1272                      SMESH_Comment("Different number of edges in source and target faces: ")
1273                      << nbE2 << " and " << nbE1 );
1274     }
1275     return error(COMPERR_BAD_SHAPE,"Topology of source and target faces seems different" );
1276   }
1277   TopoDS_Face srcFace = TopoDS::Face( shape2ShapeMap( tgtFace ).Oriented(TopAbs_FORWARD));
1278
1279   // ----------------------------------------------
1280   // Assure that mesh on a source Face is computed
1281   // ----------------------------------------------
1282
1283   SMESH_subMesh* srcSubMesh = srcMesh->GetSubMesh( srcFace );
1284   SMESH_subMesh* tgtSubMesh = tgtMesh->GetSubMesh( tgtFace );
1285
1286   string srcMeshError;
1287   if ( tgtMesh == srcMesh ) {
1288     if ( !TAssocTool::MakeComputed( srcSubMesh ))
1289       srcMeshError = TAssocTool::SourceNotComputedError( srcSubMesh, this );
1290   }
1291   else {
1292     if ( !srcSubMesh->IsMeshComputed() )
1293       srcMeshError = TAssocTool::SourceNotComputedError();
1294   }
1295   if ( !srcMeshError.empty() )
1296     return error(COMPERR_BAD_INPUT_MESH, srcMeshError );
1297
1298   // ===========
1299   // Projection
1300   // ===========
1301
1302   // get ordered src and tgt EDGEs
1303   TSideVector srcWires, tgtWires;
1304   bool is1DComputed = false; // if any tgt EDGE is meshed
1305   TError err = getWires( tgtFace, srcFace, tgtMesh, srcMesh, &helper,
1306                          shape2ShapeMap, srcWires, tgtWires, _src2tgtNodes, is1DComputed );
1307   if ( err && !err->IsOK() )
1308     return error( err );
1309
1310   bool projDone = false;
1311
1312   if ( !projDone )
1313   {
1314     // try to project from the same face with different location
1315     projDone = projectPartner( tgtFace, srcFace, tgtWires, srcWires,
1316                                shape2ShapeMap, _src2tgtNodes, is1DComputed );
1317   }
1318   if ( !projDone )
1319   {
1320     // projection in case if the faces are similar in 2D space
1321     projDone = projectBy2DSimilarity( tgtFace, srcFace, tgtWires, srcWires,
1322                                       shape2ShapeMap, _src2tgtNodes, is1DComputed );
1323   }
1324   if ( !projDone )
1325   {
1326     // projection in case of quadrilateral faces
1327     // NOT IMPLEMENTED, returns false
1328     projDone = projectQuads( tgtFace, srcFace, tgtWires, srcWires,
1329                              shape2ShapeMap, _src2tgtNodes, is1DComputed);
1330   }
1331
1332   // it will remove mesh built on edges and vertices in failure case
1333   MeshCleaner cleaner( tgtSubMesh );
1334
1335   if ( !projDone )
1336   {
1337     _src2tgtNodes.clear();
1338     // --------------------
1339     // Prepare to mapping 
1340     // --------------------
1341
1342     // Check if node projection to a face is needed
1343     Bnd_B2d uvBox;
1344     SMDS_ElemIteratorPtr faceIt = srcSubMesh->GetSubMeshDS()->GetElements();
1345     set< const SMDS_MeshNode* > faceNodes;
1346     for ( ; faceNodes.size() < 3 && faceIt->more();  ) {
1347       const SMDS_MeshElement* face = faceIt->next();
1348       SMDS_ElemIteratorPtr nodeIt = face->nodesIterator();
1349       while ( nodeIt->more() ) {
1350         const SMDS_MeshNode* node = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
1351         if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE &&
1352              faceNodes.insert( node ).second )
1353           uvBox.Add( helper.GetNodeUV( srcFace, node ));
1354       }
1355     }
1356     bool toProjectNodes = false;
1357     if ( faceNodes.size() == 1 )
1358       toProjectNodes = ( uvBox.IsVoid() || uvBox.CornerMin().IsEqual( gp_XY(0,0), 1e-12 ));
1359     else if ( faceNodes.size() > 1 )
1360       toProjectNodes = ( uvBox.IsVoid() || uvBox.SquareExtent() < DBL_MIN );
1361
1362     // Find the corresponding source and target vertex
1363     // and <theReverse> flag needed to call mapper.Apply()
1364
1365     TopoDS_Vertex srcV1, tgtV1;
1366     bool reverse = false;
1367
1368     TopExp_Explorer vSrcExp( srcFace, TopAbs_VERTEX );
1369     srcV1 = TopoDS::Vertex( vSrcExp.Current() );
1370     tgtV1 = TopoDS::Vertex( shape2ShapeMap( srcV1, /*isSrc=*/true ));
1371
1372     list< TopoDS_Edge > tgtEdges, srcEdges;
1373     list< int > nbEdgesInWires;
1374     SMESH_Block::GetOrderedEdges( tgtFace, tgtEdges, nbEdgesInWires, tgtV1 );
1375     SMESH_Block::GetOrderedEdges( srcFace, srcEdges, nbEdgesInWires, srcV1 );
1376
1377     if ( nbEdgesInWires.front() > 1 ) // possible to find out orientation
1378     {
1379       TopoDS_Edge srcE1 = srcEdges.front(), tgtE1 = tgtEdges.front();
1380       TopoDS_Shape srcE1bis = shape2ShapeMap( tgtE1 );
1381       reverse = ( ! srcE1.IsSame( srcE1bis ));
1382       if ( ( reverse || srcE1.Orientation() != srcE1bis.Orientation() ) &&
1383            nbEdgesInWires.front() > 2 &&
1384            helper.IsRealSeam( tgtEdges.front() ))
1385       {
1386         if ( srcE1.Orientation() != srcE1bis.Orientation() )
1387           reverse = true;
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           SMDS_EdgePositionPtr pos = node->GetPosition();
1590           pos2nodes.insert( make_pair( pos->GetUParameter(), node ));
1591           break;
1592         }
1593         default:
1594           RETURN_BAD_RESULT("Wrong node position type: "<<
1595                             node->GetPosition()->GetTypeOfPosition());
1596         }
1597       }
1598       const bool mergeNewToOld =
1599         ( u2nodesMaps[ NEW_NODES ].size() == u2nodesMaps[ OLD_NODES ].size() );
1600       const bool mergeSeamToNew =
1601         ( u2nodesMaps[ NEW_NODES ].size() == u2nodesOnSeam.size() );
1602
1603       if ( !mergeNewToOld )
1604         if ( u2nodesMaps[ NEW_NODES ].size() > 0 &&
1605              u2nodesMaps[ OLD_NODES ].size() > 0 )
1606         {
1607           u_oldNode = u2nodesMaps[ OLD_NODES ].begin(); 
1608           newEnd    = u2nodesMaps[ OLD_NODES ].end();
1609           for ( ; u_oldNode != newEnd; ++u_oldNode )
1610             SMESH_Algo::addBadInputElement( u_oldNode->second );
1611           return error( COMPERR_BAD_INPUT_MESH,
1612                         SMESH_Comment( "Existing mesh mismatches the projected 2D mesh on " )
1613                         << ( sm->GetSubShape().ShapeType() == TopAbs_EDGE ? "edge" : "vertex" )
1614                         << " #" << sm->GetId() );
1615         }
1616       if ( isSeam && !mergeSeamToNew ) {
1617         const TopoDS_Shape& seam = sm->GetSubShape();
1618         if ( u2nodesMaps[ NEW_NODES ].size() > 0 &&
1619              u2nodesOnSeam.size()            > 0 &&
1620              seam.ShapeType() == TopAbs_EDGE )
1621         {
1622           int nbE1 = helper.Count( tgtFace, TopAbs_EDGE, /*ignoreSame=*/true );
1623           int nbE2 = helper.Count( srcFace, TopAbs_EDGE, /*ignoreSame=*/true );
1624           if ( nbE1 != nbE2 ) // 2 EDGEs are mapped to a seam EDGE
1625           {
1626             // find the 2 EDGEs of srcFace
1627             TopTools_DataMapIteratorOfDataMapOfShapeShape src2tgtIt( shape2ShapeMap._map2to1 );
1628             for ( ; src2tgtIt.More(); src2tgtIt.Next() )
1629               if ( seam.IsSame( src2tgtIt.Value() ))
1630                 SMESH_Algo::addBadInputElements
1631                   ( srcMesh->GetMeshDS()->MeshElements( src2tgtIt.Key() ));
1632             return error( COMPERR_BAD_INPUT_MESH,
1633                           "Different number of nodes on two edges projected to a seam edge" );
1634           }
1635         }
1636       }
1637
1638       // Make groups of nodes to merge
1639
1640       u_oldNode = u2nodesMaps[ OLD_NODES ].begin(); 
1641       u_newNode = u2nodesMaps[ NEW_NODES ].begin();
1642       newEnd    = u2nodesMaps[ NEW_NODES ].end();
1643       u_newOnSeam = u2nodesOnSeam.begin();
1644       if ( mergeNewToOld )
1645         for ( ; u_newNode != newEnd; ++u_newNode, ++u_oldNode )
1646         {
1647           groupsOfNodes.push_back( list< const SMDS_MeshNode* >() );
1648           groupsOfNodes.back().push_back( u_oldNode->second );
1649           groupsOfNodes.back().push_back( u_newNode->second );
1650           if ( mergeSeamToNew )
1651             groupsOfNodes.back().push_back( (u_newOnSeam++)->second );
1652         }
1653       else if ( mergeSeamToNew )
1654         for ( ; u_newNode != newEnd; ++u_newNode, ++u_newOnSeam )
1655         {
1656           groupsOfNodes.push_back( list< const SMDS_MeshNode* >() );
1657           groupsOfNodes.back().push_back( u_newNode->second );
1658           groupsOfNodes.back().push_back( u_newOnSeam->second );
1659         }
1660
1661     } // loop on EDGE and VERTEX submeshes of a target FACE
1662
1663     // Merge
1664
1665     SMESH_MeshEditor editor( tgtMesh );
1666     int nbFaceBeforeMerge = tgtSubMesh->GetSubMeshDS()->NbElements();
1667     editor.MergeNodes( groupsOfNodes );
1668     int nbFaceAtferMerge = tgtSubMesh->GetSubMeshDS()->NbElements();
1669     if ( nbFaceBeforeMerge != nbFaceAtferMerge && !helper.HasDegeneratedEdges() )
1670       return error(COMPERR_BAD_INPUT_MESH, "Probably invalid node parameters on geom faces");
1671
1672     // ----------------------------------------------------------------
1673     // The mapper can't create quadratic elements, so convert if needed
1674     // ----------------------------------------------------------------
1675
1676     SMDS_ElemIteratorPtr faceIt;
1677     faceIt         = srcSubMesh->GetSubMeshDS()->GetElements();
1678     bool srcIsQuad = faceIt->next()->IsQuadratic();
1679     faceIt         = tgtSubMesh->GetSubMeshDS()->GetElements();
1680     bool tgtIsQuad = faceIt->next()->IsQuadratic();
1681     if ( srcIsQuad && !tgtIsQuad )
1682     {
1683       TIDSortedElemSet tgtFaces;
1684       faceIt = tgtSubMesh->GetSubMeshDS()->GetElements();
1685       while ( faceIt->more() )
1686         tgtFaces.insert( tgtFaces.end(), faceIt->next() );
1687
1688       editor.ConvertToQuadratic(/*theForce3d=*/false, tgtFaces, false);
1689     }
1690   } // end of coincident nodes and quadratic elements treatment
1691
1692
1693   if ( !projDone || is1DComputed )
1694     // ----------------------------------------------------------------
1695     // The mapper can create distorted faces by placing nodes out of the FACE
1696     // boundary, also bad face can be created if EDGEs already discretized
1697     // --> fix bad faces by smoothing
1698     // ----------------------------------------------------------------
1699     if ( helper.IsDistorted2D( tgtSubMesh, /*checkUV=*/false, &helper ))
1700     {
1701       TAssocTool::Morph morph( srcWires );
1702       morph.Perform( helper, tgtWires, helper.GetSurface( tgtFace ),
1703                      _src2tgtNodes, /*moveAll=*/true );
1704
1705       if ( !fixDistortedFaces( helper, tgtWires ))
1706         return error("Invalid mesh generated");
1707     }
1708   // ---------------------------
1709   // Check elements orientation
1710   // ---------------------------
1711
1712   TopoDS_Face face = TopoDS::Face( theShape );
1713   if ( !theMesh.IsMainShape( tgtFace ))
1714   {
1715     // find the main shape
1716     TopoDS_Shape mainShape = meshDS->ShapeToMesh();
1717     switch ( mainShape.ShapeType() ) {
1718     case TopAbs_SHELL:
1719     case TopAbs_SOLID: break;
1720     default:
1721       TopTools_ListIteratorOfListOfShape ancestIt = theMesh.GetAncestors( face );
1722       for ( ; ancestIt.More(); ancestIt.Next() ) {
1723         TopAbs_ShapeEnum type = ancestIt.Value().ShapeType();
1724         if ( type == TopAbs_SOLID ) {
1725           mainShape = ancestIt.Value();
1726           break;
1727         } else if ( type == TopAbs_SHELL ) {
1728           mainShape = ancestIt.Value();
1729         }
1730       }
1731     }
1732     // find tgtFace in the main solid or shell to know it's true orientation.
1733     TopExp_Explorer exp( mainShape, TopAbs_FACE );
1734     for ( ; exp.More(); exp.Next() ) {
1735       if ( tgtFace.IsSame( exp.Current() )) {
1736         face = TopoDS::Face( exp.Current() );
1737         break;
1738       }
1739     }
1740   }
1741   // Fix orientation
1742   if ( helper.IsReversedSubMesh( face ))
1743   {
1744     SMESH_MeshEditor editor( tgtMesh );
1745     SMDS_ElemIteratorPtr eIt = meshDS->MeshElements( face )->GetElements();
1746     while ( eIt->more() ) {
1747       const SMDS_MeshElement* e = eIt->next();
1748       if ( e->GetType() == SMDSAbs_Face && !editor.Reorient( e ))
1749         RETURN_BAD_RESULT("Pb of SMESH_MeshEditor::Reorient()");
1750     }
1751   }
1752
1753   cleaner.Release(); // not to remove mesh
1754
1755   return true;
1756 }
1757
1758
1759 //=======================================================================
1760 //function : Evaluate
1761 //purpose  : 
1762 //=======================================================================
1763
1764 bool StdMeshers_Projection_2D::Evaluate(SMESH_Mesh&         theMesh,
1765                                         const TopoDS_Shape& theShape,
1766                                         MapShapeNbElems&    aResMap)
1767 {
1768   if ( !_sourceHypo )
1769     return false;
1770
1771   SMESH_Mesh * srcMesh = _sourceHypo->GetSourceMesh();
1772   SMESH_Mesh * tgtMesh = & theMesh;
1773   if ( !srcMesh )
1774     srcMesh = tgtMesh;
1775
1776   // ---------------------------
1777   // Make sub-shapes association
1778   // ---------------------------
1779
1780   TopoDS_Face tgtFace = TopoDS::Face( theShape.Oriented(TopAbs_FORWARD));
1781   TopoDS_Shape srcShape = _sourceHypo->GetSourceFace().Oriented(TopAbs_FORWARD);
1782
1783   TAssocTool::TShapeShapeMap shape2ShapeMap;
1784   TAssocTool::InitVertexAssociation( _sourceHypo, shape2ShapeMap );
1785   if ( !TAssocTool::FindSubShapeAssociation( tgtFace, tgtMesh, srcShape, srcMesh,
1786                                              shape2ShapeMap)  ||
1787        !shape2ShapeMap.IsBound( tgtFace ))
1788     return error(COMPERR_BAD_SHAPE,"Topology of source and target faces seems different" );
1789
1790   TopoDS_Face srcFace = TopoDS::Face( shape2ShapeMap( tgtFace ).Oriented(TopAbs_FORWARD));
1791
1792   // -------------------------------------------------------
1793   // Assure that mesh on a source Face is computed/evaluated
1794   // -------------------------------------------------------
1795
1796   std::vector<int> aVec;
1797
1798   SMESH_subMesh* srcSubMesh = srcMesh->GetSubMesh( srcFace );
1799   if ( srcSubMesh->IsMeshComputed() )
1800   {
1801     aVec.resize( SMDSEntity_Last, 0 );
1802     aVec[SMDSEntity_Node] = srcSubMesh->GetSubMeshDS()->NbNodes();
1803
1804     SMDS_ElemIteratorPtr elemIt = srcSubMesh->GetSubMeshDS()->GetElements();
1805     while ( elemIt->more() )
1806       aVec[ elemIt->next()->GetEntityType() ]++;
1807   }
1808   else
1809   {
1810     MapShapeNbElems  tmpResMap;
1811     MapShapeNbElems& srcResMap = (srcMesh == tgtMesh) ? aResMap : tmpResMap;
1812     if ( !_gen->Evaluate( *srcMesh, srcShape, srcResMap ))
1813       return error(COMPERR_BAD_INPUT_MESH,"Source mesh not evaluatable");
1814     aVec = srcResMap[ srcSubMesh ];
1815     if ( aVec.empty() )
1816       return error(COMPERR_BAD_INPUT_MESH,"Source mesh is wrongly evaluated");
1817   }
1818
1819   SMESH_subMesh * sm = theMesh.GetSubMesh(theShape);
1820   aResMap.insert(std::make_pair(sm,aVec));
1821
1822   return true;
1823 }
1824
1825
1826 //=============================================================================
1827 /*!
1828  * \brief Sets a default event listener to submesh of the source face
1829   * \param subMesh - submesh where algo is set
1830  *
1831  * This method is called when a submesh gets HYP_OK algo_state.
1832  * After being set, event listener is notified on each event of a submesh.
1833  * Arranges that CLEAN event is translated from source submesh to
1834  * the submesh
1835  */
1836 //=============================================================================
1837
1838 void StdMeshers_Projection_2D::SetEventListener(SMESH_subMesh* subMesh)
1839 {
1840   TAssocTool::SetEventListener( subMesh,
1841                                 _sourceHypo->GetSourceFace(),
1842                                 _sourceHypo->GetSourceMesh() );
1843 }