1 // Copyright (C) 2007-2012 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.
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 // File: SMESH_MesherHelper.cxx
24 // Created: 15.02.06 15:22:41
25 // Author: Sergey KUUL
27 #include "SMESH_MesherHelper.hxx"
29 #include "SMDS_FacePosition.hxx"
30 #include "SMDS_EdgePosition.hxx"
31 #include "SMDS_VolumeTool.hxx"
32 #include "SMESH_subMesh.hxx"
33 #include "SMESH_ProxyMesh.hxx"
35 #include <BRepAdaptor_Surface.hxx>
36 #include <BRepTools.hxx>
37 #include <BRepTools_WireExplorer.hxx>
38 #include <BRep_Tool.hxx>
39 #include <Geom2d_Curve.hxx>
40 #include <GeomAPI_ProjectPointOnCurve.hxx>
41 #include <GeomAPI_ProjectPointOnSurf.hxx>
42 #include <Geom_Curve.hxx>
43 #include <Geom_RectangularTrimmedSurface.hxx>
44 #include <Geom_Surface.hxx>
45 #include <ShapeAnalysis.hxx>
47 #include <TopExp_Explorer.hxx>
48 #include <TopTools_ListIteratorOfListOfShape.hxx>
49 #include <TopTools_MapIteratorOfMapOfShape.hxx>
50 #include <TopTools_MapOfShape.hxx>
53 #include <gp_Pnt2d.hxx>
54 #include <gp_Trsf.hxx>
56 #include <Standard_Failure.hxx>
57 #include <Standard_ErrorHandler.hxx>
59 #include <utilities.h>
65 #define RETURN_BAD_RESULT(msg) { MESSAGE(msg); return false; }
69 gp_XYZ XYZ(const SMDS_MeshNode* n) { return gp_XYZ(n->X(), n->Y(), n->Z()); }
71 enum { U_periodic = 1, V_periodic = 2 };
74 //================================================================================
78 //================================================================================
80 SMESH_MesherHelper::SMESH_MesherHelper(SMESH_Mesh& theMesh)
81 : myParIndex(0), myMesh(&theMesh), myShapeID(0), myCreateQuadratic(false)
83 myPar1[0] = myPar2[0] = myPar1[1] = myPar2[1] = 0;
84 mySetElemOnShape = ( ! myMesh->HasShapeToMesh() );
87 //=======================================================================
88 //function : ~SMESH_MesherHelper
90 //=======================================================================
92 SMESH_MesherHelper::~SMESH_MesherHelper()
95 TID2ProjectorOnSurf::iterator i_proj = myFace2Projector.begin();
96 for ( ; i_proj != myFace2Projector.end(); ++i_proj )
97 delete i_proj->second;
100 TID2ProjectorOnCurve::iterator i_proj = myEdge2Projector.begin();
101 for ( ; i_proj != myEdge2Projector.end(); ++i_proj )
102 delete i_proj->second;
106 //=======================================================================
107 //function : IsQuadraticSubMesh
108 //purpose : Check submesh for given shape: if all elements on this shape
109 // are quadratic, quadratic elements will be created.
110 // Also fill myTLinkNodeMap
111 //=======================================================================
113 bool SMESH_MesherHelper::IsQuadraticSubMesh(const TopoDS_Shape& aSh)
115 SMESHDS_Mesh* meshDS = GetMeshDS();
116 // we can create quadratic elements only if all elements
117 // created on sub-shapes of given shape are quadratic
118 // also we have to fill myTLinkNodeMap
119 myCreateQuadratic = true;
120 mySeamShapeIds.clear();
121 myDegenShapeIds.clear();
122 TopAbs_ShapeEnum subType( aSh.ShapeType()==TopAbs_FACE ? TopAbs_EDGE : TopAbs_FACE );
123 SMDSAbs_ElementType elemType( subType==TopAbs_FACE ? SMDSAbs_Face : SMDSAbs_Edge );
125 int nbOldLinks = myTLinkNodeMap.size();
127 if ( !myMesh->HasShapeToMesh() )
129 if (( myCreateQuadratic = myMesh->NbFaces( ORDER_QUADRATIC )))
131 SMDS_FaceIteratorPtr fIt = meshDS->facesIterator();
132 while ( fIt->more() )
133 AddTLinks( static_cast< const SMDS_MeshFace* >( fIt->next() ));
138 TopExp_Explorer exp( aSh, subType );
139 TopTools_MapOfShape checkedSubShapes;
140 for (; exp.More() && myCreateQuadratic; exp.Next()) {
141 if ( !checkedSubShapes.Add( exp.Current() ))
142 continue; // needed if aSh is compound of solids
143 if ( SMESHDS_SubMesh * subMesh = meshDS->MeshElements( exp.Current() )) {
144 if ( SMDS_ElemIteratorPtr it = subMesh->GetElements() ) {
146 const SMDS_MeshElement* e = it->next();
147 if ( e->GetType() != elemType || !e->IsQuadratic() ) {
148 myCreateQuadratic = false;
153 switch ( e->NbNodes() ) {
155 AddTLinkNode(e->GetNode(0),e->GetNode(1),e->GetNode(2)); break;
157 AddTLinkNode(e->GetNode(0),e->GetNode(1),e->GetNode(3));
158 AddTLinkNode(e->GetNode(1),e->GetNode(2),e->GetNode(4));
159 AddTLinkNode(e->GetNode(2),e->GetNode(0),e->GetNode(5)); break;
161 AddTLinkNode(e->GetNode(0),e->GetNode(1),e->GetNode(4));
162 AddTLinkNode(e->GetNode(1),e->GetNode(2),e->GetNode(5));
163 AddTLinkNode(e->GetNode(2),e->GetNode(3),e->GetNode(6));
164 AddTLinkNode(e->GetNode(3),e->GetNode(0),e->GetNode(7));
167 myCreateQuadratic = false;
177 if ( nbOldLinks == myTLinkNodeMap.size() )
178 myCreateQuadratic = false;
180 if(!myCreateQuadratic) {
181 myTLinkNodeMap.clear();
185 return myCreateQuadratic;
188 //=======================================================================
189 //function : SetSubShape
190 //purpose : Set geomerty to make elements on
191 //=======================================================================
193 void SMESH_MesherHelper::SetSubShape(const int aShID)
195 if ( aShID == myShapeID )
198 SetSubShape( GetMeshDS()->IndexToShape( aShID ));
200 SetSubShape( TopoDS_Shape() );
203 //=======================================================================
204 //function : SetSubShape
205 //purpose : Set geomerty to create elements on
206 //=======================================================================
208 void SMESH_MesherHelper::SetSubShape(const TopoDS_Shape& aSh)
210 if ( myShape.IsSame( aSh ))
214 mySeamShapeIds.clear();
215 myDegenShapeIds.clear();
217 if ( myShape.IsNull() ) {
221 SMESHDS_Mesh* meshDS = GetMeshDS();
222 myShapeID = meshDS->ShapeToIndex(aSh);
225 // treatment of periodic faces
226 for ( TopExp_Explorer eF( aSh, TopAbs_FACE ); eF.More(); eF.Next() )
228 const TopoDS_Face& face = TopoDS::Face( eF.Current() );
230 Handle(Geom_Surface) surface = BRep_Tool::Surface( face, loc );
232 if ( surface->IsUPeriodic() || surface->IsVPeriodic() ||
233 surface->IsUClosed() || surface->IsVClosed() )
235 //while ( surface->IsKind(STANDARD_TYPE(Geom_RectangularTrimmedSurface )))
236 //surface = Handle(Geom_RectangularTrimmedSurface)::DownCast( surface )->BasisSurface();
237 GeomAdaptor_Surface surf( surface );
239 for (TopExp_Explorer exp( face, TopAbs_EDGE ); exp.More(); exp.Next())
241 // look for a seam edge
242 const TopoDS_Edge& edge = TopoDS::Edge( exp.Current() );
243 if ( BRep_Tool::IsClosed( edge, face )) {
244 // initialize myPar1, myPar2 and myParIndex
246 BRep_Tool::UVPoints( edge, face, uv1, uv2 );
247 if ( Abs( uv1.Coord(1) - uv2.Coord(1) ) < Abs( uv1.Coord(2) - uv2.Coord(2) ))
249 myParIndex |= U_periodic;
250 myPar1[0] = surf.FirstUParameter();
251 myPar2[0] = surf.LastUParameter();
254 myParIndex |= V_periodic;
255 myPar1[1] = surf.FirstVParameter();
256 myPar2[1] = surf.LastVParameter();
258 // store seam shape indices, negative if shape encounters twice
259 int edgeID = meshDS->ShapeToIndex( edge );
260 mySeamShapeIds.insert( IsSeamShape( edgeID ) ? -edgeID : edgeID );
261 for ( TopExp_Explorer v( edge, TopAbs_VERTEX ); v.More(); v.Next() ) {
262 int vertexID = meshDS->ShapeToIndex( v.Current() );
263 mySeamShapeIds.insert( IsSeamShape( vertexID ) ? -vertexID : vertexID );
267 // look for a degenerated edge
268 if ( BRep_Tool::Degenerated( edge )) {
269 myDegenShapeIds.insert( meshDS->ShapeToIndex( edge ));
270 for ( TopExp_Explorer v( edge, TopAbs_VERTEX ); v.More(); v.Next() )
271 myDegenShapeIds.insert( meshDS->ShapeToIndex( v.Current() ));
278 //=======================================================================
279 //function : GetNodeUVneedInFaceNode
280 //purpose : Check if inFaceNode argument is necessary for call GetNodeUV(F,..)
281 // Return true if the face is periodic.
282 // If F is Null, answer about sub-shape set through IsQuadraticSubMesh() or
284 //=======================================================================
286 bool SMESH_MesherHelper::GetNodeUVneedInFaceNode(const TopoDS_Face& F) const
288 if ( F.IsNull() ) return !mySeamShapeIds.empty();
290 if ( !F.IsNull() && !myShape.IsNull() && myShape.IsSame( F ))
291 return !mySeamShapeIds.empty();
294 Handle(Geom_Surface) aSurface = BRep_Tool::Surface( F,loc );
295 if ( !aSurface.IsNull() )
296 return ( aSurface->IsUPeriodic() || aSurface->IsVPeriodic() );
301 //=======================================================================
302 //function : IsMedium
304 //=======================================================================
306 bool SMESH_MesherHelper::IsMedium(const SMDS_MeshNode* node,
307 const SMDSAbs_ElementType typeToCheck)
309 return SMESH_MeshEditor::IsMedium( node, typeToCheck );
312 //=======================================================================
313 //function : GetSubShapeByNode
314 //purpose : Return support shape of a node
315 //=======================================================================
317 TopoDS_Shape SMESH_MesherHelper::GetSubShapeByNode(const SMDS_MeshNode* node,
318 const SMESHDS_Mesh* meshDS)
320 int shapeID = node->getshapeId();
321 if ( 0 < shapeID && shapeID <= meshDS->MaxShapeIndex() )
322 return meshDS->IndexToShape( shapeID );
324 return TopoDS_Shape();
328 //=======================================================================
329 //function : AddTLinkNode
330 //purpose : add a link in my data structure
331 //=======================================================================
333 void SMESH_MesherHelper::AddTLinkNode(const SMDS_MeshNode* n1,
334 const SMDS_MeshNode* n2,
335 const SMDS_MeshNode* n12)
337 // add new record to map
338 SMESH_TLink link( n1, n2 );
339 myTLinkNodeMap.insert( make_pair(link,n12));
342 //================================================================================
344 * \brief Add quadratic links of edge to own data structure
346 //================================================================================
348 void SMESH_MesherHelper::AddTLinks(const SMDS_MeshEdge* edge)
350 if ( edge->IsQuadratic() )
351 AddTLinkNode(edge->GetNode(0), edge->GetNode(1), edge->GetNode(2));
354 //================================================================================
356 * \brief Add quadratic links of face to own data structure
358 //================================================================================
360 void SMESH_MesherHelper::AddTLinks(const SMDS_MeshFace* f)
363 switch ( f->NbNodes() ) {
365 AddTLinkNode(f->GetNode(0),f->GetNode(1),f->GetNode(3));
366 AddTLinkNode(f->GetNode(1),f->GetNode(2),f->GetNode(4));
367 AddTLinkNode(f->GetNode(2),f->GetNode(0),f->GetNode(5)); break;
369 AddTLinkNode(f->GetNode(0),f->GetNode(1),f->GetNode(4));
370 AddTLinkNode(f->GetNode(1),f->GetNode(2),f->GetNode(5));
371 AddTLinkNode(f->GetNode(2),f->GetNode(3),f->GetNode(6));
372 AddTLinkNode(f->GetNode(3),f->GetNode(0),f->GetNode(7));
377 //================================================================================
379 * \brief Add quadratic links of volume to own data structure
381 //================================================================================
383 void SMESH_MesherHelper::AddTLinks(const SMDS_MeshVolume* volume)
385 if ( volume->IsQuadratic() )
387 SMDS_VolumeTool vTool( volume );
388 const SMDS_MeshNode** nodes = vTool.GetNodes();
390 for ( int iF = 1; iF < vTool.NbFaces(); ++iF )
392 const int nbN = vTool.NbFaceNodes( iF );
393 const int* iNodes = vTool.GetFaceNodesIndices( iF );
394 for ( int i = 0; i < nbN; )
396 int iN1 = iNodes[i++];
397 int iN12 = iNodes[i++];
398 int iN2 = iNodes[i++];
399 if ( iN1 > iN2 ) std::swap( iN1, iN2 );
400 int linkID = iN1 * vTool.NbNodes() + iN2;
401 pair< set<int>::iterator, bool > it_isNew = addedLinks.insert( linkID );
402 if ( it_isNew.second )
403 AddTLinkNode( nodes[iN1], nodes[iN2], nodes[iN12] );
405 addedLinks.erase( it_isNew.first ); // each link encounters only twice
411 //================================================================================
413 * \brief Return true if position of nodes on the shape hasn't yet been checked or
414 * the positions proved to be invalid
416 //================================================================================
418 bool SMESH_MesherHelper::toCheckPosOnShape(int shapeID ) const
420 map< int,bool >::const_iterator id_ok = myNodePosShapesValidity.find( shapeID );
421 return ( id_ok == myNodePosShapesValidity.end() || !id_ok->second );
424 //================================================================================
426 * \brief Set validity of positions of nodes on the shape.
427 * Once set, validity is not changed
429 //================================================================================
431 void SMESH_MesherHelper::setPosOnShapeValidity(int shapeID, bool ok ) const
433 ((SMESH_MesherHelper*)this)->myNodePosShapesValidity.insert( make_pair( shapeID, ok));
436 //=======================================================================
437 //function : GetUVOnSeam
438 //purpose : Select UV on either of 2 pcurves of a seam edge, closest to the given UV
439 //=======================================================================
441 gp_Pnt2d SMESH_MesherHelper::GetUVOnSeam( const gp_Pnt2d& uv1, const gp_Pnt2d& uv2 ) const
443 gp_Pnt2d result = uv1;
444 for ( int i = U_periodic; i <= V_periodic ; ++i )
446 if ( myParIndex & i )
448 double p1 = uv1.Coord( i );
449 double dp1 = Abs( p1-myPar1[i-1]), dp2 = Abs( p1-myPar2[i-1]);
450 if ( myParIndex == i ||
451 dp1 < ( myPar2[i-1] - myPar2[i-1] ) / 100. ||
452 dp2 < ( myPar2[i-1] - myPar2[i-1] ) / 100. )
454 double p2 = uv2.Coord( i );
455 double p1Alt = ( dp1 < dp2 ) ? myPar2[i-1] : myPar1[i-1];
456 if ( Abs( p2 - p1 ) > Abs( p2 - p1Alt ))
457 result.SetCoord( i, p1Alt );
464 //=======================================================================
465 //function : GetNodeUV
466 //purpose : Return node UV on face
467 //=======================================================================
469 gp_XY SMESH_MesherHelper::GetNodeUV(const TopoDS_Face& F,
470 const SMDS_MeshNode* n,
471 const SMDS_MeshNode* n2,
474 gp_Pnt2d uv( Precision::Infinite(), Precision::Infinite() );
475 const SMDS_PositionPtr Pos = n->GetPosition();
477 if(Pos->GetTypeOfPosition()==SMDS_TOP_FACE)
479 // node has position on face
480 const SMDS_FacePosition* fpos =
481 static_cast<const SMDS_FacePosition*>(n->GetPosition());
482 uv.SetCoord(fpos->GetUParameter(),fpos->GetVParameter());
484 uvOK = CheckNodeUV( F, n, uv.ChangeCoord(), 10*MaxTolerance( F ));
486 else if(Pos->GetTypeOfPosition()==SMDS_TOP_EDGE)
488 // node has position on edge => it is needed to find
489 // corresponding edge from face, get pcurve for this
490 // edge and retrieve value from this pcurve
491 const SMDS_EdgePosition* epos =
492 static_cast<const SMDS_EdgePosition*>(n->GetPosition());
493 int edgeID = n->getshapeId();
494 TopoDS_Edge E = TopoDS::Edge(GetMeshDS()->IndexToShape(edgeID));
495 double f, l, u = epos->GetUParameter();
496 Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface(E, F, f, l);
497 bool validU = ( f < u && u < l );
499 uv = C2d->Value( u );
501 uv.SetCoord( Precision::Infinite(),0.);
502 if ( check || !validU )
503 uvOK = CheckNodeUV( F, n, uv.ChangeCoord(), 10*MaxTolerance( F ),/*force=*/ !validU );
505 // for a node on a seam edge select one of UVs on 2 pcurves
506 if ( n2 && IsSeamShape( edgeID ) )
508 uv = GetUVOnSeam( uv, GetNodeUV( F, n2, 0, check ));
511 { // adjust uv to period
513 Handle(Geom_Surface) S = BRep_Tool::Surface(F,loc);
514 Standard_Boolean isUPeriodic = S->IsUPeriodic();
515 Standard_Boolean isVPeriodic = S->IsVPeriodic();
516 if ( isUPeriodic || isVPeriodic ) {
517 Standard_Real UF,UL,VF,VL;
518 S->Bounds(UF,UL,VF,VL);
520 uv.SetX( uv.X() + ShapeAnalysis::AdjustToPeriod(uv.X(),UF,UL));
522 uv.SetY( uv.Y() + ShapeAnalysis::AdjustToPeriod(uv.Y(),VF,VL));
526 else if(Pos->GetTypeOfPosition()==SMDS_TOP_VERTEX)
528 if ( int vertexID = n->getshapeId() ) {
529 const TopoDS_Vertex& V = TopoDS::Vertex(GetMeshDS()->IndexToShape(vertexID));
531 uv = BRep_Tool::Parameters( V, F );
534 catch (Standard_Failure& exc) {
537 for ( TopExp_Explorer vert(F,TopAbs_VERTEX); !uvOK && vert.More(); vert.Next() )
538 uvOK = ( V == vert.Current() );
541 MESSAGE ( "SMESH_MesherHelper::GetNodeUV(); Vertex " << vertexID
542 << " not in face " << GetMeshDS()->ShapeToIndex( F ) );
544 // get UV of a vertex closest to the node
546 gp_Pnt pn = XYZ( n );
547 for ( TopExp_Explorer vert(F,TopAbs_VERTEX); !uvOK && vert.More(); vert.Next() ) {
548 TopoDS_Vertex curV = TopoDS::Vertex( vert.Current() );
549 gp_Pnt p = BRep_Tool::Pnt( curV );
550 double curDist = p.SquareDistance( pn );
551 if ( curDist < dist ) {
553 uv = BRep_Tool::Parameters( curV, F );
554 uvOK = ( dist < DBL_MIN );
560 TopTools_ListIteratorOfListOfShape it( myMesh->GetAncestors( V ));
561 for ( ; it.More(); it.Next() ) {
562 if ( it.Value().ShapeType() == TopAbs_EDGE ) {
563 const TopoDS_Edge & edge = TopoDS::Edge( it.Value() );
565 Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface(edge, F, f, l);
566 if ( !C2d.IsNull() ) {
567 double u = ( V == TopExp::FirstVertex( edge ) ) ? f : l;
568 uv = C2d->Value( u );
576 if ( n2 && IsSeamShape( vertexID ) )
577 uv = GetUVOnSeam( uv, GetNodeUV( F, n2, 0 ));
582 uvOK = CheckNodeUV( F, n, uv.ChangeCoord(), 10*MaxTolerance( F ));
591 //=======================================================================
592 //function : CheckNodeUV
593 //purpose : Check and fix node UV on a face
594 //=======================================================================
596 bool SMESH_MesherHelper::CheckNodeUV(const TopoDS_Face& F,
597 const SMDS_MeshNode* n,
601 double distXYZ[4]) const
603 int shapeID = n->getshapeId();
604 bool infinit = ( Precision::IsInfinite( uv.X() ) || Precision::IsInfinite( uv.Y() ));
605 if ( force || toCheckPosOnShape( shapeID ) || infinit )
607 // check that uv is correct
609 Handle(Geom_Surface) surface = BRep_Tool::Surface( F,loc );
610 gp_Pnt nodePnt = XYZ( n ), surfPnt(0,0,0);
612 if ( !loc.IsIdentity() ) nodePnt.Transform( loc.Transformation().Inverted() );
614 (dist = nodePnt.Distance( surfPnt = surface->Value( uv.X(), uv.Y() ))) > tol )
616 setPosOnShapeValidity( shapeID, false );
617 if ( !infinit && distXYZ ) {
618 surfPnt.Transform( loc );
620 distXYZ[1] = surfPnt.X(); distXYZ[2] = surfPnt.Y(); distXYZ[3]=surfPnt.Z();
622 // uv incorrect, project the node to surface
623 GeomAPI_ProjectPointOnSurf& projector = GetProjector( F, loc, tol );
624 projector.Perform( nodePnt );
625 if ( !projector.IsDone() || projector.NbPoints() < 1 )
627 MESSAGE( "SMESH_MesherHelper::CheckNodeUV() failed to project" );
630 Quantity_Parameter U,V;
631 projector.LowerDistanceParameters(U,V);
633 surfPnt = surface->Value( U, V );
634 dist = nodePnt.Distance( surfPnt );
636 surfPnt.Transform( loc );
638 distXYZ[1] = surfPnt.X(); distXYZ[2] = surfPnt.Y(); distXYZ[3]=surfPnt.Z();
642 MESSAGE( "SMESH_MesherHelper::CheckNodeUV(), invalid projection" );
645 // store the fixed UV on the face
646 if ( myShape.IsSame(F) && shapeID == myShapeID )
647 const_cast<SMDS_MeshNode*>(n)->SetPosition
648 ( SMDS_PositionPtr( new SMDS_FacePosition( U, V )));
650 else if ( uv.Modulus() > numeric_limits<double>::min() )
652 setPosOnShapeValidity( shapeID, true );
658 //=======================================================================
659 //function : GetProjector
660 //purpose : Return projector intitialized by given face without location, which is returned
661 //=======================================================================
663 GeomAPI_ProjectPointOnSurf& SMESH_MesherHelper::GetProjector(const TopoDS_Face& F,
664 TopLoc_Location& loc,
667 Handle(Geom_Surface) surface = BRep_Tool::Surface( F,loc );
668 int faceID = GetMeshDS()->ShapeToIndex( F );
669 TID2ProjectorOnSurf& i2proj = const_cast< TID2ProjectorOnSurf&>( myFace2Projector );
670 TID2ProjectorOnSurf::iterator i_proj = i2proj.find( faceID );
671 if ( i_proj == i2proj.end() )
673 if ( tol == 0 ) tol = BRep_Tool::Tolerance( F );
674 double U1, U2, V1, V2;
675 surface->Bounds(U1, U2, V1, V2);
676 GeomAPI_ProjectPointOnSurf* proj = new GeomAPI_ProjectPointOnSurf();
677 proj->Init( surface, U1, U2, V1, V2, tol );
678 i_proj = i2proj.insert( make_pair( faceID, proj )).first;
680 return *( i_proj->second );
685 gp_XY AverageUV(const gp_XY& uv1, const gp_XY& uv2) { return ( uv1 + uv2 ) / 2.; }
686 gp_XY_FunPtr(Added); // define gp_XY_Added pointer to function calling gp_XY::Added(gp_XY)
687 gp_XY_FunPtr(Subtracted);
690 //=======================================================================
691 //function : applyIn2D
692 //purpose : Perform given operation on two 2d points in parameric space of given surface.
693 // It takes into account period of the surface. Use gp_XY_FunPtr macro
694 // to easily define pointer to function of gp_XY class.
695 //=======================================================================
697 gp_XY SMESH_MesherHelper::applyIn2D(const Handle(Geom_Surface)& surface,
701 const bool resultInPeriod)
703 Standard_Boolean isUPeriodic = surface.IsNull() ? false : surface->IsUPeriodic();
704 Standard_Boolean isVPeriodic = surface.IsNull() ? false : surface->IsVPeriodic();
705 if ( !isUPeriodic && !isVPeriodic )
708 // move uv2 not far than half-period from uv1
710 uv2.X()+(isUPeriodic ? ShapeAnalysis::AdjustByPeriod(uv2.X(),uv1.X(),surface->UPeriod()) :0);
712 uv2.Y()+(isVPeriodic ? ShapeAnalysis::AdjustByPeriod(uv2.Y(),uv1.Y(),surface->VPeriod()) :0);
715 gp_XY res = fun( uv1, gp_XY(u2,v2) );
717 // move result within period
718 if ( resultInPeriod )
720 Standard_Real UF,UL,VF,VL;
721 surface->Bounds(UF,UL,VF,VL);
723 res.SetX( res.X() + ShapeAnalysis::AdjustToPeriod(res.X(),UF,UL));
725 res.SetY( res.Y() + ShapeAnalysis::AdjustToPeriod(res.Y(),VF,VL));
730 //=======================================================================
731 //function : GetMiddleUV
732 //purpose : Return middle UV taking in account surface period
733 //=======================================================================
735 gp_XY SMESH_MesherHelper::GetMiddleUV(const Handle(Geom_Surface)& surface,
740 // the proper place of getting basic surface seems to be in applyIn2D()
741 // but we put it here to decrease a risk of regressions just before releasing a version
742 Handle(Geom_Surface) surf = surface;
743 while ( !surf.IsNull() && surf->IsKind(STANDARD_TYPE(Geom_RectangularTrimmedSurface )))
744 surf = Handle(Geom_RectangularTrimmedSurface)::DownCast( surf )->BasisSurface();
746 return applyIn2D( surf, p1, p2, & AverageUV );
749 //=======================================================================
750 //function : GetNodeU
751 //purpose : Return node U on edge
752 //=======================================================================
754 double SMESH_MesherHelper::GetNodeU(const TopoDS_Edge& E,
755 const SMDS_MeshNode* n,
756 const SMDS_MeshNode* inEdgeNode,
760 const SMDS_PositionPtr pos = n->GetPosition();
761 if ( pos->GetTypeOfPosition()==SMDS_TOP_EDGE )
763 const SMDS_EdgePosition* epos = static_cast<const SMDS_EdgePosition*>( pos );
764 param = epos->GetUParameter();
766 else if( pos->GetTypeOfPosition() == SMDS_TOP_VERTEX )
768 if ( inEdgeNode && TopExp::FirstVertex( E ).IsSame( TopExp::LastVertex( E ))) // issue 0020128
771 BRep_Tool::Range( E, f,l );
772 double uInEdge = GetNodeU( E, inEdgeNode );
773 param = ( fabs( uInEdge - f ) < fabs( l - uInEdge )) ? f : l;
777 SMESHDS_Mesh * meshDS = GetMeshDS();
778 int vertexID = n->getshapeId();
779 const TopoDS_Vertex& V = TopoDS::Vertex(meshDS->IndexToShape(vertexID));
780 param = BRep_Tool::Parameter( V, E );
785 double tol = BRep_Tool::Tolerance( E );
786 double f,l; BRep_Tool::Range( E, f,l );
787 bool force = ( param < f-tol || param > l+tol );
788 if ( !force && pos->GetTypeOfPosition()==SMDS_TOP_EDGE )
789 force = ( GetMeshDS()->ShapeToIndex( E ) != n->getshapeId() );
791 *check = CheckNodeU( E, n, param, 2*tol, force );
796 //=======================================================================
797 //function : CheckNodeU
798 //purpose : Check and fix node U on an edge
799 // Return false if U is bad and could not be fixed
800 //=======================================================================
802 bool SMESH_MesherHelper::CheckNodeU(const TopoDS_Edge& E,
803 const SMDS_MeshNode* n,
807 double distXYZ[4]) const
809 int shapeID = n->getshapeId();
810 if ( force || toCheckPosOnShape( shapeID ))
812 TopLoc_Location loc; double f,l;
813 Handle(Geom_Curve) curve = BRep_Tool::Curve( E,loc,f,l );
814 if ( curve.IsNull() ) // degenerated edge
816 if ( u+tol < f || u-tol > l )
818 double r = Max( 0.5, 1 - tol*n->GetID()); // to get a unique u on edge
824 gp_Pnt nodePnt = SMESH_TNodeXYZ( n );
825 if ( !loc.IsIdentity() ) nodePnt.Transform( loc.Transformation().Inverted() );
826 gp_Pnt curvPnt = curve->Value( u );
827 double dist = nodePnt.Distance( curvPnt );
829 curvPnt.Transform( loc );
831 distXYZ[1] = curvPnt.X(); distXYZ[2] = curvPnt.Y(); distXYZ[3]=curvPnt.Z();
835 setPosOnShapeValidity( shapeID, false );
836 // u incorrect, project the node to the curve
837 int edgeID = GetMeshDS()->ShapeToIndex( E );
838 TID2ProjectorOnCurve& i2proj = const_cast< TID2ProjectorOnCurve&>( myEdge2Projector );
839 TID2ProjectorOnCurve::iterator i_proj =
840 i2proj.insert( make_pair( edgeID, (GeomAPI_ProjectPointOnCurve*) 0 )).first;
841 if ( !i_proj->second )
843 i_proj->second = new GeomAPI_ProjectPointOnCurve();
844 i_proj->second->Init( curve, f, l );
846 GeomAPI_ProjectPointOnCurve* projector = i_proj->second;
847 projector->Perform( nodePnt );
848 if ( projector->NbPoints() < 1 )
850 MESSAGE( "SMESH_MesherHelper::CheckNodeU() failed to project" );
853 Quantity_Parameter U = projector->LowerDistanceParameter();
855 curvPnt = curve->Value( u );
856 dist = nodePnt.Distance( curvPnt );
858 curvPnt.Transform( loc );
860 distXYZ[1] = curvPnt.X(); distXYZ[2] = curvPnt.Y(); distXYZ[3]=curvPnt.Z();
864 MESSAGE( "SMESH_MesherHelper::CheckNodeU(), invalid projection" );
865 MESSAGE("distance " << dist << " " << tol );
868 // store the fixed U on the edge
869 if ( myShape.IsSame(E) && shapeID == myShapeID )
870 const_cast<SMDS_MeshNode*>(n)->SetPosition
871 ( SMDS_PositionPtr( new SMDS_EdgePosition( U )));
873 else if ( fabs( u ) > numeric_limits<double>::min() )
875 setPosOnShapeValidity( shapeID, true );
877 if (( u < f-tol || u > l+tol ) && force )
879 // node is on vertex but is set on periodic but trimmed edge (issue 0020890)
882 // do not use IsPeriodic() as Geom_TrimmedCurve::IsPeriodic () returns false
883 double period = curve->Period();
884 u = ( u < f ) ? u + period : u - period;
886 catch (Standard_Failure& exc)
896 //=======================================================================
897 //function : GetMediumPos
898 //purpose : Return index and type of the shape (EDGE or FACE only) to
899 // set a medium node on
900 //=======================================================================
902 std::pair<int, TopAbs_ShapeEnum> SMESH_MesherHelper::GetMediumPos(const SMDS_MeshNode* n1,
903 const SMDS_MeshNode* n2)
905 TopAbs_ShapeEnum shapeType = TopAbs_SHAPE;
909 if (( myShapeID == n1->getshapeId() || myShapeID == n2->getshapeId() ) && myShapeID > 0 )
911 shapeType = myShape.ShapeType();
914 else if ( n1->getshapeId() == n2->getshapeId() )
916 shapeID = n2->getshapeId();
917 shape = GetSubShapeByNode( n1, GetMeshDS() );
921 const SMDS_TypeOfPosition Pos1 = n1->GetPosition()->GetTypeOfPosition();
922 const SMDS_TypeOfPosition Pos2 = n2->GetPosition()->GetTypeOfPosition();
924 if ( Pos1 == SMDS_TOP_3DSPACE || Pos2 == SMDS_TOP_3DSPACE )
927 else if ( Pos1 == SMDS_TOP_FACE || Pos2 == SMDS_TOP_FACE )
929 if ( Pos1 != SMDS_TOP_FACE || Pos2 != SMDS_TOP_FACE )
931 if ( Pos1 != SMDS_TOP_FACE ) std::swap( n1,n2 );
932 TopoDS_Shape F = GetSubShapeByNode( n1, GetMeshDS() );
933 TopoDS_Shape S = GetSubShapeByNode( n2, GetMeshDS() );
934 if ( IsSubShape( S, F ))
936 shapeType = TopAbs_FACE;
937 shapeID = n1->getshapeId();
941 else if ( Pos1 == SMDS_TOP_EDGE && Pos2 == SMDS_TOP_EDGE )
943 TopoDS_Shape E1 = GetSubShapeByNode( n1, GetMeshDS() );
944 TopoDS_Shape E2 = GetSubShapeByNode( n2, GetMeshDS() );
945 shape = GetCommonAncestor( E1, E2, *myMesh, TopAbs_FACE );
947 else if ( Pos1 == SMDS_TOP_VERTEX && Pos2 == SMDS_TOP_VERTEX )
949 TopoDS_Shape V1 = GetSubShapeByNode( n1, GetMeshDS() );
950 TopoDS_Shape V2 = GetSubShapeByNode( n2, GetMeshDS() );
951 shape = GetCommonAncestor( V1, V2, *myMesh, TopAbs_EDGE );
952 if ( shape.IsNull() ) shape = GetCommonAncestor( V1, V2, *myMesh, TopAbs_FACE );
954 else // VERTEX and EDGE
956 if ( Pos1 != SMDS_TOP_VERTEX ) std::swap( n1,n2 );
957 TopoDS_Shape V = GetSubShapeByNode( n1, GetMeshDS() );
958 TopoDS_Shape E = GetSubShapeByNode( n2, GetMeshDS() );
959 if ( IsSubShape( V, E ))
962 shape = GetCommonAncestor( V, E, *myMesh, TopAbs_FACE );
966 if ( !shape.IsNull() )
969 shapeID = GetMeshDS()->ShapeToIndex( shape );
970 shapeType = shape.ShapeType();
972 return make_pair( shapeID, shapeType );
975 //=======================================================================
976 //function : GetMediumNode
977 //purpose : Return existing or create new medium nodes between given ones
978 //=======================================================================
980 const SMDS_MeshNode* SMESH_MesherHelper::GetMediumNode(const SMDS_MeshNode* n1,
981 const SMDS_MeshNode* n2,
984 // Find existing node
986 SMESH_TLink link(n1,n2);
987 ItTLinkNode itLN = myTLinkNodeMap.find( link );
988 if ( itLN != myTLinkNodeMap.end() ) {
989 return (*itLN).second;
992 // Create medium node
995 SMESHDS_Mesh* meshDS = GetMeshDS();
997 if ( IsSeamShape( n1->getshapeId() ))
998 // to get a correct UV of a node on seam, the second node must have checked UV
1001 // get type of shape for the new medium node
1002 int faceID = -1, edgeID = -1;
1003 TopoDS_Edge E; double u [2];
1004 TopoDS_Face F; gp_XY uv[2];
1005 bool uvOK[2] = { false, false };
1007 pair<int, TopAbs_ShapeEnum> pos = GetMediumPos( n1, n2 );
1009 // get positions of the given nodes on shapes
1010 if ( pos.second == TopAbs_FACE )
1012 F = TopoDS::Face(meshDS->IndexToShape( faceID = pos.first ));
1013 uv[0] = GetNodeUV(F,n1,n2, force3d ? 0 : &uvOK[0]);
1014 uv[1] = GetNodeUV(F,n2,n1, force3d ? 0 : &uvOK[1]);
1016 else if ( pos.second == TopAbs_EDGE )
1018 const SMDS_PositionPtr Pos1 = n1->GetPosition();
1019 const SMDS_PositionPtr Pos2 = n2->GetPosition();
1020 if ( Pos1->GetTypeOfPosition()==SMDS_TOP_EDGE &&
1021 Pos2->GetTypeOfPosition()==SMDS_TOP_EDGE &&
1022 n1->getshapeId() != n2->getshapeId() )
1025 return getMediumNodeOnComposedWire(n1,n2,force3d);
1027 E = TopoDS::Edge(meshDS->IndexToShape( edgeID = pos.first ));
1028 u[0] = GetNodeU(E,n1,n2, force3d ? 0 : &uvOK[0]);
1029 u[1] = GetNodeU(E,n2,n1, force3d ? 0 : &uvOK[1]);
1032 if ( !force3d & uvOK[0] && uvOK[1] )
1034 // we try to create medium node using UV parameters of
1035 // nodes, else - medium between corresponding 3d points
1038 //if ( uvOK[0] && uvOK[1] )
1040 if ( IsDegenShape( n1->getshapeId() )) {
1041 if ( myParIndex & U_periodic ) uv[0].SetCoord( 1, uv[1].Coord( 1 ));
1042 else uv[0].SetCoord( 2, uv[1].Coord( 2 ));
1044 else if ( IsDegenShape( n2->getshapeId() )) {
1045 if ( myParIndex & U_periodic ) uv[1].SetCoord( 1, uv[0].Coord( 1 ));
1046 else uv[1].SetCoord( 2, uv[0].Coord( 2 ));
1049 TopLoc_Location loc;
1050 Handle(Geom_Surface) S = BRep_Tool::Surface(F,loc);
1051 gp_XY UV = GetMiddleUV( S, uv[0], uv[1] );
1052 gp_Pnt P = S->Value( UV.X(), UV.Y() ).Transformed(loc);
1053 n12 = meshDS->AddNode(P.X(), P.Y(), P.Z());
1054 meshDS->SetNodeOnFace(n12, faceID, UV.X(), UV.Y());
1055 myTLinkNodeMap.insert(make_pair(link,n12));
1059 else if ( !E.IsNull() )
1062 Handle(Geom_Curve) C = BRep_Tool::Curve(E, f, l);
1065 Standard_Boolean isPeriodic = C->IsPeriodic();
1068 Standard_Real Period = C->Period();
1069 Standard_Real p = u[1]+ShapeAnalysis::AdjustByPeriod(u[1],u[0],Period);
1070 Standard_Real pmid = (u[0]+p)/2.;
1071 U = pmid+ShapeAnalysis::AdjustToPeriod(pmid,C->FirstParameter(),C->LastParameter());
1076 gp_Pnt P = C->Value( U );
1077 n12 = meshDS->AddNode(P.X(), P.Y(), P.Z());
1078 meshDS->SetNodeOnEdge(n12, edgeID, U);
1079 myTLinkNodeMap.insert(make_pair(link,n12));
1086 double x = ( n1->X() + n2->X() )/2.;
1087 double y = ( n1->Y() + n2->Y() )/2.;
1088 double z = ( n1->Z() + n2->Z() )/2.;
1089 n12 = meshDS->AddNode(x,y,z);
1093 gp_XY UV = ( uv[0] + uv[1] ) / 2.;
1094 CheckNodeUV( F, n12, UV, 2*BRep_Tool::Tolerance( F ), /*force=*/true);
1095 meshDS->SetNodeOnFace(n12, faceID, UV.X(), UV.Y() );
1097 else if ( !E.IsNull() )
1099 double U = ( u[0] + u[1] ) / 2.;
1100 CheckNodeU( E, n12, U, 2*BRep_Tool::Tolerance( E ), /*force=*/true);
1101 meshDS->SetNodeOnEdge(n12, edgeID, U);
1103 else if ( myShapeID > 0 )
1105 meshDS->SetNodeInVolume(n12, myShapeID);
1108 myTLinkNodeMap.insert( make_pair( link, n12 ));
1112 //================================================================================
1114 * \brief Makes a medium node if nodes reside different edges
1116 //================================================================================
1118 const SMDS_MeshNode* SMESH_MesherHelper::getMediumNodeOnComposedWire(const SMDS_MeshNode* n1,
1119 const SMDS_MeshNode* n2,
1122 gp_Pnt middle = 0.5 * XYZ(n1) + 0.5 * XYZ(n2);
1123 SMDS_MeshNode* n12 = AddNode( middle.X(), middle.Y(), middle.Z() );
1125 // To find position on edge and 3D position for n12,
1126 // project <middle> to 2 edges and select projection most close to <middle>
1128 double u = 0, distMiddleProj = Precision::Infinite(), distXYZ[4];
1130 TopoDS_Edge edges[2];
1131 for ( int is2nd = 0; is2nd < 2; ++is2nd )
1134 const SMDS_MeshNode* n = is2nd ? n2 : n1;
1135 TopoDS_Shape shape = GetSubShapeByNode( n, GetMeshDS() );
1136 if ( shape.IsNull() || shape.ShapeType() != TopAbs_EDGE )
1139 // project to get U of projection and distance from middle to projection
1140 TopoDS_Edge edge = edges[ is2nd ] = TopoDS::Edge( shape );
1141 double node2MiddleDist = middle.Distance( XYZ(n) );
1142 double foundU = GetNodeU( edge, n );
1143 CheckNodeU( edge, n12, foundU, 2*BRep_Tool::Tolerance(edge), /*force=*/true, distXYZ );
1144 if ( distXYZ[0] < node2MiddleDist )
1146 distMiddleProj = distXYZ[0];
1151 if ( Precision::IsInfinite( distMiddleProj ))
1153 // both projections failed; set n12 on the edge of n1 with U of a common vertex
1154 TopoDS_Vertex vCommon;
1155 if ( TopExp::CommonVertex( edges[0], edges[1], vCommon ))
1156 u = BRep_Tool::Parameter( vCommon, edges[0] );
1159 double f,l, u0 = GetNodeU( edges[0], n1 );
1160 BRep_Tool::Range( edges[0],f,l );
1161 u = ( fabs(u0-f) < fabs(u0-l) ) ? f : l;
1167 // move n12 to position of a successfull projection
1168 double tol = BRep_Tool::Tolerance(edges[ iOkEdge ]);
1169 if ( !force3d && distMiddleProj > 2*tol )
1171 TopLoc_Location loc; double f,l;
1172 Handle(Geom_Curve) curve = BRep_Tool::Curve( edges[iOkEdge],loc,f,l );
1173 gp_Pnt p = curve->Value( u );
1174 GetMeshDS()->MoveNode( n12, p.X(), p.Y(), p.Z() );
1177 GetMeshDS()->SetNodeOnEdge(n12, edges[iOkEdge], u);
1179 myTLinkNodeMap.insert( make_pair( SMESH_TLink(n1,n2), n12 ));
1184 //=======================================================================
1185 //function : AddNode
1186 //purpose : Creates a node
1187 //=======================================================================
1189 SMDS_MeshNode* SMESH_MesherHelper::AddNode(double x, double y, double z, int ID)
1191 SMESHDS_Mesh * meshDS = GetMeshDS();
1192 SMDS_MeshNode* node = 0;
1194 node = meshDS->AddNodeWithID( x, y, z, ID );
1196 node = meshDS->AddNode( x, y, z );
1197 if ( mySetElemOnShape && myShapeID > 0 ) {
1198 switch ( myShape.ShapeType() ) {
1199 case TopAbs_SOLID: meshDS->SetNodeInVolume( node, myShapeID); break;
1200 case TopAbs_SHELL: meshDS->SetNodeInVolume( node, myShapeID); break;
1201 case TopAbs_FACE: meshDS->SetNodeOnFace( node, myShapeID); break;
1202 case TopAbs_EDGE: meshDS->SetNodeOnEdge( node, myShapeID); break;
1203 case TopAbs_VERTEX: meshDS->SetNodeOnVertex( node, myShapeID); break;
1210 //=======================================================================
1211 //function : AddEdge
1212 //purpose : Creates quadratic or linear edge
1213 //=======================================================================
1215 SMDS_MeshEdge* SMESH_MesherHelper::AddEdge(const SMDS_MeshNode* n1,
1216 const SMDS_MeshNode* n2,
1220 SMESHDS_Mesh * meshDS = GetMeshDS();
1222 SMDS_MeshEdge* edge = 0;
1223 if (myCreateQuadratic) {
1224 const SMDS_MeshNode* n12 = GetMediumNode(n1,n2,force3d);
1226 edge = meshDS->AddEdgeWithID(n1, n2, n12, id);
1228 edge = meshDS->AddEdge(n1, n2, n12);
1232 edge = meshDS->AddEdgeWithID(n1, n2, id);
1234 edge = meshDS->AddEdge(n1, n2);
1237 if ( mySetElemOnShape && myShapeID > 0 )
1238 meshDS->SetMeshElementOnShape( edge, myShapeID );
1243 //=======================================================================
1244 //function : AddFace
1245 //purpose : Creates quadratic or linear triangle
1246 //=======================================================================
1248 SMDS_MeshFace* SMESH_MesherHelper::AddFace(const SMDS_MeshNode* n1,
1249 const SMDS_MeshNode* n2,
1250 const SMDS_MeshNode* n3,
1254 SMESHDS_Mesh * meshDS = GetMeshDS();
1255 SMDS_MeshFace* elem = 0;
1257 if( n1==n2 || n2==n3 || n3==n1 )
1260 if(!myCreateQuadratic) {
1262 elem = meshDS->AddFaceWithID(n1, n2, n3, id);
1264 elem = meshDS->AddFace(n1, n2, n3);
1267 const SMDS_MeshNode* n12 = GetMediumNode(n1,n2,force3d);
1268 const SMDS_MeshNode* n23 = GetMediumNode(n2,n3,force3d);
1269 const SMDS_MeshNode* n31 = GetMediumNode(n3,n1,force3d);
1272 elem = meshDS->AddFaceWithID(n1, n2, n3, n12, n23, n31, id);
1274 elem = meshDS->AddFace(n1, n2, n3, n12, n23, n31);
1276 if ( mySetElemOnShape && myShapeID > 0 )
1277 meshDS->SetMeshElementOnShape( elem, myShapeID );
1282 //=======================================================================
1283 //function : AddFace
1284 //purpose : Creates quadratic or linear quadrangle
1285 //=======================================================================
1287 SMDS_MeshFace* SMESH_MesherHelper::AddFace(const SMDS_MeshNode* n1,
1288 const SMDS_MeshNode* n2,
1289 const SMDS_MeshNode* n3,
1290 const SMDS_MeshNode* n4,
1294 SMESHDS_Mesh * meshDS = GetMeshDS();
1295 SMDS_MeshFace* elem = 0;
1298 return AddFace(n1,n3,n4,id,force3d);
1301 return AddFace(n1,n2,n4,id,force3d);
1304 return AddFace(n1,n2,n3,id,force3d);
1307 return AddFace(n1,n2,n4,id,force3d);
1310 return AddFace(n1,n2,n3,id,force3d);
1313 return AddFace(n1,n2,n3,id,force3d);
1316 if(!myCreateQuadratic) {
1318 elem = meshDS->AddFaceWithID(n1, n2, n3, n4, id);
1320 elem = meshDS->AddFace(n1, n2, n3, n4);
1323 const SMDS_MeshNode* n12 = GetMediumNode(n1,n2,force3d);
1324 const SMDS_MeshNode* n23 = GetMediumNode(n2,n3,force3d);
1325 const SMDS_MeshNode* n34 = GetMediumNode(n3,n4,force3d);
1326 const SMDS_MeshNode* n41 = GetMediumNode(n4,n1,force3d);
1329 elem = meshDS->AddFaceWithID(n1, n2, n3, n4, n12, n23, n34, n41, id);
1331 elem = meshDS->AddFace(n1, n2, n3, n4, n12, n23, n34, n41);
1333 if ( mySetElemOnShape && myShapeID > 0 )
1334 meshDS->SetMeshElementOnShape( elem, myShapeID );
1339 //=======================================================================
1340 //function : AddPolygonalFace
1341 //purpose : Creates polygon, with additional nodes in quadratic mesh
1342 //=======================================================================
1344 SMDS_MeshFace* SMESH_MesherHelper::AddPolygonalFace (const vector<const SMDS_MeshNode*>& nodes,
1348 SMESHDS_Mesh * meshDS = GetMeshDS();
1349 SMDS_MeshFace* elem = 0;
1351 if(!myCreateQuadratic) {
1353 elem = meshDS->AddPolygonalFaceWithID(nodes, id);
1355 elem = meshDS->AddPolygonalFace(nodes);
1358 vector<const SMDS_MeshNode*> newNodes;
1359 for ( int i = 0; i < nodes.size(); ++i )
1361 const SMDS_MeshNode* n1 = nodes[i];
1362 const SMDS_MeshNode* n2 = nodes[(i+1)%nodes.size()];
1363 const SMDS_MeshNode* n12 = GetMediumNode(n1,n2,force3d);
1364 newNodes.push_back( n1 );
1365 newNodes.push_back( n12 );
1368 elem = meshDS->AddPolygonalFaceWithID(newNodes, id);
1370 elem = meshDS->AddPolygonalFace(newNodes);
1372 if ( mySetElemOnShape && myShapeID > 0 )
1373 meshDS->SetMeshElementOnShape( elem, myShapeID );
1378 //=======================================================================
1379 //function : AddVolume
1380 //purpose : Creates quadratic or linear prism
1381 //=======================================================================
1383 SMDS_MeshVolume* SMESH_MesherHelper::AddVolume(const SMDS_MeshNode* n1,
1384 const SMDS_MeshNode* n2,
1385 const SMDS_MeshNode* n3,
1386 const SMDS_MeshNode* n4,
1387 const SMDS_MeshNode* n5,
1388 const SMDS_MeshNode* n6,
1392 SMESHDS_Mesh * meshDS = GetMeshDS();
1393 SMDS_MeshVolume* elem = 0;
1394 if(!myCreateQuadratic) {
1396 elem = meshDS->AddVolumeWithID(n1, n2, n3, n4, n5, n6, id);
1398 elem = meshDS->AddVolume(n1, n2, n3, n4, n5, n6);
1401 const SMDS_MeshNode* n12 = GetMediumNode(n1,n2,force3d);
1402 const SMDS_MeshNode* n23 = GetMediumNode(n2,n3,force3d);
1403 const SMDS_MeshNode* n31 = GetMediumNode(n3,n1,force3d);
1405 const SMDS_MeshNode* n45 = GetMediumNode(n4,n5,force3d);
1406 const SMDS_MeshNode* n56 = GetMediumNode(n5,n6,force3d);
1407 const SMDS_MeshNode* n64 = GetMediumNode(n6,n4,force3d);
1409 const SMDS_MeshNode* n14 = GetMediumNode(n1,n4,force3d);
1410 const SMDS_MeshNode* n25 = GetMediumNode(n2,n5,force3d);
1411 const SMDS_MeshNode* n36 = GetMediumNode(n3,n6,force3d);
1414 elem = meshDS->AddVolumeWithID(n1, n2, n3, n4, n5, n6,
1415 n12, n23, n31, n45, n56, n64, n14, n25, n36, id);
1417 elem = meshDS->AddVolume(n1, n2, n3, n4, n5, n6,
1418 n12, n23, n31, n45, n56, n64, n14, n25, n36);
1420 if ( mySetElemOnShape && myShapeID > 0 )
1421 meshDS->SetMeshElementOnShape( elem, myShapeID );
1426 //=======================================================================
1427 //function : AddVolume
1428 //purpose : Creates quadratic or linear tetrahedron
1429 //=======================================================================
1431 SMDS_MeshVolume* SMESH_MesherHelper::AddVolume(const SMDS_MeshNode* n1,
1432 const SMDS_MeshNode* n2,
1433 const SMDS_MeshNode* n3,
1434 const SMDS_MeshNode* n4,
1438 SMESHDS_Mesh * meshDS = GetMeshDS();
1439 SMDS_MeshVolume* elem = 0;
1440 if(!myCreateQuadratic) {
1442 elem = meshDS->AddVolumeWithID(n1, n2, n3, n4, id);
1444 elem = meshDS->AddVolume(n1, n2, n3, n4);
1447 const SMDS_MeshNode* n12 = GetMediumNode(n1,n2,force3d);
1448 const SMDS_MeshNode* n23 = GetMediumNode(n2,n3,force3d);
1449 const SMDS_MeshNode* n31 = GetMediumNode(n3,n1,force3d);
1451 const SMDS_MeshNode* n14 = GetMediumNode(n1,n4,force3d);
1452 const SMDS_MeshNode* n24 = GetMediumNode(n2,n4,force3d);
1453 const SMDS_MeshNode* n34 = GetMediumNode(n3,n4,force3d);
1456 elem = meshDS->AddVolumeWithID(n1, n2, n3, n4, n12, n23, n31, n14, n24, n34, id);
1458 elem = meshDS->AddVolume(n1, n2, n3, n4, n12, n23, n31, n14, n24, n34);
1460 if ( mySetElemOnShape && myShapeID > 0 )
1461 meshDS->SetMeshElementOnShape( elem, myShapeID );
1466 //=======================================================================
1467 //function : AddVolume
1468 //purpose : Creates quadratic or linear pyramid
1469 //=======================================================================
1471 SMDS_MeshVolume* SMESH_MesherHelper::AddVolume(const SMDS_MeshNode* n1,
1472 const SMDS_MeshNode* n2,
1473 const SMDS_MeshNode* n3,
1474 const SMDS_MeshNode* n4,
1475 const SMDS_MeshNode* n5,
1479 SMDS_MeshVolume* elem = 0;
1480 if(!myCreateQuadratic) {
1482 elem = GetMeshDS()->AddVolumeWithID(n1, n2, n3, n4, n5, id);
1484 elem = GetMeshDS()->AddVolume(n1, n2, n3, n4, n5);
1487 const SMDS_MeshNode* n12 = GetMediumNode(n1,n2,force3d);
1488 const SMDS_MeshNode* n23 = GetMediumNode(n2,n3,force3d);
1489 const SMDS_MeshNode* n34 = GetMediumNode(n3,n4,force3d);
1490 const SMDS_MeshNode* n41 = GetMediumNode(n4,n1,force3d);
1492 const SMDS_MeshNode* n15 = GetMediumNode(n1,n5,force3d);
1493 const SMDS_MeshNode* n25 = GetMediumNode(n2,n5,force3d);
1494 const SMDS_MeshNode* n35 = GetMediumNode(n3,n5,force3d);
1495 const SMDS_MeshNode* n45 = GetMediumNode(n4,n5,force3d);
1498 elem = GetMeshDS()->AddVolumeWithID ( n1, n2, n3, n4, n5,
1503 elem = GetMeshDS()->AddVolume( n1, n2, n3, n4, n5,
1505 n15, n25, n35, n45);
1507 if ( mySetElemOnShape && myShapeID > 0 )
1508 GetMeshDS()->SetMeshElementOnShape( elem, myShapeID );
1513 //=======================================================================
1514 //function : AddVolume
1515 //purpose : Creates quadratic or linear hexahedron
1516 //=======================================================================
1518 SMDS_MeshVolume* SMESH_MesherHelper::AddVolume(const SMDS_MeshNode* n1,
1519 const SMDS_MeshNode* n2,
1520 const SMDS_MeshNode* n3,
1521 const SMDS_MeshNode* n4,
1522 const SMDS_MeshNode* n5,
1523 const SMDS_MeshNode* n6,
1524 const SMDS_MeshNode* n7,
1525 const SMDS_MeshNode* n8,
1529 SMESHDS_Mesh * meshDS = GetMeshDS();
1530 SMDS_MeshVolume* elem = 0;
1531 if(!myCreateQuadratic) {
1533 elem = meshDS->AddVolumeWithID(n1, n2, n3, n4, n5, n6, n7, n8, id);
1535 elem = meshDS->AddVolume(n1, n2, n3, n4, n5, n6, n7, n8);
1538 const SMDS_MeshNode* n12 = GetMediumNode(n1,n2,force3d);
1539 const SMDS_MeshNode* n23 = GetMediumNode(n2,n3,force3d);
1540 const SMDS_MeshNode* n34 = GetMediumNode(n3,n4,force3d);
1541 const SMDS_MeshNode* n41 = GetMediumNode(n4,n1,force3d);
1543 const SMDS_MeshNode* n56 = GetMediumNode(n5,n6,force3d);
1544 const SMDS_MeshNode* n67 = GetMediumNode(n6,n7,force3d);
1545 const SMDS_MeshNode* n78 = GetMediumNode(n7,n8,force3d);
1546 const SMDS_MeshNode* n85 = GetMediumNode(n8,n5,force3d);
1548 const SMDS_MeshNode* n15 = GetMediumNode(n1,n5,force3d);
1549 const SMDS_MeshNode* n26 = GetMediumNode(n2,n6,force3d);
1550 const SMDS_MeshNode* n37 = GetMediumNode(n3,n7,force3d);
1551 const SMDS_MeshNode* n48 = GetMediumNode(n4,n8,force3d);
1554 elem = meshDS->AddVolumeWithID(n1, n2, n3, n4, n5, n6, n7, n8,
1555 n12, n23, n34, n41, n56, n67,
1556 n78, n85, n15, n26, n37, n48, id);
1558 elem = meshDS->AddVolume(n1, n2, n3, n4, n5, n6, n7, n8,
1559 n12, n23, n34, n41, n56, n67,
1560 n78, n85, n15, n26, n37, n48);
1562 if ( mySetElemOnShape && myShapeID > 0 )
1563 meshDS->SetMeshElementOnShape( elem, myShapeID );
1568 //=======================================================================
1569 //function : AddPolyhedralVolume
1570 //purpose : Creates polyhedron. In quadratic mesh, adds medium nodes
1571 //=======================================================================
1574 SMESH_MesherHelper::AddPolyhedralVolume (const std::vector<const SMDS_MeshNode*>& nodes,
1575 const std::vector<int>& quantities,
1579 SMESHDS_Mesh * meshDS = GetMeshDS();
1580 SMDS_MeshVolume* elem = 0;
1581 if(!myCreateQuadratic)
1584 elem = meshDS->AddPolyhedralVolumeWithID(nodes, quantities, id);
1586 elem = meshDS->AddPolyhedralVolume(nodes, quantities);
1590 vector<const SMDS_MeshNode*> newNodes;
1591 vector<int> newQuantities;
1592 for ( int iFace=0, iN=0; iFace < quantities.size(); ++iFace)
1594 int nbNodesInFace = quantities[iFace];
1595 newQuantities.push_back(0);
1596 for ( int i = 0; i < nbNodesInFace; ++i )
1598 const SMDS_MeshNode* n1 = nodes[ iN + i ];
1599 newNodes.push_back( n1 );
1600 newQuantities.back()++;
1602 const SMDS_MeshNode* n2 = nodes[ iN + ( i+1==nbNodesInFace ? 0 : i+1 )];
1603 // if ( n1->GetPosition()->GetTypeOfPosition() != SMDS_TOP_3DSPACE &&
1604 // n2->GetPosition()->GetTypeOfPosition() != SMDS_TOP_3DSPACE )
1606 const SMDS_MeshNode* n12 = GetMediumNode(n1,n2,force3d);
1607 newNodes.push_back( n12 );
1608 newQuantities.back()++;
1611 iN += nbNodesInFace;
1614 elem = meshDS->AddPolyhedralVolumeWithID( newNodes, newQuantities, id );
1616 elem = meshDS->AddPolyhedralVolume( newNodes, newQuantities );
1618 if ( mySetElemOnShape && myShapeID > 0 )
1619 meshDS->SetMeshElementOnShape( elem, myShapeID );
1624 //=======================================================================
1625 //function : LoadNodeColumns
1626 //purpose : Load nodes bound to face into a map of node columns
1627 //=======================================================================
1629 bool SMESH_MesherHelper::LoadNodeColumns(TParam2ColumnMap & theParam2ColumnMap,
1630 const TopoDS_Face& theFace,
1631 const TopoDS_Edge& theBaseEdge,
1632 SMESHDS_Mesh* theMesh,
1633 SMESH_ProxyMesh* theProxyMesh)
1635 return LoadNodeColumns(theParam2ColumnMap,
1637 std::list<TopoDS_Edge>(1,theBaseEdge),
1642 //=======================================================================
1643 //function : LoadNodeColumns
1644 //purpose : Load nodes bound to face into a map of node columns
1645 //=======================================================================
1647 bool SMESH_MesherHelper::LoadNodeColumns(TParam2ColumnMap & theParam2ColumnMap,
1648 const TopoDS_Face& theFace,
1649 const std::list<TopoDS_Edge>& theBaseSide,
1650 SMESHDS_Mesh* theMesh,
1651 SMESH_ProxyMesh* theProxyMesh)
1653 // get a right submesh of theFace
1655 const SMESHDS_SubMesh* faceSubMesh = 0;
1658 faceSubMesh = theProxyMesh->GetSubMesh( theFace );
1659 if ( !faceSubMesh ||
1660 faceSubMesh->NbElements() == 0 ||
1661 theProxyMesh->IsTemporary( faceSubMesh->GetElements()->next() ))
1663 // can use a proxy sub-mesh with not temporary elements only
1669 faceSubMesh = theMesh->MeshElements( theFace );
1670 if ( !faceSubMesh || faceSubMesh->NbElements() == 0 )
1673 // get data of edges for normalization of params
1675 vector< double > length;
1677 list<TopoDS_Edge>::const_iterator edge;
1679 for ( edge = theBaseSide.begin(); edge != theBaseSide.end(); ++edge )
1681 double len = std::max( 1e-10, SMESH_Algo::EdgeLength( *edge ));
1683 length.push_back( len );
1687 // get nodes on theBaseEdge sorted by param on edge and initialize theParam2ColumnMap with them
1688 edge = theBaseSide.begin();
1689 for ( int iE = 0; edge != theBaseSide.end(); ++edge, ++iE )
1691 map< double, const SMDS_MeshNode*> sortedBaseNodes;
1692 SMESH_Algo::GetSortedNodesOnEdge( theMesh, *edge,/*noMedium=*/true, sortedBaseNodes);
1693 if ( sortedBaseNodes.empty() ) continue;
1696 BRep_Tool::Range( *edge, f, l );
1697 if ( edge->Orientation() == TopAbs_REVERSED ) std::swap( f, l );
1698 const double coeff = 1. / ( l - f ) * length[iE] / fullLen;
1699 const double prevPar = theParam2ColumnMap.empty() ? 0 : theParam2ColumnMap.rbegin()->first;
1700 map< double, const SMDS_MeshNode*>::iterator u_n = sortedBaseNodes.begin();
1701 for ( ; u_n != sortedBaseNodes.end(); u_n++ )
1703 double par = prevPar + coeff * ( u_n->first - f );
1704 TParam2ColumnMap::iterator u2nn =
1705 theParam2ColumnMap.insert( theParam2ColumnMap.end(), make_pair( par, TNodeColumn()));
1706 u2nn->second.push_back( u_n->second );
1709 TParam2ColumnMap::iterator par_nVec_2, par_nVec_1 = theParam2ColumnMap.begin();
1712 for ( ; par_nVec_1 != theParam2ColumnMap.end(); ++par_nVec_1 )
1714 const SMDS_MeshNode* & n = par_nVec_1->second[0];
1715 n = theProxyMesh->GetProxyNode( n );
1719 int nbRows = 1 + faceSubMesh->NbElements() / ( theParam2ColumnMap.size()-1 );
1721 // fill theParam2ColumnMap column by column by passing from nodes on
1722 // theBaseEdge up via mesh faces on theFace
1724 par_nVec_2 = theParam2ColumnMap.begin();
1725 par_nVec_1 = par_nVec_2++;
1726 TIDSortedElemSet emptySet, avoidSet;
1727 for ( ; par_nVec_2 != theParam2ColumnMap.end(); ++par_nVec_1, ++par_nVec_2 )
1729 vector<const SMDS_MeshNode*>& nCol1 = par_nVec_1->second;
1730 vector<const SMDS_MeshNode*>& nCol2 = par_nVec_2->second;
1731 nCol1.resize( nbRows );
1732 nCol2.resize( nbRows );
1734 int i1, i2, iRow = 0;
1735 const SMDS_MeshNode *n1 = nCol1[0], *n2 = nCol2[0];
1736 // find face sharing node n1 and n2 and belonging to faceSubMesh
1737 while ( const SMDS_MeshElement* face =
1738 SMESH_MeshEditor::FindFaceInSet( n1, n2, emptySet, avoidSet, &i1, &i2))
1740 if ( faceSubMesh->Contains( face ))
1742 int nbNodes = face->IsQuadratic() ? face->NbNodes()/2 : face->NbNodes();
1745 n1 = face->GetNode( (i2+2) % 4 ); // opposite corner of quadrangle face
1746 n2 = face->GetNode( (i1+2) % 4 );
1747 if ( ++iRow >= nbRows )
1753 avoidSet.insert( face );
1755 // set a real height
1756 nCol1.resize( iRow + 1 );
1757 nCol2.resize( iRow + 1 );
1759 return theParam2ColumnMap.size() > 1 && theParam2ColumnMap.begin()->second.size() > 1;
1762 //=======================================================================
1763 //function : NbAncestors
1764 //purpose : Return number of unique ancestors of the shape
1765 //=======================================================================
1767 int SMESH_MesherHelper::NbAncestors(const TopoDS_Shape& shape,
1768 const SMESH_Mesh& mesh,
1769 TopAbs_ShapeEnum ancestorType/*=TopAbs_SHAPE*/)
1771 TopTools_MapOfShape ancestors;
1772 TopTools_ListIteratorOfListOfShape ansIt( mesh.GetAncestors(shape) );
1773 for ( ; ansIt.More(); ansIt.Next() ) {
1774 if ( ancestorType == TopAbs_SHAPE || ansIt.Value().ShapeType() == ancestorType )
1775 ancestors.Add( ansIt.Value() );
1777 return ancestors.Extent();
1780 //=======================================================================
1781 //function : GetSubShapeOri
1782 //purpose : Return orientation of sub-shape in the main shape
1783 //=======================================================================
1785 TopAbs_Orientation SMESH_MesherHelper::GetSubShapeOri(const TopoDS_Shape& shape,
1786 const TopoDS_Shape& subShape)
1788 TopAbs_Orientation ori = TopAbs_Orientation(-1);
1789 if ( !shape.IsNull() && !subShape.IsNull() )
1791 TopExp_Explorer e( shape, subShape.ShapeType() );
1792 if ( shape.Orientation() >= TopAbs_INTERNAL ) // TopAbs_INTERNAL or TopAbs_EXTERNAL
1793 e.Init( shape.Oriented(TopAbs_FORWARD), subShape.ShapeType() );
1794 for ( ; e.More(); e.Next())
1795 if ( subShape.IsSame( e.Current() ))
1798 ori = e.Current().Orientation();
1803 //=======================================================================
1804 //function : IsSubShape
1806 //=======================================================================
1808 bool SMESH_MesherHelper::IsSubShape( const TopoDS_Shape& shape,
1809 const TopoDS_Shape& mainShape )
1811 if ( !shape.IsNull() && !mainShape.IsNull() )
1813 for ( TopExp_Explorer exp( mainShape, shape.ShapeType());
1816 if ( shape.IsSame( exp.Current() ))
1819 SCRUTE((shape.IsNull()));
1820 SCRUTE((mainShape.IsNull()));
1824 //=======================================================================
1825 //function : IsSubShape
1827 //=======================================================================
1829 bool SMESH_MesherHelper::IsSubShape( const TopoDS_Shape& shape, SMESH_Mesh* aMesh )
1831 if ( shape.IsNull() || !aMesh )
1834 aMesh->GetMeshDS()->ShapeToIndex( shape ) ||
1836 (shape.ShapeType() == TopAbs_COMPOUND && aMesh->GetMeshDS()->IsGroupOfSubShapes( shape ));
1839 //================================================================================
1841 * \brief Return maximal tolerance of shape
1843 //================================================================================
1845 double SMESH_MesherHelper::MaxTolerance( const TopoDS_Shape& shape )
1847 double tol = Precision::Confusion();
1848 TopExp_Explorer exp;
1849 for ( exp.Init( shape, TopAbs_FACE ); exp.More(); exp.Next() )
1850 tol = Max( tol, BRep_Tool::Tolerance( TopoDS::Face( exp.Current())));
1851 for ( exp.Init( shape, TopAbs_EDGE ); exp.More(); exp.Next() )
1852 tol = Max( tol, BRep_Tool::Tolerance( TopoDS::Edge( exp.Current())));
1853 for ( exp.Init( shape, TopAbs_VERTEX ); exp.More(); exp.Next() )
1854 tol = Max( tol, BRep_Tool::Tolerance( TopoDS::Vertex( exp.Current())));
1859 //================================================================================
1861 * \brief Check if the first and last vertices of an edge are the same
1862 * \param anEdge - the edge to check
1863 * \retval bool - true if same
1865 //================================================================================
1867 bool SMESH_MesherHelper::IsClosedEdge( const TopoDS_Edge& anEdge )
1869 if ( anEdge.Orientation() >= TopAbs_INTERNAL )
1870 return IsClosedEdge( TopoDS::Edge( anEdge.Oriented( TopAbs_FORWARD )));
1871 return TopExp::FirstVertex( anEdge ).IsSame( TopExp::LastVertex( anEdge ));
1874 //================================================================================
1876 * \brief Wrapper over TopExp::FirstVertex() and TopExp::LastVertex() fixing them
1877 * in the case of INTERNAL edge
1879 //================================================================================
1881 TopoDS_Vertex SMESH_MesherHelper::IthVertex( const bool is2nd,
1885 if ( anEdge.Orientation() >= TopAbs_INTERNAL )
1886 anEdge.Orientation( TopAbs_FORWARD );
1888 const TopAbs_Orientation tgtOri = is2nd ? TopAbs_REVERSED : TopAbs_FORWARD;
1889 TopoDS_Iterator vIt( anEdge, CumOri );
1890 while ( vIt.More() && vIt.Value().Orientation() != tgtOri )
1893 return ( vIt.More() ? TopoDS::Vertex(vIt.Value()) : TopoDS_Vertex() );
1896 //=======================================================================
1897 //function : IsQuadraticMesh
1898 //purpose : Check mesh without geometry for: if all elements on this shape are quadratic,
1899 // quadratic elements will be created.
1900 // Used then generated 3D mesh without geometry.
1901 //=======================================================================
1903 SMESH_MesherHelper:: MType SMESH_MesherHelper::IsQuadraticMesh()
1905 int NbAllEdgsAndFaces=0;
1906 int NbQuadFacesAndEdgs=0;
1907 int NbFacesAndEdges=0;
1908 //All faces and edges
1909 NbAllEdgsAndFaces = myMesh->NbEdges() + myMesh->NbFaces();
1911 //Quadratic faces and edges
1912 NbQuadFacesAndEdgs = myMesh->NbEdges(ORDER_QUADRATIC) + myMesh->NbFaces(ORDER_QUADRATIC);
1914 //Linear faces and edges
1915 NbFacesAndEdges = myMesh->NbEdges(ORDER_LINEAR) + myMesh->NbFaces(ORDER_LINEAR);
1917 if (NbAllEdgsAndFaces == NbQuadFacesAndEdgs) {
1919 return SMESH_MesherHelper::QUADRATIC;
1921 else if (NbAllEdgsAndFaces == NbFacesAndEdges) {
1923 return SMESH_MesherHelper::LINEAR;
1926 //Mesh with both type of elements
1927 return SMESH_MesherHelper::COMP;
1930 //=======================================================================
1931 //function : GetOtherParam
1932 //purpose : Return an alternative parameter for a node on seam
1933 //=======================================================================
1935 double SMESH_MesherHelper::GetOtherParam(const double param) const
1937 int i = myParIndex & U_periodic ? 0 : 1;
1938 return fabs(param-myPar1[i]) < fabs(param-myPar2[i]) ? myPar2[i] : myPar1[i];
1943 //=======================================================================
1945 * \brief Iterator on ancestors of the given type
1947 //=======================================================================
1949 struct TAncestorsIterator : public SMDS_Iterator<const TopoDS_Shape*>
1951 TopTools_ListIteratorOfListOfShape _ancIter;
1952 TopAbs_ShapeEnum _type;
1953 TopTools_MapOfShape _encountered;
1954 TAncestorsIterator( const TopTools_ListOfShape& ancestors, TopAbs_ShapeEnum type)
1955 : _ancIter( ancestors ), _type( type )
1957 if ( _ancIter.More() ) {
1958 if ( _ancIter.Value().ShapeType() != _type ) next();
1959 else _encountered.Add( _ancIter.Value() );
1964 return _ancIter.More();
1966 virtual const TopoDS_Shape* next()
1968 const TopoDS_Shape* s = _ancIter.More() ? & _ancIter.Value() : 0;
1969 if ( _ancIter.More() )
1970 for ( _ancIter.Next(); _ancIter.More(); _ancIter.Next())
1971 if ( _ancIter.Value().ShapeType() == _type && _encountered.Add( _ancIter.Value() ))
1979 //=======================================================================
1981 * \brief Return iterator on ancestors of the given type
1983 //=======================================================================
1985 PShapeIteratorPtr SMESH_MesherHelper::GetAncestors(const TopoDS_Shape& shape,
1986 const SMESH_Mesh& mesh,
1987 TopAbs_ShapeEnum ancestorType)
1989 return PShapeIteratorPtr( new TAncestorsIterator( mesh.GetAncestors(shape), ancestorType));
1992 //=======================================================================
1993 //function : GetCommonAncestor
1994 //purpose : Find a common ancestors of two shapes of the given type
1995 //=======================================================================
1997 TopoDS_Shape SMESH_MesherHelper::GetCommonAncestor(const TopoDS_Shape& shape1,
1998 const TopoDS_Shape& shape2,
1999 const SMESH_Mesh& mesh,
2000 TopAbs_ShapeEnum ancestorType)
2002 TopoDS_Shape commonAnc;
2003 if ( !shape1.IsNull() && !shape2.IsNull() )
2005 PShapeIteratorPtr ancIt = GetAncestors( shape1, mesh, ancestorType );
2006 while ( const TopoDS_Shape* anc = ancIt->next() )
2007 if ( IsSubShape( shape2, *anc ))
2016 //#include <Perf_Meter.hxx>
2018 //=======================================================================
2019 namespace { // Structures used by FixQuadraticElements()
2020 //=======================================================================
2022 #define __DMP__(txt) \
2024 #define MSG(txt) __DMP__(txt<<endl)
2025 #define MSGBEG(txt) __DMP__(txt)
2027 //const double straightTol2 = 1e-33; // to detect straing links
2028 bool isStraightLink(double linkLen2, double middleNodeMove2)
2030 // straight if <node move> < 1/15 * <link length>
2031 return middleNodeMove2 < 1/15./15. * linkLen2;
2035 // ---------------------------------------
2037 * \brief Quadratic link knowing its faces
2039 struct QLink: public SMESH_TLink
2041 const SMDS_MeshNode* _mediumNode;
2042 mutable vector<const QFace* > _faces;
2043 mutable gp_Vec _nodeMove;
2044 mutable int _nbMoves;
2046 QLink(const SMDS_MeshNode* n1, const SMDS_MeshNode* n2, const SMDS_MeshNode* nm):
2047 SMESH_TLink( n1,n2 ), _mediumNode(nm), _nodeMove(0,0,0), _nbMoves(0) {
2049 //if ( MediumPos() != SMDS_TOP_3DSPACE )
2050 _nodeMove = MediumPnt() - MiddlePnt();
2052 void SetContinuesFaces() const;
2053 const QFace* GetContinuesFace( const QFace* face ) const;
2054 bool OnBoundary() const;
2055 gp_XYZ MiddlePnt() const { return ( XYZ( node1() ) + XYZ( node2() )) / 2.; }
2056 gp_XYZ MediumPnt() const { return XYZ( _mediumNode ); }
2058 SMDS_TypeOfPosition MediumPos() const
2059 { return _mediumNode->GetPosition()->GetTypeOfPosition(); }
2060 SMDS_TypeOfPosition EndPos(bool isSecond) const
2061 { return (isSecond ? node2() : node1())->GetPosition()->GetTypeOfPosition(); }
2062 const SMDS_MeshNode* EndPosNode(SMDS_TypeOfPosition pos) const
2063 { return EndPos(0) == pos ? node1() : EndPos(1) == pos ? node2() : 0; }
2065 void Move(const gp_Vec& move, bool sum=false) const
2066 { _nodeMove += move; _nbMoves += sum ? (_nbMoves==0) : 1; }
2067 gp_XYZ Move() const { return _nodeMove.XYZ() / _nbMoves; }
2068 bool IsMoved() const { return (_nbMoves > 0 /*&& !IsStraight()*/); }
2069 bool IsStraight() const
2070 { return isStraightLink( (XYZ(node1())-XYZ(node2())).SquareModulus(),
2071 _nodeMove.SquareMagnitude());
2073 bool operator<(const QLink& other) const {
2074 return (node1()->GetID() == other.node1()->GetID() ?
2075 node2()->GetID() < other.node2()->GetID() :
2076 node1()->GetID() < other.node1()->GetID());
2078 // struct PtrComparator {
2079 // bool operator() (const QLink* l1, const QLink* l2 ) const { return *l1 < *l2; }
2082 // ---------------------------------------------------------
2084 * \brief Link in the chain of links; it connects two faces
2088 const QLink* _qlink;
2089 mutable const QFace* _qfaces[2];
2091 TChainLink(const QLink* qlink=0):_qlink(qlink) {
2092 _qfaces[0] = _qfaces[1] = 0;
2094 void SetFace(const QFace* face) const { int iF = _qfaces[0] ? 1 : 0; _qfaces[iF]=face; }
2096 bool IsBoundary() const { return !_qfaces[1]; }
2098 void RemoveFace( const QFace* face ) const
2099 { _qfaces[(face == _qfaces[1])] = 0; if (!_qfaces[0]) std::swap(_qfaces[0],_qfaces[1]); }
2101 const QFace* NextFace( const QFace* f ) const
2102 { return _qfaces[0]==f ? _qfaces[1] : _qfaces[0]; }
2104 const SMDS_MeshNode* NextNode( const SMDS_MeshNode* n ) const
2105 { return n == _qlink->node1() ? _qlink->node2() : _qlink->node1(); }
2107 bool operator<(const TChainLink& other) const { return *_qlink < *other._qlink; }
2109 operator bool() const { return (_qlink); }
2111 const QLink* operator->() const { return _qlink; }
2113 gp_Vec Normal() const;
2115 bool IsStraight() const;
2117 // --------------------------------------------------------------------
2118 typedef list< TChainLink > TChain;
2119 typedef set < TChainLink > TLinkSet;
2120 typedef TLinkSet::const_iterator TLinkInSet;
2122 const int theFirstStep = 5;
2124 enum { ERR_OK, ERR_TRI, ERR_PRISM, ERR_UNKNOWN }; // errors of QFace::GetLinkChain()
2125 // --------------------------------------------------------------------
2127 * \brief Face shared by two volumes and bound by QLinks
2129 struct QFace: public TIDSortedNodeSet
2131 mutable const SMDS_MeshElement* _volumes[2];
2132 mutable vector< const QLink* > _sides;
2133 mutable bool _sideIsAdded[4]; // added in chain of links
2136 mutable const SMDS_MeshElement* _face;
2139 QFace( const vector< const QLink*>& links, const SMDS_MeshElement* face=0 );
2141 void SetVolume(const SMDS_MeshElement* v) const { _volumes[ _volumes[0] ? 1 : 0 ] = v; }
2143 int NbVolumes() const { return !_volumes[0] ? 0 : !_volumes[1] ? 1 : 2; }
2145 void AddSelfToLinks() const {
2146 for ( int i = 0; i < _sides.size(); ++i )
2147 _sides[i]->_faces.push_back( this );
2149 int LinkIndex( const QLink* side ) const {
2150 for (int i=0; i<_sides.size(); ++i ) if ( _sides[i] == side ) return i;
2153 bool GetLinkChain( int iSide, TChain& chain, SMDS_TypeOfPosition pos, int& err) const;
2155 bool GetLinkChain( TChainLink& link, TChain& chain, SMDS_TypeOfPosition pos, int& err) const
2157 int i = LinkIndex( link._qlink );
2158 if ( i < 0 ) return true;
2159 _sideIsAdded[i] = true;
2160 link.SetFace( this );
2161 // continue from opposite link
2162 return GetLinkChain( (i+2)%_sides.size(), chain, pos, err );
2164 bool IsBoundary() const { return !_volumes[1]; }
2166 bool Contains( const SMDS_MeshNode* node ) const { return count(node); }
2168 bool IsSpoiled(const QLink* bentLink ) const;
2170 TLinkInSet GetBoundaryLink( const TLinkSet& links,
2171 const TChainLink& avoidLink,
2172 TLinkInSet * notBoundaryLink = 0,
2173 const SMDS_MeshNode* nodeToContain = 0,
2174 bool * isAdjacentUsed = 0,
2175 int nbRecursionsLeft = -1) const;
2177 TLinkInSet GetLinkByNode( const TLinkSet& links,
2178 const TChainLink& avoidLink,
2179 const SMDS_MeshNode* nodeToContain) const;
2181 const SMDS_MeshNode* GetNodeInFace() const {
2182 for ( int iL = 0; iL < _sides.size(); ++iL )
2183 if ( _sides[iL]->MediumPos() == SMDS_TOP_FACE ) return _sides[iL]->_mediumNode;
2187 gp_Vec LinkNorm(const int i, SMESH_MesherHelper* theFaceHelper=0) const;
2189 double MoveByBoundary( const TChainLink& theLink,
2190 const gp_Vec& theRefVec,
2191 const TLinkSet& theLinks,
2192 SMESH_MesherHelper* theFaceHelper=0,
2193 const double thePrevLen=0,
2194 const int theStep=theFirstStep,
2195 gp_Vec* theLinkNorm=0,
2196 double theSign=1.0) const;
2199 //================================================================================
2201 * \brief Dump QLink and QFace
2203 ostream& operator << (ostream& out, const QLink& l)
2205 out <<"QLink nodes: "
2206 << l.node1()->GetID() << " - "
2207 << l._mediumNode->GetID() << " - "
2208 << l.node2()->GetID() << endl;
2211 ostream& operator << (ostream& out, const QFace& f)
2213 out <<"QFace nodes: "/*<< &f << " "*/;
2214 for ( TIDSortedNodeSet::const_iterator n = f.begin(); n != f.end(); ++n )
2215 out << (*n)->GetID() << " ";
2216 out << " \tvolumes: "
2217 << (f._volumes[0] ? f._volumes[0]->GetID() : 0) << " "
2218 << (f._volumes[1] ? f._volumes[1]->GetID() : 0);
2219 out << " \tNormal: "<< f._normal.X() <<", "<<f._normal.Y() <<", "<<f._normal.Z() << endl;
2223 //================================================================================
2225 * \brief Construct QFace from QLinks
2227 //================================================================================
2229 QFace::QFace( const vector< const QLink*>& links, const SMDS_MeshElement* face )
2231 _volumes[0] = _volumes[1] = 0;
2233 _sideIsAdded[0]=_sideIsAdded[1]=_sideIsAdded[2]=_sideIsAdded[3]=false;
2234 _normal.SetCoord(0,0,0);
2235 for ( int i = 1; i < _sides.size(); ++i ) {
2236 const QLink *l1 = _sides[i-1], *l2 = _sides[i];
2237 insert( l1->node1() ); insert( l1->node2() );
2239 gp_Vec v1( XYZ( l1->node2()), XYZ( l1->node1()));
2240 gp_Vec v2( XYZ( l2->node1()), XYZ( l2->node2()));
2241 if ( l1->node1() != l2->node1() && l1->node2() != l2->node2() )
2245 double normSqSize = _normal.SquareMagnitude();
2246 if ( normSqSize > numeric_limits<double>::min() )
2247 _normal /= sqrt( normSqSize );
2249 _normal.SetCoord(1e-33,0,0);
2255 //================================================================================
2257 * \brief Make up a chain of links
2258 * \param iSide - link to add first
2259 * \param chain - chain to fill in
2260 * \param pos - postion of medium nodes the links should have
2261 * \param error - out, specifies what is wrong
2262 * \retval bool - false if valid chain can't be built; "valid" means that links
2263 * of the chain belongs to rectangles bounding hexahedrons
2265 //================================================================================
2267 bool QFace::GetLinkChain( int iSide, TChain& chain, SMDS_TypeOfPosition pos, int& error) const
2269 if ( iSide >= _sides.size() ) // wrong argument iSide
2271 if ( _sideIsAdded[ iSide ]) // already in chain
2274 if ( _sides.size() != 4 ) { // triangle - visit all my continous faces
2277 list< const QFace* > faces( 1, this );
2278 while ( !faces.empty() ) {
2279 const QFace* face = faces.front();
2280 for ( int i = 0; i < face->_sides.size(); ++i ) {
2281 if ( !face->_sideIsAdded[i] && face->_sides[i] ) {
2282 face->_sideIsAdded[i] = true;
2283 // find a face side in the chain
2284 TLinkInSet chLink = links.insert( TChainLink(face->_sides[i])).first;
2285 // TChain::iterator chLink = chain.begin();
2286 // for ( ; chLink != chain.end(); ++chLink )
2287 // if ( chLink->_qlink == face->_sides[i] )
2289 // if ( chLink == chain.end() )
2290 // chLink = chain.insert( chain.begin(), TChainLink(face->_sides[i]));
2291 // add a face to a chained link and put a continues face in the queue
2292 chLink->SetFace( face );
2293 if ( face->_sides[i]->MediumPos() == pos )
2294 if ( const QFace* contFace = face->_sides[i]->GetContinuesFace( face ))
2295 if ( contFace->_sides.size() == 3 )
2296 faces.push_back( contFace );
2301 if ( error < ERR_TRI )
2303 chain.insert( chain.end(), links.begin(),links.end() );
2306 _sideIsAdded[iSide] = true; // not to add this link to chain again
2307 const QLink* link = _sides[iSide];
2311 // add link into chain
2312 TChain::iterator chLink = chain.insert( chain.begin(), TChainLink(link));
2313 chLink->SetFace( this );
2316 // propagate from quadrangle to neighbour faces
2317 if ( link->MediumPos() >= pos ) {
2318 int nbLinkFaces = link->_faces.size();
2319 if ( nbLinkFaces == 4 || (/*nbLinkFaces < 4 && */link->OnBoundary())) {
2320 // hexahedral mesh or boundary quadrangles - goto a continous face
2321 if ( const QFace* f = link->GetContinuesFace( this ))
2322 if ( f->_sides.size() == 4 )
2323 return f->GetLinkChain( *chLink, chain, pos, error );
2326 TChainLink chLink(link); // side face of prismatic mesh - visit all faces of iSide
2327 for ( int i = 0; i < nbLinkFaces; ++i )
2328 if ( link->_faces[i] )
2329 link->_faces[i]->GetLinkChain( chLink, chain, pos, error );
2330 if ( error < ERR_PRISM )
2338 //================================================================================
2340 * \brief Return a boundary link of the triangle face
2341 * \param links - set of all links
2342 * \param avoidLink - link not to return
2343 * \param notBoundaryLink - out, neither the returned link nor avoidLink
2344 * \param nodeToContain - node the returned link must contain; if provided, search
2345 * also performed on adjacent faces
2346 * \param isAdjacentUsed - returns true if link is found in adjacent faces
2347 * \param nbRecursionsLeft - to limit recursion
2349 //================================================================================
2351 TLinkInSet QFace::GetBoundaryLink( const TLinkSet& links,
2352 const TChainLink& avoidLink,
2353 TLinkInSet * notBoundaryLink,
2354 const SMDS_MeshNode* nodeToContain,
2355 bool * isAdjacentUsed,
2356 int nbRecursionsLeft) const
2358 TLinkInSet linksEnd = links.end(), boundaryLink = linksEnd;
2360 typedef list< pair< const QFace*, TLinkInSet > > TFaceLinkList;
2361 TFaceLinkList adjacentFaces;
2363 for ( int iL = 0; iL < _sides.size(); ++iL )
2365 if ( avoidLink._qlink == _sides[iL] )
2367 TLinkInSet link = links.find( _sides[iL] );
2368 if ( link == linksEnd ) continue;
2369 if ( (*link)->MediumPos() > SMDS_TOP_FACE )
2370 continue; // We work on faces here, don't go inside a solid
2373 if ( link->IsBoundary() ) {
2374 if ( !nodeToContain ||
2375 (*link)->node1() == nodeToContain ||
2376 (*link)->node2() == nodeToContain )
2378 boundaryLink = link;
2379 if ( !notBoundaryLink ) break;
2382 else if ( notBoundaryLink ) {
2383 *notBoundaryLink = link;
2384 if ( boundaryLink != linksEnd ) break;
2387 if ( boundaryLink == linksEnd && nodeToContain ) // collect adjacent faces
2388 if ( const QFace* adj = link->NextFace( this ))
2389 if ( adj->Contains( nodeToContain ))
2390 adjacentFaces.push_back( make_pair( adj, link ));
2393 if ( isAdjacentUsed ) *isAdjacentUsed = false;
2394 if ( boundaryLink == linksEnd && nodeToContain && nbRecursionsLeft) // check adjacent faces
2396 if ( nbRecursionsLeft < 0 )
2397 nbRecursionsLeft = nodeToContain->NbInverseElements();
2398 TFaceLinkList::iterator adj = adjacentFaces.begin();
2399 for ( ; boundaryLink == linksEnd && adj != adjacentFaces.end(); ++adj )
2400 boundaryLink = adj->first->GetBoundaryLink( links, *(adj->second), 0, nodeToContain,
2401 isAdjacentUsed, nbRecursionsLeft-1);
2402 if ( isAdjacentUsed ) *isAdjacentUsed = true;
2404 return boundaryLink;
2406 //================================================================================
2408 * \brief Return a link ending at the given node but not avoidLink
2410 //================================================================================
2412 TLinkInSet QFace::GetLinkByNode( const TLinkSet& links,
2413 const TChainLink& avoidLink,
2414 const SMDS_MeshNode* nodeToContain) const
2416 for ( int i = 0; i < _sides.size(); ++i )
2417 if ( avoidLink._qlink != _sides[i] &&
2418 (_sides[i]->node1() == nodeToContain || _sides[i]->node2() == nodeToContain ))
2419 return links.find( _sides[ i ]);
2423 //================================================================================
2425 * \brief Return normal to the i-th side pointing outside the face
2427 //================================================================================
2429 gp_Vec QFace::LinkNorm(const int i, SMESH_MesherHelper* /*uvHelper*/) const
2431 gp_Vec norm, vecOut;
2432 // if ( uvHelper ) {
2433 // TopoDS_Face face = TopoDS::Face( uvHelper->GetSubShape());
2434 // const SMDS_MeshNode* inFaceNode = uvHelper->GetNodeUVneedInFaceNode() ? GetNodeInFace() : 0;
2435 // gp_XY uv1 = uvHelper->GetNodeUV( face, _sides[i]->node1(), inFaceNode );
2436 // gp_XY uv2 = uvHelper->GetNodeUV( face, _sides[i]->node2(), inFaceNode );
2437 // norm.SetCoord( uv1.Y() - uv2.Y(), uv2.X() - uv1.X(), 0 );
2439 // const QLink* otherLink = _sides[(i + 1) % _sides.size()];
2440 // const SMDS_MeshNode* otherNode =
2441 // otherLink->node1() == _sides[i]->node1() ? otherLink->node2() : otherLink->node1();
2442 // gp_XY pIn = uvHelper->GetNodeUV( face, otherNode, inFaceNode );
2443 // vecOut.SetCoord( uv1.X() - pIn.X(), uv1.Y() - pIn.Y(), 0 );
2446 norm = _normal ^ gp_Vec( XYZ(_sides[i]->node1()), XYZ(_sides[i]->node2()));
2447 gp_XYZ pIn = ( XYZ( _sides[0]->node1() ) +
2448 XYZ( _sides[0]->node2() ) +
2449 XYZ( _sides[1]->node1() )) / 3.;
2450 vecOut.SetXYZ( _sides[i]->MiddlePnt() - pIn );
2452 if ( norm * vecOut < 0 )
2454 double mag2 = norm.SquareMagnitude();
2455 if ( mag2 > numeric_limits<double>::min() )
2456 norm /= sqrt( mag2 );
2459 //================================================================================
2461 * \brief Move medium node of theLink according to its distance from boundary
2462 * \param theLink - link to fix
2463 * \param theRefVec - movement of boundary
2464 * \param theLinks - all adjacent links of continous triangles
2465 * \param theFaceHelper - helper is not used so far
2466 * \param thePrevLen - distance from the boundary
2467 * \param theStep - number of steps till movement propagation limit
2468 * \param theLinkNorm - out normal to theLink
2469 * \param theSign - 1 or -1 depending on movement of boundary
2470 * \retval double - distance from boundary to propagation limit or other boundary
2472 //================================================================================
2474 double QFace::MoveByBoundary( const TChainLink& theLink,
2475 const gp_Vec& theRefVec,
2476 const TLinkSet& theLinks,
2477 SMESH_MesherHelper* theFaceHelper,
2478 const double thePrevLen,
2480 gp_Vec* theLinkNorm,
2481 double theSign) const
2484 return thePrevLen; // propagation limit reached
2486 int iL; // index of theLink
2487 for ( iL = 0; iL < _sides.size(); ++iL )
2488 if ( theLink._qlink == _sides[ iL ])
2491 MSG(string(theStep,'.')<<" Ref( "<<theRefVec.X()<<","<<theRefVec.Y()<<","<<theRefVec.Z()<<" )"
2492 <<" thePrevLen " << thePrevLen);
2493 MSG(string(theStep,'.')<<" "<<*theLink._qlink);
2495 gp_Vec linkNorm = -LinkNorm( iL/*, theFaceHelper*/ ); // normal to theLink
2496 double refProj = theRefVec * linkNorm; // project movement vector to normal of theLink
2497 if ( theStep == theFirstStep )
2498 theSign = refProj < 0. ? -1. : 1.;
2499 else if ( theSign * refProj < 0.4 * theRefVec.Magnitude())
2500 return thePrevLen; // to propagate movement forward only, not in side dir or backward
2502 int iL1 = (iL + 1) % 3, iL2 = (iL + 2) % 3; // indices of the two other links of triangle
2503 TLinkInSet link1 = theLinks.find( _sides[iL1] );
2504 TLinkInSet link2 = theLinks.find( _sides[iL2] );
2505 if ( link1 == theLinks.end() || link2 == theLinks.end() )
2507 const QFace* f1 = link1->NextFace( this ); // adjacent faces
2508 const QFace* f2 = link2->NextFace( this );
2510 // propagate to adjacent faces till limit step or boundary
2511 double len1 = thePrevLen + (theLink->MiddlePnt() - _sides[iL1]->MiddlePnt()).Modulus();
2512 double len2 = thePrevLen + (theLink->MiddlePnt() - _sides[iL2]->MiddlePnt()).Modulus();
2513 gp_Vec linkDir1(0,0,0); // initialize to avoid valgrind error ("Conditional jump...")
2514 gp_Vec linkDir2(0,0,0);
2517 if ( f1 && theLink->MediumPos() <= (*link1)->MediumPos() )
2518 len1 = f1->MoveByBoundary
2519 ( *link1, theRefVec, theLinks, theFaceHelper, len1, theStep-1, &linkDir1, theSign);
2521 linkDir1 = LinkNorm( iL1/*, theFaceHelper*/ );
2523 MSG( " --------------- EXCEPTION");
2528 if ( f2 && theLink->MediumPos() <= (*link2)->MediumPos() )
2529 len2 = f2->MoveByBoundary
2530 ( *link2, theRefVec, theLinks, theFaceHelper, len2, theStep-1, &linkDir2, theSign);
2532 linkDir2 = LinkNorm( iL2/*, theFaceHelper*/ );
2534 MSG( " --------------- EXCEPTION");
2539 if ( theStep != theFirstStep )
2541 // choose chain length by direction of propagation most codirected with theRefVec
2542 bool choose1 = ( theRefVec * linkDir1 * theSign > theRefVec * linkDir2 * theSign );
2543 fullLen = choose1 ? len1 : len2;
2544 double r = thePrevLen / fullLen;
2546 gp_Vec move = linkNorm * refProj * ( 1 - r );
2547 theLink->Move( move, true );
2549 MSG(string(theStep,'.')<<" Move "<< theLink->_mediumNode->GetID()<<
2550 " by " << refProj * ( 1 - r ) << " following " <<
2551 (choose1 ? *link1->_qlink : *link2->_qlink));
2553 if ( theLinkNorm ) *theLinkNorm = linkNorm;
2558 //================================================================================
2560 * \brief Checks if the face is distorted due to bentLink
2562 //================================================================================
2564 bool QFace::IsSpoiled(const QLink* bentLink ) const
2566 // code is valid for convex faces only
2568 for ( TIDSortedNodeSet::const_iterator n = begin(); n!=end(); ++n)
2569 gc += XYZ( *n ) / size();
2570 for (unsigned i = 0; i < _sides.size(); ++i )
2572 if ( _sides[i] == bentLink ) continue;
2573 gp_Vec linkNorm = _normal ^ gp_Vec( XYZ(_sides[i]->node1()), XYZ(_sides[i]->node2()));
2574 gp_Vec vecOut( gc, _sides[i]->MiddlePnt() );
2575 if ( linkNorm * vecOut < 0 )
2577 double mag2 = linkNorm.SquareMagnitude();
2578 if ( mag2 > numeric_limits<double>::min() )
2579 linkNorm /= sqrt( mag2 );
2580 gp_Vec vecBent ( _sides[i]->MiddlePnt(), bentLink->MediumPnt());
2581 gp_Vec vecStraight( _sides[i]->MiddlePnt(), bentLink->MiddlePnt());
2582 if ( vecBent * linkNorm > -0.1*vecStraight.Magnitude() )
2589 //================================================================================
2591 * \brief Find pairs of continues faces
2593 //================================================================================
2595 void QLink::SetContinuesFaces() const
2597 // x0 x - QLink, [-|] - QFace, v - volume
2599 // | Between _faces of link x2 two vertical faces are continues
2600 // x1----x2-----x3 and two horizontal faces are continues. We set vertical faces
2601 // | to _faces[0] and _faces[1] and horizontal faces to
2602 // v2 | v3 _faces[2] and _faces[3] (or vise versa).
2605 if ( _faces.empty() )
2607 int iFaceCont = -1, nbBoundary = 0, iBoundary[2]={-1,-1};
2608 if ( _faces[0]->IsBoundary() )
2609 iBoundary[ nbBoundary++ ] = 0;
2610 for ( int iF = 1; iFaceCont < 0 && iF < _faces.size(); ++iF )
2612 // look for a face bounding none of volumes bound by _faces[0]
2613 bool sameVol = false;
2614 int nbVol = _faces[iF]->NbVolumes();
2615 for ( int iV = 0; !sameVol && iV < nbVol; ++iV )
2616 sameVol = ( _faces[iF]->_volumes[iV] == _faces[0]->_volumes[0] ||
2617 _faces[iF]->_volumes[iV] == _faces[0]->_volumes[1]);
2620 if ( _faces[iF]->IsBoundary() )
2621 iBoundary[ nbBoundary++ ] = iF;
2623 // Set continues faces: arrange _faces to have
2624 // _faces[0] continues to _faces[1]
2625 // _faces[2] continues to _faces[3]
2626 if ( nbBoundary == 2 ) // bnd faces are continues
2628 if (( iBoundary[0] < 2 ) != ( iBoundary[1] < 2 ))
2630 int iNear0 = iBoundary[0] < 2 ? 1-iBoundary[0] : 5-iBoundary[0];
2631 std::swap( _faces[ iBoundary[1] ], _faces[iNear0] );
2634 else if ( iFaceCont > 0 ) // continues faces found
2636 if ( iFaceCont != 1 )
2637 std::swap( _faces[1], _faces[iFaceCont] );
2639 else if ( _faces.size() > 1 ) // not found, set NULL by the first face
2641 _faces.insert( ++_faces.begin(), 0 );
2644 //================================================================================
2646 * \brief Return a face continues to the given one
2648 //================================================================================
2650 const QFace* QLink::GetContinuesFace( const QFace* face ) const
2652 for ( int i = 0; i < _faces.size(); ++i ) {
2653 if ( _faces[i] == face ) {
2654 int iF = i < 2 ? 1-i : 5-i;
2655 return iF < _faces.size() ? _faces[iF] : 0;
2660 //================================================================================
2662 * \brief True if link is on mesh boundary
2664 //================================================================================
2666 bool QLink::OnBoundary() const
2668 for ( int i = 0; i < _faces.size(); ++i )
2669 if (_faces[i] && _faces[i]->IsBoundary()) return true;
2672 //================================================================================
2674 * \brief Return normal of link of the chain
2676 //================================================================================
2678 gp_Vec TChainLink::Normal() const {
2680 if (_qfaces[0]) norm = _qfaces[0]->_normal;
2681 if (_qfaces[1]) norm += _qfaces[1]->_normal;
2684 //================================================================================
2686 * \brief Test link curvature taking into account size of faces
2688 //================================================================================
2690 bool TChainLink::IsStraight() const
2692 bool isStraight = _qlink->IsStraight();
2693 if ( isStraight && _qfaces[0] && !_qfaces[1] )
2695 int i = _qfaces[0]->LinkIndex( _qlink );
2696 int iOpp = ( i + 2 ) % _qfaces[0]->_sides.size();
2697 gp_XYZ mid1 = _qlink->MiddlePnt();
2698 gp_XYZ mid2 = _qfaces[0]->_sides[ iOpp ]->MiddlePnt();
2699 double faceSize2 = (mid1-mid2).SquareModulus();
2700 isStraight = _qlink->_nodeMove.SquareMagnitude() < 1/10./10. * faceSize2;
2705 //================================================================================
2707 * \brief Move medium nodes of vertical links of pentahedrons adjacent by side faces
2709 //================================================================================
2711 void fixPrism( TChain& allLinks )
2713 // separate boundary links from internal ones
2714 typedef set<const QLink*/*, QLink::PtrComparator*/> QLinkSet;
2715 QLinkSet interLinks, bndLinks1, bndLink2;
2717 bool isCurved = false;
2718 for ( TChain::iterator lnk = allLinks.begin(); lnk != allLinks.end(); ++lnk ) {
2719 if ( (*lnk)->OnBoundary() )
2720 bndLinks1.insert( lnk->_qlink );
2722 interLinks.insert( lnk->_qlink );
2723 isCurved = isCurved || !lnk->IsStraight();
2726 return; // no need to move
2728 QLinkSet *curBndLinks = &bndLinks1, *newBndLinks = &bndLink2;
2730 while ( !interLinks.empty() && !curBndLinks->empty() )
2732 // propagate movement from boundary links to connected internal links
2733 QLinkSet::iterator bnd = curBndLinks->begin(), bndEnd = curBndLinks->end();
2734 for ( ; bnd != bndEnd; ++bnd )
2736 const QLink* bndLink = *bnd;
2737 for ( int i = 0; i < bndLink->_faces.size(); ++i ) // loop on faces of bndLink
2739 const QFace* face = bndLink->_faces[i]; // quadrange lateral face of a prism
2740 if ( !face ) continue;
2741 // find and move internal link opposite to bndLink within the face
2742 int interInd = ( face->LinkIndex( bndLink ) + 2 ) % face->_sides.size();
2743 const QLink* interLink = face->_sides[ interInd ];
2744 QLinkSet::iterator pInterLink = interLinks.find( interLink );
2745 if ( pInterLink == interLinks.end() ) continue; // not internal link
2746 interLink->Move( bndLink->_nodeMove );
2747 // treated internal links become new boundary ones
2748 interLinks. erase( pInterLink );
2749 newBndLinks->insert( interLink );
2752 curBndLinks->clear();
2753 std::swap( curBndLinks, newBndLinks );
2757 //================================================================================
2759 * \brief Fix links of continues triangles near curved boundary
2761 //================================================================================
2763 void fixTriaNearBoundary( TChain & allLinks, SMESH_MesherHelper& /*helper*/)
2765 if ( allLinks.empty() ) return;
2767 TLinkSet linkSet( allLinks.begin(), allLinks.end());
2768 TLinkInSet linkIt = linkSet.begin(), linksEnd = linkSet.end();
2770 for ( linkIt = linkSet.begin(); linkIt != linksEnd; ++linkIt)
2772 if ( linkIt->IsBoundary() && !linkIt->IsStraight() && linkIt->_qfaces[0])
2774 // move iff a boundary link is bent towards inside of a face (issue 0021084)
2775 const QFace* face = linkIt->_qfaces[0];
2776 gp_XYZ pIn = ( face->_sides[0]->MiddlePnt() +
2777 face->_sides[1]->MiddlePnt() +
2778 face->_sides[2]->MiddlePnt() ) / 3.;
2779 gp_XYZ insideDir( pIn - (*linkIt)->MiddlePnt());
2780 bool linkBentInside = ((*linkIt)->_nodeMove.Dot( insideDir ) > 0 );
2781 //if ( face->IsSpoiled( linkIt->_qlink ))
2782 if ( linkBentInside )
2783 face->MoveByBoundary( *linkIt, (*linkIt)->_nodeMove, linkSet );
2788 //================================================================================
2790 * \brief Detect rectangular structure of links and build chains from them
2792 //================================================================================
2794 enum TSplitTriaResult {
2795 _OK, _NO_CORNERS, _FEW_ROWS, _MANY_ROWS, _NO_SIDELINK, _BAD_MIDQUAD, _NOT_RECT,
2796 _NO_MIDQUAD, _NO_UPTRIA, _BAD_SET_SIZE, _BAD_CORNER, _BAD_START, _NO_BOTLINK, _TWISTED_CHAIN };
2798 TSplitTriaResult splitTrianglesIntoChains( TChain & allLinks,
2799 vector< TChain> & resultChains,
2800 SMDS_TypeOfPosition pos )
2802 // put links in the set and evalute number of result chains by number of boundary links
2805 for ( TChain::iterator lnk = allLinks.begin(); lnk != allLinks.end(); ++lnk ) {
2806 linkSet.insert( *lnk );
2807 nbBndLinks += lnk->IsBoundary();
2809 resultChains.clear();
2810 resultChains.reserve( nbBndLinks / 2 );
2812 TLinkInSet linkIt, linksEnd = linkSet.end();
2814 // find a boundary link with corner node; corner node has position pos-2
2815 // i.e. SMDS_TOP_VERTEX for links on faces and SMDS_TOP_EDGE for
2817 SMDS_TypeOfPosition cornerPos = SMDS_TypeOfPosition(pos-2);
2818 const SMDS_MeshNode* corner = 0;
2819 for ( linkIt = linkSet.begin(); linkIt != linksEnd; ++linkIt )
2820 if ( linkIt->IsBoundary() && (corner = (*linkIt)->EndPosNode(cornerPos)))
2825 TLinkInSet startLink = linkIt;
2826 const SMDS_MeshNode* startCorner = corner;
2827 vector< TChain* > rowChains;
2830 while ( startLink != linksEnd) // loop on columns
2832 // We suppose we have a rectangular structure like shown here. We have found a
2833 // corner of the rectangle (startCorner) and a boundary link sharing
2834 // |/ |/ | the startCorner (startLink). We are going to loop on rows of the
2835 // --o---o---o structure making several chains at once. One chain (columnChain)
2836 // |\ | /| starts at startLink and continues upward (we look at the structure
2837 // \ | \ | / | from such point that startLink is on the bottom of the structure).
2838 // \| \|/ | While going upward we also fill horizontal chains (rowChains) we
2839 // --o---o---o encounter.
2841 // / | \ | \ | startCorner
2846 if ( resultChains.size() == nbBndLinks / 2 )
2848 resultChains.push_back( TChain() );
2849 TChain& columnChain = resultChains.back();
2851 TLinkInSet botLink = startLink; // current horizontal link to go up from
2852 corner = startCorner; // current corner the botLink ends at
2854 while ( botLink != linksEnd ) // loop on rows
2856 // add botLink to the columnChain
2857 columnChain.push_back( *botLink );
2859 const QFace* botTria = botLink->_qfaces[0]; // bottom triangle bound by botLink
2861 { // the column ends
2862 if ( botLink == startLink )
2863 return _TWISTED_CHAIN; // issue 0020951
2864 linkSet.erase( botLink );
2865 if ( iRow != rowChains.size() )
2866 return _FEW_ROWS; // different nb of rows in columns
2869 // find the link dividing the quadrangle (midQuadLink) and vertical boundary
2870 // link ending at <corner> (sideLink); there are two cases:
2871 // 1) midQuadLink does not end at <corner>, then we easily find it by botTria,
2872 // since midQuadLink is not at boundary while sideLink is.
2873 // 2) midQuadLink ends at <corner>
2875 TLinkInSet midQuadLink = linksEnd;
2876 TLinkInSet sideLink = botTria->GetBoundaryLink( linkSet, *botLink, &midQuadLink,
2878 if ( isCase2 ) { // find midQuadLink among links of botTria
2879 midQuadLink = botTria->GetLinkByNode( linkSet, *botLink, corner );
2880 if ( midQuadLink->IsBoundary() )
2881 return _BAD_MIDQUAD;
2883 if ( sideLink == linksEnd || midQuadLink == linksEnd || sideLink == midQuadLink )
2884 return sideLink == linksEnd ? _NO_SIDELINK : _NO_MIDQUAD;
2887 columnChain.push_back( *midQuadLink );
2888 if ( iRow >= rowChains.size() ) {
2890 return _MANY_ROWS; // different nb of rows in columns
2891 if ( resultChains.size() == nbBndLinks / 2 )
2893 resultChains.push_back( TChain() );
2894 rowChains.push_back( & resultChains.back() );
2896 rowChains[iRow]->push_back( *sideLink );
2897 rowChains[iRow]->push_back( *midQuadLink );
2899 const QFace* upTria = midQuadLink->NextFace( botTria ); // upper tria of the rectangle
2903 // prepare startCorner and startLink for the next column
2904 startCorner = startLink->NextNode( startCorner );
2906 startLink = botTria->GetBoundaryLink( linkSet, *botLink, 0, startCorner );
2908 startLink = upTria->GetBoundaryLink( linkSet, *midQuadLink, 0, startCorner );
2909 // check if no more columns remains
2910 if ( startLink != linksEnd ) {
2911 const SMDS_MeshNode* botNode = startLink->NextNode( startCorner );
2912 if ( (isCase2 ? botTria : upTria)->Contains( botNode ))
2913 startLink = linksEnd; // startLink bounds upTria or botTria
2914 else if ( startLink == botLink || startLink == midQuadLink || startLink == sideLink )
2918 // find bottom link and corner for the next row
2919 corner = sideLink->NextNode( corner );
2920 // next bottom link ends at the new corner
2921 linkSet.erase( botLink );
2922 botLink = upTria->GetLinkByNode( linkSet, (isCase2 ? *sideLink : *midQuadLink), corner );
2923 if ( botLink == linksEnd || botLink == midQuadLink || botLink == sideLink)
2925 if ( midQuadLink == startLink || sideLink == startLink )
2926 return _TWISTED_CHAIN; // issue 0020951
2927 linkSet.erase( midQuadLink );
2928 linkSet.erase( sideLink );
2930 // make faces neighboring the found ones be boundary
2931 if ( startLink != linksEnd ) {
2932 const QFace* tria = isCase2 ? botTria : upTria;
2933 for ( int iL = 0; iL < 3; ++iL ) {
2934 linkIt = linkSet.find( tria->_sides[iL] );
2935 if ( linkIt != linksEnd )
2936 linkIt->RemoveFace( tria );
2939 if ( botLink->_qfaces[0] == upTria || botLink->_qfaces[1] == upTria )
2940 botLink->RemoveFace( upTria ); // make next botTria first in vector
2947 // In the linkSet, there must remain the last links of rowChains; add them
2948 if ( linkSet.size() != rowChains.size() )
2949 return _BAD_SET_SIZE;
2950 for ( int iRow = 0; iRow < rowChains.size(); ++iRow ) {
2951 // find the link (startLink) ending at startCorner
2953 for ( startLink = linkSet.begin(); startLink != linksEnd; ++startLink ) {
2954 if ( (*startLink)->node1() == startCorner ) {
2955 corner = (*startLink)->node2(); break;
2957 else if ( (*startLink)->node2() == startCorner) {
2958 corner = (*startLink)->node1(); break;
2961 if ( startLink == linksEnd )
2963 rowChains[ iRow ]->push_back( *startLink );
2964 linkSet.erase( startLink );
2965 startCorner = corner;
2972 //=======================================================================
2974 * \brief Move medium nodes of faces and volumes to fix distorted elements
2975 * \param volumeOnly - to fix nodes on faces or not, if the shape is solid
2977 * Issue 0020307: EDF 992 SMESH : Linea/Quadratic with Medium Node on Geometry
2979 //=======================================================================
2981 void SMESH_MesherHelper::FixQuadraticElements(bool volumeOnly)
2983 // setenv NO_FixQuadraticElements to know if FixQuadraticElements() is guilty of bad conversion
2984 if ( getenv("NO_FixQuadraticElements") )
2987 // 0. Apply algorithm to solids or geom faces
2988 // ----------------------------------------------
2989 if ( myShape.IsNull() ) {
2990 if ( !myMesh->HasShapeToMesh() ) return;
2991 SetSubShape( myMesh->GetShapeToMesh() );
2995 TopTools_IndexedMapOfShape solids;
2996 TopExp::MapShapes(myShape,TopAbs_SOLID,solids);
2997 nbSolids = solids.Extent();
2999 TopTools_MapOfShape faces; // faces not in solid or in not meshed solid
3000 for ( TopExp_Explorer f(myShape,TopAbs_FACE,TopAbs_SOLID); f.More(); f.Next() ) {
3001 faces.Add( f.Current() ); // not in solid
3003 for ( TopExp_Explorer s(myShape,TopAbs_SOLID); s.More(); s.Next() ) {
3004 if ( myMesh->GetSubMesh( s.Current() )->IsEmpty() ) { // get faces of solid
3005 for ( TopExp_Explorer f( s.Current(), TopAbs_FACE); f.More(); f.Next() )
3006 faces.Add( f.Current() ); // in not meshed solid
3008 else { // fix nodes in the solid and its faces
3010 MSG("FIX SOLID " << nbSolids-- << " #" << GetMeshDS()->ShapeToIndex(s.Current()));
3012 SMESH_MesherHelper h(*myMesh);
3013 h.SetSubShape( s.Current() );
3014 h.FixQuadraticElements(false);
3017 // fix nodes on geom faces
3019 int nbfaces = faces.Extent(); /*avoid "unused varianbles": */ nbfaces++, nbfaces--;
3021 for ( TopTools_MapIteratorOfMapOfShape fIt( faces ); fIt.More(); fIt.Next() ) {
3022 MSG("FIX FACE " << nbfaces-- << " #" << GetMeshDS()->ShapeToIndex(fIt.Key()));
3023 SMESH_MesherHelper h(*myMesh);
3024 h.SetSubShape( fIt.Key() );
3025 h.FixQuadraticElements(true);
3027 //perf_print_all_meters(1);
3031 // 1. Find out type of elements and get iterator on them
3032 // ---------------------------------------------------
3034 SMDS_ElemIteratorPtr elemIt;
3035 SMDSAbs_ElementType elemType = SMDSAbs_All;
3037 SMESH_subMesh* submesh = myMesh->GetSubMeshContaining( myShapeID );
3040 if ( SMESHDS_SubMesh* smDS = submesh->GetSubMeshDS() ) {
3041 elemIt = smDS->GetElements();
3042 if ( elemIt->more() ) {
3043 elemType = elemIt->next()->GetType();
3044 elemIt = smDS->GetElements();
3047 if ( !elemIt || !elemIt->more() || elemType < SMDSAbs_Face )
3050 // 2. Fill in auxiliary data structures
3051 // ----------------------------------
3055 set< QLink >::iterator pLink;
3056 set< QFace >::iterator pFace;
3058 bool isCurved = false;
3059 //bool hasRectFaces = false;
3060 //set<int> nbElemNodeSet;
3061 SMDS_VolumeTool volTool;
3063 TIDSortedNodeSet apexOfPyramid;
3064 const int apexIndex = 4;
3066 if ( elemType == SMDSAbs_Volume )
3068 while ( elemIt->more() ) // loop on volumes
3070 const SMDS_MeshElement* vol = elemIt->next();
3071 if ( !vol->IsQuadratic() || !volTool.Set( vol ))
3073 double volMinSize2 = -1.;
3074 for ( int iF = 0; iF < volTool.NbFaces(); ++iF ) // loop on faces of volume
3076 int nbN = volTool.NbFaceNodes( iF );
3077 //nbElemNodeSet.insert( nbN );
3078 const SMDS_MeshNode** faceNodes = volTool.GetFaceNodes( iF );
3079 vector< const QLink* > faceLinks( nbN/2 );
3080 for ( int iN = 0; iN < nbN; iN += 2 ) // loop on links of a face
3083 QLink link( faceNodes[iN], faceNodes[iN+2], faceNodes[iN+1] );
3084 pLink = links.insert( link ).first;
3085 faceLinks[ iN/2 ] = & *pLink;
3087 if ( link.MediumPos() == SMDS_TOP_3DSPACE )
3089 if ( !link.IsStraight() )
3090 return; // already fixed
3092 else if ( !isCurved )
3094 if ( volMinSize2 < 0 ) volMinSize2 = volTool.MinLinearSize2();
3095 isCurved = !isStraightLink( volMinSize2, link._nodeMove.SquareMagnitude() );
3099 pFace = faces.insert( QFace( faceLinks )).first;
3100 if ( pFace->NbVolumes() == 0 )
3101 pFace->AddSelfToLinks();
3102 pFace->SetVolume( vol );
3103 // hasRectFaces = hasRectFaces ||
3104 // ( volTool.GetVolumeType() == SMDS_VolumeTool::QUAD_HEXA ||
3105 // volTool.GetVolumeType() == SMDS_VolumeTool::QUAD_PENTA );
3108 pFace->_face = GetMeshDS()->FindFace(faceNodes[0],faceNodes[2],faceNodes[4]);
3110 pFace->_face = GetMeshDS()->FindFace(faceNodes[0],faceNodes[2],
3111 faceNodes[4],faceNodes[6] );
3114 // collect pyramid apexes for further correction
3115 if ( vol->NbCornerNodes() == 5 )
3116 apexOfPyramid.insert( vol->GetNode( apexIndex ));
3118 set< QLink >::iterator pLink = links.begin();
3119 for ( ; pLink != links.end(); ++pLink )
3120 pLink->SetContinuesFaces();
3124 while ( elemIt->more() ) // loop on faces
3126 const SMDS_MeshElement* face = elemIt->next();
3127 if ( !face->IsQuadratic() )
3129 //nbElemNodeSet.insert( face->NbNodes() );
3130 int nbN = face->NbNodes()/2;
3131 vector< const QLink* > faceLinks( nbN );
3132 for ( int iN = 0; iN < nbN; ++iN ) // loop on links of a face
3135 QLink link( face->GetNode(iN), face->GetNode((iN+1)%nbN), face->GetNode(iN+nbN) );
3136 pLink = links.insert( link ).first;
3137 faceLinks[ iN ] = & *pLink;
3139 isCurved = !link.IsStraight();
3142 pFace = faces.insert( QFace( faceLinks )).first;
3143 pFace->AddSelfToLinks();
3144 //hasRectFaces = ( hasRectFaces || nbN == 4 );
3148 return; // no curved edges of faces
3150 // 3. Compute displacement of medium nodes
3151 // ---------------------------------------
3153 // two loops on QFaces: the first is to treat boundary links, the second is for internal ones
3154 TopLoc_Location loc;
3155 // not treat boundary of volumic submesh
3156 int isInside = ( elemType == SMDSAbs_Volume && volumeOnly ) ? 1 : 0;
3157 for ( ; isInside < 2; ++isInside ) {
3158 MSG( "--------------- LOOP (inside=" << isInside << ") ------------------");
3159 SMDS_TypeOfPosition pos = isInside ? SMDS_TOP_3DSPACE : SMDS_TOP_FACE;
3160 SMDS_TypeOfPosition bndPos = isInside ? SMDS_TOP_FACE : SMDS_TOP_EDGE;
3162 for ( pFace = faces.begin(); pFace != faces.end(); ++pFace ) {
3163 if ( bool(isInside) == pFace->IsBoundary() )
3165 for ( int dir = 0; dir < 2; ++dir ) // 2 directions of propagation from the quadrangle
3168 // make chain of links connected via continues faces
3171 if ( !pFace->GetLinkChain( dir, rawChain, pos, error) && error ==ERR_UNKNOWN ) continue;
3173 if ( !pFace->GetLinkChain( dir+2, rawChain, pos, error ) && error ==ERR_UNKNOWN ) continue;
3175 vector< TChain > chains;
3176 if ( error == ERR_OK ) { // chain contains continues rectangles
3178 chains[0].splice( chains[0].begin(), rawChain );
3180 else if ( error == ERR_TRI ) { // chain contains continues triangles
3181 TSplitTriaResult res = splitTrianglesIntoChains( rawChain, chains, pos );
3182 if ( res != _OK ) { // not quadrangles split into triangles
3183 fixTriaNearBoundary( rawChain, *this );
3187 else if ( error == ERR_PRISM ) { // quadrangle side faces of prisms
3188 fixPrism( rawChain );
3194 for ( int iC = 0; iC < chains.size(); ++iC )
3196 TChain& chain = chains[iC];
3197 if ( chain.empty() ) continue;
3198 if ( chain.front().IsStraight() && chain.back().IsStraight() ) {
3199 MSG("3D straight - ignore");
3202 if ( chain.front()->MediumPos() > bndPos ||
3203 chain.back() ->MediumPos() > bndPos ) {
3204 MSG("Internal chain - ignore");
3207 // mesure chain length and compute link position along the chain
3208 double chainLen = 0;
3209 vector< double > linkPos;
3210 MSGBEG( "Link medium nodes: ");
3211 TChain::iterator link0 = chain.begin(), link1 = chain.begin(), link2;
3212 for ( ++link1; link1 != chain.end(); ++link1, ++link0 ) {
3213 MSGBEG( (*link0)->_mediumNode->GetID() << "-" <<(*link1)->_mediumNode->GetID()<<" ");
3214 double len = ((*link0)->MiddlePnt() - (*link1)->MiddlePnt()).Modulus();
3215 while ( len < numeric_limits<double>::min() ) { // remove degenerated link
3216 link1 = chain.erase( link1 );
3217 if ( link1 == chain.end() )
3219 len = ((*link0)->MiddlePnt() - (*link1)->MiddlePnt()).Modulus();
3222 linkPos.push_back( chainLen );
3225 if ( linkPos.size() < 2 )
3228 gp_Vec move0 = chain.front()->_nodeMove;
3229 gp_Vec move1 = chain.back ()->_nodeMove;
3232 bool checkUV = true;
3235 // compute node displacement of end links of chain in parametric space of face
3236 TChainLink& linkOnFace = *(++chain.begin());
3237 const SMDS_MeshNode* nodeOnFace = linkOnFace->_mediumNode;
3238 TopoDS_Shape f = GetSubShapeByNode( nodeOnFace, GetMeshDS() );
3239 if ( !f.IsNull() && f.ShapeType() == TopAbs_FACE )
3241 face = TopoDS::Face( f );
3242 Handle(Geom_Surface) surf = BRep_Tool::Surface(face,loc);
3244 for ( int is1 = 0; is1 < 2; ++is1 ) // move0 or move1
3246 TChainLink& link = is1 ? chain.back() : chain.front();
3247 gp_XY uvm = GetNodeUV( face, link->_mediumNode, nodeOnFace, &checkUV);
3248 gp_XY uv1 = GetNodeUV( face, link->node1(), nodeOnFace, &checkUV);
3249 gp_XY uv2 = GetNodeUV( face, link->node2(), nodeOnFace, &checkUV);
3250 gp_XY uv12 = GetMiddleUV( surf, uv1, uv2);
3251 // uvMove = uvm - uv12
3252 gp_XY uvMove = applyIn2D(surf, uvm, uv12, gp_XY_Subtracted, /*inPeriod=*/false);
3253 ( is1 ? move1 : move0 ).SetCoord( uvMove.X(), uvMove.Y(), 0 );
3254 if ( !is1 ) // correct nodeOnFace for move1 (issue 0020919)
3255 nodeOnFace = (*(++chain.rbegin()))->_mediumNode;
3256 isStraight[is1] = isStraightLink( (uv2-uv1).SquareModulus(),
3257 10 * uvMove.SquareModulus());
3259 if ( isStraight[0] && isStraight[1] ) {
3260 MSG("2D straight - ignore");
3261 continue; // straight - no need to move nodes of internal links
3264 // check if a chain is already fixed
3265 gp_XY uvm = GetNodeUV( face, linkOnFace->_mediumNode, 0, &checkUV);
3266 gp_XY uv1 = GetNodeUV( face, linkOnFace->node1(), nodeOnFace, &checkUV);
3267 gp_XY uv2 = GetNodeUV( face, linkOnFace->node2(), nodeOnFace, &checkUV);
3268 gp_XY uv12 = GetMiddleUV( surf, uv1, uv2);
3269 if (( uvm - uv12 ).SquareModulus() > 1e-10 )
3271 MSG("Already fixed - ignore");
3277 if ( isInside || face.IsNull() )
3279 // compute node displacement of end links in their local coord systems
3281 TChainLink& ln0 = chain.front(), ln1 = *(++chain.begin());
3282 trsf.SetTransformation( gp_Ax3( gp::Origin(), ln0.Normal(),
3283 gp_Vec( ln0->MiddlePnt(), ln1->MiddlePnt() )));
3284 move0.Transform(trsf);
3287 TChainLink& ln0 = *(++chain.rbegin()), ln1 = chain.back();
3288 trsf.SetTransformation( gp_Ax3( gp::Origin(), ln1.Normal(),
3289 gp_Vec( ln0->MiddlePnt(), ln1->MiddlePnt() )));
3290 move1.Transform(trsf);
3293 // compute displacement of medium nodes
3294 link2 = chain.begin();
3297 for ( int i = 0; link2 != chain.end(); ++link0, ++link1, ++link2, ++i )
3299 double r = linkPos[i] / chainLen;
3300 // displacement in local coord system
3301 gp_Vec move = (1. - r) * move0 + r * move1;
3302 if ( isInside || face.IsNull()) {
3303 // transform to global
3304 gp_Vec x01( (*link0)->MiddlePnt(), (*link1)->MiddlePnt() );
3305 gp_Vec x12( (*link1)->MiddlePnt(), (*link2)->MiddlePnt() );
3306 gp_Vec x = x01.Normalized() + x12.Normalized();
3307 trsf.SetTransformation( gp_Ax3( gp::Origin(), link1->Normal(), x), gp_Ax3() );
3308 move.Transform(trsf);
3311 // compute 3D displacement by 2D one
3312 Handle(Geom_Surface) s = BRep_Tool::Surface(face,loc);
3313 gp_XY oldUV = GetNodeUV( face, (*link1)->_mediumNode, 0, &checkUV);
3314 gp_XY newUV = applyIn2D( s, oldUV, gp_XY( move.X(),move.Y()), gp_XY_Added);
3315 gp_Pnt newPnt = s->Value( newUV.X(), newUV.Y());
3316 move = gp_Vec( XYZ((*link1)->_mediumNode), newPnt.Transformed(loc) );
3318 if ( (XYZ((*link1)->node1()) - XYZ((*link1)->node2())).SquareModulus() <
3319 move.SquareMagnitude())
3321 gp_XY uv0 = GetNodeUV( face, (*link0)->_mediumNode, 0, &checkUV);
3322 gp_XY uv2 = GetNodeUV( face, (*link2)->_mediumNode, 0, &checkUV);
3323 MSG( "TOO LONG MOVE \t" <<
3324 "uv0: "<<uv0.X()<<", "<<uv0.Y()<<" \t" <<
3325 "uv2: "<<uv2.X()<<", "<<uv2.Y()<<" \t" <<
3326 "uvOld: "<<oldUV.X()<<", "<<oldUV.Y()<<" \t" <<
3327 "newUV: "<<newUV.X()<<", "<<newUV.Y()<<" \t");
3331 (*link1)->Move( move );
3332 MSG( "Move " << (*link1)->_mediumNode->GetID() << " following "
3333 << chain.front()->_mediumNode->GetID() <<"-"
3334 << chain.back ()->_mediumNode->GetID() <<
3335 " by " << move.Magnitude());
3337 } // loop on chains of links
3338 } // loop on 2 directions of propagation from quadrangle
3345 // vector<const SMDS_MeshElement*> vols( 100 );
3346 // vector<double> volSize( 100 );
3349 for ( pLink = links.begin(); pLink != links.end(); ++pLink ) {
3350 if ( pLink->IsMoved() ) {
3351 gp_Pnt p = pLink->MiddlePnt() + pLink->Move();
3352 GetMeshDS()->MoveNode( pLink->_mediumNode, p.X(), p.Y(), p.Z());
3354 // gp_Pnt pNew = pLink->MiddlePnt() + pLink->Move();
3355 // if ( pLink->MediumPos() != SMDS_TOP_3DSPACE )
3357 // // avoid making distorted volumes near boundary
3358 // SMDS_ElemIteratorPtr volIt =
3359 // (*pLink)._mediumNode->GetInverseElementIterator( SMDSAbs_Volume );
3360 // for ( nbVols = 0; volIt->more() && volTool.Set( volIt->next() ); ++nbVols )
3362 // vols [ nbVols ] = volTool.Element();
3363 // volSize[ nbVols ] = volTool.GetSize();
3365 // gp_Pnt pOld = pLink->MediumPnt();
3366 // const_cast<SMDS_MeshNode*>( pLink->_mediumNode )->setXYZ( pNew.X(), pNew.Y(), pNew.Z() );
3368 // while ( nbVols-- && ok )
3370 // volTool.Set( vols[ nbVols ]);
3371 // ok = ( volSize[ nbVols ] * volTool.GetSize() > 1e-20 );
3375 // const_cast<SMDS_MeshNode*>( pLink->_mediumNode )->setXYZ( pOld.X(), pOld.Y(), pOld.Z() );
3376 // MSG( "Do NOT move \t" << pLink->_mediumNode->GetID()
3377 // << " because of distortion of volume " << vols[ nbVols+1 ]->GetID());
3381 // GetMeshDS()->MoveNode( pLink->_mediumNode, pNew.X(), pNew.Y(), pNew.Z() );
3388 // Move the apex of pyramid together with the most curved link
3390 TIDSortedNodeSet::iterator apexIt = apexOfPyramid.begin();
3391 for ( ; apexIt != apexOfPyramid.end(); ++apexIt )
3393 SMESH_TNodeXYZ apex = *apexIt;
3395 gp_Vec maxMove( 0,0,0 );
3396 double maxMoveSize2 = 0;
3398 // shift of node index to get medium nodes between the base nodes
3399 const int base2MediumShift = 5;
3401 // find maximal movement of medium node
3402 SMDS_ElemIteratorPtr volIt = apex._node->GetInverseElementIterator( SMDSAbs_Volume );
3403 vector< const SMDS_MeshElement* > pyramids;
3404 while ( volIt->more() )
3406 const SMDS_MeshElement* pyram = volIt->next();
3407 if ( pyram->GetEntityType() != SMDSEntity_Quad_Pyramid ) continue;
3408 pyramids.push_back( pyram );
3410 for ( int iBase = 0; iBase < apexIndex; ++iBase )
3412 SMESH_TNodeXYZ medium = pyram->GetNode( iBase + base2MediumShift );
3413 if ( medium._node->GetPosition()->GetTypeOfPosition() != SMDS_TOP_3DSPACE )
3415 SMESH_TNodeXYZ n1 = pyram->GetNode( iBase );
3416 SMESH_TNodeXYZ n2 = pyram->GetNode( ( iBase+1 ) % 4 );
3417 gp_Pnt middle = 0.5 * ( n1 + n2 );
3418 gp_Vec move( middle, medium );
3419 double moveSize2 = move.SquareMagnitude();
3420 if ( moveSize2 > maxMoveSize2 )
3421 maxMove = move, maxMoveSize2 = moveSize2;
3427 if ( maxMoveSize2 > 1e-20 )
3429 apex += maxMove.XYZ();
3430 GetMeshDS()->MoveNode( apex._node, apex.X(), apex.Y(), apex.Z());
3432 // move medium nodes neighboring the apex to the middle
3433 const int base2MediumShift_2 = 9;
3434 for ( unsigned i = 0; i < pyramids.size(); ++i )
3435 for ( int iBase = 0; iBase < apexIndex; ++iBase )
3437 SMESH_TNodeXYZ base = pyramids[i]->GetNode( iBase );
3438 const SMDS_MeshNode* medium = pyramids[i]->GetNode( iBase + base2MediumShift_2 );
3439 gp_XYZ middle = 0.5 * ( apex + base );
3440 GetMeshDS()->MoveNode( medium, middle.X(), middle.Y(), middle.Z());