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()
92 TID2Projector::iterator i_proj = myFace2Projector.begin();
93 for ( ; i_proj != myFace2Projector.end(); ++i_proj )
94 delete i_proj->second;
97 //=======================================================================
98 //function : IsQuadraticSubMesh
99 //purpose : Check submesh for given shape: if all elements on this shape
100 // are quadratic, quadratic elements will be created.
101 // Also fill myTLinkNodeMap
102 //=======================================================================
104 bool SMESH_MesherHelper::IsQuadraticSubMesh(const TopoDS_Shape& aSh)
106 SMESHDS_Mesh* meshDS = GetMeshDS();
107 // we can create quadratic elements only if all elements
108 // created on subshapes of given shape are quadratic
109 // also we have to fill myTLinkNodeMap
110 myCreateQuadratic = true;
111 mySeamShapeIds.clear();
112 myDegenShapeIds.clear();
113 TopAbs_ShapeEnum subType( aSh.ShapeType()==TopAbs_FACE ? TopAbs_EDGE : TopAbs_FACE );
114 SMDSAbs_ElementType elemType( subType==TopAbs_FACE ? SMDSAbs_Face : SMDSAbs_Edge );
116 int nbOldLinks = myTLinkNodeMap.size();
118 TopExp_Explorer exp( aSh, subType );
119 for (; exp.More() && myCreateQuadratic; exp.Next()) {
120 if ( SMESHDS_SubMesh * subMesh = meshDS->MeshElements( exp.Current() )) {
121 if ( SMDS_ElemIteratorPtr it = subMesh->GetElements() ) {
123 const SMDS_MeshElement* e = it->next();
124 if ( e->GetType() != elemType || !e->IsQuadratic() ) {
125 myCreateQuadratic = false;
130 switch ( e->NbNodes() ) {
132 AddTLinkNode(e->GetNode(0),e->GetNode(1),e->GetNode(2)); break;
134 AddTLinkNode(e->GetNode(0),e->GetNode(1),e->GetNode(3));
135 AddTLinkNode(e->GetNode(1),e->GetNode(2),e->GetNode(4));
136 AddTLinkNode(e->GetNode(2),e->GetNode(0),e->GetNode(5)); break;
138 AddTLinkNode(e->GetNode(0),e->GetNode(1),e->GetNode(4));
139 AddTLinkNode(e->GetNode(1),e->GetNode(2),e->GetNode(5));
140 AddTLinkNode(e->GetNode(2),e->GetNode(3),e->GetNode(6));
141 AddTLinkNode(e->GetNode(3),e->GetNode(0),e->GetNode(7));
144 myCreateQuadratic = false;
153 if ( nbOldLinks == myTLinkNodeMap.size() )
154 myCreateQuadratic = false;
156 if(!myCreateQuadratic) {
157 myTLinkNodeMap.clear();
161 return myCreateQuadratic;
164 //=======================================================================
165 //function : SetSubShape
166 //purpose : Set geomerty to make elements on
167 //=======================================================================
169 void SMESH_MesherHelper::SetSubShape(const int aShID)
171 if ( aShID == myShapeID )
174 SetSubShape( GetMeshDS()->IndexToShape( aShID ));
176 SetSubShape( TopoDS_Shape() );
179 //=======================================================================
180 //function : SetSubShape
181 //purpose : Set geomerty to create elements on
182 //=======================================================================
184 void SMESH_MesherHelper::SetSubShape(const TopoDS_Shape& aSh)
186 if ( myShape.IsSame( aSh ))
190 mySeamShapeIds.clear();
191 myDegenShapeIds.clear();
193 if ( myShape.IsNull() ) {
197 SMESHDS_Mesh* meshDS = GetMeshDS();
198 myShapeID = meshDS->ShapeToIndex(aSh);
201 // treatment of periodic faces
202 for ( TopExp_Explorer eF( aSh, TopAbs_FACE ); eF.More(); eF.Next() )
204 const TopoDS_Face& face = TopoDS::Face( eF.Current() );
205 BRepAdaptor_Surface surface( face );
206 if ( surface.IsUPeriodic() || surface.IsVPeriodic() )
208 for (TopExp_Explorer exp( face, TopAbs_EDGE ); exp.More(); exp.Next())
210 // look for a seam edge
211 const TopoDS_Edge& edge = TopoDS::Edge( exp.Current() );
212 if ( BRep_Tool::IsClosed( edge, face )) {
213 // initialize myPar1, myPar2 and myParIndex
215 BRep_Tool::UVPoints( edge, face, uv1, uv2 );
216 if ( Abs( uv1.Coord(1) - uv2.Coord(1) ) < Abs( uv1.Coord(2) - uv2.Coord(2) ))
218 myParIndex |= U_periodic;
219 myPar1[0] = surface.FirstUParameter();
220 myPar2[0] = surface.LastUParameter();
223 myParIndex |= V_periodic;
224 myPar1[1] = surface.FirstVParameter();
225 myPar2[1] = surface.LastVParameter();
227 // store seam shape indices, negative if shape encounters twice
228 int edgeID = meshDS->ShapeToIndex( edge );
229 mySeamShapeIds.insert( IsSeamShape( edgeID ) ? -edgeID : edgeID );
230 for ( TopExp_Explorer v( edge, TopAbs_VERTEX ); v.More(); v.Next() ) {
231 int vertexID = meshDS->ShapeToIndex( v.Current() );
232 mySeamShapeIds.insert( IsSeamShape( vertexID ) ? -vertexID : vertexID );
236 // look for a degenerated edge
237 if ( BRep_Tool::Degenerated( edge )) {
238 myDegenShapeIds.insert( meshDS->ShapeToIndex( edge ));
239 for ( TopExp_Explorer v( edge, TopAbs_VERTEX ); v.More(); v.Next() )
240 myDegenShapeIds.insert( meshDS->ShapeToIndex( v.Current() ));
247 //=======================================================================
248 //function : GetNodeUVneedInFaceNode
249 //purpose : Check if inFaceNode argument is necessary for call GetNodeUV(F,..)
250 // Return true if the face is periodic.
251 // If F is Null, answer about subshape set through IsQuadraticSubMesh() or
253 //=======================================================================
255 bool SMESH_MesherHelper::GetNodeUVneedInFaceNode(const TopoDS_Face& F) const
257 if ( F.IsNull() ) return !mySeamShapeIds.empty();
259 if ( !F.IsNull() && !myShape.IsNull() && myShape.IsSame( F ))
260 return !mySeamShapeIds.empty();
263 Handle(Geom_Surface) aSurface = BRep_Tool::Surface( F,loc );
264 if ( !aSurface.IsNull() )
265 return ( aSurface->IsUPeriodic() || aSurface->IsVPeriodic() );
270 //=======================================================================
271 //function : IsMedium
273 //=======================================================================
275 bool SMESH_MesherHelper::IsMedium(const SMDS_MeshNode* node,
276 const SMDSAbs_ElementType typeToCheck)
278 return SMESH_MeshEditor::IsMedium( node, typeToCheck );
281 //=======================================================================
282 //function : GetSubShapeByNode
283 //purpose : Return support shape of a node
284 //=======================================================================
286 TopoDS_Shape SMESH_MesherHelper::GetSubShapeByNode(const SMDS_MeshNode* node,
287 SMESHDS_Mesh* meshDS)
289 int shapeID = node->GetPosition()->GetShapeId();
290 if ( 0 < shapeID && shapeID <= meshDS->MaxShapeIndex() )
291 return meshDS->IndexToShape( shapeID );
293 return TopoDS_Shape();
297 //=======================================================================
298 //function : AddTLinkNode
299 //purpose : add a link in my data structure
300 //=======================================================================
302 void SMESH_MesherHelper::AddTLinkNode(const SMDS_MeshNode* n1,
303 const SMDS_MeshNode* n2,
304 const SMDS_MeshNode* n12)
306 // add new record to map
307 SMESH_TLink link( n1, n2 );
308 myTLinkNodeMap.insert( make_pair(link,n12));
311 //=======================================================================
312 //function : GetUVOnSeam
313 //purpose : Select UV on either of 2 pcurves of a seam edge, closest to the given UV
314 //=======================================================================
316 gp_Pnt2d SMESH_MesherHelper::GetUVOnSeam( const gp_Pnt2d& uv1, const gp_Pnt2d& uv2 ) const
318 gp_Pnt2d result = uv1;
319 for ( int i = U_periodic; i <= V_periodic ; ++i )
321 if ( myParIndex & i )
323 double p1 = uv1.Coord( i );
324 double dp1 = Abs( p1-myPar1[i-1]), dp2 = Abs( p1-myPar2[i-1]);
325 if ( myParIndex == i ||
326 dp1 < ( myPar2[i-1] - myPar2[i-1] ) / 100. ||
327 dp2 < ( myPar2[i-1] - myPar2[i-1] ) / 100. )
329 double p2 = uv2.Coord( i );
330 double p1Alt = ( dp1 < dp2 ) ? myPar2[i-1] : myPar1[i-1];
331 if ( Abs( p2 - p1 ) > Abs( p2 - p1Alt ))
332 result.SetCoord( i, p1Alt );
339 //=======================================================================
340 //function : GetNodeUV
341 //purpose : Return node UV on face
342 //=======================================================================
344 gp_XY SMESH_MesherHelper::GetNodeUV(const TopoDS_Face& F,
345 const SMDS_MeshNode* n,
346 const SMDS_MeshNode* n2,
349 gp_Pnt2d uv( Precision::Infinite(), Precision::Infinite() );
350 const SMDS_PositionPtr Pos = n->GetPosition();
352 if(Pos->GetTypeOfPosition()==SMDS_TOP_FACE)
354 // node has position on face
355 const SMDS_FacePosition* fpos =
356 static_cast<const SMDS_FacePosition*>(n->GetPosition().get());
357 uv.SetCoord(fpos->GetUParameter(),fpos->GetVParameter());
359 uvOK = CheckNodeUV( F, n, uv.ChangeCoord(), 2*BRep_Tool::Tolerance( F ));
361 else if(Pos->GetTypeOfPosition()==SMDS_TOP_EDGE)
363 // node has position on edge => it is needed to find
364 // corresponding edge from face, get pcurve for this
365 // edge and retrieve value from this pcurve
366 const SMDS_EdgePosition* epos =
367 static_cast<const SMDS_EdgePosition*>(n->GetPosition().get());
368 int edgeID = Pos->GetShapeId();
369 TopoDS_Edge E = TopoDS::Edge(GetMeshDS()->IndexToShape(edgeID));
370 double f, l, u = epos->GetUParameter();
371 Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface(E, F, f, l);
372 bool validU = ( f < u && u < l );
374 uv = C2d->Value( u );
377 if ( check || !validU )
378 uvOK = CheckNodeUV( F, n, uv.ChangeCoord(), 2*BRep_Tool::Tolerance( E ),/*force=*/ !validU );
380 // for a node on a seam edge select one of UVs on 2 pcurves
381 if ( n2 && IsSeamShape( edgeID ) )
383 uv = GetUVOnSeam( uv, GetNodeUV( F, n2, 0, check ));
386 { // adjust uv to period
388 Handle(Geom_Surface) S = BRep_Tool::Surface(F,loc);
389 Standard_Boolean isUPeriodic = S->IsUPeriodic();
390 Standard_Boolean isVPeriodic = S->IsVPeriodic();
391 if ( isUPeriodic || isVPeriodic ) {
392 Standard_Real UF,UL,VF,VL;
393 S->Bounds(UF,UL,VF,VL);
395 uv.SetX( uv.X() + ShapeAnalysis::AdjustToPeriod(uv.X(),UF,UL));
397 uv.SetY( uv.Y() + ShapeAnalysis::AdjustToPeriod(uv.Y(),VF,VL));
401 else if(Pos->GetTypeOfPosition()==SMDS_TOP_VERTEX)
403 if ( int vertexID = n->GetPosition()->GetShapeId() ) {
404 const TopoDS_Vertex& V = TopoDS::Vertex(GetMeshDS()->IndexToShape(vertexID));
406 uv = BRep_Tool::Parameters( V, F );
409 catch (Standard_Failure& exc) {
412 for ( TopExp_Explorer vert(F,TopAbs_VERTEX); !uvOK && vert.More(); vert.Next() )
413 uvOK = ( V == vert.Current() );
416 MESSAGE ( "SMESH_MesherHelper::GetNodeUV(); Vertex " << vertexID
417 << " not in face " << GetMeshDS()->ShapeToIndex( F ) );
419 // get UV of a vertex closest to the node
421 gp_Pnt pn = XYZ( n );
422 for ( TopExp_Explorer vert(F,TopAbs_VERTEX); !uvOK && vert.More(); vert.Next() ) {
423 TopoDS_Vertex curV = TopoDS::Vertex( vert.Current() );
424 gp_Pnt p = BRep_Tool::Pnt( curV );
425 double curDist = p.SquareDistance( pn );
426 if ( curDist < dist ) {
428 uv = BRep_Tool::Parameters( curV, F );
429 uvOK = ( dist < DBL_MIN );
435 TopTools_ListIteratorOfListOfShape it( myMesh->GetAncestors( V ));
436 for ( ; it.More(); it.Next() ) {
437 if ( it.Value().ShapeType() == TopAbs_EDGE ) {
438 const TopoDS_Edge & edge = TopoDS::Edge( it.Value() );
440 Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface(edge, F, f, l);
441 if ( !C2d.IsNull() ) {
442 double u = ( V == TopExp::FirstVertex( edge ) ) ? f : l;
443 uv = C2d->Value( u );
451 if ( n2 && IsSeamShape( vertexID ) )
452 uv = GetUVOnSeam( uv, GetNodeUV( F, n2, 0 ));
462 //=======================================================================
463 //function : CheckNodeUV
464 //purpose : Check and fix node UV on a face
465 //=======================================================================
467 bool SMESH_MesherHelper::CheckNodeUV(const TopoDS_Face& F,
468 const SMDS_MeshNode* n,
471 const bool force) const
473 if ( force || !myOkNodePosShapes.count( n->GetPosition()->GetShapeId() ))
475 // check that uv is correct
477 Handle(Geom_Surface) surface = BRep_Tool::Surface( F,loc );
478 gp_Pnt nodePnt = XYZ( n );
479 if ( !loc.IsIdentity() ) nodePnt.Transform( loc.Transformation().Inverted() );
480 if ( Precision::IsInfinite( uv.X() ) ||
481 Precision::IsInfinite( uv.Y() ) ||
482 nodePnt.Distance( surface->Value( uv.X(), uv.Y() )) > tol )
484 // uv incorrect, project the node to surface
485 GeomAPI_ProjectPointOnSurf& projector = GetProjector( F, loc, tol );
486 projector.Perform( nodePnt );
487 if ( !projector.IsDone() || projector.NbPoints() < 1 )
489 MESSAGE( "SMESH_MesherHelper::CheckNodeUV() failed to project" );
492 Quantity_Parameter U,V;
493 projector.LowerDistanceParameters(U,V);
495 if ( nodePnt.Distance( surface->Value( U, V )) > tol )
497 MESSAGE( "SMESH_MesherHelper::CheckNodeUV(), invalid projection" );
501 else if ( uv.Modulus() > numeric_limits<double>::min() )
503 ((SMESH_MesherHelper*) this)->myOkNodePosShapes.insert( n->GetPosition()->GetShapeId() );
509 //=======================================================================
510 //function : GetProjector
511 //purpose : Return projector intitialized by given face without location, which is returned
512 //=======================================================================
514 GeomAPI_ProjectPointOnSurf& SMESH_MesherHelper::GetProjector(const TopoDS_Face& F,
515 TopLoc_Location& loc,
518 Handle(Geom_Surface) surface = BRep_Tool::Surface( F,loc );
519 int faceID = GetMeshDS()->ShapeToIndex( F );
520 TID2Projector& i2proj = const_cast< TID2Projector&>( myFace2Projector );
521 TID2Projector::iterator i_proj = i2proj.find( faceID );
522 if ( i_proj == i2proj.end() )
524 if ( tol == 0 ) tol = BRep_Tool::Tolerance( F );
525 double U1, U2, V1, V2;
526 surface->Bounds(U1, U2, V1, V2);
527 GeomAPI_ProjectPointOnSurf* proj = new GeomAPI_ProjectPointOnSurf();
528 proj->Init( surface, U1, U2, V1, V2, tol );
529 i_proj = i2proj.insert( make_pair( faceID, proj )).first;
531 return *( i_proj->second );
536 gp_XY AverageUV(const gp_XY& uv1, const gp_XY& uv2) { return ( uv1 + uv2 ) / 2.; }
537 gp_XY_FunPtr(Added); // define gp_XY_Added pointer to function calling gp_XY::Added(gp_XY)
538 gp_XY_FunPtr(Subtracted);
541 //=======================================================================
542 //function : applyIn2D
543 //purpose : Perform given operation on two 2d points in parameric space of given surface.
544 // It takes into account period of the surface. Use gp_XY_FunPtr macro
545 // to easily define pointer to function of gp_XY class.
546 //=======================================================================
548 gp_XY SMESH_MesherHelper::applyIn2D(const Handle(Geom_Surface)& surface,
552 const bool resultInPeriod)
554 Standard_Boolean isUPeriodic = surface.IsNull() ? false : surface->IsUPeriodic();
555 Standard_Boolean isVPeriodic = surface.IsNull() ? false : surface->IsVPeriodic();
556 if ( !isUPeriodic && !isVPeriodic )
559 // move uv2 not far than half-period from uv1
561 uv2.X()+(isUPeriodic ? ShapeAnalysis::AdjustByPeriod(uv2.X(),uv1.X(),surface->UPeriod()) :0);
563 uv2.Y()+(isVPeriodic ? ShapeAnalysis::AdjustByPeriod(uv2.Y(),uv1.Y(),surface->VPeriod()) :0);
566 gp_XY res = fun( uv1, gp_XY(u2,v2) );
568 // move result within period
569 if ( resultInPeriod )
571 Standard_Real UF,UL,VF,VL;
572 surface->Bounds(UF,UL,VF,VL);
574 res.SetX( res.X() + ShapeAnalysis::AdjustToPeriod(res.X(),UF,UL));
576 res.SetY( res.Y() + ShapeAnalysis::AdjustToPeriod(res.Y(),VF,VL));
581 //=======================================================================
582 //function : GetMiddleUV
583 //purpose : Return middle UV taking in account surface period
584 //=======================================================================
586 gp_XY SMESH_MesherHelper::GetMiddleUV(const Handle(Geom_Surface)& surface,
590 return applyIn2D( surface, p1, p2, & AverageUV );
593 //=======================================================================
594 //function : GetNodeU
595 //purpose : Return node U on edge
596 //=======================================================================
598 double SMESH_MesherHelper::GetNodeU(const TopoDS_Edge& E,
599 const SMDS_MeshNode* n,
600 const SMDS_MeshNode* inEdgeNode,
604 const SMDS_PositionPtr pos = n->GetPosition();
605 if ( pos->GetTypeOfPosition()==SMDS_TOP_EDGE )
607 const SMDS_EdgePosition* epos = static_cast<const SMDS_EdgePosition*>( pos.get() );
608 param = epos->GetUParameter();
610 else if( pos->GetTypeOfPosition() == SMDS_TOP_VERTEX )
612 if ( inEdgeNode && TopExp::FirstVertex( E ).IsSame( TopExp::LastVertex( E ))) // issue 0020128
615 BRep_Tool::Range( E, f,l );
616 double uInEdge = GetNodeU( E, inEdgeNode );
617 param = ( fabs( uInEdge - f ) < fabs( l - uInEdge )) ? f : l;
621 SMESHDS_Mesh * meshDS = GetMeshDS();
622 int vertexID = pos->GetShapeId();
623 const TopoDS_Vertex& V = TopoDS::Vertex(meshDS->IndexToShape(vertexID));
624 param = BRep_Tool::Parameter( V, E );
629 double tol = BRep_Tool::Tolerance( E );
630 double f,l; BRep_Tool::Range( E, f,l );
631 bool force = ( param < f-tol || param > l+tol );
632 if ( !force && pos->GetTypeOfPosition()==SMDS_TOP_EDGE )
633 force = ( GetMeshDS()->ShapeToIndex( E ) != pos->GetShapeId() );
635 *check = CheckNodeU( E, n, param, 2*tol, force );
640 //=======================================================================
641 //function : CheckNodeU
642 //purpose : Check and fix node U on an edge
643 // Return false if U is bad and could not be fixed
644 //=======================================================================
646 bool SMESH_MesherHelper::CheckNodeU(const TopoDS_Edge& E,
647 const SMDS_MeshNode* n,
651 double* distance) const
653 if ( force || !myOkNodePosShapes.count( n->GetPosition()->GetShapeId() ))
655 // check that u is correct
656 TopLoc_Location loc; double f,l;
657 Handle(Geom_Curve) curve = BRep_Tool::Curve( E,loc,f,l );
658 if ( curve.IsNull() ) // degenerated edge
660 if ( u+tol < f || u-tol > l )
662 double r = Max( 0.5, 1 - tol*n->GetID()); // to get a unique u on edge
668 gp_Pnt nodePnt = SMESH_MeshEditor::TNodeXYZ( n );
669 if ( !loc.IsIdentity() ) nodePnt.Transform( loc.Transformation().Inverted() );
670 double dist = nodePnt.Distance( curve->Value( u ));
671 if ( distance ) *distance = dist;
674 // u incorrect, project the node to the curve
675 GeomAPI_ProjectPointOnCurve projector( nodePnt, curve, f, l );
676 if ( projector.NbPoints() < 1 )
678 MESSAGE( "SMESH_MesherHelper::CheckNodeU() failed to project" );
681 Quantity_Parameter U = projector.LowerDistanceParameter();
683 dist = nodePnt.Distance( curve->Value( U ));
684 if ( distance ) *distance = dist;
687 MESSAGE( "SMESH_MesherHelper::CheckNodeU(), invalid projection" );
692 else if ( fabs( u ) > numeric_limits<double>::min() )
694 ((SMESH_MesherHelper*) this)->myOkNodePosShapes.insert( n->GetPosition()->GetShapeId() );
696 if (( u < f-tol || u > l+tol ) && force )
698 // node is on vertex but is set on periodic but trimmed edge (issue 0020890)
701 // do not use IsPeriodic() as Geom_TrimmedCurve::IsPeriodic () returns false
702 double period = curve->Period();
703 u = ( u < f ) ? u + period : u - period;
705 catch (Standard_Failure& exc)
715 //=======================================================================
716 //function : GetMediumNode
717 //purpose : Return existing or create new medium nodes between given ones
718 //=======================================================================
720 const SMDS_MeshNode* SMESH_MesherHelper::GetMediumNode(const SMDS_MeshNode* n1,
721 const SMDS_MeshNode* n2,
724 // Find existing node
726 SMESH_TLink link(n1,n2);
727 ItTLinkNode itLN = myTLinkNodeMap.find( link );
728 if ( itLN != myTLinkNodeMap.end() ) {
729 return (*itLN).second;
732 // Create medium node
735 SMESHDS_Mesh* meshDS = GetMeshDS();
737 // get type of shape for the new medium node
738 int faceID = -1, edgeID = -1;
739 const SMDS_PositionPtr Pos1 = n1->GetPosition();
740 const SMDS_PositionPtr Pos2 = n2->GetPosition();
742 if( myShape.IsNull() )
744 if( Pos1->GetTypeOfPosition()==SMDS_TOP_FACE ) {
745 faceID = Pos1->GetShapeId();
747 else if( Pos2->GetTypeOfPosition()==SMDS_TOP_FACE ) {
748 faceID = Pos2->GetShapeId();
751 if( Pos1->GetTypeOfPosition()==SMDS_TOP_EDGE ) {
752 edgeID = Pos1->GetShapeId();
754 if( Pos2->GetTypeOfPosition()==SMDS_TOP_EDGE ) {
755 edgeID = Pos2->GetShapeId();
758 // get positions of the given nodes on shapes
759 TopoDS_Edge E; double u [2];
760 TopoDS_Face F; gp_XY uv[2];
761 bool uvOK[2] = { false, false };
762 TopAbs_ShapeEnum shapeType = myShape.IsNull() ? TopAbs_SHAPE : myShape.ShapeType();
763 if ( faceID>0 || shapeType == TopAbs_FACE)
765 if( myShape.IsNull() )
766 F = TopoDS::Face(meshDS->IndexToShape(faceID));
768 F = TopoDS::Face(myShape);
771 uv[0] = GetNodeUV(F,n1,n2, force3d ? 0 : &uvOK[0]);
772 uv[1] = GetNodeUV(F,n2,n1, force3d ? 0 : &uvOK[1]);
774 else if (edgeID>0 || shapeType == TopAbs_EDGE)
776 if ( Pos1->GetTypeOfPosition()==SMDS_TOP_EDGE &&
777 Pos2->GetTypeOfPosition()==SMDS_TOP_EDGE &&
778 Pos1->GetShapeId() != Pos2->GetShapeId() ) // issue 0021006
779 return getMediumNodeOnComposedWire(n1,n2,force3d);
781 if( myShape.IsNull() )
782 E = TopoDS::Edge(meshDS->IndexToShape(edgeID));
784 E = TopoDS::Edge(myShape);
787 u[0] = GetNodeU(E,n1,n2, force3d ? 0 : &uvOK[0]);
788 u[1] = GetNodeU(E,n2,n1, force3d ? 0 : &uvOK[1]);
792 // we try to create medium node using UV parameters of
793 // nodes, else - medium between corresponding 3d points
796 if ( uvOK[0] && uvOK[1] )
798 if ( IsDegenShape( Pos1->GetShapeId() ))
799 if ( myParIndex & U_periodic ) uv[0].SetCoord( 1, uv[1].Coord( 1 ));
800 else uv[0].SetCoord( 2, uv[1].Coord( 2 ));
801 else if ( IsDegenShape( Pos2->GetShapeId() ))
802 if ( myParIndex & U_periodic ) uv[1].SetCoord( 1, uv[0].Coord( 1 ));
803 else uv[1].SetCoord( 2, uv[0].Coord( 2 ));
806 Handle(Geom_Surface) S = BRep_Tool::Surface(F,loc);
807 gp_XY UV = GetMiddleUV( S, uv[0], uv[1] );
808 gp_Pnt P = S->Value( UV.X(), UV.Y() ).Transformed(loc);
809 n12 = meshDS->AddNode(P.X(), P.Y(), P.Z());
810 meshDS->SetNodeOnFace(n12, faceID, UV.X(), UV.Y());
811 myTLinkNodeMap.insert(make_pair(link,n12));
815 else if ( !E.IsNull() )
818 Handle(Geom_Curve) C = BRep_Tool::Curve(E, f, l);
821 Standard_Boolean isPeriodic = C->IsPeriodic();
824 Standard_Real Period = C->Period();
825 Standard_Real p = u[1]+ShapeAnalysis::AdjustByPeriod(u[1],u[0],Period);
826 Standard_Real pmid = (u[0]+p)/2.;
827 U = pmid+ShapeAnalysis::AdjustToPeriod(pmid,C->FirstParameter(),C->LastParameter());
832 gp_Pnt P = C->Value( U );
833 n12 = meshDS->AddNode(P.X(), P.Y(), P.Z());
834 meshDS->SetNodeOnEdge(n12, edgeID, U);
835 myTLinkNodeMap.insert(make_pair(link,n12));
841 double x = ( n1->X() + n2->X() )/2.;
842 double y = ( n1->Y() + n2->Y() )/2.;
843 double z = ( n1->Z() + n2->Z() )/2.;
844 n12 = meshDS->AddNode(x,y,z);
847 gp_XY UV = ( uv[0] + uv[1] ) / 2.;
848 CheckNodeUV( F, n12, UV, 2*BRep_Tool::Tolerance( F ), /*force=*/true);
849 meshDS->SetNodeOnFace(n12, faceID, UV.X(), UV.Y() );
851 else if ( !E.IsNull() )
853 double U = ( u[0] + u[1] ) / 2.;
854 CheckNodeU( E, n12, U, 2*BRep_Tool::Tolerance( E ), /*force=*/true);
855 meshDS->SetNodeOnEdge(n12, edgeID, U);
857 else if ( myShapeID > 0 )
859 meshDS->SetNodeInVolume(n12, myShapeID);
861 myTLinkNodeMap.insert( make_pair( link, n12 ));
865 //================================================================================
867 * \brief Makes a medium node if nodes reside different edges
869 //================================================================================
871 const SMDS_MeshNode* SMESH_MesherHelper::getMediumNodeOnComposedWire(const SMDS_MeshNode* n1,
872 const SMDS_MeshNode* n2,
875 gp_Pnt middle = 0.5 * XYZ(n1) + 0.5 * XYZ(n2);
876 SMDS_MeshNode* n12 = AddNode( middle.X(), middle.Y(), middle.Z() );
878 // To find position on edge and 3D position for n12,
879 // project <middle> to 2 edges and select projection most close to <middle>
881 double u = 0, distMiddleProj = Precision::Infinite();
883 TopoDS_Edge edges[2];
884 for ( int is2nd = 0; is2nd < 2; ++is2nd )
887 const SMDS_MeshNode* n = is2nd ? n2 : n1;
888 TopoDS_Shape shape = GetSubShapeByNode( n, GetMeshDS() );
889 if ( shape.IsNull() || shape.ShapeType() != TopAbs_EDGE )
892 // project to get U of projection and distance from middle to projection
893 TopoDS_Edge edge = edges[ is2nd ] = TopoDS::Edge( shape );
894 double node2MiddleDist = middle.Distance( XYZ(n) );
895 double foundU = GetNodeU( edge, n ), foundDist = node2MiddleDist;
896 CheckNodeU( edge, n12, foundU, 2*BRep_Tool::Tolerance(edge), /*force=*/true, &foundDist );
897 if ( foundDist < node2MiddleDist )
899 distMiddleProj = foundDist;
904 if ( Precision::IsInfinite( distMiddleProj ))
906 // both projections failed; set n12 on the edge of n1 with U of a common vertex
907 TopoDS_Vertex vCommon;
908 if ( TopExp::CommonVertex( edges[0], edges[1], vCommon ))
909 u = BRep_Tool::Parameter( vCommon, edges[0] );
912 double f,l, u0 = GetNodeU( edges[0], n1 );
913 BRep_Tool::Range( edges[0],f,l );
914 u = ( fabs(u0-f) < fabs(u0-l) ) ? f : l;
920 // move n12 to position of a successfull projection
921 double tol = BRep_Tool::Tolerance(edges[ iOkEdge ]);
922 if ( !force3d && distMiddleProj > 2*tol )
924 TopLoc_Location loc; double f,l;
925 Handle(Geom_Curve) curve = BRep_Tool::Curve( edges[iOkEdge],loc,f,l );
926 gp_Pnt p = curve->Value( u );
927 GetMeshDS()->MoveNode( n12, p.X(), p.Y(), p.Z() );
930 GetMeshDS()->SetNodeOnEdge(n12, edges[iOkEdge], u);
932 myTLinkNodeMap.insert( make_pair( SMESH_TLink(n1,n2), n12 ));
937 //=======================================================================
939 //purpose : Creates a node
940 //=======================================================================
942 SMDS_MeshNode* SMESH_MesherHelper::AddNode(double x, double y, double z, int ID)
944 SMESHDS_Mesh * meshDS = GetMeshDS();
945 SMDS_MeshNode* node = 0;
947 node = meshDS->AddNodeWithID( x, y, z, ID );
949 node = meshDS->AddNode( x, y, z );
950 if ( mySetElemOnShape && myShapeID > 0 ) {
951 switch ( myShape.ShapeType() ) {
952 case TopAbs_SOLID: meshDS->SetNodeInVolume( node, myShapeID); break;
953 case TopAbs_SHELL: meshDS->SetNodeInVolume( node, myShapeID); break;
954 case TopAbs_FACE: meshDS->SetNodeOnFace( node, myShapeID); break;
955 case TopAbs_EDGE: meshDS->SetNodeOnEdge( node, myShapeID); break;
956 case TopAbs_VERTEX: meshDS->SetNodeOnVertex( node, myShapeID); break;
963 //=======================================================================
965 //purpose : Creates quadratic or linear edge
966 //=======================================================================
968 SMDS_MeshEdge* SMESH_MesherHelper::AddEdge(const SMDS_MeshNode* n1,
969 const SMDS_MeshNode* n2,
973 SMESHDS_Mesh * meshDS = GetMeshDS();
975 SMDS_MeshEdge* edge = 0;
976 if (myCreateQuadratic) {
977 const SMDS_MeshNode* n12 = GetMediumNode(n1,n2,force3d);
979 edge = meshDS->AddEdgeWithID(n1, n2, n12, id);
981 edge = meshDS->AddEdge(n1, n2, n12);
985 edge = meshDS->AddEdgeWithID(n1, n2, id);
987 edge = meshDS->AddEdge(n1, n2);
990 if ( mySetElemOnShape && myShapeID > 0 )
991 meshDS->SetMeshElementOnShape( edge, myShapeID );
996 //=======================================================================
998 //purpose : Creates quadratic or linear triangle
999 //=======================================================================
1001 SMDS_MeshFace* SMESH_MesherHelper::AddFace(const SMDS_MeshNode* n1,
1002 const SMDS_MeshNode* n2,
1003 const SMDS_MeshNode* n3,
1007 SMESHDS_Mesh * meshDS = GetMeshDS();
1008 SMDS_MeshFace* elem = 0;
1010 if( n1==n2 || n2==n3 || n3==n1 )
1013 if(!myCreateQuadratic) {
1015 elem = meshDS->AddFaceWithID(n1, n2, n3, id);
1017 elem = meshDS->AddFace(n1, n2, n3);
1020 const SMDS_MeshNode* n12 = GetMediumNode(n1,n2,force3d);
1021 const SMDS_MeshNode* n23 = GetMediumNode(n2,n3,force3d);
1022 const SMDS_MeshNode* n31 = GetMediumNode(n3,n1,force3d);
1025 elem = meshDS->AddFaceWithID(n1, n2, n3, n12, n23, n31, id);
1027 elem = meshDS->AddFace(n1, n2, n3, n12, n23, n31);
1029 if ( mySetElemOnShape && myShapeID > 0 )
1030 meshDS->SetMeshElementOnShape( elem, myShapeID );
1035 //=======================================================================
1036 //function : AddFace
1037 //purpose : Creates quadratic or linear quadrangle
1038 //=======================================================================
1040 SMDS_MeshFace* SMESH_MesherHelper::AddFace(const SMDS_MeshNode* n1,
1041 const SMDS_MeshNode* n2,
1042 const SMDS_MeshNode* n3,
1043 const SMDS_MeshNode* n4,
1047 SMESHDS_Mesh * meshDS = GetMeshDS();
1048 SMDS_MeshFace* elem = 0;
1051 return AddFace(n1,n3,n4,id,force3d);
1054 return AddFace(n1,n2,n4,id,force3d);
1057 return AddFace(n1,n2,n3,id,force3d);
1060 return AddFace(n1,n2,n4,id,force3d);
1063 return AddFace(n1,n2,n3,id,force3d);
1066 return AddFace(n1,n2,n3,id,force3d);
1069 if(!myCreateQuadratic) {
1071 elem = meshDS->AddFaceWithID(n1, n2, n3, n4, id);
1073 elem = meshDS->AddFace(n1, n2, n3, n4);
1076 const SMDS_MeshNode* n12 = GetMediumNode(n1,n2,force3d);
1077 const SMDS_MeshNode* n23 = GetMediumNode(n2,n3,force3d);
1078 const SMDS_MeshNode* n34 = GetMediumNode(n3,n4,force3d);
1079 const SMDS_MeshNode* n41 = GetMediumNode(n4,n1,force3d);
1082 elem = meshDS->AddFaceWithID(n1, n2, n3, n4, n12, n23, n34, n41, id);
1084 elem = meshDS->AddFace(n1, n2, n3, n4, n12, n23, n34, n41);
1086 if ( mySetElemOnShape && myShapeID > 0 )
1087 meshDS->SetMeshElementOnShape( elem, myShapeID );
1092 //=======================================================================
1093 //function : AddVolume
1094 //purpose : Creates quadratic or linear prism
1095 //=======================================================================
1097 SMDS_MeshVolume* SMESH_MesherHelper::AddVolume(const SMDS_MeshNode* n1,
1098 const SMDS_MeshNode* n2,
1099 const SMDS_MeshNode* n3,
1100 const SMDS_MeshNode* n4,
1101 const SMDS_MeshNode* n5,
1102 const SMDS_MeshNode* n6,
1106 SMESHDS_Mesh * meshDS = GetMeshDS();
1107 SMDS_MeshVolume* elem = 0;
1108 if(!myCreateQuadratic) {
1110 elem = meshDS->AddVolumeWithID(n1, n2, n3, n4, n5, n6, id);
1112 elem = meshDS->AddVolume(n1, n2, n3, n4, n5, n6);
1115 const SMDS_MeshNode* n12 = GetMediumNode(n1,n2,force3d);
1116 const SMDS_MeshNode* n23 = GetMediumNode(n2,n3,force3d);
1117 const SMDS_MeshNode* n31 = GetMediumNode(n3,n1,force3d);
1119 const SMDS_MeshNode* n45 = GetMediumNode(n4,n5,force3d);
1120 const SMDS_MeshNode* n56 = GetMediumNode(n5,n6,force3d);
1121 const SMDS_MeshNode* n64 = GetMediumNode(n6,n4,force3d);
1123 const SMDS_MeshNode* n14 = GetMediumNode(n1,n4,force3d);
1124 const SMDS_MeshNode* n25 = GetMediumNode(n2,n5,force3d);
1125 const SMDS_MeshNode* n36 = GetMediumNode(n3,n6,force3d);
1128 elem = meshDS->AddVolumeWithID(n1, n2, n3, n4, n5, n6,
1129 n12, n23, n31, n45, n56, n64, n14, n25, n36, id);
1131 elem = meshDS->AddVolume(n1, n2, n3, n4, n5, n6,
1132 n12, n23, n31, n45, n56, n64, n14, n25, n36);
1134 if ( mySetElemOnShape && myShapeID > 0 )
1135 meshDS->SetMeshElementOnShape( elem, myShapeID );
1140 //=======================================================================
1141 //function : AddVolume
1142 //purpose : Creates quadratic or linear tetrahedron
1143 //=======================================================================
1145 SMDS_MeshVolume* SMESH_MesherHelper::AddVolume(const SMDS_MeshNode* n1,
1146 const SMDS_MeshNode* n2,
1147 const SMDS_MeshNode* n3,
1148 const SMDS_MeshNode* n4,
1152 SMESHDS_Mesh * meshDS = GetMeshDS();
1153 SMDS_MeshVolume* elem = 0;
1154 if(!myCreateQuadratic) {
1156 elem = meshDS->AddVolumeWithID(n1, n2, n3, n4, id);
1158 elem = meshDS->AddVolume(n1, n2, n3, n4);
1161 const SMDS_MeshNode* n12 = GetMediumNode(n1,n2,force3d);
1162 const SMDS_MeshNode* n23 = GetMediumNode(n2,n3,force3d);
1163 const SMDS_MeshNode* n31 = GetMediumNode(n3,n1,force3d);
1165 const SMDS_MeshNode* n14 = GetMediumNode(n1,n4,force3d);
1166 const SMDS_MeshNode* n24 = GetMediumNode(n2,n4,force3d);
1167 const SMDS_MeshNode* n34 = GetMediumNode(n3,n4,force3d);
1170 elem = meshDS->AddVolumeWithID(n1, n2, n3, n4, n12, n23, n31, n14, n24, n34, id);
1172 elem = meshDS->AddVolume(n1, n2, n3, n4, n12, n23, n31, n14, n24, n34);
1174 if ( mySetElemOnShape && myShapeID > 0 )
1175 meshDS->SetMeshElementOnShape( elem, myShapeID );
1180 //=======================================================================
1181 //function : AddVolume
1182 //purpose : Creates quadratic or linear pyramid
1183 //=======================================================================
1185 SMDS_MeshVolume* SMESH_MesherHelper::AddVolume(const SMDS_MeshNode* n1,
1186 const SMDS_MeshNode* n2,
1187 const SMDS_MeshNode* n3,
1188 const SMDS_MeshNode* n4,
1189 const SMDS_MeshNode* n5,
1193 SMDS_MeshVolume* elem = 0;
1194 if(!myCreateQuadratic) {
1196 elem = GetMeshDS()->AddVolumeWithID(n1, n2, n3, n4, n5, id);
1198 elem = GetMeshDS()->AddVolume(n1, n2, n3, n4, n5);
1201 const SMDS_MeshNode* n12 = GetMediumNode(n1,n2,force3d);
1202 const SMDS_MeshNode* n23 = GetMediumNode(n2,n3,force3d);
1203 const SMDS_MeshNode* n34 = GetMediumNode(n3,n4,force3d);
1204 const SMDS_MeshNode* n41 = GetMediumNode(n4,n1,force3d);
1206 const SMDS_MeshNode* n15 = GetMediumNode(n1,n5,force3d);
1207 const SMDS_MeshNode* n25 = GetMediumNode(n2,n5,force3d);
1208 const SMDS_MeshNode* n35 = GetMediumNode(n3,n5,force3d);
1209 const SMDS_MeshNode* n45 = GetMediumNode(n4,n5,force3d);
1212 elem = GetMeshDS()->AddVolumeWithID ( n1, n2, n3, n4, n5,
1217 elem = GetMeshDS()->AddVolume( n1, n2, n3, n4, n5,
1219 n15, n25, n35, n45);
1221 if ( mySetElemOnShape && myShapeID > 0 )
1222 GetMeshDS()->SetMeshElementOnShape( elem, myShapeID );
1227 //=======================================================================
1228 //function : AddVolume
1229 //purpose : Creates quadratic or linear hexahedron
1230 //=======================================================================
1232 SMDS_MeshVolume* SMESH_MesherHelper::AddVolume(const SMDS_MeshNode* n1,
1233 const SMDS_MeshNode* n2,
1234 const SMDS_MeshNode* n3,
1235 const SMDS_MeshNode* n4,
1236 const SMDS_MeshNode* n5,
1237 const SMDS_MeshNode* n6,
1238 const SMDS_MeshNode* n7,
1239 const SMDS_MeshNode* n8,
1243 SMESHDS_Mesh * meshDS = GetMeshDS();
1244 SMDS_MeshVolume* elem = 0;
1245 if(!myCreateQuadratic) {
1247 elem = meshDS->AddVolumeWithID(n1, n2, n3, n4, n5, n6, n7, n8, id);
1249 elem = meshDS->AddVolume(n1, n2, n3, n4, n5, n6, n7, n8);
1252 const SMDS_MeshNode* n12 = GetMediumNode(n1,n2,force3d);
1253 const SMDS_MeshNode* n23 = GetMediumNode(n2,n3,force3d);
1254 const SMDS_MeshNode* n34 = GetMediumNode(n3,n4,force3d);
1255 const SMDS_MeshNode* n41 = GetMediumNode(n4,n1,force3d);
1257 const SMDS_MeshNode* n56 = GetMediumNode(n5,n6,force3d);
1258 const SMDS_MeshNode* n67 = GetMediumNode(n6,n7,force3d);
1259 const SMDS_MeshNode* n78 = GetMediumNode(n7,n8,force3d);
1260 const SMDS_MeshNode* n85 = GetMediumNode(n8,n5,force3d);
1262 const SMDS_MeshNode* n15 = GetMediumNode(n1,n5,force3d);
1263 const SMDS_MeshNode* n26 = GetMediumNode(n2,n6,force3d);
1264 const SMDS_MeshNode* n37 = GetMediumNode(n3,n7,force3d);
1265 const SMDS_MeshNode* n48 = GetMediumNode(n4,n8,force3d);
1268 elem = meshDS->AddVolumeWithID(n1, n2, n3, n4, n5, n6, n7, n8,
1269 n12, n23, n34, n41, n56, n67,
1270 n78, n85, n15, n26, n37, n48, id);
1272 elem = meshDS->AddVolume(n1, n2, n3, n4, n5, n6, n7, n8,
1273 n12, n23, n34, n41, n56, n67,
1274 n78, n85, n15, n26, n37, n48);
1276 if ( mySetElemOnShape && myShapeID > 0 )
1277 meshDS->SetMeshElementOnShape( elem, myShapeID );
1282 //=======================================================================
1283 //function : LoadNodeColumns
1284 //purpose : Load nodes bound to face into a map of node columns
1285 //=======================================================================
1287 bool SMESH_MesherHelper::LoadNodeColumns(TParam2ColumnMap & theParam2ColumnMap,
1288 const TopoDS_Face& theFace,
1289 const TopoDS_Edge& theBaseEdge,
1290 SMESHDS_Mesh* theMesh)
1292 SMESHDS_SubMesh* faceSubMesh = theMesh->MeshElements( theFace );
1293 if ( !faceSubMesh || faceSubMesh->NbElements() == 0 )
1296 // get nodes on theBaseEdge sorted by param on edge and initialize theParam2ColumnMap with them
1298 map< double, const SMDS_MeshNode*> sortedBaseNodes;
1299 if ( !SMESH_Algo::GetSortedNodesOnEdge( theMesh, theBaseEdge,/*noMedium=*/true, sortedBaseNodes)
1300 || sortedBaseNodes.size() < 2 )
1303 int nbRows = faceSubMesh->NbElements() / ( sortedBaseNodes.size()-1 ) + 1;
1304 map< double, const SMDS_MeshNode*>::iterator u_n = sortedBaseNodes.begin();
1305 double f = u_n->first, range = sortedBaseNodes.rbegin()->first - f;
1306 for ( ; u_n != sortedBaseNodes.end(); u_n++ )
1308 double par = ( u_n->first - f ) / range;
1309 vector<const SMDS_MeshNode*>& nCol = theParam2ColumnMap[ par ];
1310 nCol.resize( nbRows );
1311 nCol[0] = u_n->second;
1314 // fill theParam2ColumnMap column by column by passing from nodes on
1315 // theBaseEdge up via mesh faces on theFace
1317 TParam2ColumnMap::iterator par_nVec_2 = theParam2ColumnMap.begin();
1318 TParam2ColumnMap::iterator par_nVec_1 = par_nVec_2++;
1319 TIDSortedElemSet emptySet, avoidSet;
1320 for ( ; par_nVec_2 != theParam2ColumnMap.end(); ++par_nVec_1, ++par_nVec_2 )
1322 vector<const SMDS_MeshNode*>& nCol1 = par_nVec_1->second;
1323 vector<const SMDS_MeshNode*>& nCol2 = par_nVec_2->second;
1325 int i1, i2, iRow = 0;
1326 const SMDS_MeshNode *n1 = nCol1[0], *n2 = nCol2[0];
1327 // find face sharing node n1 and n2 and belonging to faceSubMesh
1328 while ( const SMDS_MeshElement* face =
1329 SMESH_MeshEditor::FindFaceInSet( n1, n2, emptySet, avoidSet, &i1, &i2))
1331 if ( faceSubMesh->Contains( face ))
1333 int nbNodes = face->IsQuadratic() ? face->NbNodes()/2 : face->NbNodes();
1336 n1 = face->GetNode( (i2+2) % 4 ); // opposite corner of quadrangle face
1337 n2 = face->GetNode( (i1+2) % 4 );
1338 if ( ++iRow >= nbRows )
1344 avoidSet.insert( face );
1346 if ( iRow + 1 < nbRows ) // compact if necessary
1347 nCol1.resize( iRow + 1 ), nCol2.resize( iRow + 1 );
1352 //=======================================================================
1353 //function : NbAncestors
1354 //purpose : Return number of unique ancestors of the shape
1355 //=======================================================================
1357 int SMESH_MesherHelper::NbAncestors(const TopoDS_Shape& shape,
1358 const SMESH_Mesh& mesh,
1359 TopAbs_ShapeEnum ancestorType/*=TopAbs_SHAPE*/)
1361 TopTools_MapOfShape ancestors;
1362 TopTools_ListIteratorOfListOfShape ansIt( mesh.GetAncestors(shape) );
1363 for ( ; ansIt.More(); ansIt.Next() ) {
1364 if ( ancestorType == TopAbs_SHAPE || ansIt.Value().ShapeType() == ancestorType )
1365 ancestors.Add( ansIt.Value() );
1367 return ancestors.Extent();
1370 //=======================================================================
1371 //function : GetSubShapeOri
1372 //purpose : Return orientation of sub-shape in the main shape
1373 //=======================================================================
1375 TopAbs_Orientation SMESH_MesherHelper::GetSubShapeOri(const TopoDS_Shape& shape,
1376 const TopoDS_Shape& subShape)
1378 TopAbs_Orientation ori = TopAbs_Orientation(-1);
1379 if ( !shape.IsNull() && !subShape.IsNull() )
1381 TopExp_Explorer e( shape, subShape.ShapeType() );
1382 if ( shape.Orientation() >= TopAbs_INTERNAL ) // TopAbs_INTERNAL or TopAbs_EXTERNAL
1383 e.Init( shape.Oriented(TopAbs_FORWARD), subShape.ShapeType() );
1384 for ( ; e.More(); e.Next())
1385 if ( subShape.IsSame( e.Current() ))
1388 ori = e.Current().Orientation();
1393 //=======================================================================
1394 //function : IsSubShape
1396 //=======================================================================
1398 bool SMESH_MesherHelper::IsSubShape( const TopoDS_Shape& shape,
1399 const TopoDS_Shape& mainShape )
1401 if ( !shape.IsNull() && !mainShape.IsNull() )
1403 for ( TopExp_Explorer exp( mainShape, shape.ShapeType());
1406 if ( shape.IsSame( exp.Current() ))
1409 SCRUTE((shape.IsNull()));
1410 SCRUTE((mainShape.IsNull()));
1414 //=======================================================================
1415 //function : IsSubShape
1417 //=======================================================================
1419 bool SMESH_MesherHelper::IsSubShape( const TopoDS_Shape& shape, SMESH_Mesh* aMesh )
1421 if ( shape.IsNull() || !aMesh )
1424 aMesh->GetMeshDS()->ShapeToIndex( shape ) ||
1426 shape.ShapeType() == TopAbs_COMPOUND && aMesh->GetMeshDS()->IsGroupOfSubShapes( shape );
1429 //=======================================================================
1430 //function : IsQuadraticMesh
1431 //purpose : Check mesh without geometry for: if all elements on this shape are quadratic,
1432 // quadratic elements will be created.
1433 // Used then generated 3D mesh without geometry.
1434 //=======================================================================
1436 SMESH_MesherHelper:: MType SMESH_MesherHelper::IsQuadraticMesh()
1438 int NbAllEdgsAndFaces=0;
1439 int NbQuadFacesAndEdgs=0;
1440 int NbFacesAndEdges=0;
1441 //All faces and edges
1442 NbAllEdgsAndFaces = myMesh->NbEdges() + myMesh->NbFaces();
1444 //Quadratic faces and edges
1445 NbQuadFacesAndEdgs = myMesh->NbEdges(ORDER_QUADRATIC) + myMesh->NbFaces(ORDER_QUADRATIC);
1447 //Linear faces and edges
1448 NbFacesAndEdges = myMesh->NbEdges(ORDER_LINEAR) + myMesh->NbFaces(ORDER_LINEAR);
1450 if (NbAllEdgsAndFaces == NbQuadFacesAndEdgs) {
1452 return SMESH_MesherHelper::QUADRATIC;
1454 else if (NbAllEdgsAndFaces == NbFacesAndEdges) {
1456 return SMESH_MesherHelper::LINEAR;
1459 //Mesh with both type of elements
1460 return SMESH_MesherHelper::COMP;
1463 //=======================================================================
1464 //function : GetOtherParam
1465 //purpose : Return an alternative parameter for a node on seam
1466 //=======================================================================
1468 double SMESH_MesherHelper::GetOtherParam(const double param) const
1470 int i = myParIndex & U_periodic ? 0 : 1;
1471 return fabs(param-myPar1[i]) < fabs(param-myPar2[i]) ? myPar2[i] : myPar1[i];
1474 //#include <Perf_Meter.hxx>
1476 //=======================================================================
1477 namespace { // Structures used by FixQuadraticElements()
1478 //=======================================================================
1480 #define __DMP__(txt) \
1482 #define MSG(txt) __DMP__(txt<<endl)
1483 #define MSGBEG(txt) __DMP__(txt)
1485 //const double straightTol2 = 1e-33; // to detect straing links
1486 bool isStraightLink(double linkLen2, double middleNodeMove2)
1488 // straight if <node move> < 1/15 * <link length>
1489 return middleNodeMove2 < 1/15./15. * linkLen2;
1493 // ---------------------------------------
1495 * \brief Quadratic link knowing its faces
1497 struct QLink: public SMESH_TLink
1499 const SMDS_MeshNode* _mediumNode;
1500 mutable vector<const QFace* > _faces;
1501 mutable gp_Vec _nodeMove;
1502 mutable int _nbMoves;
1504 QLink(const SMDS_MeshNode* n1, const SMDS_MeshNode* n2, const SMDS_MeshNode* nm):
1505 SMESH_TLink( n1,n2 ), _mediumNode(nm), _nodeMove(0,0,0), _nbMoves(0) {
1507 //if ( MediumPos() != SMDS_TOP_3DSPACE )
1508 _nodeMove = MediumPnt() - MiddlePnt();
1510 void SetContinuesFaces() const;
1511 const QFace* GetContinuesFace( const QFace* face ) const;
1512 bool OnBoundary() const;
1513 gp_XYZ MiddlePnt() const { return ( XYZ( node1() ) + XYZ( node2() )) / 2.; }
1514 gp_XYZ MediumPnt() const { return XYZ( _mediumNode ); }
1516 SMDS_TypeOfPosition MediumPos() const
1517 { return _mediumNode->GetPosition()->GetTypeOfPosition(); }
1518 SMDS_TypeOfPosition EndPos(bool isSecond) const
1519 { return (isSecond ? node2() : node1())->GetPosition()->GetTypeOfPosition(); }
1520 const SMDS_MeshNode* EndPosNode(SMDS_TypeOfPosition pos) const
1521 { return EndPos(0) == pos ? node1() : EndPos(1) == pos ? node2() : 0; }
1523 void Move(const gp_Vec& move, bool sum=false) const
1524 { _nodeMove += move; _nbMoves += sum ? (_nbMoves==0) : 1; }
1525 gp_XYZ Move() const { return _nodeMove.XYZ() / _nbMoves; }
1526 bool IsMoved() const { return (_nbMoves > 0 && !IsStraight()); }
1527 bool IsStraight() const
1528 { return isStraightLink( (XYZ(node1())-XYZ(node2())).SquareModulus(),
1529 _nodeMove.SquareMagnitude());
1531 bool operator<(const QLink& other) const {
1532 return (node1()->GetID() == other.node1()->GetID() ?
1533 node2()->GetID() < other.node2()->GetID() :
1534 node1()->GetID() < other.node1()->GetID());
1536 struct PtrComparator {
1537 bool operator() (const QLink* l1, const QLink* l2 ) const { return *l1 < *l2; }
1540 // ---------------------------------------------------------
1542 * \brief Link in the chain of links; it connects two faces
1546 const QLink* _qlink;
1547 mutable const QFace* _qfaces[2];
1549 TChainLink(const QLink* qlink=0):_qlink(qlink) {
1550 _qfaces[0] = _qfaces[1] = 0;
1552 void SetFace(const QFace* face) const { int iF = _qfaces[0] ? 1 : 0; _qfaces[iF]=face; }
1554 bool IsBoundary() const { return !_qfaces[1]; }
1556 void RemoveFace( const QFace* face ) const
1557 { _qfaces[(face == _qfaces[1])] = 0; if (!_qfaces[0]) std::swap(_qfaces[0],_qfaces[1]); }
1559 const QFace* NextFace( const QFace* f ) const
1560 { return _qfaces[0]==f ? _qfaces[1] : _qfaces[0]; }
1562 const SMDS_MeshNode* NextNode( const SMDS_MeshNode* n ) const
1563 { return n == _qlink->node1() ? _qlink->node2() : _qlink->node1(); }
1565 bool operator<(const TChainLink& other) const { return *_qlink < *other._qlink; }
1567 operator bool() const { return (_qlink); }
1569 const QLink* operator->() const { return _qlink; }
1571 gp_Vec Normal() const;
1573 // --------------------------------------------------------------------
1574 typedef list< TChainLink > TChain;
1575 typedef set < TChainLink > TLinkSet;
1576 typedef TLinkSet::const_iterator TLinkInSet;
1578 const int theFirstStep = 5;
1580 enum { ERR_OK, ERR_TRI, ERR_PRISM, ERR_UNKNOWN }; // errors of QFace::GetLinkChain()
1581 // --------------------------------------------------------------------
1583 * \brief Face shared by two volumes and bound by QLinks
1585 struct QFace: public TIDSortedElemSet
1587 mutable const SMDS_MeshElement* _volumes[2];
1588 mutable vector< const QLink* > _sides;
1589 mutable bool _sideIsAdded[4]; // added in chain of links
1592 mutable const SMDS_MeshElement* _face;
1595 QFace( const vector< const QLink*>& links, const SMDS_MeshElement* face=0 );
1597 void SetVolume(const SMDS_MeshElement* v) const { _volumes[ _volumes[0] ? 1 : 0 ] = v; }
1599 int NbVolumes() const { return !_volumes[0] ? 0 : !_volumes[1] ? 1 : 2; }
1601 void AddSelfToLinks() const {
1602 for ( int i = 0; i < _sides.size(); ++i )
1603 _sides[i]->_faces.push_back( this );
1605 int LinkIndex( const QLink* side ) const {
1606 for (int i=0; i<_sides.size(); ++i ) if ( _sides[i] == side ) return i;
1609 bool GetLinkChain( int iSide, TChain& chain, SMDS_TypeOfPosition pos, int& err) const;
1611 bool GetLinkChain( TChainLink& link, TChain& chain, SMDS_TypeOfPosition pos, int& err) const
1613 int i = LinkIndex( link._qlink );
1614 if ( i < 0 ) return true;
1615 _sideIsAdded[i] = true;
1616 link.SetFace( this );
1617 // continue from opposite link
1618 return GetLinkChain( (i+2)%_sides.size(), chain, pos, err );
1620 bool IsBoundary() const { return !_volumes[1]; }
1622 bool Contains( const SMDS_MeshNode* node ) const { return count(node); }
1624 TLinkInSet GetBoundaryLink( const TLinkSet& links,
1625 const TChainLink& avoidLink,
1626 TLinkInSet * notBoundaryLink = 0,
1627 const SMDS_MeshNode* nodeToContain = 0,
1628 bool * isAdjacentUsed = 0,
1629 int nbRecursionsLeft = -1) const;
1631 TLinkInSet GetLinkByNode( const TLinkSet& links,
1632 const TChainLink& avoidLink,
1633 const SMDS_MeshNode* nodeToContain) const;
1635 const SMDS_MeshNode* GetNodeInFace() const {
1636 for ( int iL = 0; iL < _sides.size(); ++iL )
1637 if ( _sides[iL]->MediumPos() == SMDS_TOP_FACE ) return _sides[iL]->_mediumNode;
1641 gp_Vec LinkNorm(const int i, SMESH_MesherHelper* theFaceHelper=0) const;
1643 double MoveByBoundary( const TChainLink& theLink,
1644 const gp_Vec& theRefVec,
1645 const TLinkSet& theLinks,
1646 SMESH_MesherHelper* theFaceHelper=0,
1647 const double thePrevLen=0,
1648 const int theStep=theFirstStep,
1649 gp_Vec* theLinkNorm=0,
1650 double theSign=1.0) const;
1653 //================================================================================
1655 * \brief Dump QLink and QFace
1657 ostream& operator << (ostream& out, const QLink& l)
1659 out <<"QLink nodes: "
1660 << l.node1()->GetID() << " - "
1661 << l._mediumNode->GetID() << " - "
1662 << l.node2()->GetID() << endl;
1665 ostream& operator << (ostream& out, const QFace& f)
1667 out <<"QFace nodes: "/*<< &f << " "*/;
1668 for ( TIDSortedElemSet::const_iterator n = f.begin(); n != f.end(); ++n )
1669 out << (*n)->GetID() << " ";
1670 out << " \tvolumes: "
1671 << (f._volumes[0] ? f._volumes[0]->GetID() : 0) << " "
1672 << (f._volumes[1] ? f._volumes[1]->GetID() : 0);
1673 out << " \tNormal: "<< f._normal.X() <<", "<<f._normal.Y() <<", "<<f._normal.Z() << endl;
1677 //================================================================================
1679 * \brief Construct QFace from QLinks
1681 //================================================================================
1683 QFace::QFace( const vector< const QLink*>& links, const SMDS_MeshElement* face )
1685 _volumes[0] = _volumes[1] = 0;
1687 _sideIsAdded[0]=_sideIsAdded[1]=_sideIsAdded[2]=_sideIsAdded[3]=false;
1688 _normal.SetCoord(0,0,0);
1689 for ( int i = 1; i < _sides.size(); ++i ) {
1690 const QLink *l1 = _sides[i-1], *l2 = _sides[i];
1691 insert( l1->node1() ); insert( l1->node2() );
1693 gp_Vec v1( XYZ( l1->node2()), XYZ( l1->node1()));
1694 gp_Vec v2( XYZ( l2->node1()), XYZ( l2->node2()));
1695 if ( l1->node1() != l2->node1() && l1->node2() != l2->node2() )
1699 double normSqSize = _normal.SquareMagnitude();
1700 if ( normSqSize > numeric_limits<double>::min() )
1701 _normal /= sqrt( normSqSize );
1703 _normal.SetCoord(1e-33,0,0);
1709 //================================================================================
1711 * \brief Make up a chain of links
1712 * \param iSide - link to add first
1713 * \param chain - chain to fill in
1714 * \param pos - postion of medium nodes the links should have
1715 * \param error - out, specifies what is wrong
1716 * \retval bool - false if valid chain can't be built; "valid" means that links
1717 * of the chain belongs to rectangles bounding hexahedrons
1719 //================================================================================
1721 bool QFace::GetLinkChain( int iSide, TChain& chain, SMDS_TypeOfPosition pos, int& error) const
1723 if ( iSide >= _sides.size() ) // wrong argument iSide
1725 if ( _sideIsAdded[ iSide ]) // already in chain
1728 if ( _sides.size() != 4 ) { // triangle - visit all my continous faces
1731 list< const QFace* > faces( 1, this );
1732 while ( !faces.empty() ) {
1733 const QFace* face = faces.front();
1734 for ( int i = 0; i < face->_sides.size(); ++i ) {
1735 if ( !face->_sideIsAdded[i] && face->_sides[i] ) {
1736 face->_sideIsAdded[i] = true;
1737 // find a face side in the chain
1738 TLinkInSet chLink = links.insert( TChainLink(face->_sides[i])).first;
1739 // TChain::iterator chLink = chain.begin();
1740 // for ( ; chLink != chain.end(); ++chLink )
1741 // if ( chLink->_qlink == face->_sides[i] )
1743 // if ( chLink == chain.end() )
1744 // chLink = chain.insert( chain.begin(), TChainLink(face->_sides[i]));
1745 // add a face to a chained link and put a continues face in the queue
1746 chLink->SetFace( face );
1747 if ( face->_sides[i]->MediumPos() >= pos )
1748 if ( const QFace* contFace = face->_sides[i]->GetContinuesFace( face ))
1749 faces.push_back( contFace );
1754 if ( error < ERR_TRI )
1756 chain.insert( chain.end(), links.begin(),links.end() );
1759 _sideIsAdded[iSide] = true; // not to add this link to chain again
1760 const QLink* link = _sides[iSide];
1764 // add link into chain
1765 TChain::iterator chLink = chain.insert( chain.begin(), TChainLink(link));
1766 chLink->SetFace( this );
1769 // propagate from quadrangle to neighbour faces
1770 if ( link->MediumPos() >= pos ) {
1771 int nbLinkFaces = link->_faces.size();
1772 if ( nbLinkFaces == 4 || nbLinkFaces < 4 && link->OnBoundary()) {
1773 // hexahedral mesh or boundary quadrangles - goto a continous face
1774 if ( const QFace* f = link->GetContinuesFace( this ))
1775 return f->GetLinkChain( *chLink, chain, pos, error );
1778 TChainLink chLink(link); // side face of prismatic mesh - visit all faces of iSide
1779 for ( int i = 0; i < nbLinkFaces; ++i )
1780 if ( link->_faces[i] )
1781 link->_faces[i]->GetLinkChain( chLink, chain, pos, error );
1782 if ( error < ERR_PRISM )
1790 //================================================================================
1792 * \brief Return a boundary link of the triangle face
1793 * \param links - set of all links
1794 * \param avoidLink - link not to return
1795 * \param notBoundaryLink - out, neither the returned link nor avoidLink
1796 * \param nodeToContain - node the returned link must contain; if provided, search
1797 * also performed on adjacent faces
1798 * \param isAdjacentUsed - returns true if link is found in adjacent faces
1799 * \param nbRecursionsLeft - to limit recursion
1801 //================================================================================
1803 TLinkInSet QFace::GetBoundaryLink( const TLinkSet& links,
1804 const TChainLink& avoidLink,
1805 TLinkInSet * notBoundaryLink,
1806 const SMDS_MeshNode* nodeToContain,
1807 bool * isAdjacentUsed,
1808 int nbRecursionsLeft) const
1810 TLinkInSet linksEnd = links.end(), boundaryLink = linksEnd;
1812 typedef list< pair< const QFace*, TLinkInSet > > TFaceLinkList;
1813 TFaceLinkList adjacentFaces;
1815 for ( int iL = 0; iL < _sides.size(); ++iL )
1817 if ( avoidLink._qlink == _sides[iL] )
1819 TLinkInSet link = links.find( _sides[iL] );
1820 if ( link == linksEnd ) continue;
1821 if ( (*link)->MediumPos() > SMDS_TOP_FACE )
1822 continue; // We work on faces here, don't go inside a solid
1825 if ( link->IsBoundary() ) {
1826 if ( !nodeToContain ||
1827 (*link)->node1() == nodeToContain ||
1828 (*link)->node2() == nodeToContain )
1830 boundaryLink = link;
1831 if ( !notBoundaryLink ) break;
1834 else if ( notBoundaryLink ) {
1835 *notBoundaryLink = link;
1836 if ( boundaryLink != linksEnd ) break;
1839 if ( boundaryLink == linksEnd && nodeToContain ) // collect adjacent faces
1840 if ( const QFace* adj = link->NextFace( this ))
1841 if ( adj->Contains( nodeToContain ))
1842 adjacentFaces.push_back( make_pair( adj, link ));
1845 if ( isAdjacentUsed ) *isAdjacentUsed = false;
1846 if ( boundaryLink == linksEnd && nodeToContain && nbRecursionsLeft) // check adjacent faces
1848 if ( nbRecursionsLeft < 0 )
1849 nbRecursionsLeft = nodeToContain->NbInverseElements();
1850 TFaceLinkList::iterator adj = adjacentFaces.begin();
1851 for ( ; boundaryLink == linksEnd && adj != adjacentFaces.end(); ++adj )
1852 boundaryLink = adj->first->GetBoundaryLink( links, *(adj->second), 0, nodeToContain,
1853 isAdjacentUsed, nbRecursionsLeft-1);
1854 if ( isAdjacentUsed ) *isAdjacentUsed = true;
1856 return boundaryLink;
1858 //================================================================================
1860 * \brief Return a link ending at the given node but not avoidLink
1862 //================================================================================
1864 TLinkInSet QFace::GetLinkByNode( const TLinkSet& links,
1865 const TChainLink& avoidLink,
1866 const SMDS_MeshNode* nodeToContain) const
1868 for ( int i = 0; i < _sides.size(); ++i )
1869 if ( avoidLink._qlink != _sides[i] &&
1870 (_sides[i]->node1() == nodeToContain || _sides[i]->node2() == nodeToContain ))
1871 return links.find( _sides[ i ]);
1875 //================================================================================
1877 * \brief Return normal to the i-th side pointing outside the face
1879 //================================================================================
1881 gp_Vec QFace::LinkNorm(const int i, SMESH_MesherHelper* /*uvHelper*/) const
1883 gp_Vec norm, vecOut;
1884 // if ( uvHelper ) {
1885 // TopoDS_Face face = TopoDS::Face( uvHelper->GetSubShape());
1886 // const SMDS_MeshNode* inFaceNode = uvHelper->GetNodeUVneedInFaceNode() ? GetNodeInFace() : 0;
1887 // gp_XY uv1 = uvHelper->GetNodeUV( face, _sides[i]->node1(), inFaceNode );
1888 // gp_XY uv2 = uvHelper->GetNodeUV( face, _sides[i]->node2(), inFaceNode );
1889 // norm.SetCoord( uv1.Y() - uv2.Y(), uv2.X() - uv1.X(), 0 );
1891 // const QLink* otherLink = _sides[(i + 1) % _sides.size()];
1892 // const SMDS_MeshNode* otherNode =
1893 // otherLink->node1() == _sides[i]->node1() ? otherLink->node2() : otherLink->node1();
1894 // gp_XY pIn = uvHelper->GetNodeUV( face, otherNode, inFaceNode );
1895 // vecOut.SetCoord( uv1.X() - pIn.X(), uv1.Y() - pIn.Y(), 0 );
1898 norm = _normal ^ gp_Vec( XYZ(_sides[i]->node1()), XYZ(_sides[i]->node2()));
1899 gp_XYZ pIn = ( XYZ( _sides[0]->node1() ) +
1900 XYZ( _sides[0]->node2() ) +
1901 XYZ( _sides[1]->node1() )) / 3.;
1902 vecOut.SetXYZ( _sides[i]->MiddlePnt() - pIn );
1904 if ( norm * vecOut < 0 )
1906 double mag2 = norm.SquareMagnitude();
1907 if ( mag2 > numeric_limits<double>::min() )
1908 norm /= sqrt( mag2 );
1911 //================================================================================
1913 * \brief Move medium node of theLink according to its distance from boundary
1914 * \param theLink - link to fix
1915 * \param theRefVec - movement of boundary
1916 * \param theLinks - all adjacent links of continous triangles
1917 * \param theFaceHelper - helper is not used so far
1918 * \param thePrevLen - distance from the boundary
1919 * \param theStep - number of steps till movement propagation limit
1920 * \param theLinkNorm - out normal to theLink
1921 * \param theSign - 1 or -1 depending on movement of boundary
1922 * \retval double - distance from boundary to propagation limit or other boundary
1924 //================================================================================
1926 double QFace::MoveByBoundary( const TChainLink& theLink,
1927 const gp_Vec& theRefVec,
1928 const TLinkSet& theLinks,
1929 SMESH_MesherHelper* theFaceHelper,
1930 const double thePrevLen,
1932 gp_Vec* theLinkNorm,
1933 double theSign) const
1936 return thePrevLen; // propagation limit reached
1938 int iL; // index of theLink
1939 for ( iL = 0; iL < _sides.size(); ++iL )
1940 if ( theLink._qlink == _sides[ iL ])
1943 MSG(string(theStep,'.')<<" Ref( "<<theRefVec.X()<<","<<theRefVec.Y()<<","<<theRefVec.Z()<<" )"
1944 <<" thePrevLen " << thePrevLen);
1945 MSG(string(theStep,'.')<<" "<<*theLink._qlink);
1947 gp_Vec linkNorm = -LinkNorm( iL/*, theFaceHelper*/ ); // normal to theLink
1948 double refProj = theRefVec * linkNorm; // project movement vector to normal of theLink
1949 if ( theStep == theFirstStep )
1950 theSign = refProj < 0. ? -1. : 1.;
1951 else if ( theSign * refProj < 0.4 * theRefVec.Magnitude())
1952 return thePrevLen; // to propagate movement forward only, not in side dir or backward
1954 int iL1 = (iL + 1) % 3, iL2 = (iL + 2) % 3; // indices of the two other links of triangle
1955 TLinkInSet link1 = theLinks.find( _sides[iL1] );
1956 TLinkInSet link2 = theLinks.find( _sides[iL2] );
1957 if ( link1 == theLinks.end() || link2 == theLinks.end() )
1959 const QFace* f1 = link1->NextFace( this ); // adjacent faces
1960 const QFace* f2 = link2->NextFace( this );
1962 // propagate to adjacent faces till limit step or boundary
1963 double len1 = thePrevLen + (theLink->MiddlePnt() - _sides[iL1]->MiddlePnt()).Modulus();
1964 double len2 = thePrevLen + (theLink->MiddlePnt() - _sides[iL2]->MiddlePnt()).Modulus();
1965 gp_Vec linkDir1(0,0,0); // initialize to avoid valgrind error ("Conditional jump...")
1966 gp_Vec linkDir2(0,0,0);
1970 len1 = f1->MoveByBoundary
1971 ( *link1, theRefVec, theLinks, theFaceHelper, len1, theStep-1, &linkDir1, theSign);
1973 linkDir1 = LinkNorm( iL1/*, theFaceHelper*/ );
1975 MSG( " --------------- EXCEPTION");
1981 len2 = f2->MoveByBoundary
1982 ( *link2, theRefVec, theLinks, theFaceHelper, len2, theStep-1, &linkDir2, theSign);
1984 linkDir2 = LinkNorm( iL2/*, theFaceHelper*/ );
1986 MSG( " --------------- EXCEPTION");
1991 if ( theStep != theFirstStep )
1993 // choose chain length by direction of propagation most codirected with theRefVec
1994 bool choose1 = ( theRefVec * linkDir1 * theSign > theRefVec * linkDir2 * theSign );
1995 fullLen = choose1 ? len1 : len2;
1996 double r = thePrevLen / fullLen;
1998 gp_Vec move = linkNorm * refProj * ( 1 - r );
1999 theLink->Move( move, true );
2001 MSG(string(theStep,'.')<<" Move "<< theLink->_mediumNode->GetID()<<
2002 " by " << refProj * ( 1 - r ) << " following " <<
2003 (choose1 ? *link1->_qlink : *link2->_qlink));
2005 if ( theLinkNorm ) *theLinkNorm = linkNorm;
2010 //================================================================================
2012 * \brief Find pairs of continues faces
2014 //================================================================================
2016 void QLink::SetContinuesFaces() const
2018 // x0 x - QLink, [-|] - QFace, v - volume
2020 // | Between _faces of link x2 two vertical faces are continues
2021 // x1----x2-----x3 and two horizontal faces are continues. We set vertical faces
2022 // | to _faces[0] and _faces[1] and horizontal faces to
2023 // v2 | v3 _faces[2] and _faces[3] (or vise versa).
2026 if ( _faces.empty() )
2029 for ( int iF = 1; iFaceCont < 0 && iF < _faces.size(); ++iF )
2031 // look for a face bounding none of volumes bound by _faces[0]
2032 bool sameVol = false;
2033 int nbVol = _faces[iF]->NbVolumes();
2034 for ( int iV = 0; !sameVol && iV < nbVol; ++iV )
2035 sameVol = ( _faces[iF]->_volumes[iV] == _faces[0]->_volumes[0] ||
2036 _faces[iF]->_volumes[iV] == _faces[0]->_volumes[1]);
2040 if ( iFaceCont > 0 ) // continues faces found, set one by the other
2042 if ( iFaceCont != 1 )
2043 std::swap( _faces[1], _faces[iFaceCont] );
2045 else if ( _faces.size() > 1 ) // not found, set NULL by the first face
2047 _faces.insert( ++_faces.begin(), 0 );
2050 //================================================================================
2052 * \brief Return a face continues to the given one
2054 //================================================================================
2056 const QFace* QLink::GetContinuesFace( const QFace* face ) const
2058 for ( int i = 0; i < _faces.size(); ++i ) {
2059 if ( _faces[i] == face ) {
2060 int iF = i < 2 ? 1-i : 5-i;
2061 return iF < _faces.size() ? _faces[iF] : 0;
2066 //================================================================================
2068 * \brief True if link is on mesh boundary
2070 //================================================================================
2072 bool QLink::OnBoundary() const
2074 for ( int i = 0; i < _faces.size(); ++i )
2075 if (_faces[i] && _faces[i]->IsBoundary()) return true;
2078 //================================================================================
2080 * \brief Return normal of link of the chain
2082 //================================================================================
2084 gp_Vec TChainLink::Normal() const {
2086 if (_qfaces[0]) norm = _qfaces[0]->_normal;
2087 if (_qfaces[1]) norm += _qfaces[1]->_normal;
2090 //================================================================================
2092 * \brief Move medium nodes of vertical links of pentahedrons adjacent by side faces
2094 //================================================================================
2096 void fixPrism( TChain& allLinks )
2098 // separate boundary links from internal ones
2099 typedef set<const QLink*/*, QLink::PtrComparator*/> QLinkSet;
2100 QLinkSet interLinks, bndLinks1, bndLink2;
2102 bool isCurved = false;
2103 for ( TChain::iterator lnk = allLinks.begin(); lnk != allLinks.end(); ++lnk ) {
2104 if ( (*lnk)->OnBoundary() )
2105 bndLinks1.insert( lnk->_qlink );
2107 interLinks.insert( lnk->_qlink );
2108 isCurved = isCurved || !(*lnk)->IsStraight();
2111 return; // no need to move
2113 QLinkSet *curBndLinks = &bndLinks1, *newBndLinks = &bndLink2;
2115 while ( !interLinks.empty() && !curBndLinks->empty() )
2117 // propagate movement from boundary links to connected internal links
2118 QLinkSet::iterator bnd = curBndLinks->begin(), bndEnd = curBndLinks->end();
2119 for ( ; bnd != bndEnd; ++bnd )
2121 const QLink* bndLink = *bnd;
2122 for ( int i = 0; i < bndLink->_faces.size(); ++i ) // loop on faces of bndLink
2124 const QFace* face = bndLink->_faces[i]; // quadrange lateral face of a prism
2125 if ( !face ) continue;
2126 // find and move internal link opposite to bndLink within the face
2127 int interInd = ( face->LinkIndex( bndLink ) + 2 ) % face->_sides.size();
2128 const QLink* interLink = face->_sides[ interInd ];
2129 QLinkSet::iterator pInterLink = interLinks.find( interLink );
2130 if ( pInterLink == interLinks.end() ) continue; // not internal link
2131 interLink->Move( bndLink->_nodeMove );
2132 // treated internal links become new boundary ones
2133 interLinks. erase( pInterLink );
2134 newBndLinks->insert( interLink );
2137 curBndLinks->clear();
2138 std::swap( curBndLinks, newBndLinks );
2142 //================================================================================
2144 * \brief Fix links of continues triangles near curved boundary
2146 //================================================================================
2148 void fixTriaNearBoundary( TChain & allLinks, SMESH_MesherHelper& /*helper*/)
2150 if ( allLinks.empty() ) return;
2152 TLinkSet linkSet( allLinks.begin(), allLinks.end());
2153 TLinkInSet linkIt = linkSet.begin(), linksEnd = linkSet.end();
2155 // move in 2d if we are on geom face
2156 // TopoDS_Face face;
2157 // TopLoc_Location loc;
2158 // SMESH_MesherHelper faceHelper( *helper.GetMesh());
2159 // while ( linkIt->IsBoundary()) ++linkIt;
2160 // if ( linkIt == linksEnd ) return;
2161 // if ( (*linkIt)->MediumPos() == SMDS_TOP_FACE ) {
2162 // bool checkPos = true;
2163 // TopoDS_Shape f = helper.GetSubShapeByNode( (*linkIt)->_mediumNode, helper.GetMeshDS() );
2164 // if ( !f.IsNull() && f.ShapeType() == TopAbs_FACE ) {
2165 // face = TopoDS::Face( f );
2166 // helper.GetNodeUV( face, (*linkIt)->_mediumNode, 0, &checkPos);
2170 // faceHelper.SetSubShape( face );
2173 for ( linkIt = linkSet.begin(); linkIt != linksEnd; ++linkIt)
2175 if ( linkIt->IsBoundary() && !(*linkIt)->IsStraight() && linkIt->_qfaces[0])
2177 // if ( !face.IsNull() ) {
2178 // const SMDS_MeshNode* inFaceNode =
2179 // faceHelper.GetNodeUVneedInFaceNode() ? linkIt->_qfaces[0]->GetNodeInFace() : 0;
2180 // gp_XY uvm = helper.GetNodeUV( face, (*linkIt)->_mediumNode, inFaceNode );
2181 // gp_XY uv1 = helper.GetNodeUV( face, (*linkIt)->node1(), inFaceNode);
2182 // gp_XY uv2 = helper.GetNodeUV( face, (*linkIt)->node2(), inFaceNode);
2183 // gp_XY uvMove = uvm - helper.GetMiddleUV( BRep_Tool::Surface(face,loc), uv1, uv2);
2184 // gp_Vec move( uvMove.X(), uvMove.Y(), 0 );
2185 // linkIt->_qfaces[0]->MoveByBoundary( *linkIt, move, linkSet, &faceHelper );
2188 linkIt->_qfaces[0]->MoveByBoundary( *linkIt, (*linkIt)->_nodeMove, linkSet );
2194 //================================================================================
2196 * \brief Detect rectangular structure of links and build chains from them
2198 //================================================================================
2200 enum TSplitTriaResult {
2201 _OK, _NO_CORNERS, _FEW_ROWS, _MANY_ROWS, _NO_SIDELINK, _BAD_MIDQUAD, _NOT_RECT,
2202 _NO_MIDQUAD, _NO_UPTRIA, _BAD_SET_SIZE, _BAD_CORNER, _BAD_START, _NO_BOTLINK, _TWISTED_CHAIN };
2204 TSplitTriaResult splitTrianglesIntoChains( TChain & allLinks,
2205 vector< TChain> & resultChains,
2206 SMDS_TypeOfPosition pos )
2208 // put links in the set and evalute number of result chains by number of boundary links
2211 for ( TChain::iterator lnk = allLinks.begin(); lnk != allLinks.end(); ++lnk ) {
2212 linkSet.insert( *lnk );
2213 nbBndLinks += lnk->IsBoundary();
2215 resultChains.clear();
2216 resultChains.reserve( nbBndLinks / 2 );
2218 TLinkInSet linkIt, linksEnd = linkSet.end();
2220 // find a boundary link with corner node; corner node has position pos-2
2221 // i.e. SMDS_TOP_VERTEX for links on faces and SMDS_TOP_EDGE for
2223 SMDS_TypeOfPosition cornerPos = SMDS_TypeOfPosition(pos-2);
2224 const SMDS_MeshNode* corner = 0;
2225 for ( linkIt = linkSet.begin(); linkIt != linksEnd; ++linkIt )
2226 if ( linkIt->IsBoundary() && (corner = (*linkIt)->EndPosNode(cornerPos)))
2231 TLinkInSet startLink = linkIt;
2232 const SMDS_MeshNode* startCorner = corner;
2233 vector< TChain* > rowChains;
2236 while ( startLink != linksEnd) // loop on columns
2238 // We suppose we have a rectangular structure like shown here. We have found a
2239 // corner of the rectangle (startCorner) and a boundary link sharing
2240 // |/ |/ | the startCorner (startLink). We are going to loop on rows of the
2241 // --o---o---o structure making several chains at once. One chain (columnChain)
2242 // |\ | /| starts at startLink and continues upward (we look at the structure
2243 // \ | \ | / | from such point that startLink is on the bottom of the structure).
2244 // \| \|/ | While going upward we also fill horizontal chains (rowChains) we
2245 // --o---o---o encounter.
2247 // / | \ | \ | startCorner
2252 if ( resultChains.size() == nbBndLinks / 2 )
2254 resultChains.push_back( TChain() );
2255 TChain& columnChain = resultChains.back();
2257 TLinkInSet botLink = startLink; // current horizontal link to go up from
2258 corner = startCorner; // current corner the botLink ends at
2260 while ( botLink != linksEnd ) // loop on rows
2262 // add botLink to the columnChain
2263 columnChain.push_back( *botLink );
2265 const QFace* botTria = botLink->_qfaces[0]; // bottom triangle bound by botLink
2267 { // the column ends
2268 if ( botLink == startLink )
2269 return _TWISTED_CHAIN; // issue 0020951
2270 linkSet.erase( botLink );
2271 if ( iRow != rowChains.size() )
2272 return _FEW_ROWS; // different nb of rows in columns
2275 // find the link dividing the quadrangle (midQuadLink) and vertical boundary
2276 // link ending at <corner> (sideLink); there are two cases:
2277 // 1) midQuadLink does not end at <corner>, then we easily find it by botTria,
2278 // since midQuadLink is not at boundary while sideLink is.
2279 // 2) midQuadLink ends at <corner>
2281 TLinkInSet midQuadLink = linksEnd;
2282 TLinkInSet sideLink = botTria->GetBoundaryLink( linkSet, *botLink, &midQuadLink,
2284 if ( isCase2 ) { // find midQuadLink among links of botTria
2285 midQuadLink = botTria->GetLinkByNode( linkSet, *botLink, corner );
2286 if ( midQuadLink->IsBoundary() )
2287 return _BAD_MIDQUAD;
2289 if ( sideLink == linksEnd || midQuadLink == linksEnd || sideLink == midQuadLink )
2290 return sideLink == linksEnd ? _NO_SIDELINK : _NO_MIDQUAD;
2293 columnChain.push_back( *midQuadLink );
2294 if ( iRow >= rowChains.size() ) {
2296 return _MANY_ROWS; // different nb of rows in columns
2297 if ( resultChains.size() == nbBndLinks / 2 )
2299 resultChains.push_back( TChain() );
2300 rowChains.push_back( & resultChains.back() );
2302 rowChains[iRow]->push_back( *sideLink );
2303 rowChains[iRow]->push_back( *midQuadLink );
2305 const QFace* upTria = midQuadLink->NextFace( botTria ); // upper tria of the rectangle
2309 // prepare startCorner and startLink for the next column
2310 startCorner = startLink->NextNode( startCorner );
2312 startLink = botTria->GetBoundaryLink( linkSet, *botLink, 0, startCorner );
2314 startLink = upTria->GetBoundaryLink( linkSet, *midQuadLink, 0, startCorner );
2315 // check if no more columns remains
2316 if ( startLink != linksEnd ) {
2317 const SMDS_MeshNode* botNode = startLink->NextNode( startCorner );
2318 if ( (isCase2 ? botTria : upTria)->Contains( botNode ))
2319 startLink = linksEnd; // startLink bounds upTria or botTria
2320 else if ( startLink == botLink || startLink == midQuadLink || startLink == sideLink )
2324 // find bottom link and corner for the next row
2325 corner = sideLink->NextNode( corner );
2326 // next bottom link ends at the new corner
2327 linkSet.erase( botLink );
2328 botLink = upTria->GetLinkByNode( linkSet, (isCase2 ? *sideLink : *midQuadLink), corner );
2329 if ( botLink == linksEnd || botLink == midQuadLink || botLink == sideLink)
2331 if ( midQuadLink == startLink || sideLink == startLink )
2332 return _TWISTED_CHAIN; // issue 0020951
2333 linkSet.erase( midQuadLink );
2334 linkSet.erase( sideLink );
2336 // make faces neighboring the found ones be boundary
2337 if ( startLink != linksEnd ) {
2338 const QFace* tria = isCase2 ? botTria : upTria;
2339 for ( int iL = 0; iL < 3; ++iL ) {
2340 linkIt = linkSet.find( tria->_sides[iL] );
2341 if ( linkIt != linksEnd )
2342 linkIt->RemoveFace( tria );
2345 if ( botLink->_qfaces[0] == upTria || botLink->_qfaces[1] == upTria )
2346 botLink->RemoveFace( upTria ); // make next botTria first in vector
2353 // In the linkSet, there must remain the last links of rowChains; add them
2354 if ( linkSet.size() != rowChains.size() )
2355 return _BAD_SET_SIZE;
2356 for ( int iRow = 0; iRow < rowChains.size(); ++iRow ) {
2357 // find the link (startLink) ending at startCorner
2359 for ( startLink = linkSet.begin(); startLink != linksEnd; ++startLink ) {
2360 if ( (*startLink)->node1() == startCorner ) {
2361 corner = (*startLink)->node2(); break;
2363 else if ( (*startLink)->node2() == startCorner) {
2364 corner = (*startLink)->node1(); break;
2367 if ( startLink == linksEnd )
2369 rowChains[ iRow ]->push_back( *startLink );
2370 linkSet.erase( startLink );
2371 startCorner = corner;
2378 //=======================================================================
2380 * \brief Move medium nodes of faces and volumes to fix distorted elements
2381 * \param volumeOnly - to fix nodes on faces or not, if the shape is solid
2383 * Issue 0020307: EDF 992 SMESH : Linea/Quadratic with Medium Node on Geometry
2385 //=======================================================================
2387 void SMESH_MesherHelper::FixQuadraticElements(bool volumeOnly)
2389 // 0. Apply algorithm to solids or geom faces
2390 // ----------------------------------------------
2391 if ( myShape.IsNull() ) {
2392 if ( !myMesh->HasShapeToMesh() ) return;
2393 SetSubShape( myMesh->GetShapeToMesh() );
2397 TopTools_IndexedMapOfShape solids;
2398 TopExp::MapShapes(myShape,TopAbs_SOLID,solids);
2399 nbSolids = solids.Extent();
2401 TopTools_MapOfShape faces; // faces not in solid or in not meshed solid
2402 for ( TopExp_Explorer f(myShape,TopAbs_FACE,TopAbs_SOLID); f.More(); f.Next() ) {
2403 faces.Add( f.Current() ); // not in solid
2405 for ( TopExp_Explorer s(myShape,TopAbs_SOLID); s.More(); s.Next() ) {
2406 if ( myMesh->GetSubMesh( s.Current() )->IsEmpty() ) { // get faces of solid
2407 for ( TopExp_Explorer f( s.Current(), TopAbs_FACE); f.More(); f.Next() )
2408 faces.Add( f.Current() ); // in not meshed solid
2410 else { // fix nodes in the solid and its faces
2411 MSG("FIX SOLID " << nbSolids-- << " #" << GetMeshDS()->ShapeToIndex(s.Current()));
2412 SMESH_MesherHelper h(*myMesh);
2413 h.SetSubShape( s.Current() );
2414 h.FixQuadraticElements(false);
2417 // fix nodes on geom faces
2419 int nbfaces = faces.Extent();
2421 for ( TopTools_MapIteratorOfMapOfShape fIt( faces ); fIt.More(); fIt.Next() ) {
2422 MSG("FIX FACE " << nbfaces-- << " #" << GetMeshDS()->ShapeToIndex(fIt.Key()));
2423 SMESH_MesherHelper h(*myMesh);
2424 h.SetSubShape( fIt.Key() );
2425 h.FixQuadraticElements(true);
2427 //perf_print_all_meters(1);
2431 // 1. Find out type of elements and get iterator on them
2432 // ---------------------------------------------------
2434 SMDS_ElemIteratorPtr elemIt;
2435 SMDSAbs_ElementType elemType = SMDSAbs_All;
2437 SMESH_subMesh* submesh = myMesh->GetSubMeshContaining( myShapeID );
2440 if ( SMESHDS_SubMesh* smDS = submesh->GetSubMeshDS() ) {
2441 elemIt = smDS->GetElements();
2442 if ( elemIt->more() ) {
2443 elemType = elemIt->next()->GetType();
2444 elemIt = smDS->GetElements();
2447 if ( !elemIt || !elemIt->more() || elemType < SMDSAbs_Face )
2450 // 2. Fill in auxiliary data structures
2451 // ----------------------------------
2455 set< QLink >::iterator pLink;
2456 set< QFace >::iterator pFace;
2458 bool isCurved = false;
2459 //bool hasRectFaces = false;
2460 set<int> nbElemNodeSet;
2462 if ( elemType == SMDSAbs_Volume )
2464 SMDS_VolumeTool volTool;
2465 while ( elemIt->more() ) // loop on volumes
2467 const SMDS_MeshElement* vol = elemIt->next();
2468 if ( !vol->IsQuadratic() || !volTool.Set( vol ))
2470 for ( int iF = 0; iF < volTool.NbFaces(); ++iF ) // loop on faces of volume
2472 int nbN = volTool.NbFaceNodes( iF );
2473 nbElemNodeSet.insert( nbN );
2474 const SMDS_MeshNode** faceNodes = volTool.GetFaceNodes( iF );
2475 vector< const QLink* > faceLinks( nbN/2 );
2476 for ( int iN = 0; iN < nbN; iN += 2 ) // loop on links of a face
2479 QLink link( faceNodes[iN], faceNodes[iN+2], faceNodes[iN+1] );
2480 pLink = links.insert( link ).first;
2481 faceLinks[ iN/2 ] = & *pLink;
2483 isCurved = !link.IsStraight();
2484 if ( link.MediumPos() == SMDS_TOP_3DSPACE && !link.IsStraight() )
2485 return; // already fixed
2488 pFace = faces.insert( QFace( faceLinks )).first;
2489 if ( pFace->NbVolumes() == 0 )
2490 pFace->AddSelfToLinks();
2491 pFace->SetVolume( vol );
2492 // hasRectFaces = hasRectFaces ||
2493 // ( volTool.GetVolumeType() == SMDS_VolumeTool::QUAD_HEXA ||
2494 // volTool.GetVolumeType() == SMDS_VolumeTool::QUAD_PENTA );
2497 pFace->_face = GetMeshDS()->FindFace(faceNodes[0],faceNodes[2],faceNodes[4]);
2499 pFace->_face = GetMeshDS()->FindFace(faceNodes[0],faceNodes[2],
2500 faceNodes[4],faceNodes[6] );
2504 set< QLink >::iterator pLink = links.begin();
2505 for ( ; pLink != links.end(); ++pLink )
2506 pLink->SetContinuesFaces();
2510 while ( elemIt->more() ) // loop on faces
2512 const SMDS_MeshElement* face = elemIt->next();
2513 if ( !face->IsQuadratic() )
2515 nbElemNodeSet.insert( face->NbNodes() );
2516 int nbN = face->NbNodes()/2;
2517 vector< const QLink* > faceLinks( nbN );
2518 for ( int iN = 0; iN < nbN; ++iN ) // loop on links of a face
2521 QLink link( face->GetNode(iN), face->GetNode((iN+1)%nbN), face->GetNode(iN+nbN) );
2522 pLink = links.insert( link ).first;
2523 faceLinks[ iN ] = & *pLink;
2525 isCurved = !link.IsStraight();
2528 pFace = faces.insert( QFace( faceLinks )).first;
2529 pFace->AddSelfToLinks();
2530 //hasRectFaces = ( hasRectFaces || nbN == 4 );
2534 return; // no curved edges of faces
2536 // 3. Compute displacement of medium nodes
2537 // -------------------------------------
2539 // two loops on faces: the first is to treat boundary links, the second is for internal ones
2540 TopLoc_Location loc;
2541 // not treat boundary of volumic submesh
2542 int isInside = ( elemType == SMDSAbs_Volume && volumeOnly ) ? 1 : 0;
2543 for ( ; isInside < 2; ++isInside ) {
2544 MSG( "--------------- LOOP (inside=" << isInside << ") ------------------");
2545 SMDS_TypeOfPosition pos = isInside ? SMDS_TOP_3DSPACE : SMDS_TOP_FACE;
2546 SMDS_TypeOfPosition bndPos = isInside ? SMDS_TOP_FACE : SMDS_TOP_EDGE;
2548 for ( pFace = faces.begin(); pFace != faces.end(); ++pFace ) {
2549 if ( bool(isInside) == pFace->IsBoundary() )
2551 for ( int dir = 0; dir < 2; ++dir ) // 2 directions of propagation from quadrangle
2554 // make chain of links connected via continues faces
2557 if ( !pFace->GetLinkChain( dir, rawChain, pos, error) && error ==ERR_UNKNOWN ) continue;
2559 if ( !pFace->GetLinkChain( dir+2, rawChain, pos, error ) && error ==ERR_UNKNOWN ) continue;
2561 vector< TChain > chains;
2562 if ( error == ERR_OK ) { // chain contains continues rectangles
2564 chains[0].splice( chains[0].begin(), rawChain );
2566 else if ( error == ERR_TRI ) { // chain contains continues triangles
2567 TSplitTriaResult res = splitTrianglesIntoChains( rawChain, chains, pos );
2568 if ( res != _OK ) { // not quadrangles split into triangles
2569 fixTriaNearBoundary( rawChain, *this );
2573 else if ( error == ERR_PRISM ) { // quadrangle side faces of prisms
2574 fixPrism( rawChain );
2580 for ( int iC = 0; iC < chains.size(); ++iC )
2582 TChain& chain = chains[iC];
2583 if ( chain.empty() ) continue;
2584 if ( chain.front()->IsStraight() && chain.back()->IsStraight() ) {
2585 MSG("3D straight - ignore");
2588 if ( chain.front()->MediumPos() > bndPos ||
2589 chain.back()->MediumPos() > bndPos ) {
2590 MSG("Internal chain - ignore");
2593 // mesure chain length and compute link position along the chain
2594 double chainLen = 0;
2595 vector< double > linkPos;
2596 MSGBEG( "Link medium nodes: ");
2597 TChain::iterator link0 = chain.begin(), link1 = chain.begin(), link2;
2598 for ( ++link1; link1 != chain.end(); ++link1, ++link0 ) {
2599 MSGBEG( (*link0)->_mediumNode->GetID() << "-" <<(*link1)->_mediumNode->GetID()<<" ");
2600 double len = ((*link0)->MiddlePnt() - (*link1)->MiddlePnt()).Modulus();
2601 while ( len < numeric_limits<double>::min() ) { // remove degenerated link
2602 link1 = chain.erase( link1 );
2603 if ( link1 == chain.end() )
2605 len = ((*link0)->MiddlePnt() - (*link1)->MiddlePnt()).Modulus();
2608 linkPos.push_back( chainLen );
2611 if ( linkPos.size() < 2 )
2614 gp_Vec move0 = chain.front()->_nodeMove;
2615 gp_Vec move1 = chain.back ()->_nodeMove;
2618 bool checkUV = true;
2620 // compute node displacement of end links in parametric space of face
2621 const SMDS_MeshNode* nodeOnFace = (*(++chain.begin()))->_mediumNode;
2622 TopoDS_Shape f = GetSubShapeByNode( nodeOnFace, GetMeshDS() );
2623 if ( !f.IsNull() && f.ShapeType() == TopAbs_FACE )
2625 face = TopoDS::Face( f );
2626 Handle(Geom_Surface) surf = BRep_Tool::Surface(face,loc);
2628 for ( int is1 = 0; is1 < 2; ++is1 ) // move0 or move1
2630 TChainLink& link = is1 ? chain.back() : chain.front();
2631 gp_XY uvm = GetNodeUV( face, link->_mediumNode, nodeOnFace, &checkUV);
2632 gp_XY uv1 = GetNodeUV( face, link->node1(), nodeOnFace, &checkUV);
2633 gp_XY uv2 = GetNodeUV( face, link->node2(), nodeOnFace, &checkUV);
2634 gp_XY uv12 = GetMiddleUV( surf, uv1, uv2);
2635 // uvMove = uvm - uv12
2636 gp_XY uvMove = applyIn2D(surf, uvm, uv12, gp_XY_Subtracted, /*inPeriod=*/false);
2637 ( is1 ? move1 : move0 ).SetCoord( uvMove.X(), uvMove.Y(), 0 );
2638 if ( !is1 ) // correct nodeOnFace for move1 (issue 0020919)
2639 nodeOnFace = (*(++chain.rbegin()))->_mediumNode;
2640 isStraight[is1] = isStraightLink( (uv2-uv1).SquareModulus(),uvMove.SquareModulus());
2642 // if ( move0.SquareMagnitude() < straightTol2 &&
2643 // move1.SquareMagnitude() < straightTol2 ) {
2644 if ( isStraight[0] && isStraight[1] ) {
2645 MSG("2D straight - ignore");
2646 continue; // straight - no need to move nodes of internal links
2651 if ( isInside || face.IsNull() )
2653 // compute node displacement of end links in their local coord systems
2655 TChainLink& ln0 = chain.front(), ln1 = *(++chain.begin());
2656 trsf.SetTransformation( gp_Ax3( gp::Origin(), ln0.Normal(),
2657 gp_Vec( ln0->MiddlePnt(), ln1->MiddlePnt() )));
2658 move0.Transform(trsf);
2661 TChainLink& ln0 = *(++chain.rbegin()), ln1 = chain.back();
2662 trsf.SetTransformation( gp_Ax3( gp::Origin(), ln1.Normal(),
2663 gp_Vec( ln0->MiddlePnt(), ln1->MiddlePnt() )));
2664 move1.Transform(trsf);
2667 // compute displacement of medium nodes
2668 link2 = chain.begin();
2671 for ( int i = 0; link2 != chain.end(); ++link0, ++link1, ++link2, ++i )
2673 double r = linkPos[i] / chainLen;
2674 // displacement in local coord system
2675 gp_Vec move = (1. - r) * move0 + r * move1;
2676 if ( isInside || face.IsNull()) {
2677 // transform to global
2678 gp_Vec x01( (*link0)->MiddlePnt(), (*link1)->MiddlePnt() );
2679 gp_Vec x12( (*link1)->MiddlePnt(), (*link2)->MiddlePnt() );
2680 gp_Vec x = x01.Normalized() + x12.Normalized();
2681 trsf.SetTransformation( gp_Ax3( gp::Origin(), link1->Normal(), x), gp_Ax3() );
2682 move.Transform(trsf);
2685 // compute 3D displacement by 2D one
2686 Handle(Geom_Surface) s = BRep_Tool::Surface(face,loc);
2687 gp_XY oldUV = GetNodeUV( face, (*link1)->_mediumNode, 0, &checkUV);
2688 gp_XY newUV = applyIn2D( s, oldUV, gp_XY( move.X(),move.Y()), gp_XY_Added);
2689 gp_Pnt newPnt = s->Value( newUV.X(), newUV.Y());
2690 move = gp_Vec( XYZ((*link1)->_mediumNode), newPnt.Transformed(loc) );
2692 if ( (XYZ((*link1)->node1()) - XYZ((*link1)->node2())).SquareModulus() <
2693 move.SquareMagnitude())
2695 gp_XY uv0 = GetNodeUV( face, (*link0)->_mediumNode, 0, &checkUV);
2696 gp_XY uv2 = GetNodeUV( face, (*link2)->_mediumNode, 0, &checkUV);
2697 MSG( "TOO LONG MOVE \t" <<
2698 "uv0: "<<uv0.X()<<", "<<uv0.Y()<<" \t" <<
2699 "uv2: "<<uv2.X()<<", "<<uv2.Y()<<" \t" <<
2700 "uvOld: "<<oldUV.X()<<", "<<oldUV.Y()<<" \t" <<
2701 "newUV: "<<newUV.X()<<", "<<newUV.Y()<<" \t");
2705 (*link1)->Move( move );
2706 MSG( "Move " << (*link1)->_mediumNode->GetID() << " following "
2707 << chain.front()->_mediumNode->GetID() <<"-"
2708 << chain.back ()->_mediumNode->GetID() <<
2709 " by " << move.Magnitude());
2711 } // loop on chains of links
2712 } // loop on 2 directions of propagation from quadrangle
2719 for ( pLink = links.begin(); pLink != links.end(); ++pLink ) {
2720 if ( pLink->IsMoved() ) {
2721 //gp_Pnt p = pLink->MediumPnt() + pLink->Move();
2722 gp_Pnt p = pLink->MiddlePnt() + pLink->Move();
2723 GetMeshDS()->MoveNode( pLink->_mediumNode, p.X(), p.Y(), p.Z());
2728 //=======================================================================
2730 * \brief Iterator on ancestors of the given type
2732 //=======================================================================
2734 struct TAncestorsIterator : public SMDS_Iterator<const TopoDS_Shape*>
2736 TopTools_ListIteratorOfListOfShape _ancIter;
2737 TopAbs_ShapeEnum _type;
2738 TAncestorsIterator( const TopTools_ListOfShape& ancestors, TopAbs_ShapeEnum type)
2739 : _ancIter( ancestors ), _type( type )
2741 if ( _ancIter.More() && _ancIter.Value().ShapeType() != _type ) next();
2745 return _ancIter.More();
2747 virtual const TopoDS_Shape* next()
2749 const TopoDS_Shape* s = _ancIter.More() ? & _ancIter.Value() : 0;
2750 if ( _ancIter.More() )
2751 for ( _ancIter.Next(); _ancIter.More(); _ancIter.Next())
2752 if ( _ancIter.Value().ShapeType() == _type )
2758 //=======================================================================
2760 * \brief Return iterator on ancestors of the given type
2762 //=======================================================================
2764 PShapeIteratorPtr SMESH_MesherHelper::GetAncestors(const TopoDS_Shape& shape,
2765 const SMESH_Mesh& mesh,
2766 TopAbs_ShapeEnum ancestorType)
2768 return PShapeIteratorPtr( new TAncestorsIterator( mesh.GetAncestors(shape), ancestorType));