1 // Copyright (C) 2007-2016 CEA/DEN, EDF R&D, OPEN CASCADE
3 // Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
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.
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.
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
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
23 // SMESH SMESH : implementaion of SMESH idl descriptions
24 // File : StdMeshers_Projection_2D.cxx
26 // Created : Fri Oct 20 11:37:07 2006
27 // Author : Edward AGAPOV (eap)
29 #include "StdMeshers_Projection_2D.hxx"
31 #include "StdMeshers_ProjectionSource2D.hxx"
32 #include "StdMeshers_ProjectionUtils.hxx"
33 #include "StdMeshers_FaceSide.hxx"
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"
50 #include <utilities.h>
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>
61 #include <TopExp_Explorer.hxx>
62 #include <TopTools_DataMapIteratorOfDataMapOfShapeShape.hxx>
63 #include <TopTools_ListIteratorOfListOfShape.hxx>
64 #include <TopTools_MapOfShape.hxx>
66 #include <TopoDS_Solid.hxx>
69 #include <gp_GTrsf.hxx>
74 #define RETURN_BAD_RESULT(msg) { MESSAGE(")-: Error: " << msg); return false; }
76 namespace TAssocTool = StdMeshers_ProjectionUtils;
77 //typedef StdMeshers_ProjectionUtils TAssocTool;
79 //=======================================================================
80 //function : StdMeshers_Projection_2D
82 //=======================================================================
84 StdMeshers_Projection_2D::StdMeshers_Projection_2D(int hypId, int studyId, SMESH_Gen* gen)
85 :SMESH_2D_Algo(hypId, studyId, gen)
87 _name = "Projection_2D";
88 _compatibleHypothesis.push_back("ProjectionSource2D");
92 //================================================================================
96 //================================================================================
98 StdMeshers_Projection_2D::~StdMeshers_Projection_2D()
101 //=======================================================================
102 //function : CheckHypothesis
104 //=======================================================================
106 bool StdMeshers_Projection_2D::CheckHypothesis(SMESH_Mesh& theMesh,
107 const TopoDS_Shape& theShape,
108 SMESH_Hypothesis::Hypothesis_Status& theStatus)
110 list <const SMESHDS_Hypothesis * >::const_iterator itl;
112 const list <const SMESHDS_Hypothesis * >&hyps = GetUsedHypothesis(theMesh, theShape);
113 if ( hyps.size() == 0 )
115 theStatus = HYP_MISSING;
116 return false; // can't work with no hypothesis
119 if ( hyps.size() > 1 )
121 theStatus = HYP_ALREADY_EXIST;
125 const SMESHDS_Hypothesis *theHyp = hyps.front();
127 string hypName = theHyp->GetName();
131 if (hypName == "ProjectionSource2D")
133 _sourceHypo = static_cast<const StdMeshers_ProjectionSource2D *>(theHyp);
135 // Check hypo parameters
137 SMESH_Mesh* srcMesh = _sourceHypo->GetSourceMesh();
138 SMESH_Mesh* tgtMesh = & theMesh;
143 if ( _sourceHypo->HasVertexAssociation() )
146 TopoDS_Shape edge = TAssocTool::GetEdgeByVertices
147 ( srcMesh, _sourceHypo->GetSourceVertex(1), _sourceHypo->GetSourceVertex(2) );
148 if ( edge.IsNull() ||
149 !SMESH_MesherHelper::IsSubShape( edge, srcMesh ) ||
150 !SMESH_MesherHelper::IsSubShape( edge, _sourceHypo->GetSourceFace() ))
152 theStatus = HYP_BAD_PARAMETER;
153 error("Invalid source vertices");
154 SCRUTE((edge.IsNull()));
155 SCRUTE((SMESH_MesherHelper::IsSubShape( edge, srcMesh )));
156 SCRUTE((SMESH_MesherHelper::IsSubShape( edge, _sourceHypo->GetSourceFace() )));
161 edge = TAssocTool::GetEdgeByVertices
162 ( tgtMesh, _sourceHypo->GetTargetVertex(1), _sourceHypo->GetTargetVertex(2) );
163 if ( edge.IsNull() || !SMESH_MesherHelper::IsSubShape( edge, tgtMesh ))
165 theStatus = HYP_BAD_PARAMETER;
166 error("Invalid target vertices");
167 SCRUTE((edge.IsNull()));
168 SCRUTE((SMESH_MesherHelper::IsSubShape( edge, tgtMesh )));
171 else if ( !_sourceHypo->IsCompoundSource() &&
172 !SMESH_MesherHelper::IsSubShape( edge, theShape ))
174 theStatus = HYP_BAD_PARAMETER;
175 error("Invalid target vertices");
176 SCRUTE((SMESH_MesherHelper::IsSubShape( edge, theShape )));
180 // check a source face
181 if ( !SMESH_MesherHelper::IsSubShape( _sourceHypo->GetSourceFace(), srcMesh ) ||
182 ( srcMesh == tgtMesh && theShape == _sourceHypo->GetSourceFace() ))
184 theStatus = HYP_BAD_PARAMETER;
185 error("Invalid source face");
186 SCRUTE((SMESH_MesherHelper::IsSubShape( _sourceHypo->GetSourceFace(), srcMesh )));
187 SCRUTE((srcMesh == tgtMesh));
188 SCRUTE(( theShape == _sourceHypo->GetSourceFace() ));
193 theStatus = HYP_INCOMPATIBLE;
195 return ( theStatus == HYP_OK );
200 //================================================================================
202 * \brief define if a node is new or old
203 * \param node - node to check
204 * \retval bool - true if the node existed before Compute() is called
206 //================================================================================
208 bool isOldNode( const SMDS_MeshNode* node )
210 // old nodes are shared by edges and new ones are shared
211 // only by faces created by mapper
212 //if ( is1DComputed )
214 bool isOld = node->NbInverseElements(SMDSAbs_Edge) > 0;
219 // SMDS_ElemIteratorPtr invFace = node->GetInverseElementIterator(SMDSAbs_Face);
220 // bool isNew = invFace->more();
225 //================================================================================
227 * \brief Class to remove mesh built by pattern mapper on edges
228 * and vertices in the case of failure of projection algo.
229 * It does it's job at destruction
231 //================================================================================
236 MeshCleaner( SMESH_subMesh* faceSubMesh ): sm(faceSubMesh) {}
237 ~MeshCleaner() { Clean(sm); }
238 void Release() { sm = 0; } // mesh will not be removed
239 static void Clean( SMESH_subMesh* sm, bool withSub=true )
241 if ( !sm || !sm->GetSubMeshDS() ) return;
242 // PAL16567, 18920. Remove face nodes as well
243 // switch ( sm->GetSubShape().ShapeType() ) {
244 // case TopAbs_VERTEX:
245 // case TopAbs_EDGE: {
246 SMDS_NodeIteratorPtr nIt = sm->GetSubMeshDS()->GetNodes();
247 SMESHDS_Mesh* mesh = sm->GetFather()->GetMeshDS();
248 while ( nIt->more() ) {
249 const SMDS_MeshNode* node = nIt->next();
250 if ( !isOldNode( node ) )
251 mesh->RemoveNode( node );
253 // do not break but iterate over DependsOn()
256 if ( !withSub ) return;
257 SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(false,false);
258 while ( smIt->more() )
259 Clean( smIt->next(), false );
264 //================================================================================
266 * \brief find new nodes belonging to one free border of mesh on face
267 * \param sm - submesh on edge or vertex containing nodes to choose from
268 * \param face - the face bound by the submesh
269 * \param u2nodes - map to fill with nodes
270 * \param seamNodes - set of found nodes
271 * \retval bool - is a success
273 //================================================================================
275 bool getBoundaryNodes ( SMESH_subMesh* sm,
276 const TopoDS_Face& face,
277 map< double, const SMDS_MeshNode* > & u2nodes,
278 set< const SMDS_MeshNode* > & seamNodes)
282 if ( !sm || !sm->GetSubMeshDS() )
283 RETURN_BAD_RESULT("Null submesh");
285 SMDS_NodeIteratorPtr nIt = sm->GetSubMeshDS()->GetNodes();
286 switch ( sm->GetSubShape().ShapeType() ) {
288 case TopAbs_VERTEX: {
289 while ( nIt->more() ) {
290 const SMDS_MeshNode* node = nIt->next();
291 if ( isOldNode( node ) ) continue;
292 u2nodes.insert( make_pair( 0., node ));
293 seamNodes.insert( node );
300 // Get submeshes of sub-vertices
301 const map< int, SMESH_subMesh * >& subSM = sm->DependsOn();
302 if ( subSM.size() != 2 )
303 RETURN_BAD_RESULT("there must be 2 submeshes of sub-vertices"
304 " but we have " << subSM.size());
305 SMESH_subMesh* smV1 = subSM.begin()->second;
306 SMESH_subMesh* smV2 = subSM.rbegin()->second;
307 if ( !smV1->IsMeshComputed() || !smV2->IsMeshComputed() )
308 RETURN_BAD_RESULT("Empty vertex submeshes");
310 const SMDS_MeshNode* nV1 = 0;
311 const SMDS_MeshNode* nE = 0;
313 // Look for nV1 - a new node on V1
314 nIt = smV1->GetSubMeshDS()->GetNodes();
315 while ( nIt->more() && !nE ) {
316 const SMDS_MeshNode* node = nIt->next();
317 if ( isOldNode( node ) ) continue;
320 // Find nE - a new node connected to nV1 and belonging to edge submesh;
321 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
322 SMDS_ElemIteratorPtr vElems = nV1->GetInverseElementIterator(SMDSAbs_Face);
323 while ( vElems->more() && !nE ) {
324 const SMDS_MeshElement* elem = vElems->next();
325 int nbNodes = elem->NbNodes();
326 if ( elem->IsQuadratic() )
328 int iV1 = elem->GetNodeIndex( nV1 );
329 // try next after nV1
330 int iE = SMESH_MesherHelper::WrapIndex( iV1 + 1, nbNodes );
331 if ( smDS->Contains( elem->GetNode( iE ) ))
332 nE = elem->GetNode( iE );
334 // try node before nV1
335 iE = SMESH_MesherHelper::WrapIndex( iV1 - 1, nbNodes );
336 if ( smDS->Contains( elem->GetNode( iE )))
337 nE = elem->GetNode( iE );
339 if ( nE && elem->IsQuadratic() ) { // find medium node between nV1 and nE
340 if ( Abs( iV1 - iE ) == 1 )
341 nE = elem->GetNode( Min ( iV1, iE ) + nbNodes );
343 nE = elem->GetNode( elem->NbNodes() - 1 );
348 RETURN_BAD_RESULT("No new node found on V1");
350 RETURN_BAD_RESULT("new node on edge not found");
352 // Get the whole free border of a face
353 list< const SMDS_MeshNode* > bordNodes;
354 list< const SMDS_MeshElement* > bordFaces;
355 if ( !SMESH_MeshEditor::FindFreeBorder (nV1, nE, nV1, bordNodes, bordFaces ))
356 RETURN_BAD_RESULT("free border of a face not found by nodes " <<
357 nV1->GetID() << " " << nE->GetID() );
359 // Insert nodes of the free border to the map until node on V2 encountered
360 SMESHDS_SubMesh* v2smDS = smV2->GetSubMeshDS();
361 list< const SMDS_MeshNode* >::iterator bordIt = bordNodes.begin();
362 bordIt++; // skip nV1
363 for ( ; bordIt != bordNodes.end(); ++bordIt ) {
364 const SMDS_MeshNode* node = *bordIt;
365 if ( v2smDS->Contains( node ))
367 if ( node->GetPosition()->GetTypeOfPosition() != SMDS_TOP_EDGE )
368 RETURN_BAD_RESULT("Bad node position type: node " << node->GetID() <<
369 " pos type " << node->GetPosition()->GetTypeOfPosition());
370 const SMDS_EdgePosition* pos =
371 static_cast<const SMDS_EdgePosition*>(node->GetPosition());
372 u2nodes.insert( make_pair( pos->GetUParameter(), node ));
373 seamNodes.insert( node );
375 if ( u2nodes.size() != seamNodes.size() )
376 RETURN_BAD_RESULT("Bad node params on edge " << sm->GetId() <<
377 ", " << u2nodes.size() << " != " << seamNodes.size() );
382 RETURN_BAD_RESULT ("Unexpected submesh type");
384 } // bool getBoundaryNodes()
386 //================================================================================
388 * \brief Check if two consecutive EDGEs are connected in 2D
389 * \param [in] E1 - a well oriented non-seam EDGE
390 * \param [in] E2 - a possibly well oriented seam EDGE
391 * \param [in] F - a FACE
392 * \return bool - result
394 //================================================================================
396 bool are2dConnected( const TopoDS_Edge & E1,
397 const TopoDS_Edge & E2,
398 const TopoDS_Face & F )
401 Handle(Geom2d_Curve) c1 = BRep_Tool::CurveOnSurface( E1, F, f, l );
402 gp_Pnt2d uvFirst1 = c1->Value( f );
403 gp_Pnt2d uvLast1 = c1->Value( l );
405 Handle(Geom2d_Curve) c2 = BRep_Tool::CurveOnSurface( E2, F, f, l );
406 gp_Pnt2d uvFirst2 = c2->Value( E2.Orientation() == TopAbs_REVERSED ? l : f );
407 double tol2 = Max( Precision::PConfusion() * Precision::PConfusion(),
408 1e-5 * uvLast1.SquareDistance( uvFirst1 ));
410 return (( uvFirst2.SquareDistance( uvFirst1 ) < tol2 ) ||
411 ( uvFirst2.SquareDistance( uvLast1 ) < tol2 ));
414 //================================================================================
416 * \brief Compose TSideVector for both FACEs keeping matching order of EDGEs
417 * and fill src2tgtNodes map
419 //================================================================================
421 TError getWires(const TopoDS_Face& tgtFace,
422 const TopoDS_Face& srcFace,
423 SMESH_Mesh * tgtMesh,
424 SMESH_Mesh * srcMesh,
425 const TAssocTool::TShapeShapeMap& shape2ShapeMap,
426 TSideVector& srcWires,
427 TSideVector& tgtWires,
428 TAssocTool::TNodeNodeMap& src2tgtNodes,
431 src2tgtNodes.clear();
433 // get ordered src EDGEs
435 srcWires = StdMeshers_FaceSide::GetFaceWires( srcFace, *srcMesh,/*skipMediumNodes=*/0, err);
436 if (( err && !err->IsOK() ) ||
437 ( srcWires.empty() ))
440 SMESH_MesherHelper srcHelper( *srcMesh );
441 srcHelper.SetSubShape( srcFace );
443 // make corresponding sequence of tgt EDGEs
444 tgtWires.resize( srcWires.size() );
445 for ( size_t iW = 0; iW < srcWires.size(); ++iW )
447 StdMeshers_FaceSidePtr srcWire = srcWires[iW];
449 list< TopoDS_Edge > tgtEdges;
450 TopTools_IndexedMapOfShape edgeMap; // to detect seam edges
451 for ( int iE = 0; iE < srcWire->NbEdges(); ++iE )
453 TopoDS_Edge srcE = srcWire->Edge( iE );
454 TopoDS_Edge tgtE = TopoDS::Edge( shape2ShapeMap( srcE, /*isSrc=*/true));
455 TopoDS_Shape srcEbis = shape2ShapeMap( tgtE, /*isSrc=*/false );
456 if ( srcE.Orientation() != srcEbis.Orientation() )
458 // reverse a seam edge encountered for the second time
459 const int index = edgeMap.Add( tgtE );
460 if ( index < edgeMap.Extent() ) // E is a seam
462 // check which of edges to reverse, E or one already being in tgtEdges
463 if ( are2dConnected( tgtEdges.back(), tgtE, tgtFace ))
465 list< TopoDS_Edge >::iterator eIt = tgtEdges.begin();
466 std::advance( eIt, index-1 );
467 if ( are2dConnected( tgtEdges.back(), *eIt, tgtFace ))
475 if ( srcWire->NbEdges() == 1 && tgtMesh == srcMesh ) // circle
477 // try to verify ori by propagation
478 pair<int,TopoDS_Edge> nE =
479 StdMeshers_ProjectionUtils::GetPropagationEdge( srcMesh, tgtE, srcE );
480 if ( !nE.second.IsNull() )
483 tgtEdges.push_back( tgtE );
486 tgtWires[ iW ].reset( new StdMeshers_FaceSide( tgtFace, tgtEdges, tgtMesh,
487 /*theIsForward = */ true,
488 /*theIgnoreMediumNodes = */false));
489 StdMeshers_FaceSidePtr tgtWire = tgtWires[ iW ];
491 // Fill map of src to tgt nodes with nodes on edges
493 for ( int iE = 0; iE < srcWire->NbEdges(); ++iE )
495 if ( srcMesh->GetSubMesh( srcWire->Edge(iE) )->IsEmpty() ||
496 tgtMesh->GetSubMesh( tgtWire->Edge(iE) )->IsEmpty() )
498 // add nodes on VERTEXes for a case of not meshes EDGEs
499 const SMDS_MeshNode* srcN = srcWire->VertexNode( iE );
500 const SMDS_MeshNode* tgtN = tgtWire->VertexNode( iE );
502 src2tgtNodes.insert( make_pair( srcN, tgtN ));
506 const bool skipMedium = true, isFwd = true;
507 StdMeshers_FaceSide srcEdge( srcFace, srcWire->Edge(iE), srcMesh, isFwd, skipMedium);
508 StdMeshers_FaceSide tgtEdge( tgtFace, tgtWire->Edge(iE), tgtMesh, isFwd, skipMedium);
510 vector< const SMDS_MeshNode* > srcNodes = srcEdge.GetOrderedNodes();
511 vector< const SMDS_MeshNode* > tgtNodes = tgtEdge.GetOrderedNodes();
513 if (( srcNodes.size() != tgtNodes.size() ) && tgtNodes.size() > 0 )
514 return SMESH_ComputeError::New( COMPERR_BAD_INPUT_MESH,
515 "Different number of nodes on edges");
516 if ( !tgtNodes.empty() )
518 vector< const SMDS_MeshNode* >::iterator tn = tgtNodes.begin();
519 //if ( srcWire->Edge(iE).Orientation() == tgtWire->Edge(iE).Orientation() )
521 vector< const SMDS_MeshNode* >::iterator sn = srcNodes.begin();
522 for ( ; tn != tgtNodes.end(); ++tn, ++sn)
523 src2tgtNodes.insert( make_pair( *sn, *tn ));
527 // vector< const SMDS_MeshNode* >::reverse_iterator sn = srcNodes.rbegin();
528 // for ( ; tn != tgtNodes.end(); ++tn, ++sn)
529 // src2tgtNodes.insert( make_pair( *sn, *tn ));
534 } // loop on EDGEs of a WIRE
541 //================================================================================
543 * \brief Preform projection in case if tgtFace.IsPartner( srcFace ) and in case
544 * if projection by 3D transformation is possible
546 //================================================================================
548 bool projectPartner(const TopoDS_Face& tgtFace,
549 const TopoDS_Face& srcFace,
550 const TSideVector& tgtWires,
551 const TSideVector& srcWires,
552 const TAssocTool::TShapeShapeMap& shape2ShapeMap,
553 TAssocTool::TNodeNodeMap& src2tgtNodes,
554 const bool is1DComputed)
556 SMESH_Mesh * tgtMesh = tgtWires[0]->GetMesh();
557 SMESH_Mesh * srcMesh = srcWires[0]->GetMesh();
558 SMESHDS_Mesh* tgtMeshDS = tgtMesh->GetMeshDS();
559 SMESHDS_Mesh* srcMeshDS = srcMesh->GetMeshDS();
560 SMESH_MesherHelper helper( *tgtMesh );
562 const double tol = 1.e-7 * srcMeshDS->getMaxDim();
564 // transformation to get location of target nodes from source ones
565 StdMeshers_ProjectionUtils::TrsfFinder3D trsf;
566 bool trsfIsOK = false;
567 if ( tgtFace.IsPartner( srcFace ))
569 gp_GTrsf srcTrsf = srcFace.Location().Transformation();
570 gp_GTrsf tgtTrsf = tgtFace.Location().Transformation();
571 gp_GTrsf t = srcTrsf.Inverted().Multiplied( tgtTrsf );
574 gp_Pnt srcP = BRep_Tool::Pnt( srcWires[0]->FirstVertex() );
575 gp_Pnt tgtP = BRep_Tool::Pnt( tgtWires[0]->FirstVertex() );
576 trsfIsOK = ( tgtP.Distance( trsf.Transform( srcP )) < tol );
579 trsf.Set( tgtTrsf.Inverted().Multiplied( srcTrsf ));
580 trsfIsOK = ( tgtP.Distance( trsf.Transform( srcP )) < tol );
585 // Try to find the 3D transformation
587 const int totNbSeg = 50;
588 vector< gp_XYZ > srcPnts, tgtPnts;
589 srcPnts.reserve( totNbSeg );
590 tgtPnts.reserve( totNbSeg );
591 gp_XYZ srcBC( 0,0,0 ), tgtBC( 0,0,0 );
592 for ( size_t iW = 0; iW < srcWires.size(); ++iW )
594 const double minSegLen = srcWires[iW]->Length() / totNbSeg;
595 for ( int iE = 0; iE < srcWires[iW]->NbEdges(); ++iE )
597 size_t nbSeg = Max( 1, int( srcWires[iW]->EdgeLength( iE ) / minSegLen ));
598 double srcU = srcWires[iW]->FirstParameter( iE );
599 double tgtU = tgtWires[iW]->FirstParameter( iE );
600 double srcDu = ( srcWires[iW]->LastParameter( iE )- srcU ) / nbSeg;
601 double tgtDu = ( tgtWires[iW]->LastParameter( iE )- tgtU ) / nbSeg;
602 for ( size_t i = 0; i < nbSeg; ++i )
604 srcPnts.push_back( srcWires[iW]->Value3d( srcU ).XYZ() );
605 tgtPnts.push_back( tgtWires[iW]->Value3d( tgtU ).XYZ() );
608 srcBC += srcPnts.back();
609 tgtBC += tgtPnts.back();
613 if ( !trsf.Solve( srcPnts, tgtPnts ))
618 const int nbTestPnt = 20;
619 const size_t iStep = Max( 1, int( srcPnts.size() / nbTestPnt ));
621 gp_Pnt trsfTgt = trsf.Transform( srcBC / srcPnts.size() );
622 trsfIsOK = ( trsfTgt.SquareDistance( tgtBC / tgtPnts.size() ) < tol*tol );
623 for ( size_t i = 0; ( i < srcPnts.size() && trsfIsOK ); i += iStep )
625 gp_Pnt trsfTgt = trsf.Transform( srcPnts[i] );
626 trsfIsOK = ( trsfTgt.SquareDistance( tgtPnts[i] ) < tol*tol );
628 // check an in-FACE point
631 BRepAdaptor_Surface srcSurf( srcFace );
633 srcSurf.Value( 0.321 * ( srcSurf.FirstUParameter() + srcSurf.LastUParameter() ),
634 0.123 * ( srcSurf.FirstVParameter() + srcSurf.LastVParameter() ));
635 gp_Pnt tgtTrsfP = trsf.Transform( srcP );
637 GeomAPI_ProjectPointOnSurf& proj = helper.GetProjector( tgtFace, loc, 0.1*tol );
638 if ( !loc.IsIdentity() )
639 tgtTrsfP.Transform( loc.Transformation().Inverted() );
640 proj.Perform( tgtTrsfP );
641 trsfIsOK = ( proj.IsDone() &&
642 proj.NbPoints() > 0 &&
643 proj.LowerDistance() < tol );
651 // prepare the helper to adding quadratic elements if necessary
652 //helper.SetSubShape( tgtFace );
653 helper.IsQuadraticSubMesh( tgtFace );
655 SMESHDS_SubMesh* srcSubDS = srcMeshDS->MeshElements( srcFace );
656 if ( !is1DComputed && srcSubDS->NbElements() )
657 helper.SetIsQuadratic( srcSubDS->GetElements()->next()->IsQuadratic() );
659 SMESH_MesherHelper srcHelper( *srcMesh );
660 srcHelper.SetSubShape( srcFace );
661 SMESH_MesherHelper edgeHelper( *tgtMesh );
662 edgeHelper.ToFixNodeParameters( true );
664 const SMDS_MeshNode* nullNode = 0;
665 TAssocTool::TNodeNodeMap::iterator srcN_tgtN;
667 // indices of nodes to create properly oriented faces
668 bool isReverse = ( !trsf.IsIdentity() );
669 int tri1 = 1, tri2 = 2, quad1 = 1, quad3 = 3;
671 std::swap( tri1, tri2 ), std::swap( quad1, quad3 );
673 SMDS_ElemIteratorPtr elemIt = srcSubDS->GetElements();
674 vector< const SMDS_MeshNode* > tgtNodes;
675 while ( elemIt->more() ) // loop on all mesh faces on srcFace
677 const SMDS_MeshElement* elem = elemIt->next();
678 const int nbN = elem->NbCornerNodes();
679 tgtNodes.resize( nbN );
680 helper.SetElementsOnShape( false );
681 for ( int i = 0; i < nbN; ++i ) // loop on nodes of the source element
683 const SMDS_MeshNode* srcNode = elem->GetNode(i);
684 srcN_tgtN = src2tgtNodes.insert( make_pair( srcNode, nullNode )).first;
685 if ( srcN_tgtN->second == nullNode )
688 gp_Pnt tgtP = trsf.Transform( SMESH_TNodeXYZ( srcNode ));
689 SMDS_MeshNode* n = helper.AddNode( tgtP.X(), tgtP.Y(), tgtP.Z() );
690 srcN_tgtN->second = n;
691 switch ( srcNode->GetPosition()->GetTypeOfPosition() )
695 gp_Pnt2d srcUV = srcHelper.GetNodeUV( srcFace, srcNode );
696 tgtMeshDS->SetNodeOnFace( n, helper.GetSubShapeID(), srcUV.X(), srcUV.Y() );
701 const TopoDS_Edge& srcE = TopoDS::Edge( srcMeshDS->IndexToShape( srcNode->getshapeId()));
702 const TopoDS_Edge& tgtE = TopoDS::Edge( shape2ShapeMap( srcE, /*isSrc=*/true ));
703 double srcU = srcHelper.GetNodeU( srcE, srcNode );
704 tgtMeshDS->SetNodeOnEdge( n, tgtE, srcU );
705 if ( !tgtFace.IsPartner( srcFace ))
707 edgeHelper.SetSubShape( tgtE );
708 double tol = BRep_Tool::Tolerance( tgtE );
709 bool isOk = edgeHelper.CheckNodeU( tgtE, n, srcU, 2 * tol, /*force=*/true );
710 if ( !isOk ) // projection of n to tgtE failed (23395)
712 double sF, sL, tF, tL;
713 BRep_Tool::Range( srcE, sF, sL );
714 BRep_Tool::Range( tgtE, tF, tL );
715 double srcR = ( srcU - sF ) / ( sL - sF );
716 double tgtU = tF + srcR * ( tL - tF );
717 tgtMeshDS->SetNodeOnEdge( n, tgtE, tgtU );
718 gp_Pnt newP = BRepAdaptor_Curve( tgtE ).Value( tgtU );
719 double dist = newP.Distance( tgtP );
720 if ( tol < dist && dist < 1000*tol )
721 tgtMeshDS->MoveNode( n, newP.X(), newP.Y(), newP.Z() );
726 case SMDS_TOP_VERTEX:
728 const TopoDS_Shape & srcV = srcMeshDS->IndexToShape( srcNode->getshapeId() );
729 const TopoDS_Shape & tgtV = shape2ShapeMap( srcV, /*isSrc=*/true );
730 tgtMeshDS->SetNodeOnVertex( n, TopoDS::Vertex( tgtV ));
736 tgtNodes[i] = srcN_tgtN->second;
739 helper.SetElementsOnShape( true );
742 case 3: helper.AddFace(tgtNodes[0], tgtNodes[tri1], tgtNodes[tri2]); break;
743 case 4: helper.AddFace(tgtNodes[0], tgtNodes[quad1], tgtNodes[2], tgtNodes[quad3]); break;
745 if ( isReverse ) std::reverse( tgtNodes.begin(), tgtNodes.end() );
746 helper.AddPolygonalFace( tgtNodes );
750 // check node positions
752 if ( !tgtFace.IsPartner( srcFace ) )
754 helper.ToFixNodeParameters( true );
757 const double tol2d = 1e-12;
758 srcN_tgtN = src2tgtNodes.begin();
759 for ( ; srcN_tgtN != src2tgtNodes.end(); ++srcN_tgtN )
761 const SMDS_MeshNode* n = srcN_tgtN->second;
762 switch ( n->GetPosition()->GetTypeOfPosition() )
766 if ( nbOkPos > 10 ) break;
767 gp_XY uv = helper.GetNodeUV( tgtFace, n ), uvBis = uv;
768 if (( helper.CheckNodeUV( tgtFace, n, uv, tol )) &&
769 (( uv - uvBis ).SquareModulus() < tol2d ))
772 nbOkPos = -((int) src2tgtNodes.size() );
777 // const TopoDS_Edge & tgtE = TopoDS::Edge( tgtMeshDS->IndexToShape( n->getshapeId() ));
778 // edgeHelper.SetSubShape( tgtE );
779 // edgeHelper.GetNodeU( tgtE, n, 0, &toCheck );
789 } // bool projectPartner()
791 //================================================================================
793 * \brief Preform projection in case if the faces are similar in 2D space
795 //================================================================================
797 bool projectBy2DSimilarity(const TopoDS_Face& tgtFace,
798 const TopoDS_Face& srcFace,
799 const TSideVector& tgtWires,
800 const TSideVector& srcWires,
801 const TAssocTool::TShapeShapeMap& shape2ShapeMap,
802 TAssocTool::TNodeNodeMap& src2tgtNodes,
803 const bool is1DComputed)
805 SMESH_Mesh * tgtMesh = tgtWires[0]->GetMesh();
806 SMESH_Mesh * srcMesh = srcWires[0]->GetMesh();
808 // WARNING: we can have problems if the FACE is symmetrical in 2D,
809 // then the projection can be mirrored relating to what is expected
811 // 1) Find 2D transformation
813 StdMeshers_ProjectionUtils::TrsfFinder2D trsf;
815 // get 2 pairs of corresponding UVs
816 gp_Pnt2d srcP0 = srcWires[0]->Value2d(0.0);
817 gp_Pnt2d srcP1 = srcWires[0]->Value2d(0.333);
818 gp_Pnt2d tgtP0 = tgtWires[0]->Value2d(0.0);
819 gp_Pnt2d tgtP1 = tgtWires[0]->Value2d(0.333);
821 // make transformation
822 gp_Trsf2d fromTgtCS, toSrcCS; // from/to global CS
823 gp_Ax2d srcCS( srcP0, gp_Vec2d( srcP0, srcP1 ));
824 gp_Ax2d tgtCS( tgtP0, gp_Vec2d( tgtP0, tgtP1 ));
825 toSrcCS .SetTransformation( srcCS );
826 fromTgtCS.SetTransformation( tgtCS );
828 trsf.Set( fromTgtCS * toSrcCS );
830 // check transformation
831 bool trsfIsOK = true;
832 const double tol = 1e-5 * gp_Vec2d( srcP0, srcP1 ).Magnitude();
833 for ( double u = 0.12; ( u < 1. && trsfIsOK ); u += 0.1 )
835 gp_Pnt2d srcUV = srcWires[0]->Value2d( u );
836 gp_Pnt2d tgtUV = tgtWires[0]->Value2d( u );
837 gp_Pnt2d tgtUV2 = trsf.Transform( srcUV );
838 trsfIsOK = ( tgtUV.Distance( tgtUV2 ) < tol );
841 // Find trsf using a least-square approximation
845 const int totNbSeg = 50;
846 vector< gp_XY > srcPnts, tgtPnts;
847 srcPnts.reserve( totNbSeg );
848 tgtPnts.reserve( totNbSeg );
849 for ( size_t iW = 0; iW < srcWires.size(); ++iW )
851 const double minSegLen = srcWires[iW]->Length() / totNbSeg;
852 for ( int iE = 0; iE < srcWires[iW]->NbEdges(); ++iE )
854 size_t nbSeg = Max( 1, int( srcWires[iW]->EdgeLength( iE ) / minSegLen ));
855 double srcU = srcWires[iW]->FirstParameter( iE );
856 double tgtU = tgtWires[iW]->FirstParameter( iE );
857 double srcDu = ( srcWires[iW]->LastParameter( iE )- srcU ) / nbSeg;
858 double tgtDu = ( tgtWires[iW]->LastParameter( iE )- tgtU ) / nbSeg;
859 for ( size_t i = 0; i < nbSeg; ++i, srcU += srcDu, tgtU += tgtDu )
861 srcPnts.push_back( srcWires[iW]->Value2d( srcU ).XY() );
862 tgtPnts.push_back( tgtWires[iW]->Value2d( tgtU ).XY() );
866 if ( !trsf.Solve( srcPnts, tgtPnts ))
872 const int nbTestPnt = 10;
873 const size_t iStep = Max( 1, int( srcPnts.size() / nbTestPnt ));
874 for ( size_t i = 0; ( i < srcPnts.size() && trsfIsOK ); i += iStep )
876 gp_Pnt2d trsfTgt = trsf.Transform( srcPnts[i] );
877 trsfIsOK = ( trsfTgt.Distance( tgtPnts[i] ) < tol );
882 } // "Find transformation" block
886 SMESHDS_SubMesh* srcSubDS = srcMesh->GetMeshDS()->MeshElements( srcFace );
888 SMESH_MesherHelper helper( *tgtMesh );
889 helper.SetSubShape( tgtFace );
891 helper.IsQuadraticSubMesh( tgtFace );
893 helper.SetIsQuadratic( srcSubDS->GetElements()->next()->IsQuadratic() );
894 helper.SetElementsOnShape( true );
895 Handle(Geom_Surface) tgtSurface = BRep_Tool::Surface( tgtFace );
896 SMESHDS_Mesh* tgtMeshDS = tgtMesh->GetMeshDS();
898 SMESH_MesherHelper srcHelper( *srcMesh );
899 srcHelper.SetSubShape( srcFace );
901 const SMDS_MeshNode* nullNode = 0;
902 TAssocTool::TNodeNodeMap::iterator srcN_tgtN;
904 SMDS_ElemIteratorPtr elemIt = srcSubDS->GetElements();
905 vector< const SMDS_MeshNode* > tgtNodes;
907 while ( elemIt->more() ) // loop on all mesh faces on srcFace
909 const SMDS_MeshElement* elem = elemIt->next();
910 const int nbN = elem->NbCornerNodes();
911 tgtNodes.resize( nbN );
912 for ( int i = 0; i < nbN; ++i ) // loop on nodes of the source element
914 const SMDS_MeshNode* srcNode = elem->GetNode(i);
915 srcN_tgtN = src2tgtNodes.insert( make_pair( srcNode, nullNode )).first;
916 if ( srcN_tgtN->second == nullNode )
919 gp_Pnt2d srcUV = srcHelper.GetNodeUV( srcFace, srcNode,
920 elem->GetNode( helper.WrapIndex(i+1,nbN)), &uvOK);
921 gp_Pnt2d tgtUV = trsf.Transform( srcUV );
922 gp_Pnt tgtP = tgtSurface->Value( tgtUV.X(), tgtUV.Y() );
923 SMDS_MeshNode* n = tgtMeshDS->AddNode( tgtP.X(), tgtP.Y(), tgtP.Z() );
924 switch ( srcNode->GetPosition()->GetTypeOfPosition() )
926 case SMDS_TOP_FACE: {
927 tgtMeshDS->SetNodeOnFace( n, helper.GetSubShapeID(), tgtUV.X(), tgtUV.Y() );
930 case SMDS_TOP_EDGE: {
931 TopoDS_Shape srcEdge = srcHelper.GetSubShapeByNode( srcNode, srcHelper.GetMeshDS() );
932 TopoDS_Edge tgtEdge = TopoDS::Edge( shape2ShapeMap( srcEdge, /*isSrc=*/true ));
933 double U = Precision::Infinite();
934 helper.CheckNodeU( tgtEdge, n, U, Precision::PConfusion());
935 tgtMeshDS->SetNodeOnEdge( n, TopoDS::Edge( tgtEdge ), U );
938 case SMDS_TOP_VERTEX: {
939 TopoDS_Shape srcV = srcHelper.GetSubShapeByNode( srcNode, srcHelper.GetMeshDS() );
940 TopoDS_Shape tgtV = shape2ShapeMap( srcV, /*isSrc=*/true );
941 tgtMeshDS->SetNodeOnVertex( n, TopoDS::Vertex( tgtV ));
946 srcN_tgtN->second = n;
948 tgtNodes[i] = srcN_tgtN->second;
950 // create a new face (with reversed orientation)
953 case 3: helper.AddFace(tgtNodes[0], tgtNodes[2], tgtNodes[1]); break;
954 case 4: helper.AddFace(tgtNodes[0], tgtNodes[3], tgtNodes[2], tgtNodes[1]); break;
956 } // loop on all mesh faces on srcFace
961 //================================================================================
963 * \brief Preform projection in case of quadrilateral faces
965 //================================================================================
967 bool projectQuads(const TopoDS_Face& tgtFace,
968 const TopoDS_Face& srcFace,
969 const TSideVector& tgtWires,
970 const TSideVector& srcWires,
971 const TAssocTool::TShapeShapeMap& shape2ShapeMap,
972 TAssocTool::TNodeNodeMap& src2tgtNodes,
973 const bool is1DComputed)
975 // SMESH_Mesh * tgtMesh = tgtWires[0]->GetMesh();
976 // SMESH_Mesh * srcMesh = srcWires[0]->GetMesh();
977 // //SMESHDS_Mesh * tgtMeshDS = tgtMesh->GetMeshDS();
978 // SMESHDS_Mesh * srcMeshDS = srcMesh->GetMeshDS();
980 // if ( srcWires[0]->NbEdges() != 4 )
982 // if ( !is1DComputed )
984 // for ( int iE = 0; iE < 4; ++iE )
986 // SMESHDS_SubMesh* sm = srcMeshDS->MeshElements( srcWires[0]->Edge( iE ));
987 // if ( !sm ) return false;
988 // if ( sm->NbNodes() + sm->NbElements() == 0 ) return false;
990 // if ( BRepAdaptor_Surface( tgtFace ).GetType() != GeomAbs_Plane )
992 // // if ( BRepAdaptor_Surface( tgtFace ).GetType() == GeomAbs_Plane &&
993 // // BRepAdaptor_Surface( srcFace ).GetType() == GeomAbs_Plane )
994 // // return false; // too easy
996 // // load EDGEs to SMESH_Block
998 // SMESH_Block block;
999 // TopTools_IndexedMapOfOrientedShape blockSubShapes;
1001 // const TopoDS_Solid& box = srcMesh->PseudoShape();
1002 // TopoDS_Shell shell = TopoDS::Shell( TopExp_Explorer( box, TopAbs_SHELL ).Current() );
1004 // block.LoadBlockShapes( shell, v, v, blockSubShapes ); // fill all since operator[] is missing
1006 // const SMESH_Block::TShapeID srcFaceBID = SMESH_Block::ID_Fxy0;
1007 // const SMESH_Block::TShapeID tgtFaceBID = SMESH_Block::ID_Fxy1;
1008 // vector< int > edgeBID;
1009 // block.GetFaceEdgesIDs( srcFaceBID, edgeBID ); // u0, u1, 0v, 1v
1010 // blockSubShapes.Substitute( edgeBID[0], srcWires[0]->Edge(0) );
1011 // blockSubShapes.Substitute( edgeBID[1], srcWires[0]->Edge(2) );
1012 // blockSubShapes.Substitute( edgeBID[2], srcWires[0]->Edge(3) );
1013 // blockSubShapes.Substitute( edgeBID[3], srcWires[0]->Edge(1) );
1014 // block.GetFaceEdgesIDs( tgtFaceBID, edgeBID ); // u0, u1, 0v, 1v
1015 // blockSubShapes.Substitute( edgeBID[0], tgtWires[0]->Edge(0) );
1016 // blockSubShapes.Substitute( edgeBID[1], tgtWires[0]->Edge(2) );
1017 // blockSubShapes.Substitute( edgeBID[2], tgtWires[0]->Edge(3) );
1018 // blockSubShapes.Substitute( edgeBID[3], tgtWires[0]->Edge(1) );
1019 // block.LoadFace( srcFace, srcFaceBID, blockSubShapes );
1020 // block.LoadFace( tgtFace, tgtFaceBID, blockSubShapes );
1022 // // remember connectivity of new faces in terms of ( node-or-XY )
1024 // typedef std::pair< const SMDS_MeshNode*, gp_XYZ > TNodeOrXY; // node-or-XY
1025 // typedef std::vector< TNodeOrXY* > TFaceConn; // face connectivity
1026 // std::vector< TFaceConn > newFacesVec; // connectivity of all faces
1027 // std::map< const SMDS_MeshNode*, TNodeOrXY > srcNode2tgtNXY; // src node -> node-or-XY
1029 // TAssocTool::TNodeNodeMap::iterator srcN_tgtN;
1030 // std::map< const SMDS_MeshNode*, TNodeOrXY >::iterator srcN_tgtNXY;
1031 // std::pair< std::map< const SMDS_MeshNode*, TNodeOrXY >::iterator, bool > n2n_isNew;
1032 // TNodeOrXY nullNXY( (SMDS_MeshNode*)NULL, gp_XYZ(0,0,0) );
1034 // SMESHDS_SubMesh* srcSubDS = srcMeshDS->MeshElements( srcFace );
1035 // newFacesVec.resize( srcSubDS->NbElements() );
1036 // int iFaceSrc = 0;
1038 // SMDS_ElemIteratorPtr elemIt = srcSubDS->GetElements();
1039 // while ( elemIt->more() ) // loop on all mesh faces on srcFace
1041 // const SMDS_MeshElement* elem = elemIt->next();
1042 // TFaceConn& tgtNodes = newFacesVec[ iFaceSrc++ ];
1044 // const int nbN = elem->NbCornerNodes();
1045 // tgtNodes.resize( nbN );
1046 // for ( int i = 0; i < nbN; ++i ) // loop on nodes of the source element
1048 // const SMDS_MeshNode* srcNode = elem->GetNode(i);
1049 // n2n_isNew = srcNode2tgtNXY.insert( make_pair( srcNode, nullNXY ));
1050 // TNodeOrXY & tgtNodeOrXY = n2n_isNew.first->second;
1051 // if ( n2n_isNew.second ) // new src node encounters
1053 // srcN_tgtN = src2tgtNodes.find( srcNode );
1054 // if ( srcN_tgtN != src2tgtNodes.end() )
1056 // tgtNodeOrXY.first = srcN_tgtN->second; // tgt node exists
1060 // // find XY of src node withing the quadrilateral srcFace
1061 // if ( !block.ComputeParameters( SMESH_TNodeXYZ( srcNode ),
1062 // tgtNodeOrXY.second, srcFaceBID ))
1066 // tgtNodes[ i ] = & tgtNodeOrXY;
1070 // // as all XY are computed, create tgt nodes and faces
1072 // SMESH_MesherHelper helper( *tgtMesh );
1073 // helper.SetSubShape( tgtFace );
1074 // if ( is1DComputed )
1075 // helper.IsQuadraticSubMesh( tgtFace );
1077 // helper.SetIsQuadratic( srcSubDS->GetElements()->next()->IsQuadratic() );
1078 // helper.SetElementsOnShape( true );
1079 // Handle(Geom_Surface) tgtSurface = BRep_Tool::Surface( tgtFace );
1081 // SMESH_MesherHelper srcHelper( *srcMesh );
1082 // srcHelper.SetSubShape( srcFace );
1084 // vector< const SMDS_MeshNode* > tgtNodes;
1087 // for ( size_t iFaceTgt = 0; iFaceTgt < newFacesVec.size(); ++iFaceTgt )
1089 // TFaceConn& tgtConn = newFacesVec[ iFaceTgt ];
1090 // tgtNodes.resize( tgtConn.size() );
1091 // for ( size_t iN = 0; iN < tgtConn.size(); ++iN )
1093 // const SMDS_MeshNode* & tgtN = tgtConn[ iN ]->first;
1094 // if ( !tgtN ) // create a node
1096 // if ( !block.FaceUV( tgtFaceBID, tgtConn[iN]->second, uv ))
1098 // gp_Pnt p = tgtSurface->Value( uv.X(), uv.Y() );
1099 // tgtN = helper.AddNode( p.X(), p.Y(), p.Z(), uv.X(), uv.Y() );
1101 // tgtNodes[ tgtNodes.size() - iN - 1] = tgtN; // reversed orientation
1103 // switch ( tgtNodes.size() )
1105 // case 3: helper.AddFace(tgtNodes[0], tgtNodes[1], tgtNodes[2]); break;
1106 // case 4: helper.AddFace(tgtNodes[0], tgtNodes[1], tgtNodes[2], tgtNodes[3]); break;
1108 // if ( tgtNodes.size() > 4 )
1109 // helper.AddPolygonalFace( tgtNodes );
1112 return false; //true;
1114 } // bool projectQuads(...)
1116 //================================================================================
1118 * \brief Fix bad faces by smoothing
1120 //================================================================================
1122 bool fixDistortedFaces( SMESH_MesherHelper& helper,
1123 TSideVector& tgtWires )
1125 SMESH_subMesh* faceSM = helper.GetMesh()->GetSubMesh( helper.GetSubShape() );
1127 if ( helper.IsDistorted2D( faceSM, /*checkUV=*/true ))
1129 SMESH_MeshEditor editor( helper.GetMesh() );
1130 SMESHDS_SubMesh* smDS = faceSM->GetSubMeshDS();
1131 const TopoDS_Face& F = TopoDS::Face( faceSM->GetSubShape() );
1133 TIDSortedElemSet faces;
1134 SMDS_ElemIteratorPtr faceIt = smDS->GetElements();
1135 for ( faceIt = smDS->GetElements(); faceIt->more(); )
1136 faces.insert( faces.end(), faceIt->next() );
1138 // choose smoothing algo
1139 //SMESH_MeshEditor:: SmoothMethod algo = SMESH_MeshEditor::CENTROIDAL;
1140 bool isConcaveBoundary = false;
1141 for ( size_t iW = 0; iW < tgtWires.size() && !isConcaveBoundary; ++iW )
1143 TopoDS_Edge prevEdge = tgtWires[iW]->Edge( tgtWires[iW]->NbEdges() - 1 );
1144 for ( int iE = 0; iE < tgtWires[iW]->NbEdges() && !isConcaveBoundary; ++iE )
1146 double angle = helper.GetAngle( prevEdge, tgtWires[iW]->Edge( iE ),
1147 F, tgtWires[iW]->FirstVertex( iE ));
1148 isConcaveBoundary = ( angle < -5. * M_PI / 180. );
1150 prevEdge = tgtWires[iW]->Edge( iE );
1153 SMESH_MeshEditor:: SmoothMethod algo =
1154 isConcaveBoundary ? SMESH_MeshEditor::CENTROIDAL : SMESH_MeshEditor::LAPLACIAN;
1156 // smooth in 2D or 3D?
1157 TopLoc_Location loc;
1158 Handle(Geom_Surface) surface = BRep_Tool::Surface( F, loc );
1159 bool isPlanar = GeomLib_IsPlanarSurface( surface ).IsPlanar();
1162 set<const SMDS_MeshNode*> fixedNodes;
1163 editor.Smooth( faces, fixedNodes, algo, /*nbIterations=*/ 10,
1164 /*theTgtAspectRatio=*/1.0, /*the2D=*/!isPlanar);
1166 helper.ToFixNodeParameters( true );
1168 return !helper.IsDistorted2D( faceSM, /*checkUV=*/true );
1173 typedef list< pair< const SMDS_MeshNode*, const BRepMesh_Triangle* > > TNodeTriaList;
1175 //================================================================================
1177 * \brief Add in-FACE nodes surrounding a given node to a queue
1179 //================================================================================
1181 void addCloseNodes( const SMDS_MeshNode* srcNode,
1182 const BRepMesh_Triangle* bmTria,
1183 const int srcFaceID,
1184 TNodeTriaList & noTriQueue )
1186 // find in-FACE nodes
1187 SMDS_ElemIteratorPtr elems = srcNode->GetInverseElementIterator(SMDSAbs_Face);
1188 while ( elems->more() )
1190 const SMDS_MeshElement* elem = elems->next();
1191 if ( elem->getshapeId() == srcFaceID )
1193 for ( int i = 0, nb = elem->NbNodes(); i < nb; ++i )
1195 const SMDS_MeshNode* n = elem->GetNode( i );
1196 if ( !n->isMarked() )
1197 noTriQueue.push_back( make_pair( n, bmTria ));
1203 //================================================================================
1205 * \brief Find a delauney triangle containing a given 2D point and return
1206 * barycentric coordinates within the found triangle
1208 //================================================================================
1210 const BRepMesh_Triangle* findTriangle( const gp_XY& uv,
1211 const BRepMesh_Triangle* bmTria,
1212 Handle(BRepMesh_DataStructureOfDelaun)& triaDS,
1218 Standard_Boolean ori[3];
1224 triaDS->ElementNodes( *bmTria, nodeIDs );
1225 nodeUVs[0] = triaDS->GetNode( nodeIDs[0] ).Coord();
1226 nodeUVs[1] = triaDS->GetNode( nodeIDs[1] ).Coord();
1227 nodeUVs[2] = triaDS->GetNode( nodeIDs[2] ).Coord();
1229 SMESH_MeshAlgos::GetBarycentricCoords( uv,
1230 nodeUVs[0], nodeUVs[1], nodeUVs[2],
1232 if ( bc[0] >= 0 && bc[1] >= 0 && bc[0] + bc[1] <= 1 )
1234 bc[2] = 1 - bc[0] - bc[1];
1238 // look for a neighbor triangle, which is adjacent to a link intersected
1239 // by a segment( triangle center -> uv )
1241 gp_XY gc = ( nodeUVs[0] + nodeUVs[1] + nodeUVs[2] ) / 3.;
1242 gp_XY seg = uv - gc;
1244 bmTria->Edges( linkIDs, ori );
1245 int triaID = triaDS->IndexOf( *bmTria );
1248 for ( int i = 0; i < 3; ++i )
1250 const BRepMesh_PairOfIndex & triIDs = triaDS->ElementsConnectedTo( linkIDs[i] );
1251 if ( triIDs.Extent() < 2 )
1252 continue; // no neighbor triangle
1254 // check if a link intersects gc2uv
1255 const BRepMesh_Edge & link = triaDS->GetLink( linkIDs[i] );
1256 const BRepMesh_Vertex & n1 = triaDS->GetNode( link.FirstNode() );
1257 const BRepMesh_Vertex & n2 = triaDS->GetNode( link.LastNode() );
1258 gp_XY uv1 = n1.Coord();
1259 gp_XY lin = n2.Coord() - uv1; // link direction
1261 double crossSegLin = seg ^ lin;
1262 if ( Abs( crossSegLin ) < std::numeric_limits<double>::min() )
1263 continue; // parallel
1265 double uSeg = ( uv1 - gc ) ^ lin / crossSegLin;
1266 if ( 0. <= uSeg && uSeg <= 1. )
1268 bmTria = & triaDS->GetElement( triIDs.Index( 1 + ( triIDs.Index(1) == triaID )));
1276 //================================================================================
1278 * \brief Morph mesh on the target face to lie within FACE boundary w/o distortion
1281 * - make a CDT on the src FACE
1282 * - find a triangle containing a src node and get its barycentric coordinates
1283 * - move the node to a point with the same barycentric coordinates in a corresponding
1286 //================================================================================
1288 bool morph( SMESH_MesherHelper& tgtHelper,
1289 const TopoDS_Face& tgtFace,
1290 const TopoDS_Face& srcFace,
1291 const TSideVector& tgtWires,
1292 const TSideVector& srcWires,
1293 const TAssocTool::TNodeNodeMap& src2tgtNodes )
1295 if ( srcWires.size() != tgtWires.size() ) return false;
1296 if ( srcWires.size() == 1 ) return false; // tmp
1298 // count boundary points
1299 int iP = 1, nbP = 0;
1300 for ( size_t iW = 0; iW < srcWires.size(); ++iW )
1301 nbP += srcWires[iW]->NbPoints() - 1; // 1st and last points coincide
1303 // fill boundary points
1304 BRepMesh::Array1OfVertexOfDelaun srcVert( 1, 1 + nbP ), tgtVert( 1, 1 + nbP );
1305 vector< const SMDS_MeshNode* > bndSrcNodes( nbP + 1 ); bndSrcNodes[0] = 0;
1306 BRepMesh_Vertex v( 0, 0, BRepMesh_Frontier );
1307 for ( size_t iW = 0; iW < srcWires.size(); ++iW )
1309 const UVPtStructVec& srcPnt = srcWires[iW]->GetUVPtStruct();
1310 const UVPtStructVec& tgtPnt = tgtWires[iW]->GetUVPtStruct();
1311 if ( srcPnt.size() != tgtPnt.size() ) return false;
1313 for ( int i = 0, nb = srcPnt.size() - 1; i < nb; ++i, ++iP )
1315 bndSrcNodes[ iP ] = srcPnt[i].node;
1316 srcPnt[i].node->setIsMarked( true );
1318 v.ChangeCoord() = srcPnt[i].UV();
1320 v.ChangeCoord() = tgtPnt[i].UV();
1324 // triangulate the srcFace in 2D
1325 BRepMesh_Delaun delauney( srcVert );
1326 Handle(BRepMesh_DataStructureOfDelaun) triaDS = delauney.Result();
1328 Handle(ShapeAnalysis_Surface) tgtSurface = tgtHelper.GetSurface( tgtFace );
1329 SMESHDS_Mesh* srcMesh = srcWires[0]->GetMesh()->GetMeshDS();
1330 SMESHDS_Mesh* tgtMesh = tgtHelper.GetMeshDS();
1331 const SMDS_MeshNode *srcNode, *tgtNode;
1332 const BRepMesh_Triangle *bmTria;
1334 // un-mark internal src nodes; later we will mark moved nodes
1335 SMDS_NodeIteratorPtr nIt = srcMesh->MeshElements( srcFace )->GetNodes();
1336 if ( !nIt || !nIt->more() ) return true;
1337 while ( nIt->more() )
1338 ( srcNode = nIt->next() )->setIsMarked( false );
1340 // initialize a queue of nodes with starting triangles
1341 const int srcFaceID = srcNode->getshapeId();
1342 TNodeTriaList noTriQueue;
1343 size_t iBndSrcN = 1;
1344 for ( ; iBndSrcN < bndSrcNodes.size() && noTriQueue.empty(); ++iBndSrcN )
1347 const BRepMesh::ListOfInteger & linkIds = triaDS->LinksConnectedTo( iBndSrcN );
1348 const BRepMesh_PairOfIndex & triaIds = triaDS->ElementsConnectedTo( linkIds.First() );
1349 const BRepMesh_Triangle& tria = triaDS->GetElement( triaIds.Index(1) );
1351 addCloseNodes( bndSrcNodes[ iBndSrcN ], &tria, srcFaceID, noTriQueue );
1356 double bc[3]; // barycentric coordinates
1358 bool checkUV = true;
1359 const SMDS_FacePosition* pos;
1361 while ( !noTriQueue.empty() )
1363 srcNode = noTriQueue.front().first;
1364 bmTria = noTriQueue.front().second;
1365 noTriQueue.pop_front();
1366 if ( srcNode->isMarked() )
1368 srcNode->setIsMarked( true );
1370 // find a delauney triangle containing the src node
1371 gp_XY uv = tgtHelper.GetNodeUV( srcFace, srcNode, NULL, &checkUV );
1372 bmTria = findTriangle( uv, bmTria, triaDS, bc );
1376 // compute new coordinates for a corresponding tgt node
1377 gp_XY uvNew( 0., 0. ), nodeUV;
1378 triaDS->ElementNodes( *bmTria, nodeIDs );
1379 for ( int i = 0; i < 3; ++i )
1380 uvNew += bc[i] * tgtVert( nodeIDs[i]).Coord();
1381 gp_Pnt xyz = tgtSurface->Value( uvNew );
1383 // find and move tgt node
1384 TAssocTool::TNodeNodeMap::const_iterator n2n = src2tgtNodes.find( srcNode );
1385 if ( n2n == src2tgtNodes.end() ) continue;
1386 tgtNode = n2n->second;
1387 tgtMesh->MoveNode( tgtNode, xyz.X(), xyz.Y(), xyz.Z() );
1389 if (( pos = dynamic_cast< const SMDS_FacePosition* >( tgtNode->GetPosition() )))
1390 const_cast<SMDS_FacePosition*>( pos )->SetParameters( uvNew.X(), uvNew.Y() );
1392 addCloseNodes( srcNode, bmTria, srcFaceID, noTriQueue );
1394 // assure that all src nodes are visited
1395 for ( ; iBndSrcN < bndSrcNodes.size() && noTriQueue.empty(); ++iBndSrcN )
1397 const BRepMesh::ListOfInteger & linkIds = triaDS->LinksConnectedTo( iBndSrcN );
1398 const BRepMesh_PairOfIndex & triaIds = triaDS->ElementsConnectedTo( linkIds.First() );
1399 const BRepMesh_Triangle& tria = triaDS->GetElement( triaIds.Index(1) );
1400 addCloseNodes( bndSrcNodes[ iBndSrcN ], &tria, srcFaceID, noTriQueue );
1407 //=======================================================================
1409 * Set initial association of VERTEXes for the case of projection
1410 * from a quadrangle FACE to a closed FACE, where opposite src EDGEs
1411 * have different nb of segments
1413 //=======================================================================
1415 void initAssoc4Quad2Closed(const TopoDS_Shape& tgtFace,
1416 SMESH_MesherHelper& tgtHelper,
1417 const TopoDS_Shape& srcFace,
1418 SMESH_Mesh* srcMesh,
1419 TAssocTool::TShapeShapeMap & assocMap)
1421 if ( !tgtHelper.HasRealSeam() || srcFace.ShapeType() != TopAbs_FACE )
1422 return; // no seam edge
1423 list< TopoDS_Edge > tgtEdges, srcEdges;
1424 list< int > tgtNbEW, srcNbEW;
1425 int tgtNbW = SMESH_Block::GetOrderedEdges( TopoDS::Face( tgtFace ), tgtEdges, tgtNbEW );
1426 int srcNbW = SMESH_Block::GetOrderedEdges( TopoDS::Face( srcFace ), srcEdges, srcNbEW );
1427 if ( tgtNbW != 1 || srcNbW != 1 ||
1428 tgtNbEW.front() != 4 || srcNbEW.front() != 4 )
1429 return; // not quads
1432 list< TopoDS_Edge >::iterator edgeS = srcEdges.begin(), edgeT = tgtEdges.begin();
1433 for ( int i = 0; edgeS != srcEdges.end(); ++i, ++edgeS )
1434 if ( SMESHDS_SubMesh* sm = srcMesh->GetMeshDS()->MeshElements( *edgeS ))
1435 srcNbSeg[ i ] = sm->NbNodes();
1437 return; // not meshed
1438 if ( srcNbSeg[0] == srcNbSeg[2] && srcNbSeg[1] == srcNbSeg[3] )
1439 return; // same nb segments
1440 if ( srcNbSeg[0] != srcNbSeg[2] && srcNbSeg[1] != srcNbSeg[3] )
1441 return; // all different nb segments
1443 edgeS = srcEdges.begin();
1444 if ( srcNbSeg[0] != srcNbSeg[2] )
1446 TAssocTool::InsertAssociation( tgtHelper.IthVertex( 0,*edgeT ),
1447 tgtHelper.IthVertex( 0,*edgeS ), assocMap );
1448 TAssocTool::InsertAssociation( tgtHelper.IthVertex( 1,*edgeT ),
1449 tgtHelper.IthVertex( 1,*edgeS ), assocMap );
1455 //=======================================================================
1456 //function : Compute
1458 //=======================================================================
1460 bool StdMeshers_Projection_2D::Compute(SMESH_Mesh& theMesh, const TopoDS_Shape& theShape)
1462 _src2tgtNodes.clear();
1467 SMESH_Mesh * srcMesh = _sourceHypo->GetSourceMesh();
1468 SMESH_Mesh * tgtMesh = & theMesh;
1472 SMESHDS_Mesh * meshDS = theMesh.GetMeshDS();
1473 SMESH_MesherHelper helper( theMesh );
1475 // ---------------------------
1476 // Make sub-shapes association
1477 // ---------------------------
1479 TopoDS_Face tgtFace = TopoDS::Face( theShape.Oriented(TopAbs_FORWARD));
1480 TopoDS_Shape srcShape = _sourceHypo->GetSourceFace().Oriented(TopAbs_FORWARD);
1482 helper.SetSubShape( tgtFace );
1484 TAssocTool::TShapeShapeMap shape2ShapeMap;
1485 TAssocTool::InitVertexAssociation( _sourceHypo, shape2ShapeMap );
1486 if ( shape2ShapeMap.IsEmpty() )
1487 initAssoc4Quad2Closed( tgtFace, helper, srcShape, srcMesh, shape2ShapeMap );
1488 if ( !TAssocTool::FindSubShapeAssociation( tgtFace, tgtMesh, srcShape, srcMesh,
1490 !shape2ShapeMap.IsBound( tgtFace ))
1492 if ( srcShape.ShapeType() == TopAbs_FACE )
1494 int nbE1 = helper.Count( tgtFace, TopAbs_EDGE, /*ignoreSame=*/true );
1495 int nbE2 = helper.Count( srcShape, TopAbs_EDGE, /*ignoreSame=*/true );
1497 return error(COMPERR_BAD_SHAPE,
1498 SMESH_Comment("Different number of edges in source and target faces: ")
1499 << nbE2 << " and " << nbE1 );
1501 return error(COMPERR_BAD_SHAPE,"Topology of source and target faces seems different" );
1503 TopoDS_Face srcFace = TopoDS::Face( shape2ShapeMap( tgtFace ).Oriented(TopAbs_FORWARD));
1505 // ----------------------------------------------
1506 // Assure that mesh on a source Face is computed
1507 // ----------------------------------------------
1509 SMESH_subMesh* srcSubMesh = srcMesh->GetSubMesh( srcFace );
1510 SMESH_subMesh* tgtSubMesh = tgtMesh->GetSubMesh( tgtFace );
1512 string srcMeshError;
1513 if ( tgtMesh == srcMesh ) {
1514 if ( !TAssocTool::MakeComputed( srcSubMesh ))
1515 srcMeshError = TAssocTool::SourceNotComputedError( srcSubMesh, this );
1518 if ( !srcSubMesh->IsMeshComputed() )
1519 srcMeshError = TAssocTool::SourceNotComputedError();
1521 if ( !srcMeshError.empty() )
1522 return error(COMPERR_BAD_INPUT_MESH, srcMeshError );
1528 // get ordered src and tgt EDGEs
1529 TSideVector srcWires, tgtWires;
1530 bool is1DComputed = false; // if any tgt EDGE is meshed
1531 TError err = getWires( tgtFace, srcFace, tgtMesh, srcMesh,
1532 shape2ShapeMap, srcWires, tgtWires, _src2tgtNodes, is1DComputed );
1533 if ( err && !err->IsOK() )
1534 return error( err );
1536 bool projDone = false;
1540 // try to project from the same face with different location
1541 projDone = projectPartner( tgtFace, srcFace, tgtWires, srcWires,
1542 shape2ShapeMap, _src2tgtNodes, is1DComputed );
1546 // projection in case if the faces are similar in 2D space
1547 projDone = projectBy2DSimilarity( tgtFace, srcFace, tgtWires, srcWires,
1548 shape2ShapeMap, _src2tgtNodes, is1DComputed );
1552 // projection in case of quadrilateral faces
1553 // NOT IMPLEMENTED, returns false
1554 projDone = projectQuads( tgtFace, srcFace, tgtWires, srcWires,
1555 shape2ShapeMap, _src2tgtNodes, is1DComputed);
1558 // it will remove mesh built on edges and vertices in failure case
1559 MeshCleaner cleaner( tgtSubMesh );
1563 _src2tgtNodes.clear();
1564 // --------------------
1565 // Prepare to mapping
1566 // --------------------
1568 // Check if node projection to a face is needed
1570 SMDS_ElemIteratorPtr faceIt = srcSubMesh->GetSubMeshDS()->GetElements();
1571 set< const SMDS_MeshNode* > faceNodes;
1572 for ( ; faceNodes.size() < 3 && faceIt->more(); ) {
1573 const SMDS_MeshElement* face = faceIt->next();
1574 SMDS_ElemIteratorPtr nodeIt = face->nodesIterator();
1575 while ( nodeIt->more() ) {
1576 const SMDS_MeshNode* node = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
1577 if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE &&
1578 faceNodes.insert( node ).second )
1579 uvBox.Add( helper.GetNodeUV( srcFace, node ));
1582 bool toProjectNodes = false;
1583 if ( faceNodes.size() == 1 )
1584 toProjectNodes = ( uvBox.IsVoid() || uvBox.CornerMin().IsEqual( gp_XY(0,0), 1e-12 ));
1585 else if ( faceNodes.size() > 1 )
1586 toProjectNodes = ( uvBox.IsVoid() || uvBox.SquareExtent() < DBL_MIN );
1588 // Find the corresponding source and target vertex
1589 // and <theReverse> flag needed to call mapper.Apply()
1591 TopoDS_Vertex srcV1, tgtV1;
1592 bool reverse = false;
1594 TopExp_Explorer vSrcExp( srcFace, TopAbs_VERTEX );
1595 srcV1 = TopoDS::Vertex( vSrcExp.Current() );
1596 tgtV1 = TopoDS::Vertex( shape2ShapeMap( srcV1, /*isSrc=*/true ));
1598 list< TopoDS_Edge > tgtEdges, srcEdges;
1599 list< int > nbEdgesInWires;
1600 SMESH_Block::GetOrderedEdges( tgtFace, tgtEdges, nbEdgesInWires, tgtV1 );
1601 SMESH_Block::GetOrderedEdges( srcFace, srcEdges, nbEdgesInWires, srcV1 );
1603 if ( nbEdgesInWires.front() > 1 ) // possible to find out orientation
1605 TopoDS_Edge srcE1 = srcEdges.front(), tgtE1 = tgtEdges.front();
1606 TopoDS_Shape srcE1bis = shape2ShapeMap( tgtE1 );
1607 reverse = ( ! srcE1.IsSame( srcE1bis ));
1609 //_sourceHypo->HasVertexAssociation() &&
1610 nbEdgesInWires.front() > 2 &&
1611 helper.IsRealSeam( tgtEdges.front() ))
1613 // projection to a face with seam EDGE; pb is that GetOrderedEdges()
1614 // always puts a seam EDGE first (if possible) and as a result
1615 // we can't use only theReverse flag to correctly associate source
1616 // and target faces in the mapper. Thus we select srcV1 so that
1617 // GetOrderedEdges() to return EDGEs in a needed order
1618 TopoDS_Face tgtFaceBis = tgtFace;
1619 TopTools_MapOfShape checkedVMap( tgtEdges.size() );
1620 checkedVMap.Add ( srcV1 );
1621 for ( vSrcExp.Next(); vSrcExp.More(); )
1623 tgtFaceBis.Reverse();
1625 SMESH_Block::GetOrderedEdges( tgtFaceBis, tgtEdges, nbEdgesInWires, tgtV1 );
1627 list< TopoDS_Edge >::iterator edgeS = srcEdges.begin(), edgeT = tgtEdges.begin();
1628 for ( ; edgeS != srcEdges.end() && ok ; ++edgeS, ++edgeT )
1629 ok = edgeT->IsSame( shape2ShapeMap( *edgeS, /*isSrc=*/true ));
1637 while ( vSrcExp.More() && !checkedVMap.Add( vSrcExp.Current() ))
1642 srcV1 = TopoDS::Vertex( vSrcExp.Current() );
1643 tgtV1 = TopoDS::Vertex( shape2ShapeMap( srcV1, /*isSrc=*/true ));
1645 SMESH_Block::GetOrderedEdges( srcFace, srcEdges, nbEdgesInWires, srcV1 );
1649 // for the case: project to a closed face from a non-closed face w/o vertex assoc;
1650 // avoid projecting to a seam from two EDGEs with different nb nodes on them
1651 // ( test mesh_Projection_2D_01/B1 )
1652 if ( !_sourceHypo->HasVertexAssociation() &&
1653 nbEdgesInWires.front() > 2 &&
1654 helper.IsRealSeam( tgtEdges.front() ))
1656 TopoDS_Shape srcEdge1 = shape2ShapeMap( tgtEdges.front() );
1657 list< TopoDS_Edge >::iterator srcEdge2 =
1658 std::find( srcEdges.begin(), srcEdges.end(), srcEdge1);
1659 list< TopoDS_Edge >::iterator srcEdge3 =
1660 std::find( srcEdges.begin(), srcEdges.end(), srcEdge1.Reversed());
1661 if ( srcEdge2 == srcEdges.end() || srcEdge3 == srcEdges.end() ) // srcEdge1 is not a seam
1663 // find srcEdge2 which also will be projected to tgtEdges.front()
1664 for ( srcEdge2 = srcEdges.begin(); srcEdge2 != srcEdges.end(); ++srcEdge2 )
1665 if ( !srcEdge1.IsSame( *srcEdge2 ) &&
1666 tgtEdges.front().IsSame( shape2ShapeMap( *srcEdge2, /*isSrc=*/true )))
1668 // compare nb nodes on srcEdge1 and srcEdge2
1669 if ( srcEdge2 != srcEdges.end() )
1671 int nbN1 = 0, nbN2 = 0;
1672 if ( SMESHDS_SubMesh* sm = srcMesh->GetMeshDS()->MeshElements( srcEdge1 ))
1673 nbN1 = sm->NbNodes();
1674 if ( SMESHDS_SubMesh* sm = srcMesh->GetMeshDS()->MeshElements( *srcEdge2 ))
1675 nbN2 = sm->NbNodes();
1677 srcV1 = helper.IthVertex( 1, srcEdges.front() );
1682 else if ( nbEdgesInWires.front() == 1 ) // a sole edge in a wire
1684 TopoDS_Edge srcE1 = srcEdges.front(), tgtE1 = tgtEdges.front();
1685 for ( size_t iW = 0; iW < srcWires.size(); ++iW )
1687 StdMeshers_FaceSidePtr srcWire = srcWires[iW];
1688 for ( int iE = 0; iE < srcWire->NbEdges(); ++iE )
1689 if ( srcE1.IsSame( srcWire->Edge( iE )))
1691 reverse = ( tgtE1.Orientation() != tgtWires[iW]->Edge( iE ).Orientation() );
1698 RETURN_BAD_RESULT("Bad result from SMESH_Block::GetOrderedEdges()");
1701 // Load pattern from the source face
1702 SMESH_Pattern mapper;
1703 mapper.Load( srcMesh, srcFace, toProjectNodes, srcV1, /*keepNodes=*/true );
1704 if ( mapper.GetErrorCode() != SMESH_Pattern::ERR_OK )
1705 return error(COMPERR_BAD_INPUT_MESH,"Can't load mesh pattern from the source face");
1707 // --------------------
1708 // Perform 2D mapping
1709 // --------------------
1711 // Compute mesh on a target face
1713 mapper.Apply( tgtFace, tgtV1, reverse );
1714 if ( mapper.GetErrorCode() != SMESH_Pattern::ERR_OK ) {
1715 // std::ofstream file("/tmp/Pattern.smp" );
1716 // mapper.Save( file );
1717 return error("Can't apply source mesh pattern to the face");
1722 const bool toCreatePolygons = false, toCreatePolyedrs = false;
1723 mapper.MakeMesh( tgtMesh, toCreatePolygons, toCreatePolyedrs );
1724 if ( mapper.GetErrorCode() != SMESH_Pattern::ERR_OK )
1725 return error("Can't make mesh by source mesh pattern");
1727 // fill _src2tgtNodes
1728 std::vector< const SMDS_MeshNode* > *srcNodes, *tgtNodes;
1729 mapper.GetInOutNodes( srcNodes, tgtNodes );
1730 size_t nbN = std::min( srcNodes->size(), tgtNodes->size() );
1731 for ( size_t i = 0; i < nbN; ++i )
1732 if ( (*srcNodes)[i] && (*tgtNodes)[i] )
1733 _src2tgtNodes.insert( make_pair( (*srcNodes)[i], (*tgtNodes)[i] ));
1736 } // end of projection using Pattern mapping
1739 // -------------------------------------------------------------------------
1740 // mapper doesn't take care of nodes already existing on edges and vertices,
1741 // so we must merge nodes created by it with existing ones
1742 // -------------------------------------------------------------------------
1744 SMESH_MeshEditor::TListOfListOfNodes groupsOfNodes;
1746 // Make groups of nodes to merge
1748 // loop on EDGE and VERTEX sub-meshes of a target FACE
1749 SMESH_subMeshIteratorPtr smIt = tgtSubMesh->getDependsOnIterator(/*includeSelf=*/false,
1750 /*complexShapeFirst=*/false);
1751 while ( smIt->more() )
1753 SMESH_subMesh* sm = smIt->next();
1754 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
1755 if ( !smDS || smDS->NbNodes() == 0 )
1757 //if ( !is1DComputed && sm->GetSubShape().ShapeType() == TopAbs_EDGE )
1760 if ( helper.IsDegenShape( sm->GetId() ) ) // to merge all nodes on degenerated
1762 if ( sm->GetSubShape().ShapeType() == TopAbs_EDGE )
1764 groupsOfNodes.push_back( list< const SMDS_MeshNode* >() );
1765 SMESH_subMeshIteratorPtr smDegenIt
1766 = sm->getDependsOnIterator(/*includeSelf=*/true,/*complexShapeFirst=*/false);
1767 while ( smDegenIt->more() )
1768 if (( smDS = smDegenIt->next()->GetSubMeshDS() ))
1770 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
1771 while ( nIt->more() )
1772 groupsOfNodes.back().push_back( nIt->next() );
1775 continue; // do not treat sm of degen VERTEX
1778 // Sort new and old nodes of a sub-mesh separately
1780 bool isSeam = helper.IsRealSeam( sm->GetId() );
1782 enum { NEW_NODES = 0, OLD_NODES };
1783 map< double, const SMDS_MeshNode* > u2nodesMaps[2], u2nodesOnSeam;
1784 map< double, const SMDS_MeshNode* >::iterator u_oldNode, u_newNode, u_newOnSeam, newEnd;
1785 set< const SMDS_MeshNode* > seamNodes;
1787 // mapper changed, no more "mapper puts on a seam edge nodes from 2 edges"
1788 if ( isSeam && ! getBoundaryNodes ( sm, tgtFace, u2nodesOnSeam, seamNodes ))
1789 ;//RETURN_BAD_RESULT("getBoundaryNodes() failed");
1791 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
1792 while ( nIt->more() )
1794 const SMDS_MeshNode* node = nIt->next();
1795 bool isOld = isOldNode( node );
1797 if ( !isOld && isSeam ) { // new node on a seam edge
1798 if ( seamNodes.count( node ) )
1799 continue; // node is already in the map
1802 // sort nodes on edges by their position
1803 map< double, const SMDS_MeshNode* > & pos2nodes = u2nodesMaps[isOld ? OLD_NODES : NEW_NODES];
1804 switch ( node->GetPosition()->GetTypeOfPosition() )
1806 case SMDS_TOP_VERTEX: {
1807 if ( !is1DComputed && !pos2nodes.empty() )
1808 u2nodesMaps[isOld ? NEW_NODES : OLD_NODES].insert( make_pair( 0, node ));
1810 pos2nodes.insert( make_pair( 0, node ));
1813 case SMDS_TOP_EDGE: {
1814 const SMDS_EdgePosition* pos =
1815 static_cast<const SMDS_EdgePosition*>(node->GetPosition());
1816 pos2nodes.insert( make_pair( pos->GetUParameter(), node ));
1820 RETURN_BAD_RESULT("Wrong node position type: "<<
1821 node->GetPosition()->GetTypeOfPosition());
1824 const bool mergeNewToOld =
1825 ( u2nodesMaps[ NEW_NODES ].size() == u2nodesMaps[ OLD_NODES ].size() );
1826 const bool mergeSeamToNew =
1827 ( u2nodesMaps[ NEW_NODES ].size() == u2nodesOnSeam.size() );
1829 if ( !mergeNewToOld )
1830 if ( u2nodesMaps[ NEW_NODES ].size() > 0 &&
1831 u2nodesMaps[ OLD_NODES ].size() > 0 )
1833 u_oldNode = u2nodesMaps[ OLD_NODES ].begin();
1834 newEnd = u2nodesMaps[ OLD_NODES ].end();
1835 for ( ; u_oldNode != newEnd; ++u_oldNode )
1836 SMESH_Algo::addBadInputElement( u_oldNode->second );
1837 return error( COMPERR_BAD_INPUT_MESH,
1838 SMESH_Comment( "Existing mesh mismatches the projected 2D mesh on " )
1839 << ( sm->GetSubShape().ShapeType() == TopAbs_EDGE ? "edge" : "vertex" )
1840 << " #" << sm->GetId() );
1842 if ( isSeam && !mergeSeamToNew ) {
1843 const TopoDS_Shape& seam = sm->GetSubShape();
1844 if ( u2nodesMaps[ NEW_NODES ].size() > 0 &&
1845 u2nodesOnSeam.size() > 0 &&
1846 seam.ShapeType() == TopAbs_EDGE )
1848 int nbE1 = helper.Count( tgtFace, TopAbs_EDGE, /*ignoreSame=*/true );
1849 int nbE2 = helper.Count( srcFace, TopAbs_EDGE, /*ignoreSame=*/true );
1850 if ( nbE1 != nbE2 ) // 2 EDGEs are mapped to a seam EDGE
1852 // find the 2 EDGEs of srcFace
1853 TopTools_DataMapIteratorOfDataMapOfShapeShape src2tgtIt( shape2ShapeMap._map2to1 );
1854 for ( ; src2tgtIt.More(); src2tgtIt.Next() )
1855 if ( seam.IsSame( src2tgtIt.Value() ))
1856 SMESH_Algo::addBadInputElements
1857 ( srcMesh->GetMeshDS()->MeshElements( src2tgtIt.Key() ));
1858 return error( COMPERR_BAD_INPUT_MESH,
1859 "Different number of nodes on two edges projected to a seam edge" );
1864 // Make groups of nodes to merge
1866 u_oldNode = u2nodesMaps[ OLD_NODES ].begin();
1867 u_newNode = u2nodesMaps[ NEW_NODES ].begin();
1868 newEnd = u2nodesMaps[ NEW_NODES ].end();
1869 u_newOnSeam = u2nodesOnSeam.begin();
1870 if ( mergeNewToOld )
1871 for ( ; u_newNode != newEnd; ++u_newNode, ++u_oldNode )
1873 groupsOfNodes.push_back( list< const SMDS_MeshNode* >() );
1874 groupsOfNodes.back().push_back( u_oldNode->second );
1875 groupsOfNodes.back().push_back( u_newNode->second );
1876 if ( mergeSeamToNew )
1877 groupsOfNodes.back().push_back( (u_newOnSeam++)->second );
1879 else if ( mergeSeamToNew )
1880 for ( ; u_newNode != newEnd; ++u_newNode, ++u_newOnSeam )
1882 groupsOfNodes.push_back( list< const SMDS_MeshNode* >() );
1883 groupsOfNodes.back().push_back( u_newNode->second );
1884 groupsOfNodes.back().push_back( u_newOnSeam->second );
1887 } // loop on EDGE and VERTEX submeshes of a target FACE
1891 SMESH_MeshEditor editor( tgtMesh );
1892 int nbFaceBeforeMerge = tgtSubMesh->GetSubMeshDS()->NbElements();
1893 editor.MergeNodes( groupsOfNodes );
1894 int nbFaceAtferMerge = tgtSubMesh->GetSubMeshDS()->NbElements();
1895 if ( nbFaceBeforeMerge != nbFaceAtferMerge && !helper.HasDegeneratedEdges() )
1896 return error(COMPERR_BAD_INPUT_MESH, "Probably invalid node parameters on geom faces");
1898 // ----------------------------------------------------------------
1899 // The mapper can't create quadratic elements, so convert if needed
1900 // ----------------------------------------------------------------
1902 SMDS_ElemIteratorPtr faceIt;
1903 faceIt = srcSubMesh->GetSubMeshDS()->GetElements();
1904 bool srcIsQuad = faceIt->next()->IsQuadratic();
1905 faceIt = tgtSubMesh->GetSubMeshDS()->GetElements();
1906 bool tgtIsQuad = faceIt->next()->IsQuadratic();
1907 if ( srcIsQuad && !tgtIsQuad )
1909 TIDSortedElemSet tgtFaces;
1910 faceIt = tgtSubMesh->GetSubMeshDS()->GetElements();
1911 while ( faceIt->more() )
1912 tgtFaces.insert( tgtFaces.end(), faceIt->next() );
1914 editor.ConvertToQuadratic(/*theForce3d=*/false, tgtFaces, false);
1916 } // end of coincident nodes and quadratic elements treatment
1919 if ( !projDone || is1DComputed )
1920 // ----------------------------------------------------------------
1921 // The mapper can create distorted faces by placing nodes out of the FACE
1922 // boundary, also bad face can be created if EDGEs already discretized
1923 // --> fix bad faces by smoothing
1924 // ----------------------------------------------------------------
1925 if ( helper.IsDistorted2D( tgtSubMesh, /*checkUV=*/false ))
1927 morph( helper, tgtFace, srcFace, tgtWires, srcWires, _src2tgtNodes );
1929 if ( !fixDistortedFaces( helper, tgtWires ))
1930 return error("Invalid mesh generated");
1932 // ---------------------------
1933 // Check elements orientation
1934 // ---------------------------
1936 TopoDS_Face face = TopoDS::Face( theShape );
1937 if ( !theMesh.IsMainShape( tgtFace ))
1939 // find the main shape
1940 TopoDS_Shape mainShape = meshDS->ShapeToMesh();
1941 switch ( mainShape.ShapeType() ) {
1943 case TopAbs_SOLID: break;
1945 TopTools_ListIteratorOfListOfShape ancestIt = theMesh.GetAncestors( face );
1946 for ( ; ancestIt.More(); ancestIt.Next() ) {
1947 TopAbs_ShapeEnum type = ancestIt.Value().ShapeType();
1948 if ( type == TopAbs_SOLID ) {
1949 mainShape = ancestIt.Value();
1951 } else if ( type == TopAbs_SHELL ) {
1952 mainShape = ancestIt.Value();
1956 // find tgtFace in the main solid or shell to know it's true orientation.
1957 TopExp_Explorer exp( mainShape, TopAbs_FACE );
1958 for ( ; exp.More(); exp.Next() ) {
1959 if ( tgtFace.IsSame( exp.Current() )) {
1960 face = TopoDS::Face( exp.Current() );
1966 if ( helper.IsReversedSubMesh( face ))
1968 SMESH_MeshEditor editor( tgtMesh );
1969 SMDS_ElemIteratorPtr eIt = meshDS->MeshElements( face )->GetElements();
1970 while ( eIt->more() ) {
1971 const SMDS_MeshElement* e = eIt->next();
1972 if ( e->GetType() == SMDSAbs_Face && !editor.Reorient( e ))
1973 RETURN_BAD_RESULT("Pb of SMESH_MeshEditor::Reorient()");
1977 cleaner.Release(); // not to remove mesh
1983 //=======================================================================
1984 //function : Evaluate
1986 //=======================================================================
1988 bool StdMeshers_Projection_2D::Evaluate(SMESH_Mesh& theMesh,
1989 const TopoDS_Shape& theShape,
1990 MapShapeNbElems& aResMap)
1995 SMESH_Mesh * srcMesh = _sourceHypo->GetSourceMesh();
1996 SMESH_Mesh * tgtMesh = & theMesh;
2000 // ---------------------------
2001 // Make sub-shapes association
2002 // ---------------------------
2004 TopoDS_Face tgtFace = TopoDS::Face( theShape.Oriented(TopAbs_FORWARD));
2005 TopoDS_Shape srcShape = _sourceHypo->GetSourceFace().Oriented(TopAbs_FORWARD);
2007 TAssocTool::TShapeShapeMap shape2ShapeMap;
2008 TAssocTool::InitVertexAssociation( _sourceHypo, shape2ShapeMap );
2009 if ( !TAssocTool::FindSubShapeAssociation( tgtFace, tgtMesh, srcShape, srcMesh,
2011 !shape2ShapeMap.IsBound( tgtFace ))
2012 return error(COMPERR_BAD_SHAPE,"Topology of source and target faces seems different" );
2014 TopoDS_Face srcFace = TopoDS::Face( shape2ShapeMap( tgtFace ).Oriented(TopAbs_FORWARD));
2016 // -------------------------------------------------------
2017 // Assure that mesh on a source Face is computed/evaluated
2018 // -------------------------------------------------------
2020 std::vector<int> aVec;
2022 SMESH_subMesh* srcSubMesh = srcMesh->GetSubMesh( srcFace );
2023 if ( srcSubMesh->IsMeshComputed() )
2025 aVec.resize( SMDSEntity_Last, 0 );
2026 aVec[SMDSEntity_Node] = srcSubMesh->GetSubMeshDS()->NbNodes();
2028 SMDS_ElemIteratorPtr elemIt = srcSubMesh->GetSubMeshDS()->GetElements();
2029 while ( elemIt->more() )
2030 aVec[ elemIt->next()->GetEntityType() ]++;
2034 MapShapeNbElems tmpResMap;
2035 MapShapeNbElems& srcResMap = (srcMesh == tgtMesh) ? aResMap : tmpResMap;
2036 if ( !_gen->Evaluate( *srcMesh, srcShape, srcResMap ))
2037 return error(COMPERR_BAD_INPUT_MESH,"Source mesh not evaluatable");
2038 aVec = srcResMap[ srcSubMesh ];
2040 return error(COMPERR_BAD_INPUT_MESH,"Source mesh is wrongly evaluated");
2043 SMESH_subMesh * sm = theMesh.GetSubMesh(theShape);
2044 aResMap.insert(std::make_pair(sm,aVec));
2050 //=============================================================================
2052 * \brief Sets a default event listener to submesh of the source face
2053 * \param subMesh - submesh where algo is set
2055 * This method is called when a submesh gets HYP_OK algo_state.
2056 * After being set, event listener is notified on each event of a submesh.
2057 * Arranges that CLEAN event is translated from source submesh to
2060 //=============================================================================
2062 void StdMeshers_Projection_2D::SetEventListener(SMESH_subMesh* subMesh)
2064 TAssocTool::SetEventListener( subMesh,
2065 _sourceHypo->GetSourceFace(),
2066 _sourceHypo->GetSourceMesh() );