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_EdgePosition.hxx"
30 #include "SMDS_FaceOfNodes.hxx"
31 #include "SMDS_FacePosition.hxx"
32 #include "SMDS_IteratorOnIterators.hxx"
33 #include "SMDS_VolumeTool.hxx"
34 #include "SMESH_Block.hxx"
35 #include "SMESH_ProxyMesh.hxx"
36 #include "SMESH_subMesh.hxx"
38 #include <BRepAdaptor_Curve.hxx>
39 #include <BRepAdaptor_Surface.hxx>
40 #include <BRepTools.hxx>
41 #include <BRep_Tool.hxx>
42 #include <Geom2d_Curve.hxx>
43 #include <GeomAPI_ProjectPointOnCurve.hxx>
44 #include <GeomAPI_ProjectPointOnSurf.hxx>
45 #include <Geom_Curve.hxx>
46 #include <Geom_RectangularTrimmedSurface.hxx>
47 #include <Geom_Surface.hxx>
48 #include <ShapeAnalysis.hxx>
50 #include <TopExp_Explorer.hxx>
51 #include <TopTools_ListIteratorOfListOfShape.hxx>
52 #include <TopTools_MapIteratorOfMapOfShape.hxx>
53 #include <TopTools_MapOfShape.hxx>
56 #include <gp_Pnt2d.hxx>
57 #include <gp_Trsf.hxx>
59 #include <Standard_Failure.hxx>
60 #include <Standard_ErrorHandler.hxx>
62 #include <utilities.h>
68 #define RETURN_BAD_RESULT(msg) { MESSAGE(msg); return false; }
72 gp_XYZ XYZ(const SMDS_MeshNode* n) { return gp_XYZ(n->X(), n->Y(), n->Z()); }
74 enum { U_periodic = 1, V_periodic = 2 };
77 //================================================================================
81 //================================================================================
83 SMESH_MesherHelper::SMESH_MesherHelper(SMESH_Mesh& theMesh)
84 : myParIndex(0), myMesh(&theMesh), myShapeID(0), myCreateQuadratic(false),
85 myFixNodeParameters(false)
87 myPar1[0] = myPar2[0] = myPar1[1] = myPar2[1] = 0;
88 mySetElemOnShape = ( ! myMesh->HasShapeToMesh() );
91 //=======================================================================
92 //function : ~SMESH_MesherHelper
94 //=======================================================================
96 SMESH_MesherHelper::~SMESH_MesherHelper()
99 TID2ProjectorOnSurf::iterator i_proj = myFace2Projector.begin();
100 for ( ; i_proj != myFace2Projector.end(); ++i_proj )
101 delete i_proj->second;
104 TID2ProjectorOnCurve::iterator i_proj = myEdge2Projector.begin();
105 for ( ; i_proj != myEdge2Projector.end(); ++i_proj )
106 delete i_proj->second;
110 //=======================================================================
111 //function : IsQuadraticSubMesh
112 //purpose : Check submesh for given shape: if all elements on this shape
113 // are quadratic, quadratic elements will be created.
114 // Also fill myTLinkNodeMap
115 //=======================================================================
117 bool SMESH_MesherHelper::IsQuadraticSubMesh(const TopoDS_Shape& aSh)
119 SMESHDS_Mesh* meshDS = GetMeshDS();
120 // we can create quadratic elements only if all elements
121 // created on sub-shapes of given shape are quadratic
122 // also we have to fill myTLinkNodeMap
123 myCreateQuadratic = true;
124 mySeamShapeIds.clear();
125 myDegenShapeIds.clear();
126 TopAbs_ShapeEnum subType( aSh.ShapeType()==TopAbs_FACE ? TopAbs_EDGE : TopAbs_FACE );
127 if ( aSh.ShapeType()==TopAbs_COMPOUND )
129 TopoDS_Iterator subIt( aSh );
131 subType = ( subIt.Value().ShapeType()==TopAbs_FACE ) ? TopAbs_EDGE : TopAbs_FACE;
133 SMDSAbs_ElementType elemType( subType==TopAbs_FACE ? SMDSAbs_Face : SMDSAbs_Edge );
136 int nbOldLinks = myTLinkNodeMap.size();
138 if ( !myMesh->HasShapeToMesh() )
140 if (( myCreateQuadratic = myMesh->NbFaces( ORDER_QUADRATIC )))
142 SMDS_FaceIteratorPtr fIt = meshDS->facesIterator();
143 while ( fIt->more() )
144 AddTLinks( static_cast< const SMDS_MeshFace* >( fIt->next() ));
149 TopExp_Explorer exp( aSh, subType );
150 TopTools_MapOfShape checkedSubShapes;
151 for (; exp.More() && myCreateQuadratic; exp.Next()) {
152 if ( !checkedSubShapes.Add( exp.Current() ))
153 continue; // needed if aSh is compound of solids
154 if ( SMESHDS_SubMesh * subMesh = meshDS->MeshElements( exp.Current() )) {
155 if ( SMDS_ElemIteratorPtr it = subMesh->GetElements() ) {
157 const SMDS_MeshElement* e = it->next();
158 if ( e->GetType() != elemType || !e->IsQuadratic() ) {
159 myCreateQuadratic = false;
164 switch ( e->NbNodes() ) {
166 AddTLinkNode(e->GetNode(0),e->GetNode(1),e->GetNode(2)); break;
168 AddTLinkNode(e->GetNode(0),e->GetNode(1),e->GetNode(3));
169 AddTLinkNode(e->GetNode(1),e->GetNode(2),e->GetNode(4));
170 AddTLinkNode(e->GetNode(2),e->GetNode(0),e->GetNode(5)); break;
172 AddTLinkNode(e->GetNode(0),e->GetNode(1),e->GetNode(4));
173 AddTLinkNode(e->GetNode(1),e->GetNode(2),e->GetNode(5));
174 AddTLinkNode(e->GetNode(2),e->GetNode(3),e->GetNode(6));
175 AddTLinkNode(e->GetNode(3),e->GetNode(0),e->GetNode(7));
178 myCreateQuadratic = false;
188 if ( nbOldLinks == myTLinkNodeMap.size() )
189 myCreateQuadratic = false;
191 if(!myCreateQuadratic) {
192 myTLinkNodeMap.clear();
196 return myCreateQuadratic;
199 //=======================================================================
200 //function : SetSubShape
201 //purpose : Set geometry to make elements on
202 //=======================================================================
204 void SMESH_MesherHelper::SetSubShape(const int aShID)
206 if ( aShID == myShapeID )
209 SetSubShape( GetMeshDS()->IndexToShape( aShID ));
211 SetSubShape( TopoDS_Shape() );
214 //=======================================================================
215 //function : SetSubShape
216 //purpose : Set geometry to create elements on
217 //=======================================================================
219 void SMESH_MesherHelper::SetSubShape(const TopoDS_Shape& aSh)
221 if ( myShape.IsSame( aSh ))
225 mySeamShapeIds.clear();
226 myDegenShapeIds.clear();
228 if ( myShape.IsNull() ) {
232 SMESHDS_Mesh* meshDS = GetMeshDS();
233 myShapeID = meshDS->ShapeToIndex(aSh);
236 // treatment of periodic faces
237 for ( TopExp_Explorer eF( aSh, TopAbs_FACE ); eF.More(); eF.Next() )
239 const TopoDS_Face& face = TopoDS::Face( eF.Current() );
241 Handle(Geom_Surface) surface = BRep_Tool::Surface( face, loc );
243 if ( surface->IsUPeriodic() || surface->IsVPeriodic() ||
244 surface->IsUClosed() || surface->IsVClosed() )
246 //while ( surface->IsKind(STANDARD_TYPE(Geom_RectangularTrimmedSurface )))
247 //surface = Handle(Geom_RectangularTrimmedSurface)::DownCast( surface )->BasisSurface();
248 GeomAdaptor_Surface surf( surface );
250 for (TopExp_Explorer exp( face, TopAbs_EDGE ); exp.More(); exp.Next())
252 // look for a seam edge
253 const TopoDS_Edge& edge = TopoDS::Edge( exp.Current() );
254 if ( BRep_Tool::IsClosed( edge, face )) {
255 // initialize myPar1, myPar2 and myParIndex
257 BRep_Tool::UVPoints( edge, face, uv1, uv2 );
258 if ( Abs( uv1.Coord(1) - uv2.Coord(1) ) < Abs( uv1.Coord(2) - uv2.Coord(2) ))
260 myParIndex |= U_periodic;
261 myPar1[0] = surf.FirstUParameter();
262 myPar2[0] = surf.LastUParameter();
265 myParIndex |= V_periodic;
266 myPar1[1] = surf.FirstVParameter();
267 myPar2[1] = surf.LastVParameter();
269 // store seam shape indices, negative if shape encounters twice
270 int edgeID = meshDS->ShapeToIndex( edge );
271 mySeamShapeIds.insert( IsSeamShape( edgeID ) ? -edgeID : edgeID );
272 for ( TopExp_Explorer v( edge, TopAbs_VERTEX ); v.More(); v.Next() ) {
273 int vertexID = meshDS->ShapeToIndex( v.Current() );
274 mySeamShapeIds.insert( IsSeamShape( vertexID ) ? -vertexID : vertexID );
278 // look for a degenerated edge
279 if ( BRep_Tool::Degenerated( edge )) {
280 myDegenShapeIds.insert( meshDS->ShapeToIndex( edge ));
281 for ( TopExp_Explorer v( edge, TopAbs_VERTEX ); v.More(); v.Next() )
282 myDegenShapeIds.insert( meshDS->ShapeToIndex( v.Current() ));
285 if ( !myDegenShapeIds.empty() && !myParIndex ) {
286 if ( surface->IsUPeriodic() || surface->IsUClosed() ) {
287 myParIndex |= U_periodic;
288 myPar1[0] = surf.FirstUParameter();
289 myPar2[0] = surf.LastUParameter();
291 else if ( surface->IsVPeriodic() || surface->IsVClosed() ) {
292 myParIndex |= V_periodic;
293 myPar1[1] = surf.FirstVParameter();
294 myPar2[1] = surf.LastVParameter();
301 //=======================================================================
302 //function : GetNodeUVneedInFaceNode
303 //purpose : Check if inFaceNode argument is necessary for call GetNodeUV(F,..)
304 // Return true if the face is periodic.
305 // If F is Null, answer about sub-shape set through IsQuadraticSubMesh() or
307 //=======================================================================
309 bool SMESH_MesherHelper::GetNodeUVneedInFaceNode(const TopoDS_Face& F) const
311 if ( F.IsNull() ) return !mySeamShapeIds.empty();
313 if ( !F.IsNull() && !myShape.IsNull() && myShape.IsSame( F ))
314 return !mySeamShapeIds.empty();
317 Handle(Geom_Surface) aSurface = BRep_Tool::Surface( F,loc );
318 if ( !aSurface.IsNull() )
319 return ( aSurface->IsUPeriodic() || aSurface->IsVPeriodic() );
324 //=======================================================================
325 //function : IsMedium
327 //=======================================================================
329 bool SMESH_MesherHelper::IsMedium(const SMDS_MeshNode* node,
330 const SMDSAbs_ElementType typeToCheck)
332 return SMESH_MeshEditor::IsMedium( node, typeToCheck );
335 //=======================================================================
336 //function : GetSubShapeByNode
337 //purpose : Return support shape of a node
338 //=======================================================================
340 TopoDS_Shape SMESH_MesherHelper::GetSubShapeByNode(const SMDS_MeshNode* node,
341 const SMESHDS_Mesh* meshDS)
343 int shapeID = node ? node->getshapeId() : 0;
344 if ( 0 < shapeID && shapeID <= meshDS->MaxShapeIndex() )
345 return meshDS->IndexToShape( shapeID );
347 return TopoDS_Shape();
351 //=======================================================================
352 //function : AddTLinkNode
353 //purpose : add a link in my data structure
354 //=======================================================================
356 void SMESH_MesherHelper::AddTLinkNode(const SMDS_MeshNode* n1,
357 const SMDS_MeshNode* n2,
358 const SMDS_MeshNode* n12)
360 // add new record to map
361 SMESH_TLink link( n1, n2 );
362 myTLinkNodeMap.insert( make_pair(link,n12));
365 //================================================================================
367 * \brief Add quadratic links of edge to own data structure
369 //================================================================================
371 void SMESH_MesherHelper::AddTLinks(const SMDS_MeshEdge* edge)
373 if ( edge->IsQuadratic() )
374 AddTLinkNode(edge->GetNode(0), edge->GetNode(1), edge->GetNode(2));
377 //================================================================================
379 * \brief Add quadratic links of face to own data structure
381 //================================================================================
383 void SMESH_MesherHelper::AddTLinks(const SMDS_MeshFace* f)
386 switch ( f->NbNodes() ) {
388 AddTLinkNode(f->GetNode(0),f->GetNode(1),f->GetNode(3));
389 AddTLinkNode(f->GetNode(1),f->GetNode(2),f->GetNode(4));
390 AddTLinkNode(f->GetNode(2),f->GetNode(0),f->GetNode(5)); break;
392 AddTLinkNode(f->GetNode(0),f->GetNode(1),f->GetNode(4));
393 AddTLinkNode(f->GetNode(1),f->GetNode(2),f->GetNode(5));
394 AddTLinkNode(f->GetNode(2),f->GetNode(3),f->GetNode(6));
395 AddTLinkNode(f->GetNode(3),f->GetNode(0),f->GetNode(7));
400 //================================================================================
402 * \brief Add quadratic links of volume to own data structure
404 //================================================================================
406 void SMESH_MesherHelper::AddTLinks(const SMDS_MeshVolume* volume)
408 if ( volume->IsQuadratic() )
410 SMDS_VolumeTool vTool( volume );
411 const SMDS_MeshNode** nodes = vTool.GetNodes();
413 for ( int iF = 1; iF < vTool.NbFaces(); ++iF )
415 const int nbN = vTool.NbFaceNodes( iF );
416 const int* iNodes = vTool.GetFaceNodesIndices( iF );
417 for ( int i = 0; i < nbN; )
419 int iN1 = iNodes[i++];
420 int iN12 = iNodes[i++];
422 if ( iN1 > iN2 ) std::swap( iN1, iN2 );
423 int linkID = iN1 * vTool.NbNodes() + iN2;
424 pair< set<int>::iterator, bool > it_isNew = addedLinks.insert( linkID );
425 if ( it_isNew.second )
426 AddTLinkNode( nodes[iN1], nodes[iN2], nodes[iN12] );
428 addedLinks.erase( it_isNew.first ); // each link encounters only twice
434 //================================================================================
436 * \brief Return true if position of nodes on the shape hasn't yet been checked or
437 * the positions proved to be invalid
439 //================================================================================
441 bool SMESH_MesherHelper::toCheckPosOnShape(int shapeID ) const
443 map< int,bool >::const_iterator id_ok = myNodePosShapesValidity.find( shapeID );
444 return ( id_ok == myNodePosShapesValidity.end() || !id_ok->second );
447 //================================================================================
449 * \brief Set validity of positions of nodes on the shape.
450 * Once set, validity is not changed
452 //================================================================================
454 void SMESH_MesherHelper::setPosOnShapeValidity(int shapeID, bool ok ) const
456 ((SMESH_MesherHelper*)this)->myNodePosShapesValidity.insert( make_pair( shapeID, ok));
459 //=======================================================================
460 //function : ToFixNodeParameters
461 //purpose : Enables fixing node parameters on EDGEs and FACEs in
462 // GetNodeU(...,check=true), GetNodeUV(...,check=true), CheckNodeUV() and
463 // CheckNodeU() in case if a node lies on a shape set via SetSubShape().
465 //=======================================================================
467 void SMESH_MesherHelper::ToFixNodeParameters(bool toFix)
469 myFixNodeParameters = toFix;
473 //=======================================================================
474 //function : GetUVOnSeam
475 //purpose : Select UV on either of 2 pcurves of a seam edge, closest to the given UV
476 //=======================================================================
478 gp_Pnt2d SMESH_MesherHelper::GetUVOnSeam( const gp_Pnt2d& uv1, const gp_Pnt2d& uv2 ) const
480 gp_Pnt2d result = uv1;
481 for ( int i = U_periodic; i <= V_periodic ; ++i )
483 if ( myParIndex & i )
485 double p1 = uv1.Coord( i );
486 double dp1 = Abs( p1-myPar1[i-1]), dp2 = Abs( p1-myPar2[i-1]);
487 if ( myParIndex == i ||
488 dp1 < ( myPar2[i-1] - myPar2[i-1] ) / 100. ||
489 dp2 < ( myPar2[i-1] - myPar2[i-1] ) / 100. )
491 double p2 = uv2.Coord( i );
492 double p1Alt = ( dp1 < dp2 ) ? myPar2[i-1] : myPar1[i-1];
493 if ( Abs( p2 - p1 ) > Abs( p2 - p1Alt ))
494 result.SetCoord( i, p1Alt );
501 //=======================================================================
502 //function : GetNodeUV
503 //purpose : Return node UV on face
504 //=======================================================================
506 gp_XY SMESH_MesherHelper::GetNodeUV(const TopoDS_Face& F,
507 const SMDS_MeshNode* n,
508 const SMDS_MeshNode* n2,
511 gp_Pnt2d uv( Precision::Infinite(), Precision::Infinite() );
512 const SMDS_PositionPtr Pos = n->GetPosition();
514 if(Pos->GetTypeOfPosition()==SMDS_TOP_FACE)
516 // node has position on face
517 const SMDS_FacePosition* fpos =
518 static_cast<const SMDS_FacePosition*>(n->GetPosition());
519 uv.SetCoord(fpos->GetUParameter(),fpos->GetVParameter());
521 uvOK = CheckNodeUV( F, n, uv.ChangeCoord(), 10*MaxTolerance( F ));
523 else if(Pos->GetTypeOfPosition()==SMDS_TOP_EDGE)
525 // node has position on edge => it is needed to find
526 // corresponding edge from face, get pcurve for this
527 // edge and retrieve value from this pcurve
528 const SMDS_EdgePosition* epos =
529 static_cast<const SMDS_EdgePosition*>(n->GetPosition());
530 int edgeID = n->getshapeId();
531 TopoDS_Edge E = TopoDS::Edge(GetMeshDS()->IndexToShape(edgeID));
532 double f, l, u = epos->GetUParameter();
533 Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface(E, F, f, l);
534 bool validU = ( f < u && u < l );
536 uv = C2d->Value( u );
538 uv.SetCoord( Precision::Infinite(),0.);
539 if ( check || !validU )
540 uvOK = CheckNodeUV( F, n, uv.ChangeCoord(), 10*MaxTolerance( F ),/*force=*/ !validU );
542 // for a node on a seam edge select one of UVs on 2 pcurves
543 if ( n2 && IsSeamShape( edgeID ) )
545 uv = GetUVOnSeam( uv, GetNodeUV( F, n2, 0, check ));
548 { // adjust uv to period
550 Handle(Geom_Surface) S = BRep_Tool::Surface(F,loc);
551 Standard_Boolean isUPeriodic = S->IsUPeriodic();
552 Standard_Boolean isVPeriodic = S->IsVPeriodic();
553 if ( isUPeriodic || isVPeriodic ) {
554 Standard_Real UF,UL,VF,VL;
555 S->Bounds(UF,UL,VF,VL);
557 uv.SetX( uv.X() + ShapeAnalysis::AdjustToPeriod(uv.X(),UF,UL));
559 uv.SetY( uv.Y() + ShapeAnalysis::AdjustToPeriod(uv.Y(),VF,VL));
563 else if(Pos->GetTypeOfPosition()==SMDS_TOP_VERTEX)
565 if ( int vertexID = n->getshapeId() ) {
566 const TopoDS_Vertex& V = TopoDS::Vertex(GetMeshDS()->IndexToShape(vertexID));
568 uv = BRep_Tool::Parameters( V, F );
571 catch (Standard_Failure& exc) {
574 for ( TopExp_Explorer vert(F,TopAbs_VERTEX); !uvOK && vert.More(); vert.Next() )
575 uvOK = ( V == vert.Current() );
578 MESSAGE ( "SMESH_MesherHelper::GetNodeUV(); Vertex " << vertexID
579 << " not in face " << GetMeshDS()->ShapeToIndex( F ) );
581 // get UV of a vertex closest to the node
583 gp_Pnt pn = XYZ( n );
584 for ( TopExp_Explorer vert(F,TopAbs_VERTEX); !uvOK && vert.More(); vert.Next() ) {
585 TopoDS_Vertex curV = TopoDS::Vertex( vert.Current() );
586 gp_Pnt p = BRep_Tool::Pnt( curV );
587 double curDist = p.SquareDistance( pn );
588 if ( curDist < dist ) {
590 uv = BRep_Tool::Parameters( curV, F );
591 uvOK = ( dist < DBL_MIN );
597 TopTools_ListIteratorOfListOfShape it( myMesh->GetAncestors( V ));
598 for ( ; it.More(); it.Next() ) {
599 if ( it.Value().ShapeType() == TopAbs_EDGE ) {
600 const TopoDS_Edge & edge = TopoDS::Edge( it.Value() );
602 Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface(edge, F, f, l);
603 if ( !C2d.IsNull() ) {
604 double u = ( V == TopExp::FirstVertex( edge ) ) ? f : l;
605 uv = C2d->Value( u );
613 if ( n2 && IsSeamShape( vertexID ) )
614 uv = GetUVOnSeam( uv, GetNodeUV( F, n2, 0 ));
619 uvOK = CheckNodeUV( F, n, uv.ChangeCoord(), 10*MaxTolerance( F ));
628 //=======================================================================
629 //function : CheckNodeUV
630 //purpose : Check and fix node UV on a face
631 //=======================================================================
633 bool SMESH_MesherHelper::CheckNodeUV(const TopoDS_Face& F,
634 const SMDS_MeshNode* n,
638 double distXYZ[4]) const
640 int shapeID = n->getshapeId();
641 bool infinit = ( Precision::IsInfinite( uv.X() ) || Precision::IsInfinite( uv.Y() ));
642 if ( force || toCheckPosOnShape( shapeID ) || infinit )
644 // check that uv is correct
646 Handle(Geom_Surface) surface = BRep_Tool::Surface( F,loc );
647 gp_Pnt nodePnt = XYZ( n ), surfPnt(0,0,0);
649 if ( !loc.IsIdentity() ) nodePnt.Transform( loc.Transformation().Inverted() );
651 (dist = nodePnt.Distance( surfPnt = surface->Value( uv.X(), uv.Y() ))) > tol )
653 setPosOnShapeValidity( shapeID, false );
654 if ( !infinit && distXYZ ) {
655 surfPnt.Transform( loc );
657 distXYZ[1] = surfPnt.X(); distXYZ[2] = surfPnt.Y(); distXYZ[3]=surfPnt.Z();
659 // uv incorrect, project the node to surface
660 GeomAPI_ProjectPointOnSurf& projector = GetProjector( F, loc, tol );
661 projector.Perform( nodePnt );
662 if ( !projector.IsDone() || projector.NbPoints() < 1 )
664 MESSAGE( "SMESH_MesherHelper::CheckNodeUV() failed to project" );
667 Quantity_Parameter U,V;
668 projector.LowerDistanceParameters(U,V);
670 surfPnt = surface->Value( U, V );
671 dist = nodePnt.Distance( surfPnt );
673 surfPnt.Transform( loc );
675 distXYZ[1] = surfPnt.X(); distXYZ[2] = surfPnt.Y(); distXYZ[3]=surfPnt.Z();
679 MESSAGE( "SMESH_MesherHelper::CheckNodeUV(), invalid projection" );
682 // store the fixed UV on the face
683 if ( myShape.IsSame(F) && shapeID == myShapeID && myFixNodeParameters )
684 const_cast<SMDS_MeshNode*>(n)->SetPosition
685 ( SMDS_PositionPtr( new SMDS_FacePosition( U, V )));
687 else if ( uv.Modulus() > numeric_limits<double>::min() )
689 setPosOnShapeValidity( shapeID, true );
695 //=======================================================================
696 //function : GetProjector
697 //purpose : Return projector intitialized by given face without location, which is returned
698 //=======================================================================
700 GeomAPI_ProjectPointOnSurf& SMESH_MesherHelper::GetProjector(const TopoDS_Face& F,
701 TopLoc_Location& loc,
704 Handle(Geom_Surface) surface = BRep_Tool::Surface( F,loc );
705 int faceID = GetMeshDS()->ShapeToIndex( F );
706 TID2ProjectorOnSurf& i2proj = const_cast< TID2ProjectorOnSurf&>( myFace2Projector );
707 TID2ProjectorOnSurf::iterator i_proj = i2proj.find( faceID );
708 if ( i_proj == i2proj.end() )
710 if ( tol == 0 ) tol = BRep_Tool::Tolerance( F );
711 double U1, U2, V1, V2;
712 surface->Bounds(U1, U2, V1, V2);
713 GeomAPI_ProjectPointOnSurf* proj = new GeomAPI_ProjectPointOnSurf();
714 proj->Init( surface, U1, U2, V1, V2, tol );
715 i_proj = i2proj.insert( make_pair( faceID, proj )).first;
717 return *( i_proj->second );
722 gp_XY AverageUV(const gp_XY& uv1, const gp_XY& uv2) { return ( uv1 + uv2 ) / 2.; }
723 gp_XY_FunPtr(Added); // define gp_XY_Added pointer to function calling gp_XY::Added(gp_XY)
724 gp_XY_FunPtr(Subtracted);
727 //=======================================================================
728 //function : applyIn2D
729 //purpose : Perform given operation on two 2d points in parameric space of given surface.
730 // It takes into account period of the surface. Use gp_XY_FunPtr macro
731 // to easily define pointer to function of gp_XY class.
732 //=======================================================================
734 gp_XY SMESH_MesherHelper::applyIn2D(const Handle(Geom_Surface)& surface,
738 const bool resultInPeriod)
740 Standard_Boolean isUPeriodic = surface.IsNull() ? false : surface->IsUPeriodic();
741 Standard_Boolean isVPeriodic = surface.IsNull() ? false : surface->IsVPeriodic();
742 if ( !isUPeriodic && !isVPeriodic )
745 // move uv2 not far than half-period from uv1
747 uv2.X()+(isUPeriodic ? ShapeAnalysis::AdjustByPeriod(uv2.X(),uv1.X(),surface->UPeriod()) :0);
749 uv2.Y()+(isVPeriodic ? ShapeAnalysis::AdjustByPeriod(uv2.Y(),uv1.Y(),surface->VPeriod()) :0);
752 gp_XY res = fun( uv1, gp_XY(u2,v2) );
754 // move result within period
755 if ( resultInPeriod )
757 Standard_Real UF,UL,VF,VL;
758 surface->Bounds(UF,UL,VF,VL);
760 res.SetX( res.X() + ShapeAnalysis::AdjustToPeriod(res.X(),UF,UL));
762 res.SetY( res.Y() + ShapeAnalysis::AdjustToPeriod(res.Y(),VF,VL));
767 //=======================================================================
768 //function : GetMiddleUV
769 //purpose : Return middle UV taking in account surface period
770 //=======================================================================
772 gp_XY SMESH_MesherHelper::GetMiddleUV(const Handle(Geom_Surface)& surface,
777 // the proper place of getting basic surface seems to be in applyIn2D()
778 // but we put it here to decrease a risk of regressions just before releasing a version
779 Handle(Geom_Surface) surf = surface;
780 while ( !surf.IsNull() && surf->IsKind(STANDARD_TYPE(Geom_RectangularTrimmedSurface )))
781 surf = Handle(Geom_RectangularTrimmedSurface)::DownCast( surf )->BasisSurface();
783 return applyIn2D( surf, p1, p2, & AverageUV );
786 //=======================================================================
787 //function : GetNodeU
788 //purpose : Return node U on edge
789 //=======================================================================
791 double SMESH_MesherHelper::GetNodeU(const TopoDS_Edge& E,
792 const SMDS_MeshNode* n,
793 const SMDS_MeshNode* inEdgeNode,
797 const SMDS_PositionPtr pos = n->GetPosition();
798 if ( pos->GetTypeOfPosition()==SMDS_TOP_EDGE )
800 const SMDS_EdgePosition* epos = static_cast<const SMDS_EdgePosition*>( pos );
801 param = epos->GetUParameter();
803 else if( pos->GetTypeOfPosition() == SMDS_TOP_VERTEX )
805 if ( inEdgeNode && TopExp::FirstVertex( E ).IsSame( TopExp::LastVertex( E ))) // issue 0020128
808 BRep_Tool::Range( E, f,l );
809 double uInEdge = GetNodeU( E, inEdgeNode );
810 param = ( fabs( uInEdge - f ) < fabs( l - uInEdge )) ? f : l;
814 SMESHDS_Mesh * meshDS = GetMeshDS();
815 int vertexID = n->getshapeId();
816 const TopoDS_Vertex& V = TopoDS::Vertex(meshDS->IndexToShape(vertexID));
817 param = BRep_Tool::Parameter( V, E );
822 double tol = BRep_Tool::Tolerance( E );
823 double f,l; BRep_Tool::Range( E, f,l );
824 bool force = ( param < f-tol || param > l+tol );
825 if ( !force && pos->GetTypeOfPosition()==SMDS_TOP_EDGE )
826 force = ( GetMeshDS()->ShapeToIndex( E ) != n->getshapeId() );
828 *check = CheckNodeU( E, n, param, 2*tol, force );
833 //=======================================================================
834 //function : CheckNodeU
835 //purpose : Check and fix node U on an edge
836 // Return false if U is bad and could not be fixed
837 //=======================================================================
839 bool SMESH_MesherHelper::CheckNodeU(const TopoDS_Edge& E,
840 const SMDS_MeshNode* n,
844 double distXYZ[4]) const
846 int shapeID = n->getshapeId();
847 if ( force || toCheckPosOnShape( shapeID ))
849 TopLoc_Location loc; double f,l;
850 Handle(Geom_Curve) curve = BRep_Tool::Curve( E,loc,f,l );
851 if ( curve.IsNull() ) // degenerated edge
853 if ( u+tol < f || u-tol > l )
855 double r = Max( 0.5, 1 - tol*n->GetID()); // to get a unique u on edge
861 gp_Pnt nodePnt = SMESH_TNodeXYZ( n );
862 if ( !loc.IsIdentity() ) nodePnt.Transform( loc.Transformation().Inverted() );
863 gp_Pnt curvPnt = curve->Value( u );
864 double dist = nodePnt.Distance( curvPnt );
866 curvPnt.Transform( loc );
868 distXYZ[1] = curvPnt.X(); distXYZ[2] = curvPnt.Y(); distXYZ[3]=curvPnt.Z();
872 setPosOnShapeValidity( shapeID, false );
873 // u incorrect, project the node to the curve
874 int edgeID = GetMeshDS()->ShapeToIndex( E );
875 TID2ProjectorOnCurve& i2proj = const_cast< TID2ProjectorOnCurve&>( myEdge2Projector );
876 TID2ProjectorOnCurve::iterator i_proj =
877 i2proj.insert( make_pair( edgeID, (GeomAPI_ProjectPointOnCurve*) 0 )).first;
878 if ( !i_proj->second )
880 i_proj->second = new GeomAPI_ProjectPointOnCurve();
881 i_proj->second->Init( curve, f, l );
883 GeomAPI_ProjectPointOnCurve* projector = i_proj->second;
884 projector->Perform( nodePnt );
885 if ( projector->NbPoints() < 1 )
887 MESSAGE( "SMESH_MesherHelper::CheckNodeU() failed to project" );
890 Quantity_Parameter U = projector->LowerDistanceParameter();
892 curvPnt = curve->Value( u );
893 dist = nodePnt.Distance( curvPnt );
895 curvPnt.Transform( loc );
897 distXYZ[1] = curvPnt.X(); distXYZ[2] = curvPnt.Y(); distXYZ[3]=curvPnt.Z();
901 MESSAGE( "SMESH_MesherHelper::CheckNodeU(), invalid projection" );
902 MESSAGE("distance " << dist << " " << tol );
905 // store the fixed U on the edge
906 if ( myShape.IsSame(E) && shapeID == myShapeID && myFixNodeParameters )
907 const_cast<SMDS_MeshNode*>(n)->SetPosition
908 ( SMDS_PositionPtr( new SMDS_EdgePosition( U )));
910 else if ( fabs( u ) > numeric_limits<double>::min() )
912 setPosOnShapeValidity( shapeID, true );
914 if (( u < f-tol || u > l+tol ) && force )
916 // node is on vertex but is set on periodic but trimmed edge (issue 0020890)
919 // do not use IsPeriodic() as Geom_TrimmedCurve::IsPeriodic () returns false
920 double period = curve->Period();
921 u = ( u < f ) ? u + period : u - period;
923 catch (Standard_Failure& exc)
933 //=======================================================================
934 //function : GetMediumPos
935 //purpose : Return index and type of the shape (EDGE or FACE only) to
936 // set a medium node on
937 //=======================================================================
939 std::pair<int, TopAbs_ShapeEnum> SMESH_MesherHelper::GetMediumPos(const SMDS_MeshNode* n1,
940 const SMDS_MeshNode* n2)
942 TopAbs_ShapeEnum shapeType = TopAbs_SHAPE;
946 if (( myShapeID == n1->getshapeId() || myShapeID == n2->getshapeId() ) && myShapeID > 0 )
948 shapeType = myShape.ShapeType();
951 else if ( n1->getshapeId() == n2->getshapeId() )
953 shapeID = n2->getshapeId();
954 shape = GetSubShapeByNode( n1, GetMeshDS() );
958 const SMDS_TypeOfPosition Pos1 = n1->GetPosition()->GetTypeOfPosition();
959 const SMDS_TypeOfPosition Pos2 = n2->GetPosition()->GetTypeOfPosition();
961 if ( Pos1 == SMDS_TOP_3DSPACE || Pos2 == SMDS_TOP_3DSPACE )
964 else if ( Pos1 == SMDS_TOP_FACE || Pos2 == SMDS_TOP_FACE )
966 if ( Pos1 != SMDS_TOP_FACE || Pos2 != SMDS_TOP_FACE )
968 if ( Pos1 != SMDS_TOP_FACE ) std::swap( n1,n2 );
969 TopoDS_Shape F = GetSubShapeByNode( n1, GetMeshDS() );
970 TopoDS_Shape S = GetSubShapeByNode( n2, GetMeshDS() );
971 if ( IsSubShape( S, F ))
973 shapeType = TopAbs_FACE;
974 shapeID = n1->getshapeId();
978 else if ( Pos1 == SMDS_TOP_EDGE && Pos2 == SMDS_TOP_EDGE )
980 TopoDS_Shape E1 = GetSubShapeByNode( n1, GetMeshDS() );
981 TopoDS_Shape E2 = GetSubShapeByNode( n2, GetMeshDS() );
982 shape = GetCommonAncestor( E1, E2, *myMesh, TopAbs_FACE );
984 else if ( Pos1 == SMDS_TOP_VERTEX && Pos2 == SMDS_TOP_VERTEX )
986 TopoDS_Shape V1 = GetSubShapeByNode( n1, GetMeshDS() );
987 TopoDS_Shape V2 = GetSubShapeByNode( n2, GetMeshDS() );
988 shape = GetCommonAncestor( V1, V2, *myMesh, TopAbs_EDGE );
989 if ( shape.IsNull() ) shape = GetCommonAncestor( V1, V2, *myMesh, TopAbs_FACE );
991 else // VERTEX and EDGE
993 if ( Pos1 != SMDS_TOP_VERTEX ) std::swap( n1,n2 );
994 TopoDS_Shape V = GetSubShapeByNode( n1, GetMeshDS() );
995 TopoDS_Shape E = GetSubShapeByNode( n2, GetMeshDS() );
996 if ( IsSubShape( V, E ))
999 shape = GetCommonAncestor( V, E, *myMesh, TopAbs_FACE );
1003 if ( !shape.IsNull() )
1006 shapeID = GetMeshDS()->ShapeToIndex( shape );
1007 shapeType = shape.ShapeType();
1009 return make_pair( shapeID, shapeType );
1012 //=======================================================================
1013 //function : GetMediumNode
1014 //purpose : Return existing or create new medium nodes between given ones
1015 //=======================================================================
1017 const SMDS_MeshNode* SMESH_MesherHelper::GetMediumNode(const SMDS_MeshNode* n1,
1018 const SMDS_MeshNode* n2,
1021 // Find existing node
1023 SMESH_TLink link(n1,n2);
1024 ItTLinkNode itLN = myTLinkNodeMap.find( link );
1025 if ( itLN != myTLinkNodeMap.end() ) {
1026 return (*itLN).second;
1029 // Create medium node
1032 SMESHDS_Mesh* meshDS = GetMeshDS();
1034 if ( IsSeamShape( n1->getshapeId() ))
1035 // to get a correct UV of a node on seam, the second node must have checked UV
1036 std::swap( n1, n2 );
1038 // get type of shape for the new medium node
1039 int faceID = -1, edgeID = -1;
1040 TopoDS_Edge E; double u [2];
1041 TopoDS_Face F; gp_XY uv[2];
1042 bool uvOK[2] = { false, false };
1044 pair<int, TopAbs_ShapeEnum> pos = GetMediumPos( n1, n2 );
1046 // get positions of the given nodes on shapes
1047 if ( pos.second == TopAbs_FACE )
1049 F = TopoDS::Face(meshDS->IndexToShape( faceID = pos.first ));
1050 uv[0] = GetNodeUV(F,n1,n2, force3d ? 0 : &uvOK[0]);
1051 uv[1] = GetNodeUV(F,n2,n1, force3d ? 0 : &uvOK[1]);
1053 else if ( pos.second == TopAbs_EDGE )
1055 const SMDS_PositionPtr Pos1 = n1->GetPosition();
1056 const SMDS_PositionPtr Pos2 = n2->GetPosition();
1057 if ( Pos1->GetTypeOfPosition()==SMDS_TOP_EDGE &&
1058 Pos2->GetTypeOfPosition()==SMDS_TOP_EDGE &&
1059 n1->getshapeId() != n2->getshapeId() )
1062 return getMediumNodeOnComposedWire(n1,n2,force3d);
1064 E = TopoDS::Edge(meshDS->IndexToShape( edgeID = pos.first ));
1065 u[0] = GetNodeU(E,n1,n2, force3d ? 0 : &uvOK[0]);
1066 u[1] = GetNodeU(E,n2,n1, force3d ? 0 : &uvOK[1]);
1069 if ( !force3d & uvOK[0] && uvOK[1] )
1071 // we try to create medium node using UV parameters of
1072 // nodes, else - medium between corresponding 3d points
1075 //if ( uvOK[0] && uvOK[1] )
1077 if ( IsDegenShape( n1->getshapeId() )) {
1078 if ( myParIndex & U_periodic ) uv[0].SetCoord( 1, uv[1].Coord( 1 ));
1079 else uv[0].SetCoord( 2, uv[1].Coord( 2 ));
1081 else if ( IsDegenShape( n2->getshapeId() )) {
1082 if ( myParIndex & U_periodic ) uv[1].SetCoord( 1, uv[0].Coord( 1 ));
1083 else uv[1].SetCoord( 2, uv[0].Coord( 2 ));
1086 TopLoc_Location loc;
1087 Handle(Geom_Surface) S = BRep_Tool::Surface(F,loc);
1088 gp_XY UV = GetMiddleUV( S, uv[0], uv[1] );
1089 gp_Pnt P = S->Value( UV.X(), UV.Y() ).Transformed(loc);
1090 n12 = meshDS->AddNode(P.X(), P.Y(), P.Z());
1091 meshDS->SetNodeOnFace(n12, faceID, UV.X(), UV.Y());
1092 myTLinkNodeMap.insert(make_pair(link,n12));
1096 else if ( !E.IsNull() )
1099 Handle(Geom_Curve) C = BRep_Tool::Curve(E, f, l);
1102 Standard_Boolean isPeriodic = C->IsPeriodic();
1105 Standard_Real Period = C->Period();
1106 Standard_Real p = u[1]+ShapeAnalysis::AdjustByPeriod(u[1],u[0],Period);
1107 Standard_Real pmid = (u[0]+p)/2.;
1108 U = pmid+ShapeAnalysis::AdjustToPeriod(pmid,C->FirstParameter(),C->LastParameter());
1113 gp_Pnt P = C->Value( U );
1114 n12 = meshDS->AddNode(P.X(), P.Y(), P.Z());
1115 meshDS->SetNodeOnEdge(n12, edgeID, U);
1116 myTLinkNodeMap.insert(make_pair(link,n12));
1123 double x = ( n1->X() + n2->X() )/2.;
1124 double y = ( n1->Y() + n2->Y() )/2.;
1125 double z = ( n1->Z() + n2->Z() )/2.;
1126 n12 = meshDS->AddNode(x,y,z);
1130 gp_XY UV = ( uv[0] + uv[1] ) / 2.;
1131 CheckNodeUV( F, n12, UV, 2*BRep_Tool::Tolerance( F ), /*force=*/true);
1132 meshDS->SetNodeOnFace(n12, faceID, UV.X(), UV.Y() );
1134 else if ( !E.IsNull() )
1136 double U = ( u[0] + u[1] ) / 2.;
1137 CheckNodeU( E, n12, U, 2*BRep_Tool::Tolerance( E ), /*force=*/true);
1138 meshDS->SetNodeOnEdge(n12, edgeID, U);
1140 else if ( myShapeID > 0 )
1142 meshDS->SetNodeInVolume(n12, myShapeID);
1145 myTLinkNodeMap.insert( make_pair( link, n12 ));
1149 //================================================================================
1151 * \brief Makes a medium node if nodes reside different edges
1153 //================================================================================
1155 const SMDS_MeshNode* SMESH_MesherHelper::getMediumNodeOnComposedWire(const SMDS_MeshNode* n1,
1156 const SMDS_MeshNode* n2,
1159 gp_Pnt middle = 0.5 * XYZ(n1) + 0.5 * XYZ(n2);
1160 SMDS_MeshNode* n12 = AddNode( middle.X(), middle.Y(), middle.Z() );
1162 // To find position on edge and 3D position for n12,
1163 // project <middle> to 2 edges and select projection most close to <middle>
1165 double u = 0, distMiddleProj = Precision::Infinite(), distXYZ[4];
1167 TopoDS_Edge edges[2];
1168 for ( int is2nd = 0; is2nd < 2; ++is2nd )
1171 const SMDS_MeshNode* n = is2nd ? n2 : n1;
1172 TopoDS_Shape shape = GetSubShapeByNode( n, GetMeshDS() );
1173 if ( shape.IsNull() || shape.ShapeType() != TopAbs_EDGE )
1176 // project to get U of projection and distance from middle to projection
1177 TopoDS_Edge edge = edges[ is2nd ] = TopoDS::Edge( shape );
1178 double node2MiddleDist = middle.Distance( XYZ(n) );
1179 double foundU = GetNodeU( edge, n );
1180 CheckNodeU( edge, n12, foundU, 2*BRep_Tool::Tolerance(edge), /*force=*/true, distXYZ );
1181 if ( distXYZ[0] < node2MiddleDist )
1183 distMiddleProj = distXYZ[0];
1188 if ( Precision::IsInfinite( distMiddleProj ))
1190 // both projections failed; set n12 on the edge of n1 with U of a common vertex
1191 TopoDS_Vertex vCommon;
1192 if ( TopExp::CommonVertex( edges[0], edges[1], vCommon ))
1193 u = BRep_Tool::Parameter( vCommon, edges[0] );
1196 double f,l, u0 = GetNodeU( edges[0], n1 );
1197 BRep_Tool::Range( edges[0],f,l );
1198 u = ( fabs(u0-f) < fabs(u0-l) ) ? f : l;
1204 // move n12 to position of a successfull projection
1205 double tol = BRep_Tool::Tolerance(edges[ iOkEdge ]);
1206 if ( !force3d && distMiddleProj > 2*tol )
1208 TopLoc_Location loc; double f,l;
1209 Handle(Geom_Curve) curve = BRep_Tool::Curve( edges[iOkEdge],loc,f,l );
1210 gp_Pnt p = curve->Value( u );
1211 GetMeshDS()->MoveNode( n12, p.X(), p.Y(), p.Z() );
1214 GetMeshDS()->SetNodeOnEdge(n12, edges[iOkEdge], u);
1216 myTLinkNodeMap.insert( make_pair( SMESH_TLink(n1,n2), n12 ));
1221 //=======================================================================
1222 //function : AddNode
1223 //purpose : Creates a node
1224 //=======================================================================
1226 SMDS_MeshNode* SMESH_MesherHelper::AddNode(double x, double y, double z, int ID,
1229 SMESHDS_Mesh * meshDS = GetMeshDS();
1230 SMDS_MeshNode* node = 0;
1232 node = meshDS->AddNodeWithID( x, y, z, ID );
1234 node = meshDS->AddNode( x, y, z );
1235 if ( mySetElemOnShape && myShapeID > 0 ) {
1236 switch ( myShape.ShapeType() ) {
1237 case TopAbs_SOLID: meshDS->SetNodeInVolume( node, myShapeID); break;
1238 case TopAbs_SHELL: meshDS->SetNodeInVolume( node, myShapeID); break;
1239 case TopAbs_FACE: meshDS->SetNodeOnFace( node, myShapeID, u, v); break;
1240 case TopAbs_EDGE: meshDS->SetNodeOnEdge( node, myShapeID, u); break;
1241 case TopAbs_VERTEX: meshDS->SetNodeOnVertex( node, myShapeID); break;
1248 //=======================================================================
1249 //function : AddEdge
1250 //purpose : Creates quadratic or linear edge
1251 //=======================================================================
1253 SMDS_MeshEdge* SMESH_MesherHelper::AddEdge(const SMDS_MeshNode* n1,
1254 const SMDS_MeshNode* n2,
1258 SMESHDS_Mesh * meshDS = GetMeshDS();
1260 SMDS_MeshEdge* edge = 0;
1261 if (myCreateQuadratic) {
1262 const SMDS_MeshNode* n12 = GetMediumNode(n1,n2,force3d);
1264 edge = meshDS->AddEdgeWithID(n1, n2, n12, id);
1266 edge = meshDS->AddEdge(n1, n2, n12);
1270 edge = meshDS->AddEdgeWithID(n1, n2, id);
1272 edge = meshDS->AddEdge(n1, n2);
1275 if ( mySetElemOnShape && myShapeID > 0 )
1276 meshDS->SetMeshElementOnShape( edge, myShapeID );
1281 //=======================================================================
1282 //function : AddFace
1283 //purpose : Creates quadratic or linear triangle
1284 //=======================================================================
1286 SMDS_MeshFace* SMESH_MesherHelper::AddFace(const SMDS_MeshNode* n1,
1287 const SMDS_MeshNode* n2,
1288 const SMDS_MeshNode* n3,
1292 SMESHDS_Mesh * meshDS = GetMeshDS();
1293 SMDS_MeshFace* elem = 0;
1295 if( n1==n2 || n2==n3 || n3==n1 )
1298 if(!myCreateQuadratic) {
1300 elem = meshDS->AddFaceWithID(n1, n2, n3, id);
1302 elem = meshDS->AddFace(n1, n2, n3);
1305 const SMDS_MeshNode* n12 = GetMediumNode(n1,n2,force3d);
1306 const SMDS_MeshNode* n23 = GetMediumNode(n2,n3,force3d);
1307 const SMDS_MeshNode* n31 = GetMediumNode(n3,n1,force3d);
1310 elem = meshDS->AddFaceWithID(n1, n2, n3, n12, n23, n31, id);
1312 elem = meshDS->AddFace(n1, n2, n3, n12, n23, n31);
1314 if ( mySetElemOnShape && myShapeID > 0 )
1315 meshDS->SetMeshElementOnShape( elem, myShapeID );
1320 //=======================================================================
1321 //function : AddFace
1322 //purpose : Creates quadratic or linear quadrangle
1323 //=======================================================================
1325 SMDS_MeshFace* SMESH_MesherHelper::AddFace(const SMDS_MeshNode* n1,
1326 const SMDS_MeshNode* n2,
1327 const SMDS_MeshNode* n3,
1328 const SMDS_MeshNode* n4,
1332 SMESHDS_Mesh * meshDS = GetMeshDS();
1333 SMDS_MeshFace* elem = 0;
1336 return AddFace(n1,n3,n4,id,force3d);
1339 return AddFace(n1,n2,n4,id,force3d);
1342 return AddFace(n1,n2,n3,id,force3d);
1345 return AddFace(n1,n2,n4,id,force3d);
1348 return AddFace(n1,n2,n3,id,force3d);
1351 return AddFace(n1,n2,n3,id,force3d);
1354 if(!myCreateQuadratic) {
1356 elem = meshDS->AddFaceWithID(n1, n2, n3, n4, id);
1358 elem = meshDS->AddFace(n1, n2, n3, n4);
1361 const SMDS_MeshNode* n12 = GetMediumNode(n1,n2,force3d);
1362 const SMDS_MeshNode* n23 = GetMediumNode(n2,n3,force3d);
1363 const SMDS_MeshNode* n34 = GetMediumNode(n3,n4,force3d);
1364 const SMDS_MeshNode* n41 = GetMediumNode(n4,n1,force3d);
1367 elem = meshDS->AddFaceWithID(n1, n2, n3, n4, n12, n23, n34, n41, id);
1369 elem = meshDS->AddFace(n1, n2, n3, n4, n12, n23, n34, n41);
1371 if ( mySetElemOnShape && myShapeID > 0 )
1372 meshDS->SetMeshElementOnShape( elem, myShapeID );
1377 //=======================================================================
1378 //function : AddPolygonalFace
1379 //purpose : Creates polygon, with additional nodes in quadratic mesh
1380 //=======================================================================
1382 SMDS_MeshFace* SMESH_MesherHelper::AddPolygonalFace (const vector<const SMDS_MeshNode*>& nodes,
1386 SMESHDS_Mesh * meshDS = GetMeshDS();
1387 SMDS_MeshFace* elem = 0;
1389 if(!myCreateQuadratic) {
1391 elem = meshDS->AddPolygonalFaceWithID(nodes, id);
1393 elem = meshDS->AddPolygonalFace(nodes);
1396 vector<const SMDS_MeshNode*> newNodes;
1397 for ( int i = 0; i < nodes.size(); ++i )
1399 const SMDS_MeshNode* n1 = nodes[i];
1400 const SMDS_MeshNode* n2 = nodes[(i+1)%nodes.size()];
1401 const SMDS_MeshNode* n12 = GetMediumNode(n1,n2,force3d);
1402 newNodes.push_back( n1 );
1403 newNodes.push_back( n12 );
1406 elem = meshDS->AddPolygonalFaceWithID(newNodes, id);
1408 elem = meshDS->AddPolygonalFace(newNodes);
1410 if ( mySetElemOnShape && myShapeID > 0 )
1411 meshDS->SetMeshElementOnShape( elem, myShapeID );
1416 //=======================================================================
1417 //function : AddVolume
1418 //purpose : Creates quadratic or linear prism
1419 //=======================================================================
1421 SMDS_MeshVolume* SMESH_MesherHelper::AddVolume(const SMDS_MeshNode* n1,
1422 const SMDS_MeshNode* n2,
1423 const SMDS_MeshNode* n3,
1424 const SMDS_MeshNode* n4,
1425 const SMDS_MeshNode* n5,
1426 const SMDS_MeshNode* n6,
1430 SMESHDS_Mesh * meshDS = GetMeshDS();
1431 SMDS_MeshVolume* elem = 0;
1432 if(!myCreateQuadratic) {
1434 elem = meshDS->AddVolumeWithID(n1, n2, n3, n4, n5, n6, id);
1436 elem = meshDS->AddVolume(n1, n2, n3, n4, n5, n6);
1439 const SMDS_MeshNode* n12 = GetMediumNode(n1,n2,force3d);
1440 const SMDS_MeshNode* n23 = GetMediumNode(n2,n3,force3d);
1441 const SMDS_MeshNode* n31 = GetMediumNode(n3,n1,force3d);
1443 const SMDS_MeshNode* n45 = GetMediumNode(n4,n5,force3d);
1444 const SMDS_MeshNode* n56 = GetMediumNode(n5,n6,force3d);
1445 const SMDS_MeshNode* n64 = GetMediumNode(n6,n4,force3d);
1447 const SMDS_MeshNode* n14 = GetMediumNode(n1,n4,force3d);
1448 const SMDS_MeshNode* n25 = GetMediumNode(n2,n5,force3d);
1449 const SMDS_MeshNode* n36 = GetMediumNode(n3,n6,force3d);
1452 elem = meshDS->AddVolumeWithID(n1, n2, n3, n4, n5, n6,
1453 n12, n23, n31, n45, n56, n64, n14, n25, n36, id);
1455 elem = meshDS->AddVolume(n1, n2, n3, n4, n5, n6,
1456 n12, n23, n31, n45, n56, n64, n14, n25, n36);
1458 if ( mySetElemOnShape && myShapeID > 0 )
1459 meshDS->SetMeshElementOnShape( elem, myShapeID );
1464 //=======================================================================
1465 //function : AddVolume
1466 //purpose : Creates quadratic or linear tetrahedron
1467 //=======================================================================
1469 SMDS_MeshVolume* SMESH_MesherHelper::AddVolume(const SMDS_MeshNode* n1,
1470 const SMDS_MeshNode* n2,
1471 const SMDS_MeshNode* n3,
1472 const SMDS_MeshNode* n4,
1476 SMESHDS_Mesh * meshDS = GetMeshDS();
1477 SMDS_MeshVolume* elem = 0;
1478 if(!myCreateQuadratic) {
1480 elem = meshDS->AddVolumeWithID(n1, n2, n3, n4, id);
1482 elem = meshDS->AddVolume(n1, n2, n3, n4);
1485 const SMDS_MeshNode* n12 = GetMediumNode(n1,n2,force3d);
1486 const SMDS_MeshNode* n23 = GetMediumNode(n2,n3,force3d);
1487 const SMDS_MeshNode* n31 = GetMediumNode(n3,n1,force3d);
1489 const SMDS_MeshNode* n14 = GetMediumNode(n1,n4,force3d);
1490 const SMDS_MeshNode* n24 = GetMediumNode(n2,n4,force3d);
1491 const SMDS_MeshNode* n34 = GetMediumNode(n3,n4,force3d);
1494 elem = meshDS->AddVolumeWithID(n1, n2, n3, n4, n12, n23, n31, n14, n24, n34, id);
1496 elem = meshDS->AddVolume(n1, n2, n3, n4, n12, n23, n31, n14, n24, n34);
1498 if ( mySetElemOnShape && myShapeID > 0 )
1499 meshDS->SetMeshElementOnShape( elem, myShapeID );
1504 //=======================================================================
1505 //function : AddVolume
1506 //purpose : Creates quadratic or linear pyramid
1507 //=======================================================================
1509 SMDS_MeshVolume* SMESH_MesherHelper::AddVolume(const SMDS_MeshNode* n1,
1510 const SMDS_MeshNode* n2,
1511 const SMDS_MeshNode* n3,
1512 const SMDS_MeshNode* n4,
1513 const SMDS_MeshNode* n5,
1517 SMDS_MeshVolume* elem = 0;
1518 if(!myCreateQuadratic) {
1520 elem = GetMeshDS()->AddVolumeWithID(n1, n2, n3, n4, n5, id);
1522 elem = GetMeshDS()->AddVolume(n1, n2, n3, n4, n5);
1525 const SMDS_MeshNode* n12 = GetMediumNode(n1,n2,force3d);
1526 const SMDS_MeshNode* n23 = GetMediumNode(n2,n3,force3d);
1527 const SMDS_MeshNode* n34 = GetMediumNode(n3,n4,force3d);
1528 const SMDS_MeshNode* n41 = GetMediumNode(n4,n1,force3d);
1530 const SMDS_MeshNode* n15 = GetMediumNode(n1,n5,force3d);
1531 const SMDS_MeshNode* n25 = GetMediumNode(n2,n5,force3d);
1532 const SMDS_MeshNode* n35 = GetMediumNode(n3,n5,force3d);
1533 const SMDS_MeshNode* n45 = GetMediumNode(n4,n5,force3d);
1536 elem = GetMeshDS()->AddVolumeWithID ( n1, n2, n3, n4, n5,
1541 elem = GetMeshDS()->AddVolume( n1, n2, n3, n4, n5,
1543 n15, n25, n35, n45);
1545 if ( mySetElemOnShape && myShapeID > 0 )
1546 GetMeshDS()->SetMeshElementOnShape( elem, myShapeID );
1551 //=======================================================================
1552 //function : AddVolume
1553 //purpose : Creates quadratic or linear hexahedron
1554 //=======================================================================
1556 SMDS_MeshVolume* SMESH_MesherHelper::AddVolume(const SMDS_MeshNode* n1,
1557 const SMDS_MeshNode* n2,
1558 const SMDS_MeshNode* n3,
1559 const SMDS_MeshNode* n4,
1560 const SMDS_MeshNode* n5,
1561 const SMDS_MeshNode* n6,
1562 const SMDS_MeshNode* n7,
1563 const SMDS_MeshNode* n8,
1567 SMESHDS_Mesh * meshDS = GetMeshDS();
1568 SMDS_MeshVolume* elem = 0;
1569 if(!myCreateQuadratic) {
1571 elem = meshDS->AddVolumeWithID(n1, n2, n3, n4, n5, n6, n7, n8, id);
1573 elem = meshDS->AddVolume(n1, n2, n3, n4, n5, n6, n7, n8);
1576 const SMDS_MeshNode* n12 = GetMediumNode(n1,n2,force3d);
1577 const SMDS_MeshNode* n23 = GetMediumNode(n2,n3,force3d);
1578 const SMDS_MeshNode* n34 = GetMediumNode(n3,n4,force3d);
1579 const SMDS_MeshNode* n41 = GetMediumNode(n4,n1,force3d);
1581 const SMDS_MeshNode* n56 = GetMediumNode(n5,n6,force3d);
1582 const SMDS_MeshNode* n67 = GetMediumNode(n6,n7,force3d);
1583 const SMDS_MeshNode* n78 = GetMediumNode(n7,n8,force3d);
1584 const SMDS_MeshNode* n85 = GetMediumNode(n8,n5,force3d);
1586 const SMDS_MeshNode* n15 = GetMediumNode(n1,n5,force3d);
1587 const SMDS_MeshNode* n26 = GetMediumNode(n2,n6,force3d);
1588 const SMDS_MeshNode* n37 = GetMediumNode(n3,n7,force3d);
1589 const SMDS_MeshNode* n48 = GetMediumNode(n4,n8,force3d);
1592 elem = meshDS->AddVolumeWithID(n1, n2, n3, n4, n5, n6, n7, n8,
1593 n12, n23, n34, n41, n56, n67,
1594 n78, n85, n15, n26, n37, n48, id);
1596 elem = meshDS->AddVolume(n1, n2, n3, n4, n5, n6, n7, n8,
1597 n12, n23, n34, n41, n56, n67,
1598 n78, n85, n15, n26, n37, n48);
1600 if ( mySetElemOnShape && myShapeID > 0 )
1601 meshDS->SetMeshElementOnShape( elem, myShapeID );
1606 //=======================================================================
1607 //function : AddVolume
1608 //purpose : Creates LINEAR!!!!!!!!! octahedron
1609 //=======================================================================
1611 SMDS_MeshVolume* SMESH_MesherHelper::AddVolume(const SMDS_MeshNode* n1,
1612 const SMDS_MeshNode* n2,
1613 const SMDS_MeshNode* n3,
1614 const SMDS_MeshNode* n4,
1615 const SMDS_MeshNode* n5,
1616 const SMDS_MeshNode* n6,
1617 const SMDS_MeshNode* n7,
1618 const SMDS_MeshNode* n8,
1619 const SMDS_MeshNode* n9,
1620 const SMDS_MeshNode* n10,
1621 const SMDS_MeshNode* n11,
1622 const SMDS_MeshNode* n12,
1626 SMESHDS_Mesh * meshDS = GetMeshDS();
1627 SMDS_MeshVolume* elem = 0;
1629 elem = meshDS->AddVolumeWithID(n1,n2,n3,n4,n5,n6,n7,n8,n9,n10,n11,n12,id);
1631 elem = meshDS->AddVolume(n1,n2,n3,n4,n5,n6,n7,n8,n9,n10,n11,n12);
1632 if ( mySetElemOnShape && myShapeID > 0 )
1633 meshDS->SetMeshElementOnShape( elem, myShapeID );
1637 //=======================================================================
1638 //function : AddPolyhedralVolume
1639 //purpose : Creates polyhedron. In quadratic mesh, adds medium nodes
1640 //=======================================================================
1643 SMESH_MesherHelper::AddPolyhedralVolume (const std::vector<const SMDS_MeshNode*>& nodes,
1644 const std::vector<int>& quantities,
1648 SMESHDS_Mesh * meshDS = GetMeshDS();
1649 SMDS_MeshVolume* elem = 0;
1650 if(!myCreateQuadratic)
1653 elem = meshDS->AddPolyhedralVolumeWithID(nodes, quantities, id);
1655 elem = meshDS->AddPolyhedralVolume(nodes, quantities);
1659 vector<const SMDS_MeshNode*> newNodes;
1660 vector<int> newQuantities;
1661 for ( int iFace=0, iN=0; iFace < quantities.size(); ++iFace)
1663 int nbNodesInFace = quantities[iFace];
1664 newQuantities.push_back(0);
1665 for ( int i = 0; i < nbNodesInFace; ++i )
1667 const SMDS_MeshNode* n1 = nodes[ iN + i ];
1668 newNodes.push_back( n1 );
1669 newQuantities.back()++;
1671 const SMDS_MeshNode* n2 = nodes[ iN + ( i+1==nbNodesInFace ? 0 : i+1 )];
1672 // if ( n1->GetPosition()->GetTypeOfPosition() != SMDS_TOP_3DSPACE &&
1673 // n2->GetPosition()->GetTypeOfPosition() != SMDS_TOP_3DSPACE )
1675 const SMDS_MeshNode* n12 = GetMediumNode(n1,n2,force3d);
1676 newNodes.push_back( n12 );
1677 newQuantities.back()++;
1680 iN += nbNodesInFace;
1683 elem = meshDS->AddPolyhedralVolumeWithID( newNodes, newQuantities, id );
1685 elem = meshDS->AddPolyhedralVolume( newNodes, newQuantities );
1687 if ( mySetElemOnShape && myShapeID > 0 )
1688 meshDS->SetMeshElementOnShape( elem, myShapeID );
1695 //================================================================================
1697 * \brief Check if a node belongs to any face of sub-mesh
1699 //================================================================================
1701 bool isNodeInSubMesh( const SMDS_MeshNode* n, const SMESHDS_SubMesh* sm )
1703 SMDS_ElemIteratorPtr fIt = n->GetInverseElementIterator( SMDSAbs_Face );
1704 while ( fIt->more() )
1705 if ( sm->Contains( fIt->next() ))
1711 //=======================================================================
1712 //function : IsSameElemGeometry
1713 //purpose : Returns true if all elements of a sub-mesh are of same shape
1714 //=======================================================================
1716 bool SMESH_MesherHelper::IsSameElemGeometry(const SMESHDS_SubMesh* smDS,
1717 SMDSAbs_GeometryType shape,
1718 const bool nullSubMeshRes)
1720 if ( !smDS ) return nullSubMeshRes;
1722 SMDS_ElemIteratorPtr elemIt = smDS->GetElements();
1723 while ( elemIt->more() )
1724 if ( elemIt->next()->GetGeomType() != shape )
1730 //=======================================================================
1731 //function : LoadNodeColumns
1732 //purpose : Load nodes bound to face into a map of node columns
1733 //=======================================================================
1735 bool SMESH_MesherHelper::LoadNodeColumns(TParam2ColumnMap & theParam2ColumnMap,
1736 const TopoDS_Face& theFace,
1737 const TopoDS_Edge& theBaseEdge,
1738 SMESHDS_Mesh* theMesh,
1739 SMESH_ProxyMesh* theProxyMesh)
1741 return LoadNodeColumns(theParam2ColumnMap,
1743 std::list<TopoDS_Edge>(1,theBaseEdge),
1748 //=======================================================================
1749 //function : LoadNodeColumns
1750 //purpose : Load nodes bound to face into a map of node columns
1751 //=======================================================================
1753 bool SMESH_MesherHelper::LoadNodeColumns(TParam2ColumnMap & theParam2ColumnMap,
1754 const TopoDS_Face& theFace,
1755 const std::list<TopoDS_Edge>& theBaseSide,
1756 SMESHDS_Mesh* theMesh,
1757 SMESH_ProxyMesh* theProxyMesh)
1759 // get a right sub-mesh of theFace
1761 const SMESHDS_SubMesh* faceSubMesh = 0;
1764 faceSubMesh = theProxyMesh->GetSubMesh( theFace );
1765 if ( !faceSubMesh ||
1766 faceSubMesh->NbElements() == 0 ||
1767 theProxyMesh->IsTemporary( faceSubMesh->GetElements()->next() ))
1769 // can use a proxy sub-mesh with not temporary elements only
1775 faceSubMesh = theMesh->MeshElements( theFace );
1776 if ( !faceSubMesh || faceSubMesh->NbElements() == 0 )
1779 if ( theParam2ColumnMap.empty() )
1781 // get data of edges for normalization of params
1783 vector< double > length;
1785 list<TopoDS_Edge>::const_iterator edge;
1787 for ( edge = theBaseSide.begin(); edge != theBaseSide.end(); ++edge )
1789 double len = std::max( 1e-10, SMESH_Algo::EdgeLength( *edge ));
1791 length.push_back( len );
1795 // get nodes on theBaseEdge sorted by param on edge and initialize theParam2ColumnMap with them
1796 edge = theBaseSide.begin();
1797 for ( int iE = 0; edge != theBaseSide.end(); ++edge, ++iE )
1799 map< double, const SMDS_MeshNode*> sortedBaseNN;
1800 SMESH_Algo::GetSortedNodesOnEdge( theMesh, *edge,/*noMedium=*/true, sortedBaseNN);
1801 if ( sortedBaseNN.empty() ) continue;
1803 map< double, const SMDS_MeshNode*>::iterator u_n = sortedBaseNN.begin();
1804 if ( theProxyMesh ) // from sortedBaseNN remove nodes not shared by faces of faceSubMesh
1806 const SMDS_MeshNode* n1 = sortedBaseNN.begin()->second;
1807 const SMDS_MeshNode* n2 = sortedBaseNN.rbegin()->second;
1808 bool allNodesAreProxy = ( n1 != theProxyMesh->GetProxyNode( n1 ) &&
1809 n2 != theProxyMesh->GetProxyNode( n2 ));
1810 if ( allNodesAreProxy )
1811 for ( u_n = sortedBaseNN.begin(); u_n != sortedBaseNN.end(); u_n++ )
1812 u_n->second = theProxyMesh->GetProxyNode( u_n->second );
1814 if ( u_n = sortedBaseNN.begin(), !isNodeInSubMesh( u_n->second, faceSubMesh ))
1816 while ( ++u_n != sortedBaseNN.end() && !isNodeInSubMesh( u_n->second, faceSubMesh ));
1817 sortedBaseNN.erase( sortedBaseNN.begin(), u_n );
1819 else if ( u_n = --sortedBaseNN.end(), !isNodeInSubMesh( u_n->second, faceSubMesh ))
1821 while ( u_n != sortedBaseNN.begin() && !isNodeInSubMesh( (--u_n)->second, faceSubMesh ));
1822 sortedBaseNN.erase( ++u_n, sortedBaseNN.end() );
1824 if ( sortedBaseNN.empty() ) continue;
1828 BRep_Tool::Range( *edge, f, l );
1829 if ( edge->Orientation() == TopAbs_REVERSED ) std::swap( f, l );
1830 const double coeff = 1. / ( l - f ) * length[iE] / fullLen;
1831 const double prevPar = theParam2ColumnMap.empty() ? 0 : theParam2ColumnMap.rbegin()->first;
1832 for ( u_n = sortedBaseNN.begin(); u_n != sortedBaseNN.end(); u_n++ )
1834 double par = prevPar + coeff * ( u_n->first - f );
1835 TParam2ColumnMap::iterator u2nn =
1836 theParam2ColumnMap.insert( theParam2ColumnMap.end(), make_pair( par, TNodeColumn()));
1837 u2nn->second.push_back( u_n->second );
1840 if ( theParam2ColumnMap.empty() )
1845 int prevNbRows = theParam2ColumnMap.begin()->second.size(); // current, at least 1 here
1846 int expectedNbRows = faceSubMesh->NbElements() / ( theParam2ColumnMap.size()-1 ); // to be added
1848 // fill theParam2ColumnMap column by column by passing from nodes on
1849 // theBaseEdge up via mesh faces on theFace
1851 TParam2ColumnMap::iterator par_nVec_1, par_nVec_2;
1852 par_nVec_2 = theParam2ColumnMap.begin();
1853 par_nVec_1 = par_nVec_2++;
1854 TIDSortedElemSet emptySet, avoidSet;
1855 for ( ; par_nVec_2 != theParam2ColumnMap.end(); ++par_nVec_1, ++par_nVec_2 )
1857 vector<const SMDS_MeshNode*>& nCol1 = par_nVec_1->second;
1858 vector<const SMDS_MeshNode*>& nCol2 = par_nVec_2->second;
1859 nCol1.resize( prevNbRows + expectedNbRows );
1860 nCol2.resize( prevNbRows + expectedNbRows );
1862 int i1, i2, foundNbRows = 0;
1863 const SMDS_MeshNode *n1 = nCol1[ prevNbRows-1 ];
1864 const SMDS_MeshNode *n2 = nCol2[ prevNbRows-1 ];
1865 // find face sharing node n1 and n2 and belonging to faceSubMesh
1866 while ( const SMDS_MeshElement* face =
1867 SMESH_MeshEditor::FindFaceInSet( n1, n2, emptySet, avoidSet, &i1, &i2))
1869 if ( faceSubMesh->Contains( face ))
1871 int nbNodes = face->NbCornerNodes();
1874 if ( foundNbRows + 1 > expectedNbRows )
1876 n1 = face->GetNode( (i2+2) % 4 ); // opposite corner of quadrangle face
1877 n2 = face->GetNode( (i1+2) % 4 );
1878 nCol1[ prevNbRows + foundNbRows] = n1;
1879 nCol2[ prevNbRows + foundNbRows] = n2;
1882 avoidSet.insert( face );
1884 if ( foundNbRows != expectedNbRows )
1888 return ( theParam2ColumnMap.size() > 1 &&
1889 theParam2ColumnMap.begin()->second.size() == prevNbRows + expectedNbRows );
1894 //================================================================================
1896 * \brief Return true if a node is at a corner of a 2D structured mesh of FACE
1898 //================================================================================
1900 bool isCornerOfStructure( const SMDS_MeshNode* n,
1901 const SMESHDS_SubMesh* faceSM )
1903 int nbFacesInSM = 0;
1905 SMDS_ElemIteratorPtr fIt = n->GetInverseElementIterator( SMDSAbs_Face );
1906 while ( fIt->more() )
1907 nbFacesInSM += faceSM->Contains( fIt->next() );
1909 return ( nbFacesInSM == 1 );
1913 //=======================================================================
1914 //function : IsStructured
1915 //purpose : Return true if 2D mesh on FACE is structured
1916 //=======================================================================
1918 bool SMESH_MesherHelper::IsStructured( SMESH_subMesh* faceSM )
1920 SMESHDS_SubMesh* fSM = faceSM->GetSubMeshDS();
1921 if ( !fSM || fSM->NbElements() == 0 )
1924 list< TopoDS_Edge > edges;
1925 list< int > nbEdgesInWires;
1926 int nbWires = SMESH_Block::GetOrderedEdges( TopoDS::Face( faceSM->GetSubShape() ),
1927 edges, nbEdgesInWires );
1931 // algo: find corners of a structure and then analyze nb of faces and
1932 // length of structure sides
1934 SMESHDS_Mesh* meshDS = faceSM->GetFather()->GetMeshDS();
1936 // rotate edges to get the first node being at corner
1937 // (in principle it's not necessary but so far none SALOME algo can make
1938 // such a structured mesh that all corner nodes are not on VERTEXes)
1939 bool isCorner = false;
1940 int nbRemainEdges = nbEdgesInWires.front();
1942 TopoDS_Vertex V = IthVertex( 0, edges.front() );
1943 isCorner = isCornerOfStructure( SMESH_Algo::VertexNode( V, meshDS ), fSM);
1945 edges.splice( edges.end(), edges, edges.begin() );
1949 while ( !isCorner && nbRemainEdges > 0 );
1954 // get all nodes from EDGEs
1955 list< const SMDS_MeshNode* > nodes;
1956 list< TopoDS_Edge >::iterator edge = edges.begin();
1957 for ( ; edge != edges.end(); ++edge )
1959 map< double, const SMDS_MeshNode* > u2Nodes;
1960 if ( !SMESH_Algo::GetSortedNodesOnEdge( meshDS, *edge,
1961 /*skipMedium=*/true, u2Nodes ))
1964 list< const SMDS_MeshNode* > edgeNodes;
1965 map< double, const SMDS_MeshNode* >::iterator u2n = u2Nodes.begin();
1966 if ( !nodes.empty() && nodes.back() == u2n->second )
1968 map< double, const SMDS_MeshNode* >::iterator u2nEnd = --u2Nodes.end();
1969 if ( nodes.empty() || nodes.back() != u2nEnd->second )
1971 for ( ; u2n != u2nEnd; ++u2n )
1972 edgeNodes.push_back( u2n->second );
1974 if ( edge->Orientation() == TopAbs_REVERSED )
1975 edgeNodes.reverse();
1976 nodes.splice( nodes.end(), edgeNodes, edgeNodes.begin(), edgeNodes.end() );
1979 // get length of structured sides
1980 vector<int> nbEdgesInSide;
1982 list< const SMDS_MeshNode* >::iterator n = ++nodes.begin();
1983 for ( ; n != nodes.end(); ++n )
1986 if ( isCornerOfStructure( *n, fSM )) {
1987 nbEdgesInSide.push_back( nbEdges );
1993 if ( nbEdgesInSide.size() != 4 )
1995 if ( nbEdgesInSide[0] != nbEdgesInSide[2] )
1997 if ( nbEdgesInSide[1] != nbEdgesInSide[3] )
1999 if ( nbEdgesInSide[0] * nbEdgesInSide[1] != fSM->NbElements() )
2005 //=======================================================================
2007 //purpose : Count nb of sub-shapes
2008 //=======================================================================
2010 int SMESH_MesherHelper::Count(const TopoDS_Shape& shape,
2011 const TopAbs_ShapeEnum type,
2012 const bool ignoreSame)
2015 TopTools_IndexedMapOfShape map;
2016 TopExp::MapShapes( shape, type, map );
2017 return map.Extent();
2021 for ( TopExp_Explorer exp( shape, type ); exp.More(); exp.Next() )
2027 //=======================================================================
2028 //function : NbAncestors
2029 //purpose : Return number of unique ancestors of the shape
2030 //=======================================================================
2032 int SMESH_MesherHelper::NbAncestors(const TopoDS_Shape& shape,
2033 const SMESH_Mesh& mesh,
2034 TopAbs_ShapeEnum ancestorType/*=TopAbs_SHAPE*/)
2036 TopTools_MapOfShape ancestors;
2037 TopTools_ListIteratorOfListOfShape ansIt( mesh.GetAncestors(shape) );
2038 for ( ; ansIt.More(); ansIt.Next() ) {
2039 if ( ancestorType == TopAbs_SHAPE || ansIt.Value().ShapeType() == ancestorType )
2040 ancestors.Add( ansIt.Value() );
2042 return ancestors.Extent();
2045 //=======================================================================
2046 //function : GetSubShapeOri
2047 //purpose : Return orientation of sub-shape in the main shape
2048 //=======================================================================
2050 TopAbs_Orientation SMESH_MesherHelper::GetSubShapeOri(const TopoDS_Shape& shape,
2051 const TopoDS_Shape& subShape)
2053 TopAbs_Orientation ori = TopAbs_Orientation(-1);
2054 if ( !shape.IsNull() && !subShape.IsNull() )
2056 TopExp_Explorer e( shape, subShape.ShapeType() );
2057 if ( shape.Orientation() >= TopAbs_INTERNAL ) // TopAbs_INTERNAL or TopAbs_EXTERNAL
2058 e.Init( shape.Oriented(TopAbs_FORWARD), subShape.ShapeType() );
2059 for ( ; e.More(); e.Next())
2060 if ( subShape.IsSame( e.Current() ))
2063 ori = e.Current().Orientation();
2068 //=======================================================================
2069 //function : IsSubShape
2071 //=======================================================================
2073 bool SMESH_MesherHelper::IsSubShape( const TopoDS_Shape& shape,
2074 const TopoDS_Shape& mainShape )
2076 if ( !shape.IsNull() && !mainShape.IsNull() )
2078 for ( TopExp_Explorer exp( mainShape, shape.ShapeType());
2081 if ( shape.IsSame( exp.Current() ))
2084 SCRUTE((shape.IsNull()));
2085 SCRUTE((mainShape.IsNull()));
2089 //=======================================================================
2090 //function : IsSubShape
2092 //=======================================================================
2094 bool SMESH_MesherHelper::IsSubShape( const TopoDS_Shape& shape, SMESH_Mesh* aMesh )
2096 if ( shape.IsNull() || !aMesh )
2099 aMesh->GetMeshDS()->ShapeToIndex( shape ) ||
2101 (shape.ShapeType() == TopAbs_COMPOUND && aMesh->GetMeshDS()->IsGroupOfSubShapes( shape ));
2104 //================================================================================
2106 * \brief Return maximal tolerance of shape
2108 //================================================================================
2110 double SMESH_MesherHelper::MaxTolerance( const TopoDS_Shape& shape )
2112 double tol = Precision::Confusion();
2113 TopExp_Explorer exp;
2114 for ( exp.Init( shape, TopAbs_FACE ); exp.More(); exp.Next() )
2115 tol = Max( tol, BRep_Tool::Tolerance( TopoDS::Face( exp.Current())));
2116 for ( exp.Init( shape, TopAbs_EDGE ); exp.More(); exp.Next() )
2117 tol = Max( tol, BRep_Tool::Tolerance( TopoDS::Edge( exp.Current())));
2118 for ( exp.Init( shape, TopAbs_VERTEX ); exp.More(); exp.Next() )
2119 tol = Max( tol, BRep_Tool::Tolerance( TopoDS::Vertex( exp.Current())));
2124 //================================================================================
2126 * \brief Check if the first and last vertices of an edge are the same
2127 * \param anEdge - the edge to check
2128 * \retval bool - true if same
2130 //================================================================================
2132 bool SMESH_MesherHelper::IsClosedEdge( const TopoDS_Edge& anEdge )
2134 if ( anEdge.Orientation() >= TopAbs_INTERNAL )
2135 return IsClosedEdge( TopoDS::Edge( anEdge.Oriented( TopAbs_FORWARD )));
2136 return TopExp::FirstVertex( anEdge ).IsSame( TopExp::LastVertex( anEdge ));
2139 //================================================================================
2141 * \brief Wrapper over TopExp::FirstVertex() and TopExp::LastVertex() fixing them
2142 * in the case of INTERNAL edge
2144 //================================================================================
2146 TopoDS_Vertex SMESH_MesherHelper::IthVertex( const bool is2nd,
2150 if ( anEdge.Orientation() >= TopAbs_INTERNAL )
2151 anEdge.Orientation( TopAbs_FORWARD );
2153 const TopAbs_Orientation tgtOri = is2nd ? TopAbs_REVERSED : TopAbs_FORWARD;
2154 TopoDS_Iterator vIt( anEdge, CumOri );
2155 while ( vIt.More() && vIt.Value().Orientation() != tgtOri )
2158 return ( vIt.More() ? TopoDS::Vertex(vIt.Value()) : TopoDS_Vertex() );
2161 //================================================================================
2163 * \brief Return type of shape contained in a group
2164 * \param group - a shape of type TopAbs_COMPOUND
2165 * \param avoidCompound - not to return TopAbs_COMPOUND
2167 //================================================================================
2169 TopAbs_ShapeEnum SMESH_MesherHelper::GetGroupType(const TopoDS_Shape& group,
2170 const bool avoidCompound)
2172 if ( !group.IsNull() )
2174 if ( group.ShapeType() != TopAbs_COMPOUND )
2175 return group.ShapeType();
2177 // iterate on a compound
2178 TopoDS_Iterator it( group );
2180 return avoidCompound ? GetGroupType( it.Value() ) : it.Value().ShapeType();
2182 return TopAbs_SHAPE;
2185 //=======================================================================
2186 //function : IsQuadraticMesh
2187 //purpose : Check mesh without geometry for: if all elements on this shape are quadratic,
2188 // quadratic elements will be created.
2189 // Used then generated 3D mesh without geometry.
2190 //=======================================================================
2192 SMESH_MesherHelper:: MType SMESH_MesherHelper::IsQuadraticMesh()
2194 int NbAllEdgsAndFaces=0;
2195 int NbQuadFacesAndEdgs=0;
2196 int NbFacesAndEdges=0;
2197 //All faces and edges
2198 NbAllEdgsAndFaces = myMesh->NbEdges() + myMesh->NbFaces();
2199 if ( NbAllEdgsAndFaces == 0 )
2200 return SMESH_MesherHelper::LINEAR;
2202 //Quadratic faces and edges
2203 NbQuadFacesAndEdgs = myMesh->NbEdges(ORDER_QUADRATIC) + myMesh->NbFaces(ORDER_QUADRATIC);
2205 //Linear faces and edges
2206 NbFacesAndEdges = myMesh->NbEdges(ORDER_LINEAR) + myMesh->NbFaces(ORDER_LINEAR);
2208 if (NbAllEdgsAndFaces == NbQuadFacesAndEdgs) {
2210 return SMESH_MesherHelper::QUADRATIC;
2212 else if (NbAllEdgsAndFaces == NbFacesAndEdges) {
2214 return SMESH_MesherHelper::LINEAR;
2217 //Mesh with both type of elements
2218 return SMESH_MesherHelper::COMP;
2221 //=======================================================================
2222 //function : GetOtherParam
2223 //purpose : Return an alternative parameter for a node on seam
2224 //=======================================================================
2226 double SMESH_MesherHelper::GetOtherParam(const double param) const
2228 int i = myParIndex & U_periodic ? 0 : 1;
2229 return fabs(param-myPar1[i]) < fabs(param-myPar2[i]) ? myPar2[i] : myPar1[i];
2234 //=======================================================================
2236 * \brief Iterator on ancestors of the given type
2238 //=======================================================================
2240 struct TAncestorsIterator : public SMDS_Iterator<const TopoDS_Shape*>
2242 TopTools_ListIteratorOfListOfShape _ancIter;
2243 TopAbs_ShapeEnum _type;
2244 TopTools_MapOfShape _encountered;
2245 TAncestorsIterator( const TopTools_ListOfShape& ancestors, TopAbs_ShapeEnum type)
2246 : _ancIter( ancestors ), _type( type )
2248 if ( _ancIter.More() ) {
2249 if ( _ancIter.Value().ShapeType() != _type ) next();
2250 else _encountered.Add( _ancIter.Value() );
2255 return _ancIter.More();
2257 virtual const TopoDS_Shape* next()
2259 const TopoDS_Shape* s = _ancIter.More() ? & _ancIter.Value() : 0;
2260 if ( _ancIter.More() )
2261 for ( _ancIter.Next(); _ancIter.More(); _ancIter.Next())
2262 if ( _ancIter.Value().ShapeType() == _type && _encountered.Add( _ancIter.Value() ))
2270 //=======================================================================
2272 * \brief Return iterator on ancestors of the given type
2274 //=======================================================================
2276 PShapeIteratorPtr SMESH_MesherHelper::GetAncestors(const TopoDS_Shape& shape,
2277 const SMESH_Mesh& mesh,
2278 TopAbs_ShapeEnum ancestorType)
2280 return PShapeIteratorPtr( new TAncestorsIterator( mesh.GetAncestors(shape), ancestorType));
2283 //=======================================================================
2284 //function : GetCommonAncestor
2285 //purpose : Find a common ancestors of two shapes of the given type
2286 //=======================================================================
2288 TopoDS_Shape SMESH_MesherHelper::GetCommonAncestor(const TopoDS_Shape& shape1,
2289 const TopoDS_Shape& shape2,
2290 const SMESH_Mesh& mesh,
2291 TopAbs_ShapeEnum ancestorType)
2293 TopoDS_Shape commonAnc;
2294 if ( !shape1.IsNull() && !shape2.IsNull() )
2296 PShapeIteratorPtr ancIt = GetAncestors( shape1, mesh, ancestorType );
2297 while ( const TopoDS_Shape* anc = ancIt->next() )
2298 if ( IsSubShape( shape2, *anc ))
2307 //#include <Perf_Meter.hxx>
2309 //=======================================================================
2310 namespace { // Structures used by FixQuadraticElements()
2311 //=======================================================================
2313 #define __DMP__(txt) \
2315 #define MSG(txt) __DMP__(txt<<endl)
2316 #define MSGBEG(txt) __DMP__(txt)
2318 //const double straightTol2 = 1e-33; // to detect straing links
2319 bool isStraightLink(double linkLen2, double middleNodeMove2)
2321 // straight if <node move> < 1/15 * <link length>
2322 return middleNodeMove2 < 1/15./15. * linkLen2;
2326 // ---------------------------------------
2328 * \brief Quadratic link knowing its faces
2330 struct QLink: public SMESH_TLink
2332 const SMDS_MeshNode* _mediumNode;
2333 mutable vector<const QFace* > _faces;
2334 mutable gp_Vec _nodeMove;
2335 mutable int _nbMoves;
2337 QLink(const SMDS_MeshNode* n1, const SMDS_MeshNode* n2, const SMDS_MeshNode* nm):
2338 SMESH_TLink( n1,n2 ), _mediumNode(nm), _nodeMove(0,0,0), _nbMoves(0) {
2340 //if ( MediumPos() != SMDS_TOP_3DSPACE )
2341 _nodeMove = MediumPnt() - MiddlePnt();
2343 void SetContinuesFaces() const;
2344 const QFace* GetContinuesFace( const QFace* face ) const;
2345 bool OnBoundary() const;
2346 gp_XYZ MiddlePnt() const { return ( XYZ( node1() ) + XYZ( node2() )) / 2.; }
2347 gp_XYZ MediumPnt() const { return XYZ( _mediumNode ); }
2349 SMDS_TypeOfPosition MediumPos() const
2350 { return _mediumNode->GetPosition()->GetTypeOfPosition(); }
2351 SMDS_TypeOfPosition EndPos(bool isSecond) const
2352 { return (isSecond ? node2() : node1())->GetPosition()->GetTypeOfPosition(); }
2353 const SMDS_MeshNode* EndPosNode(SMDS_TypeOfPosition pos) const
2354 { return EndPos(0) == pos ? node1() : EndPos(1) == pos ? node2() : 0; }
2356 void Move(const gp_Vec& move, bool sum=false) const
2357 { _nodeMove += move; _nbMoves += sum ? (_nbMoves==0) : 1; }
2358 gp_XYZ Move() const { return _nodeMove.XYZ() / _nbMoves; }
2359 bool IsMoved() const { return (_nbMoves > 0 /*&& !IsStraight()*/); }
2360 bool IsStraight() const
2361 { return isStraightLink( (XYZ(node1())-XYZ(node2())).SquareModulus(),
2362 _nodeMove.SquareMagnitude());
2364 bool operator<(const QLink& other) const {
2365 return (node1()->GetID() == other.node1()->GetID() ?
2366 node2()->GetID() < other.node2()->GetID() :
2367 node1()->GetID() < other.node1()->GetID());
2369 // struct PtrComparator {
2370 // bool operator() (const QLink* l1, const QLink* l2 ) const { return *l1 < *l2; }
2373 // ---------------------------------------------------------
2375 * \brief Link in the chain of links; it connects two faces
2379 const QLink* _qlink;
2380 mutable const QFace* _qfaces[2];
2382 TChainLink(const QLink* qlink=0):_qlink(qlink) {
2383 _qfaces[0] = _qfaces[1] = 0;
2385 void SetFace(const QFace* face) const { int iF = _qfaces[0] ? 1 : 0; _qfaces[iF]=face; }
2387 bool IsBoundary() const { return !_qfaces[1]; }
2389 void RemoveFace( const QFace* face ) const
2390 { _qfaces[(face == _qfaces[1])] = 0; if (!_qfaces[0]) std::swap(_qfaces[0],_qfaces[1]); }
2392 const QFace* NextFace( const QFace* f ) const
2393 { return _qfaces[0]==f ? _qfaces[1] : _qfaces[0]; }
2395 const SMDS_MeshNode* NextNode( const SMDS_MeshNode* n ) const
2396 { return n == _qlink->node1() ? _qlink->node2() : _qlink->node1(); }
2398 bool operator<(const TChainLink& other) const { return *_qlink < *other._qlink; }
2400 operator bool() const { return (_qlink); }
2402 const QLink* operator->() const { return _qlink; }
2404 gp_Vec Normal() const;
2406 bool IsStraight() const;
2408 // --------------------------------------------------------------------
2409 typedef list< TChainLink > TChain;
2410 typedef set < TChainLink > TLinkSet;
2411 typedef TLinkSet::const_iterator TLinkInSet;
2413 const int theFirstStep = 5;
2415 enum { ERR_OK, ERR_TRI, ERR_PRISM, ERR_UNKNOWN }; // errors of QFace::GetLinkChain()
2416 // --------------------------------------------------------------------
2418 * \brief Face shared by two volumes and bound by QLinks
2420 struct QFace: public TIDSortedNodeSet
2422 mutable const SMDS_MeshElement* _volumes[2];
2423 mutable vector< const QLink* > _sides;
2424 mutable bool _sideIsAdded[4]; // added in chain of links
2427 mutable const SMDS_MeshElement* _face;
2430 QFace( const vector< const QLink*>& links, const SMDS_MeshElement* face=0 );
2432 void SetVolume(const SMDS_MeshElement* v) const { _volumes[ _volumes[0] ? 1 : 0 ] = v; }
2434 int NbVolumes() const { return !_volumes[0] ? 0 : !_volumes[1] ? 1 : 2; }
2436 void AddSelfToLinks() const {
2437 for ( int i = 0; i < _sides.size(); ++i )
2438 _sides[i]->_faces.push_back( this );
2440 int LinkIndex( const QLink* side ) const {
2441 for (int i=0; i<_sides.size(); ++i ) if ( _sides[i] == side ) return i;
2444 bool GetLinkChain( int iSide, TChain& chain, SMDS_TypeOfPosition pos, int& err) const;
2446 bool GetLinkChain( TChainLink& link, TChain& chain, SMDS_TypeOfPosition pos, int& err) const
2448 int i = LinkIndex( link._qlink );
2449 if ( i < 0 ) return true;
2450 _sideIsAdded[i] = true;
2451 link.SetFace( this );
2452 // continue from opposite link
2453 return GetLinkChain( (i+2)%_sides.size(), chain, pos, err );
2455 bool IsBoundary() const { return !_volumes[1]; }
2457 bool Contains( const SMDS_MeshNode* node ) const { return count(node); }
2459 bool IsSpoiled(const QLink* bentLink ) const;
2461 TLinkInSet GetBoundaryLink( const TLinkSet& links,
2462 const TChainLink& avoidLink,
2463 TLinkInSet * notBoundaryLink = 0,
2464 const SMDS_MeshNode* nodeToContain = 0,
2465 bool * isAdjacentUsed = 0,
2466 int nbRecursionsLeft = -1) const;
2468 TLinkInSet GetLinkByNode( const TLinkSet& links,
2469 const TChainLink& avoidLink,
2470 const SMDS_MeshNode* nodeToContain) const;
2472 const SMDS_MeshNode* GetNodeInFace() const {
2473 for ( int iL = 0; iL < _sides.size(); ++iL )
2474 if ( _sides[iL]->MediumPos() == SMDS_TOP_FACE ) return _sides[iL]->_mediumNode;
2478 gp_Vec LinkNorm(const int i, SMESH_MesherHelper* theFaceHelper=0) const;
2480 double MoveByBoundary( const TChainLink& theLink,
2481 const gp_Vec& theRefVec,
2482 const TLinkSet& theLinks,
2483 SMESH_MesherHelper* theFaceHelper=0,
2484 const double thePrevLen=0,
2485 const int theStep=theFirstStep,
2486 gp_Vec* theLinkNorm=0,
2487 double theSign=1.0) const;
2490 //================================================================================
2492 * \brief Dump QLink and QFace
2494 ostream& operator << (ostream& out, const QLink& l)
2496 out <<"QLink nodes: "
2497 << l.node1()->GetID() << " - "
2498 << l._mediumNode->GetID() << " - "
2499 << l.node2()->GetID() << endl;
2502 ostream& operator << (ostream& out, const QFace& f)
2504 out <<"QFace nodes: "/*<< &f << " "*/;
2505 for ( TIDSortedNodeSet::const_iterator n = f.begin(); n != f.end(); ++n )
2506 out << (*n)->GetID() << " ";
2507 out << " \tvolumes: "
2508 << (f._volumes[0] ? f._volumes[0]->GetID() : 0) << " "
2509 << (f._volumes[1] ? f._volumes[1]->GetID() : 0);
2510 out << " \tNormal: "<< f._normal.X() <<", "<<f._normal.Y() <<", "<<f._normal.Z() << endl;
2514 //================================================================================
2516 * \brief Construct QFace from QLinks
2518 //================================================================================
2520 QFace::QFace( const vector< const QLink*>& links, const SMDS_MeshElement* face )
2522 _volumes[0] = _volumes[1] = 0;
2524 _sideIsAdded[0]=_sideIsAdded[1]=_sideIsAdded[2]=_sideIsAdded[3]=false;
2525 _normal.SetCoord(0,0,0);
2526 for ( int i = 1; i < _sides.size(); ++i ) {
2527 const QLink *l1 = _sides[i-1], *l2 = _sides[i];
2528 insert( l1->node1() ); insert( l1->node2() );
2530 gp_Vec v1( XYZ( l1->node2()), XYZ( l1->node1()));
2531 gp_Vec v2( XYZ( l2->node1()), XYZ( l2->node2()));
2532 if ( l1->node1() != l2->node1() && l1->node2() != l2->node2() )
2536 double normSqSize = _normal.SquareMagnitude();
2537 if ( normSqSize > numeric_limits<double>::min() )
2538 _normal /= sqrt( normSqSize );
2540 _normal.SetCoord(1e-33,0,0);
2546 //================================================================================
2548 * \brief Make up a chain of links
2549 * \param iSide - link to add first
2550 * \param chain - chain to fill in
2551 * \param pos - postion of medium nodes the links should have
2552 * \param error - out, specifies what is wrong
2553 * \retval bool - false if valid chain can't be built; "valid" means that links
2554 * of the chain belongs to rectangles bounding hexahedrons
2556 //================================================================================
2558 bool QFace::GetLinkChain( int iSide, TChain& chain, SMDS_TypeOfPosition pos, int& error) const
2560 if ( iSide >= _sides.size() ) // wrong argument iSide
2562 if ( _sideIsAdded[ iSide ]) // already in chain
2565 if ( _sides.size() != 4 ) { // triangle - visit all my continous faces
2568 list< const QFace* > faces( 1, this );
2569 while ( !faces.empty() ) {
2570 const QFace* face = faces.front();
2571 for ( int i = 0; i < face->_sides.size(); ++i ) {
2572 if ( !face->_sideIsAdded[i] && face->_sides[i] ) {
2573 face->_sideIsAdded[i] = true;
2574 // find a face side in the chain
2575 TLinkInSet chLink = links.insert( TChainLink(face->_sides[i])).first;
2576 // TChain::iterator chLink = chain.begin();
2577 // for ( ; chLink != chain.end(); ++chLink )
2578 // if ( chLink->_qlink == face->_sides[i] )
2580 // if ( chLink == chain.end() )
2581 // chLink = chain.insert( chain.begin(), TChainLink(face->_sides[i]));
2582 // add a face to a chained link and put a continues face in the queue
2583 chLink->SetFace( face );
2584 if ( face->_sides[i]->MediumPos() == pos )
2585 if ( const QFace* contFace = face->_sides[i]->GetContinuesFace( face ))
2586 if ( contFace->_sides.size() == 3 )
2587 faces.push_back( contFace );
2592 if ( error < ERR_TRI )
2594 chain.insert( chain.end(), links.begin(),links.end() );
2597 _sideIsAdded[iSide] = true; // not to add this link to chain again
2598 const QLink* link = _sides[iSide];
2602 // add link into chain
2603 TChain::iterator chLink = chain.insert( chain.begin(), TChainLink(link));
2604 chLink->SetFace( this );
2607 // propagate from quadrangle to neighbour faces
2608 if ( link->MediumPos() >= pos ) {
2609 int nbLinkFaces = link->_faces.size();
2610 if ( nbLinkFaces == 4 || (/*nbLinkFaces < 4 && */link->OnBoundary())) {
2611 // hexahedral mesh or boundary quadrangles - goto a continous face
2612 if ( const QFace* f = link->GetContinuesFace( this ))
2613 if ( f->_sides.size() == 4 )
2614 return f->GetLinkChain( *chLink, chain, pos, error );
2617 TChainLink chLink(link); // side face of prismatic mesh - visit all faces of iSide
2618 for ( int i = 0; i < nbLinkFaces; ++i )
2619 if ( link->_faces[i] )
2620 link->_faces[i]->GetLinkChain( chLink, chain, pos, error );
2621 if ( error < ERR_PRISM )
2629 //================================================================================
2631 * \brief Return a boundary link of the triangle face
2632 * \param links - set of all links
2633 * \param avoidLink - link not to return
2634 * \param notBoundaryLink - out, neither the returned link nor avoidLink
2635 * \param nodeToContain - node the returned link must contain; if provided, search
2636 * also performed on adjacent faces
2637 * \param isAdjacentUsed - returns true if link is found in adjacent faces
2638 * \param nbRecursionsLeft - to limit recursion
2640 //================================================================================
2642 TLinkInSet QFace::GetBoundaryLink( const TLinkSet& links,
2643 const TChainLink& avoidLink,
2644 TLinkInSet * notBoundaryLink,
2645 const SMDS_MeshNode* nodeToContain,
2646 bool * isAdjacentUsed,
2647 int nbRecursionsLeft) const
2649 TLinkInSet linksEnd = links.end(), boundaryLink = linksEnd;
2651 typedef list< pair< const QFace*, TLinkInSet > > TFaceLinkList;
2652 TFaceLinkList adjacentFaces;
2654 for ( int iL = 0; iL < _sides.size(); ++iL )
2656 if ( avoidLink._qlink == _sides[iL] )
2658 TLinkInSet link = links.find( _sides[iL] );
2659 if ( link == linksEnd ) continue;
2660 if ( (*link)->MediumPos() > SMDS_TOP_FACE )
2661 continue; // We work on faces here, don't go inside a solid
2664 if ( link->IsBoundary() ) {
2665 if ( !nodeToContain ||
2666 (*link)->node1() == nodeToContain ||
2667 (*link)->node2() == nodeToContain )
2669 boundaryLink = link;
2670 if ( !notBoundaryLink ) break;
2673 else if ( notBoundaryLink ) {
2674 *notBoundaryLink = link;
2675 if ( boundaryLink != linksEnd ) break;
2678 if ( boundaryLink == linksEnd && nodeToContain ) // collect adjacent faces
2679 if ( const QFace* adj = link->NextFace( this ))
2680 if ( adj->Contains( nodeToContain ))
2681 adjacentFaces.push_back( make_pair( adj, link ));
2684 if ( isAdjacentUsed ) *isAdjacentUsed = false;
2685 if ( boundaryLink == linksEnd && nodeToContain && nbRecursionsLeft) // check adjacent faces
2687 if ( nbRecursionsLeft < 0 )
2688 nbRecursionsLeft = nodeToContain->NbInverseElements();
2689 TFaceLinkList::iterator adj = adjacentFaces.begin();
2690 for ( ; boundaryLink == linksEnd && adj != adjacentFaces.end(); ++adj )
2691 boundaryLink = adj->first->GetBoundaryLink( links, *(adj->second), 0, nodeToContain,
2692 isAdjacentUsed, nbRecursionsLeft-1);
2693 if ( isAdjacentUsed ) *isAdjacentUsed = true;
2695 return boundaryLink;
2697 //================================================================================
2699 * \brief Return a link ending at the given node but not avoidLink
2701 //================================================================================
2703 TLinkInSet QFace::GetLinkByNode( const TLinkSet& links,
2704 const TChainLink& avoidLink,
2705 const SMDS_MeshNode* nodeToContain) const
2707 for ( int i = 0; i < _sides.size(); ++i )
2708 if ( avoidLink._qlink != _sides[i] &&
2709 (_sides[i]->node1() == nodeToContain || _sides[i]->node2() == nodeToContain ))
2710 return links.find( _sides[ i ]);
2714 //================================================================================
2716 * \brief Return normal to the i-th side pointing outside the face
2718 //================================================================================
2720 gp_Vec QFace::LinkNorm(const int i, SMESH_MesherHelper* /*uvHelper*/) const
2722 gp_Vec norm, vecOut;
2723 // if ( uvHelper ) {
2724 // TopoDS_Face face = TopoDS::Face( uvHelper->GetSubShape());
2725 // const SMDS_MeshNode* inFaceNode = uvHelper->GetNodeUVneedInFaceNode() ? GetNodeInFace() : 0;
2726 // gp_XY uv1 = uvHelper->GetNodeUV( face, _sides[i]->node1(), inFaceNode );
2727 // gp_XY uv2 = uvHelper->GetNodeUV( face, _sides[i]->node2(), inFaceNode );
2728 // norm.SetCoord( uv1.Y() - uv2.Y(), uv2.X() - uv1.X(), 0 );
2730 // const QLink* otherLink = _sides[(i + 1) % _sides.size()];
2731 // const SMDS_MeshNode* otherNode =
2732 // otherLink->node1() == _sides[i]->node1() ? otherLink->node2() : otherLink->node1();
2733 // gp_XY pIn = uvHelper->GetNodeUV( face, otherNode, inFaceNode );
2734 // vecOut.SetCoord( uv1.X() - pIn.X(), uv1.Y() - pIn.Y(), 0 );
2737 norm = _normal ^ gp_Vec( XYZ(_sides[i]->node1()), XYZ(_sides[i]->node2()));
2738 gp_XYZ pIn = ( XYZ( _sides[0]->node1() ) +
2739 XYZ( _sides[0]->node2() ) +
2740 XYZ( _sides[1]->node1() )) / 3.;
2741 vecOut.SetXYZ( _sides[i]->MiddlePnt() - pIn );
2743 if ( norm * vecOut < 0 )
2745 double mag2 = norm.SquareMagnitude();
2746 if ( mag2 > numeric_limits<double>::min() )
2747 norm /= sqrt( mag2 );
2750 //================================================================================
2752 * \brief Move medium node of theLink according to its distance from boundary
2753 * \param theLink - link to fix
2754 * \param theRefVec - movement of boundary
2755 * \param theLinks - all adjacent links of continous triangles
2756 * \param theFaceHelper - helper is not used so far
2757 * \param thePrevLen - distance from the boundary
2758 * \param theStep - number of steps till movement propagation limit
2759 * \param theLinkNorm - out normal to theLink
2760 * \param theSign - 1 or -1 depending on movement of boundary
2761 * \retval double - distance from boundary to propagation limit or other boundary
2763 //================================================================================
2765 double QFace::MoveByBoundary( const TChainLink& theLink,
2766 const gp_Vec& theRefVec,
2767 const TLinkSet& theLinks,
2768 SMESH_MesherHelper* theFaceHelper,
2769 const double thePrevLen,
2771 gp_Vec* theLinkNorm,
2772 double theSign) const
2775 return thePrevLen; // propagation limit reached
2777 int iL; // index of theLink
2778 for ( iL = 0; iL < _sides.size(); ++iL )
2779 if ( theLink._qlink == _sides[ iL ])
2782 MSG(string(theStep,'.')<<" Ref( "<<theRefVec.X()<<","<<theRefVec.Y()<<","<<theRefVec.Z()<<" )"
2783 <<" thePrevLen " << thePrevLen);
2784 MSG(string(theStep,'.')<<" "<<*theLink._qlink);
2786 gp_Vec linkNorm = -LinkNorm( iL/*, theFaceHelper*/ ); // normal to theLink
2787 double refProj = theRefVec * linkNorm; // project movement vector to normal of theLink
2788 if ( theStep == theFirstStep )
2789 theSign = refProj < 0. ? -1. : 1.;
2790 else if ( theSign * refProj < 0.4 * theRefVec.Magnitude())
2791 return thePrevLen; // to propagate movement forward only, not in side dir or backward
2793 int iL1 = (iL + 1) % 3, iL2 = (iL + 2) % 3; // indices of the two other links of triangle
2794 TLinkInSet link1 = theLinks.find( _sides[iL1] );
2795 TLinkInSet link2 = theLinks.find( _sides[iL2] );
2796 if ( link1 == theLinks.end() || link2 == theLinks.end() )
2798 const QFace* f1 = link1->NextFace( this ); // adjacent faces
2799 const QFace* f2 = link2->NextFace( this );
2801 // propagate to adjacent faces till limit step or boundary
2802 double len1 = thePrevLen + (theLink->MiddlePnt() - _sides[iL1]->MiddlePnt()).Modulus();
2803 double len2 = thePrevLen + (theLink->MiddlePnt() - _sides[iL2]->MiddlePnt()).Modulus();
2804 gp_Vec linkDir1(0,0,0); // initialize to avoid valgrind error ("Conditional jump...")
2805 gp_Vec linkDir2(0,0,0);
2808 if ( f1 && theLink->MediumPos() <= (*link1)->MediumPos() )
2809 len1 = f1->MoveByBoundary
2810 ( *link1, theRefVec, theLinks, theFaceHelper, len1, theStep-1, &linkDir1, theSign);
2812 linkDir1 = LinkNorm( iL1/*, theFaceHelper*/ );
2814 MSG( " --------------- EXCEPTION");
2819 if ( f2 && theLink->MediumPos() <= (*link2)->MediumPos() )
2820 len2 = f2->MoveByBoundary
2821 ( *link2, theRefVec, theLinks, theFaceHelper, len2, theStep-1, &linkDir2, theSign);
2823 linkDir2 = LinkNorm( iL2/*, theFaceHelper*/ );
2825 MSG( " --------------- EXCEPTION");
2830 if ( theStep != theFirstStep )
2832 // choose chain length by direction of propagation most codirected with theRefVec
2833 bool choose1 = ( theRefVec * linkDir1 * theSign > theRefVec * linkDir2 * theSign );
2834 fullLen = choose1 ? len1 : len2;
2835 double r = thePrevLen / fullLen;
2837 gp_Vec move = linkNorm * refProj * ( 1 - r );
2838 theLink->Move( move, true );
2840 MSG(string(theStep,'.')<<" Move "<< theLink->_mediumNode->GetID()<<
2841 " by " << refProj * ( 1 - r ) << " following " <<
2842 (choose1 ? *link1->_qlink : *link2->_qlink));
2844 if ( theLinkNorm ) *theLinkNorm = linkNorm;
2849 //================================================================================
2851 * \brief Checks if the face is distorted due to bentLink
2853 //================================================================================
2855 bool QFace::IsSpoiled(const QLink* bentLink ) const
2857 // code is valid for convex faces only
2859 for ( TIDSortedNodeSet::const_iterator n = begin(); n!=end(); ++n)
2860 gc += XYZ( *n ) / size();
2861 for (unsigned i = 0; i < _sides.size(); ++i )
2863 if ( _sides[i] == bentLink ) continue;
2864 gp_Vec linkNorm = _normal ^ gp_Vec( XYZ(_sides[i]->node1()), XYZ(_sides[i]->node2()));
2865 gp_Vec vecOut( gc, _sides[i]->MiddlePnt() );
2866 if ( linkNorm * vecOut < 0 )
2868 double mag2 = linkNorm.SquareMagnitude();
2869 if ( mag2 > numeric_limits<double>::min() )
2870 linkNorm /= sqrt( mag2 );
2871 gp_Vec vecBent ( _sides[i]->MiddlePnt(), bentLink->MediumPnt());
2872 gp_Vec vecStraight( _sides[i]->MiddlePnt(), bentLink->MiddlePnt());
2873 if ( vecBent * linkNorm > -0.1*vecStraight.Magnitude() )
2880 //================================================================================
2882 * \brief Find pairs of continues faces
2884 //================================================================================
2886 void QLink::SetContinuesFaces() const
2888 // x0 x - QLink, [-|] - QFace, v - volume
2890 // | Between _faces of link x2 two vertical faces are continues
2891 // x1----x2-----x3 and two horizontal faces are continues. We set vertical faces
2892 // | to _faces[0] and _faces[1] and horizontal faces to
2893 // v2 | v3 _faces[2] and _faces[3] (or vise versa).
2896 if ( _faces.empty() )
2898 int iFaceCont = -1, nbBoundary = 0, iBoundary[2]={-1,-1};
2899 if ( _faces[0]->IsBoundary() )
2900 iBoundary[ nbBoundary++ ] = 0;
2901 for ( int iF = 1; iFaceCont < 0 && iF < _faces.size(); ++iF )
2903 // look for a face bounding none of volumes bound by _faces[0]
2904 bool sameVol = false;
2905 int nbVol = _faces[iF]->NbVolumes();
2906 for ( int iV = 0; !sameVol && iV < nbVol; ++iV )
2907 sameVol = ( _faces[iF]->_volumes[iV] == _faces[0]->_volumes[0] ||
2908 _faces[iF]->_volumes[iV] == _faces[0]->_volumes[1]);
2911 if ( _faces[iF]->IsBoundary() )
2912 iBoundary[ nbBoundary++ ] = iF;
2914 // Set continues faces: arrange _faces to have
2915 // _faces[0] continues to _faces[1]
2916 // _faces[2] continues to _faces[3]
2917 if ( nbBoundary == 2 ) // bnd faces are continues
2919 if (( iBoundary[0] < 2 ) != ( iBoundary[1] < 2 ))
2921 int iNear0 = iBoundary[0] < 2 ? 1-iBoundary[0] : 5-iBoundary[0];
2922 std::swap( _faces[ iBoundary[1] ], _faces[iNear0] );
2925 else if ( iFaceCont > 0 ) // continues faces found
2927 if ( iFaceCont != 1 )
2928 std::swap( _faces[1], _faces[iFaceCont] );
2930 else if ( _faces.size() > 1 ) // not found, set NULL by the first face
2932 _faces.insert( ++_faces.begin(), 0 );
2935 //================================================================================
2937 * \brief Return a face continues to the given one
2939 //================================================================================
2941 const QFace* QLink::GetContinuesFace( const QFace* face ) const
2943 for ( int i = 0; i < _faces.size(); ++i ) {
2944 if ( _faces[i] == face ) {
2945 int iF = i < 2 ? 1-i : 5-i;
2946 return iF < _faces.size() ? _faces[iF] : 0;
2951 //================================================================================
2953 * \brief True if link is on mesh boundary
2955 //================================================================================
2957 bool QLink::OnBoundary() const
2959 for ( int i = 0; i < _faces.size(); ++i )
2960 if (_faces[i] && _faces[i]->IsBoundary()) return true;
2963 //================================================================================
2965 * \brief Return normal of link of the chain
2967 //================================================================================
2969 gp_Vec TChainLink::Normal() const {
2971 if (_qfaces[0]) norm = _qfaces[0]->_normal;
2972 if (_qfaces[1]) norm += _qfaces[1]->_normal;
2975 //================================================================================
2977 * \brief Test link curvature taking into account size of faces
2979 //================================================================================
2981 bool TChainLink::IsStraight() const
2983 bool isStraight = _qlink->IsStraight();
2984 if ( isStraight && _qfaces[0] && !_qfaces[1] )
2986 int i = _qfaces[0]->LinkIndex( _qlink );
2987 int iOpp = ( i + 2 ) % _qfaces[0]->_sides.size();
2988 gp_XYZ mid1 = _qlink->MiddlePnt();
2989 gp_XYZ mid2 = _qfaces[0]->_sides[ iOpp ]->MiddlePnt();
2990 double faceSize2 = (mid1-mid2).SquareModulus();
2991 isStraight = _qlink->_nodeMove.SquareMagnitude() < 1/10./10. * faceSize2;
2996 //================================================================================
2998 * \brief Move medium nodes of vertical links of pentahedrons adjacent by side faces
3000 //================================================================================
3002 void fixPrism( TChain& allLinks )
3004 // separate boundary links from internal ones
3005 typedef set<const QLink*/*, QLink::PtrComparator*/> QLinkSet;
3006 QLinkSet interLinks, bndLinks1, bndLink2;
3008 bool isCurved = false;
3009 for ( TChain::iterator lnk = allLinks.begin(); lnk != allLinks.end(); ++lnk ) {
3010 if ( (*lnk)->OnBoundary() )
3011 bndLinks1.insert( lnk->_qlink );
3013 interLinks.insert( lnk->_qlink );
3014 isCurved = isCurved || !lnk->IsStraight();
3017 return; // no need to move
3019 QLinkSet *curBndLinks = &bndLinks1, *newBndLinks = &bndLink2;
3021 while ( !interLinks.empty() && !curBndLinks->empty() )
3023 // propagate movement from boundary links to connected internal links
3024 QLinkSet::iterator bnd = curBndLinks->begin(), bndEnd = curBndLinks->end();
3025 for ( ; bnd != bndEnd; ++bnd )
3027 const QLink* bndLink = *bnd;
3028 for ( int i = 0; i < bndLink->_faces.size(); ++i ) // loop on faces of bndLink
3030 const QFace* face = bndLink->_faces[i]; // quadrange lateral face of a prism
3031 if ( !face ) continue;
3032 // find and move internal link opposite to bndLink within the face
3033 int interInd = ( face->LinkIndex( bndLink ) + 2 ) % face->_sides.size();
3034 const QLink* interLink = face->_sides[ interInd ];
3035 QLinkSet::iterator pInterLink = interLinks.find( interLink );
3036 if ( pInterLink == interLinks.end() ) continue; // not internal link
3037 interLink->Move( bndLink->_nodeMove );
3038 // treated internal links become new boundary ones
3039 interLinks. erase( pInterLink );
3040 newBndLinks->insert( interLink );
3043 curBndLinks->clear();
3044 std::swap( curBndLinks, newBndLinks );
3048 //================================================================================
3050 * \brief Fix links of continues triangles near curved boundary
3052 //================================================================================
3054 void fixTriaNearBoundary( TChain & allLinks, SMESH_MesherHelper& /*helper*/)
3056 if ( allLinks.empty() ) return;
3058 TLinkSet linkSet( allLinks.begin(), allLinks.end());
3059 TLinkInSet linkIt = linkSet.begin(), linksEnd = linkSet.end();
3061 for ( linkIt = linkSet.begin(); linkIt != linksEnd; ++linkIt)
3063 if ( linkIt->IsBoundary() && !linkIt->IsStraight() && linkIt->_qfaces[0])
3065 // move iff a boundary link is bent towards inside of a face (issue 0021084)
3066 const QFace* face = linkIt->_qfaces[0];
3067 gp_XYZ pIn = ( face->_sides[0]->MiddlePnt() +
3068 face->_sides[1]->MiddlePnt() +
3069 face->_sides[2]->MiddlePnt() ) / 3.;
3070 gp_XYZ insideDir( pIn - (*linkIt)->MiddlePnt());
3071 bool linkBentInside = ((*linkIt)->_nodeMove.Dot( insideDir ) > 0 );
3072 //if ( face->IsSpoiled( linkIt->_qlink ))
3073 if ( linkBentInside )
3074 face->MoveByBoundary( *linkIt, (*linkIt)->_nodeMove, linkSet );
3079 //================================================================================
3081 * \brief Detect rectangular structure of links and build chains from them
3083 //================================================================================
3085 enum TSplitTriaResult {
3086 _OK, _NO_CORNERS, _FEW_ROWS, _MANY_ROWS, _NO_SIDELINK, _BAD_MIDQUAD, _NOT_RECT,
3087 _NO_MIDQUAD, _NO_UPTRIA, _BAD_SET_SIZE, _BAD_CORNER, _BAD_START, _NO_BOTLINK, _TWISTED_CHAIN };
3089 TSplitTriaResult splitTrianglesIntoChains( TChain & allLinks,
3090 vector< TChain> & resultChains,
3091 SMDS_TypeOfPosition pos )
3093 // put links in the set and evalute number of result chains by number of boundary links
3096 for ( TChain::iterator lnk = allLinks.begin(); lnk != allLinks.end(); ++lnk ) {
3097 linkSet.insert( *lnk );
3098 nbBndLinks += lnk->IsBoundary();
3100 resultChains.clear();
3101 resultChains.reserve( nbBndLinks / 2 );
3103 TLinkInSet linkIt, linksEnd = linkSet.end();
3105 // find a boundary link with corner node; corner node has position pos-2
3106 // i.e. SMDS_TOP_VERTEX for links on faces and SMDS_TOP_EDGE for
3108 SMDS_TypeOfPosition cornerPos = SMDS_TypeOfPosition(pos-2);
3109 const SMDS_MeshNode* corner = 0;
3110 for ( linkIt = linkSet.begin(); linkIt != linksEnd; ++linkIt )
3111 if ( linkIt->IsBoundary() && (corner = (*linkIt)->EndPosNode(cornerPos)))
3116 TLinkInSet startLink = linkIt;
3117 const SMDS_MeshNode* startCorner = corner;
3118 vector< TChain* > rowChains;
3121 while ( startLink != linksEnd) // loop on columns
3123 // We suppose we have a rectangular structure like shown here. We have found a
3124 // corner of the rectangle (startCorner) and a boundary link sharing
3125 // |/ |/ | the startCorner (startLink). We are going to loop on rows of the
3126 // --o---o---o structure making several chains at once. One chain (columnChain)
3127 // |\ | /| starts at startLink and continues upward (we look at the structure
3128 // \ | \ | / | from such point that startLink is on the bottom of the structure).
3129 // \| \|/ | While going upward we also fill horizontal chains (rowChains) we
3130 // --o---o---o encounter.
3132 // / | \ | \ | startCorner
3137 if ( resultChains.size() == nbBndLinks / 2 )
3139 resultChains.push_back( TChain() );
3140 TChain& columnChain = resultChains.back();
3142 TLinkInSet botLink = startLink; // current horizontal link to go up from
3143 corner = startCorner; // current corner the botLink ends at
3145 while ( botLink != linksEnd ) // loop on rows
3147 // add botLink to the columnChain
3148 columnChain.push_back( *botLink );
3150 const QFace* botTria = botLink->_qfaces[0]; // bottom triangle bound by botLink
3152 { // the column ends
3153 if ( botLink == startLink )
3154 return _TWISTED_CHAIN; // issue 0020951
3155 linkSet.erase( botLink );
3156 if ( iRow != rowChains.size() )
3157 return _FEW_ROWS; // different nb of rows in columns
3160 // find the link dividing the quadrangle (midQuadLink) and vertical boundary
3161 // link ending at <corner> (sideLink); there are two cases:
3162 // 1) midQuadLink does not end at <corner>, then we easily find it by botTria,
3163 // since midQuadLink is not at boundary while sideLink is.
3164 // 2) midQuadLink ends at <corner>
3166 TLinkInSet midQuadLink = linksEnd;
3167 TLinkInSet sideLink = botTria->GetBoundaryLink( linkSet, *botLink, &midQuadLink,
3169 if ( isCase2 ) { // find midQuadLink among links of botTria
3170 midQuadLink = botTria->GetLinkByNode( linkSet, *botLink, corner );
3171 if ( midQuadLink->IsBoundary() )
3172 return _BAD_MIDQUAD;
3174 if ( sideLink == linksEnd || midQuadLink == linksEnd || sideLink == midQuadLink )
3175 return sideLink == linksEnd ? _NO_SIDELINK : _NO_MIDQUAD;
3178 columnChain.push_back( *midQuadLink );
3179 if ( iRow >= rowChains.size() ) {
3181 return _MANY_ROWS; // different nb of rows in columns
3182 if ( resultChains.size() == nbBndLinks / 2 )
3184 resultChains.push_back( TChain() );
3185 rowChains.push_back( & resultChains.back() );
3187 rowChains[iRow]->push_back( *sideLink );
3188 rowChains[iRow]->push_back( *midQuadLink );
3190 const QFace* upTria = midQuadLink->NextFace( botTria ); // upper tria of the rectangle
3194 // prepare startCorner and startLink for the next column
3195 startCorner = startLink->NextNode( startCorner );
3197 startLink = botTria->GetBoundaryLink( linkSet, *botLink, 0, startCorner );
3199 startLink = upTria->GetBoundaryLink( linkSet, *midQuadLink, 0, startCorner );
3200 // check if no more columns remains
3201 if ( startLink != linksEnd ) {
3202 const SMDS_MeshNode* botNode = startLink->NextNode( startCorner );
3203 if ( (isCase2 ? botTria : upTria)->Contains( botNode ))
3204 startLink = linksEnd; // startLink bounds upTria or botTria
3205 else if ( startLink == botLink || startLink == midQuadLink || startLink == sideLink )
3209 // find bottom link and corner for the next row
3210 corner = sideLink->NextNode( corner );
3211 // next bottom link ends at the new corner
3212 linkSet.erase( botLink );
3213 botLink = upTria->GetLinkByNode( linkSet, (isCase2 ? *sideLink : *midQuadLink), corner );
3214 if ( botLink == linksEnd || botLink == midQuadLink || botLink == sideLink)
3216 if ( midQuadLink == startLink || sideLink == startLink )
3217 return _TWISTED_CHAIN; // issue 0020951
3218 linkSet.erase( midQuadLink );
3219 linkSet.erase( sideLink );
3221 // make faces neighboring the found ones be boundary
3222 if ( startLink != linksEnd ) {
3223 const QFace* tria = isCase2 ? botTria : upTria;
3224 for ( int iL = 0; iL < 3; ++iL ) {
3225 linkIt = linkSet.find( tria->_sides[iL] );
3226 if ( linkIt != linksEnd )
3227 linkIt->RemoveFace( tria );
3230 if ( botLink->_qfaces[0] == upTria || botLink->_qfaces[1] == upTria )
3231 botLink->RemoveFace( upTria ); // make next botTria first in vector
3238 // In the linkSet, there must remain the last links of rowChains; add them
3239 if ( linkSet.size() != rowChains.size() )
3240 return _BAD_SET_SIZE;
3241 for ( int iRow = 0; iRow < rowChains.size(); ++iRow ) {
3242 // find the link (startLink) ending at startCorner
3244 for ( startLink = linkSet.begin(); startLink != linksEnd; ++startLink ) {
3245 if ( (*startLink)->node1() == startCorner ) {
3246 corner = (*startLink)->node2(); break;
3248 else if ( (*startLink)->node2() == startCorner) {
3249 corner = (*startLink)->node1(); break;
3252 if ( startLink == linksEnd )
3254 rowChains[ iRow ]->push_back( *startLink );
3255 linkSet.erase( startLink );
3256 startCorner = corner;
3262 //================================================================================
3264 * \brief Place medium nodes at the link middle for elements whose corner nodes
3265 * are out of geometrical boundary to prevent distorting elements.
3266 * Issue 0020982, note 0013990
3268 //================================================================================
3270 void force3DOutOfBoundary( SMESH_MesherHelper& theHelper,
3271 SMESH_ComputeErrorPtr& theError)
3273 SMESHDS_Mesh* meshDS = theHelper.GetMeshDS();
3274 TopoDS_Shape shape = theHelper.GetSubShape().Oriented( TopAbs_FORWARD );
3275 if ( shape.IsNull() ) return;
3277 if ( !theError ) theError = SMESH_ComputeError::New();
3281 if ( shape.ShapeType() == TopAbs_FACE ) // 2D
3283 if ( theHelper.GetMesh()->NbTriangles( ORDER_QUADRATIC ) < 1 ) return;
3285 SMESHDS_SubMesh* faceSM = meshDS->MeshElements( shape );
3286 if ( !faceSM ) return;
3288 const TopoDS_Face& face = TopoDS::Face( shape );
3289 Handle(Geom_Surface) surface = BRep_Tool::Surface( face );
3291 TopExp_Explorer edgeIt( face, TopAbs_EDGE );
3292 for ( ; edgeIt.More(); edgeIt.Next() ) // loop on EDGEs of a FACE
3294 // check if the EDGE needs checking
3295 const TopoDS_Edge& edge = TopoDS::Edge( edgeIt.Current() );
3296 if ( BRep_Tool::Degenerated( edge ) )
3298 if ( theHelper.IsRealSeam( edge ) &&
3299 edge.Orientation() == TopAbs_REVERSED )
3302 SMESHDS_SubMesh* edgeSM = meshDS->MeshElements( edge );
3303 if ( !edgeSM ) continue;
3306 Handle(Geom2d_Curve) pcurve = BRep_Tool::CurveOnSurface( edge, face, f, l );
3307 BRepAdaptor_Curve curve3D( edge );
3308 switch ( curve3D.GetType() ) {
3309 case GeomAbs_Line: continue;
3310 case GeomAbs_Circle:
3311 case GeomAbs_Ellipse:
3312 case GeomAbs_Hyperbola:
3313 case GeomAbs_Parabola:
3316 gp_Vec D1, D2, Du1, Dv1; gp_Pnt p;
3317 curve3D.D2( 0.5 * ( f + l ), p, D1, D2 );
3318 gp_Pnt2d uv = pcurve->Value( 0.5 * ( f + l ) );
3319 surface->D1( uv.X(), uv.Y(), p, Du1, Dv1 );
3320 gp_Vec fNorm = Du1 ^ Dv1;
3321 if ( fNorm.IsParallel( D2, M_PI * 25./180. ))
3322 continue; // face is normal to the curve3D
3324 gp_Vec curvNorm = fNorm ^ D1;
3325 if ( edge.Orientation() == TopAbs_REVERSED ) curvNorm.Reverse();
3326 if ( curvNorm * D2 > 0 )
3327 continue; // convex edge
3329 catch ( Standard_Failure )
3334 // get nodes shared by faces that may be distorted
3335 SMDS_NodeIteratorPtr nodeIt;
3336 if ( edgeSM->NbNodes() > 0 ) {
3337 nodeIt = edgeSM->GetNodes();
3340 SMESHDS_SubMesh* vertexSM = meshDS->MeshElements( theHelper.IthVertex( 0, edge ));
3342 vertexSM = meshDS->MeshElements( theHelper.IthVertex( 1, edge ));
3343 if ( !vertexSM ) continue;
3344 nodeIt = vertexSM->GetNodes();
3347 // find suspicious faces
3348 TIDSortedElemSet checkedFaces;
3349 vector< const SMDS_MeshNode* > nOnEdge( 2 );
3350 const SMDS_MeshNode* nOnFace;
3351 while ( nodeIt->more() )
3353 const SMDS_MeshNode* n = nodeIt->next();
3354 SMDS_ElemIteratorPtr faceIt = n->GetInverseElementIterator( SMDSAbs_Face );
3355 while ( faceIt->more() )
3357 const SMDS_MeshElement* f = faceIt->next();
3358 if ( !faceSM->Contains( f ) ||
3359 f->NbNodes() != 6 || // check quadratic triangles only
3360 !checkedFaces.insert( f ).second )
3363 // get nodes on EDGE and on FACE of a suspicious face
3364 nOnEdge.clear(); nOnFace = 0;
3365 SMDS_MeshElement::iterator triNode = f->begin_nodes();
3366 for ( int nbN = 0; nbN < 3; ++triNode, ++nbN )
3369 if ( n->GetPosition()->GetDim() == 2 )
3372 nOnEdge.push_back( n );
3375 // check if nOnFace is inside the FACE
3376 if ( nOnFace && nOnEdge.size() == 2 )
3378 theHelper.AddTLinks( static_cast< const SMDS_MeshFace* > ( f ));
3379 if ( !SMESH_Algo::FaceNormal( f, faceNorm, /*normalized=*/false ))
3381 gp_XYZ edgeDir = SMESH_TNodeXYZ( nOnEdge[0] ) - SMESH_TNodeXYZ( nOnEdge[1] );
3382 gp_XYZ edgeNorm = faceNorm ^ edgeDir;
3383 n = theHelper.GetMediumNode( nOnEdge[0], nOnEdge[1], true );
3384 gp_XYZ pN0 = SMESH_TNodeXYZ( nOnEdge[0] );
3385 gp_XYZ pMedium = SMESH_TNodeXYZ( n ); // on-edge node location
3386 gp_XYZ pFaceN = SMESH_TNodeXYZ( nOnFace ); // on-face node location
3387 double hMedium = edgeNorm * gp_Vec( pN0, pMedium ).XYZ();
3388 double hFace = edgeNorm * gp_Vec( pN0, pFaceN ).XYZ();
3389 if ( Abs( hMedium ) > Abs( hFace * 0.6 ))
3391 // nOnFace is out of FACE, move a medium on-edge node to the middle
3392 gp_XYZ pMid3D = 0.5 * ( pN0 + SMESH_TNodeXYZ( nOnEdge[1] ));
3393 meshDS->MoveNode( n, pMid3D.X(), pMid3D.Y(), pMid3D.Z() );
3394 MSG( "move OUT of face " << n );
3395 theError->myBadElements.push_back( f );
3401 if ( !theError->myBadElements.empty() )
3402 theError->myName = EDITERR_NO_MEDIUM_ON_GEOM;
3405 } // 2D ==============================================================================
3407 if ( shape.ShapeType() == TopAbs_SOLID ) // 3D
3409 if ( theHelper.GetMesh()->NbTetras ( ORDER_QUADRATIC ) < 1 &&
3410 theHelper.GetMesh()->NbPyramids( ORDER_QUADRATIC ) < 1 ) return;
3412 SMESHDS_SubMesh* solidSM = meshDS->MeshElements( shape );
3413 if ( !solidSM ) return;
3415 // check if the SOLID is bound by concave FACEs
3416 vector< TopoDS_Face > concaveFaces;
3417 TopExp_Explorer faceIt( shape, TopAbs_FACE );
3418 for ( ; faceIt.More(); faceIt.Next() ) // loop on FACEs of a SOLID
3420 const TopoDS_Face& face = TopoDS::Face( faceIt.Current() );
3421 if ( !meshDS->MeshElements( face )) continue;
3423 BRepAdaptor_Surface surface( face );
3424 switch ( surface.GetType() ) {
3425 case GeomAbs_Plane: continue;
3426 case GeomAbs_Cylinder:
3428 case GeomAbs_Sphere:
3431 double u = 0.5 * ( surface.FirstUParameter() + surface.LastUParameter() );
3432 double v = 0.5 * ( surface.FirstVParameter() + surface.LastVParameter() );
3433 gp_Vec Du1, Dv1, Du2, Dv2, Duv2; gp_Pnt p;
3434 surface.D2( u,v, p, Du1, Dv1, Du2, Dv2, Duv2 );
3435 gp_Vec fNorm = Du1 ^ Dv1;
3436 if ( face.Orientation() == TopAbs_REVERSED ) fNorm.Reverse();
3437 bool concaveU = ( fNorm * Du2 > 1e-100 );
3438 bool concaveV = ( fNorm * Dv2 > 1e-100 );
3439 if ( concaveU || concaveV )
3440 concaveFaces.push_back( face );
3442 catch ( Standard_Failure )
3444 concaveFaces.push_back( face );
3448 if ( concaveFaces.empty() )
3451 // fix 2D mesh on the SOLID
3452 for ( faceIt.ReInit(); faceIt.More(); faceIt.Next() ) // loop on FACEs of a SOLID
3454 SMESH_MesherHelper faceHelper( *theHelper.GetMesh() );
3455 faceHelper.SetSubShape( faceIt.Current() );
3456 force3DOutOfBoundary( faceHelper, theError );
3459 // get an iterator over faces on concaveFaces
3460 vector< SMDS_ElemIteratorPtr > faceIterVec( concaveFaces.size() );
3461 for ( size_t i = 0; i < concaveFaces.size(); ++i )
3462 faceIterVec[i] = meshDS->MeshElements( concaveFaces[i] )->GetElements();
3463 typedef SMDS_IteratorOnIterators
3464 < const SMDS_MeshElement*, vector< SMDS_ElemIteratorPtr > > TIterOnIter;
3465 SMDS_ElemIteratorPtr faceIter( new TIterOnIter( faceIterVec ));
3467 // a seacher to check if a volume is close to a concave face
3468 std::auto_ptr< SMESH_ElementSearcher > faceSearcher
3469 ( SMESH_MeshEditor( theHelper.GetMesh() ).GetElementSearcher( faceIter ));
3472 //BRepClass3d_SolidClassifier solidClassifier( shape );
3474 TIDSortedElemSet checkedVols, movedNodes;
3475 for ( faceIt.ReInit(); faceIt.More(); faceIt.Next() ) // loop on FACEs of a SOLID
3477 const TopoDS_Shape& face = faceIt.Current();
3478 SMESHDS_SubMesh* faceSM = meshDS->MeshElements( face );
3479 if ( !faceSM ) continue;
3481 // get nodes shared by volumes (tet and pyra) on the FACE that may be distorted
3482 SMDS_NodeIteratorPtr nodeIt;
3483 if ( faceSM->NbNodes() > 0 ) {
3484 nodeIt = faceSM->GetNodes();
3487 TopExp_Explorer vertex( face, TopAbs_VERTEX );
3488 SMESHDS_SubMesh* vertexSM = meshDS->MeshElements( vertex.Current() );
3489 if ( !vertexSM ) continue;
3490 nodeIt = vertexSM->GetNodes();
3493 // find suspicious volumes adjacent to the FACE
3494 vector< const SMDS_MeshNode* > nOnFace( 4 );
3495 const SMDS_MeshNode* nInSolid;
3496 //vector< const SMDS_MeshElement* > intersectedFaces;
3497 while ( nodeIt->more() )
3499 const SMDS_MeshNode* n = nodeIt->next();
3500 SMDS_ElemIteratorPtr volIt = n->GetInverseElementIterator( SMDSAbs_Volume );
3501 while ( volIt->more() )
3503 const SMDS_MeshElement* vol = volIt->next();
3504 int nbN = vol->NbCornerNodes();
3505 if ( ( nbN != 4 && nbN != 5 ) ||
3506 !solidSM->Contains( vol ) ||
3507 !checkedVols.insert( vol ).second )
3510 // get nodes on FACE and in SOLID of a suspicious volume
3511 nOnFace.clear(); nInSolid = 0;
3512 SMDS_MeshElement::iterator volNode = vol->begin_nodes();
3513 for ( int nb = nbN; nb > 0; ++volNode, --nb )
3516 if ( n->GetPosition()->GetDim() == 3 )
3519 nOnFace.push_back( n );
3521 if ( !nInSolid || nOnFace.size() != nbN - 1 )
3524 // get size of the vol
3525 SMESH_TNodeXYZ pInSolid( nInSolid ), pOnFace0( nOnFace[0] );
3526 double volLength = pInSolid.SquareDistance( nOnFace[0] );
3527 for ( size_t i = 1; i < nOnFace.size(); ++i )
3529 volLength = Max( volLength, pOnFace0.SquareDistance( nOnFace[i] ));
3532 // check if vol is close to concaveFaces
3533 const SMDS_MeshElement* closeFace =
3534 faceSearcher->FindClosestTo( pInSolid, SMDSAbs_Face );
3536 pInSolid.SquareDistance( closeFace->GetNode(0) ) > 4 * volLength )
3539 // check if vol is distorted, i.e. a medium node is much closer
3540 // to nInSolid than the link middle
3541 bool isDistorted = false;
3542 SMDS_FaceOfNodes onFaceTria( nOnFace[0], nOnFace[1], nOnFace[2] );
3543 if ( !SMESH_Algo::FaceNormal( &onFaceTria, faceNorm, /*normalized=*/false ))
3545 theHelper.AddTLinks( static_cast< const SMDS_MeshVolume* > ( vol ));
3546 vector< pair< SMESH_TLink, const SMDS_MeshNode* > > links;
3547 for ( size_t i = 0; i < nOnFace.size(); ++i ) // loop on links between nOnFace
3548 for ( size_t j = i+1; j < nOnFace.size(); ++j )
3550 SMESH_TLink link( nOnFace[i], nOnFace[j] );
3551 TLinkNodeMap::const_iterator linkIt =
3552 theHelper.GetTLinkNodeMap().find( link );
3553 if ( linkIt != theHelper.GetTLinkNodeMap().end() )
3555 links.push_back( make_pair( linkIt->first, linkIt->second ));
3556 if ( !isDistorted ) {
3557 // compare projections of nInSolid and nMedium to face normal
3558 gp_Pnt pMedium = SMESH_TNodeXYZ( linkIt->second );
3559 double hMedium = faceNorm * gp_Vec( pOnFace0, pMedium ).XYZ();
3560 double hVol = faceNorm * gp_Vec( pOnFace0, pInSolid ).XYZ();
3561 isDistorted = ( Abs( hMedium ) > Abs( hVol * 0.5 ));
3565 // move medium nodes to link middle
3568 for ( size_t i = 0; i < links.size(); ++i )
3570 const SMDS_MeshNode* nMedium = links[i].second;
3571 if ( movedNodes.insert( nMedium ).second )
3573 gp_Pnt pMid3D = 0.5 * ( SMESH_TNodeXYZ( links[i].first.node1() ) +
3574 SMESH_TNodeXYZ( links[i].first.node2() ));
3575 meshDS->MoveNode( nMedium, pMid3D.X(), pMid3D.Y(), pMid3D.Z() );
3576 MSG( "move OUT of solid " << nMedium );
3579 theError->myBadElements.push_back( vol );
3581 } // loop on volumes sharing a node on FACE
3582 } // loop on nodes on FACE
3583 } // loop on FACEs of a SOLID
3585 if ( !theError->myBadElements.empty() )
3586 theError->myName = EDITERR_NO_MEDIUM_ON_GEOM;
3592 //=======================================================================
3594 * \brief Move medium nodes of faces and volumes to fix distorted elements
3595 * \param error - container of fixed distorted elements
3596 * \param volumeOnly - to fix nodes on faces or not, if the shape is solid
3598 * Issue 0020307: EDF 992 SMESH : Linea/Quadratic with Medium Node on Geometry
3600 //=======================================================================
3602 void SMESH_MesherHelper::FixQuadraticElements(SMESH_ComputeErrorPtr& compError,
3605 // setenv NO_FixQuadraticElements to know if FixQuadraticElements() is guilty of bad conversion
3606 if ( getenv("NO_FixQuadraticElements") )
3609 // 0. Apply algorithm to SOLIDs or FACEs
3610 // ----------------------------------------------
3611 if ( myShape.IsNull() ) {
3612 if ( !myMesh->HasShapeToMesh() ) return;
3613 SetSubShape( myMesh->GetShapeToMesh() );
3617 TopTools_IndexedMapOfShape solids;
3618 TopExp::MapShapes(myShape,TopAbs_SOLID,solids);
3619 nbSolids = solids.Extent();
3621 TopTools_MapOfShape faces; // faces not in solid or in not meshed solid
3622 for ( TopExp_Explorer f(myShape,TopAbs_FACE,TopAbs_SOLID); f.More(); f.Next() ) {
3623 faces.Add( f.Current() ); // not in solid
3625 for ( TopExp_Explorer s(myShape,TopAbs_SOLID); s.More(); s.Next() ) {
3626 if ( myMesh->GetSubMesh( s.Current() )->IsEmpty() ) { // get faces of solid
3627 for ( TopExp_Explorer f( s.Current(), TopAbs_FACE); f.More(); f.Next() )
3628 faces.Add( f.Current() ); // in not meshed solid
3630 else { // fix nodes in the solid and its faces
3632 MSG("FIX SOLID " << nbSolids-- << " #" << GetMeshDS()->ShapeToIndex(s.Current()));
3634 SMESH_MesherHelper h(*myMesh);
3635 h.SetSubShape( s.Current() );
3636 h.ToFixNodeParameters(true);
3637 h.FixQuadraticElements( compError, false );
3640 // fix nodes on geom faces
3642 int nbfaces = faces.Extent(); /*avoid "unused varianbles": */ nbfaces++, nbfaces--;
3644 for ( TopTools_MapIteratorOfMapOfShape fIt( faces ); fIt.More(); fIt.Next() ) {
3645 MSG("FIX FACE " << nbfaces-- << " #" << GetMeshDS()->ShapeToIndex(fIt.Key()));
3646 SMESH_MesherHelper h(*myMesh);
3647 h.SetSubShape( fIt.Key() );
3648 h.ToFixNodeParameters(true);
3649 h.FixQuadraticElements( compError, true);
3651 //perf_print_all_meters(1);
3652 if ( compError && compError->myName == EDITERR_NO_MEDIUM_ON_GEOM )
3653 compError->myComment = "during conversion to quadratic, "
3654 "some medium nodes were not placed on geometry to avoid distorting elements";
3658 // 1. Find out type of elements and get iterator on them
3659 // ---------------------------------------------------
3661 SMDS_ElemIteratorPtr elemIt;
3662 SMDSAbs_ElementType elemType = SMDSAbs_All;
3664 SMESH_subMesh* submesh = myMesh->GetSubMeshContaining( myShapeID );
3667 if ( SMESHDS_SubMesh* smDS = submesh->GetSubMeshDS() ) {
3668 elemIt = smDS->GetElements();
3669 if ( elemIt->more() ) {
3670 elemType = elemIt->next()->GetType();
3671 elemIt = smDS->GetElements();
3674 if ( !elemIt || !elemIt->more() || elemType < SMDSAbs_Face )
3677 // 2. Fill in auxiliary data structures
3678 // ----------------------------------
3682 set< QLink >::iterator pLink;
3683 set< QFace >::iterator pFace;
3685 bool isCurved = false;
3686 //bool hasRectFaces = false;
3687 //set<int> nbElemNodeSet;
3688 SMDS_VolumeTool volTool;
3690 TIDSortedNodeSet apexOfPyramid;
3691 const int apexIndex = 4;
3694 // Move medium nodes to the link middle for elements whose corner nodes
3695 // are out of geometrical boundary to fix distorted elements.
3696 force3DOutOfBoundary( *this, compError );
3698 if ( elemType == SMDSAbs_Volume )
3700 while ( elemIt->more() ) // loop on volumes
3702 const SMDS_MeshElement* vol = elemIt->next();
3703 if ( !vol->IsQuadratic() || !volTool.Set( vol ))
3705 double volMinSize2 = -1.;
3706 for ( int iF = 0; iF < volTool.NbFaces(); ++iF ) // loop on faces of volume
3708 int nbN = volTool.NbFaceNodes( iF );
3709 //nbElemNodeSet.insert( nbN );
3710 const SMDS_MeshNode** faceNodes = volTool.GetFaceNodes( iF );
3711 vector< const QLink* > faceLinks( nbN/2 );
3712 for ( int iN = 0; iN < nbN; iN += 2 ) // loop on links of a face
3715 QLink link( faceNodes[iN], faceNodes[iN+2], faceNodes[iN+1] );
3716 pLink = links.insert( link ).first;
3717 faceLinks[ iN/2 ] = & *pLink;
3719 if ( link.MediumPos() == SMDS_TOP_3DSPACE )
3721 if ( !link.IsStraight() )
3722 return; // already fixed
3724 else if ( !isCurved )
3726 if ( volMinSize2 < 0 ) volMinSize2 = volTool.MinLinearSize2();
3727 isCurved = !isStraightLink( volMinSize2, link._nodeMove.SquareMagnitude() );
3731 pFace = faces.insert( QFace( faceLinks )).first;
3732 if ( pFace->NbVolumes() == 0 )
3733 pFace->AddSelfToLinks();
3734 pFace->SetVolume( vol );
3735 // hasRectFaces = hasRectFaces ||
3736 // ( volTool.GetVolumeType() == SMDS_VolumeTool::QUAD_HEXA ||
3737 // volTool.GetVolumeType() == SMDS_VolumeTool::QUAD_PENTA );
3740 pFace->_face = GetMeshDS()->FindFace(faceNodes[0],faceNodes[2],faceNodes[4]);
3742 pFace->_face = GetMeshDS()->FindFace(faceNodes[0],faceNodes[2],
3743 faceNodes[4],faceNodes[6] );
3746 // collect pyramid apexes for further correction
3747 if ( vol->NbCornerNodes() == 5 )
3748 apexOfPyramid.insert( vol->GetNode( apexIndex ));
3750 set< QLink >::iterator pLink = links.begin();
3751 for ( ; pLink != links.end(); ++pLink )
3752 pLink->SetContinuesFaces();
3756 while ( elemIt->more() ) // loop on faces
3758 const SMDS_MeshElement* face = elemIt->next();
3759 if ( !face->IsQuadratic() )
3761 //nbElemNodeSet.insert( face->NbNodes() );
3762 int nbN = face->NbNodes()/2;
3763 vector< const QLink* > faceLinks( nbN );
3764 for ( int iN = 0; iN < nbN; ++iN ) // loop on links of a face
3767 QLink link( face->GetNode(iN), face->GetNode((iN+1)%nbN), face->GetNode(iN+nbN) );
3768 pLink = links.insert( link ).first;
3769 faceLinks[ iN ] = & *pLink;
3771 link.node1()->GetPosition()->GetTypeOfPosition() < 2 &&
3772 link.node2()->GetPosition()->GetTypeOfPosition() < 2 )
3773 isCurved = !link.IsStraight();
3776 pFace = faces.insert( QFace( faceLinks )).first;
3777 pFace->AddSelfToLinks();
3778 //hasRectFaces = ( hasRectFaces || nbN == 4 );
3782 return; // no curved edges of faces
3784 // 3. Compute displacement of medium nodes
3785 // ---------------------------------------
3787 // two loops on QFaces: the first is to treat boundary links, the second is for internal ones
3788 TopLoc_Location loc;
3789 // not treat boundary of volumic submesh
3790 int isInside = ( elemType == SMDSAbs_Volume && volumeOnly ) ? 1 : 0;
3791 for ( ; isInside < 2; ++isInside ) {
3792 MSG( "--------------- LOOP (inside=" << isInside << ") ------------------");
3793 SMDS_TypeOfPosition pos = isInside ? SMDS_TOP_3DSPACE : SMDS_TOP_FACE;
3794 SMDS_TypeOfPosition bndPos = isInside ? SMDS_TOP_FACE : SMDS_TOP_EDGE;
3796 for ( pFace = faces.begin(); pFace != faces.end(); ++pFace ) {
3797 if ( bool(isInside) == pFace->IsBoundary() )
3799 for ( int dir = 0; dir < 2; ++dir ) // 2 directions of propagation from the quadrangle
3802 // make chain of links connected via continues faces
3805 if ( !pFace->GetLinkChain( dir, rawChain, pos, error) && error ==ERR_UNKNOWN ) continue;
3807 if ( !pFace->GetLinkChain( dir+2, rawChain, pos, error ) && error ==ERR_UNKNOWN ) continue;
3809 vector< TChain > chains;
3810 if ( error == ERR_OK ) { // chain contains continues rectangles
3812 chains[0].splice( chains[0].begin(), rawChain );
3814 else if ( error == ERR_TRI ) { // chain contains continues triangles
3815 TSplitTriaResult res = splitTrianglesIntoChains( rawChain, chains, pos );
3816 if ( res != _OK ) { // not quadrangles split into triangles
3817 fixTriaNearBoundary( rawChain, *this );
3821 else if ( error == ERR_PRISM ) { // quadrangle side faces of prisms
3822 fixPrism( rawChain );
3828 for ( int iC = 0; iC < chains.size(); ++iC )
3830 TChain& chain = chains[iC];
3831 if ( chain.empty() ) continue;
3832 if ( chain.front().IsStraight() && chain.back().IsStraight() ) {
3833 MSG("3D straight - ignore");
3836 if ( chain.front()->MediumPos() > bndPos ||
3837 chain.back() ->MediumPos() > bndPos ) {
3838 MSG("Internal chain - ignore");
3841 // mesure chain length and compute link position along the chain
3842 double chainLen = 0;
3843 vector< double > linkPos;
3844 MSGBEG( "Link medium nodes: ");
3845 TChain::iterator link0 = chain.begin(), link1 = chain.begin(), link2;
3846 for ( ++link1; link1 != chain.end(); ++link1, ++link0 ) {
3847 MSGBEG( (*link0)->_mediumNode->GetID() << "-" <<(*link1)->_mediumNode->GetID()<<" ");
3848 double len = ((*link0)->MiddlePnt() - (*link1)->MiddlePnt()).Modulus();
3849 while ( len < numeric_limits<double>::min() ) { // remove degenerated link
3850 link1 = chain.erase( link1 );
3851 if ( link1 == chain.end() )
3853 len = ((*link0)->MiddlePnt() - (*link1)->MiddlePnt()).Modulus();
3856 linkPos.push_back( chainLen );
3859 if ( linkPos.size() < 2 )
3862 gp_Vec move0 = chain.front()->_nodeMove;
3863 gp_Vec move1 = chain.back ()->_nodeMove;
3866 bool checkUV = true;
3869 // compute node displacement of end links of chain in parametric space of face
3870 TChainLink& linkOnFace = *(++chain.begin());
3871 const SMDS_MeshNode* nodeOnFace = linkOnFace->_mediumNode;
3872 TopoDS_Shape f = GetSubShapeByNode( nodeOnFace, GetMeshDS() );
3873 if ( !f.IsNull() && f.ShapeType() == TopAbs_FACE )
3875 face = TopoDS::Face( f );
3876 Handle(Geom_Surface) surf = BRep_Tool::Surface(face,loc);
3878 for ( int is1 = 0; is1 < 2; ++is1 ) // move0 or move1
3880 TChainLink& link = is1 ? chain.back() : chain.front();
3881 gp_XY uvm = GetNodeUV( face, link->_mediumNode, nodeOnFace, &checkUV);
3882 gp_XY uv1 = GetNodeUV( face, link->node1(), nodeOnFace, &checkUV);
3883 gp_XY uv2 = GetNodeUV( face, link->node2(), nodeOnFace, &checkUV);
3884 gp_XY uv12 = GetMiddleUV( surf, uv1, uv2);
3885 // uvMove = uvm - uv12
3886 gp_XY uvMove = applyIn2D(surf, uvm, uv12, gp_XY_Subtracted, /*inPeriod=*/false);
3887 ( is1 ? move1 : move0 ).SetCoord( uvMove.X(), uvMove.Y(), 0 );
3888 if ( !is1 ) // correct nodeOnFace for move1 (issue 0020919)
3889 nodeOnFace = (*(++chain.rbegin()))->_mediumNode;
3890 isStraight[is1] = isStraightLink( (uv2-uv1).SquareModulus(),
3891 10 * uvMove.SquareModulus());
3893 if ( isStraight[0] && isStraight[1] ) {
3894 MSG("2D straight - ignore");
3895 continue; // straight - no need to move nodes of internal links
3898 // check if a chain is already fixed
3899 gp_XY uvm = GetNodeUV( face, linkOnFace->_mediumNode, 0, &checkUV);
3900 gp_XY uv1 = GetNodeUV( face, linkOnFace->node1(), nodeOnFace, &checkUV);
3901 gp_XY uv2 = GetNodeUV( face, linkOnFace->node2(), nodeOnFace, &checkUV);
3902 gp_XY uv12 = GetMiddleUV( surf, uv1, uv2);
3903 if (( uvm - uv12 ).SquareModulus() > 1e-10 )
3905 MSG("Already fixed - ignore");
3911 if ( isInside || face.IsNull() )
3913 // compute node displacement of end links in their local coord systems
3915 TChainLink& ln0 = chain.front(), ln1 = *(++chain.begin());
3916 trsf.SetTransformation( gp_Ax3( gp::Origin(), ln0.Normal(),
3917 gp_Vec( ln0->MiddlePnt(), ln1->MiddlePnt() )));
3918 move0.Transform(trsf);
3921 TChainLink& ln0 = *(++chain.rbegin()), ln1 = chain.back();
3922 trsf.SetTransformation( gp_Ax3( gp::Origin(), ln1.Normal(),
3923 gp_Vec( ln0->MiddlePnt(), ln1->MiddlePnt() )));
3924 move1.Transform(trsf);
3927 // compute displacement of medium nodes
3928 link2 = chain.begin();
3931 for ( int i = 0; link2 != chain.end(); ++link0, ++link1, ++link2, ++i )
3933 double r = linkPos[i] / chainLen;
3934 // displacement in local coord system
3935 gp_Vec move = (1. - r) * move0 + r * move1;
3936 if ( isInside || face.IsNull()) {
3937 // transform to global
3938 gp_Vec x01( (*link0)->MiddlePnt(), (*link1)->MiddlePnt() );
3939 gp_Vec x12( (*link1)->MiddlePnt(), (*link2)->MiddlePnt() );
3940 gp_Vec x = x01.Normalized() + x12.Normalized();
3941 trsf.SetTransformation( gp_Ax3( gp::Origin(), link1->Normal(), x), gp_Ax3() );
3942 move.Transform(trsf);
3945 // compute 3D displacement by 2D one
3946 Handle(Geom_Surface) s = BRep_Tool::Surface(face,loc);
3947 gp_XY oldUV = GetNodeUV( face, (*link1)->_mediumNode, 0, &checkUV);
3948 gp_XY newUV = applyIn2D( s, oldUV, gp_XY( move.X(),move.Y()), gp_XY_Added);
3949 gp_Pnt newPnt = s->Value( newUV.X(), newUV.Y());
3950 move = gp_Vec( XYZ((*link1)->_mediumNode), newPnt.Transformed(loc) );
3952 if ( (XYZ((*link1)->node1()) - XYZ((*link1)->node2())).SquareModulus() <
3953 move.SquareMagnitude())
3955 gp_XY uv0 = GetNodeUV( face, (*link0)->_mediumNode, 0, &checkUV);
3956 gp_XY uv2 = GetNodeUV( face, (*link2)->_mediumNode, 0, &checkUV);
3957 MSG( "TOO LONG MOVE \t" <<
3958 "uv0: "<<uv0.X()<<", "<<uv0.Y()<<" \t" <<
3959 "uv2: "<<uv2.X()<<", "<<uv2.Y()<<" \t" <<
3960 "uvOld: "<<oldUV.X()<<", "<<oldUV.Y()<<" \t" <<
3961 "newUV: "<<newUV.X()<<", "<<newUV.Y()<<" \t");
3965 (*link1)->Move( move );
3966 MSG( "Move " << (*link1)->_mediumNode->GetID() << " following "
3967 << chain.front()->_mediumNode->GetID() <<"-"
3968 << chain.back ()->_mediumNode->GetID() <<
3969 " by " << move.Magnitude());
3971 } // loop on chains of links
3972 } // loop on 2 directions of propagation from quadrangle
3974 } // fix faces and/or volumes
3979 for ( pLink = links.begin(); pLink != links.end(); ++pLink ) {
3980 if ( pLink->IsMoved() ) {
3981 gp_Pnt p = pLink->MiddlePnt() + pLink->Move();
3982 GetMeshDS()->MoveNode( pLink->_mediumNode, p.X(), p.Y(), p.Z());
3987 // Move the apex of pyramid together with the most curved link.
3988 // TIDSortedNodeSet::iterator apexIt = apexOfPyramid.begin();
3989 // for ( ; apexIt != apexOfPyramid.end(); ++apexIt )
3991 // SMESH_TNodeXYZ apex = *apexIt;
3993 // gp_Vec maxMove( 0,0,0 );
3994 // double maxMoveSize2 = 0;
3996 // // shift of node index to get medium nodes between the base nodes
3997 // const int base2MediumShift = 5;
3999 // // find maximal movement of medium node
4000 // SMDS_ElemIteratorPtr volIt = apex._node->GetInverseElementIterator( SMDSAbs_Volume );
4001 // vector< const SMDS_MeshElement* > pyramids;
4002 // while ( volIt->more() )
4004 // const SMDS_MeshElement* pyram = volIt->next();
4005 // if ( pyram->GetEntityType() != SMDSEntity_Quad_Pyramid ) continue;
4006 // pyramids.push_back( pyram );
4008 // for ( int iBase = 0; iBase < apexIndex; ++iBase )
4010 // SMESH_TNodeXYZ medium = pyram->GetNode( iBase + base2MediumShift );
4011 // if ( medium._node->GetPosition()->GetTypeOfPosition() != SMDS_TOP_3DSPACE )
4013 // SMESH_TNodeXYZ n1 = pyram->GetNode( iBase );
4014 // SMESH_TNodeXYZ n2 = pyram->GetNode( ( iBase+1 ) % 4 );
4015 // gp_Pnt middle = 0.5 * ( n1 + n2 );
4016 // gp_Vec move( middle, medium );
4017 // double moveSize2 = move.SquareMagnitude();
4018 // if ( moveSize2 > maxMoveSize2 )
4019 // maxMove = move, maxMoveSize2 = moveSize2;
4025 // if ( maxMoveSize2 > 1e-20 )
4027 // apex += maxMove.XYZ();
4028 // GetMeshDS()->MoveNode( apex._node, apex.X(), apex.Y(), apex.Z());
4030 // // move medium nodes neighboring the apex to the middle
4031 // const int base2MediumShift_2 = 9;
4032 // for ( unsigned i = 0; i < pyramids.size(); ++i )
4033 // for ( int iBase = 0; iBase < apexIndex; ++iBase )
4035 // SMESH_TNodeXYZ base = pyramids[i]->GetNode( iBase );
4036 // const SMDS_MeshNode* medium = pyramids[i]->GetNode( iBase + base2MediumShift_2 );
4037 // gp_XYZ middle = 0.5 * ( apex + base );
4038 // GetMeshDS()->MoveNode( medium, middle.X(), middle.Y(), middle.Z());