1 // Copyright (C) 2007-2010 CEA/DEN, EDF R&D, OPEN CASCADE
3 // Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License.
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 // Lesser General Public License for more details.
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
23 // File: SMESH_MesherHelper.cxx
24 // Created: 15.02.06 15:22:41
25 // Author: Sergey KUUL
27 #include "SMESH_MesherHelper.hxx"
29 #include "SMDS_FacePosition.hxx"
30 #include "SMDS_EdgePosition.hxx"
31 #include "SMDS_VolumeTool.hxx"
32 #include "SMESH_subMesh.hxx"
34 #include <BRepAdaptor_Surface.hxx>
35 #include <BRepTools.hxx>
36 #include <BRepTools_WireExplorer.hxx>
37 #include <BRep_Tool.hxx>
38 #include <Geom2d_Curve.hxx>
39 #include <GeomAPI_ProjectPointOnCurve.hxx>
40 #include <GeomAPI_ProjectPointOnSurf.hxx>
41 #include <Geom_Curve.hxx>
42 #include <Geom_Surface.hxx>
43 #include <ShapeAnalysis.hxx>
45 #include <TopExp_Explorer.hxx>
46 #include <TopTools_ListIteratorOfListOfShape.hxx>
47 #include <TopTools_MapIteratorOfMapOfShape.hxx>
48 #include <TopTools_MapOfShape.hxx>
51 #include <gp_Pnt2d.hxx>
52 #include <gp_Trsf.hxx>
54 #include <Standard_Failure.hxx>
55 #include <Standard_ErrorHandler.hxx>
57 #include <utilities.h>
63 #define RETURN_BAD_RESULT(msg) { MESSAGE(msg); return false; }
67 gp_XYZ XYZ(const SMDS_MeshNode* n) { return gp_XYZ(n->X(), n->Y(), n->Z()); }
69 enum { U_periodic = 1, V_periodic = 2 };
72 //================================================================================
76 //================================================================================
78 SMESH_MesherHelper::SMESH_MesherHelper(SMESH_Mesh& theMesh)
79 : myParIndex(0), myMesh(&theMesh), myShapeID(0), myCreateQuadratic(false)
81 myPar1[0] = myPar2[0] = myPar1[1] = myPar2[1] = 0;
82 mySetElemOnShape = ( ! myMesh->HasShapeToMesh() );
85 //=======================================================================
86 //function : ~SMESH_MesherHelper
88 //=======================================================================
90 SMESH_MesherHelper::~SMESH_MesherHelper()
93 TID2ProjectorOnSurf::iterator i_proj = myFace2Projector.begin();
94 for ( ; i_proj != myFace2Projector.end(); ++i_proj )
95 delete i_proj->second;
98 TID2ProjectorOnCurve::iterator i_proj = myEdge2Projector.begin();
99 for ( ; i_proj != myEdge2Projector.end(); ++i_proj )
100 delete i_proj->second;
104 //=======================================================================
105 //function : IsQuadraticSubMesh
106 //purpose : Check submesh for given shape: if all elements on this shape
107 // are quadratic, quadratic elements will be created.
108 // Also fill myTLinkNodeMap
109 //=======================================================================
111 bool SMESH_MesherHelper::IsQuadraticSubMesh(const TopoDS_Shape& aSh)
113 SMESHDS_Mesh* meshDS = GetMeshDS();
114 // we can create quadratic elements only if all elements
115 // created on subshapes of given shape are quadratic
116 // also we have to fill myTLinkNodeMap
117 myCreateQuadratic = true;
118 mySeamShapeIds.clear();
119 myDegenShapeIds.clear();
120 TopAbs_ShapeEnum subType( aSh.ShapeType()==TopAbs_FACE ? TopAbs_EDGE : TopAbs_FACE );
121 SMDSAbs_ElementType elemType( subType==TopAbs_FACE ? SMDSAbs_Face : SMDSAbs_Edge );
123 int nbOldLinks = myTLinkNodeMap.size();
125 TopExp_Explorer exp( aSh, subType );
126 for (; exp.More() && myCreateQuadratic; exp.Next()) {
127 if ( SMESHDS_SubMesh * subMesh = meshDS->MeshElements( exp.Current() )) {
128 if ( SMDS_ElemIteratorPtr it = subMesh->GetElements() ) {
130 const SMDS_MeshElement* e = it->next();
131 if ( e->GetType() != elemType || !e->IsQuadratic() ) {
132 myCreateQuadratic = false;
137 switch ( e->NbNodes() ) {
139 AddTLinkNode(e->GetNode(0),e->GetNode(1),e->GetNode(2)); break;
141 AddTLinkNode(e->GetNode(0),e->GetNode(1),e->GetNode(3));
142 AddTLinkNode(e->GetNode(1),e->GetNode(2),e->GetNode(4));
143 AddTLinkNode(e->GetNode(2),e->GetNode(0),e->GetNode(5)); break;
145 AddTLinkNode(e->GetNode(0),e->GetNode(1),e->GetNode(4));
146 AddTLinkNode(e->GetNode(1),e->GetNode(2),e->GetNode(5));
147 AddTLinkNode(e->GetNode(2),e->GetNode(3),e->GetNode(6));
148 AddTLinkNode(e->GetNode(3),e->GetNode(0),e->GetNode(7));
151 myCreateQuadratic = false;
160 if ( nbOldLinks == myTLinkNodeMap.size() )
161 myCreateQuadratic = false;
163 if(!myCreateQuadratic) {
164 myTLinkNodeMap.clear();
168 return myCreateQuadratic;
171 //=======================================================================
172 //function : SetSubShape
173 //purpose : Set geomerty to make elements on
174 //=======================================================================
176 void SMESH_MesherHelper::SetSubShape(const int aShID)
178 if ( aShID == myShapeID )
181 SetSubShape( GetMeshDS()->IndexToShape( aShID ));
183 SetSubShape( TopoDS_Shape() );
186 //=======================================================================
187 //function : SetSubShape
188 //purpose : Set geomerty to create elements on
189 //=======================================================================
191 void SMESH_MesherHelper::SetSubShape(const TopoDS_Shape& aSh)
193 if ( myShape.IsSame( aSh ))
197 mySeamShapeIds.clear();
198 myDegenShapeIds.clear();
200 if ( myShape.IsNull() ) {
204 SMESHDS_Mesh* meshDS = GetMeshDS();
205 myShapeID = meshDS->ShapeToIndex(aSh);
208 // treatment of periodic faces
209 for ( TopExp_Explorer eF( aSh, TopAbs_FACE ); eF.More(); eF.Next() )
211 const TopoDS_Face& face = TopoDS::Face( eF.Current() );
212 BRepAdaptor_Surface surface( face );
213 if ( surface.IsUPeriodic() || surface.IsVPeriodic() )
215 for (TopExp_Explorer exp( face, TopAbs_EDGE ); exp.More(); exp.Next())
217 // look for a seam edge
218 const TopoDS_Edge& edge = TopoDS::Edge( exp.Current() );
219 if ( BRep_Tool::IsClosed( edge, face )) {
220 // initialize myPar1, myPar2 and myParIndex
222 BRep_Tool::UVPoints( edge, face, uv1, uv2 );
223 if ( Abs( uv1.Coord(1) - uv2.Coord(1) ) < Abs( uv1.Coord(2) - uv2.Coord(2) ))
225 myParIndex |= U_periodic;
226 myPar1[0] = surface.FirstUParameter();
227 myPar2[0] = surface.LastUParameter();
230 myParIndex |= V_periodic;
231 myPar1[1] = surface.FirstVParameter();
232 myPar2[1] = surface.LastVParameter();
234 // store seam shape indices, negative if shape encounters twice
235 int edgeID = meshDS->ShapeToIndex( edge );
236 mySeamShapeIds.insert( IsSeamShape( edgeID ) ? -edgeID : edgeID );
237 for ( TopExp_Explorer v( edge, TopAbs_VERTEX ); v.More(); v.Next() ) {
238 int vertexID = meshDS->ShapeToIndex( v.Current() );
239 mySeamShapeIds.insert( IsSeamShape( vertexID ) ? -vertexID : vertexID );
243 // look for a degenerated edge
244 if ( BRep_Tool::Degenerated( edge )) {
245 myDegenShapeIds.insert( meshDS->ShapeToIndex( edge ));
246 for ( TopExp_Explorer v( edge, TopAbs_VERTEX ); v.More(); v.Next() )
247 myDegenShapeIds.insert( meshDS->ShapeToIndex( v.Current() ));
254 //=======================================================================
255 //function : GetNodeUVneedInFaceNode
256 //purpose : Check if inFaceNode argument is necessary for call GetNodeUV(F,..)
257 // Return true if the face is periodic.
258 // If F is Null, answer about subshape set through IsQuadraticSubMesh() or
260 //=======================================================================
262 bool SMESH_MesherHelper::GetNodeUVneedInFaceNode(const TopoDS_Face& F) const
264 if ( F.IsNull() ) return !mySeamShapeIds.empty();
266 if ( !F.IsNull() && !myShape.IsNull() && myShape.IsSame( F ))
267 return !mySeamShapeIds.empty();
270 Handle(Geom_Surface) aSurface = BRep_Tool::Surface( F,loc );
271 if ( !aSurface.IsNull() )
272 return ( aSurface->IsUPeriodic() || aSurface->IsVPeriodic() );
277 //=======================================================================
278 //function : IsMedium
280 //=======================================================================
282 bool SMESH_MesherHelper::IsMedium(const SMDS_MeshNode* node,
283 const SMDSAbs_ElementType typeToCheck)
285 return SMESH_MeshEditor::IsMedium( node, typeToCheck );
288 //=======================================================================
289 //function : GetSubShapeByNode
290 //purpose : Return support shape of a node
291 //=======================================================================
293 TopoDS_Shape SMESH_MesherHelper::GetSubShapeByNode(const SMDS_MeshNode* node,
294 SMESHDS_Mesh* meshDS)
296 int shapeID = node->getshapeId();
297 if ( 0 < shapeID && shapeID <= meshDS->MaxShapeIndex() )
298 return meshDS->IndexToShape( shapeID );
300 return TopoDS_Shape();
304 //=======================================================================
305 //function : AddTLinkNode
306 //purpose : add a link in my data structure
307 //=======================================================================
309 void SMESH_MesherHelper::AddTLinkNode(const SMDS_MeshNode* n1,
310 const SMDS_MeshNode* n2,
311 const SMDS_MeshNode* n12)
313 // add new record to map
314 SMESH_TLink link( n1, n2 );
315 myTLinkNodeMap.insert( make_pair(link,n12));
318 //=======================================================================
319 //function : GetUVOnSeam
320 //purpose : Select UV on either of 2 pcurves of a seam edge, closest to the given UV
321 //=======================================================================
323 gp_Pnt2d SMESH_MesherHelper::GetUVOnSeam( const gp_Pnt2d& uv1, const gp_Pnt2d& uv2 ) const
325 gp_Pnt2d result = uv1;
326 for ( int i = U_periodic; i <= V_periodic ; ++i )
328 if ( myParIndex & i )
330 double p1 = uv1.Coord( i );
331 double dp1 = Abs( p1-myPar1[i-1]), dp2 = Abs( p1-myPar2[i-1]);
332 if ( myParIndex == i ||
333 dp1 < ( myPar2[i-1] - myPar2[i-1] ) / 100. ||
334 dp2 < ( myPar2[i-1] - myPar2[i-1] ) / 100. )
336 double p2 = uv2.Coord( i );
337 double p1Alt = ( dp1 < dp2 ) ? myPar2[i-1] : myPar1[i-1];
338 if ( Abs( p2 - p1 ) > Abs( p2 - p1Alt ))
339 result.SetCoord( i, p1Alt );
346 //=======================================================================
347 //function : GetNodeUV
348 //purpose : Return node UV on face
349 //=======================================================================
351 gp_XY SMESH_MesherHelper::GetNodeUV(const TopoDS_Face& F,
352 const SMDS_MeshNode* n,
353 const SMDS_MeshNode* n2,
356 gp_Pnt2d uv( Precision::Infinite(), Precision::Infinite() );
357 const SMDS_PositionPtr Pos = n->GetPosition();
359 if(Pos->GetTypeOfPosition()==SMDS_TOP_FACE)
361 // node has position on face
362 const SMDS_FacePosition* fpos =
363 static_cast<const SMDS_FacePosition*>(n->GetPosition());
364 uv.SetCoord(fpos->GetUParameter(),fpos->GetVParameter());
366 uvOK = CheckNodeUV( F, n, uv.ChangeCoord(), 10*MaxTolerance( F ));
368 else if(Pos->GetTypeOfPosition()==SMDS_TOP_EDGE)
370 // node has position on edge => it is needed to find
371 // corresponding edge from face, get pcurve for this
372 // edge and retrieve value from this pcurve
373 const SMDS_EdgePosition* epos =
374 static_cast<const SMDS_EdgePosition*>(n->GetPosition());
375 int edgeID = n->getshapeId();
376 TopoDS_Edge E = TopoDS::Edge(GetMeshDS()->IndexToShape(edgeID));
377 double f, l, u = epos->GetUParameter();
378 Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface(E, F, f, l);
379 bool validU = ( f < u && u < l );
381 uv = C2d->Value( u );
384 if ( check || !validU )
385 uvOK = CheckNodeUV( F, n, uv.ChangeCoord(), 10*MaxTolerance( F ),/*force=*/ !validU );
387 // for a node on a seam edge select one of UVs on 2 pcurves
388 if ( n2 && IsSeamShape( edgeID ) )
390 uv = GetUVOnSeam( uv, GetNodeUV( F, n2, 0, check ));
393 { // adjust uv to period
395 Handle(Geom_Surface) S = BRep_Tool::Surface(F,loc);
396 Standard_Boolean isUPeriodic = S->IsUPeriodic();
397 Standard_Boolean isVPeriodic = S->IsVPeriodic();
398 if ( isUPeriodic || isVPeriodic ) {
399 Standard_Real UF,UL,VF,VL;
400 S->Bounds(UF,UL,VF,VL);
402 uv.SetX( uv.X() + ShapeAnalysis::AdjustToPeriod(uv.X(),UF,UL));
404 uv.SetY( uv.Y() + ShapeAnalysis::AdjustToPeriod(uv.Y(),VF,VL));
408 else if(Pos->GetTypeOfPosition()==SMDS_TOP_VERTEX)
410 if ( int vertexID = n->getshapeId() ) {
411 const TopoDS_Vertex& V = TopoDS::Vertex(GetMeshDS()->IndexToShape(vertexID));
413 uv = BRep_Tool::Parameters( V, F );
416 catch (Standard_Failure& exc) {
419 for ( TopExp_Explorer vert(F,TopAbs_VERTEX); !uvOK && vert.More(); vert.Next() )
420 uvOK = ( V == vert.Current() );
423 MESSAGE ( "SMESH_MesherHelper::GetNodeUV(); Vertex " << vertexID
424 << " not in face " << GetMeshDS()->ShapeToIndex( F ) );
426 // get UV of a vertex closest to the node
428 gp_Pnt pn = XYZ( n );
429 for ( TopExp_Explorer vert(F,TopAbs_VERTEX); !uvOK && vert.More(); vert.Next() ) {
430 TopoDS_Vertex curV = TopoDS::Vertex( vert.Current() );
431 gp_Pnt p = BRep_Tool::Pnt( curV );
432 double curDist = p.SquareDistance( pn );
433 if ( curDist < dist ) {
435 uv = BRep_Tool::Parameters( curV, F );
436 uvOK = ( dist < DBL_MIN );
442 TopTools_ListIteratorOfListOfShape it( myMesh->GetAncestors( V ));
443 for ( ; it.More(); it.Next() ) {
444 if ( it.Value().ShapeType() == TopAbs_EDGE ) {
445 const TopoDS_Edge & edge = TopoDS::Edge( it.Value() );
447 Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface(edge, F, f, l);
448 if ( !C2d.IsNull() ) {
449 double u = ( V == TopExp::FirstVertex( edge ) ) ? f : l;
450 uv = C2d->Value( u );
458 if ( n2 && IsSeamShape( vertexID ) )
459 uv = GetUVOnSeam( uv, GetNodeUV( F, n2, 0 ));
469 //=======================================================================
470 //function : CheckNodeUV
471 //purpose : Check and fix node UV on a face
472 //=======================================================================
474 bool SMESH_MesherHelper::CheckNodeUV(const TopoDS_Face& F,
475 const SMDS_MeshNode* n,
478 const bool force) const
480 if ( force || !myOkNodePosShapes.count( n->getshapeId() ))
483 double tolmin = 1.e-7*myMesh->GetMeshDS()->getMaxDim(); // nodes coordinates are stored in float format
484 if (toldis < tolmin) toldis = tolmin;
485 // check that uv is correct
487 Handle(Geom_Surface) surface = BRep_Tool::Surface( F,loc );
488 gp_Pnt nodePnt = XYZ( n );
489 if ( !loc.IsIdentity() ) nodePnt.Transform( loc.Transformation().Inverted() );
490 if ( Precision::IsInfinite( uv.X() ) ||
491 Precision::IsInfinite( uv.Y() ) ||
492 nodePnt.Distance( surface->Value( uv.X(), uv.Y() )) > toldis )
494 // uv incorrect, project the node to surface
495 GeomAPI_ProjectPointOnSurf& projector = GetProjector( F, loc, tol );
496 projector.Perform( nodePnt );
497 if ( !projector.IsDone() || projector.NbPoints() < 1 )
499 MESSAGE( "SMESH_MesherHelper::CheckNodeUV() failed to project" );
502 Quantity_Parameter U,V;
503 projector.LowerDistanceParameters(U,V);
505 if ( nodePnt.Distance( surface->Value( U, V )) > toldis )
507 MESSAGE( "SMESH_MesherHelper::CheckNodeUV(), invalid projection" );
511 else if ( uv.Modulus() > numeric_limits<double>::min() )
513 ((SMESH_MesherHelper*) this)->myOkNodePosShapes.insert( n->getshapeId() );
519 //=======================================================================
520 //function : GetProjector
521 //purpose : Return projector intitialized by given face without location, which is returned
522 //=======================================================================
524 GeomAPI_ProjectPointOnSurf& SMESH_MesherHelper::GetProjector(const TopoDS_Face& F,
525 TopLoc_Location& loc,
528 Handle(Geom_Surface) surface = BRep_Tool::Surface( F,loc );
529 int faceID = GetMeshDS()->ShapeToIndex( F );
530 TID2ProjectorOnSurf& i2proj = const_cast< TID2ProjectorOnSurf&>( myFace2Projector );
531 TID2ProjectorOnSurf::iterator i_proj = i2proj.find( faceID );
532 if ( i_proj == i2proj.end() )
534 if ( tol == 0 ) tol = BRep_Tool::Tolerance( F );
535 double U1, U2, V1, V2;
536 surface->Bounds(U1, U2, V1, V2);
537 GeomAPI_ProjectPointOnSurf* proj = new GeomAPI_ProjectPointOnSurf();
538 proj->Init( surface, U1, U2, V1, V2, tol );
539 i_proj = i2proj.insert( make_pair( faceID, proj )).first;
541 return *( i_proj->second );
546 gp_XY AverageUV(const gp_XY& uv1, const gp_XY& uv2) { return ( uv1 + uv2 ) / 2.; }
547 gp_XY_FunPtr(Added); // define gp_XY_Added pointer to function calling gp_XY::Added(gp_XY)
548 gp_XY_FunPtr(Subtracted);
551 //=======================================================================
552 //function : applyIn2D
553 //purpose : Perform given operation on two 2d points in parameric space of given surface.
554 // It takes into account period of the surface. Use gp_XY_FunPtr macro
555 // to easily define pointer to function of gp_XY class.
556 //=======================================================================
558 gp_XY SMESH_MesherHelper::applyIn2D(const Handle(Geom_Surface)& surface,
562 const bool resultInPeriod)
564 Standard_Boolean isUPeriodic = surface.IsNull() ? false : surface->IsUPeriodic();
565 Standard_Boolean isVPeriodic = surface.IsNull() ? false : surface->IsVPeriodic();
566 if ( !isUPeriodic && !isVPeriodic )
569 // move uv2 not far than half-period from uv1
571 uv2.X()+(isUPeriodic ? ShapeAnalysis::AdjustByPeriod(uv2.X(),uv1.X(),surface->UPeriod()) :0);
573 uv2.Y()+(isVPeriodic ? ShapeAnalysis::AdjustByPeriod(uv2.Y(),uv1.Y(),surface->VPeriod()) :0);
576 gp_XY res = fun( uv1, gp_XY(u2,v2) );
578 // move result within period
579 if ( resultInPeriod )
581 Standard_Real UF,UL,VF,VL;
582 surface->Bounds(UF,UL,VF,VL);
584 res.SetX( res.X() + ShapeAnalysis::AdjustToPeriod(res.X(),UF,UL));
586 res.SetY( res.Y() + ShapeAnalysis::AdjustToPeriod(res.Y(),VF,VL));
591 //=======================================================================
592 //function : GetMiddleUV
593 //purpose : Return middle UV taking in account surface period
594 //=======================================================================
596 gp_XY SMESH_MesherHelper::GetMiddleUV(const Handle(Geom_Surface)& surface,
600 return applyIn2D( surface, p1, p2, & AverageUV );
603 //=======================================================================
604 //function : GetNodeU
605 //purpose : Return node U on edge
606 //=======================================================================
608 double SMESH_MesherHelper::GetNodeU(const TopoDS_Edge& E,
609 const SMDS_MeshNode* n,
610 const SMDS_MeshNode* inEdgeNode,
614 const SMDS_PositionPtr pos = n->GetPosition();
615 if ( pos->GetTypeOfPosition()==SMDS_TOP_EDGE )
617 const SMDS_EdgePosition* epos = static_cast<const SMDS_EdgePosition*>( pos );
618 param = epos->GetUParameter();
620 else if( pos->GetTypeOfPosition() == SMDS_TOP_VERTEX )
622 if ( inEdgeNode && TopExp::FirstVertex( E ).IsSame( TopExp::LastVertex( E ))) // issue 0020128
625 BRep_Tool::Range( E, f,l );
626 double uInEdge = GetNodeU( E, inEdgeNode );
627 param = ( fabs( uInEdge - f ) < fabs( l - uInEdge )) ? f : l;
631 SMESHDS_Mesh * meshDS = GetMeshDS();
632 int vertexID = n->getshapeId();
633 const TopoDS_Vertex& V = TopoDS::Vertex(meshDS->IndexToShape(vertexID));
634 param = BRep_Tool::Parameter( V, E );
639 double tol = BRep_Tool::Tolerance( E );
640 double f,l; BRep_Tool::Range( E, f,l );
641 bool force = ( param < f-tol || param > l+tol );
642 if ( !force && pos->GetTypeOfPosition()==SMDS_TOP_EDGE )
643 force = ( GetMeshDS()->ShapeToIndex( E ) != n->getshapeId() );
645 *check = CheckNodeU( E, n, param, 2*tol, force );
650 //=======================================================================
651 //function : CheckNodeU
652 //purpose : Check and fix node U on an edge
653 // Return false if U is bad and could not be fixed
654 //=======================================================================
656 bool SMESH_MesherHelper::CheckNodeU(const TopoDS_Edge& E,
657 const SMDS_MeshNode* n,
661 double* distance) const
663 if ( force || !myOkNodePosShapes.count( n->getshapeId() ))
666 double tolmin = 1.e-7*myMesh->GetMeshDS()->getMaxDim(); // nodes coordinates are stored in float format
667 if (toldis < tolmin) toldis = tolmin;
668 // check that u is correct
669 TopLoc_Location loc; double f,l;
670 Handle(Geom_Curve) curve = BRep_Tool::Curve( E,loc,f,l );
671 if ( curve.IsNull() ) // degenerated edge
673 if ( u+tol < f || u-tol > l )
675 double r = Max( 0.5, 1 - tol*n->GetID()); // to get a unique u on edge
681 gp_Pnt nodePnt = SMESH_MeshEditor::TNodeXYZ( n );
682 if ( !loc.IsIdentity() ) nodePnt.Transform( loc.Transformation().Inverted() );
683 double dist = nodePnt.Distance( curve->Value( u ));
684 if ( distance ) *distance = dist;
687 // u incorrect, project the node to the curve
688 int edgeID = GetMeshDS()->ShapeToIndex( E );
689 TID2ProjectorOnCurve& i2proj = const_cast< TID2ProjectorOnCurve&>( myEdge2Projector );
690 TID2ProjectorOnCurve::iterator i_proj =
691 i2proj.insert( make_pair( edgeID, (GeomAPI_ProjectPointOnCurve*) 0 )).first;
692 if ( !i_proj->second )
694 i_proj->second = new GeomAPI_ProjectPointOnCurve();
695 i_proj->second->Init( curve, f, l );
697 GeomAPI_ProjectPointOnCurve* projector = i_proj->second;
698 projector->Perform( nodePnt );
699 if ( projector->NbPoints() < 1 )
701 MESSAGE( "SMESH_MesherHelper::CheckNodeU() failed to project" );
704 Quantity_Parameter U = projector->LowerDistanceParameter();
706 dist = nodePnt.Distance( curve->Value( U ));
707 if ( distance ) *distance = dist;
710 MESSAGE( "SMESH_MesherHelper::CheckNodeU(), invalid projection" );
711 MESSAGE("distance " << nodePnt.Distance(curve->Value( U )) << " " << toldis);
716 else if ( fabs( u ) > numeric_limits<double>::min() )
718 ((SMESH_MesherHelper*) this)->myOkNodePosShapes.insert( n->getshapeId() );
720 if (( u < f-tol || u > l+tol ) && force )
722 // node is on vertex but is set on periodic but trimmed edge (issue 0020890)
725 // do not use IsPeriodic() as Geom_TrimmedCurve::IsPeriodic () returns false
726 double period = curve->Period();
727 u = ( u < f ) ? u + period : u - period;
729 catch (Standard_Failure& exc)
739 //=======================================================================
740 //function : GetMediumNode
741 //purpose : Return existing or create new medium nodes between given ones
742 //=======================================================================
744 const SMDS_MeshNode* SMESH_MesherHelper::GetMediumNode(const SMDS_MeshNode* n1,
745 const SMDS_MeshNode* n2,
748 // Find existing node
750 SMESH_TLink link(n1,n2);
751 ItTLinkNode itLN = myTLinkNodeMap.find( link );
752 if ( itLN != myTLinkNodeMap.end() ) {
753 return (*itLN).second;
756 // Create medium node
759 SMESHDS_Mesh* meshDS = GetMeshDS();
761 // get type of shape for the new medium node
762 int faceID = -1, edgeID = -1;
763 const SMDS_PositionPtr Pos1 = n1->GetPosition();
764 const SMDS_PositionPtr Pos2 = n2->GetPosition();
766 TopoDS_Edge E; double u [2];
767 TopoDS_Face F; gp_XY uv[2];
768 bool uvOK[2] = { false, false };
770 if( myShape.IsNull() )
772 if( Pos1->GetTypeOfPosition()==SMDS_TOP_FACE ) {
773 faceID = n1->getshapeId();
775 else if( Pos2->GetTypeOfPosition()==SMDS_TOP_FACE ) {
776 faceID = n2->getshapeId();
779 if( Pos1->GetTypeOfPosition()==SMDS_TOP_EDGE ) {
780 edgeID = n1->getshapeId();
782 if( Pos2->GetTypeOfPosition()==SMDS_TOP_EDGE ) {
783 edgeID = n2->getshapeId();
786 // get positions of the given nodes on shapes
787 TopAbs_ShapeEnum shapeType = myShape.IsNull() ? TopAbs_SHAPE : myShape.ShapeType();
788 if ( faceID>0 || shapeType == TopAbs_FACE)
790 if( myShape.IsNull() )
791 F = TopoDS::Face(meshDS->IndexToShape(faceID));
793 F = TopoDS::Face(myShape);
796 uv[0] = GetNodeUV(F,n1,n2, force3d ? 0 : &uvOK[0]);
797 uv[1] = GetNodeUV(F,n2,n1, force3d ? 0 : &uvOK[1]);
799 else if (edgeID>0 || shapeType == TopAbs_EDGE)
801 if ( Pos1->GetTypeOfPosition()==SMDS_TOP_EDGE &&
802 Pos2->GetTypeOfPosition()==SMDS_TOP_EDGE &&
803 n1->getshapeId() != n2->getshapeId() ) // issue 0021006
804 return getMediumNodeOnComposedWire(n1,n2,force3d);
806 if( myShape.IsNull() )
807 E = TopoDS::Edge(meshDS->IndexToShape(edgeID));
809 E = TopoDS::Edge(myShape);
812 u[0] = GetNodeU(E,n1,n2, force3d ? 0 : &uvOK[0]);
813 u[1] = GetNodeU(E,n2,n1, force3d ? 0 : &uvOK[1]);
817 // we try to create medium node using UV parameters of
818 // nodes, else - medium between corresponding 3d points
821 if ( uvOK[0] && uvOK[1] )
823 if ( IsDegenShape( n1->getshapeId() ))
824 if ( myParIndex & U_periodic ) uv[0].SetCoord( 1, uv[1].Coord( 1 ));
825 else uv[0].SetCoord( 2, uv[1].Coord( 2 ));
826 else if ( IsDegenShape( n2->getshapeId() ))
827 if ( myParIndex & U_periodic ) uv[1].SetCoord( 1, uv[0].Coord( 1 ));
828 else uv[1].SetCoord( 2, uv[0].Coord( 2 ));
831 Handle(Geom_Surface) S = BRep_Tool::Surface(F,loc);
832 gp_XY UV = GetMiddleUV( S, uv[0], uv[1] );
833 gp_Pnt P = S->Value( UV.X(), UV.Y() ).Transformed(loc);
834 n12 = meshDS->AddNode(P.X(), P.Y(), P.Z());
835 meshDS->SetNodeOnFace(n12, faceID, UV.X(), UV.Y());
836 myTLinkNodeMap.insert(make_pair(link,n12));
840 else if ( !E.IsNull() )
843 Handle(Geom_Curve) C = BRep_Tool::Curve(E, f, l);
846 Standard_Boolean isPeriodic = C->IsPeriodic();
849 Standard_Real Period = C->Period();
850 Standard_Real p = u[1]+ShapeAnalysis::AdjustByPeriod(u[1],u[0],Period);
851 Standard_Real pmid = (u[0]+p)/2.;
852 U = pmid+ShapeAnalysis::AdjustToPeriod(pmid,C->FirstParameter(),C->LastParameter());
857 gp_Pnt P = C->Value( U );
858 n12 = meshDS->AddNode(P.X(), P.Y(), P.Z());
859 meshDS->SetNodeOnEdge(n12, edgeID, U);
860 myTLinkNodeMap.insert(make_pair(link,n12));
867 double x = ( n1->X() + n2->X() )/2.;
868 double y = ( n1->Y() + n2->Y() )/2.;
869 double z = ( n1->Z() + n2->Z() )/2.;
870 n12 = meshDS->AddNode(x,y,z);
874 gp_XY UV = ( uv[0] + uv[1] ) / 2.;
875 CheckNodeUV( F, n12, UV, 2*BRep_Tool::Tolerance( F ), /*force=*/true);
876 meshDS->SetNodeOnFace(n12, faceID, UV.X(), UV.Y() );
878 else if ( !E.IsNull() )
880 double U = ( u[0] + u[1] ) / 2.;
881 CheckNodeU( E, n12, U, 2*BRep_Tool::Tolerance( E ), /*force=*/true);
882 meshDS->SetNodeOnEdge(n12, edgeID, U);
884 else if ( myShapeID > 0 )
886 meshDS->SetNodeInVolume(n12, myShapeID);
889 myTLinkNodeMap.insert( make_pair( link, n12 ));
893 //================================================================================
895 * \brief Makes a medium node if nodes reside different edges
897 //================================================================================
899 const SMDS_MeshNode* SMESH_MesherHelper::getMediumNodeOnComposedWire(const SMDS_MeshNode* n1,
900 const SMDS_MeshNode* n2,
903 gp_Pnt middle = 0.5 * XYZ(n1) + 0.5 * XYZ(n2);
904 SMDS_MeshNode* n12 = AddNode( middle.X(), middle.Y(), middle.Z() );
906 // To find position on edge and 3D position for n12,
907 // project <middle> to 2 edges and select projection most close to <middle>
909 double u = 0, distMiddleProj = Precision::Infinite();
911 TopoDS_Edge edges[2];
912 for ( int is2nd = 0; is2nd < 2; ++is2nd )
915 const SMDS_MeshNode* n = is2nd ? n2 : n1;
916 TopoDS_Shape shape = GetSubShapeByNode( n, GetMeshDS() );
917 if ( shape.IsNull() || shape.ShapeType() != TopAbs_EDGE )
920 // project to get U of projection and distance from middle to projection
921 TopoDS_Edge edge = edges[ is2nd ] = TopoDS::Edge( shape );
922 double node2MiddleDist = middle.Distance( XYZ(n) );
923 double foundU = GetNodeU( edge, n ), foundDist = node2MiddleDist;
924 CheckNodeU( edge, n12, foundU, 2*BRep_Tool::Tolerance(edge), /*force=*/true, &foundDist );
925 if ( foundDist < node2MiddleDist )
927 distMiddleProj = foundDist;
932 if ( Precision::IsInfinite( distMiddleProj ))
934 // both projections failed; set n12 on the edge of n1 with U of a common vertex
935 TopoDS_Vertex vCommon;
936 if ( TopExp::CommonVertex( edges[0], edges[1], vCommon ))
937 u = BRep_Tool::Parameter( vCommon, edges[0] );
940 double f,l, u0 = GetNodeU( edges[0], n1 );
941 BRep_Tool::Range( edges[0],f,l );
942 u = ( fabs(u0-f) < fabs(u0-l) ) ? f : l;
948 // move n12 to position of a successfull projection
949 double tol = BRep_Tool::Tolerance(edges[ iOkEdge ]);
950 if ( !force3d && distMiddleProj > 2*tol )
952 TopLoc_Location loc; double f,l;
953 Handle(Geom_Curve) curve = BRep_Tool::Curve( edges[iOkEdge],loc,f,l );
954 gp_Pnt p = curve->Value( u );
955 GetMeshDS()->MoveNode( n12, p.X(), p.Y(), p.Z() );
958 GetMeshDS()->SetNodeOnEdge(n12, edges[iOkEdge], u);
960 myTLinkNodeMap.insert( make_pair( SMESH_TLink(n1,n2), n12 ));
965 //=======================================================================
967 //purpose : Creates a node
968 //=======================================================================
970 SMDS_MeshNode* SMESH_MesherHelper::AddNode(double x, double y, double z, int ID)
972 SMESHDS_Mesh * meshDS = GetMeshDS();
973 SMDS_MeshNode* node = 0;
975 node = meshDS->AddNodeWithID( x, y, z, ID );
977 node = meshDS->AddNode( x, y, z );
978 if ( mySetElemOnShape && myShapeID > 0 ) {
979 switch ( myShape.ShapeType() ) {
980 case TopAbs_SOLID: meshDS->SetNodeInVolume( node, myShapeID); break;
981 case TopAbs_SHELL: meshDS->SetNodeInVolume( node, myShapeID); break;
982 case TopAbs_FACE: meshDS->SetNodeOnFace( node, myShapeID); break;
983 case TopAbs_EDGE: meshDS->SetNodeOnEdge( node, myShapeID); break;
984 case TopAbs_VERTEX: meshDS->SetNodeOnVertex( node, myShapeID); break;
991 //=======================================================================
993 //purpose : Creates quadratic or linear edge
994 //=======================================================================
996 SMDS_MeshEdge* SMESH_MesherHelper::AddEdge(const SMDS_MeshNode* n1,
997 const SMDS_MeshNode* n2,
1001 SMESHDS_Mesh * meshDS = GetMeshDS();
1003 SMDS_MeshEdge* edge = 0;
1004 if (myCreateQuadratic) {
1005 const SMDS_MeshNode* n12 = GetMediumNode(n1,n2,force3d);
1007 edge = meshDS->AddEdgeWithID(n1, n2, n12, id);
1009 edge = meshDS->AddEdge(n1, n2, n12);
1013 edge = meshDS->AddEdgeWithID(n1, n2, id);
1015 edge = meshDS->AddEdge(n1, n2);
1018 if ( mySetElemOnShape && myShapeID > 0 )
1019 meshDS->SetMeshElementOnShape( edge, myShapeID );
1024 //=======================================================================
1025 //function : AddFace
1026 //purpose : Creates quadratic or linear triangle
1027 //=======================================================================
1029 SMDS_MeshFace* SMESH_MesherHelper::AddFace(const SMDS_MeshNode* n1,
1030 const SMDS_MeshNode* n2,
1031 const SMDS_MeshNode* n3,
1035 SMESHDS_Mesh * meshDS = GetMeshDS();
1036 SMDS_MeshFace* elem = 0;
1038 if( n1==n2 || n2==n3 || n3==n1 )
1041 if(!myCreateQuadratic) {
1043 elem = meshDS->AddFaceWithID(n1, n2, n3, id);
1045 elem = meshDS->AddFace(n1, n2, n3);
1048 const SMDS_MeshNode* n12 = GetMediumNode(n1,n2,force3d);
1049 const SMDS_MeshNode* n23 = GetMediumNode(n2,n3,force3d);
1050 const SMDS_MeshNode* n31 = GetMediumNode(n3,n1,force3d);
1053 elem = meshDS->AddFaceWithID(n1, n2, n3, n12, n23, n31, id);
1055 elem = meshDS->AddFace(n1, n2, n3, n12, n23, n31);
1057 if ( mySetElemOnShape && myShapeID > 0 )
1058 meshDS->SetMeshElementOnShape( elem, myShapeID );
1063 //=======================================================================
1064 //function : AddFace
1065 //purpose : Creates quadratic or linear quadrangle
1066 //=======================================================================
1068 SMDS_MeshFace* SMESH_MesherHelper::AddFace(const SMDS_MeshNode* n1,
1069 const SMDS_MeshNode* n2,
1070 const SMDS_MeshNode* n3,
1071 const SMDS_MeshNode* n4,
1075 SMESHDS_Mesh * meshDS = GetMeshDS();
1076 SMDS_MeshFace* elem = 0;
1079 return AddFace(n1,n3,n4,id,force3d);
1082 return AddFace(n1,n2,n4,id,force3d);
1085 return AddFace(n1,n2,n3,id,force3d);
1088 return AddFace(n1,n2,n4,id,force3d);
1091 return AddFace(n1,n2,n3,id,force3d);
1094 return AddFace(n1,n2,n3,id,force3d);
1097 if(!myCreateQuadratic) {
1099 elem = meshDS->AddFaceWithID(n1, n2, n3, n4, id);
1101 elem = meshDS->AddFace(n1, n2, n3, n4);
1104 const SMDS_MeshNode* n12 = GetMediumNode(n1,n2,force3d);
1105 const SMDS_MeshNode* n23 = GetMediumNode(n2,n3,force3d);
1106 const SMDS_MeshNode* n34 = GetMediumNode(n3,n4,force3d);
1107 const SMDS_MeshNode* n41 = GetMediumNode(n4,n1,force3d);
1110 elem = meshDS->AddFaceWithID(n1, n2, n3, n4, n12, n23, n34, n41, id);
1112 elem = meshDS->AddFace(n1, n2, n3, n4, n12, n23, n34, n41);
1114 if ( mySetElemOnShape && myShapeID > 0 )
1115 meshDS->SetMeshElementOnShape( elem, myShapeID );
1120 //=======================================================================
1121 //function : AddPolygonalFace
1122 //purpose : Creates polygon, with additional nodes in quadratic mesh
1123 //=======================================================================
1125 SMDS_MeshFace* SMESH_MesherHelper::AddPolygonalFace (const vector<const SMDS_MeshNode*>& nodes,
1129 SMESHDS_Mesh * meshDS = GetMeshDS();
1130 SMDS_MeshFace* elem = 0;
1132 if(!myCreateQuadratic) {
1134 elem = meshDS->AddPolygonalFaceWithID(nodes, id);
1136 elem = meshDS->AddPolygonalFace(nodes);
1139 vector<const SMDS_MeshNode*> newNodes;
1140 for ( int i = 0; i < nodes.size(); ++i )
1142 const SMDS_MeshNode* n1 = nodes[i];
1143 const SMDS_MeshNode* n2 = nodes[(i+1)/nodes.size()];
1144 const SMDS_MeshNode* n12 = GetMediumNode(n1,n2,force3d);
1145 newNodes.push_back( n1 );
1146 newNodes.push_back( n12 );
1149 elem = meshDS->AddPolygonalFaceWithID(newNodes, id);
1151 elem = meshDS->AddPolygonalFace(newNodes);
1153 if ( mySetElemOnShape && myShapeID > 0 )
1154 meshDS->SetMeshElementOnShape( elem, myShapeID );
1159 //=======================================================================
1160 //function : AddVolume
1161 //purpose : Creates quadratic or linear prism
1162 //=======================================================================
1164 SMDS_MeshVolume* SMESH_MesherHelper::AddVolume(const SMDS_MeshNode* n1,
1165 const SMDS_MeshNode* n2,
1166 const SMDS_MeshNode* n3,
1167 const SMDS_MeshNode* n4,
1168 const SMDS_MeshNode* n5,
1169 const SMDS_MeshNode* n6,
1173 SMESHDS_Mesh * meshDS = GetMeshDS();
1174 SMDS_MeshVolume* elem = 0;
1175 if(!myCreateQuadratic) {
1177 elem = meshDS->AddVolumeWithID(n1, n2, n3, n4, n5, n6, id);
1179 elem = meshDS->AddVolume(n1, n2, n3, n4, n5, n6);
1182 const SMDS_MeshNode* n12 = GetMediumNode(n1,n2,force3d);
1183 const SMDS_MeshNode* n23 = GetMediumNode(n2,n3,force3d);
1184 const SMDS_MeshNode* n31 = GetMediumNode(n3,n1,force3d);
1186 const SMDS_MeshNode* n45 = GetMediumNode(n4,n5,force3d);
1187 const SMDS_MeshNode* n56 = GetMediumNode(n5,n6,force3d);
1188 const SMDS_MeshNode* n64 = GetMediumNode(n6,n4,force3d);
1190 const SMDS_MeshNode* n14 = GetMediumNode(n1,n4,force3d);
1191 const SMDS_MeshNode* n25 = GetMediumNode(n2,n5,force3d);
1192 const SMDS_MeshNode* n36 = GetMediumNode(n3,n6,force3d);
1195 elem = meshDS->AddVolumeWithID(n1, n2, n3, n4, n5, n6,
1196 n12, n23, n31, n45, n56, n64, n14, n25, n36, id);
1198 elem = meshDS->AddVolume(n1, n2, n3, n4, n5, n6,
1199 n12, n23, n31, n45, n56, n64, n14, n25, n36);
1201 if ( mySetElemOnShape && myShapeID > 0 )
1202 meshDS->SetMeshElementOnShape( elem, myShapeID );
1207 //=======================================================================
1208 //function : AddVolume
1209 //purpose : Creates quadratic or linear tetrahedron
1210 //=======================================================================
1212 SMDS_MeshVolume* SMESH_MesherHelper::AddVolume(const SMDS_MeshNode* n1,
1213 const SMDS_MeshNode* n2,
1214 const SMDS_MeshNode* n3,
1215 const SMDS_MeshNode* n4,
1219 SMESHDS_Mesh * meshDS = GetMeshDS();
1220 SMDS_MeshVolume* elem = 0;
1221 if(!myCreateQuadratic) {
1223 elem = meshDS->AddVolumeWithID(n1, n2, n3, n4, id);
1225 elem = meshDS->AddVolume(n1, n2, n3, n4);
1228 const SMDS_MeshNode* n12 = GetMediumNode(n1,n2,force3d);
1229 const SMDS_MeshNode* n23 = GetMediumNode(n2,n3,force3d);
1230 const SMDS_MeshNode* n31 = GetMediumNode(n3,n1,force3d);
1232 const SMDS_MeshNode* n14 = GetMediumNode(n1,n4,force3d);
1233 const SMDS_MeshNode* n24 = GetMediumNode(n2,n4,force3d);
1234 const SMDS_MeshNode* n34 = GetMediumNode(n3,n4,force3d);
1237 elem = meshDS->AddVolumeWithID(n1, n2, n3, n4, n12, n23, n31, n14, n24, n34, id);
1239 elem = meshDS->AddVolume(n1, n2, n3, n4, n12, n23, n31, n14, n24, n34);
1241 if ( mySetElemOnShape && myShapeID > 0 )
1242 meshDS->SetMeshElementOnShape( elem, myShapeID );
1247 //=======================================================================
1248 //function : AddVolume
1249 //purpose : Creates quadratic or linear pyramid
1250 //=======================================================================
1252 SMDS_MeshVolume* SMESH_MesherHelper::AddVolume(const SMDS_MeshNode* n1,
1253 const SMDS_MeshNode* n2,
1254 const SMDS_MeshNode* n3,
1255 const SMDS_MeshNode* n4,
1256 const SMDS_MeshNode* n5,
1260 SMDS_MeshVolume* elem = 0;
1261 if(!myCreateQuadratic) {
1263 elem = GetMeshDS()->AddVolumeWithID(n1, n2, n3, n4, n5, id);
1265 elem = GetMeshDS()->AddVolume(n1, n2, n3, n4, n5);
1268 const SMDS_MeshNode* n12 = GetMediumNode(n1,n2,force3d);
1269 const SMDS_MeshNode* n23 = GetMediumNode(n2,n3,force3d);
1270 const SMDS_MeshNode* n34 = GetMediumNode(n3,n4,force3d);
1271 const SMDS_MeshNode* n41 = GetMediumNode(n4,n1,force3d);
1273 const SMDS_MeshNode* n15 = GetMediumNode(n1,n5,force3d);
1274 const SMDS_MeshNode* n25 = GetMediumNode(n2,n5,force3d);
1275 const SMDS_MeshNode* n35 = GetMediumNode(n3,n5,force3d);
1276 const SMDS_MeshNode* n45 = GetMediumNode(n4,n5,force3d);
1279 elem = GetMeshDS()->AddVolumeWithID ( n1, n2, n3, n4, n5,
1284 elem = GetMeshDS()->AddVolume( n1, n2, n3, n4, n5,
1286 n15, n25, n35, n45);
1288 if ( mySetElemOnShape && myShapeID > 0 )
1289 GetMeshDS()->SetMeshElementOnShape( elem, myShapeID );
1294 //=======================================================================
1295 //function : AddVolume
1296 //purpose : Creates quadratic or linear hexahedron
1297 //=======================================================================
1299 SMDS_MeshVolume* SMESH_MesherHelper::AddVolume(const SMDS_MeshNode* n1,
1300 const SMDS_MeshNode* n2,
1301 const SMDS_MeshNode* n3,
1302 const SMDS_MeshNode* n4,
1303 const SMDS_MeshNode* n5,
1304 const SMDS_MeshNode* n6,
1305 const SMDS_MeshNode* n7,
1306 const SMDS_MeshNode* n8,
1310 SMESHDS_Mesh * meshDS = GetMeshDS();
1311 SMDS_MeshVolume* elem = 0;
1312 if(!myCreateQuadratic) {
1314 elem = meshDS->AddVolumeWithID(n1, n2, n3, n4, n5, n6, n7, n8, id);
1316 elem = meshDS->AddVolume(n1, n2, n3, n4, n5, n6, n7, n8);
1319 const SMDS_MeshNode* n12 = GetMediumNode(n1,n2,force3d);
1320 const SMDS_MeshNode* n23 = GetMediumNode(n2,n3,force3d);
1321 const SMDS_MeshNode* n34 = GetMediumNode(n3,n4,force3d);
1322 const SMDS_MeshNode* n41 = GetMediumNode(n4,n1,force3d);
1324 const SMDS_MeshNode* n56 = GetMediumNode(n5,n6,force3d);
1325 const SMDS_MeshNode* n67 = GetMediumNode(n6,n7,force3d);
1326 const SMDS_MeshNode* n78 = GetMediumNode(n7,n8,force3d);
1327 const SMDS_MeshNode* n85 = GetMediumNode(n8,n5,force3d);
1329 const SMDS_MeshNode* n15 = GetMediumNode(n1,n5,force3d);
1330 const SMDS_MeshNode* n26 = GetMediumNode(n2,n6,force3d);
1331 const SMDS_MeshNode* n37 = GetMediumNode(n3,n7,force3d);
1332 const SMDS_MeshNode* n48 = GetMediumNode(n4,n8,force3d);
1335 elem = meshDS->AddVolumeWithID(n1, n2, n3, n4, n5, n6, n7, n8,
1336 n12, n23, n34, n41, n56, n67,
1337 n78, n85, n15, n26, n37, n48, id);
1339 elem = meshDS->AddVolume(n1, n2, n3, n4, n5, n6, n7, n8,
1340 n12, n23, n34, n41, n56, n67,
1341 n78, n85, n15, n26, n37, n48);
1343 if ( mySetElemOnShape && myShapeID > 0 )
1344 meshDS->SetMeshElementOnShape( elem, myShapeID );
1349 //=======================================================================
1350 //function : AddPolyhedralVolume
1351 //purpose : Creates polyhedron. In quadratic mesh, adds medium nodes
1352 //=======================================================================
1355 SMESH_MesherHelper::AddPolyhedralVolume (const std::vector<const SMDS_MeshNode*>& nodes,
1356 const std::vector<int>& quantities,
1360 SMESHDS_Mesh * meshDS = GetMeshDS();
1361 SMDS_MeshVolume* elem = 0;
1362 if(!myCreateQuadratic)
1365 elem = meshDS->AddPolyhedralVolumeWithID(nodes, quantities, id);
1367 elem = meshDS->AddPolyhedralVolume(nodes, quantities);
1371 vector<const SMDS_MeshNode*> newNodes;
1372 vector<int> newQuantities;
1373 for ( int iFace=0, iN=0; iFace < quantities.size(); ++iFace)
1375 int nbNodesInFace = quantities[iFace];
1376 newQuantities.push_back(0);
1377 for ( int i = 0; i < nbNodesInFace; ++i )
1379 const SMDS_MeshNode* n1 = nodes[ iN + i ];
1380 newNodes.push_back( n1 );
1381 newQuantities.back()++;
1383 const SMDS_MeshNode* n2 = nodes[ iN + ( i+1==nbNodesInFace ? 0 : i+1 )];
1384 // if ( n1->GetPosition()->GetTypeOfPosition() != SMDS_TOP_3DSPACE &&
1385 // n2->GetPosition()->GetTypeOfPosition() != SMDS_TOP_3DSPACE )
1387 const SMDS_MeshNode* n12 = GetMediumNode(n1,n2,force3d);
1388 newNodes.push_back( n12 );
1389 newQuantities.back()++;
1392 iN += nbNodesInFace;
1395 elem = meshDS->AddPolyhedralVolumeWithID( newNodes, newQuantities, id );
1397 elem = meshDS->AddPolyhedralVolume( newNodes, newQuantities );
1399 if ( mySetElemOnShape && myShapeID > 0 )
1400 meshDS->SetMeshElementOnShape( elem, myShapeID );
1405 //=======================================================================
1406 //function : LoadNodeColumns
1407 //purpose : Load nodes bound to face into a map of node columns
1408 //=======================================================================
1410 bool SMESH_MesherHelper::LoadNodeColumns(TParam2ColumnMap & theParam2ColumnMap,
1411 const TopoDS_Face& theFace,
1412 const TopoDS_Edge& theBaseEdge,
1413 SMESHDS_Mesh* theMesh)
1415 SMESHDS_SubMesh* faceSubMesh = theMesh->MeshElements( theFace );
1416 if ( !faceSubMesh || faceSubMesh->NbElements() == 0 )
1419 // get nodes on theBaseEdge sorted by param on edge and initialize theParam2ColumnMap with them
1421 map< double, const SMDS_MeshNode*> sortedBaseNodes;
1422 if ( !SMESH_Algo::GetSortedNodesOnEdge( theMesh, theBaseEdge,/*noMedium=*/true, sortedBaseNodes)
1423 || sortedBaseNodes.size() < 2 )
1426 int nbRows = faceSubMesh->NbElements() / ( sortedBaseNodes.size()-1 ) + 1;
1427 map< double, const SMDS_MeshNode*>::iterator u_n = sortedBaseNodes.begin();
1428 double f = u_n->first, range = sortedBaseNodes.rbegin()->first - f;
1429 for ( ; u_n != sortedBaseNodes.end(); u_n++ )
1431 double par = ( u_n->first - f ) / range;
1432 vector<const SMDS_MeshNode*>& nCol = theParam2ColumnMap[ par ];
1433 nCol.resize( nbRows );
1434 nCol[0] = u_n->second;
1437 // fill theParam2ColumnMap column by column by passing from nodes on
1438 // theBaseEdge up via mesh faces on theFace
1440 TParam2ColumnMap::iterator par_nVec_2 = theParam2ColumnMap.begin();
1441 TParam2ColumnMap::iterator par_nVec_1 = par_nVec_2++;
1442 TIDSortedElemSet emptySet, avoidSet;
1443 for ( ; par_nVec_2 != theParam2ColumnMap.end(); ++par_nVec_1, ++par_nVec_2 )
1445 vector<const SMDS_MeshNode*>& nCol1 = par_nVec_1->second;
1446 vector<const SMDS_MeshNode*>& nCol2 = par_nVec_2->second;
1448 int i1, i2, iRow = 0;
1449 const SMDS_MeshNode *n1 = nCol1[0], *n2 = nCol2[0];
1450 // find face sharing node n1 and n2 and belonging to faceSubMesh
1451 while ( const SMDS_MeshElement* face =
1452 SMESH_MeshEditor::FindFaceInSet( n1, n2, emptySet, avoidSet, &i1, &i2))
1454 if ( faceSubMesh->Contains( face ))
1456 int nbNodes = face->IsQuadratic() ? face->NbNodes()/2 : face->NbNodes();
1459 n1 = face->GetNode( (i2+2) % 4 ); // opposite corner of quadrangle face
1460 n2 = face->GetNode( (i1+2) % 4 );
1461 if ( ++iRow >= nbRows )
1467 avoidSet.insert( face );
1469 if ( iRow + 1 < nbRows ) // compact if necessary
1470 nCol1.resize( iRow + 1 ), nCol2.resize( iRow + 1 );
1475 //=======================================================================
1476 //function : NbAncestors
1477 //purpose : Return number of unique ancestors of the shape
1478 //=======================================================================
1480 int SMESH_MesherHelper::NbAncestors(const TopoDS_Shape& shape,
1481 const SMESH_Mesh& mesh,
1482 TopAbs_ShapeEnum ancestorType/*=TopAbs_SHAPE*/)
1484 TopTools_MapOfShape ancestors;
1485 TopTools_ListIteratorOfListOfShape ansIt( mesh.GetAncestors(shape) );
1486 for ( ; ansIt.More(); ansIt.Next() ) {
1487 if ( ancestorType == TopAbs_SHAPE || ansIt.Value().ShapeType() == ancestorType )
1488 ancestors.Add( ansIt.Value() );
1490 return ancestors.Extent();
1493 //=======================================================================
1494 //function : GetSubShapeOri
1495 //purpose : Return orientation of sub-shape in the main shape
1496 //=======================================================================
1498 TopAbs_Orientation SMESH_MesherHelper::GetSubShapeOri(const TopoDS_Shape& shape,
1499 const TopoDS_Shape& subShape)
1501 TopAbs_Orientation ori = TopAbs_Orientation(-1);
1502 if ( !shape.IsNull() && !subShape.IsNull() )
1504 TopExp_Explorer e( shape, subShape.ShapeType() );
1505 if ( shape.Orientation() >= TopAbs_INTERNAL ) // TopAbs_INTERNAL or TopAbs_EXTERNAL
1506 e.Init( shape.Oriented(TopAbs_FORWARD), subShape.ShapeType() );
1507 for ( ; e.More(); e.Next())
1508 if ( subShape.IsSame( e.Current() ))
1511 ori = e.Current().Orientation();
1516 //=======================================================================
1517 //function : IsSubShape
1519 //=======================================================================
1521 bool SMESH_MesherHelper::IsSubShape( const TopoDS_Shape& shape,
1522 const TopoDS_Shape& mainShape )
1524 if ( !shape.IsNull() && !mainShape.IsNull() )
1526 for ( TopExp_Explorer exp( mainShape, shape.ShapeType());
1529 if ( shape.IsSame( exp.Current() ))
1532 SCRUTE((shape.IsNull()));
1533 SCRUTE((mainShape.IsNull()));
1537 //=======================================================================
1538 //function : IsSubShape
1540 //=======================================================================
1542 bool SMESH_MesherHelper::IsSubShape( const TopoDS_Shape& shape, SMESH_Mesh* aMesh )
1544 if ( shape.IsNull() || !aMesh )
1547 aMesh->GetMeshDS()->ShapeToIndex( shape ) ||
1549 shape.ShapeType() == TopAbs_COMPOUND && aMesh->GetMeshDS()->IsGroupOfSubShapes( shape );
1552 //================================================================================
1554 * \brief Return maximal tolerance of shape
1556 //================================================================================
1558 double SMESH_MesherHelper::MaxTolerance( const TopoDS_Shape& shape )
1560 double tol = Precision::Confusion();
1561 TopExp_Explorer exp;
1562 for ( exp.Init( shape, TopAbs_FACE ); exp.More(); exp.Next() )
1563 tol = Max( tol, BRep_Tool::Tolerance( TopoDS::Face( exp.Current())));
1564 for ( exp.Init( shape, TopAbs_EDGE ); exp.More(); exp.Next() )
1565 tol = Max( tol, BRep_Tool::Tolerance( TopoDS::Edge( exp.Current())));
1566 for ( exp.Init( shape, TopAbs_VERTEX ); exp.More(); exp.Next() )
1567 tol = Max( tol, BRep_Tool::Tolerance( TopoDS::Vertex( exp.Current())));
1572 //=======================================================================
1573 //function : IsQuadraticMesh
1574 //purpose : Check mesh without geometry for: if all elements on this shape are quadratic,
1575 // quadratic elements will be created.
1576 // Used then generated 3D mesh without geometry.
1577 //=======================================================================
1579 SMESH_MesherHelper:: MType SMESH_MesherHelper::IsQuadraticMesh()
1581 int NbAllEdgsAndFaces=0;
1582 int NbQuadFacesAndEdgs=0;
1583 int NbFacesAndEdges=0;
1584 //All faces and edges
1585 NbAllEdgsAndFaces = myMesh->NbEdges() + myMesh->NbFaces();
1587 //Quadratic faces and edges
1588 NbQuadFacesAndEdgs = myMesh->NbEdges(ORDER_QUADRATIC) + myMesh->NbFaces(ORDER_QUADRATIC);
1590 //Linear faces and edges
1591 NbFacesAndEdges = myMesh->NbEdges(ORDER_LINEAR) + myMesh->NbFaces(ORDER_LINEAR);
1593 if (NbAllEdgsAndFaces == NbQuadFacesAndEdgs) {
1595 return SMESH_MesherHelper::QUADRATIC;
1597 else if (NbAllEdgsAndFaces == NbFacesAndEdges) {
1599 return SMESH_MesherHelper::LINEAR;
1602 //Mesh with both type of elements
1603 return SMESH_MesherHelper::COMP;
1606 //=======================================================================
1607 //function : GetOtherParam
1608 //purpose : Return an alternative parameter for a node on seam
1609 //=======================================================================
1611 double SMESH_MesherHelper::GetOtherParam(const double param) const
1613 int i = myParIndex & U_periodic ? 0 : 1;
1614 return fabs(param-myPar1[i]) < fabs(param-myPar2[i]) ? myPar2[i] : myPar1[i];
1617 //#include <Perf_Meter.hxx>
1619 //=======================================================================
1620 namespace { // Structures used by FixQuadraticElements()
1621 //=======================================================================
1623 #define __DMP__(txt) \
1625 #define MSG(txt) __DMP__(txt<<endl)
1626 #define MSGBEG(txt) __DMP__(txt)
1628 //const double straightTol2 = 1e-33; // to detect straing links
1629 bool isStraightLink(double linkLen2, double middleNodeMove2)
1631 // straight if <node move> < 1/15 * <link length>
1632 return middleNodeMove2 < 1/15./15. * linkLen2;
1636 // ---------------------------------------
1638 * \brief Quadratic link knowing its faces
1640 struct QLink: public SMESH_TLink
1642 const SMDS_MeshNode* _mediumNode;
1643 mutable vector<const QFace* > _faces;
1644 mutable gp_Vec _nodeMove;
1645 mutable int _nbMoves;
1647 QLink(const SMDS_MeshNode* n1, const SMDS_MeshNode* n2, const SMDS_MeshNode* nm):
1648 SMESH_TLink( n1,n2 ), _mediumNode(nm), _nodeMove(0,0,0), _nbMoves(0) {
1650 //if ( MediumPos() != SMDS_TOP_3DSPACE )
1651 _nodeMove = MediumPnt() - MiddlePnt();
1653 void SetContinuesFaces() const;
1654 const QFace* GetContinuesFace( const QFace* face ) const;
1655 bool OnBoundary() const;
1656 gp_XYZ MiddlePnt() const { return ( XYZ( node1() ) + XYZ( node2() )) / 2.; }
1657 gp_XYZ MediumPnt() const { return XYZ( _mediumNode ); }
1659 SMDS_TypeOfPosition MediumPos() const
1660 { return _mediumNode->GetPosition()->GetTypeOfPosition(); }
1661 SMDS_TypeOfPosition EndPos(bool isSecond) const
1662 { return (isSecond ? node2() : node1())->GetPosition()->GetTypeOfPosition(); }
1663 const SMDS_MeshNode* EndPosNode(SMDS_TypeOfPosition pos) const
1664 { return EndPos(0) == pos ? node1() : EndPos(1) == pos ? node2() : 0; }
1666 void Move(const gp_Vec& move, bool sum=false) const
1667 { _nodeMove += move; _nbMoves += sum ? (_nbMoves==0) : 1; }
1668 gp_XYZ Move() const { return _nodeMove.XYZ() / _nbMoves; }
1669 bool IsMoved() const { return (_nbMoves > 0 && !IsStraight()); }
1670 bool IsStraight() const
1671 { return isStraightLink( (XYZ(node1())-XYZ(node2())).SquareModulus(),
1672 _nodeMove.SquareMagnitude());
1674 bool operator<(const QLink& other) const {
1675 return (node1()->GetID() == other.node1()->GetID() ?
1676 node2()->GetID() < other.node2()->GetID() :
1677 node1()->GetID() < other.node1()->GetID());
1679 struct PtrComparator {
1680 bool operator() (const QLink* l1, const QLink* l2 ) const { return *l1 < *l2; }
1683 // ---------------------------------------------------------
1685 * \brief Link in the chain of links; it connects two faces
1689 const QLink* _qlink;
1690 mutable const QFace* _qfaces[2];
1692 TChainLink(const QLink* qlink=0):_qlink(qlink) {
1693 _qfaces[0] = _qfaces[1] = 0;
1695 void SetFace(const QFace* face) const { int iF = _qfaces[0] ? 1 : 0; _qfaces[iF]=face; }
1697 bool IsBoundary() const { return !_qfaces[1]; }
1699 void RemoveFace( const QFace* face ) const
1700 { _qfaces[(face == _qfaces[1])] = 0; if (!_qfaces[0]) std::swap(_qfaces[0],_qfaces[1]); }
1702 const QFace* NextFace( const QFace* f ) const
1703 { return _qfaces[0]==f ? _qfaces[1] : _qfaces[0]; }
1705 const SMDS_MeshNode* NextNode( const SMDS_MeshNode* n ) const
1706 { return n == _qlink->node1() ? _qlink->node2() : _qlink->node1(); }
1708 bool operator<(const TChainLink& other) const { return *_qlink < *other._qlink; }
1710 operator bool() const { return (_qlink); }
1712 const QLink* operator->() const { return _qlink; }
1714 gp_Vec Normal() const;
1716 // --------------------------------------------------------------------
1717 typedef list< TChainLink > TChain;
1718 typedef set < TChainLink > TLinkSet;
1719 typedef TLinkSet::const_iterator TLinkInSet;
1721 const int theFirstStep = 5;
1723 enum { ERR_OK, ERR_TRI, ERR_PRISM, ERR_UNKNOWN }; // errors of QFace::GetLinkChain()
1724 // --------------------------------------------------------------------
1726 * \brief Face shared by two volumes and bound by QLinks
1728 struct QFace: public TIDSortedElemSet
1730 mutable const SMDS_MeshElement* _volumes[2];
1731 mutable vector< const QLink* > _sides;
1732 mutable bool _sideIsAdded[4]; // added in chain of links
1735 mutable const SMDS_MeshElement* _face;
1738 QFace( const vector< const QLink*>& links, const SMDS_MeshElement* face=0 );
1740 void SetVolume(const SMDS_MeshElement* v) const { _volumes[ _volumes[0] ? 1 : 0 ] = v; }
1742 int NbVolumes() const { return !_volumes[0] ? 0 : !_volumes[1] ? 1 : 2; }
1744 void AddSelfToLinks() const {
1745 for ( int i = 0; i < _sides.size(); ++i )
1746 _sides[i]->_faces.push_back( this );
1748 int LinkIndex( const QLink* side ) const {
1749 for (int i=0; i<_sides.size(); ++i ) if ( _sides[i] == side ) return i;
1752 bool GetLinkChain( int iSide, TChain& chain, SMDS_TypeOfPosition pos, int& err) const;
1754 bool GetLinkChain( TChainLink& link, TChain& chain, SMDS_TypeOfPosition pos, int& err) const
1756 int i = LinkIndex( link._qlink );
1757 if ( i < 0 ) return true;
1758 _sideIsAdded[i] = true;
1759 link.SetFace( this );
1760 // continue from opposite link
1761 return GetLinkChain( (i+2)%_sides.size(), chain, pos, err );
1763 bool IsBoundary() const { return !_volumes[1]; }
1765 bool Contains( const SMDS_MeshNode* node ) const { return count(node); }
1767 TLinkInSet GetBoundaryLink( const TLinkSet& links,
1768 const TChainLink& avoidLink,
1769 TLinkInSet * notBoundaryLink = 0,
1770 const SMDS_MeshNode* nodeToContain = 0,
1771 bool * isAdjacentUsed = 0,
1772 int nbRecursionsLeft = -1) const;
1774 TLinkInSet GetLinkByNode( const TLinkSet& links,
1775 const TChainLink& avoidLink,
1776 const SMDS_MeshNode* nodeToContain) const;
1778 const SMDS_MeshNode* GetNodeInFace() const {
1779 for ( int iL = 0; iL < _sides.size(); ++iL )
1780 if ( _sides[iL]->MediumPos() == SMDS_TOP_FACE ) return _sides[iL]->_mediumNode;
1784 gp_Vec LinkNorm(const int i, SMESH_MesherHelper* theFaceHelper=0) const;
1786 double MoveByBoundary( const TChainLink& theLink,
1787 const gp_Vec& theRefVec,
1788 const TLinkSet& theLinks,
1789 SMESH_MesherHelper* theFaceHelper=0,
1790 const double thePrevLen=0,
1791 const int theStep=theFirstStep,
1792 gp_Vec* theLinkNorm=0,
1793 double theSign=1.0) const;
1796 //================================================================================
1798 * \brief Dump QLink and QFace
1800 ostream& operator << (ostream& out, const QLink& l)
1802 out <<"QLink nodes: "
1803 << l.node1()->GetID() << " - "
1804 << l._mediumNode->GetID() << " - "
1805 << l.node2()->GetID() << endl;
1808 ostream& operator << (ostream& out, const QFace& f)
1810 out <<"QFace nodes: "/*<< &f << " "*/;
1811 for ( TIDSortedElemSet::const_iterator n = f.begin(); n != f.end(); ++n )
1812 out << (*n)->GetID() << " ";
1813 out << " \tvolumes: "
1814 << (f._volumes[0] ? f._volumes[0]->GetID() : 0) << " "
1815 << (f._volumes[1] ? f._volumes[1]->GetID() : 0);
1816 out << " \tNormal: "<< f._normal.X() <<", "<<f._normal.Y() <<", "<<f._normal.Z() << endl;
1820 //================================================================================
1822 * \brief Construct QFace from QLinks
1824 //================================================================================
1826 QFace::QFace( const vector< const QLink*>& links, const SMDS_MeshElement* face )
1828 _volumes[0] = _volumes[1] = 0;
1830 _sideIsAdded[0]=_sideIsAdded[1]=_sideIsAdded[2]=_sideIsAdded[3]=false;
1831 _normal.SetCoord(0,0,0);
1832 for ( int i = 1; i < _sides.size(); ++i ) {
1833 const QLink *l1 = _sides[i-1], *l2 = _sides[i];
1834 insert( l1->node1() ); insert( l1->node2() );
1836 gp_Vec v1( XYZ( l1->node2()), XYZ( l1->node1()));
1837 gp_Vec v2( XYZ( l2->node1()), XYZ( l2->node2()));
1838 if ( l1->node1() != l2->node1() && l1->node2() != l2->node2() )
1842 double normSqSize = _normal.SquareMagnitude();
1843 if ( normSqSize > numeric_limits<double>::min() )
1844 _normal /= sqrt( normSqSize );
1846 _normal.SetCoord(1e-33,0,0);
1852 //================================================================================
1854 * \brief Make up a chain of links
1855 * \param iSide - link to add first
1856 * \param chain - chain to fill in
1857 * \param pos - postion of medium nodes the links should have
1858 * \param error - out, specifies what is wrong
1859 * \retval bool - false if valid chain can't be built; "valid" means that links
1860 * of the chain belongs to rectangles bounding hexahedrons
1862 //================================================================================
1864 bool QFace::GetLinkChain( int iSide, TChain& chain, SMDS_TypeOfPosition pos, int& error) const
1866 if ( iSide >= _sides.size() ) // wrong argument iSide
1868 if ( _sideIsAdded[ iSide ]) // already in chain
1871 if ( _sides.size() != 4 ) { // triangle - visit all my continous faces
1874 list< const QFace* > faces( 1, this );
1875 while ( !faces.empty() ) {
1876 const QFace* face = faces.front();
1877 for ( int i = 0; i < face->_sides.size(); ++i ) {
1878 if ( !face->_sideIsAdded[i] && face->_sides[i] ) {
1879 face->_sideIsAdded[i] = true;
1880 // find a face side in the chain
1881 TLinkInSet chLink = links.insert( TChainLink(face->_sides[i])).first;
1882 // TChain::iterator chLink = chain.begin();
1883 // for ( ; chLink != chain.end(); ++chLink )
1884 // if ( chLink->_qlink == face->_sides[i] )
1886 // if ( chLink == chain.end() )
1887 // chLink = chain.insert( chain.begin(), TChainLink(face->_sides[i]));
1888 // add a face to a chained link and put a continues face in the queue
1889 chLink->SetFace( face );
1890 if ( face->_sides[i]->MediumPos() >= pos )
1891 if ( const QFace* contFace = face->_sides[i]->GetContinuesFace( face ))
1892 faces.push_back( contFace );
1897 if ( error < ERR_TRI )
1899 chain.insert( chain.end(), links.begin(),links.end() );
1902 _sideIsAdded[iSide] = true; // not to add this link to chain again
1903 const QLink* link = _sides[iSide];
1907 // add link into chain
1908 TChain::iterator chLink = chain.insert( chain.begin(), TChainLink(link));
1909 chLink->SetFace( this );
1912 // propagate from quadrangle to neighbour faces
1913 if ( link->MediumPos() >= pos ) {
1914 int nbLinkFaces = link->_faces.size();
1915 if ( nbLinkFaces == 4 || nbLinkFaces < 4 && link->OnBoundary()) {
1916 // hexahedral mesh or boundary quadrangles - goto a continous face
1917 if ( const QFace* f = link->GetContinuesFace( this ))
1918 return f->GetLinkChain( *chLink, chain, pos, error );
1921 TChainLink chLink(link); // side face of prismatic mesh - visit all faces of iSide
1922 for ( int i = 0; i < nbLinkFaces; ++i )
1923 if ( link->_faces[i] )
1924 link->_faces[i]->GetLinkChain( chLink, chain, pos, error );
1925 if ( error < ERR_PRISM )
1933 //================================================================================
1935 * \brief Return a boundary link of the triangle face
1936 * \param links - set of all links
1937 * \param avoidLink - link not to return
1938 * \param notBoundaryLink - out, neither the returned link nor avoidLink
1939 * \param nodeToContain - node the returned link must contain; if provided, search
1940 * also performed on adjacent faces
1941 * \param isAdjacentUsed - returns true if link is found in adjacent faces
1942 * \param nbRecursionsLeft - to limit recursion
1944 //================================================================================
1946 TLinkInSet QFace::GetBoundaryLink( const TLinkSet& links,
1947 const TChainLink& avoidLink,
1948 TLinkInSet * notBoundaryLink,
1949 const SMDS_MeshNode* nodeToContain,
1950 bool * isAdjacentUsed,
1951 int nbRecursionsLeft) const
1953 TLinkInSet linksEnd = links.end(), boundaryLink = linksEnd;
1955 typedef list< pair< const QFace*, TLinkInSet > > TFaceLinkList;
1956 TFaceLinkList adjacentFaces;
1958 for ( int iL = 0; iL < _sides.size(); ++iL )
1960 if ( avoidLink._qlink == _sides[iL] )
1962 TLinkInSet link = links.find( _sides[iL] );
1963 if ( link == linksEnd ) continue;
1964 if ( (*link)->MediumPos() > SMDS_TOP_FACE )
1965 continue; // We work on faces here, don't go inside a solid
1968 if ( link->IsBoundary() ) {
1969 if ( !nodeToContain ||
1970 (*link)->node1() == nodeToContain ||
1971 (*link)->node2() == nodeToContain )
1973 boundaryLink = link;
1974 if ( !notBoundaryLink ) break;
1977 else if ( notBoundaryLink ) {
1978 *notBoundaryLink = link;
1979 if ( boundaryLink != linksEnd ) break;
1982 if ( boundaryLink == linksEnd && nodeToContain ) // collect adjacent faces
1983 if ( const QFace* adj = link->NextFace( this ))
1984 if ( adj->Contains( nodeToContain ))
1985 adjacentFaces.push_back( make_pair( adj, link ));
1988 if ( isAdjacentUsed ) *isAdjacentUsed = false;
1989 if ( boundaryLink == linksEnd && nodeToContain && nbRecursionsLeft) // check adjacent faces
1991 if ( nbRecursionsLeft < 0 )
1992 nbRecursionsLeft = nodeToContain->NbInverseElements();
1993 TFaceLinkList::iterator adj = adjacentFaces.begin();
1994 for ( ; boundaryLink == linksEnd && adj != adjacentFaces.end(); ++adj )
1995 boundaryLink = adj->first->GetBoundaryLink( links, *(adj->second), 0, nodeToContain,
1996 isAdjacentUsed, nbRecursionsLeft-1);
1997 if ( isAdjacentUsed ) *isAdjacentUsed = true;
1999 return boundaryLink;
2001 //================================================================================
2003 * \brief Return a link ending at the given node but not avoidLink
2005 //================================================================================
2007 TLinkInSet QFace::GetLinkByNode( const TLinkSet& links,
2008 const TChainLink& avoidLink,
2009 const SMDS_MeshNode* nodeToContain) const
2011 for ( int i = 0; i < _sides.size(); ++i )
2012 if ( avoidLink._qlink != _sides[i] &&
2013 (_sides[i]->node1() == nodeToContain || _sides[i]->node2() == nodeToContain ))
2014 return links.find( _sides[ i ]);
2018 //================================================================================
2020 * \brief Return normal to the i-th side pointing outside the face
2022 //================================================================================
2024 gp_Vec QFace::LinkNorm(const int i, SMESH_MesherHelper* /*uvHelper*/) const
2026 gp_Vec norm, vecOut;
2027 // if ( uvHelper ) {
2028 // TopoDS_Face face = TopoDS::Face( uvHelper->GetSubShape());
2029 // const SMDS_MeshNode* inFaceNode = uvHelper->GetNodeUVneedInFaceNode() ? GetNodeInFace() : 0;
2030 // gp_XY uv1 = uvHelper->GetNodeUV( face, _sides[i]->node1(), inFaceNode );
2031 // gp_XY uv2 = uvHelper->GetNodeUV( face, _sides[i]->node2(), inFaceNode );
2032 // norm.SetCoord( uv1.Y() - uv2.Y(), uv2.X() - uv1.X(), 0 );
2034 // const QLink* otherLink = _sides[(i + 1) % _sides.size()];
2035 // const SMDS_MeshNode* otherNode =
2036 // otherLink->node1() == _sides[i]->node1() ? otherLink->node2() : otherLink->node1();
2037 // gp_XY pIn = uvHelper->GetNodeUV( face, otherNode, inFaceNode );
2038 // vecOut.SetCoord( uv1.X() - pIn.X(), uv1.Y() - pIn.Y(), 0 );
2041 norm = _normal ^ gp_Vec( XYZ(_sides[i]->node1()), XYZ(_sides[i]->node2()));
2042 gp_XYZ pIn = ( XYZ( _sides[0]->node1() ) +
2043 XYZ( _sides[0]->node2() ) +
2044 XYZ( _sides[1]->node1() )) / 3.;
2045 vecOut.SetXYZ( _sides[i]->MiddlePnt() - pIn );
2047 if ( norm * vecOut < 0 )
2049 double mag2 = norm.SquareMagnitude();
2050 if ( mag2 > numeric_limits<double>::min() )
2051 norm /= sqrt( mag2 );
2054 //================================================================================
2056 * \brief Move medium node of theLink according to its distance from boundary
2057 * \param theLink - link to fix
2058 * \param theRefVec - movement of boundary
2059 * \param theLinks - all adjacent links of continous triangles
2060 * \param theFaceHelper - helper is not used so far
2061 * \param thePrevLen - distance from the boundary
2062 * \param theStep - number of steps till movement propagation limit
2063 * \param theLinkNorm - out normal to theLink
2064 * \param theSign - 1 or -1 depending on movement of boundary
2065 * \retval double - distance from boundary to propagation limit or other boundary
2067 //================================================================================
2069 double QFace::MoveByBoundary( const TChainLink& theLink,
2070 const gp_Vec& theRefVec,
2071 const TLinkSet& theLinks,
2072 SMESH_MesherHelper* theFaceHelper,
2073 const double thePrevLen,
2075 gp_Vec* theLinkNorm,
2076 double theSign) const
2079 return thePrevLen; // propagation limit reached
2081 int iL; // index of theLink
2082 for ( iL = 0; iL < _sides.size(); ++iL )
2083 if ( theLink._qlink == _sides[ iL ])
2086 MSG(string(theStep,'.')<<" Ref( "<<theRefVec.X()<<","<<theRefVec.Y()<<","<<theRefVec.Z()<<" )"
2087 <<" thePrevLen " << thePrevLen);
2088 MSG(string(theStep,'.')<<" "<<*theLink._qlink);
2090 gp_Vec linkNorm = -LinkNorm( iL/*, theFaceHelper*/ ); // normal to theLink
2091 double refProj = theRefVec * linkNorm; // project movement vector to normal of theLink
2092 if ( theStep == theFirstStep )
2093 theSign = refProj < 0. ? -1. : 1.;
2094 else if ( theSign * refProj < 0.4 * theRefVec.Magnitude())
2095 return thePrevLen; // to propagate movement forward only, not in side dir or backward
2097 int iL1 = (iL + 1) % 3, iL2 = (iL + 2) % 3; // indices of the two other links of triangle
2098 TLinkInSet link1 = theLinks.find( _sides[iL1] );
2099 TLinkInSet link2 = theLinks.find( _sides[iL2] );
2100 if ( link1 == theLinks.end() || link2 == theLinks.end() )
2102 const QFace* f1 = link1->NextFace( this ); // adjacent faces
2103 const QFace* f2 = link2->NextFace( this );
2105 // propagate to adjacent faces till limit step or boundary
2106 double len1 = thePrevLen + (theLink->MiddlePnt() - _sides[iL1]->MiddlePnt()).Modulus();
2107 double len2 = thePrevLen + (theLink->MiddlePnt() - _sides[iL2]->MiddlePnt()).Modulus();
2108 gp_Vec linkDir1(0,0,0); // initialize to avoid valgrind error ("Conditional jump...")
2109 gp_Vec linkDir2(0,0,0);
2113 len1 = f1->MoveByBoundary
2114 ( *link1, theRefVec, theLinks, theFaceHelper, len1, theStep-1, &linkDir1, theSign);
2116 linkDir1 = LinkNorm( iL1/*, theFaceHelper*/ );
2118 MSG( " --------------- EXCEPTION");
2124 len2 = f2->MoveByBoundary
2125 ( *link2, theRefVec, theLinks, theFaceHelper, len2, theStep-1, &linkDir2, theSign);
2127 linkDir2 = LinkNorm( iL2/*, theFaceHelper*/ );
2129 MSG( " --------------- EXCEPTION");
2134 if ( theStep != theFirstStep )
2136 // choose chain length by direction of propagation most codirected with theRefVec
2137 bool choose1 = ( theRefVec * linkDir1 * theSign > theRefVec * linkDir2 * theSign );
2138 fullLen = choose1 ? len1 : len2;
2139 double r = thePrevLen / fullLen;
2141 gp_Vec move = linkNorm * refProj * ( 1 - r );
2142 theLink->Move( move, true );
2144 MSG(string(theStep,'.')<<" Move "<< theLink->_mediumNode->GetID()<<
2145 " by " << refProj * ( 1 - r ) << " following " <<
2146 (choose1 ? *link1->_qlink : *link2->_qlink));
2148 if ( theLinkNorm ) *theLinkNorm = linkNorm;
2153 //================================================================================
2155 * \brief Find pairs of continues faces
2157 //================================================================================
2159 void QLink::SetContinuesFaces() const
2161 // x0 x - QLink, [-|] - QFace, v - volume
2163 // | Between _faces of link x2 two vertical faces are continues
2164 // x1----x2-----x3 and two horizontal faces are continues. We set vertical faces
2165 // | to _faces[0] and _faces[1] and horizontal faces to
2166 // v2 | v3 _faces[2] and _faces[3] (or vise versa).
2169 if ( _faces.empty() )
2172 for ( int iF = 1; iFaceCont < 0 && iF < _faces.size(); ++iF )
2174 // look for a face bounding none of volumes bound by _faces[0]
2175 bool sameVol = false;
2176 int nbVol = _faces[iF]->NbVolumes();
2177 for ( int iV = 0; !sameVol && iV < nbVol; ++iV )
2178 sameVol = ( _faces[iF]->_volumes[iV] == _faces[0]->_volumes[0] ||
2179 _faces[iF]->_volumes[iV] == _faces[0]->_volumes[1]);
2183 if ( iFaceCont > 0 ) // continues faces found, set one by the other
2185 if ( iFaceCont != 1 )
2186 std::swap( _faces[1], _faces[iFaceCont] );
2188 else if ( _faces.size() > 1 ) // not found, set NULL by the first face
2190 _faces.insert( ++_faces.begin(), 0 );
2193 //================================================================================
2195 * \brief Return a face continues to the given one
2197 //================================================================================
2199 const QFace* QLink::GetContinuesFace( const QFace* face ) const
2201 for ( int i = 0; i < _faces.size(); ++i ) {
2202 if ( _faces[i] == face ) {
2203 int iF = i < 2 ? 1-i : 5-i;
2204 return iF < _faces.size() ? _faces[iF] : 0;
2209 //================================================================================
2211 * \brief True if link is on mesh boundary
2213 //================================================================================
2215 bool QLink::OnBoundary() const
2217 for ( int i = 0; i < _faces.size(); ++i )
2218 if (_faces[i] && _faces[i]->IsBoundary()) return true;
2221 //================================================================================
2223 * \brief Return normal of link of the chain
2225 //================================================================================
2227 gp_Vec TChainLink::Normal() const {
2229 if (_qfaces[0]) norm = _qfaces[0]->_normal;
2230 if (_qfaces[1]) norm += _qfaces[1]->_normal;
2233 //================================================================================
2235 * \brief Move medium nodes of vertical links of pentahedrons adjacent by side faces
2237 //================================================================================
2239 void fixPrism( TChain& allLinks )
2241 // separate boundary links from internal ones
2242 typedef set<const QLink*/*, QLink::PtrComparator*/> QLinkSet;
2243 QLinkSet interLinks, bndLinks1, bndLink2;
2245 bool isCurved = false;
2246 for ( TChain::iterator lnk = allLinks.begin(); lnk != allLinks.end(); ++lnk ) {
2247 if ( (*lnk)->OnBoundary() )
2248 bndLinks1.insert( lnk->_qlink );
2250 interLinks.insert( lnk->_qlink );
2251 isCurved = isCurved || !(*lnk)->IsStraight();
2254 return; // no need to move
2256 QLinkSet *curBndLinks = &bndLinks1, *newBndLinks = &bndLink2;
2258 while ( !interLinks.empty() && !curBndLinks->empty() )
2260 // propagate movement from boundary links to connected internal links
2261 QLinkSet::iterator bnd = curBndLinks->begin(), bndEnd = curBndLinks->end();
2262 for ( ; bnd != bndEnd; ++bnd )
2264 const QLink* bndLink = *bnd;
2265 for ( int i = 0; i < bndLink->_faces.size(); ++i ) // loop on faces of bndLink
2267 const QFace* face = bndLink->_faces[i]; // quadrange lateral face of a prism
2268 if ( !face ) continue;
2269 // find and move internal link opposite to bndLink within the face
2270 int interInd = ( face->LinkIndex( bndLink ) + 2 ) % face->_sides.size();
2271 const QLink* interLink = face->_sides[ interInd ];
2272 QLinkSet::iterator pInterLink = interLinks.find( interLink );
2273 if ( pInterLink == interLinks.end() ) continue; // not internal link
2274 interLink->Move( bndLink->_nodeMove );
2275 // treated internal links become new boundary ones
2276 interLinks. erase( pInterLink );
2277 newBndLinks->insert( interLink );
2280 curBndLinks->clear();
2281 std::swap( curBndLinks, newBndLinks );
2285 //================================================================================
2287 * \brief Fix links of continues triangles near curved boundary
2289 //================================================================================
2291 void fixTriaNearBoundary( TChain & allLinks, SMESH_MesherHelper& /*helper*/)
2293 if ( allLinks.empty() ) return;
2295 TLinkSet linkSet( allLinks.begin(), allLinks.end());
2296 TLinkInSet linkIt = linkSet.begin(), linksEnd = linkSet.end();
2298 // move in 2d if we are on geom face
2299 // TopoDS_Face face;
2300 // TopLoc_Location loc;
2301 // SMESH_MesherHelper faceHelper( *helper.GetMesh());
2302 // while ( linkIt->IsBoundary()) ++linkIt;
2303 // if ( linkIt == linksEnd ) return;
2304 // if ( (*linkIt)->MediumPos() == SMDS_TOP_FACE ) {
2305 // bool checkPos = true;
2306 // TopoDS_Shape f = helper.GetSubShapeByNode( (*linkIt)->_mediumNode, helper.GetMeshDS() );
2307 // if ( !f.IsNull() && f.ShapeType() == TopAbs_FACE ) {
2308 // face = TopoDS::Face( f );
2309 // helper.GetNodeUV( face, (*linkIt)->_mediumNode, 0, &checkPos);
2313 // faceHelper.SetSubShape( face );
2316 for ( linkIt = linkSet.begin(); linkIt != linksEnd; ++linkIt)
2318 if ( linkIt->IsBoundary() && !(*linkIt)->IsStraight() && linkIt->_qfaces[0])
2320 // if ( !face.IsNull() ) {
2321 // const SMDS_MeshNode* inFaceNode =
2322 // faceHelper.GetNodeUVneedInFaceNode() ? linkIt->_qfaces[0]->GetNodeInFace() : 0;
2323 // gp_XY uvm = helper.GetNodeUV( face, (*linkIt)->_mediumNode, inFaceNode );
2324 // gp_XY uv1 = helper.GetNodeUV( face, (*linkIt)->node1(), inFaceNode);
2325 // gp_XY uv2 = helper.GetNodeUV( face, (*linkIt)->node2(), inFaceNode);
2326 // gp_XY uvMove = uvm - helper.GetMiddleUV( BRep_Tool::Surface(face,loc), uv1, uv2);
2327 // gp_Vec move( uvMove.X(), uvMove.Y(), 0 );
2328 // linkIt->_qfaces[0]->MoveByBoundary( *linkIt, move, linkSet, &faceHelper );
2331 linkIt->_qfaces[0]->MoveByBoundary( *linkIt, (*linkIt)->_nodeMove, linkSet );
2337 //================================================================================
2339 * \brief Detect rectangular structure of links and build chains from them
2341 //================================================================================
2343 enum TSplitTriaResult {
2344 _OK, _NO_CORNERS, _FEW_ROWS, _MANY_ROWS, _NO_SIDELINK, _BAD_MIDQUAD, _NOT_RECT,
2345 _NO_MIDQUAD, _NO_UPTRIA, _BAD_SET_SIZE, _BAD_CORNER, _BAD_START, _NO_BOTLINK, _TWISTED_CHAIN };
2347 TSplitTriaResult splitTrianglesIntoChains( TChain & allLinks,
2348 vector< TChain> & resultChains,
2349 SMDS_TypeOfPosition pos )
2351 // put links in the set and evalute number of result chains by number of boundary links
2354 for ( TChain::iterator lnk = allLinks.begin(); lnk != allLinks.end(); ++lnk ) {
2355 linkSet.insert( *lnk );
2356 nbBndLinks += lnk->IsBoundary();
2358 resultChains.clear();
2359 resultChains.reserve( nbBndLinks / 2 );
2361 TLinkInSet linkIt, linksEnd = linkSet.end();
2363 // find a boundary link with corner node; corner node has position pos-2
2364 // i.e. SMDS_TOP_VERTEX for links on faces and SMDS_TOP_EDGE for
2366 SMDS_TypeOfPosition cornerPos = SMDS_TypeOfPosition(pos-2);
2367 const SMDS_MeshNode* corner = 0;
2368 for ( linkIt = linkSet.begin(); linkIt != linksEnd; ++linkIt )
2369 if ( linkIt->IsBoundary() && (corner = (*linkIt)->EndPosNode(cornerPos)))
2374 TLinkInSet startLink = linkIt;
2375 const SMDS_MeshNode* startCorner = corner;
2376 vector< TChain* > rowChains;
2379 while ( startLink != linksEnd) // loop on columns
2381 // We suppose we have a rectangular structure like shown here. We have found a
2382 // corner of the rectangle (startCorner) and a boundary link sharing
2383 // |/ |/ | the startCorner (startLink). We are going to loop on rows of the
2384 // --o---o---o structure making several chains at once. One chain (columnChain)
2385 // |\ | /| starts at startLink and continues upward (we look at the structure
2386 // \ | \ | / | from such point that startLink is on the bottom of the structure).
2387 // \| \|/ | While going upward we also fill horizontal chains (rowChains) we
2388 // --o---o---o encounter.
2390 // / | \ | \ | startCorner
2395 if ( resultChains.size() == nbBndLinks / 2 )
2397 resultChains.push_back( TChain() );
2398 TChain& columnChain = resultChains.back();
2400 TLinkInSet botLink = startLink; // current horizontal link to go up from
2401 corner = startCorner; // current corner the botLink ends at
2403 while ( botLink != linksEnd ) // loop on rows
2405 // add botLink to the columnChain
2406 columnChain.push_back( *botLink );
2408 const QFace* botTria = botLink->_qfaces[0]; // bottom triangle bound by botLink
2410 { // the column ends
2411 if ( botLink == startLink )
2412 return _TWISTED_CHAIN; // issue 0020951
2413 linkSet.erase( botLink );
2414 if ( iRow != rowChains.size() )
2415 return _FEW_ROWS; // different nb of rows in columns
2418 // find the link dividing the quadrangle (midQuadLink) and vertical boundary
2419 // link ending at <corner> (sideLink); there are two cases:
2420 // 1) midQuadLink does not end at <corner>, then we easily find it by botTria,
2421 // since midQuadLink is not at boundary while sideLink is.
2422 // 2) midQuadLink ends at <corner>
2424 TLinkInSet midQuadLink = linksEnd;
2425 TLinkInSet sideLink = botTria->GetBoundaryLink( linkSet, *botLink, &midQuadLink,
2427 if ( isCase2 ) { // find midQuadLink among links of botTria
2428 midQuadLink = botTria->GetLinkByNode( linkSet, *botLink, corner );
2429 if ( midQuadLink->IsBoundary() )
2430 return _BAD_MIDQUAD;
2432 if ( sideLink == linksEnd || midQuadLink == linksEnd || sideLink == midQuadLink )
2433 return sideLink == linksEnd ? _NO_SIDELINK : _NO_MIDQUAD;
2436 columnChain.push_back( *midQuadLink );
2437 if ( iRow >= rowChains.size() ) {
2439 return _MANY_ROWS; // different nb of rows in columns
2440 if ( resultChains.size() == nbBndLinks / 2 )
2442 resultChains.push_back( TChain() );
2443 rowChains.push_back( & resultChains.back() );
2445 rowChains[iRow]->push_back( *sideLink );
2446 rowChains[iRow]->push_back( *midQuadLink );
2448 const QFace* upTria = midQuadLink->NextFace( botTria ); // upper tria of the rectangle
2452 // prepare startCorner and startLink for the next column
2453 startCorner = startLink->NextNode( startCorner );
2455 startLink = botTria->GetBoundaryLink( linkSet, *botLink, 0, startCorner );
2457 startLink = upTria->GetBoundaryLink( linkSet, *midQuadLink, 0, startCorner );
2458 // check if no more columns remains
2459 if ( startLink != linksEnd ) {
2460 const SMDS_MeshNode* botNode = startLink->NextNode( startCorner );
2461 if ( (isCase2 ? botTria : upTria)->Contains( botNode ))
2462 startLink = linksEnd; // startLink bounds upTria or botTria
2463 else if ( startLink == botLink || startLink == midQuadLink || startLink == sideLink )
2467 // find bottom link and corner for the next row
2468 corner = sideLink->NextNode( corner );
2469 // next bottom link ends at the new corner
2470 linkSet.erase( botLink );
2471 botLink = upTria->GetLinkByNode( linkSet, (isCase2 ? *sideLink : *midQuadLink), corner );
2472 if ( botLink == linksEnd || botLink == midQuadLink || botLink == sideLink)
2474 if ( midQuadLink == startLink || sideLink == startLink )
2475 return _TWISTED_CHAIN; // issue 0020951
2476 linkSet.erase( midQuadLink );
2477 linkSet.erase( sideLink );
2479 // make faces neighboring the found ones be boundary
2480 if ( startLink != linksEnd ) {
2481 const QFace* tria = isCase2 ? botTria : upTria;
2482 for ( int iL = 0; iL < 3; ++iL ) {
2483 linkIt = linkSet.find( tria->_sides[iL] );
2484 if ( linkIt != linksEnd )
2485 linkIt->RemoveFace( tria );
2488 if ( botLink->_qfaces[0] == upTria || botLink->_qfaces[1] == upTria )
2489 botLink->RemoveFace( upTria ); // make next botTria first in vector
2496 // In the linkSet, there must remain the last links of rowChains; add them
2497 if ( linkSet.size() != rowChains.size() )
2498 return _BAD_SET_SIZE;
2499 for ( int iRow = 0; iRow < rowChains.size(); ++iRow ) {
2500 // find the link (startLink) ending at startCorner
2502 for ( startLink = linkSet.begin(); startLink != linksEnd; ++startLink ) {
2503 if ( (*startLink)->node1() == startCorner ) {
2504 corner = (*startLink)->node2(); break;
2506 else if ( (*startLink)->node2() == startCorner) {
2507 corner = (*startLink)->node1(); break;
2510 if ( startLink == linksEnd )
2512 rowChains[ iRow ]->push_back( *startLink );
2513 linkSet.erase( startLink );
2514 startCorner = corner;
2521 //=======================================================================
2523 * \brief Move medium nodes of faces and volumes to fix distorted elements
2524 * \param volumeOnly - to fix nodes on faces or not, if the shape is solid
2526 * Issue 0020307: EDF 992 SMESH : Linea/Quadratic with Medium Node on Geometry
2528 //=======================================================================
2530 void SMESH_MesherHelper::FixQuadraticElements(bool volumeOnly)
2532 // 0. Apply algorithm to solids or geom faces
2533 // ----------------------------------------------
2534 if ( myShape.IsNull() ) {
2535 if ( !myMesh->HasShapeToMesh() ) return;
2536 SetSubShape( myMesh->GetShapeToMesh() );
2540 TopTools_IndexedMapOfShape solids;
2541 TopExp::MapShapes(myShape,TopAbs_SOLID,solids);
2542 nbSolids = solids.Extent();
2544 TopTools_MapOfShape faces; // faces not in solid or in not meshed solid
2545 for ( TopExp_Explorer f(myShape,TopAbs_FACE,TopAbs_SOLID); f.More(); f.Next() ) {
2546 faces.Add( f.Current() ); // not in solid
2548 for ( TopExp_Explorer s(myShape,TopAbs_SOLID); s.More(); s.Next() ) {
2549 if ( myMesh->GetSubMesh( s.Current() )->IsEmpty() ) { // get faces of solid
2550 for ( TopExp_Explorer f( s.Current(), TopAbs_FACE); f.More(); f.Next() )
2551 faces.Add( f.Current() ); // in not meshed solid
2553 else { // fix nodes in the solid and its faces
2554 MSG("FIX SOLID " << nbSolids-- << " #" << GetMeshDS()->ShapeToIndex(s.Current()));
2555 SMESH_MesherHelper h(*myMesh);
2556 h.SetSubShape( s.Current() );
2557 h.FixQuadraticElements(false);
2560 // fix nodes on geom faces
2562 int nbfaces = faces.Extent();
2564 for ( TopTools_MapIteratorOfMapOfShape fIt( faces ); fIt.More(); fIt.Next() ) {
2565 MSG("FIX FACE " << nbfaces-- << " #" << GetMeshDS()->ShapeToIndex(fIt.Key()));
2566 SMESH_MesherHelper h(*myMesh);
2567 h.SetSubShape( fIt.Key() );
2568 h.FixQuadraticElements(true);
2570 //perf_print_all_meters(1);
2574 // 1. Find out type of elements and get iterator on them
2575 // ---------------------------------------------------
2577 SMDS_ElemIteratorPtr elemIt;
2578 SMDSAbs_ElementType elemType = SMDSAbs_All;
2580 SMESH_subMesh* submesh = myMesh->GetSubMeshContaining( myShapeID );
2583 if ( SMESHDS_SubMesh* smDS = submesh->GetSubMeshDS() ) {
2584 elemIt = smDS->GetElements();
2585 if ( elemIt->more() ) {
2586 elemType = elemIt->next()->GetType();
2587 elemIt = smDS->GetElements();
2590 if ( !elemIt || !elemIt->more() || elemType < SMDSAbs_Face )
2593 // 2. Fill in auxiliary data structures
2594 // ----------------------------------
2598 set< QLink >::iterator pLink;
2599 set< QFace >::iterator pFace;
2601 bool isCurved = false;
2602 //bool hasRectFaces = false;
2603 set<int> nbElemNodeSet;
2605 if ( elemType == SMDSAbs_Volume )
2607 SMDS_VolumeTool volTool;
2608 while ( elemIt->more() ) // loop on volumes
2610 const SMDS_MeshElement* vol = elemIt->next();
2611 if ( !vol->IsQuadratic() || !volTool.Set( vol ))
2613 for ( int iF = 0; iF < volTool.NbFaces(); ++iF ) // loop on faces of volume
2615 int nbN = volTool.NbFaceNodes( iF );
2616 nbElemNodeSet.insert( nbN );
2617 const SMDS_MeshNode** faceNodes = volTool.GetFaceNodes( iF );
2618 vector< const QLink* > faceLinks( nbN/2 );
2619 for ( int iN = 0; iN < nbN; iN += 2 ) // loop on links of a face
2622 QLink link( faceNodes[iN], faceNodes[iN+2], faceNodes[iN+1] );
2623 pLink = links.insert( link ).first;
2624 faceLinks[ iN/2 ] = & *pLink;
2626 isCurved = !link.IsStraight();
2627 if ( link.MediumPos() == SMDS_TOP_3DSPACE && !link.IsStraight() )
2628 return; // already fixed
2631 pFace = faces.insert( QFace( faceLinks )).first;
2632 if ( pFace->NbVolumes() == 0 )
2633 pFace->AddSelfToLinks();
2634 pFace->SetVolume( vol );
2635 // hasRectFaces = hasRectFaces ||
2636 // ( volTool.GetVolumeType() == SMDS_VolumeTool::QUAD_HEXA ||
2637 // volTool.GetVolumeType() == SMDS_VolumeTool::QUAD_PENTA );
2640 pFace->_face = GetMeshDS()->FindFace(faceNodes[0],faceNodes[2],faceNodes[4]);
2642 pFace->_face = GetMeshDS()->FindFace(faceNodes[0],faceNodes[2],
2643 faceNodes[4],faceNodes[6] );
2647 set< QLink >::iterator pLink = links.begin();
2648 for ( ; pLink != links.end(); ++pLink )
2649 pLink->SetContinuesFaces();
2653 while ( elemIt->more() ) // loop on faces
2655 const SMDS_MeshElement* face = elemIt->next();
2656 if ( !face->IsQuadratic() )
2658 nbElemNodeSet.insert( face->NbNodes() );
2659 int nbN = face->NbNodes()/2;
2660 vector< const QLink* > faceLinks( nbN );
2661 for ( int iN = 0; iN < nbN; ++iN ) // loop on links of a face
2664 QLink link( face->GetNode(iN), face->GetNode((iN+1)%nbN), face->GetNode(iN+nbN) );
2665 pLink = links.insert( link ).first;
2666 faceLinks[ iN ] = & *pLink;
2668 isCurved = !link.IsStraight();
2671 pFace = faces.insert( QFace( faceLinks )).first;
2672 pFace->AddSelfToLinks();
2673 //hasRectFaces = ( hasRectFaces || nbN == 4 );
2677 return; // no curved edges of faces
2679 // 3. Compute displacement of medium nodes
2680 // -------------------------------------
2682 // two loops on faces: the first is to treat boundary links, the second is for internal ones
2683 TopLoc_Location loc;
2684 // not treat boundary of volumic submesh
2685 int isInside = ( elemType == SMDSAbs_Volume && volumeOnly ) ? 1 : 0;
2686 for ( ; isInside < 2; ++isInside ) {
2687 MSG( "--------------- LOOP (inside=" << isInside << ") ------------------");
2688 SMDS_TypeOfPosition pos = isInside ? SMDS_TOP_3DSPACE : SMDS_TOP_FACE;
2689 SMDS_TypeOfPosition bndPos = isInside ? SMDS_TOP_FACE : SMDS_TOP_EDGE;
2691 for ( pFace = faces.begin(); pFace != faces.end(); ++pFace ) {
2692 if ( bool(isInside) == pFace->IsBoundary() )
2694 for ( int dir = 0; dir < 2; ++dir ) // 2 directions of propagation from quadrangle
2697 // make chain of links connected via continues faces
2700 if ( !pFace->GetLinkChain( dir, rawChain, pos, error) && error ==ERR_UNKNOWN ) continue;
2702 if ( !pFace->GetLinkChain( dir+2, rawChain, pos, error ) && error ==ERR_UNKNOWN ) continue;
2704 vector< TChain > chains;
2705 if ( error == ERR_OK ) { // chain contains continues rectangles
2707 chains[0].splice( chains[0].begin(), rawChain );
2709 else if ( error == ERR_TRI ) { // chain contains continues triangles
2710 TSplitTriaResult res = splitTrianglesIntoChains( rawChain, chains, pos );
2711 if ( res != _OK ) { // not quadrangles split into triangles
2712 fixTriaNearBoundary( rawChain, *this );
2716 else if ( error == ERR_PRISM ) { // quadrangle side faces of prisms
2717 fixPrism( rawChain );
2723 for ( int iC = 0; iC < chains.size(); ++iC )
2725 TChain& chain = chains[iC];
2726 if ( chain.empty() ) continue;
2727 if ( chain.front()->IsStraight() && chain.back()->IsStraight() ) {
2728 MSG("3D straight - ignore");
2731 if ( chain.front()->MediumPos() > bndPos ||
2732 chain.back()->MediumPos() > bndPos ) {
2733 MSG("Internal chain - ignore");
2736 // mesure chain length and compute link position along the chain
2737 double chainLen = 0;
2738 vector< double > linkPos;
2739 MSGBEG( "Link medium nodes: ");
2740 TChain::iterator link0 = chain.begin(), link1 = chain.begin(), link2;
2741 for ( ++link1; link1 != chain.end(); ++link1, ++link0 ) {
2742 MSGBEG( (*link0)->_mediumNode->GetID() << "-" <<(*link1)->_mediumNode->GetID()<<" ");
2743 double len = ((*link0)->MiddlePnt() - (*link1)->MiddlePnt()).Modulus();
2744 while ( len < numeric_limits<double>::min() ) { // remove degenerated link
2745 link1 = chain.erase( link1 );
2746 if ( link1 == chain.end() )
2748 len = ((*link0)->MiddlePnt() - (*link1)->MiddlePnt()).Modulus();
2751 linkPos.push_back( chainLen );
2754 if ( linkPos.size() < 2 )
2757 gp_Vec move0 = chain.front()->_nodeMove;
2758 gp_Vec move1 = chain.back ()->_nodeMove;
2761 bool checkUV = true;
2763 // compute node displacement of end links in parametric space of face
2764 const SMDS_MeshNode* nodeOnFace = (*(++chain.begin()))->_mediumNode;
2765 TopoDS_Shape f = GetSubShapeByNode( nodeOnFace, GetMeshDS() );
2766 if ( !f.IsNull() && f.ShapeType() == TopAbs_FACE )
2768 face = TopoDS::Face( f );
2769 Handle(Geom_Surface) surf = BRep_Tool::Surface(face,loc);
2771 for ( int is1 = 0; is1 < 2; ++is1 ) // move0 or move1
2773 TChainLink& link = is1 ? chain.back() : chain.front();
2774 gp_XY uvm = GetNodeUV( face, link->_mediumNode, nodeOnFace, &checkUV);
2775 gp_XY uv1 = GetNodeUV( face, link->node1(), nodeOnFace, &checkUV);
2776 gp_XY uv2 = GetNodeUV( face, link->node2(), nodeOnFace, &checkUV);
2777 gp_XY uv12 = GetMiddleUV( surf, uv1, uv2);
2778 // uvMove = uvm - uv12
2779 gp_XY uvMove = applyIn2D(surf, uvm, uv12, gp_XY_Subtracted, /*inPeriod=*/false);
2780 ( is1 ? move1 : move0 ).SetCoord( uvMove.X(), uvMove.Y(), 0 );
2781 if ( !is1 ) // correct nodeOnFace for move1 (issue 0020919)
2782 nodeOnFace = (*(++chain.rbegin()))->_mediumNode;
2783 isStraight[is1] = isStraightLink( (uv2-uv1).SquareModulus(),uvMove.SquareModulus());
2785 // if ( move0.SquareMagnitude() < straightTol2 &&
2786 // move1.SquareMagnitude() < straightTol2 ) {
2787 if ( isStraight[0] && isStraight[1] ) {
2788 MSG("2D straight - ignore");
2789 continue; // straight - no need to move nodes of internal links
2794 if ( isInside || face.IsNull() )
2796 // compute node displacement of end links in their local coord systems
2798 TChainLink& ln0 = chain.front(), ln1 = *(++chain.begin());
2799 trsf.SetTransformation( gp_Ax3( gp::Origin(), ln0.Normal(),
2800 gp_Vec( ln0->MiddlePnt(), ln1->MiddlePnt() )));
2801 move0.Transform(trsf);
2804 TChainLink& ln0 = *(++chain.rbegin()), ln1 = chain.back();
2805 trsf.SetTransformation( gp_Ax3( gp::Origin(), ln1.Normal(),
2806 gp_Vec( ln0->MiddlePnt(), ln1->MiddlePnt() )));
2807 move1.Transform(trsf);
2810 // compute displacement of medium nodes
2811 link2 = chain.begin();
2814 for ( int i = 0; link2 != chain.end(); ++link0, ++link1, ++link2, ++i )
2816 double r = linkPos[i] / chainLen;
2817 // displacement in local coord system
2818 gp_Vec move = (1. - r) * move0 + r * move1;
2819 if ( isInside || face.IsNull()) {
2820 // transform to global
2821 gp_Vec x01( (*link0)->MiddlePnt(), (*link1)->MiddlePnt() );
2822 gp_Vec x12( (*link1)->MiddlePnt(), (*link2)->MiddlePnt() );
2823 gp_Vec x = x01.Normalized() + x12.Normalized();
2824 trsf.SetTransformation( gp_Ax3( gp::Origin(), link1->Normal(), x), gp_Ax3() );
2825 move.Transform(trsf);
2828 // compute 3D displacement by 2D one
2829 Handle(Geom_Surface) s = BRep_Tool::Surface(face,loc);
2830 gp_XY oldUV = GetNodeUV( face, (*link1)->_mediumNode, 0, &checkUV);
2831 gp_XY newUV = applyIn2D( s, oldUV, gp_XY( move.X(),move.Y()), gp_XY_Added);
2832 gp_Pnt newPnt = s->Value( newUV.X(), newUV.Y());
2833 move = gp_Vec( XYZ((*link1)->_mediumNode), newPnt.Transformed(loc) );
2835 if ( (XYZ((*link1)->node1()) - XYZ((*link1)->node2())).SquareModulus() <
2836 move.SquareMagnitude())
2838 gp_XY uv0 = GetNodeUV( face, (*link0)->_mediumNode, 0, &checkUV);
2839 gp_XY uv2 = GetNodeUV( face, (*link2)->_mediumNode, 0, &checkUV);
2840 MSG( "TOO LONG MOVE \t" <<
2841 "uv0: "<<uv0.X()<<", "<<uv0.Y()<<" \t" <<
2842 "uv2: "<<uv2.X()<<", "<<uv2.Y()<<" \t" <<
2843 "uvOld: "<<oldUV.X()<<", "<<oldUV.Y()<<" \t" <<
2844 "newUV: "<<newUV.X()<<", "<<newUV.Y()<<" \t");
2848 (*link1)->Move( move );
2849 MSG( "Move " << (*link1)->_mediumNode->GetID() << " following "
2850 << chain.front()->_mediumNode->GetID() <<"-"
2851 << chain.back ()->_mediumNode->GetID() <<
2852 " by " << move.Magnitude());
2854 } // loop on chains of links
2855 } // loop on 2 directions of propagation from quadrangle
2862 for ( pLink = links.begin(); pLink != links.end(); ++pLink ) {
2863 if ( pLink->IsMoved() ) {
2864 //gp_Pnt p = pLink->MediumPnt() + pLink->Move();
2865 gp_Pnt p = pLink->MiddlePnt() + pLink->Move();
2866 GetMeshDS()->MoveNode( pLink->_mediumNode, p.X(), p.Y(), p.Z());
2871 //=======================================================================
2873 * \brief Iterator on ancestors of the given type
2875 //=======================================================================
2877 struct TAncestorsIterator : public SMDS_Iterator<const TopoDS_Shape*>
2879 TopTools_ListIteratorOfListOfShape _ancIter;
2880 TopAbs_ShapeEnum _type;
2881 TAncestorsIterator( const TopTools_ListOfShape& ancestors, TopAbs_ShapeEnum type)
2882 : _ancIter( ancestors ), _type( type )
2884 if ( _ancIter.More() && _ancIter.Value().ShapeType() != _type ) next();
2888 return _ancIter.More();
2890 virtual const TopoDS_Shape* next()
2892 const TopoDS_Shape* s = _ancIter.More() ? & _ancIter.Value() : 0;
2893 if ( _ancIter.More() )
2894 for ( _ancIter.Next(); _ancIter.More(); _ancIter.Next())
2895 if ( _ancIter.Value().ShapeType() == _type )
2901 //=======================================================================
2903 * \brief Return iterator on ancestors of the given type
2905 //=======================================================================
2907 PShapeIteratorPtr SMESH_MesherHelper::GetAncestors(const TopoDS_Shape& shape,
2908 const SMESH_Mesh& mesh,
2909 TopAbs_ShapeEnum ancestorType)
2911 return PShapeIteratorPtr( new TAncestorsIterator( mesh.GetAncestors(shape), ancestorType));