1 // Copyright (C) 2007-2015 CEA/DEN, EDF R&D, OPEN CASCADE
3 // Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License, or (at your option) any later version.
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 // Lesser General Public License for more details.
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
23 // 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_MeshAlgos.hxx"
36 #include "SMESH_ProxyMesh.hxx"
37 #include "SMESH_subMesh.hxx"
39 #include <BRepAdaptor_Curve.hxx>
40 #include <BRepAdaptor_Surface.hxx>
41 #include <BRepTools.hxx>
42 #include <BRep_Tool.hxx>
43 #include <Geom2d_Curve.hxx>
44 #include <GeomAPI_ProjectPointOnCurve.hxx>
45 #include <GeomAPI_ProjectPointOnSurf.hxx>
46 #include <Geom_Curve.hxx>
47 #include <Geom_RectangularTrimmedSurface.hxx>
48 #include <Geom_Surface.hxx>
49 #include <ShapeAnalysis.hxx>
51 #include <TopExp_Explorer.hxx>
52 #include <TopTools_ListIteratorOfListOfShape.hxx>
53 #include <TopTools_MapIteratorOfMapOfShape.hxx>
54 #include <TopTools_MapOfShape.hxx>
57 #include <gp_Pnt2d.hxx>
58 #include <gp_Trsf.hxx>
60 #include <Standard_Failure.hxx>
61 #include <Standard_ErrorHandler.hxx>
63 #include <utilities.h>
69 #define RETURN_BAD_RESULT(msg) { MESSAGE(msg); return false; }
73 inline SMESH_TNodeXYZ XYZ(const SMDS_MeshNode* n) { return SMESH_TNodeXYZ(n); }
75 enum { U_periodic = 1, V_periodic = 2 };
78 //================================================================================
82 //================================================================================
84 SMESH_MesherHelper::SMESH_MesherHelper(SMESH_Mesh& theMesh)
88 myCreateQuadratic(false),
89 myCreateBiQuadratic(false),
90 myFixNodeParameters(false)
92 myPar1[0] = myPar2[0] = myPar1[1] = myPar2[1] = 0;
93 mySetElemOnShape = ( ! myMesh->HasShapeToMesh() );
96 //=======================================================================
97 //function : ~SMESH_MesherHelper
99 //=======================================================================
101 SMESH_MesherHelper::~SMESH_MesherHelper()
104 TID2ProjectorOnSurf::iterator i_proj = myFace2Projector.begin();
105 for ( ; i_proj != myFace2Projector.end(); ++i_proj )
106 delete i_proj->second;
109 TID2ProjectorOnCurve::iterator i_proj = myEdge2Projector.begin();
110 for ( ; i_proj != myEdge2Projector.end(); ++i_proj )
111 delete i_proj->second;
115 //=======================================================================
116 //function : IsQuadraticSubMesh
117 //purpose : Check submesh for given shape: if all elements on this shape
118 // are quadratic, quadratic elements will be created.
119 // Also fill myTLinkNodeMap
120 //=======================================================================
122 bool SMESH_MesherHelper::IsQuadraticSubMesh(const TopoDS_Shape& aSh)
124 SMESHDS_Mesh* meshDS = GetMeshDS();
125 // we can create quadratic elements only if all elements
126 // created on sub-shapes of given shape are quadratic
127 // also we have to fill myTLinkNodeMap
128 myCreateQuadratic = true;
129 mySeamShapeIds.clear();
130 myDegenShapeIds.clear();
131 TopAbs_ShapeEnum subType( aSh.ShapeType()==TopAbs_FACE ? TopAbs_EDGE : TopAbs_FACE );
132 if ( aSh.ShapeType()==TopAbs_COMPOUND )
134 TopoDS_Iterator subIt( aSh );
136 subType = ( subIt.Value().ShapeType()==TopAbs_FACE ) ? TopAbs_EDGE : TopAbs_FACE;
138 SMDSAbs_ElementType elemType( subType==TopAbs_FACE ? SMDSAbs_Face : SMDSAbs_Edge );
141 int nbOldLinks = myTLinkNodeMap.size();
143 if ( !myMesh->HasShapeToMesh() )
145 if (( myCreateQuadratic = myMesh->NbFaces( ORDER_QUADRATIC )))
147 SMDS_FaceIteratorPtr fIt = meshDS->facesIterator();
148 while ( fIt->more() )
149 AddTLinks( static_cast< const SMDS_MeshFace* >( fIt->next() ));
154 TopExp_Explorer exp( aSh, subType );
155 TopTools_MapOfShape checkedSubShapes;
156 for (; exp.More() && myCreateQuadratic; exp.Next()) {
157 if ( !checkedSubShapes.Add( exp.Current() ))
158 continue; // needed if aSh is compound of solids
159 if ( SMESHDS_SubMesh * subMesh = meshDS->MeshElements( exp.Current() )) {
160 if ( SMDS_ElemIteratorPtr it = subMesh->GetElements() ) {
162 const SMDS_MeshElement* e = it->next();
163 if ( e->GetType() != elemType || !e->IsQuadratic() ) {
164 myCreateQuadratic = false;
169 switch ( e->NbCornerNodes() ) {
171 AddTLinkNode(e->GetNode(0),e->GetNode(1),e->GetNode(2)); break;
173 AddTLinkNode(e->GetNode(0),e->GetNode(1),e->GetNode(3));
174 AddTLinkNode(e->GetNode(1),e->GetNode(2),e->GetNode(4));
175 AddTLinkNode(e->GetNode(2),e->GetNode(0),e->GetNode(5)); break;
177 AddTLinkNode(e->GetNode(0),e->GetNode(1),e->GetNode(4));
178 AddTLinkNode(e->GetNode(1),e->GetNode(2),e->GetNode(5));
179 AddTLinkNode(e->GetNode(2),e->GetNode(3),e->GetNode(6));
180 AddTLinkNode(e->GetNode(3),e->GetNode(0),e->GetNode(7));
183 myCreateQuadratic = false;
193 if ( nbOldLinks == myTLinkNodeMap.size() )
194 myCreateQuadratic = false;
196 if(!myCreateQuadratic) {
197 myTLinkNodeMap.clear();
201 return myCreateQuadratic;
204 //=======================================================================
205 //function : SetSubShape
206 //purpose : Set geometry to make elements on
207 //=======================================================================
209 void SMESH_MesherHelper::SetSubShape(const int aShID)
211 if ( aShID == myShapeID )
214 SetSubShape( GetMeshDS()->IndexToShape( aShID ));
216 SetSubShape( TopoDS_Shape() );
219 //=======================================================================
220 //function : SetSubShape
221 //purpose : Set geometry to create elements on
222 //=======================================================================
224 void SMESH_MesherHelper::SetSubShape(const TopoDS_Shape& aSh)
226 if ( myShape.IsSame( aSh ))
230 mySeamShapeIds.clear();
231 myDegenShapeIds.clear();
233 if ( myShape.IsNull() ) {
237 SMESHDS_Mesh* meshDS = GetMeshDS();
238 myShapeID = meshDS->ShapeToIndex(aSh);
241 // treatment of periodic faces
242 for ( TopExp_Explorer eF( aSh, TopAbs_FACE ); eF.More(); eF.Next() )
244 const TopoDS_Face& face = TopoDS::Face( eF.Current() );
245 BRepAdaptor_Surface surf( face, false );
246 if ( surf.IsUPeriodic() || surf.IsUClosed() ) {
247 myParIndex |= U_periodic;
248 myPar1[0] = surf.FirstUParameter();
249 myPar2[0] = surf.LastUParameter();
251 if ( surf.IsVPeriodic() || surf.IsVClosed() ) {
252 myParIndex |= V_periodic;
253 myPar1[1] = surf.FirstVParameter();
254 myPar2[1] = surf.LastVParameter();
258 for (TopExp_Explorer exp( face, TopAbs_EDGE ); exp.More(); exp.Next())
260 // look for a "seam" edge, a real seam or an edge on period boundary
261 TopoDS_Edge edge = TopoDS::Edge( exp.Current() );
262 const int edgeID = meshDS->ShapeToIndex( edge );
265 BRep_Tool::UVPoints( edge, face, uv1, uv2 );
266 const double du = Abs( uv1.Coord(1) - uv2.Coord(1) );
267 const double dv = Abs( uv1.Coord(2) - uv2.Coord(2) );
269 bool isSeam = BRep_Tool::IsClosed( edge, face );
270 if ( isSeam ) // real seam - having two pcurves on face
272 // pcurve can lie not on pediod boundary (22582, mesh_Quadratic_01/C9)
275 double u1 = uv1.Coord(1);
277 BRep_Tool::UVPoints( edge, face, uv1, uv2 );
278 double u2 = uv1.Coord(1);
279 myPar1[0] = Min( u1, u2 );
280 myPar2[0] = Max( u1, u2 );
284 double v1 = uv1.Coord(2);
286 BRep_Tool::UVPoints( edge, face, uv1, uv2 );
287 double v2 = uv1.Coord(2);
288 myPar1[1] = Min( v1, v2 );
289 myPar2[1] = Max( v1, v2 );
292 else //if ( !isSeam )
294 // one pcurve but on period boundary (22772, mesh_Quadratic_01/D1)
295 if (( myParIndex & U_periodic ) && du < Precision::PConfusion() )
297 isSeam = ( Abs( uv1.Coord(1) - myPar1[0] ) < Precision::PConfusion() ||
298 Abs( uv1.Coord(1) - myPar2[0] ) < Precision::PConfusion() );
300 else if (( myParIndex & V_periodic ) && dv < Precision::PConfusion() )
302 isSeam = ( Abs( uv1.Coord(2) - myPar1[1] ) < Precision::PConfusion() ||
303 Abs( uv1.Coord(2) - myPar2[1] ) < Precision::PConfusion() );
305 if ( isSeam ) // vertices are on period boundary, check a middle point (23032)
307 double f,l, r = 0.2345;
308 Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface( edge, face, f, l );
309 uv2 = C2d->Value( f * r + l * ( 1.-r ));
310 if ( du < Precision::PConfusion() )
311 isSeam = ( Abs( uv1.Coord(1) - uv2.Coord(1) ) < Precision::PConfusion() );
313 isSeam = ( Abs( uv1.Coord(2) - uv2.Coord(2) ) < Precision::PConfusion() );
318 // store seam shape indices, negative if shape encounters twice ('real seam')
319 mySeamShapeIds.insert( IsSeamShape( edgeID ) ? -edgeID : edgeID );
320 for ( TopExp_Explorer v( edge, TopAbs_VERTEX ); v.More(); v.Next() ) {
321 int vertexID = meshDS->ShapeToIndex( v.Current() );
322 mySeamShapeIds.insert( IsSeamShape( vertexID ) ? -vertexID : vertexID );
326 // look for a degenerated edge
327 if ( SMESH_Algo::isDegenerated( edge )) {
328 myDegenShapeIds.insert( edgeID );
329 for ( TopExp_Explorer v( edge, TopAbs_VERTEX ); v.More(); v.Next() )
330 myDegenShapeIds.insert( meshDS->ShapeToIndex( v.Current() ));
332 if ( !BRep_Tool::SameParameter( edge ) ||
333 !BRep_Tool::SameRange( edge ))
335 setPosOnShapeValidity( edgeID, false );
341 //=======================================================================
342 //function : GetNodeUVneedInFaceNode
343 //purpose : Check if inFaceNode argument is necessary for call GetNodeUV(F,..)
344 // Return true if the face is periodic.
345 // If F is Null, answer about sub-shape set through IsQuadraticSubMesh() or
347 //=======================================================================
349 bool SMESH_MesherHelper::GetNodeUVneedInFaceNode(const TopoDS_Face& F) const
351 if ( F.IsNull() ) return !mySeamShapeIds.empty();
353 if ( !F.IsNull() && !myShape.IsNull() && myShape.IsSame( F ))
354 return !mySeamShapeIds.empty();
357 Handle(Geom_Surface) aSurface = BRep_Tool::Surface( F,loc );
358 if ( !aSurface.IsNull() )
359 return ( aSurface->IsUPeriodic() || aSurface->IsVPeriodic() );
364 //=======================================================================
365 //function : IsMedium
367 //=======================================================================
369 bool SMESH_MesherHelper::IsMedium(const SMDS_MeshNode* node,
370 const SMDSAbs_ElementType typeToCheck)
372 return SMESH_MeshEditor::IsMedium( node, typeToCheck );
375 //=======================================================================
376 //function : GetSubShapeByNode
377 //purpose : Return support shape of a node
378 //=======================================================================
380 TopoDS_Shape SMESH_MesherHelper::GetSubShapeByNode(const SMDS_MeshNode* node,
381 const SMESHDS_Mesh* meshDS)
383 int shapeID = node ? node->getshapeId() : 0;
384 if ( 0 < shapeID && shapeID <= meshDS->MaxShapeIndex() )
385 return meshDS->IndexToShape( shapeID );
387 return TopoDS_Shape();
391 //=======================================================================
392 //function : AddTLinkNode
393 //purpose : add a link in my data structure
394 //=======================================================================
396 void SMESH_MesherHelper::AddTLinkNode(const SMDS_MeshNode* n1,
397 const SMDS_MeshNode* n2,
398 const SMDS_MeshNode* n12)
400 // add new record to map
401 SMESH_TLink link( n1, n2 );
402 myTLinkNodeMap.insert( make_pair(link,n12));
405 //================================================================================
407 * \brief Add quadratic links of edge to own data structure
409 //================================================================================
411 bool SMESH_MesherHelper::AddTLinks(const SMDS_MeshEdge* edge)
413 if ( edge && edge->IsQuadratic() )
414 AddTLinkNode(edge->GetNode(0), edge->GetNode(1), edge->GetNode(2));
420 //================================================================================
422 * \brief Add quadratic links of face to own data structure
424 //================================================================================
426 bool SMESH_MesherHelper::AddTLinks(const SMDS_MeshFace* f)
430 switch ( f->NbNodes() ) {
432 // myMapWithCentralNode.insert
433 // ( make_pair( TBiQuad( f->GetNode(0),f->GetNode(1),f->GetNode(2) ),
435 // break; -- add medium nodes as well
437 AddTLinkNode(f->GetNode(0),f->GetNode(1),f->GetNode(3));
438 AddTLinkNode(f->GetNode(1),f->GetNode(2),f->GetNode(4));
439 AddTLinkNode(f->GetNode(2),f->GetNode(0),f->GetNode(5)); break;
442 // myMapWithCentralNode.insert
443 // ( make_pair( TBiQuad( f->GetNode(0),f->GetNode(1),f->GetNode(2),f->GetNode(3) ),
445 // break; -- add medium nodes as well
447 AddTLinkNode(f->GetNode(0),f->GetNode(1),f->GetNode(4));
448 AddTLinkNode(f->GetNode(1),f->GetNode(2),f->GetNode(5));
449 AddTLinkNode(f->GetNode(2),f->GetNode(3),f->GetNode(6));
450 AddTLinkNode(f->GetNode(3),f->GetNode(0),f->GetNode(7)); break;
457 //================================================================================
459 * \brief Add quadratic links of volume to own data structure
461 //================================================================================
463 bool SMESH_MesherHelper::AddTLinks(const SMDS_MeshVolume* volume)
465 if ( volume->IsQuadratic() )
467 SMDS_VolumeTool vTool( volume );
468 const SMDS_MeshNode** nodes = vTool.GetNodes();
470 for ( int iF = 1; iF < vTool.NbFaces(); ++iF )
472 const int nbN = vTool.NbFaceNodes( iF );
473 const int* iNodes = vTool.GetFaceNodesIndices( iF );
474 for ( int i = 0; i < nbN; )
476 int iN1 = iNodes[i++];
477 int iN12 = iNodes[i++];
479 if ( iN1 > iN2 ) std::swap( iN1, iN2 );
480 int linkID = iN1 * vTool.NbNodes() + iN2;
481 pair< set<int>::iterator, bool > it_isNew = addedLinks.insert( linkID );
482 if ( it_isNew.second )
483 AddTLinkNode( nodes[iN1], nodes[iN2], nodes[iN12] );
485 addedLinks.erase( it_isNew.first ); // each link encounters only twice
487 if ( vTool.NbNodes() == 27 )
489 const SMDS_MeshNode* nFCenter = nodes[ vTool.GetCenterNodeIndex( iF )];
490 if ( nFCenter->GetPosition()->GetTypeOfPosition() == SMDS_TOP_3DSPACE )
491 myMapWithCentralNode.insert
492 ( make_pair( TBiQuad( nodes[ iNodes[0]], nodes[ iNodes[1]],
493 nodes[ iNodes[2]], nodes[ iNodes[3]] ),
502 //================================================================================
504 * \brief Return true if position of nodes on the shape hasn't yet been checked or
505 * the positions proved to be invalid
507 //================================================================================
509 bool SMESH_MesherHelper::toCheckPosOnShape(int shapeID ) const
511 map< int,bool >::const_iterator id_ok = myNodePosShapesValidity.find( shapeID );
512 return ( id_ok == myNodePosShapesValidity.end() || !id_ok->second );
515 //================================================================================
517 * \brief Set validity of positions of nodes on the shape.
518 * Once set, validity is not changed
520 //================================================================================
522 void SMESH_MesherHelper::setPosOnShapeValidity(int shapeID, bool ok ) const
524 std::map< int,bool >::iterator sh_ok =
525 ((SMESH_MesherHelper*)this)->myNodePosShapesValidity.insert( make_pair( shapeID, ok)).first;
530 //=======================================================================
531 //function : ToFixNodeParameters
532 //purpose : Enables fixing node parameters on EDGEs and FACEs in
533 // GetNodeU(...,check=true), GetNodeUV(...,check=true), CheckNodeUV() and
534 // CheckNodeU() in case if a node lies on a shape set via SetSubShape().
536 //=======================================================================
538 void SMESH_MesherHelper::ToFixNodeParameters(bool toFix)
540 myFixNodeParameters = toFix;
544 //=======================================================================
545 //function : getUVOnSeam
546 //purpose : Select UV on either of 2 pcurves of a seam edge, closest to the given UV
547 //=======================================================================
549 gp_Pnt2d SMESH_MesherHelper::getUVOnSeam( const gp_Pnt2d& uv1, const gp_Pnt2d& uv2 ) const
551 gp_Pnt2d result = uv1;
552 for ( int i = U_periodic; i <= V_periodic ; ++i )
554 if ( myParIndex & i )
556 double p1 = uv1.Coord( i );
557 double dp1 = Abs( p1-myPar1[i-1]), dp2 = Abs( p1-myPar2[i-1]);
558 if ( myParIndex == i ||
559 dp1 < ( myPar2[i-1] - myPar1[i-1] ) / 100. ||
560 dp2 < ( myPar2[i-1] - myPar1[i-1] ) / 100. )
562 double p2 = uv2.Coord( i );
563 double p1Alt = ( dp1 < dp2 ) ? myPar2[i-1] : myPar1[i-1];
564 if ( Abs( p2 - p1 ) > Abs( p2 - p1Alt ))
565 result.SetCoord( i, p1Alt );
572 //=======================================================================
573 //function : GetNodeUV
574 //purpose : Return node UV on face
575 //=======================================================================
577 gp_XY SMESH_MesherHelper::GetNodeUV(const TopoDS_Face& F,
578 const SMDS_MeshNode* n,
579 const SMDS_MeshNode* n2,
582 gp_Pnt2d uv( Precision::Infinite(), Precision::Infinite() );
584 const SMDS_PositionPtr Pos = n->GetPosition();
586 if ( Pos->GetTypeOfPosition() == SMDS_TOP_FACE )
588 // node has position on face
589 const SMDS_FacePosition* fpos = static_cast<const SMDS_FacePosition*>( Pos );
590 uv.SetCoord( fpos->GetUParameter(), fpos->GetVParameter() );
592 uvOK = CheckNodeUV( F, n, uv.ChangeCoord(), 2.*getFaceMaxTol( F )); // 2. from 22830
594 else if ( Pos->GetTypeOfPosition() == SMDS_TOP_EDGE )
596 // node has position on EDGE => it is needed to find
597 // corresponding EDGE from FACE, get pcurve for this
598 // EDGE and retrieve value from this pcurve
599 const SMDS_EdgePosition* epos = static_cast<const SMDS_EdgePosition*>( Pos );
600 const int edgeID = n->getshapeId();
601 const TopoDS_Edge& E = TopoDS::Edge( GetMeshDS()->IndexToShape( edgeID ));
602 double f, l, u = epos->GetUParameter();
603 Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface( E, F, f, l );
604 bool validU = ( !C2d.IsNull() && ( f < u ) && ( u < l ));
605 if ( validU ) uv = C2d->Value( u );
606 else uv.SetCoord( Precision::Infinite(),0.);
607 if ( check || !validU )
608 uvOK = CheckNodeUV( F, n, uv.ChangeCoord(), 2.*getFaceMaxTol( F ),/*force=*/ !validU );
610 // for a node on a seam EDGE select one of UVs on 2 pcurves
611 if ( n2 && IsSeamShape( edgeID ))
613 uv = getUVOnSeam( uv, GetNodeUV( F, n2, 0, check ));
616 { // adjust uv to period
618 Handle(Geom_Surface) S = BRep_Tool::Surface(F,loc);
619 Standard_Boolean isUPeriodic = S->IsUPeriodic();
620 Standard_Boolean isVPeriodic = S->IsVPeriodic();
622 if ( isUPeriodic || isVPeriodic ) {
623 Standard_Real UF,UL,VF,VL;
624 S->Bounds(UF,UL,VF,VL);
625 if ( isUPeriodic ) newUV.SetX( uv.X() + ShapeAnalysis::AdjustToPeriod(uv.X(),UF,UL));
626 if ( isVPeriodic ) newUV.SetY( uv.Y() + ShapeAnalysis::AdjustToPeriod(uv.Y(),VF,VL));
630 gp_Pnt2d uv2 = GetNodeUV( F, n2, 0, check );
631 if ( isUPeriodic && Abs( uv.X()-uv2.X() ) < Abs( newUV.X()-uv2.X() ))
632 newUV.SetX( uv.X() );
633 if ( isVPeriodic && Abs( uv.Y()-uv2.Y() ) < Abs( newUV.Y()-uv2.Y() ))
634 newUV.SetY( uv.Y() );
640 else if ( Pos->GetTypeOfPosition() == SMDS_TOP_VERTEX )
642 if ( int vertexID = n->getshapeId() ) {
643 const TopoDS_Vertex& V = TopoDS::Vertex(GetMeshDS()->IndexToShape(vertexID));
645 uv = BRep_Tool::Parameters( V, F );
648 catch (Standard_Failure& exc) {
651 for ( TopExp_Explorer vert(F,TopAbs_VERTEX); !uvOK && vert.More(); vert.Next() )
652 uvOK = ( V == vert.Current() );
654 MESSAGE ( "SMESH_MesherHelper::GetNodeUV(); Vertex " << vertexID
655 << " not in face " << GetMeshDS()->ShapeToIndex( F ) );
656 // get UV of a vertex closest to the node
658 gp_Pnt pn = XYZ( n );
659 for ( TopExp_Explorer vert( F,TopAbs_VERTEX ); !uvOK && vert.More(); vert.Next() ) {
660 TopoDS_Vertex curV = TopoDS::Vertex( vert.Current() );
661 gp_Pnt p = BRep_Tool::Pnt( curV );
662 double curDist = p.SquareDistance( pn );
663 if ( curDist < dist ) {
665 uv = BRep_Tool::Parameters( curV, F );
666 uvOK = ( dist < DBL_MIN );
672 TopTools_ListIteratorOfListOfShape it( myMesh->GetAncestors( V ));
673 for ( ; it.More(); it.Next() ) {
674 if ( it.Value().ShapeType() == TopAbs_EDGE ) {
675 const TopoDS_Edge & edge = TopoDS::Edge( it.Value() );
677 Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface(edge, F, f, l);
678 if ( !C2d.IsNull() ) {
679 double u = ( V == TopExp::FirstVertex( edge ) ) ? f : l;
680 uv = C2d->Value( u );
688 if ( n2 && IsSeamShape( vertexID ))
690 bool isSeam = ( myShape.IsSame( F ));
692 SMESH_MesherHelper h( *myMesh );
694 isSeam = IsSeamShape( vertexID );
698 uv = getUVOnSeam( uv, GetNodeUV( F, n2, 0 ));
704 uvOK = CheckNodeUV( F, n, uv.ChangeCoord(), 2.*getFaceMaxTol( F ));
707 if ( check && !uvOK )
713 //=======================================================================
714 //function : CheckNodeUV
715 //purpose : Check and fix node UV on a face
716 //=======================================================================
718 bool SMESH_MesherHelper::CheckNodeUV(const TopoDS_Face& F,
719 const SMDS_MeshNode* n,
723 double distXYZ[4]) const
725 int shapeID = n->getshapeId();
727 if (( infinit = ( Precision::IsInfinite( uv.X() ) || Precision::IsInfinite( uv.Y() ))) ||
729 ( uv.X() == 0. && uv.Y() == 0. ) ||
730 ( toCheckPosOnShape( shapeID )))
732 // check that uv is correct
734 Handle(Geom_Surface) surface = BRep_Tool::Surface( F,loc );
735 gp_Pnt nodePnt = XYZ( n ), surfPnt(0,0,0);
737 if ( !loc.IsIdentity() ) nodePnt.Transform( loc.Transformation().Inverted() );
739 (dist = nodePnt.Distance( surfPnt = surface->Value( uv.X(), uv.Y() ))) > tol )
741 setPosOnShapeValidity( shapeID, false );
742 if ( !infinit && distXYZ ) {
743 surfPnt.Transform( loc );
745 distXYZ[1] = surfPnt.X(); distXYZ[2] = surfPnt.Y(); distXYZ[3]=surfPnt.Z();
747 // uv incorrect, project the node to surface
748 GeomAPI_ProjectPointOnSurf& projector = GetProjector( F, loc, tol );
749 projector.Perform( nodePnt );
750 if ( !projector.IsDone() || projector.NbPoints() < 1 )
752 MESSAGE( "SMESH_MesherHelper::CheckNodeUV() failed to project" );
755 Quantity_Parameter U,V;
756 projector.LowerDistanceParameters(U,V);
758 surfPnt = surface->Value( U, V );
759 dist = nodePnt.Distance( surfPnt );
761 surfPnt.Transform( loc );
763 distXYZ[1] = surfPnt.X(); distXYZ[2] = surfPnt.Y(); distXYZ[3]=surfPnt.Z();
767 MESSAGE( "SMESH_MesherHelper::CheckNodeUV(), invalid projection" );
770 // store the fixed UV on the face
771 if ( myShape.IsSame(F) && shapeID == myShapeID && myFixNodeParameters )
772 const_cast<SMDS_MeshNode*>(n)->SetPosition
773 ( SMDS_PositionPtr( new SMDS_FacePosition( U, V )));
775 else if ( myShape.IsSame(F) && uv.Modulus() > numeric_limits<double>::min() )
777 setPosOnShapeValidity( shapeID, true );
783 //=======================================================================
784 //function : GetProjector
785 //purpose : Return projector intitialized by given face without location, which is returned
786 //=======================================================================
788 GeomAPI_ProjectPointOnSurf& SMESH_MesherHelper::GetProjector(const TopoDS_Face& F,
789 TopLoc_Location& loc,
792 Handle(Geom_Surface) surface = BRep_Tool::Surface( F,loc );
793 int faceID = GetMeshDS()->ShapeToIndex( F );
794 TID2ProjectorOnSurf& i2proj = const_cast< TID2ProjectorOnSurf&>( myFace2Projector );
795 TID2ProjectorOnSurf::iterator i_proj = i2proj.find( faceID );
796 if ( i_proj == i2proj.end() )
798 if ( tol == 0 ) tol = BRep_Tool::Tolerance( F );
799 double U1, U2, V1, V2;
800 surface->Bounds(U1, U2, V1, V2);
801 GeomAPI_ProjectPointOnSurf* proj = new GeomAPI_ProjectPointOnSurf();
802 proj->Init( surface, U1, U2, V1, V2, tol );
803 i_proj = i2proj.insert( make_pair( faceID, proj )).first;
805 return *( i_proj->second );
810 gp_XY AverageUV(const gp_XY& uv1, const gp_XY& uv2) { return ( uv1 + uv2 ) / 2.; }
811 gp_XY_FunPtr(Added); // define gp_XY_Added pointer to function calling gp_XY::Added(gp_XY)
812 gp_XY_FunPtr(Subtracted);
815 //=======================================================================
816 //function : applyIn2D
817 //purpose : Perform given operation on two 2d points in parameric space of given surface.
818 // It takes into account period of the surface. Use gp_XY_FunPtr macro
819 // to easily define pointer to function of gp_XY class.
820 //=======================================================================
822 gp_XY SMESH_MesherHelper::applyIn2D(const Handle(Geom_Surface)& surface,
826 const bool resultInPeriod)
828 Standard_Boolean isUPeriodic = surface.IsNull() ? false : surface->IsUPeriodic();
829 Standard_Boolean isVPeriodic = surface.IsNull() ? false : surface->IsVPeriodic();
830 if ( !isUPeriodic && !isVPeriodic )
833 // move uv2 not far than half-period from uv1
835 uv2.X()+(isUPeriodic ? ShapeAnalysis::AdjustByPeriod(uv2.X(),uv1.X(),surface->UPeriod()) :0);
837 uv2.Y()+(isVPeriodic ? ShapeAnalysis::AdjustByPeriod(uv2.Y(),uv1.Y(),surface->VPeriod()) :0);
840 gp_XY res = fun( uv1, gp_XY(u2,v2) );
842 // move result within period
843 if ( resultInPeriod )
845 Standard_Real UF,UL,VF,VL;
846 surface->Bounds(UF,UL,VF,VL);
848 res.SetX( res.X() + ShapeAnalysis::AdjustToPeriod(res.X(),UF,UL));
850 res.SetY( res.Y() + ShapeAnalysis::AdjustToPeriod(res.Y(),VF,VL));
855 //=======================================================================
856 //function : GetMiddleUV
857 //purpose : Return middle UV taking in account surface period
858 //=======================================================================
860 gp_XY SMESH_MesherHelper::GetMiddleUV(const Handle(Geom_Surface)& surface,
865 // the proper place of getting basic surface seems to be in applyIn2D()
866 // but we put it here to decrease a risk of regressions just before releasing a version
867 Handle(Geom_Surface) surf = surface;
868 while ( !surf.IsNull() && surf->IsKind(STANDARD_TYPE(Geom_RectangularTrimmedSurface )))
869 surf = Handle(Geom_RectangularTrimmedSurface)::DownCast( surf )->BasisSurface();
871 return applyIn2D( surf, p1, p2, & AverageUV );
874 //=======================================================================
875 //function : GetCenterUV
876 //purpose : Return UV for the central node of a biquadratic triangle
877 //=======================================================================
879 gp_XY SMESH_MesherHelper::GetCenterUV(const gp_XY& uv1,
885 bool * isBadTria/*=0*/)
888 gp_XY uvAvg = ( uv12 + uv23 + uv31 ) / 3.;
890 if (( badTria = (( uvAvg - uv1 ) * ( uvAvg - uv23 ) > 0 )))
891 uvAvg = ( uv1 + uv23 ) / 2.;
892 else if (( badTria = (( uvAvg - uv2 ) * ( uvAvg - uv31 ) > 0 )))
893 uvAvg = ( uv2 + uv31 ) / 2.;
894 else if (( badTria = (( uvAvg - uv3 ) * ( uvAvg - uv12 ) > 0 )))
895 uvAvg = ( uv3 + uv12 ) / 2.;
898 *isBadTria = badTria;
902 //=======================================================================
903 //function : GetNodeU
904 //purpose : Return node U on edge
905 //=======================================================================
907 double SMESH_MesherHelper::GetNodeU(const TopoDS_Edge& E,
908 const SMDS_MeshNode* n,
909 const SMDS_MeshNode* inEdgeNode,
912 double param = Precision::Infinite();
914 const SMDS_PositionPtr pos = n->GetPosition();
915 if ( pos->GetTypeOfPosition()==SMDS_TOP_EDGE )
917 const SMDS_EdgePosition* epos = static_cast<const SMDS_EdgePosition*>( pos );
918 param = epos->GetUParameter();
920 else if( pos->GetTypeOfPosition() == SMDS_TOP_VERTEX )
922 if ( inEdgeNode && TopExp::FirstVertex( E ).IsSame( TopExp::LastVertex( E ))) // issue 0020128
925 BRep_Tool::Range( E, f,l );
926 double uInEdge = GetNodeU( E, inEdgeNode );
927 param = ( fabs( uInEdge - f ) < fabs( l - uInEdge )) ? f : l;
931 SMESHDS_Mesh * meshDS = GetMeshDS();
932 int vertexID = n->getshapeId();
933 const TopoDS_Vertex& V = TopoDS::Vertex(meshDS->IndexToShape(vertexID));
934 param = BRep_Tool::Parameter( V, E );
939 double tol = BRep_Tool::Tolerance( E );
940 double f,l; BRep_Tool::Range( E, f,l );
941 bool force = ( param < f-tol || param > l+tol );
942 if ( !force && pos->GetTypeOfPosition()==SMDS_TOP_EDGE )
943 force = ( GetMeshDS()->ShapeToIndex( E ) != n->getshapeId() );
945 *check = CheckNodeU( E, n, param, 2*tol, force );
950 //=======================================================================
951 //function : CheckNodeU
952 //purpose : Check and fix node U on an edge
953 // Return false if U is bad and could not be fixed
954 //=======================================================================
956 bool SMESH_MesherHelper::CheckNodeU(const TopoDS_Edge& E,
957 const SMDS_MeshNode* n,
961 double distXYZ[4]) const
963 int shapeID = n->getshapeId();
965 if (( infinit = Precision::IsInfinite( u )) ||
968 ( toCheckPosOnShape( shapeID )))
970 TopLoc_Location loc; double f,l;
971 Handle(Geom_Curve) curve = BRep_Tool::Curve( E,loc,f,l );
972 if ( curve.IsNull() ) // degenerated edge
974 if ( u+tol < f || u-tol > l )
976 double r = Max( 0.5, 1 - tol*n->GetID()); // to get a unique u on edge
982 gp_Pnt nodePnt = SMESH_TNodeXYZ( n );
983 if ( !loc.IsIdentity() ) nodePnt.Transform( loc.Transformation().Inverted() );
988 curvPnt = curve->Value( u );
989 dist = nodePnt.Distance( curvPnt );
991 curvPnt.Transform( loc );
993 distXYZ[1] = curvPnt.X(); distXYZ[2] = curvPnt.Y(); distXYZ[3]=curvPnt.Z();
998 setPosOnShapeValidity( shapeID, false );
999 // u incorrect, project the node to the curve
1000 int edgeID = GetMeshDS()->ShapeToIndex( E );
1001 TID2ProjectorOnCurve& i2proj = const_cast< TID2ProjectorOnCurve&>( myEdge2Projector );
1002 TID2ProjectorOnCurve::iterator i_proj =
1003 i2proj.insert( make_pair( edgeID, (GeomAPI_ProjectPointOnCurve*) 0 )).first;
1004 if ( !i_proj->second )
1006 i_proj->second = new GeomAPI_ProjectPointOnCurve();
1007 i_proj->second->Init( curve, f, l );
1009 GeomAPI_ProjectPointOnCurve* projector = i_proj->second;
1010 projector->Perform( nodePnt );
1011 if ( projector->NbPoints() < 1 )
1013 MESSAGE( "SMESH_MesherHelper::CheckNodeU() failed to project" );
1016 Quantity_Parameter U = projector->LowerDistanceParameter();
1018 MESSAGE(" f " << f << " l " << l << " u " << u);
1019 curvPnt = curve->Value( u );
1020 dist = nodePnt.Distance( curvPnt );
1022 curvPnt.Transform( loc );
1024 distXYZ[1] = curvPnt.X(); distXYZ[2] = curvPnt.Y(); distXYZ[3]=curvPnt.Z();
1028 MESSAGE( "SMESH_MesherHelper::CheckNodeU(), invalid projection" );
1029 MESSAGE("distance " << dist << " " << tol );
1032 // store the fixed U on the edge
1033 if ( myShape.IsSame(E) && shapeID == myShapeID && myFixNodeParameters )
1034 const_cast<SMDS_MeshNode*>(n)->SetPosition
1035 ( SMDS_PositionPtr( new SMDS_EdgePosition( U )));
1037 else if ( fabs( u ) > numeric_limits<double>::min() )
1039 setPosOnShapeValidity( shapeID, true );
1041 if (( u < f-tol || u > l+tol ) && force )
1043 MESSAGE("u < f-tol || u > l+tol ; u " << u << " f " << f << " l " << l);
1044 // node is on vertex but is set on periodic but trimmed edge (issue 0020890)
1047 // do not use IsPeriodic() as Geom_TrimmedCurve::IsPeriodic () returns false
1048 double period = curve->Period();
1049 u = ( u < f ) ? u + period : u - period;
1051 catch (Standard_Failure& exc)
1061 //=======================================================================
1062 //function : GetMediumPos
1063 //purpose : Return index and type of the shape (EDGE or FACE only) to
1064 // set a medium node on
1065 //param : useCurSubShape - if true, returns the shape set via SetSubShape()
1067 //param : expectedSupport - shape type corresponding to element being created,
1068 // e.g TopAbs_EDGE if SMDSAbs_Edge is created
1069 // basing on \a n1 and \a n2
1070 // Calling GetMediumPos() with useCurSubShape=true is OK only for the
1071 // case where the lower dim mesh is already constructed and converted to quadratic,
1072 // else, nodes on EDGEs are assigned to FACE, for example.
1073 //=======================================================================
1075 std::pair<int, TopAbs_ShapeEnum>
1076 SMESH_MesherHelper::GetMediumPos(const SMDS_MeshNode* n1,
1077 const SMDS_MeshNode* n2,
1078 const bool useCurSubShape,
1079 TopAbs_ShapeEnum expectedSupport)
1081 if ( useCurSubShape && !myShape.IsNull() )
1082 return std::make_pair( myShapeID, myShape.ShapeType() );
1084 TopAbs_ShapeEnum shapeType = TopAbs_SHAPE;
1088 if (( myShapeID == n1->getshapeId() || myShapeID == n2->getshapeId() ) && myShapeID > 0 )
1090 shapeType = myShape.ShapeType();
1091 shapeID = myShapeID;
1093 else if ( n1->getshapeId() == n2->getshapeId() )
1095 shapeID = n2->getshapeId();
1096 shape = GetSubShapeByNode( n1, GetMeshDS() );
1098 else // 2 different shapes
1100 const SMDS_TypeOfPosition Pos1 = n1->GetPosition()->GetTypeOfPosition();
1101 const SMDS_TypeOfPosition Pos2 = n2->GetPosition()->GetTypeOfPosition();
1103 if ( Pos1 == SMDS_TOP_3DSPACE || Pos2 == SMDS_TOP_3DSPACE )
1107 else if ( Pos1 == SMDS_TOP_FACE || Pos2 == SMDS_TOP_FACE )
1110 if ( Pos1 != SMDS_TOP_FACE || Pos2 != SMDS_TOP_FACE ) // not 2 FACEs
1112 if ( Pos1 != SMDS_TOP_FACE ) std::swap( n1,n2 );
1113 TopoDS_Shape F = GetSubShapeByNode( n1, GetMeshDS() );
1114 TopoDS_Shape S = GetSubShapeByNode( n2, GetMeshDS() );
1115 if ( IsSubShape( S, F ))
1117 shapeType = TopAbs_FACE;
1118 shapeID = n1->getshapeId();
1122 else if ( Pos1 == SMDS_TOP_EDGE && Pos2 == SMDS_TOP_EDGE )
1124 TopoDS_Shape E1 = GetSubShapeByNode( n1, GetMeshDS() );
1125 TopoDS_Shape E2 = GetSubShapeByNode( n2, GetMeshDS() );
1126 shape = GetCommonAncestor( E1, E2, *myMesh, TopAbs_FACE );
1128 else if ( Pos1 == SMDS_TOP_VERTEX && Pos2 == SMDS_TOP_VERTEX )
1130 TopoDS_Shape V1 = GetSubShapeByNode( n1, GetMeshDS() );
1131 TopoDS_Shape V2 = GetSubShapeByNode( n2, GetMeshDS() );
1132 shape = GetCommonAncestor( V1, V2, *myMesh, TopAbs_EDGE );
1133 if ( shape.IsNull() ) shape = GetCommonAncestor( V1, V2, *myMesh, TopAbs_FACE );
1135 else // on VERTEX and EDGE
1137 if ( Pos1 != SMDS_TOP_VERTEX ) std::swap( n1,n2 );
1138 TopoDS_Shape V = GetSubShapeByNode( n1, GetMeshDS() );
1139 TopoDS_Shape E = GetSubShapeByNode( n2, GetMeshDS() );
1140 if ( IsSubShape( V, E ))
1143 shape = GetCommonAncestor( V, E, *myMesh, TopAbs_FACE );
1147 if ( !shape.IsNull() )
1150 shapeID = GetMeshDS()->ShapeToIndex( shape );
1151 shapeType = shape.ShapeType(); // EDGE or FACE
1153 if ( expectedSupport < shapeType &&
1154 expectedSupport != TopAbs_SHAPE &&
1155 !myShape.IsNull() &&
1156 myShape.ShapeType() == expectedSupport )
1158 // e.g. a side of triangle connects nodes on the same EDGE but does not
1159 // lie on this EDGE (an arc with a coarse mesh)
1160 // => shapeType == TopAbs_EDGE, expectedSupport == TopAbs_FACE;
1161 // hope that myShape is a right shape, return it if the found shape
1162 // has converted elements of corresponding dim (segments in our example)
1163 int nbConvertedElems = 0;
1164 SMDSAbs_ElementType type = ( shapeType == TopAbs_FACE ? SMDSAbs_Face : SMDSAbs_Edge );
1165 for ( int iN = 0; iN < 2; ++iN )
1167 const SMDS_MeshNode* n = iN ? n2 : n1;
1168 SMDS_ElemIteratorPtr it = n->GetInverseElementIterator( type );
1169 while ( it->more() )
1171 const SMDS_MeshElement* elem = it->next();
1172 if ( elem->getshapeId() == shapeID &&
1173 elem->IsQuadratic() )
1180 if ( nbConvertedElems == 2 )
1182 shapeType = myShape.ShapeType();
1183 shapeID = myShapeID;
1187 return make_pair( shapeID, shapeType );
1190 //=======================================================================
1191 //function : GetCentralNode
1192 //purpose : Return existing or create a new central node for a quardilateral
1193 // quadratic face given its 8 nodes.
1194 //@param : force3d - true means node creation in between the given nodes,
1195 // else node position is found on a geometrical face if any.
1196 //=======================================================================
1198 const SMDS_MeshNode* SMESH_MesherHelper::GetCentralNode(const SMDS_MeshNode* n1,
1199 const SMDS_MeshNode* n2,
1200 const SMDS_MeshNode* n3,
1201 const SMDS_MeshNode* n4,
1202 const SMDS_MeshNode* n12,
1203 const SMDS_MeshNode* n23,
1204 const SMDS_MeshNode* n34,
1205 const SMDS_MeshNode* n41,
1208 SMDS_MeshNode *centralNode = 0; // central node to return
1210 // Find an existing central node
1212 TBiQuad keyOfMap(n1,n2,n3,n4);
1213 std::map<TBiQuad, const SMDS_MeshNode* >::iterator itMapCentralNode;
1214 itMapCentralNode = myMapWithCentralNode.find( keyOfMap );
1215 if ( itMapCentralNode != myMapWithCentralNode.end() )
1217 return (*itMapCentralNode).second;
1220 // Get type of shape for the new central node
1222 TopAbs_ShapeEnum shapeType = TopAbs_SHAPE;
1226 TopTools_ListIteratorOfListOfShape it;
1228 std::map< int, int > faceId2nbNodes;
1229 std::map< int, int > ::iterator itMapWithIdFace;
1231 SMESHDS_Mesh* meshDS = GetMeshDS();
1233 // check if a face lies on a FACE, i.e. its all corner nodes lie either on the FACE or
1234 // on sub-shapes of the FACE
1235 if ( GetMesh()->HasShapeToMesh() )
1237 const SMDS_MeshNode* nodes[] = { n1, n2, n3, n4 };
1238 for(int i = 0; i < 4; i++)
1240 shape = GetSubShapeByNode( nodes[i], meshDS );
1241 if ( shape.IsNull() ) break;
1242 if ( shape.ShapeType() == TopAbs_SOLID )
1244 solidID = nodes[i]->getshapeId();
1245 shapeType = TopAbs_SOLID;
1248 if ( shape.ShapeType() == TopAbs_FACE )
1250 faceID = nodes[i]->getshapeId();
1251 itMapWithIdFace = faceId2nbNodes.insert( std::make_pair( faceID, 0 ) ).first;
1252 itMapWithIdFace->second++;
1256 PShapeIteratorPtr it = GetAncestors( shape, *GetMesh(), TopAbs_FACE );
1257 while ( const TopoDS_Shape* face = it->next() )
1259 faceID = meshDS->ShapeToIndex( *face );
1260 itMapWithIdFace = faceId2nbNodes.insert( std::make_pair( faceID, 0 )).first;
1261 itMapWithIdFace->second++;
1266 if ( solidID < 1 && !faceId2nbNodes.empty() ) // SOLID not found
1268 // find ID of the FACE the four corner nodes belong to
1269 itMapWithIdFace = faceId2nbNodes.begin();
1270 for ( ; itMapWithIdFace != faceId2nbNodes.end(); ++itMapWithIdFace)
1272 if ( itMapWithIdFace->second == 4 )
1274 shapeType = TopAbs_FACE;
1275 faceID = (*itMapWithIdFace).first;
1282 if ( shapeType == TopAbs_FACE )
1284 F = TopoDS::Face( meshDS->IndexToShape( faceID ));
1291 bool toCheck = true;
1292 if ( !F.IsNull() && !force3d )
1294 uvAvg = calcTFI (0.5, 0.5,
1295 GetNodeUV(F,n1,n3,&toCheck), GetNodeUV(F,n2,n4,&toCheck),
1296 GetNodeUV(F,n3,n1,&toCheck), GetNodeUV(F,n4,n2,&toCheck),
1297 GetNodeUV(F,n12,n3), GetNodeUV(F,n23,n4),
1298 GetNodeUV(F,n34,n2), GetNodeUV(F,n41,n2));
1299 TopLoc_Location loc;
1300 Handle( Geom_Surface ) S = BRep_Tool::Surface( F, loc );
1301 P = S->Value( uvAvg.X(), uvAvg.Y() ).Transformed( loc );
1302 centralNode = meshDS->AddNode( P.X(), P.Y(), P.Z() );
1303 // if ( mySetElemOnShape ) node is not elem!
1304 meshDS->SetNodeOnFace( centralNode, faceID, uvAvg.X(), uvAvg.Y() );
1306 else // ( force3d || F.IsNull() )
1308 P = calcTFI (0.5, 0.5,
1309 SMESH_TNodeXYZ(n1), SMESH_TNodeXYZ(n2),
1310 SMESH_TNodeXYZ(n3), SMESH_TNodeXYZ(n4),
1311 SMESH_TNodeXYZ(n12), SMESH_TNodeXYZ(n23),
1312 SMESH_TNodeXYZ(n34), SMESH_TNodeXYZ(n41));
1313 centralNode = meshDS->AddNode( P.X(), P.Y(), P.Z() );
1315 if ( !F.IsNull() ) // force3d
1317 uvAvg = (GetNodeUV(F,n1,n3,&toCheck) +
1318 GetNodeUV(F,n2,n4,&toCheck) +
1319 GetNodeUV(F,n3,n1,&toCheck) +
1320 GetNodeUV(F,n4,n2,&toCheck)) / 4;
1321 //CheckNodeUV( F, centralNode, uvAvg, 2*BRep_Tool::Tolerance( F ), /*force=*/true);
1322 meshDS->SetNodeOnFace( centralNode, faceID, uvAvg.X(), uvAvg.Y() );
1324 else if ( solidID > 0 )
1326 meshDS->SetNodeInVolume( centralNode, solidID );
1328 else if ( myShapeID > 0 && mySetElemOnShape )
1330 meshDS->SetMeshElementOnShape( centralNode, myShapeID );
1333 myMapWithCentralNode.insert( std::make_pair( keyOfMap, centralNode ) );
1337 //=======================================================================
1338 //function : GetCentralNode
1339 //purpose : Return existing or create a new central node for a
1340 // quadratic triangle given its 6 nodes.
1341 //@param : force3d - true means node creation in between the given nodes,
1342 // else node position is found on a geometrical face if any.
1343 //=======================================================================
1345 const SMDS_MeshNode* SMESH_MesherHelper::GetCentralNode(const SMDS_MeshNode* n1,
1346 const SMDS_MeshNode* n2,
1347 const SMDS_MeshNode* n3,
1348 const SMDS_MeshNode* n12,
1349 const SMDS_MeshNode* n23,
1350 const SMDS_MeshNode* n31,
1353 SMDS_MeshNode *centralNode = 0; // central node to return
1355 // Find an existing central node
1357 TBiQuad keyOfMap(n1,n2,n3);
1358 std::map<TBiQuad, const SMDS_MeshNode* >::iterator itMapCentralNode;
1359 itMapCentralNode = myMapWithCentralNode.find( keyOfMap );
1360 if ( itMapCentralNode != myMapWithCentralNode.end() )
1362 return (*itMapCentralNode).second;
1365 // Get type of shape for the new central node
1367 TopAbs_ShapeEnum shapeType = TopAbs_SHAPE;
1371 TopTools_ListIteratorOfListOfShape it;
1373 std::map< int, int > faceId2nbNodes;
1374 std::map< int, int > ::iterator itMapWithIdFace;
1376 SMESHDS_Mesh* meshDS = GetMeshDS();
1378 // check if a face lies on a FACE, i.e. its all corner nodes lie either on the FACE or
1379 // on sub-shapes of the FACE
1380 if ( GetMesh()->HasShapeToMesh() )
1382 const SMDS_MeshNode* nodes[] = { n1, n2, n3 };
1383 for(int i = 0; i < 3; i++)
1385 shape = GetSubShapeByNode( nodes[i], meshDS );
1386 if ( shape.IsNull() ) break;
1387 if ( shape.ShapeType() == TopAbs_SOLID )
1389 solidID = nodes[i]->getshapeId();
1390 shapeType = TopAbs_SOLID;
1393 if ( shape.ShapeType() == TopAbs_FACE )
1395 faceID = nodes[i]->getshapeId();
1396 itMapWithIdFace = faceId2nbNodes.insert( std::make_pair( faceID, 0 ) ).first;
1397 itMapWithIdFace->second++;
1401 PShapeIteratorPtr it = GetAncestors(shape, *GetMesh(), TopAbs_FACE );
1402 while ( const TopoDS_Shape* face = it->next() )
1404 faceID = meshDS->ShapeToIndex( *face );
1405 itMapWithIdFace = faceId2nbNodes.insert( std::make_pair( faceID, 0 ) ).first;
1406 itMapWithIdFace->second++;
1411 if ( solidID < 1 && !faceId2nbNodes.empty() ) // SOLID not found
1413 // find ID of the FACE the four corner nodes belong to
1414 itMapWithIdFace = faceId2nbNodes.begin();
1415 for ( ; itMapWithIdFace != faceId2nbNodes.end(); ++itMapWithIdFace)
1417 if ( itMapWithIdFace->second == 3 )
1419 shapeType = TopAbs_FACE;
1420 faceID = (*itMapWithIdFace).first;
1429 if ( shapeType == TopAbs_FACE )
1431 F = TopoDS::Face( meshDS->IndexToShape( faceID ));
1432 bool checkOK = true, badTria = false;
1433 gp_XY uv1 = GetNodeUV( F, n1, n23, &checkOK );
1434 gp_XY uv2 = GetNodeUV( F, n2, n31, &checkOK );
1435 gp_XY uv3 = GetNodeUV( F, n3, n12, &checkOK );
1436 gp_XY uv12 = GetNodeUV( F, n12, n3, &checkOK );
1437 gp_XY uv23 = GetNodeUV( F, n23, n1, &checkOK );
1438 gp_XY uv31 = GetNodeUV( F, n31, n2, &checkOK );
1439 uvAvg = GetCenterUV( uv1,uv2,uv3, uv12,uv23,uv31, &badTria );
1440 if ( badTria || !checkOK )
1444 // Create a central node
1447 if ( !F.IsNull() && !force3d )
1449 TopLoc_Location loc;
1450 Handle( Geom_Surface ) S = BRep_Tool::Surface( F, loc );
1451 P = S->Value( uvAvg.X(), uvAvg.Y() ).Transformed( loc );
1452 centralNode = meshDS->AddNode( P.X(), P.Y(), P.Z() );
1453 // if ( mySetElemOnShape ) node is not elem!
1454 meshDS->SetNodeOnFace( centralNode, faceID, uvAvg.X(), uvAvg.Y() );
1456 else // ( force3d || F.IsNull() )
1458 P = ( SMESH_TNodeXYZ( n12 ) +
1459 SMESH_TNodeXYZ( n23 ) +
1460 SMESH_TNodeXYZ( n31 ) ) / 3;
1461 centralNode = meshDS->AddNode( P.X(), P.Y(), P.Z() );
1463 if ( !F.IsNull() ) // force3d
1465 meshDS->SetNodeOnFace( centralNode, faceID, uvAvg.X(), uvAvg.Y() );
1467 else if ( solidID > 0 )
1469 meshDS->SetNodeInVolume( centralNode, solidID );
1471 else if ( myShapeID > 0 && mySetElemOnShape )
1473 meshDS->SetMeshElementOnShape( centralNode, myShapeID );
1476 myMapWithCentralNode.insert( std::make_pair( keyOfMap, centralNode ) );
1480 //=======================================================================
1481 //function : GetMediumNode
1482 //purpose : Return existing or create a new medium node between given ones
1483 //=======================================================================
1485 const SMDS_MeshNode* SMESH_MesherHelper::GetMediumNode(const SMDS_MeshNode* n1,
1486 const SMDS_MeshNode* n2,
1488 TopAbs_ShapeEnum expectedSupport)
1490 // Find existing node
1492 SMESH_TLink link(n1,n2);
1493 ItTLinkNode itLN = myTLinkNodeMap.find( link );
1494 if ( itLN != myTLinkNodeMap.end() ) {
1495 return (*itLN).second;
1498 // Create medium node
1501 SMESHDS_Mesh* meshDS = GetMeshDS();
1503 if ( IsSeamShape( n1->getshapeId() ))
1504 // to get a correct UV of a node on seam, the second node must have checked UV
1505 std::swap( n1, n2 );
1507 // get type of shape for the new medium node
1508 int faceID = -1, edgeID = -1;
1509 TopoDS_Edge E; double u [2];
1510 TopoDS_Face F; gp_XY uv[2];
1511 bool uvOK[2] = { true, true };
1512 const bool useCurSubShape = ( !myShape.IsNull() && myShape.ShapeType() == TopAbs_EDGE );
1514 pair<int, TopAbs_ShapeEnum> pos = GetMediumPos( n1, n2, useCurSubShape, expectedSupport );
1516 // get positions of the given nodes on shapes
1517 if ( pos.second == TopAbs_FACE )
1519 F = TopoDS::Face(meshDS->IndexToShape( faceID = pos.first ));
1520 uv[0] = GetNodeUV(F,n1,n2, force3d ? 0 : &uvOK[0]);
1521 uv[1] = GetNodeUV(F,n2,n1, force3d ? 0 : &uvOK[1]);
1523 else if ( pos.second == TopAbs_EDGE )
1525 const SMDS_PositionPtr Pos1 = n1->GetPosition();
1526 const SMDS_PositionPtr Pos2 = n2->GetPosition();
1527 if ( Pos1->GetTypeOfPosition()==SMDS_TOP_EDGE &&
1528 Pos2->GetTypeOfPosition()==SMDS_TOP_EDGE &&
1529 n1->getshapeId() != n2->getshapeId() )
1532 return getMediumNodeOnComposedWire(n1,n2,force3d);
1534 E = TopoDS::Edge(meshDS->IndexToShape( edgeID = pos.first ));
1536 u[0] = GetNodeU(E,n1,n2, force3d ? 0 : &uvOK[0]);
1537 u[1] = GetNodeU(E,n2,n1, force3d ? 0 : &uvOK[1]);
1539 catch ( Standard_Failure& f )
1541 // issue 22502 / a node is on VERTEX not belonging to E
1542 // issue 22568 / both nodes are on non-connected VERTEXes
1543 return getMediumNodeOnComposedWire(n1,n2,force3d);
1547 if ( !force3d & uvOK[0] && uvOK[1] )
1549 // we try to create medium node using UV parameters of
1550 // nodes, else - medium between corresponding 3d points
1553 //if ( uvOK[0] && uvOK[1] )
1555 if ( IsDegenShape( n1->getshapeId() )) {
1556 if ( myParIndex & U_periodic ) uv[0].SetCoord( 1, uv[1].Coord( 1 ));
1557 else uv[0].SetCoord( 2, uv[1].Coord( 2 ));
1559 else if ( IsDegenShape( n2->getshapeId() )) {
1560 if ( myParIndex & U_periodic ) uv[1].SetCoord( 1, uv[0].Coord( 1 ));
1561 else uv[1].SetCoord( 2, uv[0].Coord( 2 ));
1563 TopLoc_Location loc;
1564 Handle(Geom_Surface) S = BRep_Tool::Surface(F,loc);
1565 gp_XY UV = GetMiddleUV( S, uv[0], uv[1] );
1566 gp_Pnt P = S->Value( UV.X(), UV.Y() ).Transformed(loc);
1567 n12 = meshDS->AddNode(P.X(), P.Y(), P.Z());
1568 // if ( mySetElemOnShape ) node is not elem!
1569 meshDS->SetNodeOnFace(n12, faceID, UV.X(), UV.Y());
1570 myTLinkNodeMap.insert(make_pair(link,n12));
1574 else if ( !E.IsNull() )
1577 Handle(Geom_Curve) C = BRep_Tool::Curve(E, f, l);
1580 Standard_Boolean isPeriodic = C->IsPeriodic();
1583 Standard_Real Period = C->Period();
1584 Standard_Real p = u[1]+ShapeAnalysis::AdjustByPeriod(u[1],u[0],Period);
1585 Standard_Real pmid = (u[0]+p)/2.;
1586 U = pmid+ShapeAnalysis::AdjustToPeriod(pmid,C->FirstParameter(),C->LastParameter());
1591 gp_Pnt P = C->Value( U );
1592 n12 = meshDS->AddNode(P.X(), P.Y(), P.Z());
1593 //if ( mySetElemOnShape ) node is not elem!
1594 meshDS->SetNodeOnEdge(n12, edgeID, U);
1595 myTLinkNodeMap.insert(make_pair(link,n12));
1602 double x = ( n1->X() + n2->X() )/2.;
1603 double y = ( n1->Y() + n2->Y() )/2.;
1604 double z = ( n1->Z() + n2->Z() )/2.;
1605 n12 = meshDS->AddNode(x,y,z);
1607 //if ( mySetElemOnShape ) node is not elem!
1611 gp_XY UV = ( uv[0] + uv[1] ) / 2.;
1612 CheckNodeUV( F, n12, UV, 2 * BRep_Tool::Tolerance( F ), /*force=*/true);
1613 meshDS->SetNodeOnFace(n12, faceID, UV.X(), UV.Y() );
1615 else if ( !E.IsNull() )
1617 double U = ( u[0] + u[1] ) / 2.;
1618 CheckNodeU( E, n12, U, 2 * BRep_Tool::Tolerance( E ), /*force=*/true);
1619 meshDS->SetNodeOnEdge(n12, edgeID, U);
1621 else if ( myShapeID > 0 && mySetElemOnShape )
1623 meshDS->SetMeshElementOnShape(n12, myShapeID);
1627 myTLinkNodeMap.insert( make_pair( link, n12 ));
1631 //================================================================================
1633 * \brief Makes a medium node if nodes reside different edges
1635 //================================================================================
1637 const SMDS_MeshNode* SMESH_MesherHelper::getMediumNodeOnComposedWire(const SMDS_MeshNode* n1,
1638 const SMDS_MeshNode* n2,
1641 SMESH_TNodeXYZ p1( n1 ), p2( n2 );
1642 gp_Pnt middle = 0.5 * p1 + 0.5 * p2;
1643 SMDS_MeshNode* n12 = AddNode( middle.X(), middle.Y(), middle.Z() );
1645 // To find position on edge and 3D position for n12,
1646 // project <middle> to 2 edges and select projection most close to <middle>
1648 TopoDS_Edge bestEdge;
1649 double u = 0, distMiddleProj = Precision::Infinite(), distXYZ[4], f,l;
1651 // get shapes under the nodes
1652 TopoDS_Shape shape[2];
1654 for ( int is2nd = 0; is2nd < 2; ++is2nd )
1656 const SMDS_MeshNode* n = is2nd ? n2 : n1;
1657 TopoDS_Shape S = GetSubShapeByNode( n, GetMeshDS() );
1659 shape[ nbShapes++ ] = S;
1662 vector< TopoDS_Shape > edges;
1663 for ( int iS = 0; iS < nbShapes; ++iS )
1665 switch ( shape[iS].ShapeType() ) {
1668 edges.push_back( shape[iS] );
1674 if ( nbShapes == 2 && iS==0 && shape[1-iS].ShapeType() == TopAbs_VERTEX )
1675 edge = GetCommonAncestor( shape[iS], shape[1-iS], *myMesh, TopAbs_EDGE );
1677 if ( edge.IsNull() )
1679 PShapeIteratorPtr eIt = GetAncestors( shape[iS], *myMesh, TopAbs_EDGE );
1680 while( const TopoDS_Shape* e = eIt->next() )
1681 edges.push_back( *e );
1687 if ( nbShapes == 1 || shape[1-iS].ShapeType() < TopAbs_EDGE )
1688 for ( TopExp_Explorer e( shape[iS], TopAbs_EDGE ); e.More(); e.Next() )
1689 edges.push_back( e.Current() );
1696 // project to get U of projection and distance from middle to projection
1697 for ( size_t iE = 0; iE < edges.size(); ++iE )
1699 const TopoDS_Edge& edge = TopoDS::Edge( edges[ iE ]);
1700 distXYZ[0] = distMiddleProj;
1702 CheckNodeU( edge, n12, testU, 2 * BRep_Tool::Tolerance(edge), /*force=*/true, distXYZ );
1703 if ( distXYZ[0] < distMiddleProj )
1705 distMiddleProj = distXYZ[0];
1711 // // both projections failed; set n12 on the edge of n1 with U of a common vertex
1712 // TopoDS_Vertex vCommon;
1713 // if ( TopExp::CommonVertex( edges[0], edges[1], vCommon ))
1714 // u = BRep_Tool::Parameter( vCommon, edges[0] );
1717 // double f,l, u0 = GetNodeU( edges[0], n1 );
1718 // BRep_Tool::Range( edges[0],f,l );
1719 // u = ( fabs(u0-f) < fabs(u0-l) ) ? f : l;
1722 // distMiddleProj = 0;
1725 if ( !bestEdge.IsNull() )
1727 // move n12 to position of a successfull projection
1728 //double tol = BRep_Tool::Tolerance(edges[ iOkEdge ]);
1729 if ( !force3d /*&& distMiddleProj > 2*tol*/ )
1731 TopLoc_Location loc;
1732 Handle(Geom_Curve) curve = BRep_Tool::Curve( bestEdge,loc,f,l );
1733 gp_Pnt p = curve->Value( u ).Transformed( loc );
1734 GetMeshDS()->MoveNode( n12, p.X(), p.Y(), p.Z() );
1736 //if ( mySetElemOnShape ) node is not elem!
1738 int edgeID = GetMeshDS()->ShapeToIndex( bestEdge );
1739 if ( edgeID != n12->getshapeId() )
1740 GetMeshDS()->UnSetNodeOnShape( n12 );
1741 GetMeshDS()->SetNodeOnEdge(n12, edgeID, u);
1744 myTLinkNodeMap.insert( make_pair( SMESH_TLink(n1,n2), n12 ));
1749 //=======================================================================
1750 //function : AddNode
1751 //purpose : Creates a node
1752 //=======================================================================
1754 SMDS_MeshNode* SMESH_MesherHelper::AddNode(double x, double y, double z, int ID,
1757 SMESHDS_Mesh * meshDS = GetMeshDS();
1758 SMDS_MeshNode* node = 0;
1760 node = meshDS->AddNodeWithID( x, y, z, ID );
1762 node = meshDS->AddNode( x, y, z );
1763 if ( mySetElemOnShape && myShapeID > 0 ) { // node is not elem ?
1764 switch ( myShape.ShapeType() ) {
1765 case TopAbs_SOLID: meshDS->SetNodeInVolume( node, myShapeID); break;
1766 case TopAbs_SHELL: meshDS->SetNodeInVolume( node, myShapeID); break;
1767 case TopAbs_FACE: meshDS->SetNodeOnFace( node, myShapeID, u, v); break;
1768 case TopAbs_EDGE: meshDS->SetNodeOnEdge( node, myShapeID, u); break;
1769 case TopAbs_VERTEX: meshDS->SetNodeOnVertex( node, myShapeID); break;
1776 //=======================================================================
1777 //function : AddEdge
1778 //purpose : Creates quadratic or linear edge
1779 //=======================================================================
1781 SMDS_MeshEdge* SMESH_MesherHelper::AddEdge(const SMDS_MeshNode* n1,
1782 const SMDS_MeshNode* n2,
1786 SMESHDS_Mesh * meshDS = GetMeshDS();
1788 SMDS_MeshEdge* edge = 0;
1789 if (myCreateQuadratic) {
1790 const SMDS_MeshNode* n12 = GetMediumNode(n1,n2,force3d);
1792 edge = meshDS->AddEdgeWithID(n1, n2, n12, id);
1794 edge = meshDS->AddEdge(n1, n2, n12);
1798 edge = meshDS->AddEdgeWithID(n1, n2, id);
1800 edge = meshDS->AddEdge(n1, n2);
1803 if ( mySetElemOnShape && myShapeID > 0 )
1804 meshDS->SetMeshElementOnShape( edge, myShapeID );
1809 //=======================================================================
1810 //function : AddFace
1811 //purpose : Creates quadratic or linear triangle
1812 //=======================================================================
1814 SMDS_MeshFace* SMESH_MesherHelper::AddFace(const SMDS_MeshNode* n1,
1815 const SMDS_MeshNode* n2,
1816 const SMDS_MeshNode* n3,
1820 SMESHDS_Mesh * meshDS = GetMeshDS();
1821 SMDS_MeshFace* elem = 0;
1823 if( n1==n2 || n2==n3 || n3==n1 )
1826 if(!myCreateQuadratic) {
1828 elem = meshDS->AddFaceWithID(n1, n2, n3, id);
1830 elem = meshDS->AddFace(n1, n2, n3);
1833 const SMDS_MeshNode* n12 = GetMediumNode( n1, n2, force3d, TopAbs_FACE );
1834 const SMDS_MeshNode* n23 = GetMediumNode( n2, n3, force3d, TopAbs_FACE );
1835 const SMDS_MeshNode* n31 = GetMediumNode( n3, n1, force3d, TopAbs_FACE );
1836 if(myCreateBiQuadratic)
1838 const SMDS_MeshNode* nCenter = GetCentralNode(n1, n2, n3, n12, n23, n31, force3d);
1840 elem = meshDS->AddFaceWithID(n1, n2, n3, n12, n23, n31, nCenter, id);
1842 elem = meshDS->AddFace(n1, n2, n3, n12, n23, n31, nCenter);
1847 elem = meshDS->AddFaceWithID(n1, n2, n3, n12, n23, n31, id);
1849 elem = meshDS->AddFace(n1, n2, n3, n12, n23, n31);
1852 if ( mySetElemOnShape && myShapeID > 0 )
1853 meshDS->SetMeshElementOnShape( elem, myShapeID );
1858 //=======================================================================
1859 //function : AddFace
1860 //purpose : Creates bi-quadratic, quadratic or linear quadrangle
1861 //=======================================================================
1863 SMDS_MeshFace* SMESH_MesherHelper::AddFace(const SMDS_MeshNode* n1,
1864 const SMDS_MeshNode* n2,
1865 const SMDS_MeshNode* n3,
1866 const SMDS_MeshNode* n4,
1870 SMESHDS_Mesh * meshDS = GetMeshDS();
1871 SMDS_MeshFace* elem = 0;
1874 return AddFace(n1,n3,n4,id,force3d);
1877 return AddFace(n1,n2,n4,id,force3d);
1880 return AddFace(n1,n2,n3,id,force3d);
1883 return AddFace(n1,n2,n4,id,force3d);
1886 return AddFace(n1,n2,n3,id,force3d);
1889 return AddFace(n1,n2,n3,id,force3d);
1892 if(!myCreateQuadratic) {
1894 elem = meshDS->AddFaceWithID(n1, n2, n3, n4, id);
1896 elem = meshDS->AddFace(n1, n2, n3, n4);
1899 const SMDS_MeshNode* n12 = GetMediumNode( n1, n2, force3d, TopAbs_FACE );
1900 const SMDS_MeshNode* n23 = GetMediumNode( n2, n3, force3d, TopAbs_FACE );
1901 const SMDS_MeshNode* n34 = GetMediumNode( n3, n4, force3d, TopAbs_FACE );
1902 const SMDS_MeshNode* n41 = GetMediumNode( n4, n1, force3d, TopAbs_FACE );
1903 if(myCreateBiQuadratic)
1905 const SMDS_MeshNode* nCenter = GetCentralNode(n1, n2, n3, n4, n12, n23, n34, n41, force3d);
1907 elem = meshDS->AddFaceWithID(n1, n2, n3, n4, n12, n23, n34, n41, nCenter, id);
1909 elem = meshDS->AddFace(n1, n2, n3, n4, n12, n23, n34, n41, nCenter);
1914 elem = meshDS->AddFaceWithID(n1, n2, n3, n4, n12, n23, n34, n41, id);
1916 elem = meshDS->AddFace(n1, n2, n3, n4, n12, n23, n34, n41);
1919 if ( mySetElemOnShape && myShapeID > 0 )
1920 meshDS->SetMeshElementOnShape( elem, myShapeID );
1925 //=======================================================================
1926 //function : AddPolygonalFace
1927 //purpose : Creates polygon, with additional nodes in quadratic mesh
1928 //=======================================================================
1930 SMDS_MeshFace* SMESH_MesherHelper::AddPolygonalFace (const vector<const SMDS_MeshNode*>& nodes,
1934 SMESHDS_Mesh * meshDS = GetMeshDS();
1935 SMDS_MeshFace* elem = 0;
1937 if(!myCreateQuadratic) {
1939 elem = meshDS->AddPolygonalFaceWithID(nodes, id);
1941 elem = meshDS->AddPolygonalFace(nodes);
1944 vector<const SMDS_MeshNode*> newNodes;
1945 for ( int i = 0; i < nodes.size(); ++i )
1947 const SMDS_MeshNode* n1 = nodes[i];
1948 const SMDS_MeshNode* n2 = nodes[(i+1)%nodes.size()];
1949 const SMDS_MeshNode* n12 = GetMediumNode( n1, n2, force3d, TopAbs_FACE );
1950 newNodes.push_back( n1 );
1951 newNodes.push_back( n12 );
1954 elem = meshDS->AddPolygonalFaceWithID(newNodes, id);
1956 elem = meshDS->AddPolygonalFace(newNodes);
1958 if ( mySetElemOnShape && myShapeID > 0 )
1959 meshDS->SetMeshElementOnShape( elem, myShapeID );
1964 //=======================================================================
1965 //function : AddVolume
1966 //purpose : Creates quadratic or linear prism
1967 //=======================================================================
1969 SMDS_MeshVolume* SMESH_MesherHelper::AddVolume(const SMDS_MeshNode* n1,
1970 const SMDS_MeshNode* n2,
1971 const SMDS_MeshNode* n3,
1972 const SMDS_MeshNode* n4,
1973 const SMDS_MeshNode* n5,
1974 const SMDS_MeshNode* n6,
1978 SMESHDS_Mesh * meshDS = GetMeshDS();
1979 SMDS_MeshVolume* elem = 0;
1980 if(!myCreateQuadratic) {
1982 elem = meshDS->AddVolumeWithID(n1, n2, n3, n4, n5, n6, id);
1984 elem = meshDS->AddVolume(n1, n2, n3, n4, n5, n6);
1987 const SMDS_MeshNode* n12 = GetMediumNode( n1, n2, force3d, TopAbs_SOLID );
1988 const SMDS_MeshNode* n23 = GetMediumNode( n2, n3, force3d, TopAbs_SOLID );
1989 const SMDS_MeshNode* n31 = GetMediumNode( n3, n1, force3d, TopAbs_SOLID );
1991 const SMDS_MeshNode* n45 = GetMediumNode( n4, n5, force3d, TopAbs_SOLID );
1992 const SMDS_MeshNode* n56 = GetMediumNode( n5, n6, force3d, TopAbs_SOLID );
1993 const SMDS_MeshNode* n64 = GetMediumNode( n6, n4, force3d, TopAbs_SOLID );
1995 const SMDS_MeshNode* n14 = GetMediumNode( n1, n4, force3d, TopAbs_SOLID );
1996 const SMDS_MeshNode* n25 = GetMediumNode( n2, n5, force3d, TopAbs_SOLID );
1997 const SMDS_MeshNode* n36 = GetMediumNode( n3, n6, force3d, TopAbs_SOLID );
2000 elem = meshDS->AddVolumeWithID(n1, n2, n3, n4, n5, n6,
2001 n12, n23, n31, n45, n56, n64, n14, n25, n36, id);
2003 elem = meshDS->AddVolume(n1, n2, n3, n4, n5, n6,
2004 n12, n23, n31, n45, n56, n64, n14, n25, n36);
2006 if ( mySetElemOnShape && myShapeID > 0 )
2007 meshDS->SetMeshElementOnShape( elem, myShapeID );
2012 //=======================================================================
2013 //function : AddVolume
2014 //purpose : Creates quadratic or linear tetrahedron
2015 //=======================================================================
2017 SMDS_MeshVolume* SMESH_MesherHelper::AddVolume(const SMDS_MeshNode* n1,
2018 const SMDS_MeshNode* n2,
2019 const SMDS_MeshNode* n3,
2020 const SMDS_MeshNode* n4,
2024 SMESHDS_Mesh * meshDS = GetMeshDS();
2025 SMDS_MeshVolume* elem = 0;
2026 if(!myCreateQuadratic) {
2028 elem = meshDS->AddVolumeWithID(n1, n2, n3, n4, id);
2030 elem = meshDS->AddVolume(n1, n2, n3, n4);
2033 const SMDS_MeshNode* n12 = GetMediumNode( n1, n2, force3d, TopAbs_SOLID );
2034 const SMDS_MeshNode* n23 = GetMediumNode( n2, n3, force3d, TopAbs_SOLID );
2035 const SMDS_MeshNode* n31 = GetMediumNode( n3, n1, force3d, TopAbs_SOLID );
2037 const SMDS_MeshNode* n14 = GetMediumNode( n1, n4, force3d, TopAbs_SOLID );
2038 const SMDS_MeshNode* n24 = GetMediumNode( n2, n4, force3d, TopAbs_SOLID );
2039 const SMDS_MeshNode* n34 = GetMediumNode( n3, n4, force3d, TopAbs_SOLID );
2042 elem = meshDS->AddVolumeWithID(n1, n2, n3, n4, n12, n23, n31, n14, n24, n34, id);
2044 elem = meshDS->AddVolume(n1, n2, n3, n4, n12, n23, n31, n14, n24, n34);
2046 if ( mySetElemOnShape && myShapeID > 0 )
2047 meshDS->SetMeshElementOnShape( elem, myShapeID );
2052 //=======================================================================
2053 //function : AddVolume
2054 //purpose : Creates quadratic or linear pyramid
2055 //=======================================================================
2057 SMDS_MeshVolume* SMESH_MesherHelper::AddVolume(const SMDS_MeshNode* n1,
2058 const SMDS_MeshNode* n2,
2059 const SMDS_MeshNode* n3,
2060 const SMDS_MeshNode* n4,
2061 const SMDS_MeshNode* n5,
2065 SMDS_MeshVolume* elem = 0;
2066 if(!myCreateQuadratic) {
2068 elem = GetMeshDS()->AddVolumeWithID(n1, n2, n3, n4, n5, id);
2070 elem = GetMeshDS()->AddVolume(n1, n2, n3, n4, n5);
2073 const SMDS_MeshNode* n12 = GetMediumNode( n1, n2, force3d, TopAbs_SOLID );
2074 const SMDS_MeshNode* n23 = GetMediumNode( n2, n3, force3d, TopAbs_SOLID );
2075 const SMDS_MeshNode* n34 = GetMediumNode( n3, n4, force3d, TopAbs_SOLID );
2076 const SMDS_MeshNode* n41 = GetMediumNode( n4, n1, force3d, TopAbs_SOLID );
2078 const SMDS_MeshNode* n15 = GetMediumNode( n1, n5, force3d, TopAbs_SOLID );
2079 const SMDS_MeshNode* n25 = GetMediumNode( n2, n5, force3d, TopAbs_SOLID );
2080 const SMDS_MeshNode* n35 = GetMediumNode( n3, n5, force3d, TopAbs_SOLID );
2081 const SMDS_MeshNode* n45 = GetMediumNode( n4, n5, force3d, TopAbs_SOLID );
2084 elem = GetMeshDS()->AddVolumeWithID ( n1, n2, n3, n4, n5,
2089 elem = GetMeshDS()->AddVolume( n1, n2, n3, n4, n5,
2091 n15, n25, n35, n45);
2093 if ( mySetElemOnShape && myShapeID > 0 )
2094 GetMeshDS()->SetMeshElementOnShape( elem, myShapeID );
2099 //=======================================================================
2100 //function : AddVolume
2101 //purpose : Creates tri-quadratic, quadratic or linear hexahedron
2102 //=======================================================================
2104 SMDS_MeshVolume* SMESH_MesherHelper::AddVolume(const SMDS_MeshNode* n1,
2105 const SMDS_MeshNode* n2,
2106 const SMDS_MeshNode* n3,
2107 const SMDS_MeshNode* n4,
2108 const SMDS_MeshNode* n5,
2109 const SMDS_MeshNode* n6,
2110 const SMDS_MeshNode* n7,
2111 const SMDS_MeshNode* n8,
2115 SMESHDS_Mesh * meshDS = GetMeshDS();
2116 SMDS_MeshVolume* elem = 0;
2117 if(!myCreateQuadratic) {
2119 elem = meshDS->AddVolumeWithID(n1, n2, n3, n4, n5, n6, n7, n8, id);
2121 elem = meshDS->AddVolume(n1, n2, n3, n4, n5, n6, n7, n8);
2124 const SMDS_MeshNode* n12 = GetMediumNode( n1, n2, force3d, TopAbs_SOLID );
2125 const SMDS_MeshNode* n23 = GetMediumNode( n2, n3, force3d, TopAbs_SOLID );
2126 const SMDS_MeshNode* n34 = GetMediumNode( n3, n4, force3d, TopAbs_SOLID );
2127 const SMDS_MeshNode* n41 = GetMediumNode( n4, n1, force3d, TopAbs_SOLID );
2129 const SMDS_MeshNode* n56 = GetMediumNode( n5, n6, force3d, TopAbs_SOLID );
2130 const SMDS_MeshNode* n67 = GetMediumNode( n6, n7, force3d, TopAbs_SOLID );
2131 const SMDS_MeshNode* n78 = GetMediumNode( n7, n8, force3d, TopAbs_SOLID );
2132 const SMDS_MeshNode* n85 = GetMediumNode( n8, n5, force3d, TopAbs_SOLID );
2134 const SMDS_MeshNode* n15 = GetMediumNode( n1, n5, force3d, TopAbs_SOLID );
2135 const SMDS_MeshNode* n26 = GetMediumNode( n2, n6, force3d, TopAbs_SOLID );
2136 const SMDS_MeshNode* n37 = GetMediumNode( n3, n7, force3d, TopAbs_SOLID );
2137 const SMDS_MeshNode* n48 = GetMediumNode( n4, n8, force3d, TopAbs_SOLID );
2138 if(myCreateBiQuadratic)
2140 const SMDS_MeshNode* n1234 = GetCentralNode( n1,n2,n3,n4,n12,n23,n34,n41,force3d );
2141 const SMDS_MeshNode* n1256 = GetCentralNode( n1,n2,n5,n6,n12,n26,n56,n15,force3d );
2142 const SMDS_MeshNode* n2367 = GetCentralNode( n2,n3,n6,n7,n23,n37,n67,n26,force3d );
2143 const SMDS_MeshNode* n3478 = GetCentralNode( n3,n4,n7,n8,n34,n48,n78,n37,force3d );
2144 const SMDS_MeshNode* n1458 = GetCentralNode( n1,n4,n5,n8,n41,n48,n15,n85,force3d );
2145 const SMDS_MeshNode* n5678 = GetCentralNode( n5,n6,n7,n8,n56,n67,n78,n85,force3d );
2147 vector<gp_XYZ> pointsOnShapes( SMESH_Block::ID_Shell );
2149 pointsOnShapes[ SMESH_Block::ID_V000 ] = SMESH_TNodeXYZ( n4 );
2150 pointsOnShapes[ SMESH_Block::ID_V100 ] = SMESH_TNodeXYZ( n8 );
2151 pointsOnShapes[ SMESH_Block::ID_V010 ] = SMESH_TNodeXYZ( n3 );
2152 pointsOnShapes[ SMESH_Block::ID_V110 ] = SMESH_TNodeXYZ( n7 );
2153 pointsOnShapes[ SMESH_Block::ID_V001 ] = SMESH_TNodeXYZ( n1 );
2154 pointsOnShapes[ SMESH_Block::ID_V101 ] = SMESH_TNodeXYZ( n5 );
2155 pointsOnShapes[ SMESH_Block::ID_V011 ] = SMESH_TNodeXYZ( n2 );
2156 pointsOnShapes[ SMESH_Block::ID_V111 ] = SMESH_TNodeXYZ( n6 );
2158 pointsOnShapes[ SMESH_Block::ID_Ex00 ] = SMESH_TNodeXYZ( n48 );
2159 pointsOnShapes[ SMESH_Block::ID_Ex10 ] = SMESH_TNodeXYZ( n37 );
2160 pointsOnShapes[ SMESH_Block::ID_E0y0 ] = SMESH_TNodeXYZ( n15 );
2161 pointsOnShapes[ SMESH_Block::ID_E1y0 ] = SMESH_TNodeXYZ( n26 );
2162 pointsOnShapes[ SMESH_Block::ID_Ex01 ] = SMESH_TNodeXYZ( n34 );
2163 pointsOnShapes[ SMESH_Block::ID_Ex11 ] = SMESH_TNodeXYZ( n78 );
2164 pointsOnShapes[ SMESH_Block::ID_E0y1 ] = SMESH_TNodeXYZ( n12 );
2165 pointsOnShapes[ SMESH_Block::ID_E1y1 ] = SMESH_TNodeXYZ( n56 );
2166 pointsOnShapes[ SMESH_Block::ID_E00z ] = SMESH_TNodeXYZ( n41 );
2167 pointsOnShapes[ SMESH_Block::ID_E10z ] = SMESH_TNodeXYZ( n85 );
2168 pointsOnShapes[ SMESH_Block::ID_E01z ] = SMESH_TNodeXYZ( n23 );
2169 pointsOnShapes[ SMESH_Block::ID_E11z ] = SMESH_TNodeXYZ( n67 );
2171 pointsOnShapes[ SMESH_Block::ID_Fxy0 ] = SMESH_TNodeXYZ( n3478 );
2172 pointsOnShapes[ SMESH_Block::ID_Fxy1 ] = SMESH_TNodeXYZ( n1256 );
2173 pointsOnShapes[ SMESH_Block::ID_Fx0z ] = SMESH_TNodeXYZ( n1458 );
2174 pointsOnShapes[ SMESH_Block::ID_Fx1z ] = SMESH_TNodeXYZ( n2367 );
2175 pointsOnShapes[ SMESH_Block::ID_F0yz ] = SMESH_TNodeXYZ( n1234 );
2176 pointsOnShapes[ SMESH_Block::ID_F1yz ] = SMESH_TNodeXYZ( n5678 );
2178 gp_XYZ centerCube(0.5, 0.5, 0.5);
2180 SMESH_Block::ShellPoint( centerCube, pointsOnShapes, nCenterElem );
2181 const SMDS_MeshNode* nCenter =
2182 meshDS->AddNode( nCenterElem.X(), nCenterElem.Y(), nCenterElem.Z() );
2183 meshDS->SetNodeInVolume( nCenter, myShapeID );
2186 elem = meshDS->AddVolumeWithID(n1, n2, n3, n4, n5, n6, n7, n8,
2187 n12, n23, n34, n41, n56, n67,
2188 n78, n85, n15, n26, n37, n48,
2189 n1234, n1256, n2367, n3478, n1458, n5678, nCenter, id);
2191 elem = meshDS->AddVolume(n1, n2, n3, n4, n5, n6, n7, n8,
2192 n12, n23, n34, n41, n56, n67,
2193 n78, n85, n15, n26, n37, n48,
2194 n1234, n1256, n2367, n3478, n1458, n5678, nCenter);
2199 elem = meshDS->AddVolumeWithID(n1, n2, n3, n4, n5, n6, n7, n8,
2200 n12, n23, n34, n41, n56, n67,
2201 n78, n85, n15, n26, n37, n48, id);
2203 elem = meshDS->AddVolume(n1, n2, n3, n4, n5, n6, n7, n8,
2204 n12, n23, n34, n41, n56, n67,
2205 n78, n85, n15, n26, n37, n48);
2208 if ( mySetElemOnShape && myShapeID > 0 )
2209 meshDS->SetMeshElementOnShape( elem, myShapeID );
2214 //=======================================================================
2215 //function : AddVolume
2216 //purpose : Creates LINEAR!!!!!!!!! octahedron
2217 //=======================================================================
2219 SMDS_MeshVolume* SMESH_MesherHelper::AddVolume(const SMDS_MeshNode* n1,
2220 const SMDS_MeshNode* n2,
2221 const SMDS_MeshNode* n3,
2222 const SMDS_MeshNode* n4,
2223 const SMDS_MeshNode* n5,
2224 const SMDS_MeshNode* n6,
2225 const SMDS_MeshNode* n7,
2226 const SMDS_MeshNode* n8,
2227 const SMDS_MeshNode* n9,
2228 const SMDS_MeshNode* n10,
2229 const SMDS_MeshNode* n11,
2230 const SMDS_MeshNode* n12,
2234 SMESHDS_Mesh * meshDS = GetMeshDS();
2235 SMDS_MeshVolume* elem = 0;
2237 elem = meshDS->AddVolumeWithID(n1,n2,n3,n4,n5,n6,n7,n8,n9,n10,n11,n12,id);
2239 elem = meshDS->AddVolume(n1,n2,n3,n4,n5,n6,n7,n8,n9,n10,n11,n12);
2240 if ( mySetElemOnShape && myShapeID > 0 )
2241 meshDS->SetMeshElementOnShape( elem, myShapeID );
2245 //=======================================================================
2246 //function : AddPolyhedralVolume
2247 //purpose : Creates polyhedron. In quadratic mesh, adds medium nodes
2248 //=======================================================================
2251 SMESH_MesherHelper::AddPolyhedralVolume (const std::vector<const SMDS_MeshNode*>& nodes,
2252 const std::vector<int>& quantities,
2256 SMESHDS_Mesh * meshDS = GetMeshDS();
2257 SMDS_MeshVolume* elem = 0;
2258 if(!myCreateQuadratic)
2261 elem = meshDS->AddPolyhedralVolumeWithID(nodes, quantities, id);
2263 elem = meshDS->AddPolyhedralVolume(nodes, quantities);
2267 vector<const SMDS_MeshNode*> newNodes;
2268 vector<int> newQuantities;
2269 for ( int iFace=0, iN=0; iFace < quantities.size(); ++iFace)
2271 int nbNodesInFace = quantities[iFace];
2272 newQuantities.push_back(0);
2273 for ( int i = 0; i < nbNodesInFace; ++i )
2275 const SMDS_MeshNode* n1 = nodes[ iN + i ];
2276 newNodes.push_back( n1 );
2277 newQuantities.back()++;
2279 const SMDS_MeshNode* n2 = nodes[ iN + ( i+1==nbNodesInFace ? 0 : i+1 )];
2280 // if ( n1->GetPosition()->GetTypeOfPosition() != SMDS_TOP_3DSPACE &&
2281 // n2->GetPosition()->GetTypeOfPosition() != SMDS_TOP_3DSPACE )
2283 const SMDS_MeshNode* n12 = GetMediumNode( n1, n2, force3d, TopAbs_SOLID );
2284 newNodes.push_back( n12 );
2285 newQuantities.back()++;
2288 iN += nbNodesInFace;
2291 elem = meshDS->AddPolyhedralVolumeWithID( newNodes, newQuantities, id );
2293 elem = meshDS->AddPolyhedralVolume( newNodes, newQuantities );
2295 if ( mySetElemOnShape && myShapeID > 0 )
2296 meshDS->SetMeshElementOnShape( elem, myShapeID );
2303 //================================================================================
2305 * \brief Check if a node belongs to any face of sub-mesh
2307 //================================================================================
2309 bool isNodeInSubMesh( const SMDS_MeshNode* n, const SMESHDS_SubMesh* sm )
2311 SMDS_ElemIteratorPtr fIt = n->GetInverseElementIterator( SMDSAbs_Face );
2312 while ( fIt->more() )
2313 if ( sm->Contains( fIt->next() ))
2319 //=======================================================================
2320 //function : IsSameElemGeometry
2321 //purpose : Returns true if all elements of a sub-mesh are of same shape
2322 //=======================================================================
2324 bool SMESH_MesherHelper::IsSameElemGeometry(const SMESHDS_SubMesh* smDS,
2325 SMDSAbs_GeometryType shape,
2326 const bool nullSubMeshRes)
2328 if ( !smDS ) return nullSubMeshRes;
2330 SMDS_ElemIteratorPtr elemIt = smDS->GetElements();
2331 while ( elemIt->more() ) {
2332 const SMDS_MeshElement* e = elemIt->next();
2333 if ( e->GetGeomType() != shape )
2339 //=======================================================================
2340 //function : LoadNodeColumns
2341 //purpose : Load nodes bound to face into a map of node columns
2342 //=======================================================================
2344 bool SMESH_MesherHelper::LoadNodeColumns(TParam2ColumnMap & theParam2ColumnMap,
2345 const TopoDS_Face& theFace,
2346 const TopoDS_Edge& theBaseEdge,
2347 SMESHDS_Mesh* theMesh,
2348 SMESH_ProxyMesh* theProxyMesh)
2350 return LoadNodeColumns(theParam2ColumnMap,
2352 std::list<TopoDS_Edge>(1,theBaseEdge),
2357 //=======================================================================
2358 //function : LoadNodeColumns
2359 //purpose : Load nodes bound to face into a map of node columns
2360 //=======================================================================
2362 bool SMESH_MesherHelper::LoadNodeColumns(TParam2ColumnMap & theParam2ColumnMap,
2363 const TopoDS_Face& theFace,
2364 const std::list<TopoDS_Edge>& theBaseSide,
2365 SMESHDS_Mesh* theMesh,
2366 SMESH_ProxyMesh* theProxyMesh)
2368 // get a right sub-mesh of theFace
2370 const SMESHDS_SubMesh* faceSubMesh = 0;
2373 faceSubMesh = theProxyMesh->GetSubMesh( theFace );
2374 if ( !faceSubMesh ||
2375 faceSubMesh->NbElements() == 0 ||
2376 theProxyMesh->IsTemporary( faceSubMesh->GetElements()->next() ))
2378 // can use a proxy sub-mesh with not temporary elements only
2384 faceSubMesh = theMesh->MeshElements( theFace );
2385 if ( !faceSubMesh || faceSubMesh->NbElements() == 0 )
2388 if ( theParam2ColumnMap.empty() )
2390 // get data of edges for normalization of params
2391 vector< double > length;
2393 list<TopoDS_Edge>::const_iterator edge;
2395 for ( edge = theBaseSide.begin(); edge != theBaseSide.end(); ++edge )
2397 double len = std::max( 1e-10, SMESH_Algo::EdgeLength( *edge ));
2399 length.push_back( len );
2403 // get nodes on theBaseEdge sorted by param on edge and initialize theParam2ColumnMap with them
2404 edge = theBaseSide.begin();
2405 for ( int iE = 0; edge != theBaseSide.end(); ++edge, ++iE )
2407 map< double, const SMDS_MeshNode*> sortedBaseNN;
2408 SMESH_Algo::GetSortedNodesOnEdge( theMesh, *edge,/*noMedium=*/true, sortedBaseNN );
2410 map< double, const SMDS_MeshNode*>::iterator u_n;
2411 // pb with mesh_Projection_2D_00/A1 fixed by adding expectedSupport arg to GetMediumPos()
2412 // so the following solution is commented (hope forever :)
2414 // SMESH_Algo::GetSortedNodesOnEdge( theMesh, *edge,/*noMedium=*/true, sortedBaseNN,
2415 // // SMDSAbs_Edge here is needed to be coherent with
2416 // // StdMeshers_FaceSide used by Quadrangle to get nodes
2417 // // on EDGE; else pb in mesh_Projection_2D_00/A1 where a
2418 // // medium node on EDGE is medium in a triangle but not
2421 // if ( faceSubMesh->GetElements()->next()->IsQuadratic() )
2422 // // filter off nodes medium in faces on theFace (same pb with mesh_Projection_2D_00/A1)
2423 // for ( u_n = sortedBaseNN.begin(); u_n != sortedBaseNN.end() ; )
2425 // const SMDS_MeshNode* node = u_n->second;
2426 // SMDS_ElemIteratorPtr faceIt = node->GetInverseElementIterator( SMDSAbs_Face );
2427 // if ( faceIt->more() && node ) {
2428 // const SMDS_MeshElement* face = faceIt->next();
2429 // if ( faceSubMesh->Contains( face ) && face->IsMediumNode( node ))
2433 // sortedBaseNN.erase( u_n++ );
2437 if ( sortedBaseNN.empty() ) continue;
2439 u_n = sortedBaseNN.begin();
2440 if ( theProxyMesh ) // from sortedBaseNN remove nodes not shared by faces of faceSubMesh
2442 const SMDS_MeshNode* n1 = (++sortedBaseNN.begin())->second;
2443 const SMDS_MeshNode* n2 = (++sortedBaseNN.rbegin())->second;
2444 bool allNodesAreProxy = ( n1 != theProxyMesh->GetProxyNode( n1 ) &&
2445 n2 != theProxyMesh->GetProxyNode( n2 ));
2446 if ( allNodesAreProxy )
2447 for ( u_n = sortedBaseNN.begin(); u_n != sortedBaseNN.end(); u_n++ )
2448 u_n->second = theProxyMesh->GetProxyNode( u_n->second );
2450 if ( u_n = sortedBaseNN.begin(), !isNodeInSubMesh( u_n->second, faceSubMesh ))
2452 while ( ++u_n != sortedBaseNN.end() && !isNodeInSubMesh( u_n->second, faceSubMesh ));
2453 sortedBaseNN.erase( sortedBaseNN.begin(), u_n );
2455 if ( !sortedBaseNN.empty() )
2456 if ( u_n = --sortedBaseNN.end(), !isNodeInSubMesh( u_n->second, faceSubMesh ))
2458 while ( u_n != sortedBaseNN.begin() && !isNodeInSubMesh( (--u_n)->second, faceSubMesh ));
2459 sortedBaseNN.erase( ++u_n, sortedBaseNN.end() );
2461 if ( sortedBaseNN.empty() ) continue;
2465 BRep_Tool::Range( *edge, f, l );
2466 if ( edge->Orientation() == TopAbs_REVERSED ) std::swap( f, l );
2467 const double coeff = 1. / ( l - f ) * length[iE] / fullLen;
2468 const double prevPar = theParam2ColumnMap.empty() ? 0 : theParam2ColumnMap.rbegin()->first;
2469 for ( u_n = sortedBaseNN.begin(); u_n != sortedBaseNN.end(); u_n++ )
2471 double par = prevPar + coeff * ( u_n->first - f );
2472 TParam2ColumnMap::iterator u2nn =
2473 theParam2ColumnMap.insert( theParam2ColumnMap.end(), make_pair( par, TNodeColumn()));
2474 u2nn->second.push_back( u_n->second );
2477 if ( theParam2ColumnMap.size() < 2 )
2482 int prevNbRows = theParam2ColumnMap.begin()->second.size(); // current, at least 1 here
2483 int expectedNbRows = faceSubMesh->NbElements() / ( theParam2ColumnMap.size()-1 ); // to be added
2485 // fill theParam2ColumnMap column by column by passing from nodes on
2486 // theBaseEdge up via mesh faces on theFace
2488 TParam2ColumnMap::iterator par_nVec_1, par_nVec_2;
2489 par_nVec_2 = theParam2ColumnMap.begin();
2490 par_nVec_1 = par_nVec_2++;
2491 TIDSortedElemSet emptySet, avoidSet;
2492 for ( ; par_nVec_2 != theParam2ColumnMap.end(); ++par_nVec_1, ++par_nVec_2 )
2494 vector<const SMDS_MeshNode*>& nCol1 = par_nVec_1->second;
2495 vector<const SMDS_MeshNode*>& nCol2 = par_nVec_2->second;
2496 nCol1.resize( prevNbRows + expectedNbRows );
2497 nCol2.resize( prevNbRows + expectedNbRows );
2499 int i1, i2, foundNbRows = 0;
2500 const SMDS_MeshNode *n1 = nCol1[ prevNbRows-1 ];
2501 const SMDS_MeshNode *n2 = nCol2[ prevNbRows-1 ];
2502 // find face sharing node n1 and n2 and belonging to faceSubMesh
2503 while ( const SMDS_MeshElement* face =
2504 SMESH_MeshAlgos::FindFaceInSet( n1, n2, emptySet, avoidSet, &i1, &i2))
2506 if ( faceSubMesh->Contains( face ))
2508 int nbNodes = face->NbCornerNodes();
2511 if ( foundNbRows + 1 > expectedNbRows )
2513 n1 = face->GetNode( (i2+2) % 4 ); // opposite corner of quadrangle face
2514 n2 = face->GetNode( (i1+2) % 4 );
2515 nCol1[ prevNbRows + foundNbRows] = n1;
2516 nCol2[ prevNbRows + foundNbRows] = n2;
2519 avoidSet.insert( face );
2521 if ( foundNbRows != expectedNbRows )
2525 return ( theParam2ColumnMap.size() > 1 &&
2526 theParam2ColumnMap.begin()->second.size() == prevNbRows + expectedNbRows );
2531 //================================================================================
2533 * \brief Return true if a node is at a corner of a 2D structured mesh of FACE
2535 //================================================================================
2537 bool isCornerOfStructure( const SMDS_MeshNode* n,
2538 const SMESHDS_SubMesh* faceSM,
2539 SMESH_MesherHelper& faceAnalyser )
2541 int nbFacesInSM = 0;
2543 SMDS_ElemIteratorPtr fIt = n->GetInverseElementIterator( SMDSAbs_Face );
2544 while ( fIt->more() )
2545 nbFacesInSM += faceSM->Contains( fIt->next() );
2547 if ( nbFacesInSM == 1 )
2550 if ( nbFacesInSM == 2 && n->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX )
2552 return faceAnalyser.IsRealSeam( n->getshapeId() );
2558 //=======================================================================
2559 //function : IsStructured
2560 //purpose : Return true if 2D mesh on FACE is a structured rectangle
2561 //=======================================================================
2563 bool SMESH_MesherHelper::IsStructured( SMESH_subMesh* faceSM )
2565 SMESHDS_SubMesh* fSM = faceSM->GetSubMeshDS();
2566 if ( !fSM || fSM->NbElements() == 0 )
2569 list< TopoDS_Edge > edges;
2570 list< int > nbEdgesInWires;
2571 int nbWires = SMESH_Block::GetOrderedEdges( TopoDS::Face( faceSM->GetSubShape() ),
2572 edges, nbEdgesInWires );
2573 if ( nbWires != 1 /*|| nbEdgesInWires.front() != 4*/ ) // allow composite sides
2576 // algo: find corners of a structure and then analyze nb of faces and
2577 // length of structure sides
2579 SMESHDS_Mesh* meshDS = faceSM->GetFather()->GetMeshDS();
2580 SMESH_MesherHelper faceAnalyser( *faceSM->GetFather() );
2581 faceAnalyser.SetSubShape( faceSM->GetSubShape() );
2583 // rotate edges to get the first node being at corner
2584 // (in principle it's not necessary but so far none SALOME algo can make
2585 // such a structured mesh that all corner nodes are not on VERTEXes)
2586 bool isCorner = false;
2587 int nbRemainEdges = nbEdgesInWires.front();
2589 TopoDS_Vertex V = IthVertex( 0, edges.front() );
2590 isCorner = isCornerOfStructure( SMESH_Algo::VertexNode( V, meshDS ),
2593 edges.splice( edges.end(), edges, edges.begin() );
2597 while ( !isCorner && nbRemainEdges > 0 );
2602 // get all nodes from EDGEs
2603 list< const SMDS_MeshNode* > nodes;
2604 list< TopoDS_Edge >::iterator edge = edges.begin();
2605 for ( ; edge != edges.end(); ++edge )
2607 map< double, const SMDS_MeshNode* > u2Nodes;
2608 if ( !SMESH_Algo::GetSortedNodesOnEdge( meshDS, *edge,
2609 /*skipMedium=*/true, u2Nodes ))
2612 list< const SMDS_MeshNode* > edgeNodes;
2613 map< double, const SMDS_MeshNode* >::iterator u2n = u2Nodes.begin();
2614 for ( ; u2n != u2Nodes.end(); ++u2n )
2615 edgeNodes.push_back( u2n->second );
2616 if ( edge->Orientation() == TopAbs_REVERSED )
2617 edgeNodes.reverse();
2619 if ( !nodes.empty() && nodes.back() == edgeNodes.front() )
2620 edgeNodes.pop_front();
2621 nodes.splice( nodes.end(), edgeNodes, edgeNodes.begin(), edgeNodes.end() );
2624 // get length of structured sides
2625 vector<int> nbEdgesInSide;
2627 list< const SMDS_MeshNode* >::iterator n = ++nodes.begin();
2628 for ( ; n != nodes.end(); ++n )
2631 if ( isCornerOfStructure( *n, fSM, faceAnalyser )) {
2632 nbEdgesInSide.push_back( nbEdges );
2638 if ( nbEdgesInSide.size() != 4 )
2640 if ( nbEdgesInSide[0] != nbEdgesInSide[2] )
2642 if ( nbEdgesInSide[1] != nbEdgesInSide[3] )
2644 if ( nbEdgesInSide[0] * nbEdgesInSide[1] != fSM->NbElements() )
2650 //=======================================================================
2651 //function : IsDistorted2D
2652 //purpose : Return true if 2D mesh on FACE is ditorted
2653 //=======================================================================
2655 bool SMESH_MesherHelper::IsDistorted2D( SMESH_subMesh* faceSM,
2658 if ( !faceSM || faceSM->GetSubShape().ShapeType() != TopAbs_FACE )
2661 bool haveBadFaces = false;
2663 SMESH_MesherHelper helper( *faceSM->GetFather() );
2664 helper.SetSubShape( faceSM->GetSubShape() );
2666 const TopoDS_Face& F = TopoDS::Face( faceSM->GetSubShape() );
2667 SMESHDS_SubMesh* smDS = helper.GetMeshDS()->MeshElements( F );
2668 if ( !smDS || smDS->NbElements() == 0 ) return false;
2670 SMDS_ElemIteratorPtr faceIt = smDS->GetElements();
2671 double prevArea = 0;
2672 vector< const SMDS_MeshNode* > nodes;
2674 bool* toCheckUV = checkUV ? & checkUV : 0;
2675 while ( faceIt->more() && !haveBadFaces )
2677 const SMDS_MeshElement* face = faceIt->next();
2680 nodes.resize( face->NbCornerNodes() );
2681 SMDS_MeshElement::iterator n = face->begin_nodes();
2682 for ( size_t i = 0; i < nodes.size(); ++n, ++i )
2685 // avoid elems on degenarate shapes as UV on them can be wrong
2686 if ( helper.HasDegeneratedEdges() )
2688 bool isOnDegen = false;
2689 for ( size_t i = 0; ( i < nodes.size() && !isOnDegen ); ++i )
2690 isOnDegen = helper.IsDegenShape( nodes[ i ]->getshapeId() );
2694 // prepare to getting UVs
2695 const SMDS_MeshNode* inFaceNode = 0;
2696 if ( helper.HasSeam() ) {
2697 for ( size_t i = 0; ( i < nodes.size() && !inFaceNode ); ++i )
2698 if ( !helper.IsSeamShape( nodes[ i ]->getshapeId() ))
2699 inFaceNode = nodes[ i ];
2704 uv.resize( nodes.size() );
2705 for ( size_t i = 0; i < nodes.size(); ++i )
2706 uv[ i ] = helper.GetNodeUV( F, nodes[ i ], inFaceNode, toCheckUV );
2708 // compare orientation of triangles
2709 double faceArea = 0;
2710 for ( int iT = 0, nbT = nodes.size()-2; iT < nbT; ++iT )
2712 gp_XY v1 = uv[ iT+1 ] - uv[ 0 ];
2713 gp_XY v2 = uv[ iT+2 ] - uv[ 0 ];
2714 faceArea += v2 ^ v1;
2716 haveBadFaces = ( faceArea * prevArea < 0 );
2717 prevArea = faceArea;
2720 return haveBadFaces;
2723 //================================================================================
2725 * \brief Find out elements orientation on a geometrical face
2726 * \param theFace - The face correctly oriented in the shape being meshed
2727 * \retval bool - true if the face normal and the normal of first element
2728 * in the correspoding submesh point in different directions
2730 //================================================================================
2732 bool SMESH_MesherHelper::IsReversedSubMesh (const TopoDS_Face& theFace)
2734 if ( theFace.IsNull() )
2737 // find out orientation of a meshed face
2738 int faceID = GetMeshDS()->ShapeToIndex( theFace );
2739 TopoDS_Shape aMeshedFace = GetMeshDS()->IndexToShape( faceID );
2740 bool isReversed = ( theFace.Orientation() != aMeshedFace.Orientation() );
2742 const SMESHDS_SubMesh * aSubMeshDSFace = GetMeshDS()->MeshElements( faceID );
2743 if ( !aSubMeshDSFace )
2746 // find an element on a bounday of theFace
2747 SMDS_ElemIteratorPtr iteratorElem = aSubMeshDSFace->GetElements();
2748 const SMDS_MeshNode* nn[2];
2749 while ( iteratorElem->more() ) // loop on elements on theFace
2751 const SMDS_MeshElement* elem = iteratorElem->next();
2752 if ( ! elem ) continue;
2754 // look for 2 nodes on EDGE
2755 int nbNodes = elem->NbCornerNodes();
2756 nn[0] = elem->GetNode( nbNodes-1 );
2757 for ( int iN = 0; iN < nbNodes; ++iN )
2759 nn[1] = elem->GetNode( iN );
2760 if ( nn[0]->GetPosition()->GetDim() < 2 &&
2761 nn[1]->GetPosition()->GetDim() < 2 )
2763 TopoDS_Shape s0 = GetSubShapeByNode( nn[0], GetMeshDS() );
2764 TopoDS_Shape s1 = GetSubShapeByNode( nn[1], GetMeshDS() );
2765 TopoDS_Shape E = GetCommonAncestor( s0, s1, *myMesh, TopAbs_EDGE );
2766 if ( !E.IsNull() && !s0.IsSame( s1 ))
2770 for ( TopExp_Explorer exp( theFace, TopAbs_EDGE ); exp.More(); exp.Next() )
2771 if ( E.IsSame( exp.Current() )) {
2773 E = exp.Current(); // to know orientation
2778 double u0 = GetNodeU( TopoDS::Edge( E ), nn[0], nn[1], &ok );
2779 double u1 = GetNodeU( TopoDS::Edge( E ), nn[1], nn[0], &ok );
2782 isReversed = ( u0 > u1 );
2783 if ( E.Orientation() == TopAbs_REVERSED )
2784 isReversed = !isReversed;
2794 // find an element with a good normal
2796 bool normalOK = false;
2798 iteratorElem = aSubMeshDSFace->GetElements();
2799 while ( !normalOK && iteratorElem->more() ) // loop on elements on theFace
2801 const SMDS_MeshElement* elem = iteratorElem->next();
2802 if ( ! SMESH_MeshAlgos::FaceNormal( elem, const_cast<gp_XYZ&>( Ne.XYZ() ), /*normalized=*/0 ))
2806 // get UV of a node inside theFACE
2807 SMDS_ElemIteratorPtr nodesIt = elem->nodesIterator();
2808 const SMDS_MeshNode* nInFace = 0;
2809 int iPosDim = SMDS_TOP_VERTEX;
2810 while ( nodesIt->more() ) // loop on nodes
2812 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nodesIt->next() );
2813 if ( n->GetPosition()->GetTypeOfPosition() >= iPosDim )
2816 iPosDim = n->GetPosition()->GetTypeOfPosition();
2819 uv = GetNodeUV( theFace, nInFace, 0, &normalOK );
2824 // face normal at node position
2825 TopLoc_Location loc;
2826 Handle(Geom_Surface) surf = BRep_Tool::Surface( theFace, loc );
2827 // if ( surf.IsNull() || surf->Continuity() < GeomAbs_C1 )
2828 // some surfaces not detected as GeomAbs_C1 are nevertheless correct for meshing
2829 if ( surf.IsNull() || surf->Continuity() < GeomAbs_C0 )
2832 gp_Vec d1u, d1v; gp_Pnt p;
2833 surf->D1( uv.X(), uv.Y(), p, d1u, d1v );
2834 gp_Vec Nf = (d1u ^ d1v).Transformed( loc );
2836 if ( theFace.Orientation() == TopAbs_REVERSED )
2839 return Ne * Nf < 0.;
2842 //=======================================================================
2844 //purpose : Count nb of sub-shapes
2845 //=======================================================================
2847 int SMESH_MesherHelper::Count(const TopoDS_Shape& shape,
2848 const TopAbs_ShapeEnum type,
2849 const bool ignoreSame)
2852 TopTools_IndexedMapOfShape map;
2853 TopExp::MapShapes( shape, type, map );
2854 return map.Extent();
2858 for ( TopExp_Explorer exp( shape, type ); exp.More(); exp.Next() )
2864 //=======================================================================
2865 //function : NbAncestors
2866 //purpose : Return number of unique ancestors of the shape
2867 //=======================================================================
2869 int SMESH_MesherHelper::NbAncestors(const TopoDS_Shape& shape,
2870 const SMESH_Mesh& mesh,
2871 TopAbs_ShapeEnum ancestorType/*=TopAbs_SHAPE*/)
2873 TopTools_MapOfShape ancestors;
2874 TopTools_ListIteratorOfListOfShape ansIt( mesh.GetAncestors(shape) );
2875 for ( ; ansIt.More(); ansIt.Next() ) {
2876 if ( ancestorType == TopAbs_SHAPE || ansIt.Value().ShapeType() == ancestorType )
2877 ancestors.Add( ansIt.Value() );
2879 return ancestors.Extent();
2882 //=======================================================================
2883 //function : GetSubShapeOri
2884 //purpose : Return orientation of sub-shape in the main shape
2885 //=======================================================================
2887 TopAbs_Orientation SMESH_MesherHelper::GetSubShapeOri(const TopoDS_Shape& shape,
2888 const TopoDS_Shape& subShape)
2890 TopAbs_Orientation ori = TopAbs_Orientation(-1);
2891 if ( !shape.IsNull() && !subShape.IsNull() )
2893 TopExp_Explorer e( shape, subShape.ShapeType() );
2894 if ( shape.Orientation() >= TopAbs_INTERNAL ) // TopAbs_INTERNAL or TopAbs_EXTERNAL
2895 e.Init( shape.Oriented(TopAbs_FORWARD), subShape.ShapeType() );
2896 for ( ; e.More(); e.Next())
2897 if ( subShape.IsSame( e.Current() ))
2900 ori = e.Current().Orientation();
2905 //=======================================================================
2906 //function : IsSubShape
2908 //=======================================================================
2910 bool SMESH_MesherHelper::IsSubShape( const TopoDS_Shape& shape,
2911 const TopoDS_Shape& mainShape )
2913 if ( !shape.IsNull() && !mainShape.IsNull() )
2915 for ( TopExp_Explorer exp( mainShape, shape.ShapeType());
2918 if ( shape.IsSame( exp.Current() ))
2921 SCRUTE((shape.IsNull()));
2922 SCRUTE((mainShape.IsNull()));
2926 //=======================================================================
2927 //function : IsSubShape
2929 //=======================================================================
2931 bool SMESH_MesherHelper::IsSubShape( const TopoDS_Shape& shape, SMESH_Mesh* aMesh )
2933 if ( shape.IsNull() || !aMesh )
2936 aMesh->GetMeshDS()->ShapeToIndex( shape ) ||
2938 (shape.ShapeType() == TopAbs_COMPOUND && aMesh->GetMeshDS()->IsGroupOfSubShapes( shape ));
2941 //=======================================================================
2942 //function : IsBlock
2944 //=======================================================================
2946 bool SMESH_MesherHelper::IsBlock( const TopoDS_Shape& shape )
2948 if ( shape.IsNull() )
2952 TopExp_Explorer exp( shape, TopAbs_SHELL );
2953 if ( !exp.More() ) return false;
2954 shell = TopoDS::Shell( exp.Current() );
2955 if ( exp.Next(), exp.More() ) return false;
2958 TopTools_IndexedMapOfOrientedShape map;
2959 return SMESH_Block::FindBlockShapes( shell, v, v, map );
2963 //================================================================================
2965 * \brief Return maximal tolerance of shape
2967 //================================================================================
2969 double SMESH_MesherHelper::MaxTolerance( const TopoDS_Shape& shape )
2971 double tol = Precision::Confusion();
2972 TopExp_Explorer exp;
2973 for ( exp.Init( shape, TopAbs_FACE ); exp.More(); exp.Next() )
2974 tol = Max( tol, BRep_Tool::Tolerance( TopoDS::Face( exp.Current())));
2975 for ( exp.Init( shape, TopAbs_EDGE ); exp.More(); exp.Next() )
2976 tol = Max( tol, BRep_Tool::Tolerance( TopoDS::Edge( exp.Current())));
2977 for ( exp.Init( shape, TopAbs_VERTEX ); exp.More(); exp.Next() )
2978 tol = Max( tol, BRep_Tool::Tolerance( TopoDS::Vertex( exp.Current())));
2983 //================================================================================
2985 * \brief Return MaxTolerance( face ), probably cached
2987 //================================================================================
2989 double SMESH_MesherHelper::getFaceMaxTol( const TopoDS_Shape& face ) const
2991 int faceID = GetMeshDS()->ShapeToIndex( face );
2993 SMESH_MesherHelper* me = const_cast< SMESH_MesherHelper* >( this );
2994 double & tol = me->myFaceMaxTol.insert( make_pair( faceID, -1. )).first->second;
2996 tol = MaxTolerance( face );
3001 //================================================================================
3003 * \brief Return an angle between two EDGEs sharing a common VERTEX with reference
3004 * of the FACE normal
3005 * \return double - the angle (between -Pi and Pi), negative if the angle is concave,
3006 * 1e100 in case of failure
3007 * \waring Care about order of the EDGEs and their orientation to be as they are
3008 * within the FACE! Don't pass degenerated EDGEs neither!
3010 //================================================================================
3012 double SMESH_MesherHelper::GetAngle( const TopoDS_Edge & theE1,
3013 const TopoDS_Edge & theE2,
3014 const TopoDS_Face & theFace,
3015 const TopoDS_Vertex & theCommonV,
3016 gp_Vec* theFaceNormal)
3018 double angle = 1e100;
3022 Handle(Geom_Curve) c1 = BRep_Tool::Curve( theE1, f,l );
3023 Handle(Geom_Curve) c2 = BRep_Tool::Curve( theE2, f,l );
3024 Handle(Geom2d_Curve) c2d1 = BRep_Tool::CurveOnSurface( theE1, theFace, f,l );
3025 Handle(Geom_Surface) surf = BRep_Tool::Surface( theFace );
3026 double p1 = BRep_Tool::Parameter( theCommonV, theE1 );
3027 double p2 = BRep_Tool::Parameter( theCommonV, theE2 );
3028 if ( c1.IsNull() || c2.IsNull() )
3030 gp_XY uv = c2d1->Value( p1 ).XY();
3031 gp_Vec du, dv; gp_Pnt p;
3032 surf->D1( uv.X(), uv.Y(), p, du, dv );
3033 gp_Vec vec1, vec2, vecRef = du ^ dv;
3036 while ( vecRef.SquareMagnitude() < 1e-25 )
3038 double dp = ( l - f ) / 1000.;
3039 p1tmp += dp * (( Abs( p1 - f ) > Abs( p1 - l )) ? -1. : +1.);
3040 uv = c2d1->Value( p1tmp ).XY();
3041 surf->D1( uv.X(), uv.Y(), p, du, dv );
3043 if ( ++nbLoops > 10 )
3046 cout << "SMESH_MesherHelper::GetAngle(): Captured in a sigularity" << endl;
3051 if ( theFace.Orientation() == TopAbs_REVERSED )
3053 if ( theFaceNormal ) *theFaceNormal = vecRef;
3055 c1->D1( p1, p, vec1 );
3056 c2->D1( p2, p, vec2 );
3057 // TopoDS_Face F = theFace;
3058 // if ( F.Orientation() == TopAbs_INTERNAL )
3059 // F.Orientation( TopAbs_FORWARD );
3060 if ( theE1.Orientation() /*GetSubShapeOri( F, theE1 )*/ == TopAbs_REVERSED )
3062 if ( theE2.Orientation() /*GetSubShapeOri( F, theE2 )*/ == TopAbs_REVERSED )
3064 angle = vec1.AngleWithRef( vec2, vecRef );
3066 if ( Abs ( angle ) >= 0.99 * M_PI )
3068 BRep_Tool::Range( theE1, f, l );
3069 p1 += 1e-7 * ( p1-f < l-p1 ? +1. : -1. );
3070 c1->D1( p1, p, vec1 );
3071 if ( theE1.Orientation() == TopAbs_REVERSED )
3073 BRep_Tool::Range( theE2, f, l );
3074 p2 += 1e-7 * ( p2-f < l-p2 ? +1. : -1. );
3075 c2->D1( p2, p, vec2 );
3076 if ( theE2.Orientation() == TopAbs_REVERSED )
3078 angle = vec1.AngleWithRef( vec2, vecRef );
3087 //================================================================================
3089 * \brief Check if the first and last vertices of an edge are the same
3090 * \param anEdge - the edge to check
3091 * \retval bool - true if same
3093 //================================================================================
3095 bool SMESH_MesherHelper::IsClosedEdge( const TopoDS_Edge& anEdge )
3097 if ( anEdge.Orientation() >= TopAbs_INTERNAL )
3098 return IsClosedEdge( TopoDS::Edge( anEdge.Oriented( TopAbs_FORWARD )));
3099 return TopExp::FirstVertex( anEdge ).IsSame( TopExp::LastVertex( anEdge ));
3102 //================================================================================
3104 * \brief Wrapper over TopExp::FirstVertex() and TopExp::LastVertex() fixing them
3105 * in the case of INTERNAL edge
3107 //================================================================================
3109 TopoDS_Vertex SMESH_MesherHelper::IthVertex( const bool is2nd,
3113 if ( anEdge.Orientation() >= TopAbs_INTERNAL )
3114 anEdge.Orientation( TopAbs_FORWARD );
3116 const TopAbs_Orientation tgtOri = is2nd ? TopAbs_REVERSED : TopAbs_FORWARD;
3117 TopoDS_Iterator vIt( anEdge, CumOri );
3118 while ( vIt.More() && vIt.Value().Orientation() != tgtOri )
3121 return ( vIt.More() ? TopoDS::Vertex(vIt.Value()) : TopoDS_Vertex() );
3124 //================================================================================
3126 * \brief Return type of shape contained in a group
3127 * \param group - a shape of type TopAbs_COMPOUND
3128 * \param avoidCompound - not to return TopAbs_COMPOUND
3130 //================================================================================
3132 TopAbs_ShapeEnum SMESH_MesherHelper::GetGroupType(const TopoDS_Shape& group,
3133 const bool avoidCompound)
3135 if ( !group.IsNull() )
3137 if ( group.ShapeType() != TopAbs_COMPOUND )
3138 return group.ShapeType();
3140 // iterate on a compound
3141 TopoDS_Iterator it( group );
3143 return avoidCompound ? GetGroupType( it.Value() ) : it.Value().ShapeType();
3145 return TopAbs_SHAPE;
3148 //=======================================================================
3149 //function : IsQuadraticMesh
3150 //purpose : Check mesh without geometry for: if all elements on this shape are quadratic,
3151 // quadratic elements will be created.
3152 // Used then generated 3D mesh without geometry.
3153 //=======================================================================
3155 SMESH_MesherHelper:: MType SMESH_MesherHelper::IsQuadraticMesh()
3157 int NbAllEdgsAndFaces=0;
3158 int NbQuadFacesAndEdgs=0;
3159 int NbFacesAndEdges=0;
3160 //All faces and edges
3161 NbAllEdgsAndFaces = myMesh->NbEdges() + myMesh->NbFaces();
3162 if ( NbAllEdgsAndFaces == 0 )
3163 return SMESH_MesherHelper::LINEAR;
3165 //Quadratic faces and edges
3166 NbQuadFacesAndEdgs = myMesh->NbEdges(ORDER_QUADRATIC) + myMesh->NbFaces(ORDER_QUADRATIC);
3168 //Linear faces and edges
3169 NbFacesAndEdges = myMesh->NbEdges(ORDER_LINEAR) + myMesh->NbFaces(ORDER_LINEAR);
3171 if (NbAllEdgsAndFaces == NbQuadFacesAndEdgs) {
3173 return SMESH_MesherHelper::QUADRATIC;
3175 else if (NbAllEdgsAndFaces == NbFacesAndEdges) {
3177 return SMESH_MesherHelper::LINEAR;
3180 //Mesh with both type of elements
3181 return SMESH_MesherHelper::COMP;
3184 //=======================================================================
3185 //function : GetOtherParam
3186 //purpose : Return an alternative parameter for a node on seam
3187 //=======================================================================
3189 double SMESH_MesherHelper::GetOtherParam(const double param) const
3191 int i = myParIndex & U_periodic ? 0 : 1;
3192 return fabs(param-myPar1[i]) < fabs(param-myPar2[i]) ? myPar2[i] : myPar1[i];
3197 //=======================================================================
3199 * \brief Iterator on ancestors of the given type
3201 //=======================================================================
3203 struct TAncestorsIterator : public SMDS_Iterator<const TopoDS_Shape*>
3205 TopTools_ListIteratorOfListOfShape _ancIter;
3206 TopAbs_ShapeEnum _type;
3207 TopTools_MapOfShape _encountered;
3208 TAncestorsIterator( const TopTools_ListOfShape& ancestors, TopAbs_ShapeEnum type)
3209 : _ancIter( ancestors ), _type( type )
3211 if ( _ancIter.More() ) {
3212 if ( _ancIter.Value().ShapeType() != _type ) next();
3213 else _encountered.Add( _ancIter.Value() );
3218 return _ancIter.More();
3220 virtual const TopoDS_Shape* next()
3222 const TopoDS_Shape* s = _ancIter.More() ? & _ancIter.Value() : 0;
3223 if ( _ancIter.More() )
3224 for ( _ancIter.Next(); _ancIter.More(); _ancIter.Next())
3225 if ( _ancIter.Value().ShapeType() == _type && _encountered.Add( _ancIter.Value() ))
3233 //=======================================================================
3235 * \brief Return iterator on ancestors of the given type
3237 //=======================================================================
3239 PShapeIteratorPtr SMESH_MesherHelper::GetAncestors(const TopoDS_Shape& shape,
3240 const SMESH_Mesh& mesh,
3241 TopAbs_ShapeEnum ancestorType)
3243 return PShapeIteratorPtr( new TAncestorsIterator( mesh.GetAncestors(shape), ancestorType));
3246 //=======================================================================
3247 //function : GetCommonAncestor
3248 //purpose : Find a common ancestors of two shapes of the given type
3249 //=======================================================================
3251 TopoDS_Shape SMESH_MesherHelper::GetCommonAncestor(const TopoDS_Shape& shape1,
3252 const TopoDS_Shape& shape2,
3253 const SMESH_Mesh& mesh,
3254 TopAbs_ShapeEnum ancestorType)
3256 TopoDS_Shape commonAnc;
3257 if ( !shape1.IsNull() && !shape2.IsNull() )
3259 if ( shape1.ShapeType() == ancestorType && IsSubShape( shape2, shape1 ))
3261 if ( shape2.ShapeType() == ancestorType && IsSubShape( shape1, shape2 ))
3264 PShapeIteratorPtr ancIt = GetAncestors( shape1, mesh, ancestorType );
3265 while ( const TopoDS_Shape* anc = ancIt->next() )
3266 if ( IsSubShape( shape2, *anc ))
3275 //#include <Perf_Meter.hxx>
3277 //=======================================================================
3278 namespace { // Structures used by FixQuadraticElements()
3279 //=======================================================================
3281 #define __DMP__(txt) \
3283 #define MSG(txt) __DMP__(txt<<endl)
3284 #define MSGBEG(txt) __DMP__(txt)
3286 //const double straightTol2 = 1e-33; // to detect straing links
3287 bool isStraightLink(double linkLen2, double middleNodeMove2)
3289 // straight if <node move> < 1/15 * <link length>
3290 return middleNodeMove2 < 1/15./15. * linkLen2;
3294 // ---------------------------------------
3296 * \brief Quadratic link knowing its faces
3298 struct QLink: public SMESH_TLink
3300 const SMDS_MeshNode* _mediumNode;
3301 mutable vector<const QFace* > _faces;
3302 mutable gp_Vec _nodeMove;
3303 mutable int _nbMoves;
3305 QLink(const SMDS_MeshNode* n1, const SMDS_MeshNode* n2, const SMDS_MeshNode* nm):
3306 SMESH_TLink( n1,n2 ), _mediumNode(nm), _nodeMove(0,0,0), _nbMoves(0) {
3308 //if ( MediumPos() != SMDS_TOP_3DSPACE )
3309 _nodeMove = MediumPnt() - MiddlePnt();
3311 void SetContinuesFaces() const;
3312 const QFace* GetContinuesFace( const QFace* face ) const;
3313 bool OnBoundary() const;
3314 gp_XYZ MiddlePnt() const { return ( XYZ( node1() ) + XYZ( node2() )) / 2.; }
3315 gp_XYZ MediumPnt() const { return XYZ( _mediumNode ); }
3317 SMDS_TypeOfPosition MediumPos() const
3318 { return _mediumNode->GetPosition()->GetTypeOfPosition(); }
3319 SMDS_TypeOfPosition EndPos(bool isSecond) const
3320 { return (isSecond ? node2() : node1())->GetPosition()->GetTypeOfPosition(); }
3321 const SMDS_MeshNode* EndPosNode(SMDS_TypeOfPosition pos) const
3322 { return EndPos(0) == pos ? node1() : EndPos(1) == pos ? node2() : 0; }
3324 void Move(const gp_Vec& move, bool sum=false) const
3325 { _nodeMove += move; _nbMoves += sum ? (_nbMoves==0) : 1; }
3326 gp_XYZ Move() const { return _nodeMove.XYZ() / _nbMoves; }
3327 bool IsMoved() const { return (_nbMoves > 0 /*&& !IsStraight()*/); }
3328 bool IsStraight() const
3329 { return isStraightLink( (XYZ(node1())-XYZ(node2())).SquareModulus(),
3330 _nodeMove.SquareMagnitude());
3332 bool operator<(const QLink& other) const {
3333 return (node1()->GetID() == other.node1()->GetID() ?
3334 node2()->GetID() < other.node2()->GetID() :
3335 node1()->GetID() < other.node1()->GetID());
3337 // struct PtrComparator {
3338 // bool operator() (const QLink* l1, const QLink* l2 ) const { return *l1 < *l2; }
3341 // ---------------------------------------------------------
3343 * \brief Link in the chain of links; it connects two faces
3347 const QLink* _qlink;
3348 mutable const QFace* _qfaces[2];
3350 TChainLink(const QLink* qlink=0):_qlink(qlink) {
3351 _qfaces[0] = _qfaces[1] = 0;
3353 void SetFace(const QFace* face) const { int iF = _qfaces[0] ? 1 : 0; _qfaces[iF]=face; }
3355 bool IsBoundary() const { return !_qfaces[1]; }
3357 void RemoveFace( const QFace* face ) const
3358 { _qfaces[(face == _qfaces[1])] = 0; if (!_qfaces[0]) std::swap(_qfaces[0],_qfaces[1]); }
3360 const QFace* NextFace( const QFace* f ) const
3361 { return _qfaces[0]==f ? _qfaces[1] : _qfaces[0]; }
3363 const SMDS_MeshNode* NextNode( const SMDS_MeshNode* n ) const
3364 { return n == _qlink->node1() ? _qlink->node2() : _qlink->node1(); }
3366 bool operator<(const TChainLink& other) const { return *_qlink < *other._qlink; }
3368 operator bool() const { return (_qlink); }
3370 const QLink* operator->() const { return _qlink; }
3372 gp_Vec Normal() const;
3374 bool IsStraight() const;
3376 // --------------------------------------------------------------------
3377 typedef list< TChainLink > TChain;
3378 typedef set < TChainLink > TLinkSet;
3379 typedef TLinkSet::const_iterator TLinkInSet;
3381 const int theFirstStep = 5;
3383 enum { ERR_OK, ERR_TRI, ERR_PRISM, ERR_UNKNOWN }; // errors of QFace::GetLinkChain()
3384 // --------------------------------------------------------------------
3386 * \brief Quadratic face shared by two volumes and bound by QLinks
3388 struct QFace: public TIDSortedNodeSet
3390 mutable const SMDS_MeshElement* _volumes[2];
3391 mutable vector< const QLink* > _sides;
3392 mutable bool _sideIsAdded[4]; // added in chain of links
3395 mutable const SMDS_MeshElement* _face;
3398 QFace( const vector< const QLink*>& links, const SMDS_MeshElement* face=0 );
3400 void SetVolume(const SMDS_MeshElement* v) const { _volumes[ _volumes[0] ? 1 : 0 ] = v; }
3402 int NbVolumes() const { return !_volumes[0] ? 0 : !_volumes[1] ? 1 : 2; }
3404 void AddSelfToLinks() const {
3405 for ( int i = 0; i < _sides.size(); ++i )
3406 _sides[i]->_faces.push_back( this );
3408 int LinkIndex( const QLink* side ) const {
3409 for (int i=0; i<_sides.size(); ++i ) if ( _sides[i] == side ) return i;
3412 bool GetLinkChain( int iSide, TChain& chain, SMDS_TypeOfPosition pos, int& err) const;
3414 bool GetLinkChain( TChainLink& link, TChain& chain, SMDS_TypeOfPosition pos, int& err) const
3416 int i = LinkIndex( link._qlink );
3417 if ( i < 0 ) return true;
3418 _sideIsAdded[i] = true;
3419 link.SetFace( this );
3420 // continue from opposite link
3421 return GetLinkChain( (i+2)%_sides.size(), chain, pos, err );
3423 bool IsBoundary() const { return !_volumes[1]; }
3425 bool Contains( const SMDS_MeshNode* node ) const { return count(node); }
3427 bool IsSpoiled(const QLink* bentLink ) const;
3429 TLinkInSet GetBoundaryLink( const TLinkSet& links,
3430 const TChainLink& avoidLink,
3431 TLinkInSet * notBoundaryLink = 0,
3432 const SMDS_MeshNode* nodeToContain = 0,
3433 bool * isAdjacentUsed = 0,
3434 int nbRecursionsLeft = -1) const;
3436 TLinkInSet GetLinkByNode( const TLinkSet& links,
3437 const TChainLink& avoidLink,
3438 const SMDS_MeshNode* nodeToContain) const;
3440 const SMDS_MeshNode* GetNodeInFace() const {
3441 for ( int iL = 0; iL < _sides.size(); ++iL )
3442 if ( _sides[iL]->MediumPos() == SMDS_TOP_FACE ) return _sides[iL]->_mediumNode;
3446 gp_Vec LinkNorm(const int i, SMESH_MesherHelper* theFaceHelper=0) const;
3448 double MoveByBoundary( const TChainLink& theLink,
3449 const gp_Vec& theRefVec,
3450 const TLinkSet& theLinks,
3451 SMESH_MesherHelper* theFaceHelper=0,
3452 const double thePrevLen=0,
3453 const int theStep=theFirstStep,
3454 gp_Vec* theLinkNorm=0,
3455 double theSign=1.0) const;
3458 //================================================================================
3460 * \brief Dump QLink and QFace
3462 ostream& operator << (ostream& out, const QLink& l)
3464 out <<"QLink nodes: "
3465 << l.node1()->GetID() << " - "
3466 << l._mediumNode->GetID() << " - "
3467 << l.node2()->GetID() << endl;
3470 ostream& operator << (ostream& out, const QFace& f)
3472 out <<"QFace nodes: "/*<< &f << " "*/;
3473 for ( TIDSortedNodeSet::const_iterator n = f.begin(); n != f.end(); ++n )
3474 out << (*n)->GetID() << " ";
3475 out << " \tvolumes: "
3476 << (f._volumes[0] ? f._volumes[0]->GetID() : 0) << " "
3477 << (f._volumes[1] ? f._volumes[1]->GetID() : 0);
3478 out << " \tNormal: "<< f._normal.X() <<", "<<f._normal.Y() <<", "<<f._normal.Z() << endl;
3482 //================================================================================
3484 * \brief Construct QFace from QLinks
3486 //================================================================================
3488 QFace::QFace( const vector< const QLink*>& links, const SMDS_MeshElement* face )
3490 _volumes[0] = _volumes[1] = 0;
3492 _sideIsAdded[0]=_sideIsAdded[1]=_sideIsAdded[2]=_sideIsAdded[3]=false;
3493 _normal.SetCoord(0,0,0);
3494 for ( int i = 1; i < _sides.size(); ++i ) {
3495 const QLink *l1 = _sides[i-1], *l2 = _sides[i];
3496 insert( l1->node1() ); insert( l1->node2() );
3498 gp_Vec v1( XYZ( l1->node2()), XYZ( l1->node1()));
3499 gp_Vec v2( XYZ( l2->node1()), XYZ( l2->node2()));
3500 if ( l1->node1() != l2->node1() && l1->node2() != l2->node2() )
3504 double normSqSize = _normal.SquareMagnitude();
3505 if ( normSqSize > numeric_limits<double>::min() )
3506 _normal /= sqrt( normSqSize );
3508 _normal.SetCoord(1e-33,0,0);
3514 //================================================================================
3516 * \brief Make up a chain of links
3517 * \param iSide - link to add first
3518 * \param chain - chain to fill in
3519 * \param pos - postion of medium nodes the links should have
3520 * \param error - out, specifies what is wrong
3521 * \retval bool - false if valid chain can't be built; "valid" means that links
3522 * of the chain belongs to rectangles bounding hexahedrons
3524 //================================================================================
3526 bool QFace::GetLinkChain( int iSide, TChain& chain, SMDS_TypeOfPosition pos, int& error) const
3528 if ( iSide >= _sides.size() ) // wrong argument iSide
3530 if ( _sideIsAdded[ iSide ]) // already in chain
3533 if ( _sides.size() != 4 ) { // triangle - visit all my continous faces
3536 list< const QFace* > faces( 1, this );
3537 while ( !faces.empty() ) {
3538 const QFace* face = faces.front();
3539 for ( int i = 0; i < face->_sides.size(); ++i ) {
3540 if ( !face->_sideIsAdded[i] && face->_sides[i] ) {
3541 face->_sideIsAdded[i] = true;
3542 // find a face side in the chain
3543 TLinkInSet chLink = links.insert( TChainLink(face->_sides[i])).first;
3544 // TChain::iterator chLink = chain.begin();
3545 // for ( ; chLink != chain.end(); ++chLink )
3546 // if ( chLink->_qlink == face->_sides[i] )
3548 // if ( chLink == chain.end() )
3549 // chLink = chain.insert( chain.begin(), TChainLink(face->_sides[i]));
3550 // add a face to a chained link and put a continues face in the queue
3551 chLink->SetFace( face );
3552 if ( face->_sides[i]->MediumPos() == pos )
3553 if ( const QFace* contFace = face->_sides[i]->GetContinuesFace( face ))
3554 if ( contFace->_sides.size() == 3 )
3555 faces.push_back( contFace );
3560 if ( error < ERR_TRI )
3562 chain.insert( chain.end(), links.begin(),links.end() );
3565 _sideIsAdded[iSide] = true; // not to add this link to chain again
3566 const QLink* link = _sides[iSide];
3570 // add link into chain
3571 TChain::iterator chLink = chain.insert( chain.begin(), TChainLink(link));
3572 chLink->SetFace( this );
3575 // propagate from a quadrangle to neighbour faces
3576 if ( link->MediumPos() >= pos ) {
3577 int nbLinkFaces = link->_faces.size();
3578 if ( nbLinkFaces == 4 || (/*nbLinkFaces < 4 && */link->OnBoundary())) {
3579 // hexahedral mesh or boundary quadrangles - goto a continous face
3580 if ( const QFace* f = link->GetContinuesFace( this ))
3581 if ( f->_sides.size() == 4 )
3582 return f->GetLinkChain( *chLink, chain, pos, error );
3585 TChainLink chLink(link); // side face of prismatic mesh - visit all faces of iSide
3586 for ( int i = 0; i < nbLinkFaces; ++i )
3587 if ( link->_faces[i] )
3588 link->_faces[i]->GetLinkChain( chLink, chain, pos, error );
3589 if ( error < ERR_PRISM )
3597 //================================================================================
3599 * \brief Return a boundary link of the triangle face
3600 * \param links - set of all links
3601 * \param avoidLink - link not to return
3602 * \param notBoundaryLink - out, neither the returned link nor avoidLink
3603 * \param nodeToContain - node the returned link must contain; if provided, search
3604 * also performed on adjacent faces
3605 * \param isAdjacentUsed - returns true if link is found in adjacent faces
3606 * \param nbRecursionsLeft - to limit recursion
3608 //================================================================================
3610 TLinkInSet QFace::GetBoundaryLink( const TLinkSet& links,
3611 const TChainLink& avoidLink,
3612 TLinkInSet * notBoundaryLink,
3613 const SMDS_MeshNode* nodeToContain,
3614 bool * isAdjacentUsed,
3615 int nbRecursionsLeft) const
3617 TLinkInSet linksEnd = links.end(), boundaryLink = linksEnd;
3619 typedef list< pair< const QFace*, TLinkInSet > > TFaceLinkList;
3620 TFaceLinkList adjacentFaces;
3622 for ( int iL = 0; iL < _sides.size(); ++iL )
3624 if ( avoidLink._qlink == _sides[iL] )
3626 TLinkInSet link = links.find( _sides[iL] );
3627 if ( link == linksEnd ) continue;
3628 if ( (*link)->MediumPos() > SMDS_TOP_FACE )
3629 continue; // We work on faces here, don't go inside a solid
3632 if ( link->IsBoundary() ) {
3633 if ( !nodeToContain ||
3634 (*link)->node1() == nodeToContain ||
3635 (*link)->node2() == nodeToContain )
3637 boundaryLink = link;
3638 if ( !notBoundaryLink ) break;
3641 else if ( notBoundaryLink ) {
3642 *notBoundaryLink = link;
3643 if ( boundaryLink != linksEnd ) break;
3646 if ( boundaryLink == linksEnd && nodeToContain ) // collect adjacent faces
3647 if ( const QFace* adj = link->NextFace( this ))
3648 if ( adj->Contains( nodeToContain ))
3649 adjacentFaces.push_back( make_pair( adj, link ));
3652 if ( isAdjacentUsed ) *isAdjacentUsed = false;
3653 if ( boundaryLink == linksEnd && nodeToContain && nbRecursionsLeft) // check adjacent faces
3655 if ( nbRecursionsLeft < 0 )
3656 nbRecursionsLeft = nodeToContain->NbInverseElements();
3657 TFaceLinkList::iterator adj = adjacentFaces.begin();
3658 for ( ; boundaryLink == linksEnd && adj != adjacentFaces.end(); ++adj )
3659 boundaryLink = adj->first->GetBoundaryLink( links, *(adj->second), 0, nodeToContain,
3660 isAdjacentUsed, nbRecursionsLeft-1);
3661 if ( isAdjacentUsed ) *isAdjacentUsed = true;
3663 return boundaryLink;
3665 //================================================================================
3667 * \brief Return a link ending at the given node but not avoidLink
3669 //================================================================================
3671 TLinkInSet QFace::GetLinkByNode( const TLinkSet& links,
3672 const TChainLink& avoidLink,
3673 const SMDS_MeshNode* nodeToContain) const
3675 for ( int i = 0; i < _sides.size(); ++i )
3676 if ( avoidLink._qlink != _sides[i] &&
3677 (_sides[i]->node1() == nodeToContain || _sides[i]->node2() == nodeToContain ))
3678 return links.find( _sides[ i ]);
3682 //================================================================================
3684 * \brief Return normal to the i-th side pointing outside the face
3686 //================================================================================
3688 gp_Vec QFace::LinkNorm(const int i, SMESH_MesherHelper* /*uvHelper*/) const
3690 gp_Vec norm = _normal ^ gp_Vec( XYZ(_sides[i]->node1()), XYZ(_sides[i]->node2()));
3691 gp_XYZ pIn = ( _sides[ (i+1)%3 ]->MiddlePnt() +
3692 _sides[ (i+2)%3 ]->MiddlePnt() ) / 2.;
3693 gp_Vec vecOut = ( _sides[i]->MiddlePnt() - pIn );
3695 if ( norm * vecOut < 0 )
3697 double mag2 = norm.SquareMagnitude();
3698 if ( mag2 > numeric_limits<double>::min() )
3699 norm /= sqrt( mag2 );
3702 //================================================================================
3704 * \brief Move medium node of theLink according to its distance from boundary
3705 * \param theLink - link to fix
3706 * \param theRefVec - movement of boundary
3707 * \param theLinks - all adjacent links of continous triangles
3708 * \param theFaceHelper - helper is not used so far
3709 * \param thePrevLen - distance from the boundary
3710 * \param theStep - number of steps till movement propagation limit
3711 * \param theLinkNorm - out normal to theLink
3712 * \param theSign - 1 or -1 depending on movement of boundary
3713 * \retval double - distance from boundary to propagation limit or other boundary
3715 //================================================================================
3717 double QFace::MoveByBoundary( const TChainLink& theLink,
3718 const gp_Vec& theRefVec,
3719 const TLinkSet& theLinks,
3720 SMESH_MesherHelper* theFaceHelper,
3721 const double thePrevLen,
3723 gp_Vec* theLinkNorm,
3724 double theSign) const
3727 return thePrevLen; // propagation limit reached
3729 int iL; // index of theLink
3730 for ( iL = 0; iL < _sides.size(); ++iL )
3731 if ( theLink._qlink == _sides[ iL ])
3734 MSG(string(theStep,'.')<<" Ref( "<<theRefVec.X()<<","<<theRefVec.Y()<<","<<theRefVec.Z()<<" )"
3735 <<" thePrevLen " << thePrevLen);
3736 MSG(string(theStep,'.')<<" "<<*theLink._qlink);
3738 gp_Vec linkNorm = -LinkNorm( iL/*, theFaceHelper*/ ); // normal to theLink
3739 double refProj = theRefVec * linkNorm; // project movement vector to normal of theLink
3740 if ( theStep == theFirstStep )
3741 theSign = refProj < 0. ? -1. : 1.;
3742 else if ( theSign * refProj < 0.4 * theRefVec.Magnitude())
3743 return thePrevLen; // to propagate movement forward only, not in side dir or backward
3745 int iL1 = (iL + 1) % 3, iL2 = (iL + 2) % 3; // indices of the two other links of triangle
3746 TLinkInSet link1 = theLinks.find( _sides[iL1] );
3747 TLinkInSet link2 = theLinks.find( _sides[iL2] );
3749 const QFace *f1 = 0, *f2 = 0; // adjacent faces
3750 bool isBndLink1 = true, isBndLink2 = true;
3751 if ( link1 != theLinks.end() && link2 != theLinks.end() )
3753 f1 = link1->NextFace( this );
3754 f2 = link2->NextFace( this );
3756 isBndLink1 = ( theLink->MediumPos() > (*link1)->MediumPos() );
3757 isBndLink2 = ( theLink->MediumPos() > (*link2)->MediumPos() );
3758 if ( theStep == theFirstStep ) // (issue 22541) quad-dominant mesh
3760 if ( !isBndLink1 && !f1 )
3761 f1 = (*link1)->GetContinuesFace( this ); // get a quadrangle face
3762 if ( !isBndLink2 && !f2 )
3763 f2 = (*link2)->GetContinuesFace( this );
3766 else if ( _sides.size() < 4 )
3769 // propagate to adjacent faces till limit step or boundary
3770 double len1 = thePrevLen + (theLink->MiddlePnt() - _sides[iL1]->MiddlePnt()).Modulus();
3771 double len2 = thePrevLen + (theLink->MiddlePnt() - _sides[iL2]->MiddlePnt()).Modulus();
3772 gp_Vec linkDir1(0,0,0); // initialize to avoid valgrind error ("Conditional jump...")
3773 gp_Vec linkDir2(0,0,0);
3776 if ( f1 && !isBndLink1 )
3777 len1 = f1->MoveByBoundary
3778 ( *link1, theRefVec, theLinks, theFaceHelper, len1, theStep-1, &linkDir1, theSign);
3780 linkDir1 = LinkNorm( iL1/*, theFaceHelper*/ );
3782 MSG( " --------------- EXCEPTION");
3787 if ( f2 && !isBndLink2 )
3788 len2 = f2->MoveByBoundary
3789 ( *link2, theRefVec, theLinks, theFaceHelper, len2, theStep-1, &linkDir2, theSign);
3791 linkDir2 = LinkNorm( iL2/*, theFaceHelper*/ );
3793 MSG( " --------------- EXCEPTION");
3798 if ( theStep != theFirstStep )
3800 // choose chain length by direction of propagation most codirected with theRefVec
3801 bool choose1 = ( theRefVec * linkDir1 * theSign > theRefVec * linkDir2 * theSign );
3802 fullLen = choose1 ? len1 : len2;
3803 double r = thePrevLen / fullLen;
3805 gp_Vec move = linkNorm * refProj * ( 1 - r );
3806 theLink->Move( move, true );
3808 MSG(string(theStep,'.')<<" Move "<< theLink->_mediumNode->GetID()<<
3809 " by " << refProj * ( 1 - r ) << " following " <<
3810 (choose1 ? *link1->_qlink : *link2->_qlink)); // warning: link1 can be invalid
3812 if ( theLinkNorm ) *theLinkNorm = linkNorm;
3817 //================================================================================
3819 * \brief Checks if the face is distorted due to bentLink
3821 //================================================================================
3823 bool QFace::IsSpoiled(const QLink* bentLink ) const
3825 // code is valid for convex faces only
3827 for ( TIDSortedNodeSet::const_iterator n = begin(); n!=end(); ++n)
3828 gc += XYZ( *n ) / size();
3829 for (unsigned i = 0; i < _sides.size(); ++i )
3831 if ( _sides[i] == bentLink ) continue;
3832 gp_Vec linkNorm = _normal ^ gp_Vec( XYZ(_sides[i]->node1()), XYZ(_sides[i]->node2()));
3833 gp_Vec vecOut( gc, _sides[i]->MiddlePnt() );
3834 if ( linkNorm * vecOut < 0 )
3836 double mag2 = linkNorm.SquareMagnitude();
3837 if ( mag2 > numeric_limits<double>::min() )
3838 linkNorm /= sqrt( mag2 );
3839 gp_Vec vecBent ( _sides[i]->MiddlePnt(), bentLink->MediumPnt());
3840 gp_Vec vecStraight( _sides[i]->MiddlePnt(), bentLink->MiddlePnt());
3841 if ( vecBent * linkNorm > -0.1*vecStraight.Magnitude() )
3848 //================================================================================
3850 * \brief Find pairs of continues faces
3852 //================================================================================
3854 void QLink::SetContinuesFaces() const
3856 // x0 x - QLink, [-|] - QFace, v - volume
3858 // | Between _faces of link x2 two vertical faces are continues
3859 // x1----x2-----x3 and two horizontal faces are continues. We set vertical faces
3860 // | to _faces[0] and _faces[1] and horizontal faces to
3861 // v2 | v3 _faces[2] and _faces[3] (or vise versa).
3864 if ( _faces.empty() )
3866 int iFaceCont = -1, nbBoundary = 0, iBoundary[2]={-1,-1};
3867 if ( _faces[0]->IsBoundary() )
3868 iBoundary[ nbBoundary++ ] = 0;
3869 for ( int iF = 1; iFaceCont < 0 && iF < _faces.size(); ++iF )
3871 // look for a face bounding none of volumes bound by _faces[0]
3872 bool sameVol = false;
3873 int nbVol = _faces[iF]->NbVolumes();
3874 for ( int iV = 0; !sameVol && iV < nbVol; ++iV )
3875 sameVol = ( _faces[iF]->_volumes[iV] == _faces[0]->_volumes[0] ||
3876 _faces[iF]->_volumes[iV] == _faces[0]->_volumes[1]);
3879 if ( _faces[iF]->IsBoundary() )
3880 iBoundary[ nbBoundary++ ] = iF;
3882 // Set continues faces: arrange _faces to have
3883 // _faces[0] continues to _faces[1]
3884 // _faces[2] continues to _faces[3]
3885 if ( nbBoundary == 2 ) // bnd faces are continues
3887 if (( iBoundary[0] < 2 ) != ( iBoundary[1] < 2 ))
3889 int iNear0 = iBoundary[0] < 2 ? 1-iBoundary[0] : 5-iBoundary[0];
3890 std::swap( _faces[ iBoundary[1] ], _faces[iNear0] );
3893 else if ( iFaceCont > 0 ) // continues faces found
3895 if ( iFaceCont != 1 )
3896 std::swap( _faces[1], _faces[iFaceCont] );
3898 else if ( _faces.size() > 1 ) // not found, set NULL by the first face
3900 _faces.insert( ++_faces.begin(), (QFace*) 0 );
3903 //================================================================================
3905 * \brief Return a face continues to the given one
3907 //================================================================================
3909 const QFace* QLink::GetContinuesFace( const QFace* face ) const
3911 for ( int i = 0; i < _faces.size(); ++i ) {
3912 if ( _faces[i] == face ) {
3913 int iF = i < 2 ? 1-i : 5-i;
3914 return iF < _faces.size() ? _faces[iF] : 0;
3919 //================================================================================
3921 * \brief True if link is on mesh boundary
3923 //================================================================================
3925 bool QLink::OnBoundary() const
3927 for ( int i = 0; i < _faces.size(); ++i )
3928 if (_faces[i] && _faces[i]->IsBoundary()) return true;
3931 //================================================================================
3933 * \brief Return normal of link of the chain
3935 //================================================================================
3937 gp_Vec TChainLink::Normal() const {
3939 if (_qfaces[0]) norm = _qfaces[0]->_normal;
3940 if (_qfaces[1]) norm += _qfaces[1]->_normal;
3943 //================================================================================
3945 * \brief Test link curvature taking into account size of faces
3947 //================================================================================
3949 bool TChainLink::IsStraight() const
3951 bool isStraight = _qlink->IsStraight();
3952 if ( isStraight && _qfaces[0] && !_qfaces[1] )
3954 int i = _qfaces[0]->LinkIndex( _qlink );
3955 int iOpp = ( i + 2 ) % _qfaces[0]->_sides.size();
3956 gp_XYZ mid1 = _qlink->MiddlePnt();
3957 gp_XYZ mid2 = _qfaces[0]->_sides[ iOpp ]->MiddlePnt();
3958 double faceSize2 = (mid1-mid2).SquareModulus();
3959 isStraight = _qlink->_nodeMove.SquareMagnitude() < 1/10./10. * faceSize2;
3964 //================================================================================
3966 * \brief Move medium nodes of vertical links of pentahedrons adjacent by side faces
3968 //================================================================================
3970 void fixPrism( TChain& allLinks )
3972 // separate boundary links from internal ones
3973 typedef set<const QLink*/*, QLink::PtrComparator*/> QLinkSet;
3974 QLinkSet interLinks, bndLinks1, bndLink2;
3976 bool isCurved = false;
3977 for ( TChain::iterator lnk = allLinks.begin(); lnk != allLinks.end(); ++lnk ) {
3978 if ( (*lnk)->OnBoundary() )
3979 bndLinks1.insert( lnk->_qlink );
3981 interLinks.insert( lnk->_qlink );
3982 isCurved = isCurved || !lnk->IsStraight();
3985 return; // no need to move
3987 QLinkSet *curBndLinks = &bndLinks1, *newBndLinks = &bndLink2;
3989 while ( !interLinks.empty() && !curBndLinks->empty() )
3991 // propagate movement from boundary links to connected internal links
3992 QLinkSet::iterator bnd = curBndLinks->begin(), bndEnd = curBndLinks->end();
3993 for ( ; bnd != bndEnd; ++bnd )
3995 const QLink* bndLink = *bnd;
3996 for ( int i = 0; i < bndLink->_faces.size(); ++i ) // loop on faces of bndLink
3998 const QFace* face = bndLink->_faces[i]; // quadrange lateral face of a prism
3999 if ( !face ) continue;
4000 // find and move internal link opposite to bndLink within the face
4001 int interInd = ( face->LinkIndex( bndLink ) + 2 ) % face->_sides.size();
4002 const QLink* interLink = face->_sides[ interInd ];
4003 QLinkSet::iterator pInterLink = interLinks.find( interLink );
4004 if ( pInterLink == interLinks.end() ) continue; // not internal link
4005 interLink->Move( bndLink->_nodeMove );
4006 // treated internal links become new boundary ones
4007 interLinks.erase( pInterLink );
4008 newBndLinks->insert( interLink );
4011 curBndLinks->clear();
4012 std::swap( curBndLinks, newBndLinks );
4016 //================================================================================
4018 * \brief Fix links of continues triangles near curved boundary
4020 //================================================================================
4022 void fixTriaNearBoundary( TChain & allLinks, SMESH_MesherHelper& /*helper*/)
4024 if ( allLinks.empty() ) return;
4026 TLinkSet linkSet( allLinks.begin(), allLinks.end());
4027 TLinkInSet linkIt = linkSet.begin(), linksEnd = linkSet.end();
4029 for ( linkIt = linkSet.begin(); linkIt != linksEnd; ++linkIt)
4031 if ( linkIt->IsBoundary() && !linkIt->IsStraight() && linkIt->_qfaces[0])
4033 // move iff a boundary link is bent towards inside of a face (issue 0021084)
4034 const QFace* face = linkIt->_qfaces[0];
4035 gp_XYZ pIn = ( face->_sides[0]->MiddlePnt() +
4036 face->_sides[1]->MiddlePnt() +
4037 face->_sides[2]->MiddlePnt() ) / 3.;
4038 gp_XYZ insideDir( pIn - (*linkIt)->MiddlePnt());
4039 bool linkBentInside = ((*linkIt)->_nodeMove.Dot( insideDir ) > 0 );
4040 //if ( face->IsSpoiled( linkIt->_qlink ))
4041 if ( linkBentInside )
4042 face->MoveByBoundary( *linkIt, (*linkIt)->_nodeMove, linkSet );
4047 //================================================================================
4049 * \brief Detect rectangular structure of links and build chains from them
4051 //================================================================================
4053 enum TSplitTriaResult {
4054 _OK, _NO_CORNERS, _FEW_ROWS, _MANY_ROWS, _NO_SIDELINK, _BAD_MIDQUAD, _NOT_RECT,
4055 _NO_MIDQUAD, _NO_UPTRIA, _BAD_SET_SIZE, _BAD_CORNER, _BAD_START, _NO_BOTLINK, _TWISTED_CHAIN };
4057 TSplitTriaResult splitTrianglesIntoChains( TChain & allLinks,
4058 vector< TChain> & resultChains,
4059 SMDS_TypeOfPosition pos )
4061 // put links in the set and evalute number of result chains by number of boundary links
4064 for ( TChain::iterator lnk = allLinks.begin(); lnk != allLinks.end(); ++lnk ) {
4065 linkSet.insert( *lnk );
4066 nbBndLinks += lnk->IsBoundary();
4068 resultChains.clear();
4069 resultChains.reserve( nbBndLinks / 2 );
4071 TLinkInSet linkIt, linksEnd = linkSet.end();
4073 // find a boundary link with corner node; corner node has position pos-2
4074 // i.e. SMDS_TOP_VERTEX for links on faces and SMDS_TOP_EDGE for
4076 SMDS_TypeOfPosition cornerPos = SMDS_TypeOfPosition(pos-2);
4077 const SMDS_MeshNode* corner = 0;
4078 for ( linkIt = linkSet.begin(); linkIt != linksEnd; ++linkIt )
4079 if ( linkIt->IsBoundary() && (corner = (*linkIt)->EndPosNode(cornerPos)))
4084 TLinkInSet startLink = linkIt;
4085 const SMDS_MeshNode* startCorner = corner;
4086 vector< TChain* > rowChains;
4089 while ( startLink != linksEnd) // loop on columns
4091 // We suppose we have a rectangular structure like shown here. We have found a
4092 // corner of the rectangle (startCorner) and a boundary link sharing
4093 // |/ |/ | the startCorner (startLink). We are going to loop on rows of the
4094 // --o---o---o structure making several chains at once. One chain (columnChain)
4095 // |\ | /| starts at startLink and continues upward (we look at the structure
4096 // \ | \ | / | from such point that startLink is on the bottom of the structure).
4097 // \| \|/ | While going upward we also fill horizontal chains (rowChains) we
4098 // --o---o---o encounter.
4100 // / | \ | \ | startCorner
4105 if ( resultChains.size() == nbBndLinks / 2 )
4107 resultChains.push_back( TChain() );
4108 TChain& columnChain = resultChains.back();
4110 TLinkInSet botLink = startLink; // current horizontal link to go up from
4111 corner = startCorner; // current corner the botLink ends at
4113 while ( botLink != linksEnd ) // loop on rows
4115 // add botLink to the columnChain
4116 columnChain.push_back( *botLink );
4118 const QFace* botTria = botLink->_qfaces[0]; // bottom triangle bound by botLink
4120 { // the column ends
4121 if ( botLink == startLink )
4122 return _TWISTED_CHAIN; // issue 0020951
4123 linkSet.erase( botLink );
4124 if ( iRow != rowChains.size() )
4125 return _FEW_ROWS; // different nb of rows in columns
4128 // find the link dividing the quadrangle (midQuadLink) and vertical boundary
4129 // link ending at <corner> (sideLink); there are two cases:
4130 // 1) midQuadLink does not end at <corner>, then we easily find it by botTria,
4131 // since midQuadLink is not at boundary while sideLink is.
4132 // 2) midQuadLink ends at <corner>
4134 TLinkInSet midQuadLink = linksEnd;
4135 TLinkInSet sideLink = botTria->GetBoundaryLink( linkSet, *botLink, &midQuadLink,
4137 if ( isCase2 ) { // find midQuadLink among links of botTria
4138 midQuadLink = botTria->GetLinkByNode( linkSet, *botLink, corner );
4139 if ( midQuadLink->IsBoundary() )
4140 return _BAD_MIDQUAD;
4142 if ( sideLink == linksEnd || midQuadLink == linksEnd || sideLink == midQuadLink )
4143 return sideLink == linksEnd ? _NO_SIDELINK : _NO_MIDQUAD;
4146 columnChain.push_back( *midQuadLink );
4147 if ( iRow >= rowChains.size() ) {
4149 return _MANY_ROWS; // different nb of rows in columns
4150 if ( resultChains.size() == nbBndLinks / 2 )
4152 resultChains.push_back( TChain() );
4153 rowChains.push_back( & resultChains.back() );
4155 rowChains[iRow]->push_back( *sideLink );
4156 rowChains[iRow]->push_back( *midQuadLink );
4158 const QFace* upTria = midQuadLink->NextFace( botTria ); // upper tria of the rectangle
4162 // prepare startCorner and startLink for the next column
4163 startCorner = startLink->NextNode( startCorner );
4165 startLink = botTria->GetBoundaryLink( linkSet, *botLink, 0, startCorner );
4167 startLink = upTria->GetBoundaryLink( linkSet, *midQuadLink, 0, startCorner );
4168 // check if no more columns remains
4169 if ( startLink != linksEnd ) {
4170 const SMDS_MeshNode* botNode = startLink->NextNode( startCorner );
4171 if ( (isCase2 ? botTria : upTria)->Contains( botNode ))
4172 startLink = linksEnd; // startLink bounds upTria or botTria
4173 else if ( startLink == botLink || startLink == midQuadLink || startLink == sideLink )
4177 // find bottom link and corner for the next row
4178 corner = sideLink->NextNode( corner );
4179 // next bottom link ends at the new corner
4180 linkSet.erase( botLink );
4181 botLink = upTria->GetLinkByNode( linkSet, (isCase2 ? *sideLink : *midQuadLink), corner );
4182 if ( botLink == linksEnd || botLink == midQuadLink || botLink == sideLink)
4184 if ( midQuadLink == startLink || sideLink == startLink )
4185 return _TWISTED_CHAIN; // issue 0020951
4186 linkSet.erase( midQuadLink );
4187 linkSet.erase( sideLink );
4189 // make faces neighboring the found ones be boundary
4190 if ( startLink != linksEnd ) {
4191 const QFace* tria = isCase2 ? botTria : upTria;
4192 for ( int iL = 0; iL < 3; ++iL ) {
4193 linkIt = linkSet.find( tria->_sides[iL] );
4194 if ( linkIt != linksEnd )
4195 linkIt->RemoveFace( tria );
4198 if ( botLink->_qfaces[0] == upTria || botLink->_qfaces[1] == upTria )
4199 botLink->RemoveFace( upTria ); // make next botTria first in vector
4206 // In the linkSet, there must remain the last links of rowChains; add them
4207 if ( linkSet.size() != rowChains.size() )
4208 return _BAD_SET_SIZE;
4209 for ( int iRow = 0; iRow < rowChains.size(); ++iRow ) {
4210 // find the link (startLink) ending at startCorner
4212 for ( startLink = linkSet.begin(); startLink != linksEnd; ++startLink ) {
4213 if ( (*startLink)->node1() == startCorner ) {
4214 corner = (*startLink)->node2(); break;
4216 else if ( (*startLink)->node2() == startCorner) {
4217 corner = (*startLink)->node1(); break;
4220 if ( startLink == linksEnd )
4222 rowChains[ iRow ]->push_back( *startLink );
4223 linkSet.erase( startLink );
4224 startCorner = corner;
4230 //================================================================================
4232 * \brief Place medium nodes at the link middle for elements whose corner nodes
4233 * are out of geometrical boundary to prevent distorting elements.
4234 * Issue 0020982, note 0013990
4236 //================================================================================
4238 void force3DOutOfBoundary( SMESH_MesherHelper& theHelper,
4239 SMESH_ComputeErrorPtr& theError)
4241 SMESHDS_Mesh* meshDS = theHelper.GetMeshDS();
4242 TopoDS_Shape shape = theHelper.GetSubShape().Oriented( TopAbs_FORWARD );
4243 if ( shape.IsNull() ) return;
4245 if ( !theError ) theError = SMESH_ComputeError::New();
4249 if ( shape.ShapeType() == TopAbs_FACE ) // 2D
4251 if ( theHelper.GetMesh()->NbTriangles( ORDER_QUADRATIC ) < 1 ) return;
4253 SMESHDS_SubMesh* faceSM = meshDS->MeshElements( shape );
4254 if ( !faceSM ) return;
4256 const TopoDS_Face& face = TopoDS::Face( shape );
4257 Handle(Geom_Surface) surface = BRep_Tool::Surface( face );
4259 TopExp_Explorer edgeIt( face, TopAbs_EDGE );
4260 for ( ; edgeIt.More(); edgeIt.Next() ) // loop on EDGEs of a FACE
4262 // check if the EDGE needs checking
4263 const TopoDS_Edge& edge = TopoDS::Edge( edgeIt.Current() );
4264 if ( SMESH_Algo::isDegenerated( edge ) )
4266 if ( theHelper.IsRealSeam( edge ) &&
4267 edge.Orientation() == TopAbs_REVERSED )
4270 SMESHDS_SubMesh* edgeSM = meshDS->MeshElements( edge );
4271 if ( !edgeSM ) continue;
4274 Handle(Geom2d_Curve) pcurve = BRep_Tool::CurveOnSurface( edge, face, f, l );
4275 BRepAdaptor_Curve curve3D( edge );
4276 switch ( curve3D.GetType() ) {
4277 case GeomAbs_Line: continue;
4278 case GeomAbs_Circle:
4279 case GeomAbs_Ellipse:
4280 case GeomAbs_Hyperbola:
4281 case GeomAbs_Parabola:
4284 gp_Vec D1, D2, Du1, Dv1; gp_Pnt p;
4285 curve3D.D2( 0.5 * ( f + l ), p, D1, D2 );
4286 gp_Pnt2d uv = pcurve->Value( 0.5 * ( f + l ) );
4287 surface->D1( uv.X(), uv.Y(), p, Du1, Dv1 );
4288 gp_Vec fNorm = Du1 ^ Dv1;
4289 if ( fNorm.IsParallel( D2, M_PI * 25./180. ))
4290 continue; // face is normal to the curve3D
4292 gp_Vec curvNorm = fNorm ^ D1;
4293 if ( edge.Orientation() == TopAbs_REVERSED ) curvNorm.Reverse();
4294 if ( curvNorm * D2 > 0 )
4295 continue; // convex edge
4297 catch ( Standard_Failure )
4302 // get nodes shared by faces that may be distorted
4303 SMDS_NodeIteratorPtr nodeIt;
4304 if ( edgeSM->NbNodes() > 0 ) {
4305 nodeIt = edgeSM->GetNodes();
4308 SMESHDS_SubMesh* vertexSM = meshDS->MeshElements( theHelper.IthVertex( 0, edge ));
4310 vertexSM = meshDS->MeshElements( theHelper.IthVertex( 1, edge ));
4311 if ( !vertexSM ) continue;
4312 nodeIt = vertexSM->GetNodes();
4315 // find suspicious faces
4316 TIDSortedElemSet checkedFaces;
4317 vector< const SMDS_MeshNode* > nOnEdge( 2 );
4318 const SMDS_MeshNode* nOnFace;
4319 while ( nodeIt->more() )
4321 const SMDS_MeshNode* n = nodeIt->next();
4322 SMDS_ElemIteratorPtr faceIt = n->GetInverseElementIterator( SMDSAbs_Face );
4323 while ( faceIt->more() )
4325 const SMDS_MeshElement* f = faceIt->next();
4326 if ( !faceSM->Contains( f ) ||
4327 f->NbNodes() < 6 || // check quadratic triangles only
4328 !checkedFaces.insert( f ).second )
4331 // get nodes on EDGE and on FACE of a suspicious face
4332 nOnEdge.clear(); nOnFace = 0;
4333 SMDS_MeshElement::iterator triNode = f->begin_nodes();
4334 for ( int nbN = 0; nbN < 3; ++triNode, ++nbN )
4337 if ( n->GetPosition()->GetDim() == 2 )
4340 nOnEdge.push_back( n );
4343 // check if nOnFace is inside the FACE
4344 if ( nOnFace && nOnEdge.size() == 2 )
4346 theHelper.AddTLinks( static_cast< const SMDS_MeshFace* > ( f ));
4347 if ( !SMESH_MeshAlgos::FaceNormal( f, faceNorm, /*normalized=*/false ))
4349 gp_XYZ edgeDir = SMESH_TNodeXYZ( nOnEdge[0] ) - SMESH_TNodeXYZ( nOnEdge[1] );
4350 gp_XYZ edgeNorm = faceNorm ^ edgeDir;
4351 n = theHelper.GetMediumNode( nOnEdge[0], nOnEdge[1], true ); // find n, not create
4352 gp_XYZ pN0 = SMESH_TNodeXYZ( nOnEdge[0] );
4353 gp_XYZ pMedium = SMESH_TNodeXYZ( n ); // on-edge node location
4354 gp_XYZ pFaceN = SMESH_TNodeXYZ( nOnFace ); // on-face node location
4355 double hMedium = edgeNorm * gp_Vec( pN0, pMedium ).XYZ();
4356 double hFace = edgeNorm * gp_Vec( pN0, pFaceN ).XYZ();
4357 if ( Abs( hMedium ) > Abs( hFace * 0.6 ))
4359 // nOnFace is out of FACE, move a medium on-edge node to the middle
4360 gp_XYZ pMid3D = 0.5 * ( pN0 + SMESH_TNodeXYZ( nOnEdge[1] ));
4361 meshDS->MoveNode( n, pMid3D.X(), pMid3D.Y(), pMid3D.Z() );
4362 MSG( "move OUT of face " << n );
4363 theError->myBadElements.push_back( f );
4369 if ( !theError->myBadElements.empty() )
4370 theError->myName = EDITERR_NO_MEDIUM_ON_GEOM;
4373 } // 2D ==============================================================================
4375 if ( shape.ShapeType() == TopAbs_SOLID ) // 3D
4377 if ( theHelper.GetMesh()->NbTetras ( ORDER_QUADRATIC ) < 1 &&
4378 theHelper.GetMesh()->NbPyramids( ORDER_QUADRATIC ) < 1 ) return;
4380 SMESHDS_SubMesh* solidSM = meshDS->MeshElements( shape );
4381 if ( !solidSM ) return;
4383 // check if the SOLID is bound by concave FACEs
4384 vector< TopoDS_Face > concaveFaces;
4385 TopExp_Explorer faceIt( shape, TopAbs_FACE );
4386 for ( ; faceIt.More(); faceIt.Next() ) // loop on FACEs of a SOLID
4388 const TopoDS_Face& face = TopoDS::Face( faceIt.Current() );
4389 if ( !meshDS->MeshElements( face )) continue;
4391 BRepAdaptor_Surface surface( face );
4392 switch ( surface.GetType() ) {
4393 case GeomAbs_Plane: continue;
4394 case GeomAbs_Cylinder:
4396 case GeomAbs_Sphere:
4399 double u = 0.5 * ( surface.FirstUParameter() + surface.LastUParameter() );
4400 double v = 0.5 * ( surface.FirstVParameter() + surface.LastVParameter() );
4401 gp_Vec Du1, Dv1, Du2, Dv2, Duv2; gp_Pnt p;
4402 surface.D2( u,v, p, Du1, Dv1, Du2, Dv2, Duv2 );
4403 gp_Vec fNorm = Du1 ^ Dv1;
4404 if ( face.Orientation() == TopAbs_REVERSED ) fNorm.Reverse();
4405 bool concaveU = ( fNorm * Du2 > 1e-100 );
4406 bool concaveV = ( fNorm * Dv2 > 1e-100 );
4407 if ( concaveU || concaveV )
4408 concaveFaces.push_back( face );
4410 catch ( Standard_Failure )
4412 concaveFaces.push_back( face );
4416 if ( concaveFaces.empty() )
4419 // fix 2D mesh on the SOLID
4420 for ( faceIt.ReInit(); faceIt.More(); faceIt.Next() ) // loop on FACEs of a SOLID
4422 SMESH_MesherHelper faceHelper( *theHelper.GetMesh() );
4423 faceHelper.SetSubShape( faceIt.Current() );
4424 force3DOutOfBoundary( faceHelper, theError );
4427 // get an iterator over faces on concaveFaces
4428 vector< SMDS_ElemIteratorPtr > faceIterVec( concaveFaces.size() );
4429 for ( size_t i = 0; i < concaveFaces.size(); ++i )
4430 faceIterVec[i] = meshDS->MeshElements( concaveFaces[i] )->GetElements();
4431 typedef SMDS_IteratorOnIterators
4432 < const SMDS_MeshElement*, vector< SMDS_ElemIteratorPtr > > TIterOnIter;
4433 SMDS_ElemIteratorPtr faceIter( new TIterOnIter( faceIterVec ));
4435 // a seacher to check if a volume is close to a concave face
4436 std::auto_ptr< SMESH_ElementSearcher > faceSearcher
4437 ( SMESH_MeshAlgos::GetElementSearcher( *theHelper.GetMeshDS(), faceIter ));
4440 //BRepClass3d_SolidClassifier solidClassifier( shape );
4442 TIDSortedElemSet checkedVols, movedNodes;
4443 //for ( faceIt.ReInit(); faceIt.More(); faceIt.Next() ) // loop on FACEs of a SOLID
4444 for ( size_t iF = 0; iF < concaveFaces.size(); ++iF ) // loop on concave FACEs
4446 //const TopoDS_Shape& face = faceIt.Current();
4447 const TopoDS_Shape& face = concaveFaces[ iF ];
4448 SMESHDS_SubMesh* faceSM = meshDS->MeshElements( face );
4449 if ( !faceSM ) continue;
4451 // get nodes shared by volumes (tet and pyra) on the FACE that may be distorted
4452 SMDS_NodeIteratorPtr nodeIt;
4453 if ( faceSM->NbNodes() > 0 ) {
4454 nodeIt = faceSM->GetNodes();
4457 TopExp_Explorer vertex( face, TopAbs_VERTEX );
4458 SMESHDS_SubMesh* vertexSM = meshDS->MeshElements( vertex.Current() );
4459 if ( !vertexSM ) continue;
4460 nodeIt = vertexSM->GetNodes();
4462 // get ids of sub-shapes of the FACE
4464 SMESH_subMeshIteratorPtr smIt =
4465 theHelper.GetMesh()->GetSubMesh( face )->getDependsOnIterator(/*includeSelf=*/true);
4466 while ( smIt->more() )
4467 subIDs.insert( smIt->next()->GetId() );
4469 // find suspicious volumes adjacent to the FACE
4470 vector< const SMDS_MeshNode* > nOnFace( 4 );
4471 const SMDS_MeshNode* nInSolid;
4472 while ( nodeIt->more() )
4474 const SMDS_MeshNode* n = nodeIt->next();
4475 SMDS_ElemIteratorPtr volIt = n->GetInverseElementIterator( SMDSAbs_Volume );
4476 while ( volIt->more() )
4478 const SMDS_MeshElement* vol = volIt->next();
4479 int nbN = vol->NbCornerNodes();
4480 if ( ( nbN != 4 && nbN != 5 ) ||
4481 !solidSM->Contains( vol ) ||
4482 !checkedVols.insert( vol ).second )
4485 // get nodes on FACE and in SOLID of a suspicious volume
4486 nOnFace.clear(); nInSolid = 0;
4487 SMDS_MeshElement::iterator volNode = vol->begin_nodes();
4488 for ( int nb = nbN; nb > 0; ++volNode, --nb )
4491 if ( n->GetPosition()->GetDim() == 3 )
4493 else if ( subIDs.count( n->getshapeId() ))
4494 nOnFace.push_back( n );
4498 if ( !nInSolid || nOnFace.size() != nbN - 1 )
4501 // get size of the vol
4502 SMESH_TNodeXYZ pInSolid( nInSolid ), pOnFace0( nOnFace[0] );
4503 double volLength = pInSolid.SquareDistance( nOnFace[0] );
4504 for ( size_t i = 1; i < nOnFace.size(); ++i )
4506 volLength = Max( volLength, pOnFace0.SquareDistance( nOnFace[i] ));
4509 // check if vol is close to concaveFaces
4510 const SMDS_MeshElement* closeFace =
4511 faceSearcher->FindClosestTo( pInSolid, SMDSAbs_Face );
4513 pInSolid.SquareDistance( closeFace->GetNode(0) ) > 4 * volLength )
4516 // check if vol is distorted, i.e. a medium node is much closer
4517 // to nInSolid than the link middle
4518 bool isDistorted = false;
4519 SMDS_FaceOfNodes onFaceTria( nOnFace[0], nOnFace[1], nOnFace[2] );
4520 if ( !SMESH_MeshAlgos::FaceNormal( &onFaceTria, faceNorm, /*normalized=*/false ))
4522 theHelper.AddTLinks( static_cast< const SMDS_MeshVolume* > ( vol ));
4523 vector< pair< SMESH_TLink, const SMDS_MeshNode* > > links;
4524 for ( size_t i = 0; i < nOnFace.size(); ++i ) // loop on links between nOnFace
4525 for ( size_t j = i+1; j < nOnFace.size(); ++j )
4527 SMESH_TLink link( nOnFace[i], nOnFace[j] );
4528 TLinkNodeMap::const_iterator linkIt =
4529 theHelper.GetTLinkNodeMap().find( link );
4530 if ( linkIt != theHelper.GetTLinkNodeMap().end() )
4532 links.push_back( make_pair( linkIt->first, linkIt->second ));
4533 if ( !isDistorted ) {
4534 // compare projections of nInSolid and nMedium to face normal
4535 gp_Pnt pMedium = SMESH_TNodeXYZ( linkIt->second );
4536 double hMedium = faceNorm * gp_Vec( pOnFace0, pMedium ).XYZ();
4537 double hVol = faceNorm * gp_Vec( pOnFace0, pInSolid ).XYZ();
4538 isDistorted = ( Abs( hMedium ) > Abs( hVol * 0.5 ));
4542 // move medium nodes to link middle
4545 for ( size_t i = 0; i < links.size(); ++i )
4547 const SMDS_MeshNode* nMedium = links[i].second;
4548 if ( movedNodes.insert( nMedium ).second )
4550 gp_Pnt pMid3D = 0.5 * ( SMESH_TNodeXYZ( links[i].first.node1() ) +
4551 SMESH_TNodeXYZ( links[i].first.node2() ));
4552 meshDS->MoveNode( nMedium, pMid3D.X(), pMid3D.Y(), pMid3D.Z() );
4553 MSG( "move OUT of solid " << nMedium );
4556 theError->myBadElements.push_back( vol );
4558 } // loop on volumes sharing a node on FACE
4559 } // loop on nodes on FACE
4560 } // loop on FACEs of a SOLID
4562 if ( !theError->myBadElements.empty() )
4563 theError->myName = EDITERR_NO_MEDIUM_ON_GEOM;
4569 //=======================================================================
4571 * \brief Move medium nodes of faces and volumes to fix distorted elements
4572 * \param error - container of fixed distorted elements
4573 * \param volumeOnly - to fix nodes on faces or not, if the shape is solid
4575 * Issue 0020307: EDF 992 SMESH : Linea/Quadratic with Medium Node on Geometry
4577 //=======================================================================
4579 void SMESH_MesherHelper::FixQuadraticElements(SMESH_ComputeErrorPtr& compError,
4582 // setenv NO_FixQuadraticElements to know if FixQuadraticElements() is guilty of bad conversion
4583 if ( getenv("NO_FixQuadraticElements") )
4586 // 0. Apply algorithm to SOLIDs or FACEs
4587 // ----------------------------------------------
4588 if ( myShape.IsNull() ) {
4589 if ( !myMesh->HasShapeToMesh() ) return;
4590 SetSubShape( myMesh->GetShapeToMesh() );
4594 TopTools_IndexedMapOfShape solids;
4595 TopExp::MapShapes(myShape,TopAbs_SOLID,solids);
4596 nbSolids = solids.Extent();
4598 TopTools_MapOfShape faces; // faces not in solid or in not meshed solid
4599 for ( TopExp_Explorer f(myShape,TopAbs_FACE,TopAbs_SOLID); f.More(); f.Next() ) {
4600 faces.Add( f.Current() ); // not in solid
4602 for ( TopExp_Explorer s(myShape,TopAbs_SOLID); s.More(); s.Next() ) {
4603 if ( myMesh->GetSubMesh( s.Current() )->IsEmpty() ) { // get faces of solid
4604 for ( TopExp_Explorer f( s.Current(), TopAbs_FACE); f.More(); f.Next() )
4605 faces.Add( f.Current() ); // in not meshed solid
4607 else { // fix nodes in the solid and its faces
4609 MSG("FIX SOLID " << nbSolids-- << " #" << GetMeshDS()->ShapeToIndex(s.Current()));
4611 SMESH_MesherHelper h(*myMesh);
4612 h.SetSubShape( s.Current() );
4613 h.ToFixNodeParameters(true);
4614 h.FixQuadraticElements( compError, false );
4617 // fix nodes on geom faces
4619 int nbfaces = faces.Extent(); /*avoid "unused varianbles": */ nbfaces++, nbfaces--;
4621 for ( TopTools_MapIteratorOfMapOfShape fIt( faces ); fIt.More(); fIt.Next() ) {
4622 MSG("FIX FACE " << nbfaces-- << " #" << GetMeshDS()->ShapeToIndex(fIt.Key()));
4623 SMESH_MesherHelper h(*myMesh);
4624 h.SetSubShape( fIt.Key() );
4625 h.ToFixNodeParameters(true);
4626 h.FixQuadraticElements( compError, true);
4628 //perf_print_all_meters(1);
4629 if ( compError && compError->myName == EDITERR_NO_MEDIUM_ON_GEOM )
4630 compError->myComment = "during conversion to quadratic, "
4631 "some medium nodes were not placed on geometry to avoid distorting elements";
4635 // 1. Find out type of elements and get iterator on them
4636 // ---------------------------------------------------
4638 SMDS_ElemIteratorPtr elemIt;
4639 SMDSAbs_ElementType elemType = SMDSAbs_All;
4641 SMESH_subMesh* submesh = myMesh->GetSubMeshContaining( myShapeID );
4644 if ( SMESHDS_SubMesh* smDS = submesh->GetSubMeshDS() ) {
4645 elemIt = smDS->GetElements();
4646 if ( elemIt->more() ) {
4647 elemType = elemIt->next()->GetType();
4648 elemIt = smDS->GetElements();
4651 if ( !elemIt || !elemIt->more() || elemType < SMDSAbs_Face )
4654 // 2. Fill in auxiliary data structures
4655 // ----------------------------------
4659 set< QLink >::iterator pLink;
4660 set< QFace >::iterator pFace;
4662 bool isCurved = false;
4663 //bool hasRectFaces = false;
4664 //set<int> nbElemNodeSet;
4665 SMDS_VolumeTool volTool;
4667 TIDSortedNodeSet apexOfPyramid;
4668 const int apexIndex = 4;
4671 // Move medium nodes to the link middle for elements whose corner nodes
4672 // are out of geometrical boundary to fix distorted elements.
4673 force3DOutOfBoundary( *this, compError );
4675 if ( elemType == SMDSAbs_Volume )
4677 while ( elemIt->more() ) // loop on volumes
4679 const SMDS_MeshElement* vol = elemIt->next();
4680 if ( !vol->IsQuadratic() || !volTool.Set( vol ))
4682 double volMinSize2 = -1.;
4683 for ( int iF = 0; iF < volTool.NbFaces(); ++iF ) // loop on faces of volume
4685 int nbN = volTool.NbFaceNodes( iF );
4686 //nbElemNodeSet.insert( nbN );
4687 const SMDS_MeshNode** faceNodes = volTool.GetFaceNodes( iF );
4688 vector< const QLink* > faceLinks( nbN/2 );
4689 for ( int iN = 0; iN < nbN; iN += 2 ) // loop on links of a face
4692 QLink link( faceNodes[iN], faceNodes[iN+2], faceNodes[iN+1] );
4693 pLink = links.insert( link ).first;
4694 faceLinks[ iN/2 ] = & *pLink;
4696 if ( link.MediumPos() == SMDS_TOP_3DSPACE )
4698 if ( !link.IsStraight() )
4699 return; // already fixed
4701 else if ( !isCurved )
4703 if ( volMinSize2 < 0 ) volMinSize2 = volTool.MinLinearSize2();
4704 isCurved = !isStraightLink( volMinSize2, link._nodeMove.SquareMagnitude() );
4708 pFace = faces.insert( QFace( faceLinks )).first;
4709 if ( pFace->NbVolumes() == 0 )
4710 pFace->AddSelfToLinks();
4711 pFace->SetVolume( vol );
4712 // hasRectFaces = hasRectFaces ||
4713 // ( volTool.GetVolumeType() == SMDS_VolumeTool::QUAD_HEXA ||
4714 // volTool.GetVolumeType() == SMDS_VolumeTool::QUAD_PENTA );
4717 pFace->_face = GetMeshDS()->FindFace(faceNodes[0],faceNodes[2],faceNodes[4]);
4719 pFace->_face = GetMeshDS()->FindFace(faceNodes[0],faceNodes[2],
4720 faceNodes[4],faceNodes[6] );
4723 // collect pyramid apexes for further correction
4724 if ( vol->NbCornerNodes() == 5 )
4725 apexOfPyramid.insert( vol->GetNode( apexIndex ));
4727 set< QLink >::iterator pLink = links.begin();
4728 for ( ; pLink != links.end(); ++pLink )
4729 pLink->SetContinuesFaces();
4733 while ( elemIt->more() ) // loop on faces
4735 const SMDS_MeshElement* face = elemIt->next();
4736 if ( !face->IsQuadratic() )
4738 //nbElemNodeSet.insert( face->NbNodes() );
4739 int nbN = face->NbNodes()/2;
4740 vector< const QLink* > faceLinks( nbN );
4741 for ( int iN = 0; iN < nbN; ++iN ) // loop on links of a face
4744 QLink link( face->GetNode(iN), face->GetNode((iN+1)%nbN), face->GetNode(iN+nbN) );
4745 pLink = links.insert( link ).first;
4746 faceLinks[ iN ] = & *pLink;
4748 link.node1()->GetPosition()->GetTypeOfPosition() < 2 &&
4749 link.node2()->GetPosition()->GetTypeOfPosition() < 2 )
4750 isCurved = !link.IsStraight();
4753 pFace = faces.insert( QFace( faceLinks )).first;
4754 pFace->AddSelfToLinks();
4755 //hasRectFaces = ( hasRectFaces || nbN == 4 );
4759 return; // no curved edges of faces
4761 // 3. Compute displacement of medium nodes
4762 // ---------------------------------------
4764 SMESH_MesherHelper faceHlp(*myMesh);
4766 // two loops on QFaces: the first is to treat boundary links, the second is for internal ones.
4767 TopLoc_Location loc;
4769 // not to treat boundary of volumic sub-mesh.
4770 int isInside = ( elemType == SMDSAbs_Volume && volumeOnly ) ? 1 : 0;
4771 for ( ; isInside < 2; ++isInside )
4773 MSG( "--------------- LOOP (inside=" << isInside << ") ------------------");
4774 SMDS_TypeOfPosition pos = isInside ? SMDS_TOP_3DSPACE : SMDS_TOP_FACE;
4775 SMDS_TypeOfPosition bndPos = isInside ? SMDS_TOP_FACE : SMDS_TOP_EDGE;
4777 for ( pFace = faces.begin(); pFace != faces.end(); ++pFace ) {
4778 if ( bool(isInside) == pFace->IsBoundary() )
4780 for ( int dir = 0; dir < 2; ++dir ) // 2 directions of propagation from the quadrangle
4783 // make chain of links connected via continues faces
4786 if ( !pFace->GetLinkChain( dir, rawChain, pos, error) && error ==ERR_UNKNOWN ) continue;
4788 if ( !pFace->GetLinkChain( dir+2, rawChain, pos, error ) && error ==ERR_UNKNOWN ) continue;
4790 vector< TChain > chains;
4791 if ( error == ERR_OK ) { // chain contains continues rectangles
4793 chains[0].splice( chains[0].begin(), rawChain );
4795 else if ( error == ERR_TRI ) { // chain contains continues triangles
4796 TSplitTriaResult res = splitTrianglesIntoChains( rawChain, chains, pos );
4797 if ( res != _OK ) { // not quadrangles split into triangles
4798 fixTriaNearBoundary( rawChain, *this );
4802 else if ( error == ERR_PRISM ) { // quadrangle side faces of prisms
4803 fixPrism( rawChain );
4809 for ( int iC = 0; iC < chains.size(); ++iC )
4811 TChain& chain = chains[iC];
4812 if ( chain.empty() ) continue;
4813 if ( chain.front().IsStraight() && chain.back().IsStraight() ) {
4814 MSG("3D straight - ignore");
4817 if ( chain.front()->MediumPos() > bndPos ||
4818 chain.back() ->MediumPos() > bndPos ) {
4819 MSG("Internal chain - ignore");
4822 // mesure chain length and compute link position along the chain
4823 double chainLen = 0;
4824 vector< double > linkPos;
4825 MSGBEG( "Link medium nodes: ");
4826 TChain::iterator link0 = chain.begin(), link1 = chain.begin(), link2;
4827 for ( ++link1; link1 != chain.end(); ++link1, ++link0 ) {
4828 MSGBEG( (*link0)->_mediumNode->GetID() << "-" <<(*link1)->_mediumNode->GetID()<<" ");
4829 double len = ((*link0)->MiddlePnt() - (*link1)->MiddlePnt()).Modulus();
4830 while ( len < numeric_limits<double>::min() ) { // remove degenerated link
4831 link1 = chain.erase( link1 );
4832 if ( link1 == chain.end() )
4834 len = ((*link0)->MiddlePnt() - (*link1)->MiddlePnt()).Modulus();
4837 linkPos.push_back( chainLen );
4840 if ( linkPos.size() < 2 )
4843 gp_Vec move0 = chain.front()->_nodeMove;
4844 gp_Vec move1 = chain.back ()->_nodeMove;
4849 // compute node displacement of end links of chain in parametric space of FACE
4850 TChainLink& linkOnFace = *(++chain.begin());
4851 const SMDS_MeshNode* nodeOnFace = linkOnFace->_mediumNode;
4852 TopoDS_Shape f = GetSubShapeByNode( nodeOnFace, GetMeshDS() );
4853 if ( !f.IsNull() && f.ShapeType() == TopAbs_FACE )
4855 face = TopoDS::Face( f );
4856 faceHlp.SetSubShape( face );
4857 Handle(Geom_Surface) surf = BRep_Tool::Surface(face,loc);
4859 for ( int is1 = 0; is1 < 2; ++is1 ) // move0 or move1
4861 TChainLink& link = is1 ? chain.back() : chain.front();
4862 gp_XY uvm = faceHlp.GetNodeUV( face, link->_mediumNode, nodeOnFace, &checkUV );
4863 gp_XY uv1 = faceHlp.GetNodeUV( face, link->node1(), nodeOnFace, &checkUV );
4864 gp_XY uv2 = faceHlp.GetNodeUV( face, link->node2(), nodeOnFace, &checkUV );
4865 gp_XY uv12 = faceHlp.GetMiddleUV( surf, uv1, uv2 );
4866 // uvMove = uvm - uv12
4867 gp_XY uvMove = applyIn2D(surf, uvm, uv12, gp_XY_Subtracted, /*inPeriod=*/false);
4868 ( is1 ? move1 : move0 ).SetCoord( uvMove.X(), uvMove.Y(), 0 );
4869 if ( !is1 ) // correct nodeOnFace for move1 (issue 0020919)
4870 nodeOnFace = (*(++chain.rbegin()))->_mediumNode;
4871 isStraight[is1] = isStraightLink( (uv2-uv1).SquareModulus(),
4872 10 * uvMove.SquareModulus());
4874 if ( isStraight[0] && isStraight[1] ) {
4875 MSG("2D straight - ignore");
4876 continue; // straight - no need to move nodes of internal links
4879 // check if a chain is already fixed
4880 gp_XY uvm = faceHlp.GetNodeUV( face, linkOnFace->_mediumNode, 0, &checkUV );
4881 gp_XY uv1 = faceHlp.GetNodeUV( face, linkOnFace->node1(), nodeOnFace, &checkUV );
4882 gp_XY uv2 = faceHlp.GetNodeUV( face, linkOnFace->node2(), nodeOnFace, &checkUV );
4883 gp_XY uv12 = faceHlp.GetMiddleUV( surf, uv1, uv2 );
4884 if (( uvm - uv12 ).SquareModulus() > 1e-10 )
4886 MSG("Already fixed - ignore");
4892 if ( isInside || face.IsNull() )
4894 // compute node displacement of end links in their local coord systems
4896 TChainLink& ln0 = chain.front(), ln1 = *(++chain.begin());
4897 trsf.SetTransformation( gp_Ax3( gp::Origin(), ln0.Normal(),
4898 gp_Vec( ln0->MiddlePnt(), ln1->MiddlePnt() )));
4899 move0.Transform(trsf);
4902 TChainLink& ln0 = *(++chain.rbegin()), ln1 = chain.back();
4903 trsf.SetTransformation( gp_Ax3( gp::Origin(), ln1.Normal(),
4904 gp_Vec( ln0->MiddlePnt(), ln1->MiddlePnt() )));
4905 move1.Transform(trsf);
4908 // compute displacement of medium nodes
4909 link2 = chain.begin();
4912 for ( int i = 0; link2 != chain.end(); ++link0, ++link1, ++link2, ++i )
4914 double r = linkPos[i] / chainLen;
4915 // displacement in local coord system
4916 gp_Vec move = (1. - r) * move0 + r * move1;
4917 if ( isInside || face.IsNull()) {
4918 // transform to global
4919 gp_Vec x01( (*link0)->MiddlePnt(), (*link1)->MiddlePnt() );
4920 gp_Vec x12( (*link1)->MiddlePnt(), (*link2)->MiddlePnt() );
4921 gp_Vec x = x01.Normalized() + x12.Normalized();
4922 trsf.SetTransformation( gp_Ax3( gp::Origin(), link1->Normal(), x), gp_Ax3() );
4923 move.Transform(trsf);
4926 // compute 3D displacement by 2D one
4927 Handle(Geom_Surface) s = BRep_Tool::Surface(face,loc);
4928 gp_XY oldUV = faceHlp.GetNodeUV( face, (*link1)->_mediumNode, 0, &checkUV );
4929 gp_XY newUV = applyIn2D( s, oldUV, gp_XY( move.X(),move.Y()), gp_XY_Added );
4930 gp_Pnt newPnt = s->Value( newUV.X(), newUV.Y());
4931 move = gp_Vec( XYZ((*link1)->_mediumNode), newPnt.Transformed(loc) );
4932 if ( SMDS_FacePosition* nPos =
4933 dynamic_cast< SMDS_FacePosition* >((*link1)->_mediumNode->GetPosition()))
4934 nPos->SetParameters( newUV.X(), newUV.Y() );
4936 if ( (XYZ((*link1)->node1()) - XYZ((*link1)->node2())).SquareModulus() <
4937 move.SquareMagnitude())
4939 gp_XY uv0 = faceHlp.GetNodeUV( face, (*link0)->_mediumNode, 0, &checkUV );
4940 gp_XY uv2 = faceHlp.GetNodeUV( face, (*link2)->_mediumNode, 0, &checkUV );
4941 MSG( "TOO LONG MOVE \t" <<
4942 "uv0: "<<uv0.X()<<", "<<uv0.Y()<<" \t" <<
4943 "uv2: "<<uv2.X()<<", "<<uv2.Y()<<" \t" <<
4944 "uvOld: "<<oldUV.X()<<", "<<oldUV.Y()<<" \t" <<
4945 "newUV: "<<newUV.X()<<", "<<newUV.Y()<<" \t");
4949 (*link1)->Move( move );
4950 MSG( "Move " << (*link1)->_mediumNode->GetID() << " following "
4951 << chain.front()->_mediumNode->GetID() <<"-"
4952 << chain.back ()->_mediumNode->GetID() <<
4953 " by " << move.Magnitude());
4955 } // loop on chains of links
4956 } // loop on 2 directions of propagation from quadrangle
4958 } // fix faces and/or volumes
4963 TIDSortedElemSet biQuadQuas, biQuadTris, triQuadHexa;
4964 const SMDS_MeshElement *biQuadQua, *triQuadHex;
4965 const bool toFixCentralNodes = ( myMesh->NbBiQuadQuadrangles() +
4966 myMesh->NbBiQuadTriangles() +
4967 myMesh->NbTriQuadraticHexas() );
4969 for ( pLink = links.begin(); pLink != links.end(); ++pLink ) {
4970 if ( pLink->IsMoved() )
4972 gp_Pnt p = pLink->MiddlePnt() + pLink->Move();
4973 GetMeshDS()->MoveNode( pLink->_mediumNode, p.X(), p.Y(), p.Z());
4975 // collect bi-quadratic elements
4976 if ( toFixCentralNodes )
4978 biQuadQua = triQuadHex = 0;
4979 SMDS_ElemIteratorPtr eIt = pLink->_mediumNode->GetInverseElementIterator();
4980 while ( eIt->more() )
4982 const SMDS_MeshElement* e = eIt->next();
4983 switch( e->GetEntityType() ) {
4984 case SMDSEntity_BiQuad_Quadrangle: biQuadQuas.insert( e ); break;
4985 case SMDSEntity_BiQuad_Triangle: biQuadTris.insert( e ); break;
4986 case SMDSEntity_TriQuad_Hexa: triQuadHexa.insert( e ); break;
4993 // Fix positions of central nodes of bi-tri-quadratic elements
4995 // treat bi-quad quadrangles
4997 vector< const SMDS_MeshNode* > nodes( 9 );
4999 TIDSortedElemSet::iterator quadIt = biQuadQuas.begin();
5000 for ( ; quadIt != biQuadQuas.end(); ++quadIt )
5002 const SMDS_MeshElement* quad = *quadIt;
5005 nodes.assign( quad->begin_nodes(), quad->end_nodes() );
5007 TopoDS_Shape S = GetSubShapeByNode( nodes.back(), GetMeshDS() );
5008 if ( S.IsNull() || S.ShapeType() != TopAbs_FACE ) continue;
5009 const TopoDS_Face& F = TopoDS::Face( S );
5010 Handle( Geom_Surface ) surf = BRep_Tool::Surface( F, loc );
5011 const double tol = BRep_Tool::Tolerance( F );
5013 for ( int i = 0; i < 8; ++i )
5015 uv[ i ] = GetNodeUV( F, nodes[i], nodes[8], &checkUV );
5016 // as this method is used after mesh generation, UV of nodes is not
5017 // updated according to bending links, so we update
5018 if ( i > 3 && nodes[i]->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE )
5019 CheckNodeUV( F, nodes[i], uv[ i ], 2*tol, /*force=*/true );
5021 // move the central node
5022 gp_XY uvCent = calcTFI (0.5, 0.5, uv[0],uv[1],uv[2],uv[3],uv[4],uv[5],uv[6],uv[7] );
5023 gp_Pnt p = surf->Value( uvCent.X(), uvCent.Y() ).Transformed( loc );
5024 GetMeshDS()->MoveNode( nodes[8], p.X(), p.Y(), p.Z());
5028 // treat bi-quad triangles
5030 vector< const SMDS_MeshNode* > nodes;
5032 TIDSortedElemSet::iterator triIt = biQuadTris.begin();
5033 for ( ; triIt != biQuadTris.end(); ++triIt )
5035 const SMDS_MeshElement* tria = *triIt;
5037 const TopoDS_Shape& S = GetMeshDS()->IndexToShape( tria->getshapeId() );
5038 if ( S.IsNull() || S.ShapeType() != TopAbs_FACE ) continue;
5039 const TopoDS_Face& F = TopoDS::Face( S );
5040 Handle( Geom_Surface ) surf = BRep_Tool::Surface( F, loc );
5041 const double tol = BRep_Tool::Tolerance( F );
5044 nodes.assign( tria->begin_nodes(), tria->end_nodes() );
5046 bool uvOK = true, badTria;
5047 for ( int i = 0; i < 6; ++i )
5049 uv[ i ] = GetNodeUV( F, nodes[i], nodes[(i+1)%3], &uvOK );
5050 // as this method is used after mesh generation, UV of nodes is not
5051 // updated according to bending links, so we update
5052 if ( nodes[i]->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE )
5053 CheckNodeUV( F, nodes[i], uv[ i ], 2*tol, /*force=*/true );
5055 // move the central node
5057 if ( !uvOK || badTria )
5059 p = ( SMESH_TNodeXYZ( nodes[3] ) +
5060 SMESH_TNodeXYZ( nodes[4] ) +
5061 SMESH_TNodeXYZ( nodes[5] )) / 3;
5065 gp_XY uvCent = GetCenterUV( uv[0], uv[1], uv[2], uv[3], uv[4], uv[5], &badTria );
5066 p = surf->Value( uvCent.X(), uvCent.Y() ).Transformed( loc );
5068 GetMeshDS()->MoveNode( tria->GetNode(6), p.X(), p.Y(), p.Z() );
5072 // treat tri-quadratic hexahedra
5074 SMDS_VolumeTool volExp;
5075 TIDSortedElemSet::iterator hexIt = triQuadHexa.begin();
5076 for ( ; hexIt != triQuadHexa.end(); ++hexIt )
5078 volExp.Set( *hexIt, /*ignoreCentralNodes=*/false );
5080 // fix nodes central in sides
5081 for ( int iQuad = 0; iQuad < volExp.NbFaces(); ++iQuad )
5083 const SMDS_MeshNode** quadNodes = volExp.GetFaceNodes( iQuad );
5084 if ( quadNodes[8]->GetPosition()->GetTypeOfPosition() == SMDS_TOP_3DSPACE )
5086 gp_XYZ p = calcTFI( 0.5, 0.5,
5087 SMESH_TNodeXYZ( quadNodes[0] ), SMESH_TNodeXYZ( quadNodes[2] ),
5088 SMESH_TNodeXYZ( quadNodes[4] ), SMESH_TNodeXYZ( quadNodes[6] ),
5089 SMESH_TNodeXYZ( quadNodes[1] ), SMESH_TNodeXYZ( quadNodes[3] ),
5090 SMESH_TNodeXYZ( quadNodes[5] ), SMESH_TNodeXYZ( quadNodes[7] ));
5091 GetMeshDS()->MoveNode( quadNodes[8], p.X(), p.Y(), p.Z());
5095 // fix the volume central node
5096 vector<gp_XYZ> pointsOnShapes( SMESH_Block::ID_Shell );
5097 const SMDS_MeshNode** hexNodes = volExp.GetNodes();
5099 pointsOnShapes[ SMESH_Block::ID_V000 ] = SMESH_TNodeXYZ( hexNodes[ 0 ] );
5100 pointsOnShapes[ SMESH_Block::ID_V100 ] = SMESH_TNodeXYZ( hexNodes[ 3 ] );
5101 pointsOnShapes[ SMESH_Block::ID_V010 ] = SMESH_TNodeXYZ( hexNodes[ 1 ] );
5102 pointsOnShapes[ SMESH_Block::ID_V110 ] = SMESH_TNodeXYZ( hexNodes[ 2 ] );
5103 pointsOnShapes[ SMESH_Block::ID_V001 ] = SMESH_TNodeXYZ( hexNodes[ 4 ] );
5104 pointsOnShapes[ SMESH_Block::ID_V101 ] = SMESH_TNodeXYZ( hexNodes[ 7 ] );
5105 pointsOnShapes[ SMESH_Block::ID_V011 ] = SMESH_TNodeXYZ( hexNodes[ 5 ] );
5106 pointsOnShapes[ SMESH_Block::ID_V111 ] = SMESH_TNodeXYZ( hexNodes[ 6 ] );
5108 pointsOnShapes[ SMESH_Block::ID_Ex00 ] = SMESH_TNodeXYZ( hexNodes[ 11 ] );
5109 pointsOnShapes[ SMESH_Block::ID_Ex10 ] = SMESH_TNodeXYZ( hexNodes[ 9 ] );
5110 pointsOnShapes[ SMESH_Block::ID_E0y0 ] = SMESH_TNodeXYZ( hexNodes[ 8 ] );
5111 pointsOnShapes[ SMESH_Block::ID_E1y0 ] = SMESH_TNodeXYZ( hexNodes[ 10 ] );
5112 pointsOnShapes[ SMESH_Block::ID_Ex01 ] = SMESH_TNodeXYZ( hexNodes[ 15 ] );
5113 pointsOnShapes[ SMESH_Block::ID_Ex11 ] = SMESH_TNodeXYZ( hexNodes[ 13 ] );
5114 pointsOnShapes[ SMESH_Block::ID_E0y1 ] = SMESH_TNodeXYZ( hexNodes[ 12 ] );
5115 pointsOnShapes[ SMESH_Block::ID_E1y1 ] = SMESH_TNodeXYZ( hexNodes[ 14 ] );
5116 pointsOnShapes[ SMESH_Block::ID_E00z ] = SMESH_TNodeXYZ( hexNodes[ 16 ] );
5117 pointsOnShapes[ SMESH_Block::ID_E10z ] = SMESH_TNodeXYZ( hexNodes[ 19 ] );
5118 pointsOnShapes[ SMESH_Block::ID_E01z ] = SMESH_TNodeXYZ( hexNodes[ 17 ] );
5119 pointsOnShapes[ SMESH_Block::ID_E11z ] = SMESH_TNodeXYZ( hexNodes[ 18 ] );
5121 pointsOnShapes[ SMESH_Block::ID_Fxy0 ] = SMESH_TNodeXYZ( hexNodes[ 20 ] );
5122 pointsOnShapes[ SMESH_Block::ID_Fxy1 ] = SMESH_TNodeXYZ( hexNodes[ 25 ] );
5123 pointsOnShapes[ SMESH_Block::ID_Fx0z ] = SMESH_TNodeXYZ( hexNodes[ 21 ] );
5124 pointsOnShapes[ SMESH_Block::ID_Fx1z ] = SMESH_TNodeXYZ( hexNodes[ 23 ] );
5125 pointsOnShapes[ SMESH_Block::ID_F0yz ] = SMESH_TNodeXYZ( hexNodes[ 24 ] );
5126 pointsOnShapes[ SMESH_Block::ID_F1yz ] = SMESH_TNodeXYZ( hexNodes[ 22 ] );
5128 gp_XYZ nCenterParams(0.5, 0.5, 0.5), nCenterCoords;
5129 SMESH_Block::ShellPoint( nCenterParams, pointsOnShapes, nCenterCoords );
5130 GetMeshDS()->MoveNode( hexNodes[26],
5131 nCenterCoords.X(), nCenterCoords.Y(), nCenterCoords.Z());