1 // Copyright (C) 2007-2013 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 // NETGENPlugin : C++ implementation
24 // File : NETGENPlugin_Mesher.cxx
25 // Author : Michael Sazonov (OCN)
28 //=============================================================================
30 #include "NETGENPlugin_Mesher.hxx"
31 #include "NETGENPlugin_Hypothesis_2D.hxx"
32 #include "NETGENPlugin_SimpleHypothesis_3D.hxx"
34 #include <SMDS_FaceOfNodes.hxx>
35 #include <SMDS_MeshElement.hxx>
36 #include <SMDS_MeshNode.hxx>
37 #include <SMESHDS_Mesh.hxx>
38 #include <SMESH_Block.hxx>
39 #include <SMESH_Comment.hxx>
40 #include <SMESH_ComputeError.hxx>
41 #include <SMESH_File.hxx>
42 #include <SMESH_Gen_i.hxx>
43 #include <SMESH_Mesh.hxx>
44 #include <SMESH_MesherHelper.hxx>
45 #include <SMESH_subMesh.hxx>
46 #include <StdMeshers_QuadToTriaAdaptor.hxx>
47 #include <StdMeshers_ViscousLayers2D.hxx>
49 #include <SALOMEDS_Tool.hxx>
51 #include <utilities.h>
53 #include <BRepBuilderAPI_Copy.hxx>
54 #include <BRep_Tool.hxx>
55 #include <Bnd_B3d.hxx>
56 #include <NCollection_Map.hxx>
57 #include <Standard_ErrorHandler.hxx>
58 #include <Standard_ProgramError.hxx>
60 #include <TopExp_Explorer.hxx>
61 #include <TopTools_DataMapIteratorOfDataMapOfShapeInteger.hxx>
62 #include <TopTools_DataMapIteratorOfDataMapOfShapeShape.hxx>
63 #include <TopTools_DataMapOfShapeInteger.hxx>
64 #include <TopTools_DataMapOfShapeShape.hxx>
65 #include <TopTools_MapOfShape.hxx>
67 #include <OSD_File.hxx>
68 #include <OSD_Path.hxx>
70 // Netgen include files
74 #include <occgeom.hpp>
75 #include <meshing.hpp>
76 //#include <ngexception.hpp>
79 extern int OCCGenerateMesh (OCCGeometry&, Mesh*&, MeshingParameters&, int, int);
81 extern int OCCGenerateMesh (OCCGeometry&, Mesh*&, int, int, char*);
83 //extern void OCCSetLocalMeshSize(OCCGeometry & geom, Mesh & mesh);
84 extern MeshingParameters mparam;
85 extern volatile multithreadt multithread;
86 extern bool merge_solids;
95 using namespace nglib;
99 #define nodeVec_ACCESS(index) ((SMDS_MeshNode*) nodeVec.at((index)))
101 #define nodeVec_ACCESS(index) ((SMDS_MeshNode*) nodeVec[index])
104 #define NGPOINT_COORDS(p) p(0),p(1),p(2)
106 // dump elements added to ng mesh
107 //#define DUMP_SEGMENTS
108 //#define DUMP_TRIANGLES
109 //#define DUMP_TRIANGLES_SCRIPT "/tmp/trias.py" //!< debug AddIntVerticesInSolids()
111 TopTools_IndexedMapOfShape ShapesWithLocalSize;
112 std::map<int,double> VertexId2LocalSize;
113 std::map<int,double> EdgeId2LocalSize;
114 std::map<int,double> FaceId2LocalSize;
116 //=============================================================================
120 //=============================================================================
122 NETGENPlugin_Mesher::NETGENPlugin_Mesher (SMESH_Mesh* mesh,
123 const TopoDS_Shape& aShape,
129 _fineness(NETGENPlugin_Hypothesis::GetDefaultFineness()),
130 _isViscousLayers2D(false),
139 SetDefaultParameters();
140 ShapesWithLocalSize.Clear();
141 VertexId2LocalSize.clear();
142 EdgeId2LocalSize.clear();
143 FaceId2LocalSize.clear();
146 //================================================================================
150 //================================================================================
152 NETGENPlugin_Mesher::~NETGENPlugin_Mesher()
160 //================================================================================
162 * Set pointer to NETGENPlugin_Mesher* field of the holder, that will be
163 * nullified at destruction of this
165 //================================================================================
167 void NETGENPlugin_Mesher::SetSelfPointer( NETGENPlugin_Mesher ** ptr )
178 //================================================================================
180 * \brief Initialize global NETGEN parameters with default values
182 //================================================================================
184 void NETGENPlugin_Mesher::SetDefaultParameters()
186 netgen::MeshingParameters& mparams = netgen::mparam;
187 // maximal mesh edge size
188 mparams.maxh = 0;//NETGENPlugin_Hypothesis::GetDefaultMaxSize();
190 // minimal number of segments per edge
191 mparams.segmentsperedge = NETGENPlugin_Hypothesis::GetDefaultNbSegPerEdge();
192 // rate of growth of size between elements
193 mparams.grading = NETGENPlugin_Hypothesis::GetDefaultGrowthRate();
194 // safety factor for curvatures (elements per radius)
195 mparams.curvaturesafety = NETGENPlugin_Hypothesis::GetDefaultNbSegPerRadius();
196 // create elements of second order
197 mparams.secondorder = NETGENPlugin_Hypothesis::GetDefaultSecondOrder();
198 // quad-dominated surface meshing
202 mparams.quad = NETGENPlugin_Hypothesis_2D::GetDefaultQuadAllowed();
203 _fineness = NETGENPlugin_Hypothesis::GetDefaultFineness();
204 mparams.uselocalh = NETGENPlugin_Hypothesis::GetDefaultSurfaceCurvature();
205 netgen::merge_solids = NETGENPlugin_Hypothesis::GetDefaultFuseEdges();
208 //=============================================================================
212 //=============================================================================
213 void SetLocalSize(TopoDS_Shape GeomShape, double LocalSize)
215 TopAbs_ShapeEnum GeomType = GeomShape.ShapeType();
216 if (GeomType == TopAbs_COMPOUND) {
217 for (TopoDS_Iterator it (GeomShape); it.More(); it.Next()) {
218 SetLocalSize(it.Value(), LocalSize);
223 if (! ShapesWithLocalSize.Contains(GeomShape))
224 key = ShapesWithLocalSize.Add(GeomShape);
226 key = ShapesWithLocalSize.FindIndex(GeomShape);
227 if (GeomType == TopAbs_VERTEX) {
228 VertexId2LocalSize[key] = LocalSize;
229 } else if (GeomType == TopAbs_EDGE) {
230 EdgeId2LocalSize[key] = LocalSize;
231 } else if (GeomType == TopAbs_FACE) {
232 FaceId2LocalSize[key] = LocalSize;
236 //=============================================================================
238 * Pass parameters to NETGEN
240 //=============================================================================
241 void NETGENPlugin_Mesher::SetParameters(const NETGENPlugin_Hypothesis* hyp)
245 netgen::MeshingParameters& mparams = netgen::mparam;
246 // Initialize global NETGEN parameters:
247 // maximal mesh segment size
248 mparams.maxh = hyp->GetMaxSize();
249 // maximal mesh element linear size
250 mparams.minh = hyp->GetMinSize();
251 // minimal number of segments per edge
252 mparams.segmentsperedge = hyp->GetNbSegPerEdge();
253 // rate of growth of size between elements
254 mparams.grading = hyp->GetGrowthRate();
255 // safety factor for curvatures (elements per radius)
256 mparams.curvaturesafety = hyp->GetNbSegPerRadius();
257 // create elements of second order
258 mparams.secondorder = hyp->GetSecondOrder() ? 1 : 0;
259 // quad-dominated surface meshing
260 // only triangles are allowed for volumic mesh (before realizing IMP 0021676)
262 mparams.quad = hyp->GetQuadAllowed() ? 1 : 0;
263 _optimize = hyp->GetOptimize();
264 _fineness = hyp->GetFineness();
265 mparams.uselocalh = hyp->GetSurfaceCurvature();
266 netgen::merge_solids = hyp->GetFuseEdges();
269 SMESH_Gen_i* smeshGen_i = SMESH_Gen_i::GetSMESHGen();
270 CORBA::Object_var anObject = smeshGen_i->GetNS()->Resolve("/myStudyManager");
271 SALOMEDS::StudyManager_var aStudyMgr = SALOMEDS::StudyManager::_narrow(anObject);
272 SALOMEDS::Study_var myStudy = aStudyMgr->GetStudyByID(hyp->GetStudyId());
274 const NETGENPlugin_Hypothesis::TLocalSize localSizes = hyp->GetLocalSizesAndEntries();
275 NETGENPlugin_Hypothesis::TLocalSize::const_iterator it = localSizes.begin();
276 for (it ; it != localSizes.end() ; it++)
278 std::string entry = (*it).first;
279 double val = (*it).second;
281 GEOM::GEOM_Object_var aGeomObj;
282 TopoDS_Shape S = TopoDS_Shape();
283 SALOMEDS::SObject_var aSObj = myStudy->FindObjectID( entry.c_str() );
284 if (!aSObj->_is_nil()) {
285 CORBA::Object_var obj = aSObj->GetObject();
286 aGeomObj = GEOM::GEOM_Object::_narrow(obj);
289 if ( !aGeomObj->_is_nil() )
290 S = smeshGen_i->GeomObjectToShape( aGeomObj.in() );
292 SetLocalSize(S, val);
297 //=============================================================================
299 * Pass simple parameters to NETGEN
301 //=============================================================================
303 void NETGENPlugin_Mesher::SetParameters(const NETGENPlugin_SimpleHypothesis_2D* hyp)
307 SetDefaultParameters();
310 //=============================================================================
312 * Link - a pair of integer numbers
314 //=============================================================================
318 Link(int _n1, int _n2) : n1(_n1), n2(_n2) {}
319 Link() : n1(0), n2(0) {}
322 int HashCode(const Link& aLink, int aLimit)
324 return HashCode(aLink.n1 + aLink.n2, aLimit);
327 Standard_Boolean IsEqual(const Link& aLink1, const Link& aLink2)
329 return (aLink1.n1 == aLink2.n1 && aLink1.n2 == aLink2.n2 ||
330 aLink1.n1 == aLink2.n2 && aLink1.n2 == aLink2.n1);
335 //================================================================================
337 * \brief return id of netgen point corresponding to SMDS node
339 //================================================================================
340 typedef map< const SMDS_MeshNode*, int > TNode2IdMap;
342 int ngNodeId( const SMDS_MeshNode* node,
343 netgen::Mesh& ngMesh,
344 TNode2IdMap& nodeNgIdMap)
346 int newNgId = ngMesh.GetNP() + 1;
348 TNode2IdMap::iterator node_id = nodeNgIdMap.insert( make_pair( node, newNgId )).first;
350 if ( node_id->second == newNgId)
352 #if defined(DUMP_SEGMENTS) || defined(DUMP_TRIANGLES)
353 cout << "Ng " << newNgId << " - " << node;
355 netgen::MeshPoint p( netgen::Point<3> (node->X(), node->Y(), node->Z()) );
356 ngMesh.AddPoint( p );
358 return node_id->second;
361 //================================================================================
363 * \brief Return computed EDGEs connected to the given one
365 //================================================================================
367 list< TopoDS_Edge > getConnectedEdges( const TopoDS_Edge& edge,
368 const TopoDS_Face& face,
369 const set< SMESH_subMesh* > & computedSM,
370 const SMESH_MesherHelper& helper,
371 map< SMESH_subMesh*, set< int > >& addedEdgeSM2Faces)
374 list< TopoDS_Edge > edges;
375 list< int > nbEdgesInWire;
376 int nbWires = SMESH_Block::GetOrderedEdges( face, edges, nbEdgesInWire);
378 // find <edge> within <edges>
379 list< TopoDS_Edge >::iterator eItFwd = edges.begin();
380 for ( ; eItFwd != edges.end(); ++eItFwd )
381 if ( edge.IsSame( *eItFwd ))
383 if ( eItFwd == edges.end()) return list< TopoDS_Edge>();
385 if ( eItFwd->Orientation() >= TopAbs_INTERNAL )
387 // connected INTERNAL edges returned from GetOrderedEdges() are wrongly oriented
388 // so treat each INTERNAL edge separately
389 TopoDS_Edge e = *eItFwd;
391 edges.push_back( e );
395 // get all computed EDGEs connected to <edge>
397 list< TopoDS_Edge >::iterator eItBack = eItFwd, ePrev;
398 TopoDS_Vertex vCommon;
399 TopTools_MapOfShape eAdded; // map used not to add a seam edge twice to <edges>
402 // put edges before <edge> to <edges> back
403 while ( edges.begin() != eItFwd )
404 edges.splice( edges.end(), edges, edges.begin() );
408 while ( ++eItFwd != edges.end() )
410 SMESH_subMesh* sm = helper.GetMesh()->GetSubMesh( *eItFwd );
412 bool connected = TopExp::CommonVertex( *ePrev, *eItFwd, vCommon );
413 bool computed = sm->IsMeshComputed();
414 bool added = addedEdgeSM2Faces[ sm ].count( helper.GetSubShapeID() );
415 bool doubled = !eAdded.Add( *eItFwd );
416 bool orientOK = (( ePrev ->Orientation() < TopAbs_INTERNAL ) ==
417 ( eItFwd->Orientation() < TopAbs_INTERNAL ) );
418 if ( !connected || !computed || !orientOK || added || doubled )
420 // stop advancement; move edges from tail to head
421 while ( edges.back() != *ePrev )
422 edges.splice( edges.begin(), edges, --edges.end() );
428 while ( eItBack != edges.begin() )
432 SMESH_subMesh* sm = helper.GetMesh()->GetSubMesh( *eItBack );
434 bool connected = TopExp::CommonVertex( *ePrev, *eItBack, vCommon );
435 bool computed = sm->IsMeshComputed();
436 bool added = addedEdgeSM2Faces[ sm ].count( helper.GetSubShapeID() );
437 bool doubled = !eAdded.Add( *eItBack );
438 bool orientOK = (( ePrev ->Orientation() < TopAbs_INTERNAL ) ==
439 ( eItBack->Orientation() < TopAbs_INTERNAL ) );
440 if ( !connected || !computed || !orientOK || added || doubled)
443 edges.erase( edges.begin(), ePrev );
447 if ( edges.front() != edges.back() )
449 // assure that the 1st vertex is meshed
450 TopoDS_Edge eLast = edges.back();
451 while ( !SMESH_Algo::VertexNode( SMESH_MesherHelper::IthVertex( 0, edges.front()), helper.GetMeshDS())
453 edges.front() != eLast )
454 edges.splice( edges.end(), edges, edges.begin() );
459 //================================================================================
461 * \brief Make triangulation of a shape precise enough
463 //================================================================================
465 void updateTriangulation( const TopoDS_Shape& shape )
467 // static set< Poly_Triangulation* > updated;
469 // TopLoc_Location loc;
470 // TopExp_Explorer fExp( shape, TopAbs_FACE );
471 // for ( ; fExp.More(); fExp.Next() )
473 // Handle(Poly_Triangulation) triangulation =
474 // BRep_Tool::Triangulation ( TopoDS::Face( fExp.Current() ), loc);
475 // if ( triangulation.IsNull() ||
476 // updated.insert( triangulation.operator->() ).second )
478 // BRepTools::Clean (shape);
481 BRepMesh_IncrementalMesh e(shape, 0.01, true);
483 catch (Standard_Failure)
486 // updated.erase( triangulation.operator->() );
487 // triangulation = BRep_Tool::Triangulation ( TopoDS::Face( fExp.Current() ), loc);
488 // updated.insert( triangulation.operator->() );
494 //================================================================================
496 * \brief Initialize netgen::OCCGeometry with OCCT shape
498 //================================================================================
500 void NETGENPlugin_Mesher::PrepareOCCgeometry(netgen::OCCGeometry& occgeo,
501 const TopoDS_Shape& shape,
503 list< SMESH_subMesh* > * meshedSM,
504 NETGENPlugin_Internals* intern)
506 updateTriangulation( shape );
509 BRepBndLib::Add (shape, bb);
510 double x1,y1,z1,x2,y2,z2;
511 bb.Get (x1,y1,z1,x2,y2,z2);
512 MESSAGE("shape bounding box:\n" <<
513 "(" << x1 << " " << y1 << " " << z1 << ") " <<
514 "(" << x2 << " " << y2 << " " << z2 << ")");
515 netgen::Point<3> p1 = netgen::Point<3> (x1,y1,z1);
516 netgen::Point<3> p2 = netgen::Point<3> (x2,y2,z2);
517 occgeo.boundingbox = netgen::Box<3> (p1,p2);
519 occgeo.shape = shape;
522 // fill maps of shapes of occgeo with not yet meshed subshapes
524 // get root submeshes
525 list< SMESH_subMesh* > rootSM;
526 const int shapeID = mesh.GetMeshDS()->ShapeToIndex( shape );
527 if ( shapeID > 0 ) { // SMESH_subMesh with ID 0 may exist, don't use it!
528 rootSM.push_back( mesh.GetSubMesh( shape ));
531 for ( TopoDS_Iterator it( shape ); it.More(); it.Next() )
532 rootSM.push_back( mesh.GetSubMesh( it.Value() ));
535 // add subshapes of empty submeshes
536 list< SMESH_subMesh* >::iterator rootIt = rootSM.begin(), rootEnd = rootSM.end();
537 for ( ; rootIt != rootEnd; ++rootIt ) {
538 SMESH_subMesh * root = *rootIt;
539 SMESH_subMeshIteratorPtr smIt = root->getDependsOnIterator(/*includeSelf=*/true,
540 /*complexShapeFirst=*/true);
541 // to find a right orientation of subshapes (PAL20462)
542 TopTools_IndexedMapOfShape subShapes;
543 TopExp::MapShapes(root->GetSubShape(), subShapes);
544 while ( smIt->more() )
546 SMESH_subMesh* sm = smIt->next();
547 TopoDS_Shape shape = sm->GetSubShape();
548 if ( intern && intern->isShapeToPrecompute( shape ))
550 if ( !meshedSM || sm->IsEmpty() )
552 if ( shape.ShapeType() != TopAbs_VERTEX )
553 shape = subShapes( subShapes.FindIndex( shape ));// shape -> index -> oriented shape
554 if ( shape.Orientation() >= TopAbs_INTERNAL )
555 shape.Orientation( TopAbs_FORWARD ); // isuue 0020676
556 switch ( shape.ShapeType() ) {
557 case TopAbs_FACE : occgeo.fmap.Add( shape ); break;
558 case TopAbs_EDGE : occgeo.emap.Add( shape ); break;
559 case TopAbs_VERTEX: occgeo.vmap.Add( shape ); break;
560 case TopAbs_SOLID :occgeo.somap.Add( shape ); break;
564 // collect submeshes of meshed shapes
567 const int dim = SMESH_Gen::GetShapeDim( shape );
568 meshedSM[ dim ].push_back( sm );
572 occgeo.facemeshstatus.SetSize (occgeo.fmap.Extent());
573 occgeo.facemeshstatus = 0;
574 occgeo.face_maxh_modified.SetSize(occgeo.fmap.Extent());
575 occgeo.face_maxh_modified = 0;
576 occgeo.face_maxh.SetSize(occgeo.fmap.Extent());
577 occgeo.face_maxh = netgen::mparam.maxh;
580 //================================================================================
582 * \brief Return a default min size value suitable for the given geometry.
584 //================================================================================
586 double NETGENPlugin_Mesher::GetDefaultMinSize(const TopoDS_Shape& geom,
587 const double maxSize)
589 updateTriangulation( geom );
593 const int* pi[4] = { &i1, &i2, &i3, &i1 };
596 TopExp_Explorer fExp( geom, TopAbs_FACE );
597 for ( ; fExp.More(); fExp.Next() )
599 Handle(Poly_Triangulation) triangulation =
600 BRep_Tool::Triangulation ( TopoDS::Face( fExp.Current() ), loc);
601 if ( triangulation.IsNull() ) continue;
602 const double fTol = BRep_Tool::Tolerance( TopoDS::Face( fExp.Current() ));
603 const TColgp_Array1OfPnt& points = triangulation->Nodes();
604 const Poly_Array1OfTriangle& trias = triangulation->Triangles();
605 for ( int iT = trias.Lower(); iT <= trias.Upper(); ++iT )
607 trias(iT).Get( i1, i2, i3 );
608 for ( int j = 0; j < 3; ++j )
610 double dist2 = points(*pi[j]).SquareDistance( points( *pi[j+1] ));
611 if ( dist2 < minh && fTol*fTol < dist2 )
613 bb.Add( points(*pi[j]));
617 if ( minh > 0.25 * bb.SquareExtent() ) // simple geometry, rough triangulation
619 minh = 1e-3 * sqrt( bb.SquareExtent());
620 //cout << "BND BOX minh = " <<minh << endl;
624 minh = 3 * sqrt( minh ); // triangulation for visualization is rather fine
625 //cout << "TRIANGULATION minh = " <<minh << endl;
627 if ( minh > 0.5 * maxSize )
633 //================================================================================
635 * \brief Restrict size of elements at a given point
637 //================================================================================
639 void NETGENPlugin_Mesher::RestrictLocalSize(netgen::Mesh& ngMesh, const gp_XYZ& p, const double size)
641 if ( netgen::mparam.minh > size )
643 ngMesh.SetMinimalH( size );
644 netgen::mparam.minh = size;
646 netgen::Point3d pi(p.X(), p.Y(), p.Z());
647 ngMesh.RestrictLocalH( pi, size );
650 //================================================================================
652 * \brief fill ngMesh with nodes and elements of computed submeshes
654 //================================================================================
656 bool NETGENPlugin_Mesher::FillNgMesh(netgen::OCCGeometry& occgeom,
657 netgen::Mesh& ngMesh,
658 vector<const SMDS_MeshNode*>& nodeVec,
659 const list< SMESH_subMesh* > & meshedSM,
660 SMESH_ProxyMesh::Ptr proxyMesh)
662 TNode2IdMap nodeNgIdMap;
663 for ( int i = 1; i < nodeVec.size(); ++i )
664 nodeNgIdMap.insert( make_pair( nodeVec[i], i ));
666 TopTools_MapOfShape visitedShapes;
667 map< SMESH_subMesh*, set< int > > visitedEdgeSM2Faces;
668 set< SMESH_subMesh* > computedSM( meshedSM.begin(), meshedSM.end() );
670 SMESH_MesherHelper helper (*_mesh);
672 int faceNgID = ngMesh.GetNFD();
674 list< SMESH_subMesh* >::const_iterator smIt, smEnd = meshedSM.end();
675 for ( smIt = meshedSM.begin(); smIt != smEnd; ++smIt )
677 SMESH_subMesh* sm = *smIt;
678 if ( !visitedShapes.Add( sm->GetSubShape() ))
681 const SMESHDS_SubMesh * smDS = sm->GetSubMeshDS();
682 if ( !smDS ) continue;
684 switch ( sm->GetSubShape().ShapeType() )
686 case TopAbs_EDGE: { // EDGE
687 // ----------------------
688 TopoDS_Edge geomEdge = TopoDS::Edge( sm->GetSubShape() );
689 if ( geomEdge.Orientation() >= TopAbs_INTERNAL )
690 geomEdge.Orientation( TopAbs_FORWARD ); // issue 0020676
692 // Add ng segments for each not meshed FACE the EDGE bounds
693 PShapeIteratorPtr fIt = helper.GetAncestors( geomEdge, *sm->GetFather(), TopAbs_FACE );
694 while ( const TopoDS_Shape * anc = fIt->next() )
696 faceNgID = occgeom.fmap.FindIndex( *anc );
698 continue; // meshed face
700 int faceSMDSId = helper.GetMeshDS()->ShapeToIndex( *anc );
701 if ( visitedEdgeSM2Faces[ sm ].count( faceSMDSId ))
702 continue; // already treated EDGE
704 TopoDS_Face face = TopoDS::Face( occgeom.fmap( faceNgID ));
705 if ( face.Orientation() >= TopAbs_INTERNAL )
706 face.Orientation( TopAbs_FORWARD ); // issue 0020676
708 // get all meshed EDGEs of the FACE connected to geomEdge (issue 0021140)
709 helper.SetSubShape( face );
710 list< TopoDS_Edge > edges = getConnectedEdges( geomEdge, face, computedSM, helper,
711 visitedEdgeSM2Faces );
713 continue; // wrong ancestor?
715 // find out orientation of <edges> within <face>
716 TopoDS_Edge eNotSeam = edges.front();
717 if ( helper.HasSeam() )
719 list< TopoDS_Edge >::iterator eIt = edges.begin();
720 while ( helper.IsRealSeam( *eIt )) ++eIt;
721 if ( eIt != edges.end() )
724 TopAbs_Orientation fOri = helper.GetSubShapeOri( face, eNotSeam );
725 bool isForwad = ( fOri == eNotSeam.Orientation() || fOri >= TopAbs_INTERNAL );
727 // get all nodes from connected <edges>
728 bool isQuad = smDS->NbElements() ? smDS->GetElements()->next()->IsQuadratic() : false;
729 StdMeshers_FaceSide fSide( face, edges, _mesh, isForwad, isQuad );
730 const vector<UVPtStruct>& points = fSide.GetUVPtStruct();
731 int i, nbSeg = fSide.NbSegments();
733 // remember EDGEs of fSide to treat only once
734 for ( int iE = 0; iE < fSide.NbEdges(); ++iE )
735 visitedEdgeSM2Faces[ helper.GetMesh()->GetSubMesh( fSide.Edge(iE )) ].insert(faceSMDSId);
737 double otherSeamParam = 0;
742 int prevNgId = ngNodeId( points[0].node, ngMesh, nodeNgIdMap );
744 for ( i = 0; i < nbSeg; ++i )
746 const UVPtStruct& p1 = points[ i ];
747 const UVPtStruct& p2 = points[ i+1 ];
749 if ( p1.node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX ) //an EDGE begins
752 if ( helper.IsRealSeam( p1.node->getshapeId() ))
754 TopoDS_Edge e = fSide.Edge( fSide.EdgeIndex( 0.5 * ( p1.normParam + p2.normParam )));
755 isSeam = helper.IsRealSeam( e );
758 otherSeamParam = helper.GetOtherParam( helper.GetPeriodicIndex() & 1 ? p2.u : p2.v );
765 seg[1] = prevNgId = ngNodeId( p2.node, ngMesh, nodeNgIdMap );
766 // node param on curve
767 seg.epgeominfo[ 0 ].dist = p1.param;
768 seg.epgeominfo[ 1 ].dist = p2.param;
770 seg.epgeominfo[ 0 ].u = p1.u;
771 seg.epgeominfo[ 0 ].v = p1.v;
772 seg.epgeominfo[ 1 ].u = p2.u;
773 seg.epgeominfo[ 1 ].v = p2.v;
775 //geomEdge = fSide.Edge( fSide.EdgeIndex( 0.5 * ( p1.normParam + p2.normParam )));
776 //seg.epgeominfo[ 0 ].edgenr = seg.epgeominfo[ 1 ].edgenr = occgeom.emap.FindIndex( geomEdge );
778 //seg.epgeominfo[ iEnd ].edgenr = edgeID; // = geom.emap.FindIndex(edge);
779 seg.si = faceNgID; // = geom.fmap.FindIndex (face);
780 seg.edgenr = ngMesh.GetNSeg() + 1; // segment id
781 ngMesh.AddSegment (seg);
783 SMESH_TNodeXYZ np1( p1.node ), np2( p2.node );
784 RestrictLocalSize( ngMesh, 0.5*(np1+np2), (np1-np2).Modulus() );
787 cout << "Segment: " << seg.edgenr << " on SMESH face " << helper.GetMeshDS()->ShapeToIndex( face ) << endl
788 << "\tface index: " << seg.si << endl
789 << "\tp1: " << seg[0] << endl
790 << "\tp2: " << seg[1] << endl
791 << "\tp0 param: " << seg.epgeominfo[ 0 ].dist << endl
792 << "\tp0 uv: " << seg.epgeominfo[ 0 ].u <<", "<< seg.epgeominfo[ 0 ].v << endl
793 //<< "\tp0 edge: " << seg.epgeominfo[ 0 ].edgenr << endl
794 << "\tp1 param: " << seg.epgeominfo[ 1 ].dist << endl
795 << "\tp1 uv: " << seg.epgeominfo[ 1 ].u <<", "<< seg.epgeominfo[ 1 ].v << endl;
796 //<< "\tp1 edge: " << seg.epgeominfo[ 1 ].edgenr << endl;
800 if ( helper.GetPeriodicIndex() && 1 ) {
801 seg.epgeominfo[ 0 ].u = otherSeamParam;
802 seg.epgeominfo[ 1 ].u = otherSeamParam;
803 swap (seg.epgeominfo[0].v, seg.epgeominfo[1].v);
805 seg.epgeominfo[ 0 ].v = otherSeamParam;
806 seg.epgeominfo[ 1 ].v = otherSeamParam;
807 swap (seg.epgeominfo[0].u, seg.epgeominfo[1].u);
809 swap (seg[0], seg[1]);
810 swap (seg.epgeominfo[0].dist, seg.epgeominfo[1].dist);
811 seg.edgenr = ngMesh.GetNSeg() + 1; // segment id
812 ngMesh.AddSegment (seg);
814 cout << "Segment: " << seg.edgenr << endl
815 << "\t is SEAM (reverse) of the previous. "
816 << " Other " << (helper.GetPeriodicIndex() && 1 ? "U" : "V")
817 << " = " << otherSeamParam << endl;
820 else if ( fOri == TopAbs_INTERNAL )
822 swap (seg[0], seg[1]);
823 swap( seg.epgeominfo[0], seg.epgeominfo[1] );
824 seg.edgenr = ngMesh.GetNSeg() + 1; // segment id
825 ngMesh.AddSegment (seg);
827 cout << "Segment: " << seg.edgenr << endl << "\t is REVERSE of the previous" << endl;
831 } // loop on geomEdge ancestors
834 } // case TopAbs_EDGE
836 case TopAbs_FACE: { // FACE
837 // ----------------------
838 const TopoDS_Face& geomFace = TopoDS::Face( sm->GetSubShape() );
839 helper.SetSubShape( geomFace );
840 bool isInternalFace = ( geomFace.Orientation() == TopAbs_INTERNAL );
842 // Find solids the geomFace bounds
843 int solidID1 = 0, solidID2 = 0;
844 StdMeshers_QuadToTriaAdaptor* quadAdaptor =
845 dynamic_cast<StdMeshers_QuadToTriaAdaptor*>( proxyMesh.get() );
848 solidID1 = occgeom.somap.FindIndex( quadAdaptor->GetShape() );
852 PShapeIteratorPtr solidIt = helper.GetAncestors( geomFace, *sm->GetFather(), TopAbs_SOLID);
853 while ( const TopoDS_Shape * solid = solidIt->next() )
855 int id = occgeom.somap.FindIndex ( *solid );
856 if ( solidID1 && id != solidID1 ) solidID2 = id;
860 // Add ng face descriptors of meshed faces
862 ngMesh.AddFaceDescriptor (netgen::FaceDescriptor(faceNgID, solidID1, solidID2, 0));
864 // if second oreder is required, even already meshed faces must be passed to NETGEN
865 int fID = occgeom.fmap.Add( geomFace );
866 while ( fID < faceNgID ) // geomFace is already in occgeom.fmap, add a copy
867 fID = occgeom.fmap.Add( BRepBuilderAPI_Copy( geomFace, /*copyGeom=*/false ));
868 // Problem with the second order in a quadrangular mesh remains.
869 // 1) All quadrangles geberated by NETGEN are moved to an inexistent face
870 // by FillSMesh() (find AddFaceDescriptor)
871 // 2) Temporary triangles generated by StdMeshers_QuadToTriaAdaptor
872 // are on faces where quadrangles were.
873 // Due to these 2 points, wrong geom faces are used while conversion to qudratic
874 // of the mentioned above quadrangles and triangles
876 // Orient the face correctly in solidID1 (issue 0020206)
877 bool reverse = false;
879 TopoDS_Shape solid = occgeom.somap( solidID1 );
880 TopAbs_Orientation faceOriInSolid = helper.GetSubShapeOri( solid, geomFace );
881 if ( faceOriInSolid >= 0 )
883 helper.IsReversedSubMesh( TopoDS::Face( geomFace.Oriented( faceOriInSolid )));
886 // Add surface elements
888 netgen::Element2d tri(3);
889 tri.SetIndex ( faceNgID );
892 #ifdef DUMP_TRIANGLES
893 cout << "SMESH face " << helper.GetMeshDS()->ShapeToIndex( geomFace )
894 << " internal="<<isInternalFace << endl;
897 smDS = proxyMesh->GetSubMesh( geomFace );
899 SMDS_ElemIteratorPtr faces = smDS->GetElements();
900 while ( faces->more() )
902 const SMDS_MeshElement* f = faces->next();
903 if ( f->NbNodes() % 3 != 0 ) // not triangle
905 PShapeIteratorPtr solidIt=helper.GetAncestors(geomFace,*sm->GetFather(),TopAbs_SOLID);
906 if ( const TopoDS_Shape * solid = solidIt->next() )
907 sm = _mesh->GetSubMesh( *solid );
908 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
909 smError.reset( new SMESH_ComputeError(COMPERR_BAD_INPUT_MESH,"Not triangle submesh"));
910 smError->myBadElements.push_back( f );
914 for ( int i = 0; i < 3; ++i )
916 const SMDS_MeshNode* node = f->GetNode( i ), * inFaceNode=0;
918 // get node UV on face
919 int shapeID = node->getshapeId();
920 if ( helper.IsSeamShape( shapeID ))
921 if ( helper.IsSeamShape( f->GetNodeWrap( i+1 )->getshapeId() ))
922 inFaceNode = f->GetNodeWrap( i-1 );
924 inFaceNode = f->GetNodeWrap( i+1 );
925 gp_XY uv = helper.GetNodeUV( geomFace, node, inFaceNode );
927 int ind = reverse ? 3-i : i+1;
928 tri.GeomInfoPi(ind).u = uv.X();
929 tri.GeomInfoPi(ind).v = uv.Y();
930 tri.PNum (ind) = ngNodeId( node, ngMesh, nodeNgIdMap );
933 ngMesh.AddSurfaceElement (tri);
934 #ifdef DUMP_TRIANGLES
938 if ( isInternalFace )
940 swap( tri[1], tri[2] );
941 ngMesh.AddSurfaceElement (tri);
942 #ifdef DUMP_TRIANGLES
948 } // case TopAbs_FACE
950 case TopAbs_VERTEX: { // VERTEX
951 // --------------------------
952 // issue 0021405. Add node only if a VERTEX is shared by a not meshed EDGE,
953 // else netgen removes a free node and nodeVector becomes invalid
954 PShapeIteratorPtr ansIt = helper.GetAncestors( sm->GetSubShape(),
958 while ( const TopoDS_Shape* e = ansIt->next() )
960 SMESH_subMesh* eSub = helper.GetMesh()->GetSubMesh( *e );
961 if (( toAdd = eSub->IsEmpty() )) break;
965 SMDS_NodeIteratorPtr nodeIt = smDS->GetNodes();
966 if ( nodeIt->more() )
967 ngNodeId( nodeIt->next(), ngMesh, nodeNgIdMap );
973 } // loop on submeshes
976 nodeVec.resize( ngMesh.GetNP() + 1 );
977 TNode2IdMap::iterator node_NgId, nodeNgIdEnd = nodeNgIdMap.end();
978 for ( node_NgId = nodeNgIdMap.begin(); node_NgId != nodeNgIdEnd; ++node_NgId)
979 nodeVec[ node_NgId->second ] = node_NgId->first;
984 //================================================================================
986 * \brief Duplicate mesh faces on internal geom faces
988 //================================================================================
990 void NETGENPlugin_Mesher::FixIntFaces(const netgen::OCCGeometry& occgeom,
991 netgen::Mesh& ngMesh,
992 NETGENPlugin_Internals& internalShapes)
994 SMESHDS_Mesh* meshDS = internalShapes.getMesh().GetMeshDS();
996 // find ng indices of internal faces
998 for ( int ngFaceID = 1; ngFaceID <= occgeom.fmap.Extent(); ++ngFaceID )
1000 int smeshID = meshDS->ShapeToIndex( occgeom.fmap( ngFaceID ));
1001 if ( internalShapes.isInternalShape( smeshID ))
1002 ngFaceIds.insert( ngFaceID );
1004 if ( !ngFaceIds.empty() )
1007 int i, nbFaces = ngMesh.GetNSE();
1008 for (int i = 1; i <= nbFaces; ++i)
1010 netgen::Element2d elem = ngMesh.SurfaceElement(i);
1011 if ( ngFaceIds.count( elem.GetIndex() ))
1013 swap( elem[1], elem[2] );
1014 ngMesh.AddSurfaceElement (elem);
1022 //================================================================================
1023 // define gp_XY_Subtracted pointer to function calling gp_XY::Subtracted(gp_XY)
1024 gp_XY_FunPtr(Subtracted);
1025 //gp_XY_FunPtr(Added);
1027 //================================================================================
1029 * \brief Evaluate distance between two 2d points along the surface
1031 //================================================================================
1033 double evalDist( const gp_XY& uv1,
1035 const Handle(Geom_Surface)& surf,
1036 const int stopHandler=-1)
1038 if ( stopHandler > 0 ) // continue recursion
1040 gp_XY mid = SMESH_MesherHelper::GetMiddleUV( surf, uv1, uv2 );
1041 return evalDist( uv1,mid, surf, stopHandler-1 ) + evalDist( mid,uv2, surf, stopHandler-1 );
1043 double dist3D = surf->Value( uv1.X(), uv1.Y() ).Distance( surf->Value( uv2.X(), uv2.Y() ));
1044 if ( stopHandler == 0 ) // stop recursion
1047 // start recursion if necessary
1048 double dist2D = SMESH_MesherHelper::applyIn2D(surf, uv1, uv2, gp_XY_Subtracted, 0).Modulus();
1049 if ( fabs( dist3D - dist2D ) < dist2D * 1e-10 )
1050 return dist3D; // equal parametrization of a planar surface
1052 return evalDist( uv1, uv2, surf, 3 ); // start recursion
1055 //================================================================================
1057 * \brief Data of vertex internal in geom face
1059 //================================================================================
1063 gp_XY uv; //!< UV in face parametric space
1064 int ngId; //!< ng id of corrsponding node
1065 gp_XY uvClose; //!< UV of closest boundary node
1066 int ngIdClose; //!< ng id of closest boundary node
1069 //================================================================================
1071 * \brief Data of vertex internal in solid
1073 //================================================================================
1077 int ngId; //!< ng id of corresponding node
1078 int ngIdClose; //!< ng id of closest 2d mesh element
1079 int ngIdCloseN; //!< ng id of closest node of the closest 2d mesh element
1082 inline double dist2(const netgen::MeshPoint& p1, const netgen::MeshPoint& p2)
1084 return gp_Pnt( NGPOINT_COORDS(p1)).SquareDistance( gp_Pnt( NGPOINT_COORDS(p2)));
1088 //================================================================================
1090 * \brief Make netgen take internal vertices in faces into account by adding
1091 * segments including internal vertices
1093 * This function works in supposition that 1D mesh is already computed in ngMesh
1095 //================================================================================
1097 void NETGENPlugin_Mesher::AddIntVerticesInFaces(const netgen::OCCGeometry& occgeom,
1098 netgen::Mesh& ngMesh,
1099 vector<const SMDS_MeshNode*>& nodeVec,
1100 NETGENPlugin_Internals& internalShapes)
1102 if ( nodeVec.size() < ngMesh.GetNP() )
1103 nodeVec.resize( ngMesh.GetNP(), 0 );
1105 SMESHDS_Mesh* meshDS = internalShapes.getMesh().GetMeshDS();
1106 SMESH_MesherHelper helper( internalShapes.getMesh() );
1108 const map<int,list<int> >& face2Vert = internalShapes.getFacesWithVertices();
1109 map<int,list<int> >::const_iterator f2v = face2Vert.begin();
1110 for ( ; f2v != face2Vert.end(); ++f2v )
1112 const TopoDS_Face& face = TopoDS::Face( meshDS->IndexToShape( f2v->first ));
1113 if ( face.IsNull() ) continue;
1114 int faceNgID = occgeom.fmap.FindIndex (face);
1115 if ( faceNgID < 0 ) continue;
1117 TopLoc_Location loc;
1118 Handle(Geom_Surface) surf = BRep_Tool::Surface(face,loc);
1120 helper.SetSubShape( face );
1121 helper.SetElementsOnShape( true );
1123 // Get data of internal vertices and add them to ngMesh
1125 multimap< double, TIntVData > dist2VData; // sort vertices by distance from boundary nodes
1127 int i, nbSegInit = ngMesh.GetNSeg();
1129 // boundary characteristics
1130 double totSegLen2D = 0;
1133 const list<int>& iVertices = f2v->second;
1134 list<int>::const_iterator iv = iVertices.begin();
1135 for ( int nbV = 0; iv != iVertices.end(); ++iv, nbV++ )
1138 // get node on vertex
1139 const TopoDS_Vertex V = TopoDS::Vertex( meshDS->IndexToShape( *iv ));
1140 const SMDS_MeshNode * nV = SMESH_Algo::VertexNode( V, meshDS );
1143 SMESH_subMesh* sm = helper.GetMesh()->GetSubMesh( V );
1144 sm->ComputeStateEngine( SMESH_subMesh::COMPUTE );
1145 nV = SMESH_Algo::VertexNode( V, meshDS );
1146 if ( !nV ) continue;
1149 netgen::MeshPoint mp( netgen::Point<3> (nV->X(), nV->Y(), nV->Z()) );
1150 ngMesh.AddPoint ( mp, 1, netgen::EDGEPOINT );
1151 vData.ngId = ngMesh.GetNP();
1152 nodeVec.push_back( nV );
1156 vData.uv = helper.GetNodeUV( face, nV, 0, &uvOK );
1157 if ( !uvOK ) helper.CheckNodeUV( face, nV, vData.uv, BRep_Tool::Tolerance(V),/*force=*/1);
1159 // loop on all segments of the face to find the node closest to vertex and to count
1160 // average segment 2d length
1161 double closeDist2 = numeric_limits<double>::max(), dist2;
1163 for (i = 1; i <= ngMesh.GetNSeg(); ++i)
1165 netgen::Segment & seg = ngMesh.LineSegment(i);
1166 if ( seg.si != faceNgID ) continue;
1168 for ( int iEnd = 0; iEnd < 2; ++iEnd)
1170 uv[iEnd].SetCoord( seg.epgeominfo[iEnd].u, seg.epgeominfo[iEnd].v );
1171 if ( ngIdLast == seg[ iEnd ] ) continue;
1172 dist2 = helper.applyIn2D(surf, uv[iEnd], vData.uv, gp_XY_Subtracted,0).SquareModulus();
1173 if ( dist2 < closeDist2 )
1174 vData.ngIdClose = seg[ iEnd ], vData.uvClose = uv[iEnd], closeDist2 = dist2;
1175 ngIdLast = seg[ iEnd ];
1179 totSegLen2D += helper.applyIn2D(surf, uv[0], uv[1], gp_XY_Subtracted, false).Modulus();
1183 dist2VData.insert( make_pair( closeDist2, vData ));
1186 if ( totNbSeg == 0 ) break;
1187 double avgSegLen2d = totSegLen2D / totNbSeg;
1189 // Loop on vertices to add segments
1191 multimap< double, TIntVData >::iterator dist_vData = dist2VData.begin();
1192 for ( ; dist_vData != dist2VData.end(); ++dist_vData )
1194 double closeDist2 = dist_vData->first, dist2;
1195 TIntVData & vData = dist_vData->second;
1197 // try to find more close node among segments added for internal vertices
1198 for (i = nbSegInit+1; i <= ngMesh.GetNSeg(); ++i)
1200 netgen::Segment & seg = ngMesh.LineSegment(i);
1201 if ( seg.si != faceNgID ) continue;
1203 for ( int iEnd = 0; iEnd < 2; ++iEnd)
1205 uv[iEnd].SetCoord( seg.epgeominfo[iEnd].u, seg.epgeominfo[iEnd].v );
1206 dist2 = helper.applyIn2D(surf, uv[iEnd], vData.uv, gp_XY_Subtracted,0).SquareModulus();
1207 if ( dist2 < closeDist2 )
1208 vData.ngIdClose = seg[ iEnd ], vData.uvClose = uv[iEnd], closeDist2 = dist2;
1211 // decide whether to use the closest node as the second end of segment or to
1212 // create a new point
1213 int segEnd1 = vData.ngId;
1214 int segEnd2 = vData.ngIdClose; // to use closest node
1215 gp_XY uvV = vData.uv, uvP = vData.uvClose;
1216 double segLenHint = ngMesh.GetH( ngMesh.Point( vData.ngId ));
1217 double nodeDist2D = sqrt( closeDist2 );
1218 double nodeDist3D = evalDist( vData.uv, vData.uvClose, surf );
1219 bool avgLenOK = ( avgSegLen2d < 0.75 * nodeDist2D );
1220 bool hintLenOK = ( segLenHint < 0.75 * nodeDist3D );
1221 //cout << "uvV " << uvV.X() <<","<<uvV.Y() << " ";
1222 if ( hintLenOK || avgLenOK )
1224 // create a point between the closest node and V
1227 double r = min( 0.5, ( hintLenOK ? segLenHint/nodeDist3D : avgSegLen2d/nodeDist2D ));
1228 // direction from V to closet node in 2D
1229 gp_Dir2d v2n( helper.applyIn2D(surf, uvP, uvV, gp_XY_Subtracted, false ));
1231 uvP = vData.uv + r * nodeDist2D * v2n.XY();
1232 gp_Pnt P = surf->Value( uvP.X(), uvP.Y() ).Transformed( loc );
1234 netgen::MeshPoint mp( netgen::Point<3> (P.X(), P.Y(), P.Z()));
1235 ngMesh.AddPoint ( mp, 1, netgen::EDGEPOINT );
1236 segEnd2 = ngMesh.GetNP();
1237 //cout << "Middle " << r << " uv " << uvP.X() << "," << uvP.Y() << "( " << ngMesh.Point(segEnd2).X()<<","<<ngMesh.Point(segEnd2).Y()<<","<<ngMesh.Point(segEnd2).Z()<<" )"<< endl;
1238 SMDS_MeshNode * nP = helper.AddNode(P.X(), P.Y(), P.Z());
1239 nodeVec.push_back( nP );
1241 //else cout << "at Node " << " uv " << uvP.X() << "," << uvP.Y() << endl;
1244 netgen::Segment seg;
1246 if ( segEnd1 > segEnd2 ) swap( segEnd1, segEnd2 ), swap( uvV, uvP );
1247 seg[0] = segEnd1; // ng node id
1248 seg[1] = segEnd2; // ng node id
1249 seg.edgenr = ngMesh.GetNSeg() + 1;// segment id
1252 seg.epgeominfo[ 0 ].dist = 0; // param on curve
1253 seg.epgeominfo[ 0 ].u = uvV.X();
1254 seg.epgeominfo[ 0 ].v = uvV.Y();
1255 seg.epgeominfo[ 1 ].dist = 1; // param on curve
1256 seg.epgeominfo[ 1 ].u = uvP.X();
1257 seg.epgeominfo[ 1 ].v = uvP.Y();
1259 // seg.epgeominfo[ 0 ].edgenr = 10; // = geom.emap.FindIndex(edge);
1260 // seg.epgeominfo[ 1 ].edgenr = 10; // = geom.emap.FindIndex(edge);
1262 ngMesh.AddSegment (seg);
1264 // add reverse segment
1265 swap (seg[0], seg[1]);
1266 swap( seg.epgeominfo[0], seg.epgeominfo[1] );
1267 seg.edgenr = ngMesh.GetNSeg() + 1; // segment id
1268 ngMesh.AddSegment (seg);
1274 //================================================================================
1276 * \brief Make netgen take internal vertices in solids into account by adding
1277 * faces including internal vertices
1279 * This function works in supposition that 2D mesh is already computed in ngMesh
1281 //================================================================================
1283 void NETGENPlugin_Mesher::AddIntVerticesInSolids(const netgen::OCCGeometry& occgeom,
1284 netgen::Mesh& ngMesh,
1285 vector<const SMDS_MeshNode*>& nodeVec,
1286 NETGENPlugin_Internals& internalShapes)
1288 #ifdef DUMP_TRIANGLES_SCRIPT
1289 // create a python script making a mesh containing triangles added for internal vertices
1290 ofstream py(DUMP_TRIANGLES_SCRIPT);
1291 py << "import SMESH"<< endl
1292 << "from salome.smesh import smeshBuilder"<<endl
1293 << "smesh = smeshBuilder.New(salome.myStudy)"
1294 << "m = smesh.Mesh(name='triangles')" << endl;
1296 if ( nodeVec.size() < ngMesh.GetNP() )
1297 nodeVec.resize( ngMesh.GetNP(), 0 );
1299 SMESHDS_Mesh* meshDS = internalShapes.getMesh().GetMeshDS();
1300 SMESH_MesherHelper helper( internalShapes.getMesh() );
1302 const map<int,list<int> >& so2Vert = internalShapes.getSolidsWithVertices();
1303 map<int,list<int> >::const_iterator s2v = so2Vert.begin();
1304 for ( ; s2v != so2Vert.end(); ++s2v )
1306 const TopoDS_Shape& solid = meshDS->IndexToShape( s2v->first );
1307 if ( solid.IsNull() ) continue;
1308 int solidNgID = occgeom.somap.FindIndex (solid);
1309 if ( solidNgID < 0 && !occgeom.somap.IsEmpty() ) continue;
1311 helper.SetSubShape( solid );
1312 helper.SetElementsOnShape( true );
1314 // find ng indices of faces within the solid
1316 for (TopExp_Explorer fExp(solid, TopAbs_FACE); fExp.More(); fExp.Next() )
1317 ngFaceIds.insert( occgeom.fmap.FindIndex( fExp.Current() ));
1318 if ( ngFaceIds.size() == 1 && *ngFaceIds.begin() == 0 )
1319 ngFaceIds.insert( 1 );
1321 // Get data of internal vertices and add them to ngMesh
1323 multimap< double, TIntVSoData > dist2VData; // sort vertices by distance from ng faces
1325 int i, nbFaceInit = ngMesh.GetNSE();
1327 // boundary characteristics
1328 double totSegLen = 0;
1331 const list<int>& iVertices = s2v->second;
1332 list<int>::const_iterator iv = iVertices.begin();
1333 for ( int nbV = 0; iv != iVertices.end(); ++iv, nbV++ )
1336 const TopoDS_Vertex V = TopoDS::Vertex( meshDS->IndexToShape( *iv ));
1338 // get node on vertex
1339 const SMDS_MeshNode * nV = SMESH_Algo::VertexNode( V, meshDS );
1342 SMESH_subMesh* sm = helper.GetMesh()->GetSubMesh( V );
1343 sm->ComputeStateEngine( SMESH_subMesh::COMPUTE );
1344 nV = SMESH_Algo::VertexNode( V, meshDS );
1345 if ( !nV ) continue;
1348 netgen::MeshPoint mpV( netgen::Point<3> (nV->X(), nV->Y(), nV->Z()) );
1349 ngMesh.AddPoint ( mpV, 1, netgen::FIXEDPOINT );
1350 vData.ngId = ngMesh.GetNP();
1351 nodeVec.push_back( nV );
1353 // loop on all 2d elements to find the one closest to vertex and to count
1354 // average segment length
1355 double closeDist2 = numeric_limits<double>::max(), avgDist2;
1356 for (i = 1; i <= ngMesh.GetNSE(); ++i)
1358 const netgen::Element2d& elem = ngMesh.SurfaceElement(i);
1359 if ( !ngFaceIds.count( elem.GetIndex() )) continue;
1361 multimap< double, int> dist2nID; // sort nodes of element by distance from V
1362 for ( int j = 0; j < elem.GetNP(); ++j)
1364 netgen::MeshPoint mp = ngMesh.Point( elem[j] );
1365 double d2 = dist2( mpV, mp );
1366 dist2nID.insert( make_pair( d2, elem[j] ));
1367 avgDist2 += d2 / elem.GetNP();
1369 totNbSeg++, totSegLen+= sqrt( dist2( mp, ngMesh.Point( elem[(j+1)%elem.GetNP()])));
1371 double dist = dist2nID.begin()->first; //avgDist2;
1372 if ( dist < closeDist2 )
1373 vData.ngIdClose= i, vData.ngIdCloseN= dist2nID.begin()->second, closeDist2= dist;
1375 dist2VData.insert( make_pair( closeDist2, vData ));
1378 if ( totNbSeg == 0 ) break;
1379 double avgSegLen = totSegLen / totNbSeg;
1381 // Loop on vertices to add triangles
1383 multimap< double, TIntVSoData >::iterator dist_vData = dist2VData.begin();
1384 for ( ; dist_vData != dist2VData.end(); ++dist_vData )
1386 double closeDist2 = dist_vData->first;
1387 TIntVSoData & vData = dist_vData->second;
1389 const netgen::MeshPoint& mpV = ngMesh.Point( vData.ngId );
1391 // try to find more close face among ones added for internal vertices
1392 for (i = nbFaceInit+1; i <= ngMesh.GetNSE(); ++i)
1394 double avgDist2 = 0;
1395 multimap< double, int> dist2nID;
1396 const netgen::Element2d& elem = ngMesh.SurfaceElement(i);
1397 for ( int j = 0; j < elem.GetNP(); ++j)
1399 double d = dist2( mpV, ngMesh.Point( elem[j] ));
1400 dist2nID.insert( make_pair( d, elem[j] ));
1401 avgDist2 += d / elem.GetNP();
1402 if ( avgDist2 < closeDist2 )
1403 vData.ngIdClose= i, vData.ngIdCloseN= dist2nID.begin()->second, closeDist2= avgDist2;
1406 // sort nodes of the closest face by angle with vector from V to the closest node
1407 const double tol = numeric_limits<double>::min();
1408 map< double, int > angle2ID;
1409 const netgen::Element2d& closeFace = ngMesh.SurfaceElement( vData.ngIdClose );
1410 netgen::MeshPoint mp[2];
1411 mp[0] = ngMesh.Point( vData.ngIdCloseN );
1412 gp_XYZ p1( NGPOINT_COORDS( mp[0] ));
1413 gp_XYZ pV( NGPOINT_COORDS( mpV ));
1414 gp_Vec v2p1( pV, p1 );
1415 double distN1 = v2p1.Magnitude();
1416 if ( distN1 <= tol ) continue;
1418 for ( int j = 0; j < closeFace.GetNP(); ++j)
1420 mp[1] = ngMesh.Point( closeFace[j] );
1421 gp_Vec v2p( pV, gp_Pnt( NGPOINT_COORDS( mp[1] )) );
1422 angle2ID.insert( make_pair( v2p1.Angle( v2p ), closeFace[j]));
1424 // get node with angle of 60 degrees or greater
1425 map< double, int >::iterator angle_id = angle2ID.lower_bound( 60. * M_PI / 180. );
1426 if ( angle_id == angle2ID.end() ) angle_id = --angle2ID.end();
1427 const double minAngle = 30. * M_PI / 180.;
1428 const double angle = angle_id->first;
1429 bool angleOK = ( angle > minAngle );
1431 // find points to create a triangle
1432 netgen::Element2d tri(3);
1434 tri[0] = vData.ngId;
1435 tri[1] = vData.ngIdCloseN; // to use the closest nodes
1436 tri[2] = angle_id->second; // to use the node with best angle
1438 // decide whether to use the closest node and the node with best angle or to create new ones
1439 for ( int isBestAngleN = 0; isBestAngleN < 2; ++isBestAngleN )
1441 bool createNew = !angleOK, distOK = true;
1443 int triInd = isBestAngleN ? 2 : 1;
1444 mp[isBestAngleN] = ngMesh.Point( tri[triInd] );
1449 double distN2 = sqrt( dist2( mpV, mp[isBestAngleN]));
1450 createNew = ( fabs( distN2 - distN1 ) > 0.25 * distN1 );
1452 else if ( angle < tol )
1454 v2p1.SetX( v2p1.X() + 1e-3 );
1460 double segLenHint = ngMesh.GetH( ngMesh.Point( vData.ngId ));
1461 bool avgLenOK = ( avgSegLen < 0.75 * distN1 );
1462 bool hintLenOK = ( segLenHint < 0.75 * distN1 );
1463 createNew = (createNew || avgLenOK || hintLenOK );
1464 // we create a new node not closer than 0.5 to the closest face
1465 // in order not to clash with other close face
1466 double r = min( 0.5, ( hintLenOK ? segLenHint : avgSegLen ) / distN1 );
1467 distFromV = r * distN1;
1471 // create a new point, between the node and the vertex if angleOK
1472 gp_XYZ p( NGPOINT_COORDS( mp[isBestAngleN] ));
1473 gp_Vec v2p( pV, p ); v2p.Normalize();
1474 if ( isBestAngleN && !angleOK )
1475 p = p1 + gp_Dir( v2p.XYZ() - v2p1.XYZ()).XYZ() * distN1 * 0.95;
1477 p = pV + v2p.XYZ() * distFromV;
1479 if ( !isBestAngleN ) p1 = p, distN1 = distFromV;
1481 mp[isBestAngleN].SetPoint( netgen::Point<3> (p.X(), p.Y(), p.Z()));
1482 ngMesh.AddPoint ( mp[isBestAngleN], 1, netgen::SURFACEPOINT );
1483 tri[triInd] = ngMesh.GetNP();
1484 nodeVec.push_back( helper.AddNode( p.X(), p.Y(), p.Z()) );
1487 ngMesh.AddSurfaceElement (tri);
1488 swap( tri[1], tri[2] );
1489 ngMesh.AddSurfaceElement (tri);
1491 #ifdef DUMP_TRIANGLES_SCRIPT
1492 py << "n1 = m.AddNode( "<< mpV.X()<<", "<< mpV.Y()<<", "<< mpV.Z()<<") "<< endl
1493 << "n2 = m.AddNode( "<< mp[0].X()<<", "<< mp[0].Y()<<", "<< mp[0].Z()<<") "<< endl
1494 << "n3 = m.AddNode( "<< mp[1].X()<<", "<< mp[1].Y()<<", "<< mp[1].Z()<<" )" << endl
1495 << "m.AddFace([n1,n2,n3])" << endl;
1497 } // loop on internal vertices of a solid
1499 } // loop on solids with internal vertices
1502 //================================================================================
1504 * \brief Fill netgen mesh with segments of a FACE
1505 * \param ngMesh - netgen mesh
1506 * \param geom - container of OCCT geometry to mesh
1507 * \param wires - data of nodes on FACE boundary
1508 * \param helper - mesher helper holding the FACE
1509 * \param nodeVec - vector of nodes in which node index == netgen ID
1510 * \retval SMESH_ComputeErrorPtr - error description
1512 //================================================================================
1514 SMESH_ComputeErrorPtr
1515 NETGENPlugin_Mesher::AddSegmentsToMesh(netgen::Mesh& ngMesh,
1516 netgen::OCCGeometry& geom,
1517 const TSideVector& wires,
1518 SMESH_MesherHelper& helper,
1519 vector< const SMDS_MeshNode* > & nodeVec)
1521 // ----------------------------
1522 // Check wires and count nodes
1523 // ----------------------------
1525 for ( int iW = 0; iW < wires.size(); ++iW )
1527 StdMeshers_FaceSidePtr wire = wires[ iW ];
1528 if ( wire->MissVertexNode() )
1530 // Commented for issue 0020960. It worked for the case, let's wait for case where it doesn't.
1531 // It seems that there is no reason for this limitation
1533 // (new SMESH_ComputeError(COMPERR_BAD_INPUT_MESH, "Missing nodes on vertices"));
1535 const vector<UVPtStruct>& uvPtVec = wire->GetUVPtStruct();
1536 if ( uvPtVec.size() != wire->NbPoints() )
1537 return SMESH_ComputeError::New(COMPERR_BAD_INPUT_MESH,
1538 SMESH_Comment("Unexpected nb of points on wire ") << iW
1539 << ": " << uvPtVec.size()<<" != "<<wire->NbPoints());
1540 nbNodes += wire->NbPoints();
1542 nodeVec.reserve( nodeVec.size() + nbNodes + 1 );
1543 if ( nodeVec.empty() )
1544 nodeVec.push_back( 0 );
1546 // -----------------
1548 // -----------------
1550 const bool wasNgMeshEmpty = ( ngMesh.GetNP() < 1 ); /* true => this method is called by
1551 NETGENPlugin_NETGEN_2D_ONLY */
1553 // map for nodes on vertices since they can be shared between wires
1554 // ( issue 0020676, face_int_box.brep) and nodes built by NETGEN
1555 map<const SMDS_MeshNode*, int > node2ngID;
1556 if ( !wasNgMeshEmpty ) // fill node2ngID with nodes built by NETGEN
1558 set< int > subIDs; // ids of sub-shapes of the FACE
1559 for ( int iW = 0; iW < wires.size(); ++iW )
1561 StdMeshers_FaceSidePtr wire = wires[ iW ];
1562 for ( int iE = 0, nbE = wire->NbEdges(); iE < nbE; ++iE )
1564 subIDs.insert( wire->EdgeID( iE ));
1565 subIDs.insert( helper.GetMeshDS()->ShapeToIndex( wire->FirstVertex( iE )));
1568 for ( size_t ngID = 1; ngID < nodeVec.size(); ++ngID )
1569 if ( subIDs.count( nodeVec[ngID]->getshapeId() ))
1570 node2ngID.insert( make_pair( nodeVec[ngID], ngID ));
1573 const int solidID = 0, faceID = geom.fmap.FindIndex( helper.GetSubShape() );
1574 if ( ngMesh.GetNFD() < 1 )
1575 ngMesh.AddFaceDescriptor (netgen::FaceDescriptor(faceID, solidID, solidID, 0));
1577 for ( int iW = 0; iW < wires.size(); ++iW )
1579 StdMeshers_FaceSidePtr wire = wires[ iW ];
1580 const vector<UVPtStruct>& uvPtVec = wire->GetUVPtStruct();
1581 const int nbSegments = wire->NbPoints() - 1;
1583 // assure the 1st node to be in node2ngID, which is needed to correctly
1584 // "close chain of segments" (see below) in case if the 1st node is not
1585 // onVertex because it is on a Viscous layer
1586 node2ngID.insert( make_pair( uvPtVec[ 0 ].node, ngMesh.GetNP() + 1 ));
1588 // compute length of every segment
1589 vector<double> segLen( nbSegments );
1590 for ( int i = 0; i < nbSegments; ++i )
1591 segLen[i] = SMESH_TNodeXYZ( uvPtVec[ i ].node ).Distance( uvPtVec[ i+1 ].node );
1593 int edgeID = 1, posID = -2;
1594 bool isInternalWire = false;
1595 double vertexNormPar = 0;
1596 const int prevNbNGSeg = ngMesh.GetNSeg();
1597 for ( int i = 0; i < nbSegments; ++i ) // loop on segments
1599 // Add the first point of a segment
1601 const SMDS_MeshNode * n = uvPtVec[ i ].node;
1602 const int posShapeID = n->getshapeId();
1603 bool onVertex = ( n->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX );
1604 bool onEdge = ( n->GetPosition()->GetTypeOfPosition() == SMDS_TOP_EDGE );
1606 // skip nodes on degenerated edges
1607 if ( helper.IsDegenShape( posShapeID ) &&
1608 helper.IsDegenShape( uvPtVec[ i+1 ].node->getshapeId() ))
1611 int ngID1 = ngMesh.GetNP() + 1, ngID2 = ngID1+1;
1612 if ( onVertex || ( !wasNgMeshEmpty && onEdge ))
1613 ngID1 = node2ngID.insert( make_pair( n, ngID1 )).first->second;
1614 if ( ngID1 > ngMesh.GetNP() )
1616 netgen::MeshPoint mp( netgen::Point<3> (n->X(), n->Y(), n->Z()) );
1617 ngMesh.AddPoint ( mp, 1, netgen::EDGEPOINT );
1618 nodeVec.push_back( n );
1620 else // n is in ngMesh already, and ngID2 in prev segment is wrong
1622 ngID2 = ngMesh.GetNP() + 1;
1623 if ( i > 0 ) // prev segment belongs to same wire
1625 netgen::Segment& prevSeg = ngMesh.LineSegment( ngMesh.GetNSeg() );
1632 netgen::Segment seg;
1634 seg[0] = ngID1; // ng node id
1635 seg[1] = ngID2; // ng node id
1636 seg.edgenr = ngMesh.GetNSeg() + 1; // ng segment id
1637 seg.si = faceID; // = geom.fmap.FindIndex (face);
1639 for ( int iEnd = 0; iEnd < 2; ++iEnd)
1641 const UVPtStruct& pnt = uvPtVec[ i + iEnd ];
1643 seg.epgeominfo[ iEnd ].dist = pnt.param; // param on curve
1644 seg.epgeominfo[ iEnd ].u = pnt.u;
1645 seg.epgeominfo[ iEnd ].v = pnt.v;
1647 // find out edge id and node parameter on edge
1648 onVertex = ( pnt.normParam + 1e-10 > vertexNormPar );
1649 if ( onVertex || posShapeID != posID )
1652 double normParam = pnt.normParam;
1654 normParam = 0.5 * ( uvPtVec[ i ].normParam + uvPtVec[ i+1 ].normParam );
1655 int edgeIndexInWire = wire->EdgeIndex( normParam );
1656 vertexNormPar = wire->LastParameter( edgeIndexInWire );
1657 const TopoDS_Edge& edge = wire->Edge( edgeIndexInWire );
1658 edgeID = geom.emap.FindIndex( edge );
1660 isInternalWire = ( edge.Orientation() == TopAbs_INTERNAL );
1661 // if ( onVertex ) // param on curve is different on each of two edges
1662 // seg.epgeominfo[ iEnd ].dist = helper.GetNodeU( edge, pnt.node );
1664 seg.epgeominfo[ iEnd ].edgenr = edgeID; // = geom.emap.FindIndex(edge);
1667 ngMesh.AddSegment (seg);
1669 // restrict size of elements near the segment
1670 SMESH_TNodeXYZ np1( n ), np2( uvPtVec[ i+1 ].node );
1671 // get an average size of adjacent segments to avoid sharp change of
1672 // element size (regression on issue 0020452, note 0010898)
1673 int iPrev = SMESH_MesherHelper::WrapIndex( i-1, nbSegments );
1674 int iNext = SMESH_MesherHelper::WrapIndex( i+1, nbSegments );
1675 double sunH = segLen[ iPrev ] + segLen[ i ] + segLen[ iNext ];
1676 int nbSeg = ( int( segLen[ iPrev ] > sunH / 100.) +
1677 int( segLen[ i ] > sunH / 100.) +
1678 int( segLen[ iNext ] > sunH / 100.));
1680 RestrictLocalSize( ngMesh, 0.5*(np1+np2), sunH / nbSeg );
1682 if ( isInternalWire )
1684 swap (seg[0], seg[1]);
1685 swap( seg.epgeominfo[0], seg.epgeominfo[1] );
1686 seg.edgenr = ngMesh.GetNSeg() + 1; // segment id
1687 ngMesh.AddSegment (seg);
1689 } // loop on segments on a wire
1691 // close chain of segments
1692 if ( nbSegments > 0 )
1694 netgen::Segment& lastSeg = ngMesh.LineSegment( ngMesh.GetNSeg() - int( isInternalWire));
1695 const SMDS_MeshNode * lastNode = uvPtVec.back().node;
1696 lastSeg[1] = node2ngID.insert( make_pair( lastNode, lastSeg[1] )).first->second;
1697 if ( lastSeg[1] > ngMesh.GetNP() )
1699 netgen::MeshPoint mp( netgen::Point<3> (lastNode->X(), lastNode->Y(), lastNode->Z()) );
1700 ngMesh.AddPoint ( mp, 1, netgen::EDGEPOINT );
1701 nodeVec.push_back( lastNode );
1703 if ( isInternalWire )
1705 netgen::Segment& realLastSeg = ngMesh.LineSegment( ngMesh.GetNSeg() );
1706 realLastSeg[0] = lastSeg[1];
1710 #ifdef DUMP_SEGMENTS
1711 cout << "BEGIN WIRE " << iW << endl;
1712 for ( int i = prevNbNGSeg+1; i <= ngMesh.GetNSeg(); ++i )
1714 netgen::Segment& seg = ngMesh.LineSegment( i );
1716 netgen::Segment& prevSeg = ngMesh.LineSegment( i-1 );
1717 if ( seg[0] == prevSeg[1] && seg[1] == prevSeg[0] )
1719 cout << "Segment: " << seg.edgenr << endl << "\tis REVRESE of the previous one" << endl;
1723 cout << "Segment: " << seg.edgenr << endl
1724 << "\tp1: " << seg[0] << endl
1725 << "\tp2: " << seg[1] << endl
1726 << "\tp0 param: " << seg.epgeominfo[ 0 ].dist << endl
1727 << "\tp0 uv: " << seg.epgeominfo[ 0 ].u <<", "<< seg.epgeominfo[ 0 ].v << endl
1728 << "\tp0 edge: " << seg.epgeominfo[ 0 ].edgenr << endl
1729 << "\tp1 param: " << seg.epgeominfo[ 1 ].dist << endl
1730 << "\tp1 uv: " << seg.epgeominfo[ 1 ].u <<", "<< seg.epgeominfo[ 1 ].v << endl
1731 << "\tp1 edge: " << seg.epgeominfo[ 1 ].edgenr << endl;
1733 cout << "--END WIRE " << iW << endl;
1736 } // loop on WIREs of a FACE
1738 // add a segment instead of an internal vertex
1739 if ( wasNgMeshEmpty )
1741 NETGENPlugin_Internals intShapes( *helper.GetMesh(), helper.GetSubShape(), /*is3D=*/false );
1742 AddIntVerticesInFaces( geom, ngMesh, nodeVec, intShapes );
1744 ngMesh.CalcSurfacesOfNode();
1749 //================================================================================
1751 * \brief Fill SMESH mesh according to contents of netgen mesh
1752 * \param occgeo - container of OCCT geometry to mesh
1753 * \param ngMesh - netgen mesh
1754 * \param initState - bn of entities in netgen mesh before computing
1755 * \param sMesh - SMESH mesh to fill in
1756 * \param nodeVec - vector of nodes in which node index == netgen ID
1757 * \retval int - error
1759 //================================================================================
1761 int NETGENPlugin_Mesher::FillSMesh(const netgen::OCCGeometry& occgeo,
1762 netgen::Mesh& ngMesh,
1763 const NETGENPlugin_ngMeshInfo& initState,
1765 std::vector<const SMDS_MeshNode*>& nodeVec,
1766 SMESH_Comment& comment)
1768 int nbNod = ngMesh.GetNP();
1769 int nbSeg = ngMesh.GetNSeg();
1770 int nbFac = ngMesh.GetNSE();
1771 int nbVol = ngMesh.GetNE();
1773 SMESHDS_Mesh* meshDS = sMesh.GetMeshDS();
1775 // -------------------------------------
1776 // Create and insert nodes into nodeVec
1777 // -------------------------------------
1779 nodeVec.resize( nbNod + 1 );
1780 int i, nbInitNod = initState._nbNodes;
1781 for (i = nbInitNod+1; i <= nbNod; ++i )
1783 const netgen::MeshPoint& ngPoint = ngMesh.Point(i);
1784 SMDS_MeshNode* node = NULL;
1785 TopoDS_Vertex aVert;
1786 // First, netgen creates nodes on vertices in occgeo.vmap,
1787 // so node index corresponds to vertex index
1788 // but (issue 0020776) netgen does not create nodes with equal coordinates
1789 if ( i-nbInitNod <= occgeo.vmap.Extent() )
1791 gp_Pnt p ( NGPOINT_COORDS(ngPoint) );
1792 for (int iV = i-nbInitNod; aVert.IsNull() && iV <= occgeo.vmap.Extent(); ++iV)
1794 aVert = TopoDS::Vertex( occgeo.vmap( iV ) );
1795 gp_Pnt pV = BRep_Tool::Pnt( aVert );
1796 if ( p.SquareDistance( pV ) > 1e-20 )
1799 node = const_cast<SMDS_MeshNode*>( SMESH_Algo::VertexNode( aVert, meshDS ));
1802 if (!node) // node not found on vertex
1804 node = meshDS->AddNode( NGPOINT_COORDS( ngPoint ));
1805 if (!aVert.IsNull())
1806 meshDS->SetNodeOnVertex(node, aVert);
1811 // -------------------------------------------
1812 // Create mesh segments along geometric edges
1813 // -------------------------------------------
1815 int nbInitSeg = initState._nbSegments;
1816 for (i = nbInitSeg+1; i <= nbSeg; ++i )
1818 const netgen::Segment& seg = ngMesh.LineSegment(i);
1820 int pinds[3] = { seg.pnums[0], seg.pnums[1], seg.pnums[2] };
1823 for (int j=0; j < 3; ++j)
1825 int pind = pinds[j];
1826 if (pind <= 0 || !nodeVec_ACCESS(pind))
1834 int aGeomEdgeInd = seg.epgeominfo[j].edgenr;
1835 if (aGeomEdgeInd > 0 && aGeomEdgeInd <= occgeo.emap.Extent())
1836 aEdge = TopoDS::Edge(occgeo.emap(aGeomEdgeInd));
1838 param = seg.epgeominfo[j].dist;
1841 else // middle point
1843 param = param2 * 0.5;
1845 if (!aEdge.IsNull() && nodeVec_ACCESS(pind)->getshapeId() < 1)
1847 meshDS->SetNodeOnEdge(nodeVec_ACCESS(pind), aEdge, param);
1852 SMDS_MeshEdge* edge = 0;
1853 if (nbp == 2) // second order ?
1855 if ( meshDS->FindEdge( nodeVec_ACCESS(pinds[0]), nodeVec_ACCESS(pinds[1])))
1857 edge = meshDS->AddEdge(nodeVec_ACCESS(pinds[0]), nodeVec_ACCESS(pinds[1]));
1861 if ( meshDS->FindEdge( nodeVec_ACCESS(pinds[0]), nodeVec_ACCESS(pinds[1]),
1862 nodeVec_ACCESS(pinds[2])))
1864 edge = meshDS->AddEdge(nodeVec_ACCESS(pinds[0]), nodeVec_ACCESS(pinds[1]),
1865 nodeVec_ACCESS(pinds[2]));
1869 if ( comment.empty() ) comment << "Cannot create a mesh edge";
1870 MESSAGE("Cannot create a mesh edge");
1871 nbSeg = nbFac = nbVol = 0;
1874 if ( !aEdge.IsNull() && edge->getshapeId() < 1 )
1875 meshDS->SetMeshElementOnShape(edge, aEdge);
1877 else if ( comment.empty() )
1879 comment << "Invalid netgen segment #" << i;
1883 // ----------------------------------------
1884 // Create mesh faces along geometric faces
1885 // ----------------------------------------
1887 int nbInitFac = initState._nbFaces;
1888 int quadFaceID = ngMesh.GetNFD() + 1;
1889 if ( nbInitFac < nbFac )
1890 // add a faces descriptor to exclude qudrangle elements generated by NETGEN
1891 // from computation of 3D mesh
1892 ngMesh.AddFaceDescriptor (netgen::FaceDescriptor(quadFaceID, /*solid1=*/0, /*solid2=*/0, 0));
1894 for (i = nbInitFac+1; i <= nbFac; ++i )
1896 const netgen::Element2d& elem = ngMesh.SurfaceElement(i);
1897 int aGeomFaceInd = elem.GetIndex();
1899 if (aGeomFaceInd > 0 && aGeomFaceInd <= occgeo.fmap.Extent())
1900 aFace = TopoDS::Face(occgeo.fmap(aGeomFaceInd));
1901 vector<SMDS_MeshNode*> nodes;
1902 for (int j=1; j <= elem.GetNP(); ++j)
1904 int pind = elem.PNum(j);
1905 if ( pind < 1 || pind >= nodeVec.size() )
1907 if ( SMDS_MeshNode* node = nodeVec_ACCESS(pind))
1909 nodes.push_back(node);
1910 if (!aFace.IsNull() && node->getshapeId() < 1)
1912 const netgen::PointGeomInfo& pgi = elem.GeomInfoPi(j);
1913 meshDS->SetNodeOnFace(node, aFace, pgi.u, pgi.v);
1917 if ( nodes.size() != elem.GetNP() )
1919 if ( comment.empty() )
1920 comment << "Invalid netgen 2d element #" << i;
1921 continue; // bad node ids
1923 SMDS_MeshFace* face = NULL;
1924 switch (elem.GetType())
1927 face = meshDS->AddFace(nodes[0],nodes[1],nodes[2]);
1930 face = meshDS->AddFace(nodes[0],nodes[1],nodes[2],nodes[3]);
1931 // exclude qudrangle elements from computation of 3D mesh
1932 const_cast< netgen::Element2d& >( elem ).SetIndex( quadFaceID );
1935 face = meshDS->AddFace(nodes[0],nodes[1],nodes[2],nodes[5],nodes[3],nodes[4]);
1938 face = meshDS->AddFace(nodes[0],nodes[1],nodes[2],nodes[3],
1939 nodes[4],nodes[7],nodes[5],nodes[6]);
1940 // exclude qudrangle elements from computation of 3D mesh
1941 const_cast< netgen::Element2d& >( elem ).SetIndex( quadFaceID );
1944 MESSAGE("NETGEN created a face of unexpected type, ignoring");
1949 if ( comment.empty() ) comment << "Cannot create a mesh face";
1950 MESSAGE("Cannot create a mesh face");
1951 nbSeg = nbFac = nbVol = 0;
1954 if (!aFace.IsNull())
1955 meshDS->SetMeshElementOnShape(face, aFace);
1958 // ------------------
1959 // Create tetrahedra
1960 // ------------------
1962 for (i = 1; i <= nbVol; ++i)
1964 const netgen::Element& elem = ngMesh.VolumeElement(i);
1965 int aSolidInd = elem.GetIndex();
1966 TopoDS_Solid aSolid;
1967 if (aSolidInd > 0 && aSolidInd <= occgeo.somap.Extent())
1968 aSolid = TopoDS::Solid(occgeo.somap(aSolidInd));
1969 vector<SMDS_MeshNode*> nodes;
1970 for (int j=1; j <= elem.GetNP(); ++j)
1972 int pind = elem.PNum(j);
1973 if ( pind < 1 || pind >= nodeVec.size() )
1975 if ( SMDS_MeshNode* node = nodeVec_ACCESS(pind) )
1977 nodes.push_back(node);
1978 if ( !aSolid.IsNull() && node->getshapeId() < 1 )
1979 meshDS->SetNodeInVolume(node, aSolid);
1982 if ( nodes.size() != elem.GetNP() )
1984 if ( comment.empty() )
1985 comment << "Invalid netgen 3d element #" << i;
1988 SMDS_MeshVolume* vol = NULL;
1989 switch (elem.GetType())
1992 vol = meshDS->AddVolume(nodes[0],nodes[1],nodes[2],nodes[3]);
1995 vol = meshDS->AddVolume(nodes[0],nodes[1],nodes[2],nodes[3],
1996 nodes[4],nodes[7],nodes[5],nodes[6],nodes[8],nodes[9]);
1999 MESSAGE("NETGEN created a volume of unexpected type, ignoring");
2004 if ( comment.empty() ) comment << "Cannot create a mesh volume";
2005 MESSAGE("Cannot create a mesh volume");
2006 nbSeg = nbFac = nbVol = 0;
2009 if (!aSolid.IsNull())
2010 meshDS->SetMeshElementOnShape(vol, aSolid);
2012 return comment.empty() ? 0 : 1;
2017 //================================================================================
2019 * \brief Restrict size of elements on the given edge
2021 //================================================================================
2023 void setLocalSize(const TopoDS_Edge& edge,
2027 const int nb = 1000;
2028 Standard_Real u1, u2;
2029 Handle(Geom_Curve) curve = BRep_Tool::Curve(edge, u1, u2);
2030 if ( curve.IsNull() )
2032 TopoDS_Iterator vIt( edge );
2033 if ( !vIt.More() ) return;
2034 gp_Pnt p = BRep_Tool::Pnt( TopoDS::Vertex( vIt.Value() ));
2035 NETGENPlugin_Mesher::RestrictLocalSize( mesh, p.XYZ(), size );
2039 Standard_Real delta = (u2-u1)/nb;
2040 for(int i=0; i<nb; i++)
2042 Standard_Real u = u1 + delta*i;
2043 gp_Pnt p = curve->Value(u);
2044 NETGENPlugin_Mesher::RestrictLocalSize( mesh, p.XYZ(), size );
2045 netgen::Point3d pi(p.X(), p.Y(), p.Z());
2046 double resultSize = mesh.GetH(pi);
2047 if ( resultSize - size > 0.1*size )
2048 // netgen does restriction iff oldH/newH > 1.2 (localh.cpp:136)
2049 NETGENPlugin_Mesher::RestrictLocalSize( mesh, p.XYZ(), resultSize/1.201 );
2054 //================================================================================
2056 * \brief Convert error into text
2058 //================================================================================
2060 std::string text(int err)
2065 SMESH_Comment("Error in netgen::OCCGenerateMesh() at ") << netgen::multithread.task;
2068 //================================================================================
2070 * \brief Convert exception into text
2072 //================================================================================
2074 std::string text(Standard_Failure& ex)
2076 SMESH_Comment str("Exception in netgen::OCCGenerateMesh()");
2077 str << " at " << netgen::multithread.task
2078 << ": " << ex.DynamicType()->Name();
2079 if ( ex.GetMessageString() && strlen( ex.GetMessageString() ))
2080 str << ": " << ex.GetMessageString();
2083 //================================================================================
2085 * \brief Convert exception into text
2087 //================================================================================
2089 std::string text(netgen::NgException& ex)
2091 SMESH_Comment str("NgException");
2092 if ( strlen( netgen::multithread.task ) > 0 )
2093 str << " at " << netgen::multithread.task;
2094 str << ": " << ex.What();
2098 const double edgeMeshingTime = 0.001;
2099 const double faceMeshingTime = 0.019;
2100 const double edgeFaceMeshingTime = edgeMeshingTime + faceMeshingTime;
2101 const double faceOptimizTime = 0.06;
2102 const double voluMeshingTime = 0.15;
2103 const double volOptimizeTime = 0.77;
2106 //=============================================================================
2108 * Here we are going to use the NETGEN mesher
2110 //=============================================================================
2112 bool NETGENPlugin_Mesher::Compute()
2114 NETGENPlugin_NetgenLibWrapper ngLib;
2116 netgen::MeshingParameters& mparams = netgen::mparam;
2117 MESSAGE("Compute with:\n"
2118 " max size = " << mparams.maxh << "\n"
2119 " segments per edge = " << mparams.segmentsperedge);
2121 " growth rate = " << mparams.grading << "\n"
2122 " elements per radius = " << mparams.curvaturesafety << "\n"
2123 " second order = " << mparams.secondorder << "\n"
2124 " quad allowed = " << mparams.quad << "\n"
2125 " surface curvature = " << mparams.uselocalh << "\n"
2126 " fuse edges = " << netgen::merge_solids);
2128 SMESH_ComputeErrorPtr error = SMESH_ComputeError::New();
2130 static string debugFile = "/tmp/ngMesh.py"; /* to call toPython( ngMesh, debugFile )
2131 while debugging netgen */
2132 // -------------------------
2133 // Prepare OCC geometry
2134 // -------------------------
2136 netgen::OCCGeometry occgeo;
2137 list< SMESH_subMesh* > meshedSM[3]; // for 0-2 dimensions
2138 NETGENPlugin_Internals internals( *_mesh, _shape, _isVolume );
2139 PrepareOCCgeometry( occgeo, _shape, *_mesh, meshedSM, &internals );
2142 _totalTime = edgeFaceMeshingTime;
2144 _totalTime += faceOptimizTime;
2146 _totalTime += voluMeshingTime + ( _optimize ? volOptimizeTime : 0 );
2147 double doneTime = 0;
2150 _curShapeIndex = -1;
2152 // -------------------------
2153 // Generate the mesh
2154 // -------------------------
2157 NETGENPlugin_ngMeshInfo initState; // it remembers size of ng mesh equal to size of Smesh
2159 SMESH_Comment comment;
2162 // vector of nodes in which node index == netgen ID
2163 vector< const SMDS_MeshNode* > nodeVec;
2171 // not to RestrictLocalH() according to curvature during MESHCONST_ANALYSE
2172 mparams.uselocalh = false;
2173 mparams.grading = 0.8; // not limitited size growth
2175 if ( _simpleHyp->GetNumberOfSegments() )
2177 mparams.maxh = occgeo.boundingbox.Diam();
2180 mparams.maxh = _simpleHyp->GetLocalLength();
2183 if ( mparams.maxh == 0.0 )
2184 mparams.maxh = occgeo.boundingbox.Diam();
2185 if ( _simpleHyp || ( mparams.minh == 0.0 && _fineness != NETGENPlugin_Hypothesis::UserDefined))
2186 mparams.minh = GetDefaultMinSize( _shape, mparams.maxh );
2188 // Local size on faces
2189 occgeo.face_maxh = mparams.maxh;
2191 // Let netgen create _ngMesh and calculate element size on not meshed shapes
2195 int startWith = netgen::MESHCONST_ANALYSE;
2196 int endWith = netgen::MESHCONST_ANALYSE;
2201 err = netgen::OCCGenerateMesh(occgeo, _ngMesh, mparams, startWith, endWith);
2203 err = netgen::OCCGenerateMesh(occgeo, _ngMesh, startWith, endWith, optstr);
2205 if(netgen::multithread.terminate)
2208 comment << text(err);
2210 catch (Standard_Failure& ex)
2212 comment << text(ex);
2214 err = 0; //- MESHCONST_ANALYSE isn't so important step
2217 ngLib.setMesh(( Ng_Mesh*) _ngMesh );
2219 _ngMesh->ClearFaceDescriptors(); // we make descriptors our-self
2223 // Pass 1D simple parameters to NETGEN
2224 // --------------------------------
2225 int nbSeg = _simpleHyp->GetNumberOfSegments();
2226 double segSize = _simpleHyp->GetLocalLength();
2227 for ( int iE = 1; iE <= occgeo.emap.Extent(); ++iE )
2229 const TopoDS_Edge& e = TopoDS::Edge( occgeo.emap(iE));
2231 segSize = SMESH_Algo::EdgeLength( e ) / ( nbSeg - 0.4 );
2232 setLocalSize( e, segSize, *_ngMesh );
2235 else // if ( ! _simpleHyp )
2237 // Local size on vertices and edges
2238 // --------------------------------
2239 for(std::map<int,double>::const_iterator it=EdgeId2LocalSize.begin(); it!=EdgeId2LocalSize.end(); it++)
2241 int key = (*it).first;
2242 double hi = (*it).second;
2243 const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
2244 const TopoDS_Edge& e = TopoDS::Edge(shape);
2245 setLocalSize( e, hi, *_ngMesh );
2247 for(std::map<int,double>::const_iterator it=VertexId2LocalSize.begin(); it!=VertexId2LocalSize.end(); it++)
2249 int key = (*it).first;
2250 double hi = (*it).second;
2251 const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
2252 const TopoDS_Vertex& v = TopoDS::Vertex(shape);
2253 gp_Pnt p = BRep_Tool::Pnt(v);
2254 NETGENPlugin_Mesher::RestrictLocalSize( *_ngMesh, p.XYZ(), hi );
2256 for(map<int,double>::const_iterator it=FaceId2LocalSize.begin();
2257 it!=FaceId2LocalSize.end(); it++)
2259 int key = (*it).first;
2260 double val = (*it).second;
2261 const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
2262 int faceNgID = occgeo.fmap.FindIndex(shape);
2263 occgeo.SetFaceMaxH(faceNgID, val);
2264 for ( TopExp_Explorer edgeExp( shape, TopAbs_EDGE ); edgeExp.More(); edgeExp.Next() )
2265 setLocalSize( TopoDS::Edge( edgeExp.Current() ), val, *_ngMesh );
2269 // Precompute internal edges (issue 0020676) in order to
2270 // add mesh on them correctly (twice) to netgen mesh
2271 if ( !err && internals.hasInternalEdges() )
2273 // load internal shapes into OCCGeometry
2274 netgen::OCCGeometry intOccgeo;
2275 internals.getInternalEdges( intOccgeo.fmap, intOccgeo.emap, intOccgeo.vmap, meshedSM );
2276 intOccgeo.boundingbox = occgeo.boundingbox;
2277 intOccgeo.shape = occgeo.shape;
2278 intOccgeo.face_maxh.SetSize(intOccgeo.fmap.Extent());
2279 intOccgeo.face_maxh = netgen::mparam.maxh;
2280 netgen::Mesh *tmpNgMesh = NULL;
2284 // compute local H on internal shapes in the main mesh
2285 //OCCSetLocalMeshSize(intOccgeo, *_ngMesh); it deletes _ngMesh->localH
2287 // let netgen create a temporary mesh
2289 netgen::OCCGenerateMesh(intOccgeo, tmpNgMesh, mparams, startWith, endWith);
2291 netgen::OCCGenerateMesh(intOccgeo, tmpNgMesh, startWith, endWith, optstr);
2293 if(netgen::multithread.terminate)
2296 // copy LocalH from the main to temporary mesh
2297 initState.transferLocalH( _ngMesh, tmpNgMesh );
2299 // compute mesh on internal edges
2300 startWith = endWith = netgen::MESHCONST_MESHEDGES;
2302 err = netgen::OCCGenerateMesh(intOccgeo, tmpNgMesh, mparams, startWith, endWith);
2304 err = netgen::OCCGenerateMesh(intOccgeo, tmpNgMesh, startWith, endWith, optstr);
2306 comment << text(err);
2308 catch (Standard_Failure& ex)
2310 comment << text(ex);
2313 initState.restoreLocalH( tmpNgMesh );
2315 // fill SMESH by netgen mesh
2316 vector< const SMDS_MeshNode* > tmpNodeVec;
2317 FillSMesh( intOccgeo, *tmpNgMesh, initState, *_mesh, tmpNodeVec, comment );
2318 err = ( err || !comment.empty() );
2320 nglib::Ng_DeleteMesh((nglib::Ng_Mesh*)tmpNgMesh);
2323 // Fill _ngMesh with nodes and segments of computed submeshes
2326 err = ! ( FillNgMesh(occgeo, *_ngMesh, nodeVec, meshedSM[ MeshDim_0D ]) &&
2327 FillNgMesh(occgeo, *_ngMesh, nodeVec, meshedSM[ MeshDim_1D ]));
2329 initState = NETGENPlugin_ngMeshInfo(_ngMesh);
2334 startWith = endWith = netgen::MESHCONST_MESHEDGES;
2339 err = netgen::OCCGenerateMesh(occgeo, _ngMesh, mparams, startWith, endWith);
2341 err = netgen::OCCGenerateMesh(occgeo, _ngMesh, startWith, endWith, optstr);
2343 if(netgen::multithread.terminate)
2346 comment << text(err);
2348 catch (Standard_Failure& ex)
2350 comment << text(ex);
2355 _ticTime = ( doneTime += edgeMeshingTime ) / _totalTime / _progressTic;
2357 mparams.uselocalh = true; // restore as it is used at surface optimization
2359 // ---------------------
2360 // compute surface mesh
2361 // ---------------------
2364 // Pass 2D simple parameters to NETGEN
2366 if ( double area = _simpleHyp->GetMaxElementArea() ) {
2368 mparams.maxh = sqrt(2. * area/sqrt(3.0));
2369 mparams.grading = 0.4; // moderate size growth
2372 // length from edges
2373 if ( _ngMesh->GetNSeg() ) {
2374 double edgeLength = 0;
2375 TopTools_MapOfShape visitedEdges;
2376 for ( TopExp_Explorer exp( _shape, TopAbs_EDGE ); exp.More(); exp.Next() )
2377 if( visitedEdges.Add(exp.Current()) )
2378 edgeLength += SMESH_Algo::EdgeLength( TopoDS::Edge( exp.Current() ));
2379 // we have to multiply length by 2 since for each TopoDS_Edge there
2380 // are double set of NETGEN edges, in other words, we have to
2381 // divide _ngMesh->GetNSeg() by 2.
2382 mparams.maxh = 2*edgeLength / _ngMesh->GetNSeg();
2385 mparams.maxh = 1000;
2387 mparams.grading = 0.2; // slow size growth
2389 mparams.quad = _simpleHyp->GetAllowQuadrangles();
2390 mparams.maxh = min( mparams.maxh, occgeo.boundingbox.Diam()/2 );
2391 _ngMesh->SetGlobalH (mparams.maxh);
2392 netgen::Box<3> bb = occgeo.GetBoundingBox();
2393 bb.Increase (bb.Diam()/20);
2394 _ngMesh->SetLocalH (bb.PMin(), bb.PMax(), mparams.grading);
2397 // Care of vertices internal in faces (issue 0020676)
2398 if ( internals.hasInternalVertexInFace() )
2400 // store computed segments in SMESH in order not to create SMESH
2401 // edges for ng segments added by AddIntVerticesInFaces()
2402 FillSMesh( occgeo, *_ngMesh, initState, *_mesh, nodeVec, comment );
2403 // add segments to faces with internal vertices
2404 AddIntVerticesInFaces( occgeo, *_ngMesh, nodeVec, internals );
2405 initState = NETGENPlugin_ngMeshInfo(_ngMesh);
2408 // Build viscous layers
2409 if ( _isViscousLayers2D )
2411 if ( !internals.hasInternalVertexInFace() ) {
2412 FillSMesh( occgeo, *_ngMesh, initState, *_mesh, nodeVec, comment );
2413 initState = NETGENPlugin_ngMeshInfo(_ngMesh);
2415 SMESH_ProxyMesh::Ptr viscousMesh;
2416 SMESH_MesherHelper helper( *_mesh );
2417 for ( int faceID = 1; faceID <= occgeo.fmap.Extent(); ++faceID )
2419 const TopoDS_Face& F = TopoDS::Face( occgeo.fmap( faceID ));
2420 viscousMesh = StdMeshers_ViscousLayers2D::Compute( *_mesh, F );
2423 // exclude from computation ng segments built on EDGEs of F
2424 for (int i = 1; i <= _ngMesh->GetNSeg(); i++)
2426 netgen::Segment & seg = _ngMesh->LineSegment(i);
2427 if (seg.si == faceID)
2430 // add new segments to _ngMesh instead of excluded ones
2431 helper.SetSubShape( F );
2433 StdMeshers_FaceSide::GetFaceWires( F, *_mesh, /*skipMediumNodes=*/true,
2434 error, viscousMesh );
2435 error = AddSegmentsToMesh( *_ngMesh, occgeo, wires, helper, nodeVec );
2437 if ( !error ) error = SMESH_ComputeError::New();
2439 initState = NETGENPlugin_ngMeshInfo(_ngMesh);
2442 // Let netgen compute 2D mesh
2443 startWith = netgen::MESHCONST_MESHSURFACE;
2444 endWith = _optimize ? netgen::MESHCONST_OPTSURFACE : netgen::MESHCONST_MESHSURFACE;
2449 err = netgen::OCCGenerateMesh(occgeo, _ngMesh, mparams, startWith, endWith);
2451 err = netgen::OCCGenerateMesh(occgeo, _ngMesh, startWith, endWith, optstr);
2453 if(netgen::multithread.terminate)
2456 comment << text (err);
2458 catch (Standard_Failure& ex)
2460 comment << text(ex);
2461 //err = 1; -- try to make volumes anyway
2463 catch (netgen::NgException exc)
2465 comment << text(exc);
2466 //err = 1; -- try to make volumes anyway
2471 doneTime += faceMeshingTime + ( _optimize ? faceOptimizTime : 0 );
2472 _ticTime = doneTime / _totalTime / _progressTic;
2474 // ---------------------
2475 // generate volume mesh
2476 // ---------------------
2477 // Fill _ngMesh with nodes and faces of computed 2D submeshes
2478 if ( !err && _isVolume && ( !meshedSM[ MeshDim_2D ].empty() || mparams.quad ))
2480 // load SMESH with computed segments and faces
2481 FillSMesh( occgeo, *_ngMesh, initState, *_mesh, nodeVec, comment );
2483 // compute pyramids on quadrangles
2484 SMESH_ProxyMesh::Ptr proxyMesh;
2485 if ( _mesh->NbQuadrangles() > 0 )
2486 for ( int iS = 1; iS <= occgeo.somap.Extent(); ++iS )
2488 StdMeshers_QuadToTriaAdaptor* Adaptor = new StdMeshers_QuadToTriaAdaptor;
2489 proxyMesh.reset( Adaptor );
2491 int nbPyrams = _mesh->NbPyramids();
2492 Adaptor->Compute( *_mesh, occgeo.somap(iS) );
2493 if ( nbPyrams != _mesh->NbPyramids() )
2495 list< SMESH_subMesh* > quadFaceSM;
2496 for (TopExp_Explorer face(occgeo.somap(iS), TopAbs_FACE); face.More(); face.Next())
2497 if ( Adaptor->GetProxySubMesh( face.Current() ))
2499 quadFaceSM.push_back( _mesh->GetSubMesh( face.Current() ));
2500 meshedSM[ MeshDim_2D ].remove( quadFaceSM.back() );
2502 FillNgMesh(occgeo, *_ngMesh, nodeVec, quadFaceSM, proxyMesh);
2505 // fill _ngMesh with faces of sub-meshes
2506 err = ! ( FillNgMesh(occgeo, *_ngMesh, nodeVec, meshedSM[ MeshDim_2D ]));
2507 initState = NETGENPlugin_ngMeshInfo(_ngMesh);
2508 //toPython( _ngMesh, "/tmp/ngPython.py");
2510 if (!err && _isVolume)
2512 // Pass 3D simple parameters to NETGEN
2513 const NETGENPlugin_SimpleHypothesis_3D* simple3d =
2514 dynamic_cast< const NETGENPlugin_SimpleHypothesis_3D* > ( _simpleHyp );
2516 if ( double vol = simple3d->GetMaxElementVolume() ) {
2518 mparams.maxh = pow( 72, 1/6. ) * pow( vol, 1/3. );
2519 mparams.maxh = min( mparams.maxh, occgeo.boundingbox.Diam()/2 );
2522 // length from faces
2523 mparams.maxh = _ngMesh->AverageH();
2525 _ngMesh->SetGlobalH (mparams.maxh);
2526 mparams.grading = 0.4;
2528 _ngMesh->CalcLocalH(mparams.grading);
2530 _ngMesh->CalcLocalH();
2533 // Care of vertices internal in solids and internal faces (issue 0020676)
2534 if ( internals.hasInternalVertexInSolid() || internals.hasInternalFaces() )
2536 // store computed faces in SMESH in order not to create SMESH
2537 // faces for ng faces added here
2538 FillSMesh( occgeo, *_ngMesh, initState, *_mesh, nodeVec, comment );
2539 // add ng faces to solids with internal vertices
2540 AddIntVerticesInSolids( occgeo, *_ngMesh, nodeVec, internals );
2541 // duplicate mesh faces on internal faces
2542 FixIntFaces( occgeo, *_ngMesh, internals );
2543 initState = NETGENPlugin_ngMeshInfo(_ngMesh);
2545 // Let netgen compute 3D mesh
2546 startWith = endWith = netgen::MESHCONST_MESHVOLUME;
2551 err = netgen::OCCGenerateMesh(occgeo, _ngMesh, mparams, startWith, endWith);
2553 err = netgen::OCCGenerateMesh(occgeo, _ngMesh, startWith, endWith, optstr);
2555 if(netgen::multithread.terminate)
2558 if ( comment.empty() ) // do not overwrite a previos error
2559 comment << text(err);
2561 catch (Standard_Failure& ex)
2563 if ( comment.empty() ) // do not overwrite a previos error
2564 comment << text(ex);
2567 catch (netgen::NgException exc)
2569 if ( comment.empty() ) // do not overwrite a previos error
2570 comment << text(exc);
2573 _ticTime = ( doneTime += voluMeshingTime ) / _totalTime / _progressTic;
2575 // Let netgen optimize 3D mesh
2576 if ( !err && _optimize )
2578 startWith = endWith = netgen::MESHCONST_OPTVOLUME;
2583 err = netgen::OCCGenerateMesh(occgeo, _ngMesh, mparams, startWith, endWith);
2585 err = netgen::OCCGenerateMesh(occgeo, _ngMesh, startWith, endWith, optstr);
2587 if(netgen::multithread.terminate)
2590 if ( comment.empty() ) // do not overwrite a previos error
2591 comment << text(err);
2593 catch (Standard_Failure& ex)
2595 if ( comment.empty() ) // do not overwrite a previos error
2596 comment << text(ex);
2598 catch (netgen::NgException exc)
2600 if ( comment.empty() ) // do not overwrite a previos error
2601 comment << text(exc);
2605 if (!err && mparams.secondorder > 0)
2610 netgen::OCCRefinementSurfaces ref (occgeo);
2611 ref.MakeSecondOrder (*_ngMesh);
2613 catch (Standard_Failure& ex)
2615 if ( comment.empty() ) // do not overwrite a previos error
2616 comment << "Exception in netgen at passing to 2nd order ";
2618 catch (netgen::NgException exc)
2620 if ( comment.empty() ) // do not overwrite a previos error
2621 comment << exc.What();
2626 _ticTime = 0.98 / _progressTic;
2628 int nbNod = _ngMesh->GetNP();
2629 int nbSeg = _ngMesh->GetNSeg();
2630 int nbFac = _ngMesh->GetNSE();
2631 int nbVol = _ngMesh->GetNE();
2632 bool isOK = ( !err && (_isVolume ? (nbVol > 0) : (nbFac > 0)) );
2634 MESSAGE((err ? "Mesh Generation failure" : "End of Mesh Generation") <<
2635 ", nb nodes: " << nbNod <<
2636 ", nb segments: " << nbSeg <<
2637 ", nb faces: " << nbFac <<
2638 ", nb volumes: " << nbVol);
2640 // Feed back the SMESHDS with the generated Nodes and Elements
2641 if ( true /*isOK*/ ) // get whatever built
2642 FillSMesh( occgeo, *_ngMesh, initState, *_mesh, nodeVec, comment ); //!<
2644 SMESH_ComputeErrorPtr readErr = ReadErrors(nodeVec);
2645 if ( readErr && !readErr->myBadElements.empty() )
2648 if ( error->IsOK() && ( !isOK || comment.size() > 0 ))
2649 error->myName = COMPERR_ALGO_FAILED;
2650 if ( !comment.empty() )
2651 error->myComment = comment;
2653 // SetIsAlwaysComputed( true ) to empty sub-meshes, which
2654 // appear if the geometry contains coincident sub-shape due
2655 // to bool merge_solids = 1; in netgen/libsrc/occ/occgenmesh.cpp
2656 const int nbMaps = 2;
2657 const TopTools_IndexedMapOfShape* geoMaps[nbMaps] =
2658 { & occgeo.vmap, & occgeo.emap/*, & occgeo.fmap*/ };
2659 for ( int iMap = 0; iMap < nbMaps; ++iMap )
2660 for (int i = 1; i <= geoMaps[iMap]->Extent(); i++)
2661 if ( SMESH_subMesh* sm = _mesh->GetSubMeshContaining( geoMaps[iMap]->FindKey(i)))
2662 if ( !sm->IsMeshComputed() )
2663 sm->SetIsAlwaysComputed( true );
2665 // set bad compute error to subshapes of all failed sub-shapes
2666 if ( !error->IsOK() )
2668 bool pb2D = false, pb3D = false;
2669 for (int i = 1; i <= occgeo.fmap.Extent(); i++) {
2670 int status = occgeo.facemeshstatus[i-1];
2671 if (status == 1 ) continue;
2672 if ( SMESH_subMesh* sm = _mesh->GetSubMeshContaining( occgeo.fmap( i ))) {
2673 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
2674 if ( !smError || smError->IsOK() ) {
2676 smError.reset( new SMESH_ComputeError( *error ));
2678 smError.reset( new SMESH_ComputeError( COMPERR_ALGO_FAILED, "Ignored" ));
2679 if ( SMESH_Algo::GetMeshError( sm ) == SMESH_Algo::MEr_OK )
2680 smError->myName = COMPERR_WARNING;
2682 pb2D = pb2D || smError->IsKO();
2685 if ( !pb2D ) // all faces are OK
2686 for (int i = 1; i <= occgeo.somap.Extent(); i++)
2687 if ( SMESH_subMesh* sm = _mesh->GetSubMeshContaining( occgeo.somap( i )))
2689 bool smComputed = nbVol && !sm->IsEmpty();
2690 if ( smComputed && internals.hasInternalVertexInSolid( sm->GetId() ))
2692 int nbIntV = internals.getSolidsWithVertices().find( sm->GetId() )->second.size();
2693 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
2694 smComputed = ( smDS->NbElements() > 0 || smDS->NbNodes() > nbIntV );
2696 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
2697 if ( !smComputed && ( !smError || smError->IsOK() ))
2699 smError.reset( new SMESH_ComputeError( *error ));
2700 if ( nbVol && SMESH_Algo::GetMeshError( sm ) == SMESH_Algo::MEr_OK )
2701 smError->myName = COMPERR_WARNING;
2703 pb3D = pb3D || ( smError && smError->IsKO() );
2705 if ( !pb2D && !pb3D )
2706 err = 0; // no fatal errors, only warnings
2709 ngLib._isComputeOk = !err;
2714 //=============================================================================
2718 //=============================================================================
2719 bool NETGENPlugin_Mesher::Evaluate(MapShapeNbElems& aResMap)
2721 netgen::MeshingParameters& mparams = netgen::mparam;
2724 // -------------------------
2725 // Prepare OCC geometry
2726 // -------------------------
2727 netgen::OCCGeometry occgeo;
2728 list< SMESH_subMesh* > meshedSM[4]; // for 0-3 dimensions
2729 NETGENPlugin_Internals internals( *_mesh, _shape, _isVolume );
2730 PrepareOCCgeometry( occgeo, _shape, *_mesh, meshedSM, &internals );
2732 bool tooManyElems = false;
2733 const int hugeNb = std::numeric_limits<int>::max() / 100;
2738 // pass 1D simple parameters to NETGEN
2741 // not to RestrictLocalH() according to curvature during MESHCONST_ANALYSE
2742 mparams.uselocalh = false;
2743 mparams.grading = 0.8; // not limitited size growth
2745 if ( _simpleHyp->GetNumberOfSegments() )
2747 mparams.maxh = occgeo.boundingbox.Diam();
2750 mparams.maxh = _simpleHyp->GetLocalLength();
2753 if ( mparams.maxh == 0.0 )
2754 mparams.maxh = occgeo.boundingbox.Diam();
2755 if ( _simpleHyp || ( mparams.minh == 0.0 && _fineness != NETGENPlugin_Hypothesis::UserDefined))
2756 mparams.minh = GetDefaultMinSize( _shape, mparams.maxh );
2758 // let netgen create _ngMesh and calculate element size on not meshed shapes
2759 NETGENPlugin_NetgenLibWrapper ngLib;
2760 netgen::Mesh *ngMesh = NULL;
2764 int startWith = netgen::MESHCONST_ANALYSE;
2765 int endWith = netgen::MESHCONST_MESHEDGES;
2767 int err = netgen::OCCGenerateMesh(occgeo, ngMesh, mparams, startWith, endWith);
2769 int err = netgen::OCCGenerateMesh(occgeo, ngMesh, startWith, endWith, optstr);
2772 if(netgen::multithread.terminate)
2775 ngLib.setMesh(( Ng_Mesh*) ngMesh );
2777 if ( SMESH_subMesh* sm = _mesh->GetSubMeshContaining( _shape ))
2778 sm->GetComputeError().reset( new SMESH_ComputeError( COMPERR_ALGO_FAILED ));
2783 // Pass 1D simple parameters to NETGEN
2784 // --------------------------------
2785 int nbSeg = _simpleHyp->GetNumberOfSegments();
2786 double segSize = _simpleHyp->GetLocalLength();
2787 for ( int iE = 1; iE <= occgeo.emap.Extent(); ++iE )
2789 const TopoDS_Edge& e = TopoDS::Edge( occgeo.emap(iE));
2791 segSize = SMESH_Algo::EdgeLength( e ) / ( nbSeg - 0.4 );
2792 setLocalSize( e, segSize, *ngMesh );
2795 else // if ( ! _simpleHyp )
2797 // Local size on vertices and edges
2798 // --------------------------------
2799 for(std::map<int,double>::const_iterator it=EdgeId2LocalSize.begin(); it!=EdgeId2LocalSize.end(); it++)
2801 int key = (*it).first;
2802 double hi = (*it).second;
2803 const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
2804 const TopoDS_Edge& e = TopoDS::Edge(shape);
2805 setLocalSize( e, hi, *ngMesh );
2807 for(std::map<int,double>::const_iterator it=VertexId2LocalSize.begin(); it!=VertexId2LocalSize.end(); it++)
2809 int key = (*it).first;
2810 double hi = (*it).second;
2811 const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
2812 const TopoDS_Vertex& v = TopoDS::Vertex(shape);
2813 gp_Pnt p = BRep_Tool::Pnt(v);
2814 NETGENPlugin_Mesher::RestrictLocalSize( *ngMesh, p.XYZ(), hi );
2816 for(map<int,double>::const_iterator it=FaceId2LocalSize.begin();
2817 it!=FaceId2LocalSize.end(); it++)
2819 int key = (*it).first;
2820 double val = (*it).second;
2821 const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
2822 int faceNgID = occgeo.fmap.FindIndex(shape);
2823 occgeo.SetFaceMaxH(faceNgID, val);
2824 for ( TopExp_Explorer edgeExp( shape, TopAbs_EDGE ); edgeExp.More(); edgeExp.Next() )
2825 setLocalSize( TopoDS::Edge( edgeExp.Current() ), val, *ngMesh );
2828 // calculate total nb of segments and length of edges
2829 double fullLen = 0.0;
2831 int entity = mparams.secondorder > 0 ? SMDSEntity_Quad_Edge : SMDSEntity_Edge;
2832 TopTools_DataMapOfShapeInteger Edge2NbSeg;
2833 for (TopExp_Explorer exp(_shape, TopAbs_EDGE); exp.More(); exp.Next())
2835 TopoDS_Edge E = TopoDS::Edge( exp.Current() );
2836 if( !Edge2NbSeg.Bind(E,0) )
2839 double aLen = SMESH_Algo::EdgeLength(E);
2842 vector<int>& aVec = aResMap[_mesh->GetSubMesh(E)];
2844 aVec.resize( SMDSEntity_Last, 0);
2846 fullNbSeg += aVec[ entity ];
2849 // store nb of segments computed by Netgen
2850 NCollection_Map<Link> linkMap;
2851 for (int i = 1; i <= ngMesh->GetNSeg(); ++i )
2853 const netgen::Segment& seg = ngMesh->LineSegment(i);
2854 Link link(seg[0], seg[1]);
2855 if ( !linkMap.Add( link )) continue;
2856 int aGeomEdgeInd = seg.epgeominfo[0].edgenr;
2857 if (aGeomEdgeInd > 0 && aGeomEdgeInd <= occgeo.emap.Extent())
2859 vector<int>& aVec = aResMap[_mesh->GetSubMesh(occgeo.emap(aGeomEdgeInd))];
2863 // store nb of nodes on edges computed by Netgen
2864 TopTools_DataMapIteratorOfDataMapOfShapeInteger Edge2NbSegIt(Edge2NbSeg);
2865 for (; Edge2NbSegIt.More(); Edge2NbSegIt.Next())
2867 vector<int>& aVec = aResMap[_mesh->GetSubMesh(Edge2NbSegIt.Key())];
2868 if ( aVec[ entity ] > 1 && aVec[ SMDSEntity_Node ] == 0 )
2869 aVec[SMDSEntity_Node] = mparams.secondorder > 0 ? 2*aVec[ entity ]-1 : aVec[ entity ]-1;
2871 fullNbSeg += aVec[ entity ];
2872 Edge2NbSeg( Edge2NbSegIt.Key() ) = aVec[ entity ];
2874 if ( fullNbSeg == 0 )
2881 if ( double area = _simpleHyp->GetMaxElementArea() ) {
2883 mparams.maxh = sqrt(2. * area/sqrt(3.0));
2884 mparams.grading = 0.4; // moderate size growth
2887 // length from edges
2888 mparams.maxh = fullLen/fullNbSeg;
2889 mparams.grading = 0.2; // slow size growth
2892 mparams.maxh = min( mparams.maxh, occgeo.boundingbox.Diam()/2 );
2893 mparams.maxh = min( mparams.maxh, fullLen/fullNbSeg * (1. + mparams.grading));
2895 for (TopExp_Explorer exp(_shape, TopAbs_FACE); exp.More(); exp.Next())
2897 TopoDS_Face F = TopoDS::Face( exp.Current() );
2898 SMESH_subMesh *sm = _mesh->GetSubMesh(F);
2900 BRepGProp::SurfaceProperties(F,G);
2901 double anArea = G.Mass();
2902 tooManyElems = tooManyElems || ( anArea/hugeNb > mparams.maxh*mparams.maxh );
2904 if ( !tooManyElems )
2906 TopTools_MapOfShape egdes;
2907 for (TopExp_Explorer exp1(F,TopAbs_EDGE); exp1.More(); exp1.Next())
2908 if ( egdes.Add( exp1.Current() ))
2909 nb1d += Edge2NbSeg.Find(exp1.Current());
2911 int nbFaces = tooManyElems ? hugeNb : int( 4*anArea / (mparams.maxh*mparams.maxh*sqrt(3.)));
2912 int nbNodes = tooManyElems ? hugeNb : (( nbFaces*3 - (nb1d-1)*2 ) / 6 + 1 );
2914 vector<int> aVec(SMDSEntity_Last, 0);
2915 if( mparams.secondorder > 0 ) {
2916 int nb1d_in = (nbFaces*3 - nb1d) / 2;
2917 aVec[SMDSEntity_Node] = nbNodes + nb1d_in;
2918 aVec[SMDSEntity_Quad_Triangle] = nbFaces;
2921 aVec[SMDSEntity_Node] = Max ( nbNodes, 0 );
2922 aVec[SMDSEntity_Triangle] = nbFaces;
2924 aResMap[sm].swap(aVec);
2931 // pass 3D simple parameters to NETGEN
2932 const NETGENPlugin_SimpleHypothesis_3D* simple3d =
2933 dynamic_cast< const NETGENPlugin_SimpleHypothesis_3D* > ( _simpleHyp );
2935 if ( double vol = simple3d->GetMaxElementVolume() ) {
2937 mparams.maxh = pow( 72, 1/6. ) * pow( vol, 1/3. );
2938 mparams.maxh = min( mparams.maxh, occgeo.boundingbox.Diam()/2 );
2941 // using previous length from faces
2943 mparams.grading = 0.4;
2944 mparams.maxh = min( mparams.maxh, fullLen/fullNbSeg * (1. + mparams.grading));
2947 BRepGProp::VolumeProperties(_shape,G);
2948 double aVolume = G.Mass();
2949 double tetrVol = 0.1179*mparams.maxh*mparams.maxh*mparams.maxh;
2950 tooManyElems = tooManyElems || ( aVolume/hugeNb > tetrVol );
2951 int nbVols = tooManyElems ? hugeNb : int(aVolume/tetrVol);
2952 int nb1d_in = int(( nbVols*6 - fullNbSeg ) / 6 );
2953 vector<int> aVec(SMDSEntity_Last, 0 );
2954 if ( tooManyElems ) // avoid FPE
2956 aVec[SMDSEntity_Node] = hugeNb;
2957 aVec[ mparams.secondorder > 0 ? SMDSEntity_Quad_Tetra : SMDSEntity_Tetra] = hugeNb;
2961 if( mparams.secondorder > 0 ) {
2962 aVec[SMDSEntity_Node] = nb1d_in/3 + 1 + nb1d_in;
2963 aVec[SMDSEntity_Quad_Tetra] = nbVols;
2966 aVec[SMDSEntity_Node] = nb1d_in/3 + 1;
2967 aVec[SMDSEntity_Tetra] = nbVols;
2970 SMESH_subMesh *sm = _mesh->GetSubMesh(_shape);
2971 aResMap[sm].swap(aVec);
2977 double NETGENPlugin_Mesher::GetProgress(const SMESH_Algo* holder,
2978 const int * algoProgressTic,
2979 const double * algoProgress) const
2981 ((int&) _progressTic ) = *algoProgressTic + 1;
2983 if ( !_occgeom ) return 0;
2985 double progress = -1;
2988 if ( _ticTime < 0 && netgen::multithread.task[0] == 'O'/*Optimizing surface*/ )
2990 ((double&) _ticTime ) = edgeFaceMeshingTime / _totalTime / _progressTic;
2992 else if ( !_optimize /*&& _occgeom->fmap.Extent() > 1*/ )
2994 int doneShapeIndex = -1;
2995 while ( doneShapeIndex+1 < _occgeom->facemeshstatus.Size() &&
2996 _occgeom->facemeshstatus[ doneShapeIndex+1 ])
2998 if ( doneShapeIndex+1 != _curShapeIndex )
3000 ((int&) _curShapeIndex) = doneShapeIndex+1;
3001 double doneShapeRate = _curShapeIndex / double( _occgeom->fmap.Extent() );
3002 double doneTime = edgeMeshingTime + doneShapeRate * faceMeshingTime;
3003 ((double&) _ticTime) = doneTime / _totalTime / _progressTic;
3004 // cout << "shape " << _curShapeIndex << " _ticTime " << _ticTime
3005 // << " " << doneTime / _totalTime / _progressTic << endl;
3009 else if ( !_optimize && _occgeom->somap.Extent() > 1 )
3011 int curShapeIndex = _curShapeIndex;
3012 if ( _ngMesh->GetNE() > 0 )
3014 netgen::Element el = (*_ngMesh)[netgen::ElementIndex( _ngMesh->GetNE()-1 )];
3015 curShapeIndex = el.GetIndex();
3017 if ( curShapeIndex != _curShapeIndex )
3019 ((int&) _curShapeIndex) = curShapeIndex;
3020 double doneShapeRate = _curShapeIndex / double( _occgeom->somap.Extent() );
3021 double doneTime = edgeFaceMeshingTime + doneShapeRate * voluMeshingTime;
3022 ((double&) _ticTime) = doneTime / _totalTime / _progressTic;
3023 // cout << "shape " << _curShapeIndex << " _ticTime " << _ticTime
3024 // << " " << doneTime / _totalTime / _progressTic << endl;
3028 progress = Max( *algoProgressTic * _ticTime, *algoProgress );
3031 ((int&) *algoProgressTic )++;
3032 ((double&) *algoProgress) = progress;
3034 //cout << progress << " " << *algoProgressTic << " " << netgen::multithread.task << " "<< _ticTime << endl;
3036 return Min( progress, 0.99 );
3039 //================================================================================
3041 * \brief Remove "test.out" and "problemfaces" files in current directory
3043 //================================================================================
3045 void NETGENPlugin_Mesher::RemoveTmpFiles()
3047 bool rm = SMESH_File("test.out").remove() ;
3049 if (rm && netgen::testout)
3051 delete netgen::testout;
3052 netgen::testout = 0;
3055 SMESH_File("problemfaces").remove();
3056 SMESH_File("occmesh.rep").remove();
3059 //================================================================================
3061 * \brief Read mesh entities preventing successful computation from "test.out" file
3063 //================================================================================
3065 SMESH_ComputeErrorPtr
3066 NETGENPlugin_Mesher::ReadErrors(const vector<const SMDS_MeshNode* >& nodeVec)
3068 SMESH_ComputeErrorPtr err = SMESH_ComputeError::New
3069 (COMPERR_BAD_INPUT_MESH, "Some edges multiple times in surface mesh");
3070 SMESH_File file("test.out");
3072 const char* badEdgeStr = " multiple times in surface mesh";
3073 const int badEdgeStrLen = strlen( badEdgeStr );
3074 while( !file.eof() )
3076 if ( strncmp( file, "Edge ", 5 ) == 0 &&
3077 file.getInts( two ) &&
3078 strncmp( file, badEdgeStr, badEdgeStrLen ) == 0 &&
3079 two[0] < nodeVec.size() && two[1] < nodeVec.size())
3081 err->myBadElements.push_back( new SMDS_LinearEdge( nodeVec[ two[0]], nodeVec[ two[1]] ));
3082 file += badEdgeStrLen;
3084 else if ( strncmp( file, "Intersecting: ", 14 ) == 0 )
3087 // openelement 18 with open element 126
3090 vector<int> three1(3), three2(3);
3092 const char* pos = file;
3093 bool ok = ( strncmp( file, "openelement ", 12 ) == 0 );
3094 ok = ok && file.getInts( two );
3095 ok = ok && file.getInts( three1 );
3096 ok = ok && file.getInts( three2 );
3097 for ( int i = 0; ok && i < 3; ++i )
3098 ok = ( three1[i] < nodeVec.size() && nodeVec[ three1[i]]);
3099 for ( int i = 0; ok && i < 3; ++i )
3100 ok = ( three2[i] < nodeVec.size() && nodeVec[ three2[i]]);
3103 err->myBadElements.push_back( new SMDS_FaceOfNodes( nodeVec[ three1[0]],
3104 nodeVec[ three1[1]],
3105 nodeVec[ three1[2]]));
3106 err->myBadElements.push_back( new SMDS_FaceOfNodes( nodeVec[ three2[0]],
3107 nodeVec[ three2[1]],
3108 nodeVec[ three2[2]]));
3109 err->myComment = "Intersecting triangles";
3124 //================================================================================
3126 * \brief Write a python script creating an equivalent SALOME mesh.
3127 * This is useful to see what mesh is passed as input for the next step of mesh
3128 * generation (of mesh of higher dimension)
3130 //================================================================================
3132 void NETGENPlugin_Mesher::toPython( const netgen::Mesh* ngMesh,
3133 const std::string& pyFile)
3135 ofstream outfile(pyFile.c_str(), ios::out);
3136 if ( !outfile ) return;
3138 outfile << "import SMESH" << endl
3139 << "from salome.smesh import smeshBuilder" << endl
3140 << "smesh = smeshBuilder.New(salome.myStudy)" << endl
3141 << "mesh = smesh.Mesh()" << endl << endl;
3143 using namespace netgen;
3145 for (pi = PointIndex::BASE;
3146 pi < ngMesh->GetNP()+PointIndex::BASE; pi++)
3148 outfile << "mesh.AddNode( ";
3149 outfile << (*ngMesh)[pi](0) << ", ";
3150 outfile << (*ngMesh)[pi](1) << ", ";
3151 outfile << (*ngMesh)[pi](2) << ") ## "<< pi << endl;
3154 int nbDom = ngMesh->GetNDomains();
3155 for ( int i = 0; i < nbDom; ++i )
3156 outfile<< "grp" << i+1 << " = mesh.CreateEmptyGroup( SMESH.FACE, 'domain"<< i+1 << "')"<< endl;
3158 SurfaceElementIndex sei;
3159 for (sei = 0; sei < ngMesh->GetNSE(); sei++)
3161 outfile << "mesh.AddFace([ ";
3162 Element2d sel = (*ngMesh)[sei];
3163 for (int j = 0; j < sel.GetNP(); j++)
3164 outfile << sel[j] << ( j+1 < sel.GetNP() ? ", " : " ])");
3165 if ( sel.IsDeleted() ) outfile << " ## IsDeleted ";
3168 if ((*ngMesh)[sei].GetIndex())
3170 if ( int dom1 = ngMesh->GetFaceDescriptor((*ngMesh)[sei].GetIndex ()).DomainIn())
3171 outfile << "grp"<< dom1 <<".Add([ " << (int)sei+1 << " ])" << endl;
3172 if ( int dom2 = ngMesh->GetFaceDescriptor((*ngMesh)[sei].GetIndex ()).DomainOut())
3173 outfile << "grp"<< dom2 <<".Add([ " << (int)sei+1 << " ])" << endl;
3177 for (ElementIndex ei = 0; ei < ngMesh->GetNE(); ei++)
3179 Element el = (*ngMesh)[ei];
3180 outfile << "mesh.AddVolume([ ";
3181 for (int j = 0; j < el.GetNP(); j++)
3182 outfile << el[j] << ( j+1 < el.GetNP() ? ", " : " ])");
3186 for (int i = 1; i <= ngMesh->GetNSeg(); i++)
3188 const Segment & seg = ngMesh->LineSegment (i);
3189 outfile << "mesh.AddEdge([ "
3191 << seg[1] << " ])" << endl;
3193 cout << "Write " << pyFile << endl;
3196 //================================================================================
3198 * \brief Constructor of NETGENPlugin_ngMeshInfo
3200 //================================================================================
3202 NETGENPlugin_ngMeshInfo::NETGENPlugin_ngMeshInfo( netgen::Mesh* ngMesh):
3207 _nbNodes = ngMesh->GetNP();
3208 _nbSegments = ngMesh->GetNSeg();
3209 _nbFaces = ngMesh->GetNSE();
3210 _nbVolumes = ngMesh->GetNE();
3214 _nbNodes = _nbSegments = _nbFaces = _nbVolumes = 0;
3218 //================================================================================
3220 * \brief Copy LocalH member from one netgen mesh to another
3222 //================================================================================
3224 void NETGENPlugin_ngMeshInfo::transferLocalH( netgen::Mesh* fromMesh,
3225 netgen::Mesh* toMesh )
3227 if ( !fromMesh->LocalHFunctionGenerated() ) return;
3228 if ( !toMesh->LocalHFunctionGenerated() )
3230 toMesh->CalcLocalH(netgen::mparam.grading);
3232 toMesh->CalcLocalH();
3235 const size_t size = sizeof( netgen::LocalH );
3236 _copyOfLocalH = new char[ size ];
3237 memcpy( (void*)_copyOfLocalH, (void*)&toMesh->LocalHFunction(), size );
3238 memcpy( (void*)&toMesh->LocalHFunction(), (void*)&fromMesh->LocalHFunction(), size );
3241 //================================================================================
3243 * \brief Restore LocalH member of a netgen mesh
3245 //================================================================================
3247 void NETGENPlugin_ngMeshInfo::restoreLocalH( netgen::Mesh* toMesh )
3249 if ( _copyOfLocalH )
3251 const size_t size = sizeof( netgen::LocalH );
3252 memcpy( (void*)&toMesh->LocalHFunction(), (void*)_copyOfLocalH, size );
3253 delete [] _copyOfLocalH;
3258 //================================================================================
3260 * \brief Find "internal" sub-shapes
3262 //================================================================================
3264 NETGENPlugin_Internals::NETGENPlugin_Internals( SMESH_Mesh& mesh,
3265 const TopoDS_Shape& shape,
3267 : _mesh( mesh ), _is3D( is3D )
3269 SMESHDS_Mesh* meshDS = mesh.GetMeshDS();
3271 TopExp_Explorer f,e;
3272 for ( f.Init( shape, TopAbs_FACE ); f.More(); f.Next() )
3274 int faceID = meshDS->ShapeToIndex( f.Current() );
3276 // find not computed internal edges
3278 for ( e.Init( f.Current().Oriented(TopAbs_FORWARD), TopAbs_EDGE ); e.More(); e.Next() )
3279 if ( e.Current().Orientation() == TopAbs_INTERNAL )
3281 SMESH_subMesh* eSM = mesh.GetSubMesh( e.Current() );
3282 if ( eSM->IsEmpty() )
3284 _e2face.insert( make_pair( eSM->GetId(), faceID ));
3285 for ( TopoDS_Iterator v(e.Current()); v.More(); v.Next() )
3286 _e2face.insert( make_pair( meshDS->ShapeToIndex( v.Value() ), faceID ));
3290 // find internal vertices in a face
3291 set<int> intVV; // issue 0020850 where same vertex is twice in a face
3292 for ( TopoDS_Iterator fSub( f.Current() ); fSub.More(); fSub.Next())
3293 if ( fSub.Value().ShapeType() == TopAbs_VERTEX )
3295 int vID = meshDS->ShapeToIndex( fSub.Value() );
3296 if ( intVV.insert( vID ).second )
3297 _f2v[ faceID ].push_back( vID );
3302 // find internal faces and their subshapes where nodes are to be doubled
3303 // to make a crack with non-sewed borders
3305 if ( f.Current().Orientation() == TopAbs_INTERNAL )
3307 _intShapes.insert( meshDS->ShapeToIndex( f.Current() ));
3310 list< TopoDS_Shape > edges;
3311 for ( e.Init( f.Current(), TopAbs_EDGE ); e.More(); e.Next())
3312 if ( SMESH_MesherHelper::NbAncestors( e.Current(), mesh, TopAbs_FACE ) > 1 )
3314 _intShapes.insert( meshDS->ShapeToIndex( e.Current() ));
3315 edges.push_back( e.Current() );
3316 // find border faces
3317 PShapeIteratorPtr fIt =
3318 SMESH_MesherHelper::GetAncestors( edges.back(),mesh,TopAbs_FACE );
3319 while ( const TopoDS_Shape* pFace = fIt->next() )
3320 if ( !pFace->IsSame( f.Current() ))
3321 _borderFaces.insert( meshDS->ShapeToIndex( *pFace ));
3324 // we consider vertex internal if it is shared by more than one internal edge
3325 list< TopoDS_Shape >::iterator edge = edges.begin();
3326 for ( ; edge != edges.end(); ++edge )
3327 for ( TopoDS_Iterator v( *edge ); v.More(); v.Next() )
3329 set<int> internalEdges;
3330 PShapeIteratorPtr eIt =
3331 SMESH_MesherHelper::GetAncestors( v.Value(),mesh,TopAbs_EDGE );
3332 while ( const TopoDS_Shape* pEdge = eIt->next() )
3334 int edgeID = meshDS->ShapeToIndex( *pEdge );
3335 if ( isInternalShape( edgeID ))
3336 internalEdges.insert( edgeID );
3338 if ( internalEdges.size() > 1 )
3339 _intShapes.insert( meshDS->ShapeToIndex( v.Value() ));
3343 } // loop on geom faces
3345 // find vertices internal in solids
3348 for ( TopExp_Explorer so(shape, TopAbs_SOLID); so.More(); so.Next())
3350 int soID = meshDS->ShapeToIndex( so.Current() );
3351 for ( TopoDS_Iterator soSub( so.Current() ); soSub.More(); soSub.Next())
3352 if ( soSub.Value().ShapeType() == TopAbs_VERTEX )
3353 _s2v[ soID ].push_back( meshDS->ShapeToIndex( soSub.Value() ));
3358 //================================================================================
3360 * \brief Find mesh faces on non-internal geom faces sharing internal edge
3361 * some nodes of which are to be doubled to make the second border of the "crack"
3363 //================================================================================
3365 void NETGENPlugin_Internals::findBorderElements( TIDSortedElemSet & borderElems )
3367 if ( _intShapes.empty() ) return;
3369 SMESH_Mesh& mesh = const_cast<SMESH_Mesh&>(_mesh);
3370 SMESHDS_Mesh* meshDS = mesh.GetMeshDS();
3372 // loop on internal geom edges
3373 set<int>::const_iterator intShapeId = _intShapes.begin();
3374 for ( ; intShapeId != _intShapes.end(); ++intShapeId )
3376 const TopoDS_Shape& s = meshDS->IndexToShape( *intShapeId );
3377 if ( s.ShapeType() != TopAbs_EDGE ) continue;
3379 // get internal and non-internal geom faces sharing the internal edge <s>
3381 set<int>::iterator bordFace = _borderFaces.end();
3382 PShapeIteratorPtr faces = SMESH_MesherHelper::GetAncestors( s, _mesh, TopAbs_FACE );
3383 while ( const TopoDS_Shape* pFace = faces->next() )
3385 int faceID = meshDS->ShapeToIndex( *pFace );
3386 if ( isInternalShape( faceID ))
3389 bordFace = _borderFaces.insert( faceID ).first;
3391 if ( bordFace == _borderFaces.end() || !intFace ) continue;
3393 // get all links of mesh faces on internal geom face sharing nodes on edge <s>
3394 set< SMESH_OrientedLink > links; //!< links of faces on internal geom face
3395 list<const SMDS_MeshElement*> suspectFaces[2]; //!< mesh faces on border geom faces
3396 int nbSuspectFaces = 0;
3397 SMESHDS_SubMesh* intFaceSM = meshDS->MeshElements( intFace );
3398 if ( !intFaceSM || intFaceSM->NbElements() == 0 ) continue;
3399 SMESH_subMeshIteratorPtr smIt = mesh.GetSubMesh( s )->getDependsOnIterator(true,true);
3400 while ( smIt->more() )
3402 SMESHDS_SubMesh* sm = smIt->next()->GetSubMeshDS();
3403 if ( !sm ) continue;
3404 SMDS_NodeIteratorPtr nIt = sm->GetNodes();
3405 while ( nIt->more() )
3407 const SMDS_MeshNode* nOnEdge = nIt->next();
3408 SMDS_ElemIteratorPtr fIt = nOnEdge->GetInverseElementIterator(SMDSAbs_Face);
3409 while ( fIt->more() )
3411 const SMDS_MeshElement* f = fIt->next();
3412 int nbNodes = f->NbNodes() / ( f->IsQuadratic() ? 2 : 1 );
3413 if ( intFaceSM->Contains( f ))
3415 for ( int i = 0; i < nbNodes; ++i )
3416 links.insert( SMESH_OrientedLink( f->GetNode(i), f->GetNode((i+1)%nbNodes)));
3421 for ( int i = 0; i < nbNodes; ++i )
3422 nbDblNodes += isInternalShape( f->GetNode(i)->getshapeId() );
3424 suspectFaces[ nbDblNodes < 2 ].push_back( f );
3430 // suspectFaces[0] having link with same orientation as mesh faces on
3431 // the internal geom face are <borderElems>. suspectFaces[1] have
3432 // only one node on edge <s>, we decide on them later (at the 2nd loop)
3433 // by links of <borderElems> found at the 1st and 2nd loops
3434 set< SMESH_OrientedLink > borderLinks;
3435 for ( int isPostponed = 0; isPostponed < 2; ++isPostponed )
3437 list<const SMDS_MeshElement*>::iterator fIt = suspectFaces[isPostponed].begin();
3438 for ( int nbF = 0; fIt != suspectFaces[isPostponed].end(); ++fIt, ++nbF )
3440 const SMDS_MeshElement* f = *fIt;
3441 bool isBorder = false, linkFound = false, borderLinkFound = false;
3442 list< SMESH_OrientedLink > faceLinks;
3443 int nbNodes = f->NbNodes() / ( f->IsQuadratic() ? 2 : 1 );
3444 for ( int i = 0; i < nbNodes; ++i )
3446 SMESH_OrientedLink link( f->GetNode(i), f->GetNode((i+1)%nbNodes));
3447 faceLinks.push_back( link );
3450 set< SMESH_OrientedLink >::iterator foundLink = links.find( link );
3451 if ( foundLink != links.end() )
3454 isBorder = ( foundLink->_reversed == link._reversed );
3455 if ( !isBorder && !isPostponed ) break;
3456 faceLinks.pop_back();
3458 else if ( isPostponed && !borderLinkFound )
3460 foundLink = borderLinks.find( link );
3461 if ( foundLink != borderLinks.end() )
3463 borderLinkFound = true;
3464 isBorder = ( foundLink->_reversed != link._reversed );
3471 borderElems.insert( f );
3472 borderLinks.insert( faceLinks.begin(), faceLinks.end() );
3474 else if ( !linkFound && !borderLinkFound )
3476 suspectFaces[1].push_back( f );
3477 if ( nbF > 2 * nbSuspectFaces )
3478 break; // dead loop protection
3485 //================================================================================
3487 * \brief put internal shapes in maps and fill in submeshes to precompute
3489 //================================================================================
3491 void NETGENPlugin_Internals::getInternalEdges( TopTools_IndexedMapOfShape& fmap,
3492 TopTools_IndexedMapOfShape& emap,
3493 TopTools_IndexedMapOfShape& vmap,
3494 list< SMESH_subMesh* > smToPrecompute[])
3496 if ( !hasInternalEdges() ) return;
3497 map<int,int>::const_iterator ev_face = _e2face.begin();
3498 for ( ; ev_face != _e2face.end(); ++ev_face )
3500 const TopoDS_Shape& ev = _mesh.GetMeshDS()->IndexToShape( ev_face->first );
3501 const TopoDS_Shape& face = _mesh.GetMeshDS()->IndexToShape( ev_face->second );
3503 ( ev.ShapeType() == TopAbs_EDGE ? emap : vmap ).Add( ev );
3505 //cout<<"INTERNAL EDGE or VERTEX "<<ev_face->first<<" on face "<<ev_face->second<<endl;
3507 smToPrecompute[ MeshDim_1D ].push_back( _mesh.GetSubMeshContaining( ev_face->first ));
3511 //================================================================================
3513 * \brief return shapes and submeshes to be meshed and already meshed boundary submeshes
3515 //================================================================================
3517 void NETGENPlugin_Internals::getInternalFaces( TopTools_IndexedMapOfShape& fmap,
3518 TopTools_IndexedMapOfShape& emap,
3519 list< SMESH_subMesh* >& intFaceSM,
3520 list< SMESH_subMesh* >& boundarySM)
3522 if ( !hasInternalFaces() ) return;
3524 // <fmap> and <emap> are for not yet meshed shapes
3525 // <intFaceSM> is for submeshes of faces
3526 // <boundarySM> is for meshed edges and vertices
3531 set<int> shapeIDs ( _intShapes );
3532 if ( !_borderFaces.empty() )
3533 shapeIDs.insert( _borderFaces.begin(), _borderFaces.end() );
3535 set<int>::const_iterator intS = shapeIDs.begin();
3536 for ( ; intS != shapeIDs.end(); ++intS )
3538 SMESH_subMesh* sm = _mesh.GetSubMeshContaining( *intS );
3540 if ( sm->GetSubShape().ShapeType() != TopAbs_FACE ) continue;
3542 intFaceSM.push_back( sm );
3544 // add submeshes of not computed internal faces
3545 if ( !sm->IsEmpty() ) continue;
3547 SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(true,true);
3548 while ( smIt->more() )
3551 const TopoDS_Shape& s = sm->GetSubShape();
3553 if ( sm->IsEmpty() )
3556 switch ( s.ShapeType() ) {
3557 case TopAbs_FACE: fmap.Add ( s ); break;
3558 case TopAbs_EDGE: emap.Add ( s ); break;
3564 if ( s.ShapeType() != TopAbs_FACE )
3565 boundarySM.push_back( sm );
3571 //================================================================================
3573 * \brief Return true if given shape is to be precomputed in order to be correctly
3574 * added to netgen mesh
3576 //================================================================================
3578 bool NETGENPlugin_Internals::isShapeToPrecompute(const TopoDS_Shape& s)
3580 int shapeID = _mesh.GetMeshDS()->ShapeToIndex( s );
3581 switch ( s.ShapeType() ) {
3582 case TopAbs_FACE : break; //return isInternalShape( shapeID ) || isBorderFace( shapeID );
3583 case TopAbs_EDGE : return isInternalEdge( shapeID );
3584 case TopAbs_VERTEX: break;
3590 //================================================================================
3592 * \brief Return SMESH
3594 //================================================================================
3596 SMESH_Mesh& NETGENPlugin_Internals::getMesh() const
3598 return const_cast<SMESH_Mesh&>( _mesh );
3601 //================================================================================
3603 * \brief Initialize netgen library
3605 //================================================================================
3607 NETGENPlugin_NetgenLibWrapper::NETGENPlugin_NetgenLibWrapper()
3611 // redirect all netgen output (mycout,myerr,cout) to _outputFileName
3612 _isComputeOk = false;
3613 _outputFileName = getOutputFileName();
3614 netgen::mycout = new ofstream ( _outputFileName.c_str() );
3615 netgen::myerr = netgen::mycout;
3616 _coutBuffer = std::cout.rdbuf();
3618 cout << "NOTE: netgen output is redirected to file " << _outputFileName << endl;
3620 std::cout.rdbuf( netgen::mycout->rdbuf() );
3623 _ngMesh = Ng_NewMesh();
3626 //================================================================================
3628 * \brief Finish using netgen library
3630 //================================================================================
3632 NETGENPlugin_NetgenLibWrapper::~NETGENPlugin_NetgenLibWrapper()
3634 Ng_DeleteMesh( _ngMesh );
3636 NETGENPlugin_Mesher::RemoveTmpFiles();
3637 std::cout.rdbuf( _coutBuffer );
3644 //================================================================================
3646 * \brief Set netgen mesh to delete at destruction
3648 //================================================================================
3650 void NETGENPlugin_NetgenLibWrapper::setMesh( Ng_Mesh* mesh )
3653 Ng_DeleteMesh( _ngMesh );
3657 //================================================================================
3659 * \brief Return a unique file name
3661 //================================================================================
3663 std::string NETGENPlugin_NetgenLibWrapper::getOutputFileName()
3665 std::string aTmpDir = SALOMEDS_Tool::GetTmpDir();
3667 TCollection_AsciiString aGenericName = (char*)aTmpDir.c_str();
3668 aGenericName += "NETGEN_";
3670 aGenericName += getpid();
3672 aGenericName += _getpid();
3674 aGenericName += "_";
3675 aGenericName += Abs((Standard_Integer)(long) aGenericName.ToCString());
3676 aGenericName += ".out";
3678 return aGenericName.ToCString();
3681 //================================================================================
3683 * \brief Remove file with netgen output
3685 //================================================================================
3687 void NETGENPlugin_NetgenLibWrapper::removeOutputFile()
3689 string tmpDir = SALOMEDS_Tool::GetDirFromPath( _outputFileName );
3690 SALOMEDS::ListOfFileNames_var aFiles = new SALOMEDS::ListOfFileNames;
3692 std::string aFileName = SALOMEDS_Tool::GetNameFromPath( _outputFileName ) + ".out";
3693 aFiles[0] = aFileName.c_str();
3694 if ( netgen::mycout)
3696 delete netgen::mycout;
3701 SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.c_str(), aFiles.in(), true );
3703 //cout << "NOTE: netgen output log was REMOVED " << _outputFileName << endl;