1 // Copyright (C) 2007-2008 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
22 // File: SMESH_MesherHelper.cxx
23 // Created: 15.02.06 15:22:41
24 // Author: Sergey KUUL
26 #include "SMESH_MesherHelper.hxx"
28 #include "SMDS_FacePosition.hxx"
29 #include "SMDS_EdgePosition.hxx"
30 #include "SMDS_VolumeTool.hxx"
31 #include "SMESH_subMesh.hxx"
33 #include <BRepAdaptor_Surface.hxx>
34 #include <BRepTools.hxx>
35 #include <BRepTools_WireExplorer.hxx>
36 #include <BRep_Tool.hxx>
37 #include <Geom2d_Curve.hxx>
38 #include <GeomAPI_ProjectPointOnSurf.hxx>
39 #include <Geom_Curve.hxx>
40 #include <Geom_Surface.hxx>
41 #include <ShapeAnalysis.hxx>
43 #include <TopExp_Explorer.hxx>
44 #include <TopTools_ListIteratorOfListOfShape.hxx>
45 #include <TopTools_MapIteratorOfMapOfShape.hxx>
46 #include <TopTools_MapOfShape.hxx>
49 #include <gp_Pnt2d.hxx>
50 #include <gp_Trsf.hxx>
52 #include <Standard_Failure.hxx>
53 #include <Standard_ErrorHandler.hxx>
55 #include <utilities.h>
59 #define RETURN_BAD_RESULT(msg) { MESSAGE(msg); return false; }
63 gp_XYZ XYZ(const SMDS_MeshNode* n) { return gp_XYZ(n->X(), n->Y(), n->Z()); }
67 //================================================================================
71 //================================================================================
73 SMESH_MesherHelper::SMESH_MesherHelper(SMESH_Mesh& theMesh)
74 : myMesh(&theMesh), myShapeID(0), myCreateQuadratic(false), myCheckNodePos(false)
76 mySetElemOnShape = ( ! myMesh->HasShapeToMesh() );
79 //=======================================================================
80 //function : CheckShape
82 //=======================================================================
84 bool SMESH_MesherHelper::IsQuadraticSubMesh(const TopoDS_Shape& aSh)
86 SMESHDS_Mesh* meshDS = GetMeshDS();
87 // we can create quadratic elements only if all elements
88 // created on subshapes of given shape are quadratic
89 // also we have to fill myTLinkNodeMap
90 myCreateQuadratic = true;
91 mySeamShapeIds.clear();
92 myDegenShapeIds.clear();
93 TopAbs_ShapeEnum subType( aSh.ShapeType()==TopAbs_FACE ? TopAbs_EDGE : TopAbs_FACE );
94 SMDSAbs_ElementType elemType( subType==TopAbs_FACE ? SMDSAbs_Face : SMDSAbs_Edge );
96 int nbOldLinks = myTLinkNodeMap.size();
98 TopExp_Explorer exp( aSh, subType );
99 for (; exp.More() && myCreateQuadratic; exp.Next()) {
100 if ( SMESHDS_SubMesh * subMesh = meshDS->MeshElements( exp.Current() )) {
101 if ( SMDS_ElemIteratorPtr it = subMesh->GetElements() ) {
103 const SMDS_MeshElement* e = it->next();
104 if ( e->GetType() != elemType || !e->IsQuadratic() ) {
105 myCreateQuadratic = false;
110 switch ( e->NbNodes() ) {
112 AddTLinkNode(e->GetNode(0),e->GetNode(1),e->GetNode(2)); break;
114 AddTLinkNode(e->GetNode(0),e->GetNode(1),e->GetNode(3));
115 AddTLinkNode(e->GetNode(1),e->GetNode(2),e->GetNode(4));
116 AddTLinkNode(e->GetNode(2),e->GetNode(0),e->GetNode(5)); break;
118 AddTLinkNode(e->GetNode(0),e->GetNode(1),e->GetNode(4));
119 AddTLinkNode(e->GetNode(1),e->GetNode(2),e->GetNode(5));
120 AddTLinkNode(e->GetNode(2),e->GetNode(3),e->GetNode(6));
121 AddTLinkNode(e->GetNode(3),e->GetNode(0),e->GetNode(7));
124 myCreateQuadratic = false;
133 if ( nbOldLinks == myTLinkNodeMap.size() )
134 myCreateQuadratic = false;
136 if(!myCreateQuadratic) {
137 myTLinkNodeMap.clear();
141 return myCreateQuadratic;
144 //================================================================================
146 * \brief Set geomerty to make elements on
147 * \param aSh - geomertic shape
149 //================================================================================
151 void SMESH_MesherHelper::SetSubShape(const int aShID)
153 if ( aShID == myShapeID )
156 SetSubShape( GetMeshDS()->IndexToShape( aShID ));
158 SetSubShape( TopoDS_Shape() );
161 //================================================================================
163 * \brief Set geomerty to make elements on
164 * \param aSh - geomertic shape
166 //================================================================================
168 void SMESH_MesherHelper::SetSubShape(const TopoDS_Shape& aSh)
170 if ( myShape.IsSame( aSh ))
174 mySeamShapeIds.clear();
175 myDegenShapeIds.clear();
177 if ( myShape.IsNull() ) {
181 SMESHDS_Mesh* meshDS = GetMeshDS();
182 myShapeID = meshDS->ShapeToIndex(aSh);
184 // treatment of periodic faces
185 for ( TopExp_Explorer eF( aSh, TopAbs_FACE ); eF.More(); eF.Next() )
187 const TopoDS_Face& face = TopoDS::Face( eF.Current() );
188 BRepAdaptor_Surface surface( face );
189 if ( surface.IsUPeriodic() || surface.IsVPeriodic() )
191 for (TopExp_Explorer exp( face, TopAbs_EDGE ); exp.More(); exp.Next())
193 // look for a seam edge
194 const TopoDS_Edge& edge = TopoDS::Edge( exp.Current() );
195 if ( BRep_Tool::IsClosed( edge, face )) {
196 // initialize myPar1, myPar2 and myParIndex
197 if ( mySeamShapeIds.empty() ) {
199 BRep_Tool::UVPoints( edge, face, uv1, uv2 );
200 if ( Abs( uv1.Coord(1) - uv2.Coord(1) ) < Abs( uv1.Coord(2) - uv2.Coord(2) ))
202 myParIndex = 1; // U periodic
203 myPar1 = surface.FirstUParameter();
204 myPar2 = surface.LastUParameter();
207 myParIndex = 2; // V periodic
208 myPar1 = surface.FirstVParameter();
209 myPar2 = surface.LastVParameter();
212 // store seam shape indices, negative if shape encounters twice
213 int edgeID = meshDS->ShapeToIndex( edge );
214 mySeamShapeIds.insert( IsSeamShape( edgeID ) ? -edgeID : edgeID );
215 for ( TopExp_Explorer v( edge, TopAbs_VERTEX ); v.More(); v.Next() ) {
216 int vertexID = meshDS->ShapeToIndex( v.Current() );
217 mySeamShapeIds.insert( IsSeamShape( vertexID ) ? -vertexID : vertexID );
221 // look for a degenerated edge
222 if ( BRep_Tool::Degenerated( edge )) {
223 myDegenShapeIds.insert( meshDS->ShapeToIndex( edge ));
224 for ( TopExp_Explorer v( edge, TopAbs_VERTEX ); v.More(); v.Next() )
225 myDegenShapeIds.insert( meshDS->ShapeToIndex( v.Current() ));
232 //================================================================================
234 * \brief Check if inFaceNode argument is necessary for call GetNodeUV(F,..)
235 * \param F - the face
236 * \retval bool - return true if the face is periodic
238 //================================================================================
240 bool SMESH_MesherHelper::GetNodeUVneedInFaceNode(const TopoDS_Face& F) const
242 if ( F.IsNull() ) return !mySeamShapeIds.empty();
244 if ( !F.IsNull() && !myShape.IsNull() && myShape.IsSame( F ))
245 return !mySeamShapeIds.empty();
248 Handle(Geom_Surface) aSurface = BRep_Tool::Surface( F,loc );
249 if ( !aSurface.IsNull() )
250 return ( aSurface->IsUPeriodic() || aSurface->IsVPeriodic() );
255 //=======================================================================
256 //function : IsMedium
258 //=======================================================================
260 bool SMESH_MesherHelper::IsMedium(const SMDS_MeshNode* node,
261 const SMDSAbs_ElementType typeToCheck)
263 return SMESH_MeshEditor::IsMedium( node, typeToCheck );
266 //=======================================================================
268 * \brief Return support shape of a node
269 * \param node - the node
270 * \param meshDS - mesh DS
271 * \retval TopoDS_Shape - found support shape
273 //=======================================================================
275 TopoDS_Shape SMESH_MesherHelper::GetSubShapeByNode(const SMDS_MeshNode* node,
276 SMESHDS_Mesh* meshDS)
278 int shapeID = node->GetPosition()->GetShapeId();
279 if ( 0 < shapeID && shapeID <= meshDS->MaxShapeIndex() )
280 return meshDS->IndexToShape( shapeID );
282 return TopoDS_Shape();
286 //=======================================================================
287 //function : AddTLinkNode
289 //=======================================================================
291 * Auxilary function for filling myTLinkNodeMap
293 void SMESH_MesherHelper::AddTLinkNode(const SMDS_MeshNode* n1,
294 const SMDS_MeshNode* n2,
295 const SMDS_MeshNode* n12)
297 // add new record to map
298 SMESH_TLink link( n1, n2 );
299 myTLinkNodeMap.insert( make_pair(link,n12));
302 //=======================================================================
304 * \brief Select UV on either of 2 pcurves of a seam edge, closest to the given UV
305 * \param uv1 - UV on the seam
306 * \param uv2 - UV within a face
307 * \retval gp_Pnt2d - selected UV
309 //=======================================================================
311 gp_Pnt2d SMESH_MesherHelper::GetUVOnSeam( const gp_Pnt2d& uv1, const gp_Pnt2d& uv2 ) const
313 double p1 = uv1.Coord( myParIndex );
314 double p2 = uv2.Coord( myParIndex );
315 double p3 = ( Abs( p1 - myPar1 ) < Abs( p1 - myPar2 )) ? myPar2 : myPar1;
316 if ( Abs( p2 - p1 ) > Abs( p2 - p3 ))
318 gp_Pnt2d result = uv1;
319 result.SetCoord( myParIndex, p1 );
323 //=======================================================================
325 * \brief Return node UV on face
326 * \param F - the face
327 * \param n - the node
328 * \param n2 - a node of element being created located inside a face
329 * \retval gp_XY - resulting UV
331 * Auxilary function called form GetMediumNode()
333 //=======================================================================
335 gp_XY SMESH_MesherHelper::GetNodeUV(const TopoDS_Face& F,
336 const SMDS_MeshNode* n,
337 const SMDS_MeshNode* n2,
340 gp_Pnt2d uv( 1e100, 1e100 );
341 const SMDS_PositionPtr Pos = n->GetPosition();
342 if(Pos->GetTypeOfPosition()==SMDS_TOP_FACE)
344 // node has position on face
345 const SMDS_FacePosition* fpos =
346 static_cast<const SMDS_FacePosition*>(n->GetPosition().get());
347 uv.SetCoord(fpos->GetUParameter(),fpos->GetVParameter());
348 if ( check && *check )
350 // check that uv is correct
352 Handle(Geom_Surface) surface = BRep_Tool::Surface( F,loc );
353 double tol = 2 * BRep_Tool::Tolerance( F );
354 gp_Pnt nodePnt = XYZ( n );
355 if ( !loc.IsIdentity() ) nodePnt.Transform( loc.Transformation().Inverted() );
356 if ( nodePnt.Distance( surface->Value( uv.X(), uv.Y() )) > tol ) {
357 // uv incorrect, project the node to surface
358 GeomAPI_ProjectPointOnSurf projector( nodePnt, surface, tol );
359 if ( !projector.IsDone() || projector.NbPoints() < 1 ) {
360 MESSAGE( "SMESH_MesherHelper::GetNodeUV() failed to project" )
363 Quantity_Parameter U,V;
364 projector.LowerDistanceParameters(U,V);
365 if ( nodePnt.Distance( surface->Value( U, V )) > tol )
366 MESSAGE( "SMESH_MesherHelper::GetNodeUV(), invalid projection" );
369 else if ( uv.XY().Modulus() > numeric_limits<double>::min() ) {
370 *check = false; // parameters are OK, do not check further more
374 else if(Pos->GetTypeOfPosition()==SMDS_TOP_EDGE)
376 // node has position on edge => it is needed to find
377 // corresponding edge from face, get pcurve for this
378 // edge and retrieve value from this pcurve
379 const SMDS_EdgePosition* epos =
380 static_cast<const SMDS_EdgePosition*>(n->GetPosition().get());
381 int edgeID = Pos->GetShapeId();
382 TopoDS_Edge E = TopoDS::Edge(GetMeshDS()->IndexToShape(edgeID));
384 Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface(E, F, f, l);
385 uv = C2d->Value( epos->GetUParameter() );
386 // for a node on a seam edge select one of UVs on 2 pcurves
387 if ( n2 && IsSeamShape( edgeID ) )
388 uv = GetUVOnSeam( uv, GetNodeUV( F, n2, 0 ));
390 // adjust uv to period
392 Handle(Geom_Surface) S = BRep_Tool::Surface(F,loc);
393 Standard_Boolean isUPeriodic = S->IsUPeriodic();
394 Standard_Boolean isVPeriodic = S->IsVPeriodic();
395 if ( isUPeriodic || isVPeriodic ) {
396 Standard_Real UF,UL,VF,VL;
397 S->Bounds(UF,UL,VF,VL);
399 uv.SetX( uv.X() + ShapeAnalysis::AdjustToPeriod(uv.X(),UF,UL));
401 uv.SetY( uv.Y() + ShapeAnalysis::AdjustToPeriod(uv.Y(),VF,VL));
404 else if(Pos->GetTypeOfPosition()==SMDS_TOP_VERTEX)
406 if ( int vertexID = n->GetPosition()->GetShapeId() ) {
408 const TopoDS_Vertex& V = TopoDS::Vertex(GetMeshDS()->IndexToShape(vertexID));
410 uv = BRep_Tool::Parameters( V, F );
412 catch (Standard_Failure& exc) {
416 for ( TopExp_Explorer vert(F,TopAbs_VERTEX); !ok && vert.More(); vert.Next() )
417 ok = ( V == vert.Current() );
420 MESSAGE ( "SMESH_MesherHelper::GetNodeUV(); Vertex " << vertexID
421 << " not in face " << GetMeshDS()->ShapeToIndex( F ) );
423 // get UV of a vertex closest to the node
425 gp_Pnt pn = XYZ( n );
426 for ( TopExp_Explorer vert(F,TopAbs_VERTEX); !ok && vert.More(); vert.Next() ) {
427 TopoDS_Vertex curV = TopoDS::Vertex( vert.Current() );
428 gp_Pnt p = BRep_Tool::Pnt( curV );
429 double curDist = p.SquareDistance( pn );
430 if ( curDist < dist ) {
432 uv = BRep_Tool::Parameters( curV, F );
433 if ( dist < DBL_MIN ) break;
438 TopTools_ListIteratorOfListOfShape it( myMesh->GetAncestors( V ));
439 for ( ; it.More(); it.Next() ) {
440 if ( it.Value().ShapeType() == TopAbs_EDGE ) {
441 const TopoDS_Edge & edge = TopoDS::Edge( it.Value() );
443 Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface(edge, F, f, l);
444 if ( !C2d.IsNull() ) {
445 double u = ( V == TopExp::FirstVertex( edge ) ) ? f : l;
446 uv = C2d->Value( u );
453 if ( n2 && IsSeamShape( vertexID ) )
454 uv = GetUVOnSeam( uv, GetNodeUV( F, n2, 0 ));
460 //=======================================================================
462 * \brief Return middle UV taking in account surface period
464 //=======================================================================
466 gp_XY SMESH_MesherHelper::GetMiddleUV(const Handle(Geom_Surface)& surface,
470 if ( surface.IsNull() )
471 return 0.5 * ( p1 + p2 );
472 //checking if surface is periodic
473 Standard_Real UF,UL,VF,VL;
474 surface->Bounds(UF,UL,VF,VL);
477 Standard_Boolean isUPeriodic = surface->IsUPeriodic();
479 Standard_Real UPeriod = surface->UPeriod();
480 Standard_Real p2x = p2.X()+ShapeAnalysis::AdjustByPeriod(p2.X(),p1.X(),UPeriod);
481 Standard_Real pmid = (p1.X()+p2x)/2.;
482 u = pmid+ShapeAnalysis::AdjustToPeriod(pmid,UF,UL);
485 u= (p1.X()+p2.X())/2.;
487 Standard_Boolean isVPeriodic = surface->IsVPeriodic();
489 Standard_Real VPeriod = surface->VPeriod();
490 Standard_Real p2y = p2.Y()+ShapeAnalysis::AdjustByPeriod(p2.Y(),p1.Y(),VPeriod);
491 Standard_Real pmid = (p1.Y()+p2y)/2.;
492 v = pmid+ShapeAnalysis::AdjustToPeriod(pmid,VF,VL);
495 v = (p1.Y()+p2.Y())/2.;
500 //=======================================================================
502 * \brief Return node U on edge
503 * \param E - the Edge
504 * \param n - the node
505 * \retval double - resulting U
507 * Auxilary function called form GetMediumNode()
509 //=======================================================================
511 double SMESH_MesherHelper::GetNodeU(const TopoDS_Edge& E,
512 const SMDS_MeshNode* n,
516 const SMDS_PositionPtr Pos = n->GetPosition();
517 if(Pos->GetTypeOfPosition()==SMDS_TOP_EDGE) {
518 const SMDS_EdgePosition* epos =
519 static_cast<const SMDS_EdgePosition*>(n->GetPosition().get());
520 param = epos->GetUParameter();
522 else if(Pos->GetTypeOfPosition()==SMDS_TOP_VERTEX) {
523 SMESHDS_Mesh * meshDS = GetMeshDS();
524 int vertexID = n->GetPosition()->GetShapeId();
525 const TopoDS_Vertex& V = TopoDS::Vertex(meshDS->IndexToShape(vertexID));
526 param = BRep_Tool::Parameter( V, E );
531 //================================================================================
533 * \brief Return existing or create new medium nodes between given ones
534 * \param force3d - if true, new node is the middle of n1 and n2,
535 * else is located on geom face or geom edge
537 //================================================================================
539 const SMDS_MeshNode* SMESH_MesherHelper::GetMediumNode(const SMDS_MeshNode* n1,
540 const SMDS_MeshNode* n2,
543 SMESH_TLink link(n1,n2);
544 ItTLinkNode itLN = myTLinkNodeMap.find( link );
545 if ( itLN != myTLinkNodeMap.end() ) {
546 return (*itLN).second;
548 // create medium node
550 SMESHDS_Mesh* meshDS = GetMeshDS();
551 int faceID = -1, edgeID = -1;
552 const SMDS_PositionPtr Pos1 = n1->GetPosition();
553 const SMDS_PositionPtr Pos2 = n2->GetPosition();
555 if( myShape.IsNull() )
557 if( Pos1->GetTypeOfPosition()==SMDS_TOP_FACE ) {
558 faceID = Pos1->GetShapeId();
560 else if( Pos2->GetTypeOfPosition()==SMDS_TOP_FACE ) {
561 faceID = Pos2->GetShapeId();
564 if( Pos1->GetTypeOfPosition()==SMDS_TOP_EDGE ) {
565 edgeID = Pos1->GetShapeId();
567 if( Pos2->GetTypeOfPosition()==SMDS_TOP_EDGE ) {
568 edgeID = Pos2->GetShapeId();
573 // we try to create medium node using UV parameters of
574 // nodes, else - medium between corresponding 3d points
576 TopAbs_ShapeEnum shapeType = myShape.IsNull() ? TopAbs_SHAPE : myShape.ShapeType();
577 if(faceID>0 || shapeType == TopAbs_FACE) {
578 // obtaining a face and 2d points for nodes
580 if( myShape.IsNull() )
581 F = TopoDS::Face(meshDS->IndexToShape(faceID));
583 F = TopoDS::Face(myShape);
587 gp_XY p1 = GetNodeUV(F,n1,n2, &myCheckNodePos);
588 gp_XY p2 = GetNodeUV(F,n2,n1, &myCheckNodePos);
590 if ( IsDegenShape( Pos1->GetShapeId() ))
591 p1.SetCoord( myParIndex, p2.Coord( myParIndex ));
592 else if ( IsDegenShape( Pos2->GetShapeId() ))
593 p2.SetCoord( myParIndex, p1.Coord( myParIndex ));
596 Handle(Geom_Surface) S = BRep_Tool::Surface(F,loc);
597 gp_XY uv = GetMiddleUV( S, p1, p2 );
598 gp_Pnt P = S->Value( uv.X(), uv.Y() ).Transformed(loc);
599 n12 = meshDS->AddNode(P.X(), P.Y(), P.Z());
600 meshDS->SetNodeOnFace(n12, faceID, uv.X(), uv.Y());
601 myTLinkNodeMap.insert(make_pair(link,n12));
604 if (edgeID>0 || shapeType == TopAbs_EDGE) {
607 if( myShape.IsNull() )
608 E = TopoDS::Edge(meshDS->IndexToShape(edgeID));
610 E = TopoDS::Edge(myShape);
614 double p1 = GetNodeU(E,n1, &myCheckNodePos);
615 double p2 = GetNodeU(E,n2, &myCheckNodePos);
618 Handle(Geom_Curve) C = BRep_Tool::Curve(E, f, l);
621 Standard_Boolean isPeriodic = C->IsPeriodic();
624 Standard_Real Period = C->Period();
625 Standard_Real p = p2+ShapeAnalysis::AdjustByPeriod(p2,p1,Period);
626 Standard_Real pmid = (p1+p)/2.;
627 u = pmid+ShapeAnalysis::AdjustToPeriod(pmid,C->FirstParameter(),C->LastParameter());
632 gp_Pnt P = C->Value( u );
633 n12 = meshDS->AddNode(P.X(), P.Y(), P.Z());
634 meshDS->SetNodeOnEdge(n12, edgeID, u);
635 myTLinkNodeMap.insert(make_pair(link,n12));
641 double x = ( n1->X() + n2->X() )/2.;
642 double y = ( n1->Y() + n2->Y() )/2.;
643 double z = ( n1->Z() + n2->Z() )/2.;
644 n12 = meshDS->AddNode(x,y,z);
646 meshDS->SetNodeOnEdge(n12, edgeID);
648 meshDS->SetNodeOnFace(n12, faceID);
650 meshDS->SetNodeInVolume(n12, myShapeID);
651 myTLinkNodeMap.insert( make_pair( link, n12 ));
655 //=======================================================================
659 //=======================================================================
661 SMDS_MeshNode* SMESH_MesherHelper::AddNode(double x, double y, double z, int ID)
663 SMESHDS_Mesh * meshDS = GetMeshDS();
664 SMDS_MeshNode* node = 0;
666 node = meshDS->AddNodeWithID( x, y, z, ID );
668 node = meshDS->AddNode( x, y, z );
669 if ( mySetElemOnShape && myShapeID > 0 ) {
670 switch ( myShape.ShapeType() ) {
671 case TopAbs_SOLID: meshDS->SetNodeInVolume( node, myShapeID); break;
672 case TopAbs_SHELL: meshDS->SetNodeInVolume( node, myShapeID); break;
673 case TopAbs_FACE: meshDS->SetNodeOnFace( node, myShapeID); break;
674 case TopAbs_EDGE: meshDS->SetNodeOnEdge( node, myShapeID); break;
675 case TopAbs_VERTEX: meshDS->SetNodeOnVertex( node, myShapeID); break;
682 //=======================================================================
684 * Creates quadratic or linear edge
686 //=======================================================================
688 SMDS_MeshEdge* SMESH_MesherHelper::AddEdge(const SMDS_MeshNode* n1,
689 const SMDS_MeshNode* n2,
693 SMESHDS_Mesh * meshDS = GetMeshDS();
695 SMDS_MeshEdge* edge = 0;
696 if (myCreateQuadratic) {
697 const SMDS_MeshNode* n12 = GetMediumNode(n1,n2,force3d);
699 edge = meshDS->AddEdgeWithID(n1, n2, n12, id);
701 edge = meshDS->AddEdge(n1, n2, n12);
705 edge = meshDS->AddEdgeWithID(n1, n2, id);
707 edge = meshDS->AddEdge(n1, n2);
710 if ( mySetElemOnShape && myShapeID > 0 )
711 meshDS->SetMeshElementOnShape( edge, myShapeID );
716 //=======================================================================
718 * Creates quadratic or linear triangle
720 //=======================================================================
722 SMDS_MeshFace* SMESH_MesherHelper::AddFace(const SMDS_MeshNode* n1,
723 const SMDS_MeshNode* n2,
724 const SMDS_MeshNode* n3,
728 SMESHDS_Mesh * meshDS = GetMeshDS();
729 SMDS_MeshFace* elem = 0;
730 if(!myCreateQuadratic) {
732 elem = meshDS->AddFaceWithID(n1, n2, n3, id);
734 elem = meshDS->AddFace(n1, n2, n3);
737 const SMDS_MeshNode* n12 = GetMediumNode(n1,n2,force3d);
738 const SMDS_MeshNode* n23 = GetMediumNode(n2,n3,force3d);
739 const SMDS_MeshNode* n31 = GetMediumNode(n3,n1,force3d);
742 elem = meshDS->AddFaceWithID(n1, n2, n3, n12, n23, n31, id);
744 elem = meshDS->AddFace(n1, n2, n3, n12, n23, n31);
746 if ( mySetElemOnShape && myShapeID > 0 )
747 meshDS->SetMeshElementOnShape( elem, myShapeID );
752 //=======================================================================
754 * Creates quadratic or linear quadrangle
756 //=======================================================================
758 SMDS_MeshFace* SMESH_MesherHelper::AddFace(const SMDS_MeshNode* n1,
759 const SMDS_MeshNode* n2,
760 const SMDS_MeshNode* n3,
761 const SMDS_MeshNode* n4,
765 SMESHDS_Mesh * meshDS = GetMeshDS();
766 SMDS_MeshFace* elem = 0;
767 if(!myCreateQuadratic) {
769 elem = meshDS->AddFaceWithID(n1, n2, n3, n4, id);
771 elem = meshDS->AddFace(n1, n2, n3, n4);
774 const SMDS_MeshNode* n12 = GetMediumNode(n1,n2,force3d);
775 const SMDS_MeshNode* n23 = GetMediumNode(n2,n3,force3d);
776 const SMDS_MeshNode* n34 = GetMediumNode(n3,n4,force3d);
777 const SMDS_MeshNode* n41 = GetMediumNode(n4,n1,force3d);
780 elem = meshDS->AddFaceWithID(n1, n2, n3, n4, n12, n23, n34, n41, id);
782 elem = meshDS->AddFace(n1, n2, n3, n4, n12, n23, n34, n41);
784 if ( mySetElemOnShape && myShapeID > 0 )
785 meshDS->SetMeshElementOnShape( elem, myShapeID );
790 //=======================================================================
792 * Creates quadratic or linear volume
794 //=======================================================================
796 SMDS_MeshVolume* SMESH_MesherHelper::AddVolume(const SMDS_MeshNode* n1,
797 const SMDS_MeshNode* n2,
798 const SMDS_MeshNode* n3,
799 const SMDS_MeshNode* n4,
800 const SMDS_MeshNode* n5,
801 const SMDS_MeshNode* n6,
805 SMESHDS_Mesh * meshDS = GetMeshDS();
806 SMDS_MeshVolume* elem = 0;
807 if(!myCreateQuadratic) {
809 elem = meshDS->AddVolumeWithID(n1, n2, n3, n4, n5, n6, id);
811 elem = meshDS->AddVolume(n1, n2, n3, n4, n5, n6);
814 const SMDS_MeshNode* n12 = GetMediumNode(n1,n2,force3d);
815 const SMDS_MeshNode* n23 = GetMediumNode(n2,n3,force3d);
816 const SMDS_MeshNode* n31 = GetMediumNode(n3,n1,force3d);
818 const SMDS_MeshNode* n45 = GetMediumNode(n4,n5,force3d);
819 const SMDS_MeshNode* n56 = GetMediumNode(n5,n6,force3d);
820 const SMDS_MeshNode* n64 = GetMediumNode(n6,n4,force3d);
822 const SMDS_MeshNode* n14 = GetMediumNode(n1,n4,force3d);
823 const SMDS_MeshNode* n25 = GetMediumNode(n2,n5,force3d);
824 const SMDS_MeshNode* n36 = GetMediumNode(n3,n6,force3d);
827 elem = meshDS->AddVolumeWithID(n1, n2, n3, n4, n5, n6,
828 n12, n23, n31, n45, n56, n64, n14, n25, n36, id);
830 elem = meshDS->AddVolume(n1, n2, n3, n4, n5, n6,
831 n12, n23, n31, n45, n56, n64, n14, n25, n36);
833 if ( mySetElemOnShape && myShapeID > 0 )
834 meshDS->SetMeshElementOnShape( elem, myShapeID );
839 //=======================================================================
841 * Creates quadratic or linear volume
843 //=======================================================================
845 SMDS_MeshVolume* SMESH_MesherHelper::AddVolume(const SMDS_MeshNode* n1,
846 const SMDS_MeshNode* n2,
847 const SMDS_MeshNode* n3,
848 const SMDS_MeshNode* n4,
852 SMESHDS_Mesh * meshDS = GetMeshDS();
853 SMDS_MeshVolume* elem = 0;
854 if(!myCreateQuadratic) {
856 elem = meshDS->AddVolumeWithID(n1, n2, n3, n4, id);
858 elem = meshDS->AddVolume(n1, n2, n3, n4);
861 const SMDS_MeshNode* n12 = GetMediumNode(n1,n2,force3d);
862 const SMDS_MeshNode* n23 = GetMediumNode(n2,n3,force3d);
863 const SMDS_MeshNode* n31 = GetMediumNode(n3,n1,force3d);
865 const SMDS_MeshNode* n14 = GetMediumNode(n1,n4,force3d);
866 const SMDS_MeshNode* n24 = GetMediumNode(n2,n4,force3d);
867 const SMDS_MeshNode* n34 = GetMediumNode(n3,n4,force3d);
870 elem = meshDS->AddVolumeWithID(n1, n2, n3, n4, n12, n23, n31, n14, n24, n34, id);
872 elem = meshDS->AddVolume(n1, n2, n3, n4, n12, n23, n31, n14, n24, n34);
874 if ( mySetElemOnShape && myShapeID > 0 )
875 meshDS->SetMeshElementOnShape( elem, myShapeID );
880 //=======================================================================
882 * Creates quadratic or linear pyramid
884 //=======================================================================
886 SMDS_MeshVolume* SMESH_MesherHelper::AddVolume(const SMDS_MeshNode* n1,
887 const SMDS_MeshNode* n2,
888 const SMDS_MeshNode* n3,
889 const SMDS_MeshNode* n4,
890 const SMDS_MeshNode* n5,
894 SMDS_MeshVolume* elem = 0;
895 if(!myCreateQuadratic) {
897 elem = GetMeshDS()->AddVolumeWithID(n1, n2, n3, n4, n5, id);
899 elem = GetMeshDS()->AddVolume(n1, n2, n3, n4, n5);
902 const SMDS_MeshNode* n12 = GetMediumNode(n1,n2,force3d);
903 const SMDS_MeshNode* n23 = GetMediumNode(n2,n3,force3d);
904 const SMDS_MeshNode* n34 = GetMediumNode(n3,n4,force3d);
905 const SMDS_MeshNode* n41 = GetMediumNode(n4,n1,force3d);
907 const SMDS_MeshNode* n15 = GetMediumNode(n1,n5,force3d);
908 const SMDS_MeshNode* n25 = GetMediumNode(n2,n5,force3d);
909 const SMDS_MeshNode* n35 = GetMediumNode(n3,n5,force3d);
910 const SMDS_MeshNode* n45 = GetMediumNode(n4,n5,force3d);
913 elem = GetMeshDS()->AddVolumeWithID ( n1, n2, n3, n4, n5,
918 elem = GetMeshDS()->AddVolume( n1, n2, n3, n4, n5,
922 if ( mySetElemOnShape && myShapeID > 0 )
923 GetMeshDS()->SetMeshElementOnShape( elem, myShapeID );
928 //=======================================================================
930 * Creates quadratic or linear hexahedron
932 //=======================================================================
934 SMDS_MeshVolume* SMESH_MesherHelper::AddVolume(const SMDS_MeshNode* n1,
935 const SMDS_MeshNode* n2,
936 const SMDS_MeshNode* n3,
937 const SMDS_MeshNode* n4,
938 const SMDS_MeshNode* n5,
939 const SMDS_MeshNode* n6,
940 const SMDS_MeshNode* n7,
941 const SMDS_MeshNode* n8,
945 SMESHDS_Mesh * meshDS = GetMeshDS();
946 SMDS_MeshVolume* elem = 0;
947 if(!myCreateQuadratic) {
949 elem = meshDS->AddVolumeWithID(n1, n2, n3, n4, n5, n6, n7, n8, id);
951 elem = meshDS->AddVolume(n1, n2, n3, n4, n5, n6, n7, n8);
954 const SMDS_MeshNode* n12 = GetMediumNode(n1,n2,force3d);
955 const SMDS_MeshNode* n23 = GetMediumNode(n2,n3,force3d);
956 const SMDS_MeshNode* n34 = GetMediumNode(n3,n4,force3d);
957 const SMDS_MeshNode* n41 = GetMediumNode(n4,n1,force3d);
959 const SMDS_MeshNode* n56 = GetMediumNode(n5,n6,force3d);
960 const SMDS_MeshNode* n67 = GetMediumNode(n6,n7,force3d);
961 const SMDS_MeshNode* n78 = GetMediumNode(n7,n8,force3d);
962 const SMDS_MeshNode* n85 = GetMediumNode(n8,n5,force3d);
964 const SMDS_MeshNode* n15 = GetMediumNode(n1,n5,force3d);
965 const SMDS_MeshNode* n26 = GetMediumNode(n2,n6,force3d);
966 const SMDS_MeshNode* n37 = GetMediumNode(n3,n7,force3d);
967 const SMDS_MeshNode* n48 = GetMediumNode(n4,n8,force3d);
970 elem = meshDS->AddVolumeWithID(n1, n2, n3, n4, n5, n6, n7, n8,
971 n12, n23, n34, n41, n56, n67,
972 n78, n85, n15, n26, n37, n48, id);
974 elem = meshDS->AddVolume(n1, n2, n3, n4, n5, n6, n7, n8,
975 n12, n23, n34, n41, n56, n67,
976 n78, n85, n15, n26, n37, n48);
978 if ( mySetElemOnShape && myShapeID > 0 )
979 meshDS->SetMeshElementOnShape( elem, myShapeID );
984 //=======================================================================
986 * \brief Load nodes bound to face into a map of node columns
987 * \param theParam2ColumnMap - map of node columns to fill
988 * \param theFace - the face on which nodes are searched for
989 * \param theBaseEdge - the edge nodes of which are columns' bases
990 * \param theMesh - the mesh containing nodes
991 * \retval bool - false if something is wrong
993 * The key of the map is a normalized parameter of each
994 * base node on theBaseEdge.
995 * This method works in supposition that nodes on the face
996 * forms a rectangular grid and elements can be quardrangles or triangles
998 //=======================================================================
1000 bool SMESH_MesherHelper::LoadNodeColumns(TParam2ColumnMap & theParam2ColumnMap,
1001 const TopoDS_Face& theFace,
1002 const TopoDS_Edge& theBaseEdge,
1003 SMESHDS_Mesh* theMesh)
1005 // get vertices of theBaseEdge
1006 TopoDS_Vertex vfb, vlb, vft; // first and last, bottom and top vertices
1007 TopoDS_Edge eFrw = TopoDS::Edge( theBaseEdge.Oriented( TopAbs_FORWARD ));
1008 TopExp::Vertices( eFrw, vfb, vlb );
1010 // find the other edges of theFace and orientation of e1
1011 TopoDS_Edge e1, e2, eTop;
1012 bool rev1, CumOri = false;
1013 TopExp_Explorer exp( theFace, TopAbs_EDGE );
1015 for ( ; exp.More(); exp.Next() ) {
1016 if ( ++nbEdges > 4 ) {
1017 return false; // more than 4 edges in theFace
1019 TopoDS_Edge e = TopoDS::Edge( exp.Current() );
1020 if ( theBaseEdge.IsSame( e ))
1022 TopoDS_Vertex vCommon;
1023 if ( !TopExp::CommonVertex( theBaseEdge, e, vCommon ))
1025 else if ( vCommon.IsSame( vfb )) {
1027 vft = TopExp::LastVertex( e1, CumOri );
1028 rev1 = vfb.IsSame( vft );
1030 vft = TopExp::FirstVertex( e1, CumOri );
1035 if ( nbEdges < 4 ) {
1036 return false; // less than 4 edges in theFace
1038 if ( e2.IsNull() && vfb.IsSame( vlb ))
1041 // submeshes corresponding to shapes
1042 SMESHDS_SubMesh* smFace = theMesh->MeshElements( theFace );
1043 SMESHDS_SubMesh* smb = theMesh->MeshElements( theBaseEdge );
1044 SMESHDS_SubMesh* smt = theMesh->MeshElements( eTop );
1045 SMESHDS_SubMesh* sm1 = theMesh->MeshElements( e1 );
1046 SMESHDS_SubMesh* sm2 = theMesh->MeshElements( e2 );
1047 SMESHDS_SubMesh* smVfb = theMesh->MeshElements( vfb );
1048 SMESHDS_SubMesh* smVlb = theMesh->MeshElements( vlb );
1049 SMESHDS_SubMesh* smVft = theMesh->MeshElements( vft );
1050 if (!smFace || !smb || !smt || !sm1 || !sm2 || !smVfb || !smVlb || !smVft ) {
1051 RETURN_BAD_RESULT( "NULL submesh " <<smFace<<" "<<smb<<" "<<smt<<" "<<
1052 sm1<<" "<<sm2<<" "<<smVfb<<" "<<smVlb<<" "<<smVft);
1054 if ( smb->NbNodes() != smt->NbNodes() || sm1->NbNodes() != sm2->NbNodes() ) {
1055 RETURN_BAD_RESULT(" Diff nb of nodes on opposite edges" );
1057 if (smVfb->NbNodes() != 1 || smVlb->NbNodes() != 1 || smVft->NbNodes() != 1) {
1058 RETURN_BAD_RESULT("Empty submesh of vertex");
1060 // define whether mesh is quadratic
1061 bool isQuadraticMesh = false;
1062 SMDS_ElemIteratorPtr eIt = smFace->GetElements();
1063 if ( !eIt->more() ) {
1064 RETURN_BAD_RESULT("No elements on the face");
1066 const SMDS_MeshElement* e = eIt->next();
1067 isQuadraticMesh = e->IsQuadratic();
1069 if ( sm1->NbNodes() * smb->NbNodes() != smFace->NbNodes() ) {
1070 // check quadratic case
1071 if ( isQuadraticMesh ) {
1072 // what if there are quadrangles and triangles mixed?
1073 // int n1 = sm1->NbNodes()/2;
1074 // int n2 = smb->NbNodes()/2;
1075 // int n3 = sm1->NbNodes() - n1;
1076 // int n4 = smb->NbNodes() - n2;
1077 // int nf = sm1->NbNodes()*smb->NbNodes() - n3*n4;
1078 // if( nf != smFace->NbNodes() ) {
1079 // MESSAGE( "Wrong nb face nodes: " <<
1080 // sm1->NbNodes()<<" "<<smb->NbNodes()<<" "<<smFace->NbNodes());
1085 RETURN_BAD_RESULT( "Wrong nb face nodes: " <<
1086 sm1->NbNodes()<<" "<<smb->NbNodes()<<" "<<smFace->NbNodes());
1090 int vsize = sm1->NbNodes() + 2;
1091 int hsize = smb->NbNodes() + 2;
1092 if(isQuadraticMesh) {
1093 vsize = vsize - sm1->NbNodes()/2 -1;
1094 hsize = hsize - smb->NbNodes()/2 -1;
1097 // load nodes from theBaseEdge
1099 std::set<const SMDS_MeshNode*> loadedNodes;
1100 const SMDS_MeshNode* nullNode = 0;
1102 std::vector<const SMDS_MeshNode*> & nVecf = theParam2ColumnMap[ 0.];
1103 nVecf.resize( vsize, nullNode );
1104 loadedNodes.insert( nVecf[ 0 ] = smVfb->GetNodes()->next() );
1106 std::vector<const SMDS_MeshNode*> & nVecl = theParam2ColumnMap[ 1.];
1107 nVecl.resize( vsize, nullNode );
1108 loadedNodes.insert( nVecl[ 0 ] = smVlb->GetNodes()->next() );
1111 BRep_Tool::Range( eFrw, f, l );
1112 double range = l - f;
1113 SMDS_NodeIteratorPtr nIt = smb->GetNodes();
1114 const SMDS_MeshNode* node;
1115 while ( nIt->more() ) {
1117 if(IsMedium(node, SMDSAbs_Edge))
1119 const SMDS_EdgePosition* pos =
1120 dynamic_cast<const SMDS_EdgePosition*>( node->GetPosition().get() );
1124 double u = ( pos->GetUParameter() - f ) / range;
1125 std::vector<const SMDS_MeshNode*> & nVec = theParam2ColumnMap[ u ];
1126 nVec.resize( vsize, nullNode );
1127 loadedNodes.insert( nVec[ 0 ] = node );
1129 if ( theParam2ColumnMap.size() != hsize ) {
1130 RETURN_BAD_RESULT( "Wrong node positions on theBaseEdge" );
1133 // load nodes from e1
1135 std::map< double, const SMDS_MeshNode*> sortedNodes; // sort by param on edge
1136 nIt = sm1->GetNodes();
1137 while ( nIt->more() ) {
1141 const SMDS_EdgePosition* pos =
1142 dynamic_cast<const SMDS_EdgePosition*>( node->GetPosition().get() );
1146 sortedNodes.insert( std::make_pair( pos->GetUParameter(), node ));
1148 loadedNodes.insert( nVecf[ vsize - 1 ] = smVft->GetNodes()->next() );
1149 std::map< double, const SMDS_MeshNode*>::iterator u_n = sortedNodes.begin();
1150 int row = rev1 ? vsize - 1 : 0;
1151 int dRow = rev1 ? -1 : +1;
1152 for ( ; u_n != sortedNodes.end(); u_n++ ) {
1154 loadedNodes.insert( nVecf[ row ] = u_n->second );
1157 // try to load the rest nodes
1159 // get all faces from theFace
1160 TIDSortedElemSet allFaces, foundFaces;
1161 eIt = smFace->GetElements();
1162 while ( eIt->more() ) {
1163 const SMDS_MeshElement* e = eIt->next();
1164 if ( e->GetType() == SMDSAbs_Face )
1165 allFaces.insert( e );
1167 // Starting from 2 neighbour nodes on theBaseEdge, look for a face
1168 // the nodes belong to, and between the nodes of the found face,
1169 // look for a not loaded node considering this node to be the next
1170 // in a column of the starting second node. Repeat, starting
1171 // from nodes next to the previous starting nodes in their columns,
1172 // and so on while a face can be found. Then go the the next pair
1173 // of nodes on theBaseEdge.
1174 TParam2ColumnMap::iterator par_nVec_1 = theParam2ColumnMap.begin();
1175 TParam2ColumnMap::iterator par_nVec_2 = par_nVec_1;
1178 for ( par_nVec_2++; par_nVec_2 != theParam2ColumnMap.end(); par_nVec_1++, par_nVec_2++ ) {
1181 const SMDS_MeshNode* n1 = par_nVec_1->second[ row ];
1182 const SMDS_MeshNode* n2 = par_nVec_2->second[ row ];
1183 const SMDS_MeshElement* face = 0;
1184 bool lastColOnClosedFace = ( nVecf[ row ] == n2 );
1186 // look for a face by 2 nodes
1187 face = SMESH_MeshEditor::FindFaceInSet( n1, n2, allFaces, foundFaces );
1189 int nbFaceNodes = face->NbNodes();
1190 if ( face->IsQuadratic() )
1192 if ( nbFaceNodes>4 ) {
1193 RETURN_BAD_RESULT(" Too many nodes in a face: " << nbFaceNodes );
1195 // look for a not loaded node of the <face>
1197 const SMDS_MeshNode* n3 = 0; // a node defferent from n1 and n2
1198 for ( int i = 0; i < nbFaceNodes && !found; ++i ) {
1199 node = face->GetNode( i );
1200 found = loadedNodes.insert( node ).second;
1201 if ( !found && node != n1 && node != n2 )
1204 if ( lastColOnClosedFace && row + 1 < vsize ) {
1205 node = nVecf[ row + 1 ];
1206 found = ( face->GetNodeIndex( node ) >= 0 );
1209 if ( ++row > vsize - 1 ) {
1210 RETURN_BAD_RESULT( "Too many nodes in column "<< col <<": "<< row+1);
1212 par_nVec_2->second[ row ] = node;
1213 foundFaces.insert( face );
1215 if ( nbFaceNodes==4 ) {
1216 n1 = par_nVec_1->second[ row ];
1219 else if ( nbFaceNodes==3 && n3 == par_nVec_1->second[ row + 1 ] ) {
1223 RETURN_BAD_RESULT( "Not quad mesh, column "<< col );
1227 while ( face && n1 && n2 );
1229 if ( row < vsize - 1 ) {
1230 MESSAGE( "Too few nodes in column "<< col <<": "<< row+1);
1231 MESSAGE( "Base node 1: "<< par_nVec_1->second[0]);
1232 MESSAGE( "Base node 2: "<< par_nVec_2->second[0]);
1233 if ( n1 ) { MESSAGE( "Current node 1: "<< n1); }
1234 else { MESSAGE( "Current node 1: NULL"); }
1235 if ( n2 ) { MESSAGE( "Current node 2: "<< n2); }
1236 else { MESSAGE( "Current node 2: NULL"); }
1237 MESSAGE( "first base node: "<< theParam2ColumnMap.begin()->second[0]);
1238 MESSAGE( "last base node: "<< theParam2ColumnMap.rbegin()->second[0]);
1241 } // loop on columns
1246 //=======================================================================
1248 * \brief Return number of unique ancestors of the shape
1250 //=======================================================================
1252 int SMESH_MesherHelper::NbAncestors(const TopoDS_Shape& shape,
1253 const SMESH_Mesh& mesh,
1254 TopAbs_ShapeEnum ancestorType/*=TopAbs_SHAPE*/)
1256 TopTools_MapOfShape ancestors;
1257 TopTools_ListIteratorOfListOfShape ansIt( mesh.GetAncestors(shape) );
1258 for ( ; ansIt.More(); ansIt.Next() ) {
1259 if ( ancestorType == TopAbs_SHAPE || ansIt.Value().ShapeType() == ancestorType )
1260 ancestors.Add( ansIt.Value() );
1262 return ancestors.Extent();
1265 //=======================================================================
1267 * Check mesh without geometry for: if all elements on this shape are quadratic,
1268 * quadratic elements will be created.
1269 * Used then generated 3D mesh without geometry.
1271 //=======================================================================
1273 SMESH_MesherHelper:: MType SMESH_MesherHelper::IsQuadraticMesh()
1275 int NbAllEdgsAndFaces=0;
1276 int NbQuadFacesAndEdgs=0;
1277 int NbFacesAndEdges=0;
1278 //All faces and edges
1279 NbAllEdgsAndFaces = myMesh->NbEdges() + myMesh->NbFaces();
1281 //Quadratic faces and edges
1282 NbQuadFacesAndEdgs = myMesh->NbEdges(ORDER_QUADRATIC) + myMesh->NbFaces(ORDER_QUADRATIC);
1284 //Linear faces and edges
1285 NbFacesAndEdges = myMesh->NbEdges(ORDER_LINEAR) + myMesh->NbFaces(ORDER_LINEAR);
1287 if (NbAllEdgsAndFaces == NbQuadFacesAndEdgs) {
1289 return SMESH_MesherHelper::QUADRATIC;
1291 else if (NbAllEdgsAndFaces == NbFacesAndEdges) {
1293 return SMESH_MesherHelper::LINEAR;
1296 //Mesh with both type of elements
1297 return SMESH_MesherHelper::COMP;
1300 //=======================================================================
1302 * \brief Return an alternative parameter for a node on seam
1304 //=======================================================================
1306 double SMESH_MesherHelper::GetOtherParam(const double param) const
1308 return fabs(param-myPar1) < fabs(param-myPar2) ? myPar2 : myPar1;
1311 //=======================================================================
1312 namespace { // Structures used by FixQuadraticElements()
1313 //=======================================================================
1315 #define __DMP__(txt) \
1317 #define MSG(txt) __DMP__(txt<<endl)
1318 #define MSGBEG(txt) __DMP__(txt)
1320 const double straightTol2 = 1e-33; // to detect straing links
1323 // ---------------------------------------
1325 * \brief Quadratic link knowing its faces
1327 struct QLink: public SMESH_TLink
1329 const SMDS_MeshNode* _mediumNode;
1330 mutable vector<const QFace* > _faces;
1331 mutable gp_Vec _nodeMove;
1332 mutable int _nbMoves;
1334 QLink(const SMDS_MeshNode* n1, const SMDS_MeshNode* n2, const SMDS_MeshNode* nm):
1335 SMESH_TLink( n1,n2 ), _mediumNode(nm), _nodeMove(0,0,0), _nbMoves(0) {
1337 //if ( MediumPos() != SMDS_TOP_3DSPACE )
1338 _nodeMove = MediumPnt() - MiddlePnt();
1340 void SetContinuesFaces() const;
1341 const QFace* GetContinuesFace( const QFace* face ) const;
1342 bool OnBoundary() const;
1343 gp_XYZ MiddlePnt() const { return ( XYZ( node1() ) + XYZ( node2() )) / 2.; }
1344 gp_XYZ MediumPnt() const { return XYZ( _mediumNode ); }
1346 SMDS_TypeOfPosition MediumPos() const
1347 { return _mediumNode->GetPosition()->GetTypeOfPosition(); }
1348 SMDS_TypeOfPosition EndPos(bool isSecond) const
1349 { return (isSecond ? node2() : node1())->GetPosition()->GetTypeOfPosition(); }
1350 const SMDS_MeshNode* EndPosNode(SMDS_TypeOfPosition pos) const
1351 { return EndPos(0) == pos ? node1() : EndPos(1) == pos ? node2() : 0; }
1353 void Move(const gp_Vec& move, bool sum=false) const
1354 { _nodeMove += move; _nbMoves += sum ? (_nbMoves==0) : 1; }
1355 gp_XYZ Move() const { return _nodeMove.XYZ() / _nbMoves; }
1356 bool IsMoved() const { return (_nbMoves > 0 && !IsStraight()); }
1357 bool IsStraight() const { return _nodeMove.SquareMagnitude() <= straightTol2; }
1359 bool operator<(const QLink& other) const {
1360 return (node1()->GetID() == other.node1()->GetID() ?
1361 node2()->GetID() < other.node2()->GetID() :
1362 node1()->GetID() < other.node1()->GetID());
1364 struct PtrComparator {
1365 bool operator() (const QLink* l1, const QLink* l2 ) const { return *l1 < *l2; }
1368 // ---------------------------------------------------------
1370 * \brief Link in the chain of links; it connects two faces
1374 const QLink* _qlink;
1375 mutable const QFace* _qfaces[2];
1377 TChainLink(const QLink* qlink=0):_qlink(qlink) {
1378 _qfaces[0] = _qfaces[1] = 0;
1380 void SetFace(const QFace* face) { int iF = _qfaces[0] ? 1 : 0; _qfaces[iF]=face; }
1382 bool IsBoundary() const { return !_qfaces[1]; }
1384 void RemoveFace( const QFace* face ) const
1385 { _qfaces[(face == _qfaces[1])] = 0; if (!_qfaces[0]) swap(_qfaces[0],_qfaces[1]); }
1387 const QFace* NextFace( const QFace* f ) const
1388 { return _qfaces[0]==f ? _qfaces[1] : _qfaces[0]; }
1390 const SMDS_MeshNode* NextNode( const SMDS_MeshNode* n ) const
1391 { return n == _qlink->node1() ? _qlink->node2() : _qlink->node1(); }
1393 bool operator<(const TChainLink& other) const { return *_qlink < *other._qlink; }
1395 operator bool() const { return (_qlink); }
1397 const QLink* operator->() const { return _qlink; }
1399 gp_Vec Normal() const;
1401 // --------------------------------------------------------------------
1402 typedef list< TChainLink > TChain;
1403 typedef set < TChainLink > TLinkSet;
1404 typedef TLinkSet::iterator TLinkInSet;
1406 const int theFirstStep = 5;
1408 enum { ERR_OK, ERR_TRI, ERR_PRISM, ERR_UNKNOWN }; // errors of QFace::GetLinkChain()
1409 // --------------------------------------------------------------------
1411 * \brief Face shared by two volumes and bound by QLinks
1413 struct QFace: public TIDSortedElemSet
1415 mutable const SMDS_MeshElement* _volumes[2];
1416 mutable vector< const QLink* > _sides;
1417 mutable bool _sideIsAdded[4]; // added in chain of links
1420 QFace( const vector< const QLink*>& links );
1422 void SetVolume(const SMDS_MeshElement* v) const { _volumes[ _volumes[0] ? 1 : 0 ] = v; }
1424 int NbVolumes() const { return !_volumes[0] ? 0 : !_volumes[1] ? 1 : 2; }
1426 void AddSelfToLinks() const {
1427 for ( int i = 0; i < _sides.size(); ++i )
1428 _sides[i]->_faces.push_back( this );
1430 int LinkIndex( const QLink* side ) const {
1431 for (int i=0; i<_sides.size(); ++i ) if ( _sides[i] == side ) return i;
1434 bool GetLinkChain( int iSide, TChain& chain, SMDS_TypeOfPosition pos, int& error) const;
1436 bool GetLinkChain( TChainLink& link, TChain& chain, SMDS_TypeOfPosition pos, int& error) const
1438 int i = LinkIndex( link._qlink );
1439 if ( i < 0 ) return true;
1440 _sideIsAdded[i] = true;
1441 link.SetFace( this );
1442 // continue from opposite link
1443 return GetLinkChain( (i+2)%_sides.size(), chain, pos, error );
1445 bool IsBoundary() const { return !_volumes[1]; }
1447 bool Contains( const SMDS_MeshNode* node ) const { return count(node); }
1449 TLinkInSet GetBoundaryLink( const TLinkSet& links,
1450 const TChainLink& avoidLink,
1451 TLinkInSet * notBoundaryLink = 0,
1452 const SMDS_MeshNode* nodeToContain = 0,
1453 bool * isAdjacentUsed = 0) const;
1455 TLinkInSet GetLinkByNode( const TLinkSet& links,
1456 const TChainLink& avoidLink,
1457 const SMDS_MeshNode* nodeToContain) const;
1459 const SMDS_MeshNode* GetNodeInFace() const {
1460 for ( int iL = 0; iL < _sides.size(); ++iL )
1461 if ( _sides[iL]->MediumPos() == SMDS_TOP_FACE ) return _sides[iL]->_mediumNode;
1465 gp_Vec LinkNorm(const int i, SMESH_MesherHelper* theFaceHelper=0) const;
1467 double MoveByBoundary( const TChainLink& theLink,
1468 const gp_Vec& theRefVec,
1469 const TLinkSet& theLinks,
1470 SMESH_MesherHelper* theFaceHelper=0,
1471 const double thePrevLen=0,
1472 const int theStep=theFirstStep,
1473 gp_Vec* theLinkNorm=0,
1474 double theSign=1.0) const;
1477 //================================================================================
1479 * \brief Dump QLink and QFace
1481 ostream& operator << (ostream& out, const QLink& l)
1483 out <<"QLink nodes: "
1484 << l.node1()->GetID() << " - "
1485 << l._mediumNode->GetID() << " - "
1486 << l.node2()->GetID() << endl;
1489 ostream& operator << (ostream& out, const QFace& f)
1491 out <<"QFace nodes: "/*<< &f << " "*/;
1492 for ( TIDSortedElemSet::iterator n = f.begin(); n != f.end(); ++n )
1493 out << (*n)->GetID() << " ";
1494 out << " \tvolumes: "
1495 << (f._volumes[0] ? f._volumes[0]->GetID() : 0) << " "
1496 << (f._volumes[1] ? f._volumes[1]->GetID() : 0);
1497 out << " \tNormal: "<< f._normal.X() <<", "<<f._normal.Y() <<", "<<f._normal.Z() << endl;
1501 //================================================================================
1503 * \brief Construct QFace from QLinks
1505 //================================================================================
1507 QFace::QFace( const vector< const QLink*>& links )
1509 _volumes[0] = _volumes[1] = 0;
1511 _sideIsAdded[0]=_sideIsAdded[1]=_sideIsAdded[2]=_sideIsAdded[3]=false;
1512 _normal.SetCoord(0,0,0);
1513 for ( int i = 1; i < _sides.size(); ++i ) {
1514 const QLink *l1 = _sides[i-1], *l2 = _sides[i];
1515 insert( l1->node1() ); insert( l1->node2() );
1517 gp_Vec v1( XYZ( l1->node2()), XYZ( l1->node1()));
1518 gp_Vec v2( XYZ( l2->node1()), XYZ( l2->node2()));
1519 if ( l1->node1() != l2->node1() && l1->node2() != l2->node2() )
1523 double normSqSize = _normal.SquareMagnitude();
1524 if ( normSqSize > numeric_limits<double>::min() )
1525 _normal /= sqrt( normSqSize );
1527 _normal.SetCoord(1e-33,0,0);
1529 //================================================================================
1531 * \brief Make up chain of links
1532 * \param iSide - link to add first
1533 * \param chain - chain to fill in
1534 * \param pos - postion of medium nodes the links should have
1535 * \param error - out, specifies what is wrong
1536 * \retval bool - false if valid chain can't be built; "valid" means that links
1537 * of the chain belongs to rectangles bounding hexahedrons
1539 //================================================================================
1541 bool QFace::GetLinkChain( int iSide, TChain& chain, SMDS_TypeOfPosition pos, int& error) const
1543 if ( iSide >= _sides.size() ) // wrong argument iSide
1545 if ( _sideIsAdded[ iSide ]) // already in chain
1548 if ( _sides.size() != 4 ) { // triangle - visit all my continous faces
1550 for ( int i = 0; i < _sides.size(); ++i ) {
1551 if ( !_sideIsAdded[i] && _sides[i] ) {
1552 _sideIsAdded[i]=true;
1553 TChain::iterator chLink = chain.insert( chain.begin(), TChainLink(_sides[i]));
1554 chLink->SetFace( this );
1555 if ( _sides[i]->MediumPos() >= pos )
1556 if ( const QFace* f = _sides[i]->GetContinuesFace( this ))
1557 f->GetLinkChain( *chLink, chain, pos, error );
1560 if ( error < ERR_TRI )
1564 _sideIsAdded[iSide] = true; // not to add this link to chain again
1565 const QLink* link = _sides[iSide];
1569 // add link into chain
1570 TChain::iterator chLink = chain.insert( chain.begin(), TChainLink(link));
1571 chLink->SetFace( this );
1574 // propagate from rectangle to neighbour faces
1575 if ( link->MediumPos() >= pos ) {
1576 int nbLinkFaces = link->_faces.size();
1577 if ( nbLinkFaces == 4 || nbLinkFaces < 4 && link->OnBoundary()) {
1578 // hexahedral mesh or boundary quadrangles - goto a continous face
1579 if ( const QFace* f = link->GetContinuesFace( this ))
1580 return f->GetLinkChain( *chLink, chain, pos, error );
1583 TChainLink chLink(link); // side face of prismatic mesh - visit all faces of iSide
1584 for ( int i = 0; i < nbLinkFaces; ++i )
1585 if ( link->_faces[i] )
1586 link->_faces[i]->GetLinkChain( chLink, chain, pos, error );
1587 if ( error < ERR_PRISM )
1595 //================================================================================
1597 * \brief Return a boundary link of the triangle face
1598 * \param links - set of all links
1599 * \param avoidLink - link not to return
1600 * \param notBoundaryLink - out, neither the returned link nor avoidLink
1601 * \param nodeToContain - node the returned link must contain; if provided, search
1602 * also performed on adjacent faces
1603 * \param isAdjacentUsed - returns true if link is found in adjacent faces
1605 //================================================================================
1607 TLinkInSet QFace::GetBoundaryLink( const TLinkSet& links,
1608 const TChainLink& avoidLink,
1609 TLinkInSet * notBoundaryLink,
1610 const SMDS_MeshNode* nodeToContain,
1611 bool * isAdjacentUsed) const
1613 TLinkInSet linksEnd = links.end(), boundaryLink = linksEnd;
1615 typedef list< pair< const QFace*, TLinkInSet > > TFaceLinkList;
1616 TFaceLinkList adjacentFaces;
1618 for ( int iL = 0; iL < _sides.size(); ++iL )
1620 if ( avoidLink._qlink == _sides[iL] )
1622 TLinkInSet link = links.find( _sides[iL] );
1623 if ( link == linksEnd ) continue;
1626 if ( link->IsBoundary() ) {
1627 if ( !nodeToContain ||
1628 (*link)->node1() == nodeToContain ||
1629 (*link)->node2() == nodeToContain )
1631 boundaryLink = link;
1632 if ( !notBoundaryLink ) break;
1635 else if ( notBoundaryLink ) {
1636 *notBoundaryLink = link;
1637 if ( boundaryLink != linksEnd ) break;
1640 if ( boundaryLink == linksEnd && nodeToContain ) // cellect adjacent faces
1641 if ( const QFace* adj = link->NextFace( this ))
1642 if ( adj->Contains( nodeToContain ))
1643 adjacentFaces.push_back( make_pair( adj, link ));
1646 if ( isAdjacentUsed ) *isAdjacentUsed = false;
1647 if ( boundaryLink == linksEnd && nodeToContain ) // check adjacent faces
1649 TFaceLinkList::iterator adj = adjacentFaces.begin();
1650 for ( ; boundaryLink == linksEnd && adj != adjacentFaces.end(); ++adj )
1651 boundaryLink = adj->first->GetBoundaryLink( links, *(adj->second),
1652 0, nodeToContain, isAdjacentUsed);
1653 if ( isAdjacentUsed ) *isAdjacentUsed = true;
1655 return boundaryLink;
1657 //================================================================================
1659 * \brief Return a link ending at the given node but not avoidLink
1661 //================================================================================
1663 TLinkInSet QFace::GetLinkByNode( const TLinkSet& links,
1664 const TChainLink& avoidLink,
1665 const SMDS_MeshNode* nodeToContain) const
1667 for ( int i = 0; i < _sides.size(); ++i )
1668 if ( avoidLink._qlink != _sides[i] &&
1669 (_sides[i]->node1() == nodeToContain || _sides[i]->node2() == nodeToContain ))
1670 return links.find( _sides[ i ]);
1674 //================================================================================
1676 * \brief Return normal to the i-th side pointing outside the face
1678 //================================================================================
1680 gp_Vec QFace::LinkNorm(const int i, SMESH_MesherHelper* /*uvHelper*/) const
1682 gp_Vec norm, vecOut;
1683 // if ( uvHelper ) {
1684 // TopoDS_Face face = TopoDS::Face( uvHelper->GetSubShape());
1685 // const SMDS_MeshNode* inFaceNode = uvHelper->GetNodeUVneedInFaceNode() ? GetNodeInFace() : 0;
1686 // gp_XY uv1 = uvHelper->GetNodeUV( face, _sides[i]->node1(), inFaceNode );
1687 // gp_XY uv2 = uvHelper->GetNodeUV( face, _sides[i]->node2(), inFaceNode );
1688 // norm.SetCoord( uv1.Y() - uv2.Y(), uv2.X() - uv1.X(), 0 );
1690 // const QLink* otherLink = _sides[(i + 1) % _sides.size()];
1691 // const SMDS_MeshNode* otherNode =
1692 // otherLink->node1() == _sides[i]->node1() ? otherLink->node2() : otherLink->node1();
1693 // gp_XY pIn = uvHelper->GetNodeUV( face, otherNode, inFaceNode );
1694 // vecOut.SetCoord( uv1.X() - pIn.X(), uv1.Y() - pIn.Y(), 0 );
1697 norm = _normal ^ gp_Vec( XYZ(_sides[i]->node1()), XYZ(_sides[i]->node2()));
1698 gp_XYZ pIn = ( XYZ( _sides[0]->node1() ) +
1699 XYZ( _sides[0]->node2() ) +
1700 XYZ( _sides[1]->node1() )) / 3.;
1701 vecOut.SetXYZ( _sides[i]->MiddlePnt() - pIn );
1703 if ( norm * vecOut < 0 )
1705 double mag2 = norm.SquareMagnitude();
1706 if ( mag2 > numeric_limits<double>::min() )
1707 norm /= sqrt( mag2 );
1710 //================================================================================
1712 * \brief Move medium node of theLink according to its distance from boundary
1713 * \param theLink - link to fix
1714 * \param theRefVec - movement of boundary
1715 * \param theLinks - all adjacent links of continous triangles
1716 * \param theFaceHelper - helper is not used so far
1717 * \param thePrevLen - distance from the boundary
1718 * \param theStep - number of steps till movement propagation limit
1719 * \param theLinkNorm - out normal to theLink
1720 * \param theSign - 1 or -1 depending on movement of boundary
1721 * \retval double - distance from boundary to propagation limit or other boundary
1723 //================================================================================
1725 double QFace::MoveByBoundary( const TChainLink& theLink,
1726 const gp_Vec& theRefVec,
1727 const TLinkSet& theLinks,
1728 SMESH_MesherHelper* theFaceHelper,
1729 const double thePrevLen,
1731 gp_Vec* theLinkNorm,
1732 double theSign) const
1735 return thePrevLen; // propagation limit reached
1737 int iL; // index of theLink
1738 for ( iL = 0; iL < _sides.size(); ++iL )
1739 if ( theLink._qlink == _sides[ iL ])
1742 MSG(string(theStep,'.')<<" Ref( "<<theRefVec.X()<<","<<theRefVec.Y()<<","<<theRefVec.Z()<<" )"
1743 <<" thePrevLen " << thePrevLen);
1744 MSG(string(theStep,'.')<<" "<<*theLink._qlink);
1746 gp_Vec linkNorm = -LinkNorm( iL/*, theFaceHelper*/ ); // normal to theLink
1747 double refProj = theRefVec * linkNorm; // project movement vector to normal of theLink
1748 if ( theStep == theFirstStep )
1749 theSign = refProj < 0. ? -1. : 1.;
1750 else if ( theSign * refProj < 0.4 * theRefVec.Magnitude())
1751 return thePrevLen; // to propagate movement forward only, not in side dir or backward
1753 int iL1 = (iL + 1) % 3, iL2 = (iL + 2) % 3; // indices of the two other links of triangle
1754 TLinkInSet link1 = theLinks.find( _sides[iL1] );
1755 TLinkInSet link2 = theLinks.find( _sides[iL2] );
1756 const QFace* f1 = link1->NextFace( this ); // adjacent faces
1757 const QFace* f2 = link2->NextFace( this );
1759 // propagate to adjacent faces till limit step or boundary
1760 double len1 = thePrevLen + (theLink->MiddlePnt() - _sides[iL1]->MiddlePnt()).Modulus();
1761 double len2 = thePrevLen + (theLink->MiddlePnt() - _sides[iL2]->MiddlePnt()).Modulus();
1762 gp_Vec linkDir1, linkDir2;
1766 len1 = f1->MoveByBoundary
1767 ( *link1, theRefVec, theLinks, theFaceHelper, len1, theStep-1, &linkDir1, theSign);
1769 linkDir1 = LinkNorm( iL1/*, theFaceHelper*/ );
1771 MSG( " --------------- EXCEPTION");
1777 len2 = f2->MoveByBoundary
1778 ( *link2, theRefVec, theLinks, theFaceHelper, len2, theStep-1, &linkDir2, theSign);
1780 linkDir2 = LinkNorm( iL2/*, theFaceHelper*/ );
1782 MSG( " --------------- EXCEPTION");
1787 if ( theStep != theFirstStep )
1789 // choose chain length by direction of propagation most codirected with theRefVec
1790 bool choose1 = ( theRefVec * linkDir1 * theSign > theRefVec * linkDir2 * theSign );
1791 fullLen = choose1 ? len1 : len2;
1792 double r = thePrevLen / fullLen;
1794 gp_Vec move = linkNorm * refProj * ( 1 - r );
1795 theLink->Move( move, true );
1797 MSG(string(theStep,'.')<<" Move "<< theLink->_mediumNode->GetID()<<
1798 " by " << refProj * ( 1 - r ) << " following " <<
1799 (choose1 ? *link1->_qlink : *link2->_qlink));
1801 if ( theLinkNorm ) *theLinkNorm = linkNorm;
1806 //================================================================================
1808 * \brief Find pairs of continues faces
1810 //================================================================================
1812 void QLink::SetContinuesFaces() const
1814 // x0 x - QLink, [-|] - QFace, v - volume
1816 // | Between _faces of link x2 two vertical faces are continues
1817 // x1----x2-----x3 and two horizontal faces are continues. We set vertical faces
1818 // | to _faces[0] and _faces[1] and horizontal faces to
1819 // v2 | v3 _faces[2] and _faces[3] (or vise versa).
1822 if ( _faces.empty() )
1825 for ( int iF = 1; iFaceCont < 0 && iF < _faces.size(); ++iF )
1827 // look for a face bounding none of volumes bound by _faces[0]
1828 bool sameVol = false;
1829 int nbVol = _faces[iF]->NbVolumes();
1830 for ( int iV = 0; !sameVol && iV < nbVol; ++iV )
1831 sameVol = ( _faces[iF]->_volumes[iV] == _faces[0]->_volumes[0] ||
1832 _faces[iF]->_volumes[iV] == _faces[0]->_volumes[1]);
1836 if ( iFaceCont > 0 ) // continues faces found, set one by the other
1838 if ( iFaceCont != 1 )
1839 swap( _faces[1], _faces[iFaceCont] );
1841 else if ( _faces.size() > 1 ) // not found, set NULL by the first face
1843 _faces.insert( ++_faces.begin(), 0 );
1846 //================================================================================
1848 * \brief Return a face continues to the given one
1850 //================================================================================
1852 const QFace* QLink::GetContinuesFace( const QFace* face ) const
1854 for ( int i = 0; i < _faces.size(); ++i ) {
1855 if ( _faces[i] == face ) {
1856 int iF = i < 2 ? 1-i : 5-i;
1857 return iF < _faces.size() ? _faces[iF] : 0;
1862 //================================================================================
1864 * \brief True if link is on mesh boundary
1866 //================================================================================
1868 bool QLink::OnBoundary() const
1870 for ( int i = 0; i < _faces.size(); ++i )
1871 if (_faces[i] && _faces[i]->IsBoundary()) return true;
1874 //================================================================================
1876 * \brief Return normal of link of the chain
1878 //================================================================================
1880 gp_Vec TChainLink::Normal() const {
1882 if (_qfaces[0]) norm = _qfaces[0]->_normal;
1883 if (_qfaces[1]) norm += _qfaces[1]->_normal;
1886 //================================================================================
1888 * \brief Move medium nodes of vertical links of pentahedrons adjacent by side faces
1890 //================================================================================
1892 void fixPrism( TChain& allLinks )
1894 // separate boundary links from internal ones
1895 typedef set<const QLink*/*, QLink::PtrComparator*/> QLinkSet;
1896 QLinkSet interLinks, bndLinks1, bndLink2;
1898 bool isCurved = false;
1899 for ( TChain::iterator lnk = allLinks.begin(); lnk != allLinks.end(); ++lnk ) {
1900 if ( (*lnk)->OnBoundary() )
1901 bndLinks1.insert( lnk->_qlink );
1903 interLinks.insert( lnk->_qlink );
1904 isCurved = isCurved || !(*lnk)->IsStraight();
1907 return; // no need to move
1909 QLinkSet *curBndLinks = &bndLinks1, *newBndLinks = &bndLink2;
1911 while ( !interLinks.empty() && !curBndLinks->empty() )
1913 // propagate movement from boundary links to connected internal links
1914 QLinkSet::iterator bnd = curBndLinks->begin(), bndEnd = curBndLinks->end();
1915 for ( ; bnd != bndEnd; ++bnd )
1917 const QLink* bndLink = *bnd;
1918 for ( int i = 0; i < bndLink->_faces.size(); ++i ) // loop on faces of bndLink
1920 const QFace* face = bndLink->_faces[i]; // quadrange lateral face of a prism
1921 if ( !face ) continue;
1922 // find and move internal link opposite to bndLink within the face
1923 int interInd = ( face->LinkIndex( bndLink ) + 2 ) % face->_sides.size();
1924 const QLink* interLink = face->_sides[ interInd ];
1925 QLinkSet::iterator pInterLink = interLinks.find( interLink );
1926 if ( pInterLink == interLinks.end() ) continue; // not internal link
1927 interLink->Move( bndLink->_nodeMove );
1928 // treated internal links become new boundary ones
1929 interLinks. erase( pInterLink );
1930 newBndLinks->insert( interLink );
1933 curBndLinks->clear();
1934 swap( curBndLinks, newBndLinks );
1938 //================================================================================
1940 * \brief Fix links of continues triangles near curved boundary
1942 //================================================================================
1944 void fixTriaNearBoundary( TChain & allLinks, SMESH_MesherHelper& /*helper*/)
1946 if ( allLinks.empty() ) return;
1948 TLinkSet linkSet( allLinks.begin(), allLinks.end());
1949 TLinkInSet linkIt = linkSet.begin(), linksEnd = linkSet.end();
1951 // move in 2d if we are on geom face
1952 // TopoDS_Face face;
1953 // TopLoc_Location loc;
1954 // SMESH_MesherHelper faceHelper( *helper.GetMesh());
1955 // while ( linkIt->IsBoundary()) ++linkIt;
1956 // if ( linkIt == linksEnd ) return;
1957 // if ( (*linkIt)->MediumPos() == SMDS_TOP_FACE ) {
1958 // bool checkPos = true;
1959 // TopoDS_Shape f = helper.GetSubShapeByNode( (*linkIt)->_mediumNode, helper.GetMeshDS() );
1960 // if ( !f.IsNull() && f.ShapeType() == TopAbs_FACE ) {
1961 // face = TopoDS::Face( f );
1962 // helper.GetNodeUV( face, (*linkIt)->_mediumNode, 0, &checkPos);
1966 // faceHelper.SetSubShape( face );
1969 for ( linkIt = linkSet.begin(); linkIt != linksEnd; ++linkIt)
1971 if ( linkIt->IsBoundary() && !(*linkIt)->IsStraight() && linkIt->_qfaces[0])
1973 // if ( !face.IsNull() ) {
1974 // const SMDS_MeshNode* inFaceNode =
1975 // faceHelper.GetNodeUVneedInFaceNode() ? linkIt->_qfaces[0]->GetNodeInFace() : 0;
1976 // gp_XY uvm = helper.GetNodeUV( face, (*linkIt)->_mediumNode, inFaceNode );
1977 // gp_XY uv1 = helper.GetNodeUV( face, (*linkIt)->node1(), inFaceNode);
1978 // gp_XY uv2 = helper.GetNodeUV( face, (*linkIt)->node2(), inFaceNode);
1979 // gp_XY uvMove = uvm - helper.GetMiddleUV( BRep_Tool::Surface(face,loc), uv1, uv2);
1980 // gp_Vec move( uvMove.X(), uvMove.Y(), 0 );
1981 // linkIt->_qfaces[0]->MoveByBoundary( *linkIt, move, linkSet, &faceHelper );
1984 linkIt->_qfaces[0]->MoveByBoundary( *linkIt, (*linkIt)->_nodeMove, linkSet );
1990 //================================================================================
1992 * \brief Detect rectangular structure of links and build chains from them
1994 //================================================================================
1996 enum TSplitTriaResult {
1997 _OK, _NO_CORNERS, _FEW_ROWS, _MANY_ROWS, _NO_SIDELINK, _BAD_MIDQUAD, _NOT_RECT,
1998 _NO_MIDQUAD, _NO_UPTRIA, _BAD_SET_SIZE, _BAD_CORNER, _BAD_START, _NO_BOTLINK };
2000 TSplitTriaResult splitTrianglesIntoChains( TChain & allLinks,
2001 vector< TChain> & resultChains,
2002 SMDS_TypeOfPosition pos )
2004 // put links in the set and evalute number of result chains by number of boundary links
2007 for ( TChain::iterator lnk = allLinks.begin(); lnk != allLinks.end(); ++lnk ) {
2008 linkSet.insert( *lnk );
2009 nbBndLinks += lnk->IsBoundary();
2011 resultChains.clear();
2012 resultChains.reserve( nbBndLinks / 2 );
2014 TLinkInSet linkIt, linksEnd = linkSet.end();
2016 // find a boundary link with corner node; corner node has position pos-2
2017 // i.e. SMDS_TOP_VERTEX for links on faces and SMDS_TOP_EDGE for
2019 SMDS_TypeOfPosition cornerPos = SMDS_TypeOfPosition(pos-2);
2020 const SMDS_MeshNode* corner = 0;
2021 for ( linkIt = linkSet.begin(); linkIt != linksEnd; ++linkIt )
2022 if ( linkIt->IsBoundary() && (corner = (*linkIt)->EndPosNode(cornerPos)))
2027 TLinkInSet startLink = linkIt;
2028 const SMDS_MeshNode* startCorner = corner;
2029 vector< TChain* > rowChains;
2032 while ( startLink != linksEnd) // loop on columns
2034 // We suppose we have a rectangular structure like shown here. We have found a
2035 // corner of the rectangle (startCorner) and a boundary link sharing
2036 // |/ |/ | the startCorner (startLink). We are going to loop on rows of the
2037 // --o---o---o structure making several chains at once. One chain (columnChain)
2038 // |\ | /| starts at startLink and continues upward (we look at the structure
2039 // \ | \ | / | from such point that startLink is on the bottom of the structure).
2040 // \| \|/ | While going upward we also fill horizontal chains (rowChains) we
2041 // --o---o---o encounter.
2043 // / | \ | \ | startCorner
2048 if ( resultChains.size() == nbBndLinks / 2 )
2050 resultChains.push_back( TChain() );
2051 TChain& columnChain = resultChains.back();
2053 TLinkInSet botLink = startLink; // current horizontal link to go up from
2054 corner = startCorner; // current corner the botLink ends at
2056 while ( botLink != linksEnd ) // loop on rows
2058 // add botLink to the columnChain
2059 columnChain.push_back( *botLink );
2061 const QFace* botTria = botLink->_qfaces[0]; // bottom triangle bound by botLink
2063 { // the column ends
2064 linkSet.erase( botLink );
2065 if ( iRow != rowChains.size() )
2066 return _FEW_ROWS; // different nb of rows in columns
2069 // find the link dividing the quadrangle (midQuadLink) and vertical boundary
2070 // link ending at <corner> (sideLink); there are two cases:
2071 // 1) midQuadLink does not end at <corner>, then we easily find it by botTria,
2072 // since midQuadLink is not at boundary while sideLink is.
2073 // 2) midQuadLink ends at <corner>
2075 TLinkInSet midQuadLink = linksEnd;
2076 TLinkInSet sideLink = botTria->GetBoundaryLink( linkSet, *botLink, &midQuadLink,
2078 if ( isCase2 ) { // find midQuadLink among links of botTria
2079 midQuadLink = botTria->GetLinkByNode( linkSet, *botLink, corner );
2080 if ( midQuadLink->IsBoundary() )
2081 return _BAD_MIDQUAD;
2083 if ( sideLink == linksEnd || midQuadLink == linksEnd || sideLink == midQuadLink )
2084 return sideLink == linksEnd ? _NO_SIDELINK : _NO_MIDQUAD;
2087 columnChain.push_back( *midQuadLink );
2088 if ( iRow >= rowChains.size() ) {
2090 return _MANY_ROWS; // different nb of rows in columns
2091 if ( resultChains.size() == nbBndLinks / 2 )
2093 resultChains.push_back( TChain() );
2094 rowChains.push_back( & resultChains.back() );
2096 rowChains[iRow]->push_back( *sideLink );
2097 rowChains[iRow]->push_back( *midQuadLink );
2099 const QFace* upTria = midQuadLink->NextFace( botTria ); // upper tria of the rectangle
2103 // prepare startCorner and startLink for the next column
2104 startCorner = startLink->NextNode( startCorner );
2106 startLink = botTria->GetBoundaryLink( linkSet, *botLink, 0, startCorner );
2108 startLink = upTria->GetBoundaryLink( linkSet, *midQuadLink, 0, startCorner );
2109 // check if no more columns remains
2110 if ( startLink != linksEnd ) {
2111 const SMDS_MeshNode* botNode = startLink->NextNode( startCorner );
2112 if ( (isCase2 ? botTria : upTria)->Contains( botNode ))
2113 startLink = linksEnd; // startLink bounds upTria or botTria
2114 else if ( startLink == botLink || startLink == midQuadLink || startLink == sideLink )
2118 // find bottom link and corner for the next row
2119 corner = sideLink->NextNode( corner );
2120 // next bottom link ends at the new corner
2121 linkSet.erase( botLink );
2122 botLink = upTria->GetLinkByNode( linkSet, (isCase2 ? *sideLink : *midQuadLink), corner );
2123 if ( botLink == linksEnd || botLink == (isCase2 ? midQuadLink : sideLink))
2125 linkSet.erase( midQuadLink );
2126 linkSet.erase( sideLink );
2128 // make faces neighboring the found ones be boundary
2129 if ( startLink != linksEnd ) {
2130 const QFace* tria = isCase2 ? botTria : upTria;
2131 for ( int iL = 0; iL < 3; ++iL ) {
2132 linkIt = linkSet.find( tria->_sides[iL] );
2133 if ( linkIt != linksEnd )
2134 linkIt->RemoveFace( tria );
2137 if ( botLink->_qfaces[0] == upTria || botLink->_qfaces[1] == upTria )
2138 botLink->RemoveFace( upTria ); // make next botTria first in vector
2145 // In the linkSet, there must remain the last links of rowChains; add them
2146 if ( linkSet.size() != rowChains.size() )
2147 return _BAD_SET_SIZE;
2148 for ( int iRow = 0; iRow < rowChains.size(); ++iRow ) {
2149 // find the link (startLink) ending at startCorner
2151 for ( startLink = linkSet.begin(); startLink != linksEnd; ++startLink ) {
2152 if ( (*startLink)->node1() == startCorner ) {
2153 corner = (*startLink)->node2(); break;
2155 else if ( (*startLink)->node2() == startCorner) {
2156 corner = (*startLink)->node1(); break;
2159 if ( startLink == linksEnd )
2161 rowChains[ iRow ]->push_back( *startLink );
2162 linkSet.erase( startLink );
2163 startCorner = corner;
2170 //=======================================================================
2172 * \brief Move medium nodes of faces and volumes to fix distorted elements
2173 * \param volumeOnly - to fix nodes on faces or not, if the shape is solid
2175 * Issue 0020307: EDF 992 SMESH : Linea/Quadratic with Medium Node on Geometry
2177 //=======================================================================
2179 void SMESH_MesherHelper::FixQuadraticElements(bool volumeOnly)
2181 // apply algorithm to solids or geom faces
2182 // ----------------------------------------------
2183 if ( myShape.IsNull() ) {
2184 if ( !myMesh->HasShapeToMesh() ) return;
2185 SetSubShape( myMesh->GetShapeToMesh() );
2187 TopTools_MapOfShape faces; // faces not in solid or in not meshed solid
2188 for ( TopExp_Explorer f(myShape,TopAbs_FACE,TopAbs_SOLID); f.More(); f.Next() ) {
2189 faces.Add( f.Current() );
2191 for ( TopExp_Explorer v(myShape,TopAbs_SOLID); v.More(); v.Next() ) {
2192 if ( myMesh->GetSubMesh( v.Current() )->IsEmpty() ) { // get faces of solid
2193 for ( TopExp_Explorer f( v.Current(), TopAbs_FACE); f.More(); f.Next() )
2194 faces.Add( f.Current() );
2196 else { // fix nodes in the solid and its faces
2197 SMESH_MesherHelper h(*myMesh);
2198 h.SetSubShape( v.Current() );
2199 h.FixQuadraticElements(false);
2202 // fix nodes on geom faces
2203 for ( TopTools_MapIteratorOfMapOfShape fIt( faces ); fIt.More(); fIt.Next() ) {
2204 SMESH_MesherHelper h(*myMesh);
2205 h.SetSubShape( fIt.Key() );
2206 h.FixQuadraticElements();
2211 // Find out type of elements and get iterator on them
2212 // ---------------------------------------------------
2214 SMDS_ElemIteratorPtr elemIt;
2215 SMDSAbs_ElementType elemType = SMDSAbs_All;
2217 SMESH_subMesh* submesh = myMesh->GetSubMeshContaining( myShapeID );
2220 if ( SMESHDS_SubMesh* smDS = submesh->GetSubMeshDS() ) {
2221 elemIt = smDS->GetElements();
2222 if ( elemIt->more() ) {
2223 elemType = elemIt->next()->GetType();
2224 elemIt = smDS->GetElements();
2227 if ( !elemIt || !elemIt->more() || elemType < SMDSAbs_Face )
2230 // Fill in auxiliary data structures
2231 // ----------------------------------
2235 set< QLink >::iterator pLink;
2236 set< QFace >::iterator pFace;
2238 bool isCurved = false;
2239 bool hasRectFaces = false;
2240 set<int> nbElemNodeSet;
2242 if ( elemType == SMDSAbs_Volume )
2244 SMDS_VolumeTool volTool;
2245 while ( elemIt->more() ) // loop on volumes
2247 const SMDS_MeshElement* vol = elemIt->next();
2248 if ( !vol->IsQuadratic() || !volTool.Set( vol ))
2250 for ( int iF = 0; iF < volTool.NbFaces(); ++iF ) // loop on faces of volume
2252 int nbN = volTool.NbFaceNodes( iF );
2253 nbElemNodeSet.insert( nbN );
2254 const SMDS_MeshNode** faceNodes = volTool.GetFaceNodes( iF );
2255 vector< const QLink* > faceLinks( nbN/2 );
2256 for ( int iN = 0; iN < nbN; iN += 2 ) // loop on links of a face
2259 QLink link( faceNodes[iN], faceNodes[iN+2], faceNodes[iN+1] );
2260 pLink = links.insert( link ).first;
2261 faceLinks[ iN/2 ] = & *pLink;
2263 isCurved = !link.IsStraight();
2264 if ( link.MediumPos() == SMDS_TOP_3DSPACE && !link.IsStraight() )
2265 return; // already fixed
2268 pFace = faces.insert( QFace( faceLinks )).first;
2269 if ( pFace->NbVolumes() == 0 )
2270 pFace->AddSelfToLinks();
2271 pFace->SetVolume( vol );
2272 hasRectFaces = hasRectFaces ||
2273 ( volTool.GetVolumeType() == SMDS_VolumeTool::QUAD_HEXA ||
2274 volTool.GetVolumeType() == SMDS_VolumeTool::QUAD_PENTA );
2277 set< QLink >::iterator pLink = links.begin();
2278 for ( ; pLink != links.end(); ++pLink )
2279 pLink->SetContinuesFaces();
2283 while ( elemIt->more() ) // loop on faces
2285 const SMDS_MeshElement* face = elemIt->next();
2286 if ( !face->IsQuadratic() )
2288 nbElemNodeSet.insert( face->NbNodes() );
2289 int nbN = face->NbNodes()/2;
2290 vector< const QLink* > faceLinks( nbN );
2291 for ( int iN = 0; iN < nbN; ++iN ) // loop on links of a face
2294 QLink link( face->GetNode(iN), face->GetNode((iN+1)%nbN), face->GetNode(iN+nbN) );
2295 pLink = links.insert( link ).first;
2296 faceLinks[ iN ] = & *pLink;
2298 isCurved = !link.IsStraight();
2301 pFace = faces.insert( QFace( faceLinks )).first;
2302 pFace->AddSelfToLinks();
2303 hasRectFaces = ( hasRectFaces || nbN == 4 );
2307 return; // no curved edges of faces
2309 // Compute displacement of medium nodes
2310 // -------------------------------------
2312 // two loops on faces: the first is to treat boundary links, the second is for internal ones
2313 TopLoc_Location loc;
2314 // not treat boundary of volumic submesh
2315 int isInside = ( elemType == SMDSAbs_Volume && volumeOnly ) ? 1 : 0;
2316 for ( ; isInside < 2; ++isInside ) {
2317 MSG( "--------------- LOOP " << isInside << " ------------------");
2318 SMDS_TypeOfPosition pos = isInside ? SMDS_TOP_3DSPACE : SMDS_TOP_FACE;
2320 for ( pFace = faces.begin(); pFace != faces.end(); ++pFace ) {
2321 if ( bool(isInside) == pFace->IsBoundary() )
2323 for ( int dir = 0; dir < 2; ++dir ) // 2 directions of propagation from quadrangle
2326 // make chain of links connected via continues faces
2329 if ( !pFace->GetLinkChain( dir, rawChain, pos, error) && error ==ERR_UNKNOWN ) continue;
2331 if ( !pFace->GetLinkChain( dir+2, rawChain, pos, error ) && error ==ERR_UNKNOWN ) continue;
2333 vector< TChain > chains;
2334 if ( error == ERR_OK ) { // chains contains continues rectangles
2336 chains[0].splice( chains[0].begin(), rawChain );
2338 else if ( error == ERR_TRI ) { // chains contains continues triangles
2339 TSplitTriaResult res = splitTrianglesIntoChains( rawChain, chains, pos );
2340 if ( res != _OK ) { // not rectangles split into triangles
2341 fixTriaNearBoundary( rawChain, *this );
2345 else if ( error == ERR_PRISM ) { // side faces of prisms
2346 fixPrism( rawChain );
2352 for ( int iC = 0; iC < chains.size(); ++iC )
2354 TChain& chain = chains[iC];
2355 if ( chain.empty() ) continue;
2356 if ( chain.front()->IsStraight() && chain.back()->IsStraight() ) {
2360 // mesure chain length and compute link position along the chain
2361 double chainLen = 0;
2362 vector< double > linkPos;
2363 MSGBEG( "Link medium nodes: ");
2364 TChain::iterator link0 = chain.begin(), link1 = chain.begin(), link2;
2365 for ( ++link1; link1 != chain.end(); ++link1, ++link0 ) {
2366 MSGBEG( (*link0)->_mediumNode->GetID() << "-" <<(*link1)->_mediumNode->GetID()<<" ");
2367 double len = ((*link0)->MiddlePnt() - (*link1)->MiddlePnt()).Modulus();
2368 while ( len < numeric_limits<double>::min() ) { // remove degenerated link
2369 link1 = chain.erase( link1 );
2370 if ( link1 == chain.end() )
2372 len = ((*link0)->MiddlePnt() - (*link1)->MiddlePnt()).Modulus();
2375 linkPos.push_back( chainLen );
2378 if ( linkPos.size() < 2 )
2381 gp_Vec move0 = chain.front()->_nodeMove;
2382 gp_Vec move1 = chain.back ()->_nodeMove;
2385 bool checkUV = true;
2387 // compute node displacement of end links in parametric space of face
2388 const SMDS_MeshNode* nodeOnFace = (*(++chain.begin()))->_mediumNode;
2389 TopoDS_Shape f = GetSubShapeByNode( nodeOnFace, GetMeshDS() );
2390 if ( !f.IsNull() && f.ShapeType() == TopAbs_FACE ) {
2391 face = TopoDS::Face( f );
2392 for ( int is1 = 0; is1 < 2; ++is1 ) { // move0 or move1
2393 TChainLink& link = is1 ? chain.back() : chain.front();
2394 gp_XY uv1 = GetNodeUV( face, link->node1(), nodeOnFace, &checkUV);
2395 gp_XY uv2 = GetNodeUV( face, link->node2(), nodeOnFace, &checkUV);
2396 gp_XY uvm = GetNodeUV( face, link->_mediumNode, nodeOnFace, &checkUV);
2397 gp_XY uvMove = uvm - GetMiddleUV( BRep_Tool::Surface(face,loc), uv1, uv2);
2398 if ( is1 ) move1.SetCoord( uvMove.X(), uvMove.Y(), 0 );
2399 else move0.SetCoord( uvMove.X(), uvMove.Y(), 0 );
2401 if ( move0.SquareMagnitude() < straightTol2 &&
2402 move1.SquareMagnitude() < straightTol2 ) {
2404 continue; // straight - no need to move nodes of internal links
2409 if ( isInside || face.IsNull() )
2411 // compute node displacement of end links in their local coord systems
2413 TChainLink& ln0 = chain.front(), ln1 = *(++chain.begin());
2414 trsf.SetTransformation( gp_Ax3( gp::Origin(), ln0.Normal(),
2415 gp_Vec( ln0->MiddlePnt(), ln1->MiddlePnt() )));
2416 move0.Transform(trsf);
2419 TChainLink& ln0 = *(++chain.rbegin()), ln1 = chain.back();
2420 trsf.SetTransformation( gp_Ax3( gp::Origin(), ln1.Normal(),
2421 gp_Vec( ln0->MiddlePnt(), ln1->MiddlePnt() )));
2422 move1.Transform(trsf);
2425 // compute displacement of medium nodes
2426 link2 = chain.begin();
2429 for ( int i = 0; link2 != chain.end(); ++link0, ++link1, ++link2, ++i )
2431 double r = linkPos[i] / chainLen;
2432 // displacement in local coord system
2433 gp_Vec move = (1. - r) * move0 + r * move1;
2434 if ( isInside || face.IsNull()) {
2435 // transform to global
2436 gp_Vec x01( (*link0)->MiddlePnt(), (*link1)->MiddlePnt() );
2437 gp_Vec x12( (*link1)->MiddlePnt(), (*link2)->MiddlePnt() );
2438 gp_Vec x = x01.Normalized() + x12.Normalized();
2439 trsf.SetTransformation( gp_Ax3( gp::Origin(), link1->Normal(), x), gp_Ax3() );
2440 move.Transform(trsf);
2443 // compute 3D displacement by 2D one
2444 gp_XY oldUV = GetNodeUV( face, (*link1)->_mediumNode, 0, &checkUV);
2445 gp_XY newUV = oldUV + gp_XY( move.X(), move.Y() );
2446 gp_Pnt newPnt = BRep_Tool::Surface(face,loc)->Value( newUV.X(), newUV.Y());
2447 move = gp_Vec( XYZ((*link1)->_mediumNode), newPnt.Transformed(loc) );
2449 if ( (XYZ((*link1)->node1()) - XYZ((*link1)->node2())).SquareModulus() <
2450 move.SquareMagnitude())
2452 gp_XY uv0 = GetNodeUV( face, (*link0)->_mediumNode, 0, &checkUV);
2453 gp_XY uv2 = GetNodeUV( face, (*link2)->_mediumNode, 0, &checkUV);
2454 MSG( "uv0: "<<uv0.X()<<", "<<uv0.Y()<<" \t" <<
2455 "uv2: "<<uv2.X()<<", "<<uv2.Y()<<" \t" <<
2456 "uvOld: "<<oldUV.X()<<", "<<oldUV.Y()<<" \t" <<
2457 "newUV: "<<newUV.X()<<", "<<newUV.Y()<<" \t");
2461 (*link1)->Move( move );
2462 MSG( "Move " << (*link1)->_mediumNode->GetID() << " following "
2463 << chain.front()->_mediumNode->GetID() <<"-"
2464 << chain.back ()->_mediumNode->GetID() <<
2465 " by " << move.Magnitude());
2467 } // loop on chains of links
2468 } // loop on 2 directions of propagation from quadrangle
2475 for ( pLink = links.begin(); pLink != links.end(); ++pLink ) {
2476 if ( pLink->IsMoved() ) {
2477 //gp_Pnt p = pLink->MediumPnt() + pLink->Move();
2478 gp_Pnt p = pLink->MiddlePnt() + pLink->Move();
2479 GetMeshDS()->MoveNode( pLink->_mediumNode, p.X(), p.Y(), p.Z());