1 // Copyright (C) 2007-2015 CEA/DEN, EDF R&D, OPEN CASCADE
3 // Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License, or (at your option) any later version.
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 // Lesser General Public License for more details.
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
23 // 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)
107 // dump elements added to ng mesh
108 //#define DUMP_SEGMENTS
109 //#define DUMP_TRIANGLES
110 //#define DUMP_TRIANGLES_SCRIPT "/tmp/trias.py" //!< debug AddIntVerticesInSolids()
113 TopTools_IndexedMapOfShape ShapesWithLocalSize;
114 std::map<int,double> VertexId2LocalSize;
115 std::map<int,double> EdgeId2LocalSize;
116 std::map<int,double> FaceId2LocalSize;
118 //=============================================================================
122 //=============================================================================
124 NETGENPlugin_Mesher::NETGENPlugin_Mesher (SMESH_Mesh* mesh,
125 const TopoDS_Shape& aShape,
131 _fineness(NETGENPlugin_Hypothesis::GetDefaultFineness()),
132 _isViscousLayers2D(false),
141 SetDefaultParameters();
142 ShapesWithLocalSize.Clear();
143 VertexId2LocalSize.clear();
144 EdgeId2LocalSize.clear();
145 FaceId2LocalSize.clear();
148 //================================================================================
152 //================================================================================
154 NETGENPlugin_Mesher::~NETGENPlugin_Mesher()
162 //================================================================================
164 * Set pointer to NETGENPlugin_Mesher* field of the holder, that will be
165 * nullified at destruction of this
167 //================================================================================
169 void NETGENPlugin_Mesher::SetSelfPointer( NETGENPlugin_Mesher ** ptr )
180 //================================================================================
182 * \brief Initialize global NETGEN parameters with default values
184 //================================================================================
186 void NETGENPlugin_Mesher::SetDefaultParameters()
188 netgen::MeshingParameters& mparams = netgen::mparam;
189 // maximal mesh edge size
190 mparams.maxh = 0;//NETGENPlugin_Hypothesis::GetDefaultMaxSize();
192 // minimal number of segments per edge
193 mparams.segmentsperedge = NETGENPlugin_Hypothesis::GetDefaultNbSegPerEdge();
194 // rate of growth of size between elements
195 mparams.grading = NETGENPlugin_Hypothesis::GetDefaultGrowthRate();
196 // safety factor for curvatures (elements per radius)
197 mparams.curvaturesafety = NETGENPlugin_Hypothesis::GetDefaultNbSegPerRadius();
198 // create elements of second order
199 mparams.secondorder = NETGENPlugin_Hypothesis::GetDefaultSecondOrder();
200 // quad-dominated surface meshing
204 mparams.quad = NETGENPlugin_Hypothesis_2D::GetDefaultQuadAllowed();
205 _fineness = NETGENPlugin_Hypothesis::GetDefaultFineness();
206 mparams.uselocalh = NETGENPlugin_Hypothesis::GetDefaultSurfaceCurvature();
207 netgen::merge_solids = NETGENPlugin_Hypothesis::GetDefaultFuseEdges();
210 //=============================================================================
214 //=============================================================================
216 void SetLocalSize(TopoDS_Shape GeomShape, double LocalSize)
218 if ( GeomShape.IsNull() ) return;
219 TopAbs_ShapeEnum GeomType = GeomShape.ShapeType();
220 if (GeomType == TopAbs_COMPOUND) {
221 for (TopoDS_Iterator it (GeomShape); it.More(); it.Next()) {
222 SetLocalSize(it.Value(), LocalSize);
227 if (! ShapesWithLocalSize.Contains(GeomShape))
228 key = ShapesWithLocalSize.Add(GeomShape);
230 key = ShapesWithLocalSize.FindIndex(GeomShape);
231 if (GeomType == TopAbs_VERTEX) {
232 VertexId2LocalSize[key] = LocalSize;
233 } else if (GeomType == TopAbs_EDGE) {
234 EdgeId2LocalSize[key] = LocalSize;
235 } else if (GeomType == TopAbs_FACE) {
236 FaceId2LocalSize[key] = LocalSize;
240 //=============================================================================
242 * Pass parameters to NETGEN
244 //=============================================================================
245 void NETGENPlugin_Mesher::SetParameters(const NETGENPlugin_Hypothesis* hyp)
249 netgen::MeshingParameters& mparams = netgen::mparam;
250 // Initialize global NETGEN parameters:
251 // maximal mesh segment size
252 mparams.maxh = hyp->GetMaxSize();
253 // maximal mesh element linear size
254 mparams.minh = hyp->GetMinSize();
255 // minimal number of segments per edge
256 mparams.segmentsperedge = hyp->GetNbSegPerEdge();
257 // rate of growth of size between elements
258 mparams.grading = hyp->GetGrowthRate();
259 // safety factor for curvatures (elements per radius)
260 mparams.curvaturesafety = hyp->GetNbSegPerRadius();
261 // create elements of second order
262 mparams.secondorder = hyp->GetSecondOrder() ? 1 : 0;
263 // quad-dominated surface meshing
264 // only triangles are allowed for volumic mesh (before realizing IMP 0021676)
266 mparams.quad = hyp->GetQuadAllowed() ? 1 : 0;
267 _optimize = hyp->GetOptimize();
268 _fineness = hyp->GetFineness();
269 mparams.uselocalh = hyp->GetSurfaceCurvature();
270 netgen::merge_solids = hyp->GetFuseEdges();
273 SMESH_Gen_i* smeshGen_i = SMESH_Gen_i::GetSMESHGen();
274 CORBA::Object_var anObject = smeshGen_i->GetNS()->Resolve("/myStudyManager");
275 SALOMEDS::StudyManager_var aStudyMgr = SALOMEDS::StudyManager::_narrow(anObject);
276 SALOMEDS::Study_var myStudy = aStudyMgr->GetStudyByID(hyp->GetStudyId());
278 const NETGENPlugin_Hypothesis::TLocalSize localSizes = hyp->GetLocalSizesAndEntries();
279 NETGENPlugin_Hypothesis::TLocalSize::const_iterator it = localSizes.begin();
280 for (it ; it != localSizes.end() ; it++)
282 std::string entry = (*it).first;
283 double val = (*it).second;
285 GEOM::GEOM_Object_var aGeomObj;
286 TopoDS_Shape S = TopoDS_Shape();
287 SALOMEDS::SObject_var aSObj = myStudy->FindObjectID( entry.c_str() );
288 if (!aSObj->_is_nil()) {
289 CORBA::Object_var obj = aSObj->GetObject();
290 aGeomObj = GEOM::GEOM_Object::_narrow(obj);
293 if ( !aGeomObj->_is_nil() )
294 S = smeshGen_i->GeomObjectToShape( aGeomObj.in() );
296 SetLocalSize(S, val);
301 //=============================================================================
303 * Pass simple parameters to NETGEN
305 //=============================================================================
307 void NETGENPlugin_Mesher::SetParameters(const NETGENPlugin_SimpleHypothesis_2D* hyp)
311 SetDefaultParameters();
314 //=============================================================================
316 * Link - a pair of integer numbers
318 //=============================================================================
322 Link(int _n1, int _n2) : n1(_n1), n2(_n2) {}
323 Link() : n1(0), n2(0) {}
326 int HashCode(const Link& aLink, int aLimit)
328 return HashCode(aLink.n1 + aLink.n2, aLimit);
331 Standard_Boolean IsEqual(const Link& aLink1, const Link& aLink2)
333 return (aLink1.n1 == aLink2.n1 && aLink1.n2 == aLink2.n2 ||
334 aLink1.n1 == aLink2.n2 && aLink1.n2 == aLink2.n1);
339 //================================================================================
341 * \brief return id of netgen point corresponding to SMDS node
343 //================================================================================
344 typedef map< const SMDS_MeshNode*, int > TNode2IdMap;
346 int ngNodeId( const SMDS_MeshNode* node,
347 netgen::Mesh& ngMesh,
348 TNode2IdMap& nodeNgIdMap)
350 int newNgId = ngMesh.GetNP() + 1;
352 TNode2IdMap::iterator node_id = nodeNgIdMap.insert( make_pair( node, newNgId )).first;
354 if ( node_id->second == newNgId)
356 #if defined(DUMP_SEGMENTS) || defined(DUMP_TRIANGLES)
357 cout << "Ng " << newNgId << " - " << node;
359 netgen::MeshPoint p( netgen::Point<3> (node->X(), node->Y(), node->Z()) );
360 ngMesh.AddPoint( p );
362 return node_id->second;
365 //================================================================================
367 * \brief Return computed EDGEs connected to the given one
369 //================================================================================
371 list< TopoDS_Edge > getConnectedEdges( const TopoDS_Edge& edge,
372 const TopoDS_Face& face,
373 const set< SMESH_subMesh* > & computedSM,
374 const SMESH_MesherHelper& helper,
375 map< SMESH_subMesh*, set< int > >& addedEdgeSM2Faces)
378 list< TopoDS_Edge > edges;
379 list< int > nbEdgesInWire;
380 int nbWires = SMESH_Block::GetOrderedEdges( face, edges, nbEdgesInWire);
382 // find <edge> within <edges>
383 list< TopoDS_Edge >::iterator eItFwd = edges.begin();
384 for ( ; eItFwd != edges.end(); ++eItFwd )
385 if ( edge.IsSame( *eItFwd ))
387 if ( eItFwd == edges.end()) return list< TopoDS_Edge>();
389 if ( eItFwd->Orientation() >= TopAbs_INTERNAL )
391 // connected INTERNAL edges returned from GetOrderedEdges() are wrongly oriented
392 // so treat each INTERNAL edge separately
393 TopoDS_Edge e = *eItFwd;
395 edges.push_back( e );
399 // get all computed EDGEs connected to <edge>
401 list< TopoDS_Edge >::iterator eItBack = eItFwd, ePrev;
402 TopoDS_Vertex vCommon;
403 TopTools_MapOfShape eAdded; // map used not to add a seam edge twice to <edges>
406 // put edges before <edge> to <edges> back
407 while ( edges.begin() != eItFwd )
408 edges.splice( edges.end(), edges, edges.begin() );
412 while ( ++eItFwd != edges.end() )
414 SMESH_subMesh* sm = helper.GetMesh()->GetSubMesh( *eItFwd );
416 bool connected = TopExp::CommonVertex( *ePrev, *eItFwd, vCommon );
417 bool computed = sm->IsMeshComputed();
418 bool added = addedEdgeSM2Faces[ sm ].count( helper.GetSubShapeID() );
419 bool doubled = !eAdded.Add( *eItFwd );
420 bool orientOK = (( ePrev ->Orientation() < TopAbs_INTERNAL ) ==
421 ( eItFwd->Orientation() < TopAbs_INTERNAL ) );
422 if ( !connected || !computed || !orientOK || added || doubled )
424 // stop advancement; move edges from tail to head
425 while ( edges.back() != *ePrev )
426 edges.splice( edges.begin(), edges, --edges.end() );
432 while ( eItBack != edges.begin() )
436 SMESH_subMesh* sm = helper.GetMesh()->GetSubMesh( *eItBack );
438 bool connected = TopExp::CommonVertex( *ePrev, *eItBack, vCommon );
439 bool computed = sm->IsMeshComputed();
440 bool added = addedEdgeSM2Faces[ sm ].count( helper.GetSubShapeID() );
441 bool doubled = !eAdded.Add( *eItBack );
442 bool orientOK = (( ePrev ->Orientation() < TopAbs_INTERNAL ) ==
443 ( eItBack->Orientation() < TopAbs_INTERNAL ) );
444 if ( !connected || !computed || !orientOK || added || doubled)
447 edges.erase( edges.begin(), ePrev );
451 if ( edges.front() != edges.back() )
453 // assure that the 1st vertex is meshed
454 TopoDS_Edge eLast = edges.back();
455 while ( !SMESH_Algo::VertexNode( SMESH_MesherHelper::IthVertex( 0, edges.front()), helper.GetMeshDS())
457 edges.front() != eLast )
458 edges.splice( edges.end(), edges, edges.begin() );
463 //================================================================================
465 * \brief Make triangulation of a shape precise enough
467 //================================================================================
469 void updateTriangulation( const TopoDS_Shape& shape )
471 // static set< Poly_Triangulation* > updated;
473 // TopLoc_Location loc;
474 // TopExp_Explorer fExp( shape, TopAbs_FACE );
475 // for ( ; fExp.More(); fExp.Next() )
477 // Handle(Poly_Triangulation) triangulation =
478 // BRep_Tool::Triangulation ( TopoDS::Face( fExp.Current() ), loc);
479 // if ( triangulation.IsNull() ||
480 // updated.insert( triangulation.operator->() ).second )
482 // BRepTools::Clean (shape);
485 BRepMesh_IncrementalMesh e(shape, 0.01, true);
487 catch (Standard_Failure)
490 // updated.erase( triangulation.operator->() );
491 // triangulation = BRep_Tool::Triangulation ( TopoDS::Face( fExp.Current() ), loc);
492 // updated.insert( triangulation.operator->() );
496 //================================================================================
498 * \brief Returns a medium node either existing in SMESH of created by NETGEN
499 * \param [in] corner1 - corner node 1
500 * \param [in] corner2 - corner node 2
501 * \param [in] defaultMedium - the node created by NETGEN
502 * \param [in] helper - holder of medium nodes existing in SMESH
503 * \return const SMDS_MeshNode* - the result node
505 //================================================================================
507 const SMDS_MeshNode* mediumNode( const SMDS_MeshNode* corner1,
508 const SMDS_MeshNode* corner2,
509 const SMDS_MeshNode* defaultMedium,
510 const SMESH_MesherHelper* helper)
514 TLinkNodeMap::const_iterator l2n =
515 helper->GetTLinkNodeMap().find( SMESH_TLink( corner1, corner2 ));
516 if ( l2n != helper->GetTLinkNodeMap().end() )
517 defaultMedium = l2n->second;
519 return defaultMedium;
522 //================================================================================
524 * \brief Assure that mesh on given shapes is quadratic
526 //================================================================================
528 void makeQuadratic( const TopTools_IndexedMapOfShape& shapes,
531 for ( int i = 1; i <= shapes.Extent(); ++i )
533 SMESHDS_SubMesh* smDS = mesh->GetMeshDS()->MeshElements( shapes(i) );
534 if ( !smDS ) continue;
535 SMDS_ElemIteratorPtr elemIt = smDS->GetElements();
536 if ( !elemIt->more() ) continue;
537 const SMDS_MeshElement* e = elemIt->next();
538 if ( !e || e->IsQuadratic() )
541 TIDSortedElemSet elems;
543 while ( elemIt->more() )
544 elems.insert( elems.end(), elemIt->next() );
546 SMESH_MeshEditor( mesh ).ConvertToQuadratic( /*3d=*/false, elems, /*biQuad=*/false );
552 //================================================================================
554 * \brief Initialize netgen::OCCGeometry with OCCT shape
556 //================================================================================
558 void NETGENPlugin_Mesher::PrepareOCCgeometry(netgen::OCCGeometry& occgeo,
559 const TopoDS_Shape& shape,
561 list< SMESH_subMesh* > * meshedSM,
562 NETGENPlugin_Internals* intern)
564 updateTriangulation( shape );
567 BRepBndLib::Add (shape, bb);
568 double x1,y1,z1,x2,y2,z2;
569 bb.Get (x1,y1,z1,x2,y2,z2);
570 MESSAGE("shape bounding box:\n" <<
571 "(" << x1 << " " << y1 << " " << z1 << ") " <<
572 "(" << x2 << " " << y2 << " " << z2 << ")");
573 netgen::Point<3> p1 = netgen::Point<3> (x1,y1,z1);
574 netgen::Point<3> p2 = netgen::Point<3> (x2,y2,z2);
575 occgeo.boundingbox = netgen::Box<3> (p1,p2);
577 occgeo.shape = shape;
580 // fill maps of shapes of occgeo with not yet meshed subshapes
582 // get root submeshes
583 list< SMESH_subMesh* > rootSM;
584 const int shapeID = mesh.GetMeshDS()->ShapeToIndex( shape );
585 if ( shapeID > 0 ) { // SMESH_subMesh with ID 0 may exist, don't use it!
586 rootSM.push_back( mesh.GetSubMesh( shape ));
589 for ( TopoDS_Iterator it( shape ); it.More(); it.Next() )
590 rootSM.push_back( mesh.GetSubMesh( it.Value() ));
593 // add subshapes of empty submeshes
594 list< SMESH_subMesh* >::iterator rootIt = rootSM.begin(), rootEnd = rootSM.end();
595 for ( ; rootIt != rootEnd; ++rootIt ) {
596 SMESH_subMesh * root = *rootIt;
597 SMESH_subMeshIteratorPtr smIt = root->getDependsOnIterator(/*includeSelf=*/true,
598 /*complexShapeFirst=*/true);
599 // to find a right orientation of subshapes (PAL20462)
600 TopTools_IndexedMapOfShape subShapes;
601 TopExp::MapShapes(root->GetSubShape(), subShapes);
602 while ( smIt->more() )
604 SMESH_subMesh* sm = smIt->next();
605 TopoDS_Shape shape = sm->GetSubShape();
606 if ( intern && intern->isShapeToPrecompute( shape ))
608 if ( !meshedSM || sm->IsEmpty() )
610 if ( shape.ShapeType() != TopAbs_VERTEX )
611 shape = subShapes( subShapes.FindIndex( shape ));// shape -> index -> oriented shape
612 if ( shape.Orientation() >= TopAbs_INTERNAL )
613 shape.Orientation( TopAbs_FORWARD ); // isuue 0020676
614 switch ( shape.ShapeType() ) {
615 case TopAbs_FACE : occgeo.fmap.Add( shape ); break;
616 case TopAbs_EDGE : occgeo.emap.Add( shape ); break;
617 case TopAbs_VERTEX: occgeo.vmap.Add( shape ); break;
618 case TopAbs_SOLID :occgeo.somap.Add( shape ); break;
622 // collect submeshes of meshed shapes
625 const int dim = SMESH_Gen::GetShapeDim( shape );
626 meshedSM[ dim ].push_back( sm );
630 occgeo.facemeshstatus.SetSize (occgeo.fmap.Extent());
631 occgeo.facemeshstatus = 0;
632 occgeo.face_maxh_modified.SetSize(occgeo.fmap.Extent());
633 occgeo.face_maxh_modified = 0;
634 occgeo.face_maxh.SetSize(occgeo.fmap.Extent());
635 occgeo.face_maxh = netgen::mparam.maxh;
638 //================================================================================
640 * \brief Return a default min size value suitable for the given geometry.
642 //================================================================================
644 double NETGENPlugin_Mesher::GetDefaultMinSize(const TopoDS_Shape& geom,
645 const double maxSize)
647 updateTriangulation( geom );
651 const int* pi[4] = { &i1, &i2, &i3, &i1 };
654 TopExp_Explorer fExp( geom, TopAbs_FACE );
655 for ( ; fExp.More(); fExp.Next() )
657 Handle(Poly_Triangulation) triangulation =
658 BRep_Tool::Triangulation ( TopoDS::Face( fExp.Current() ), loc);
659 if ( triangulation.IsNull() ) continue;
660 const double fTol = BRep_Tool::Tolerance( TopoDS::Face( fExp.Current() ));
661 const TColgp_Array1OfPnt& points = triangulation->Nodes();
662 const Poly_Array1OfTriangle& trias = triangulation->Triangles();
663 for ( int iT = trias.Lower(); iT <= trias.Upper(); ++iT )
665 trias(iT).Get( i1, i2, i3 );
666 for ( int j = 0; j < 3; ++j )
668 double dist2 = points(*pi[j]).SquareDistance( points( *pi[j+1] ));
669 if ( dist2 < minh && fTol*fTol < dist2 )
671 bb.Add( points(*pi[j]));
675 if ( minh > 0.25 * bb.SquareExtent() ) // simple geometry, rough triangulation
677 minh = 1e-3 * sqrt( bb.SquareExtent());
678 //cout << "BND BOX minh = " <<minh << endl;
682 minh = 3 * sqrt( minh ); // triangulation for visualization is rather fine
683 //cout << "TRIANGULATION minh = " <<minh << endl;
685 if ( minh > 0.5 * maxSize )
691 //================================================================================
693 * \brief Restrict size of elements at a given point
695 //================================================================================
697 void NETGENPlugin_Mesher::RestrictLocalSize(netgen::Mesh& ngMesh,
700 const bool overrideMinH)
702 if ( overrideMinH && netgen::mparam.minh > size )
704 ngMesh.SetMinimalH( size );
705 netgen::mparam.minh = size;
707 netgen::Point3d pi(p.X(), p.Y(), p.Z());
708 ngMesh.RestrictLocalH( pi, size );
711 //================================================================================
713 * \brief fill ngMesh with nodes and elements of computed submeshes
715 //================================================================================
717 bool NETGENPlugin_Mesher::FillNgMesh(netgen::OCCGeometry& occgeom,
718 netgen::Mesh& ngMesh,
719 vector<const SMDS_MeshNode*>& nodeVec,
720 const list< SMESH_subMesh* > & meshedSM,
721 SMESH_MesherHelper* quadHelper,
722 SMESH_ProxyMesh::Ptr proxyMesh)
724 TNode2IdMap nodeNgIdMap;
725 for ( int i = 1; i < nodeVec.size(); ++i )
726 nodeNgIdMap.insert( make_pair( nodeVec[i], i ));
728 TopTools_MapOfShape visitedShapes;
729 map< SMESH_subMesh*, set< int > > visitedEdgeSM2Faces;
730 set< SMESH_subMesh* > computedSM( meshedSM.begin(), meshedSM.end() );
732 SMESH_MesherHelper helper (*_mesh);
734 int faceNgID = ngMesh.GetNFD();
736 list< SMESH_subMesh* >::const_iterator smIt, smEnd = meshedSM.end();
737 for ( smIt = meshedSM.begin(); smIt != smEnd; ++smIt )
739 SMESH_subMesh* sm = *smIt;
740 if ( !visitedShapes.Add( sm->GetSubShape() ))
743 const SMESHDS_SubMesh * smDS = sm->GetSubMeshDS();
744 if ( !smDS ) continue;
746 switch ( sm->GetSubShape().ShapeType() )
748 case TopAbs_EDGE: { // EDGE
749 // ----------------------
750 TopoDS_Edge geomEdge = TopoDS::Edge( sm->GetSubShape() );
751 if ( geomEdge.Orientation() >= TopAbs_INTERNAL )
752 geomEdge.Orientation( TopAbs_FORWARD ); // issue 0020676
754 // Add ng segments for each not meshed FACE the EDGE bounds
755 PShapeIteratorPtr fIt = helper.GetAncestors( geomEdge, *sm->GetFather(), TopAbs_FACE );
756 while ( const TopoDS_Shape * anc = fIt->next() )
758 faceNgID = occgeom.fmap.FindIndex( *anc );
760 continue; // meshed face
762 int faceSMDSId = helper.GetMeshDS()->ShapeToIndex( *anc );
763 if ( visitedEdgeSM2Faces[ sm ].count( faceSMDSId ))
764 continue; // already treated EDGE
766 TopoDS_Face face = TopoDS::Face( occgeom.fmap( faceNgID ));
767 if ( face.Orientation() >= TopAbs_INTERNAL )
768 face.Orientation( TopAbs_FORWARD ); // issue 0020676
770 // get all meshed EDGEs of the FACE connected to geomEdge (issue 0021140)
771 helper.SetSubShape( face );
772 list< TopoDS_Edge > edges = getConnectedEdges( geomEdge, face, computedSM, helper,
773 visitedEdgeSM2Faces );
775 continue; // wrong ancestor?
777 // find out orientation of <edges> within <face>
778 TopoDS_Edge eNotSeam = edges.front();
779 if ( helper.HasSeam() )
781 list< TopoDS_Edge >::iterator eIt = edges.begin();
782 while ( helper.IsRealSeam( *eIt )) ++eIt;
783 if ( eIt != edges.end() )
786 TopAbs_Orientation fOri = helper.GetSubShapeOri( face, eNotSeam );
787 bool isForwad = ( fOri == eNotSeam.Orientation() || fOri >= TopAbs_INTERNAL );
789 // get all nodes from connected <edges>
790 bool isQuad = smDS->NbElements() ? smDS->GetElements()->next()->IsQuadratic() : false;
791 StdMeshers_FaceSide fSide( face, edges, _mesh, isForwad, isQuad );
792 const vector<UVPtStruct>& points = fSide.GetUVPtStruct();
793 if ( points.empty() ) return false; // invalid node params?
794 int i, nbSeg = fSide.NbSegments();
796 // remember EDGEs of fSide to treat only once
797 for ( int iE = 0; iE < fSide.NbEdges(); ++iE )
798 visitedEdgeSM2Faces[ helper.GetMesh()->GetSubMesh( fSide.Edge(iE )) ].insert(faceSMDSId);
800 double otherSeamParam = 0;
805 int prevNgId = ngNodeId( points[0].node, ngMesh, nodeNgIdMap );
807 for ( i = 0; i < nbSeg; ++i )
809 const UVPtStruct& p1 = points[ i ];
810 const UVPtStruct& p2 = points[ i+1 ];
812 if ( p1.node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX ) //an EDGE begins
815 if ( helper.IsRealSeam( p1.node->getshapeId() ))
817 TopoDS_Edge e = fSide.Edge( fSide.EdgeIndex( 0.5 * ( p1.normParam + p2.normParam )));
818 isSeam = helper.IsRealSeam( e );
821 otherSeamParam = helper.GetOtherParam( helper.GetPeriodicIndex() & 1 ? p2.u : p2.v );
828 seg[1] = prevNgId = ngNodeId( p2.node, ngMesh, nodeNgIdMap );
829 // node param on curve
830 seg.epgeominfo[ 0 ].dist = p1.param;
831 seg.epgeominfo[ 1 ].dist = p2.param;
833 seg.epgeominfo[ 0 ].u = p1.u;
834 seg.epgeominfo[ 0 ].v = p1.v;
835 seg.epgeominfo[ 1 ].u = p2.u;
836 seg.epgeominfo[ 1 ].v = p2.v;
838 //geomEdge = fSide.Edge( fSide.EdgeIndex( 0.5 * ( p1.normParam + p2.normParam )));
839 //seg.epgeominfo[ 0 ].edgenr = seg.epgeominfo[ 1 ].edgenr = occgeom.emap.FindIndex( geomEdge );
841 //seg.epgeominfo[ iEnd ].edgenr = edgeID; // = geom.emap.FindIndex(edge);
842 seg.si = faceNgID; // = geom.fmap.FindIndex (face);
843 seg.edgenr = ngMesh.GetNSeg() + 1; // segment id
844 ngMesh.AddSegment (seg);
846 SMESH_TNodeXYZ np1( p1.node ), np2( p2.node );
847 RestrictLocalSize( ngMesh, 0.5*(np1+np2), (np1-np2).Modulus() );
850 cout << "Segment: " << seg.edgenr << " on SMESH face " << helper.GetMeshDS()->ShapeToIndex( face ) << endl
851 << "\tface index: " << seg.si << endl
852 << "\tp1: " << seg[0] << endl
853 << "\tp2: " << seg[1] << endl
854 << "\tp0 param: " << seg.epgeominfo[ 0 ].dist << endl
855 << "\tp0 uv: " << seg.epgeominfo[ 0 ].u <<", "<< seg.epgeominfo[ 0 ].v << endl
856 //<< "\tp0 edge: " << seg.epgeominfo[ 0 ].edgenr << endl
857 << "\tp1 param: " << seg.epgeominfo[ 1 ].dist << endl
858 << "\tp1 uv: " << seg.epgeominfo[ 1 ].u <<", "<< seg.epgeominfo[ 1 ].v << endl;
859 //<< "\tp1 edge: " << seg.epgeominfo[ 1 ].edgenr << endl;
863 if ( helper.GetPeriodicIndex() && 1 ) {
864 seg.epgeominfo[ 0 ].u = otherSeamParam;
865 seg.epgeominfo[ 1 ].u = otherSeamParam;
866 swap (seg.epgeominfo[0].v, seg.epgeominfo[1].v);
868 seg.epgeominfo[ 0 ].v = otherSeamParam;
869 seg.epgeominfo[ 1 ].v = otherSeamParam;
870 swap (seg.epgeominfo[0].u, seg.epgeominfo[1].u);
872 swap (seg[0], seg[1]);
873 swap (seg.epgeominfo[0].dist, seg.epgeominfo[1].dist);
874 seg.edgenr = ngMesh.GetNSeg() + 1; // segment id
875 ngMesh.AddSegment (seg);
877 cout << "Segment: " << seg.edgenr << endl
878 << "\t is SEAM (reverse) of the previous. "
879 << " Other " << (helper.GetPeriodicIndex() && 1 ? "U" : "V")
880 << " = " << otherSeamParam << endl;
883 else if ( fOri == TopAbs_INTERNAL )
885 swap (seg[0], seg[1]);
886 swap( seg.epgeominfo[0], seg.epgeominfo[1] );
887 seg.edgenr = ngMesh.GetNSeg() + 1; // segment id
888 ngMesh.AddSegment (seg);
890 cout << "Segment: " << seg.edgenr << endl << "\t is REVERSE of the previous" << endl;
894 } // loop on geomEdge ancestors
896 if ( quadHelper ) // remember medium nodes of sub-meshes
898 SMDS_ElemIteratorPtr edges = smDS->GetElements();
899 while ( edges->more() )
901 const SMDS_MeshElement* e = edges->next();
902 if ( !quadHelper->AddTLinks( static_cast< const SMDS_MeshEdge*>( e )))
908 } // case TopAbs_EDGE
910 case TopAbs_FACE: { // FACE
911 // ----------------------
912 const TopoDS_Face& geomFace = TopoDS::Face( sm->GetSubShape() );
913 helper.SetSubShape( geomFace );
914 bool isInternalFace = ( geomFace.Orientation() == TopAbs_INTERNAL );
916 // Find solids the geomFace bounds
917 int solidID1 = 0, solidID2 = 0;
918 StdMeshers_QuadToTriaAdaptor* quadAdaptor =
919 dynamic_cast<StdMeshers_QuadToTriaAdaptor*>( proxyMesh.get() );
922 solidID1 = occgeom.somap.FindIndex( quadAdaptor->GetShape() );
926 PShapeIteratorPtr solidIt = helper.GetAncestors( geomFace, *sm->GetFather(), TopAbs_SOLID);
927 while ( const TopoDS_Shape * solid = solidIt->next() )
929 int id = occgeom.somap.FindIndex ( *solid );
930 if ( solidID1 && id != solidID1 ) solidID2 = id;
934 // Add ng face descriptors of meshed faces
936 ngMesh.AddFaceDescriptor (netgen::FaceDescriptor(faceNgID, solidID1, solidID2, 0));
938 // if second oreder is required, even already meshed faces must be passed to NETGEN
939 int fID = occgeom.fmap.Add( geomFace );
940 while ( fID < faceNgID ) // geomFace is already in occgeom.fmap, add a copy
941 fID = occgeom.fmap.Add( BRepBuilderAPI_Copy( geomFace, /*copyGeom=*/false ));
942 // Problem with the second order in a quadrangular mesh remains.
943 // 1) All quadrangles generated by NETGEN are moved to an inexistent face
944 // by FillSMesh() (find "AddFaceDescriptor")
945 // 2) Temporary triangles generated by StdMeshers_QuadToTriaAdaptor
946 // are on faces where quadrangles were.
947 // Due to these 2 points, wrong geom faces are used while conversion to qudratic
948 // of the mentioned above quadrangles and triangles
950 // Orient the face correctly in solidID1 (issue 0020206)
951 bool reverse = false;
953 TopoDS_Shape solid = occgeom.somap( solidID1 );
954 TopAbs_Orientation faceOriInSolid = helper.GetSubShapeOri( solid, geomFace );
955 if ( faceOriInSolid >= 0 )
957 helper.IsReversedSubMesh( TopoDS::Face( geomFace.Oriented( faceOriInSolid )));
960 // Add surface elements
962 netgen::Element2d tri(3);
963 tri.SetIndex ( faceNgID );
966 #ifdef DUMP_TRIANGLES
967 cout << "SMESH face " << helper.GetMeshDS()->ShapeToIndex( geomFace )
968 << " internal="<<isInternalFace << endl;
971 smDS = proxyMesh->GetSubMesh( geomFace );
973 SMDS_ElemIteratorPtr faces = smDS->GetElements();
974 while ( faces->more() )
976 const SMDS_MeshElement* f = faces->next();
977 if ( f->NbNodes() % 3 != 0 ) // not triangle
979 PShapeIteratorPtr solidIt=helper.GetAncestors(geomFace,*sm->GetFather(),TopAbs_SOLID);
980 if ( const TopoDS_Shape * solid = solidIt->next() )
981 sm = _mesh->GetSubMesh( *solid );
982 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
983 smError.reset( new SMESH_ComputeError(COMPERR_BAD_INPUT_MESH,"Not triangle submesh"));
984 smError->myBadElements.push_back( f );
988 for ( int i = 0; i < 3; ++i )
990 const SMDS_MeshNode* node = f->GetNode( i ), * inFaceNode=0;
992 // get node UV on face
993 int shapeID = node->getshapeId();
994 if ( helper.IsSeamShape( shapeID ))
995 if ( helper.IsSeamShape( f->GetNodeWrap( i+1 )->getshapeId() ))
996 inFaceNode = f->GetNodeWrap( i-1 );
998 inFaceNode = f->GetNodeWrap( i+1 );
999 gp_XY uv = helper.GetNodeUV( geomFace, node, inFaceNode );
1001 int ind = reverse ? 3-i : i+1;
1002 tri.GeomInfoPi(ind).u = uv.X();
1003 tri.GeomInfoPi(ind).v = uv.Y();
1004 tri.PNum (ind) = ngNodeId( node, ngMesh, nodeNgIdMap );
1007 ngMesh.AddSurfaceElement (tri);
1008 #ifdef DUMP_TRIANGLES
1009 cout << tri << endl;
1012 if ( isInternalFace )
1014 swap( tri[1], tri[2] );
1015 ngMesh.AddSurfaceElement (tri);
1016 #ifdef DUMP_TRIANGLES
1017 cout << tri << endl;
1022 if ( quadHelper ) // remember medium nodes of sub-meshes
1024 SMDS_ElemIteratorPtr faces = smDS->GetElements();
1025 while ( faces->more() )
1027 const SMDS_MeshElement* f = faces->next();
1028 if ( !quadHelper->AddTLinks( static_cast< const SMDS_MeshFace*>( f )))
1034 } // case TopAbs_FACE
1036 case TopAbs_VERTEX: { // VERTEX
1037 // --------------------------
1038 // issue 0021405. Add node only if a VERTEX is shared by a not meshed EDGE,
1039 // else netgen removes a free node and nodeVector becomes invalid
1040 PShapeIteratorPtr ansIt = helper.GetAncestors( sm->GetSubShape(),
1044 while ( const TopoDS_Shape* e = ansIt->next() )
1046 SMESH_subMesh* eSub = helper.GetMesh()->GetSubMesh( *e );
1047 if (( toAdd = ( eSub->IsEmpty() && !SMESH_Algo::isDegenerated( TopoDS::Edge( *e )))))
1052 SMDS_NodeIteratorPtr nodeIt = smDS->GetNodes();
1053 if ( nodeIt->more() )
1054 ngNodeId( nodeIt->next(), ngMesh, nodeNgIdMap );
1060 } // loop on submeshes
1063 nodeVec.resize( ngMesh.GetNP() + 1 );
1064 TNode2IdMap::iterator node_NgId, nodeNgIdEnd = nodeNgIdMap.end();
1065 for ( node_NgId = nodeNgIdMap.begin(); node_NgId != nodeNgIdEnd; ++node_NgId)
1066 nodeVec[ node_NgId->second ] = node_NgId->first;
1071 //================================================================================
1073 * \brief Duplicate mesh faces on internal geom faces
1075 //================================================================================
1077 void NETGENPlugin_Mesher::FixIntFaces(const netgen::OCCGeometry& occgeom,
1078 netgen::Mesh& ngMesh,
1079 NETGENPlugin_Internals& internalShapes)
1081 SMESHDS_Mesh* meshDS = internalShapes.getMesh().GetMeshDS();
1083 // find ng indices of internal faces
1085 for ( int ngFaceID = 1; ngFaceID <= occgeom.fmap.Extent(); ++ngFaceID )
1087 int smeshID = meshDS->ShapeToIndex( occgeom.fmap( ngFaceID ));
1088 if ( internalShapes.isInternalShape( smeshID ))
1089 ngFaceIds.insert( ngFaceID );
1091 if ( !ngFaceIds.empty() )
1094 int i, nbFaces = ngMesh.GetNSE();
1095 for (int i = 1; i <= nbFaces; ++i)
1097 netgen::Element2d elem = ngMesh.SurfaceElement(i);
1098 if ( ngFaceIds.count( elem.GetIndex() ))
1100 swap( elem[1], elem[2] );
1101 ngMesh.AddSurfaceElement (elem);
1109 //================================================================================
1110 // define gp_XY_Subtracted pointer to function calling gp_XY::Subtracted(gp_XY)
1111 gp_XY_FunPtr(Subtracted);
1112 //gp_XY_FunPtr(Added);
1114 //================================================================================
1116 * \brief Evaluate distance between two 2d points along the surface
1118 //================================================================================
1120 double evalDist( const gp_XY& uv1,
1122 const Handle(Geom_Surface)& surf,
1123 const int stopHandler=-1)
1125 if ( stopHandler > 0 ) // continue recursion
1127 gp_XY mid = SMESH_MesherHelper::GetMiddleUV( surf, uv1, uv2 );
1128 return evalDist( uv1,mid, surf, stopHandler-1 ) + evalDist( mid,uv2, surf, stopHandler-1 );
1130 double dist3D = surf->Value( uv1.X(), uv1.Y() ).Distance( surf->Value( uv2.X(), uv2.Y() ));
1131 if ( stopHandler == 0 ) // stop recursion
1134 // start recursion if necessary
1135 double dist2D = SMESH_MesherHelper::applyIn2D(surf, uv1, uv2, gp_XY_Subtracted, 0).Modulus();
1136 if ( fabs( dist3D - dist2D ) < dist2D * 1e-10 )
1137 return dist3D; // equal parametrization of a planar surface
1139 return evalDist( uv1, uv2, surf, 3 ); // start recursion
1142 //================================================================================
1144 * \brief Data of vertex internal in geom face
1146 //================================================================================
1150 gp_XY uv; //!< UV in face parametric space
1151 int ngId; //!< ng id of corrsponding node
1152 gp_XY uvClose; //!< UV of closest boundary node
1153 int ngIdClose; //!< ng id of closest boundary node
1156 //================================================================================
1158 * \brief Data of vertex internal in solid
1160 //================================================================================
1164 int ngId; //!< ng id of corresponding node
1165 int ngIdClose; //!< ng id of closest 2d mesh element
1166 int ngIdCloseN; //!< ng id of closest node of the closest 2d mesh element
1169 inline double dist2(const netgen::MeshPoint& p1, const netgen::MeshPoint& p2)
1171 return gp_Pnt( NGPOINT_COORDS(p1)).SquareDistance( gp_Pnt( NGPOINT_COORDS(p2)));
1175 //================================================================================
1177 * \brief Make netgen take internal vertices in faces into account by adding
1178 * segments including internal vertices
1180 * This function works in supposition that 1D mesh is already computed in ngMesh
1182 //================================================================================
1184 void NETGENPlugin_Mesher::AddIntVerticesInFaces(const netgen::OCCGeometry& occgeom,
1185 netgen::Mesh& ngMesh,
1186 vector<const SMDS_MeshNode*>& nodeVec,
1187 NETGENPlugin_Internals& internalShapes)
1189 if ( nodeVec.size() < ngMesh.GetNP() )
1190 nodeVec.resize( ngMesh.GetNP(), 0 );
1192 SMESHDS_Mesh* meshDS = internalShapes.getMesh().GetMeshDS();
1193 SMESH_MesherHelper helper( internalShapes.getMesh() );
1195 const map<int,list<int> >& face2Vert = internalShapes.getFacesWithVertices();
1196 map<int,list<int> >::const_iterator f2v = face2Vert.begin();
1197 for ( ; f2v != face2Vert.end(); ++f2v )
1199 const TopoDS_Face& face = TopoDS::Face( meshDS->IndexToShape( f2v->first ));
1200 if ( face.IsNull() ) continue;
1201 int faceNgID = occgeom.fmap.FindIndex (face);
1202 if ( faceNgID < 0 ) continue;
1204 TopLoc_Location loc;
1205 Handle(Geom_Surface) surf = BRep_Tool::Surface(face,loc);
1207 helper.SetSubShape( face );
1208 helper.SetElementsOnShape( true );
1210 // Get data of internal vertices and add them to ngMesh
1212 multimap< double, TIntVData > dist2VData; // sort vertices by distance from boundary nodes
1214 int i, nbSegInit = ngMesh.GetNSeg();
1216 // boundary characteristics
1217 double totSegLen2D = 0;
1220 const list<int>& iVertices = f2v->second;
1221 list<int>::const_iterator iv = iVertices.begin();
1222 for ( int nbV = 0; iv != iVertices.end(); ++iv, nbV++ )
1225 // get node on vertex
1226 const TopoDS_Vertex V = TopoDS::Vertex( meshDS->IndexToShape( *iv ));
1227 const SMDS_MeshNode * nV = SMESH_Algo::VertexNode( V, meshDS );
1230 SMESH_subMesh* sm = helper.GetMesh()->GetSubMesh( V );
1231 sm->ComputeStateEngine( SMESH_subMesh::COMPUTE );
1232 nV = SMESH_Algo::VertexNode( V, meshDS );
1233 if ( !nV ) continue;
1236 netgen::MeshPoint mp( netgen::Point<3> (nV->X(), nV->Y(), nV->Z()) );
1237 ngMesh.AddPoint ( mp, 1, netgen::EDGEPOINT );
1238 vData.ngId = ngMesh.GetNP();
1239 nodeVec.push_back( nV );
1243 vData.uv = helper.GetNodeUV( face, nV, 0, &uvOK );
1244 if ( !uvOK ) helper.CheckNodeUV( face, nV, vData.uv, BRep_Tool::Tolerance(V),/*force=*/1);
1246 // loop on all segments of the face to find the node closest to vertex and to count
1247 // average segment 2d length
1248 double closeDist2 = numeric_limits<double>::max(), dist2;
1250 for (i = 1; i <= ngMesh.GetNSeg(); ++i)
1252 netgen::Segment & seg = ngMesh.LineSegment(i);
1253 if ( seg.si != faceNgID ) continue;
1255 for ( int iEnd = 0; iEnd < 2; ++iEnd)
1257 uv[iEnd].SetCoord( seg.epgeominfo[iEnd].u, seg.epgeominfo[iEnd].v );
1258 if ( ngIdLast == seg[ iEnd ] ) continue;
1259 dist2 = helper.applyIn2D(surf, uv[iEnd], vData.uv, gp_XY_Subtracted,0).SquareModulus();
1260 if ( dist2 < closeDist2 )
1261 vData.ngIdClose = seg[ iEnd ], vData.uvClose = uv[iEnd], closeDist2 = dist2;
1262 ngIdLast = seg[ iEnd ];
1266 totSegLen2D += helper.applyIn2D(surf, uv[0], uv[1], gp_XY_Subtracted, false).Modulus();
1270 dist2VData.insert( make_pair( closeDist2, vData ));
1273 if ( totNbSeg == 0 ) break;
1274 double avgSegLen2d = totSegLen2D / totNbSeg;
1276 // Loop on vertices to add segments
1278 multimap< double, TIntVData >::iterator dist_vData = dist2VData.begin();
1279 for ( ; dist_vData != dist2VData.end(); ++dist_vData )
1281 double closeDist2 = dist_vData->first, dist2;
1282 TIntVData & vData = dist_vData->second;
1284 // try to find more close node among segments added for internal vertices
1285 for (i = nbSegInit+1; i <= ngMesh.GetNSeg(); ++i)
1287 netgen::Segment & seg = ngMesh.LineSegment(i);
1288 if ( seg.si != faceNgID ) continue;
1290 for ( int iEnd = 0; iEnd < 2; ++iEnd)
1292 uv[iEnd].SetCoord( seg.epgeominfo[iEnd].u, seg.epgeominfo[iEnd].v );
1293 dist2 = helper.applyIn2D(surf, uv[iEnd], vData.uv, gp_XY_Subtracted,0).SquareModulus();
1294 if ( dist2 < closeDist2 )
1295 vData.ngIdClose = seg[ iEnd ], vData.uvClose = uv[iEnd], closeDist2 = dist2;
1298 // decide whether to use the closest node as the second end of segment or to
1299 // create a new point
1300 int segEnd1 = vData.ngId;
1301 int segEnd2 = vData.ngIdClose; // to use closest node
1302 gp_XY uvV = vData.uv, uvP = vData.uvClose;
1303 double segLenHint = ngMesh.GetH( ngMesh.Point( vData.ngId ));
1304 double nodeDist2D = sqrt( closeDist2 );
1305 double nodeDist3D = evalDist( vData.uv, vData.uvClose, surf );
1306 bool avgLenOK = ( avgSegLen2d < 0.75 * nodeDist2D );
1307 bool hintLenOK = ( segLenHint < 0.75 * nodeDist3D );
1308 //cout << "uvV " << uvV.X() <<","<<uvV.Y() << " ";
1309 if ( hintLenOK || avgLenOK )
1311 // create a point between the closest node and V
1314 double r = min( 0.5, ( hintLenOK ? segLenHint/nodeDist3D : avgSegLen2d/nodeDist2D ));
1315 // direction from V to closet node in 2D
1316 gp_Dir2d v2n( helper.applyIn2D(surf, uvP, uvV, gp_XY_Subtracted, false ));
1318 uvP = vData.uv + r * nodeDist2D * v2n.XY();
1319 gp_Pnt P = surf->Value( uvP.X(), uvP.Y() ).Transformed( loc );
1321 netgen::MeshPoint mp( netgen::Point<3> (P.X(), P.Y(), P.Z()));
1322 ngMesh.AddPoint ( mp, 1, netgen::EDGEPOINT );
1323 segEnd2 = ngMesh.GetNP();
1324 //cout << "Middle " << r << " uv " << uvP.X() << "," << uvP.Y() << "( " << ngMesh.Point(segEnd2).X()<<","<<ngMesh.Point(segEnd2).Y()<<","<<ngMesh.Point(segEnd2).Z()<<" )"<< endl;
1325 SMDS_MeshNode * nP = helper.AddNode(P.X(), P.Y(), P.Z());
1326 nodeVec.push_back( nP );
1328 //else cout << "at Node " << " uv " << uvP.X() << "," << uvP.Y() << endl;
1331 netgen::Segment seg;
1333 if ( segEnd1 > segEnd2 ) swap( segEnd1, segEnd2 ), swap( uvV, uvP );
1334 seg[0] = segEnd1; // ng node id
1335 seg[1] = segEnd2; // ng node id
1336 seg.edgenr = ngMesh.GetNSeg() + 1;// segment id
1339 seg.epgeominfo[ 0 ].dist = 0; // param on curve
1340 seg.epgeominfo[ 0 ].u = uvV.X();
1341 seg.epgeominfo[ 0 ].v = uvV.Y();
1342 seg.epgeominfo[ 1 ].dist = 1; // param on curve
1343 seg.epgeominfo[ 1 ].u = uvP.X();
1344 seg.epgeominfo[ 1 ].v = uvP.Y();
1346 // seg.epgeominfo[ 0 ].edgenr = 10; // = geom.emap.FindIndex(edge);
1347 // seg.epgeominfo[ 1 ].edgenr = 10; // = geom.emap.FindIndex(edge);
1349 ngMesh.AddSegment (seg);
1351 // add reverse segment
1352 swap (seg[0], seg[1]);
1353 swap( seg.epgeominfo[0], seg.epgeominfo[1] );
1354 seg.edgenr = ngMesh.GetNSeg() + 1; // segment id
1355 ngMesh.AddSegment (seg);
1361 //================================================================================
1363 * \brief Make netgen take internal vertices in solids into account by adding
1364 * faces including internal vertices
1366 * This function works in supposition that 2D mesh is already computed in ngMesh
1368 //================================================================================
1370 void NETGENPlugin_Mesher::AddIntVerticesInSolids(const netgen::OCCGeometry& occgeom,
1371 netgen::Mesh& ngMesh,
1372 vector<const SMDS_MeshNode*>& nodeVec,
1373 NETGENPlugin_Internals& internalShapes)
1375 #ifdef DUMP_TRIANGLES_SCRIPT
1376 // create a python script making a mesh containing triangles added for internal vertices
1377 ofstream py(DUMP_TRIANGLES_SCRIPT);
1378 py << "import SMESH"<< endl
1379 << "from salome.smesh import smeshBuilder"<<endl
1380 << "smesh = smeshBuilder.New(salome.myStudy)"<<endl
1381 << "m = smesh.Mesh(name='triangles')" << endl;
1383 if ( nodeVec.size() < ngMesh.GetNP() )
1384 nodeVec.resize( ngMesh.GetNP(), 0 );
1386 SMESHDS_Mesh* meshDS = internalShapes.getMesh().GetMeshDS();
1387 SMESH_MesherHelper helper( internalShapes.getMesh() );
1389 const map<int,list<int> >& so2Vert = internalShapes.getSolidsWithVertices();
1390 map<int,list<int> >::const_iterator s2v = so2Vert.begin();
1391 for ( ; s2v != so2Vert.end(); ++s2v )
1393 const TopoDS_Shape& solid = meshDS->IndexToShape( s2v->first );
1394 if ( solid.IsNull() ) continue;
1395 int solidNgID = occgeom.somap.FindIndex (solid);
1396 if ( solidNgID < 0 && !occgeom.somap.IsEmpty() ) continue;
1398 helper.SetSubShape( solid );
1399 helper.SetElementsOnShape( true );
1401 // find ng indices of faces within the solid
1403 for (TopExp_Explorer fExp(solid, TopAbs_FACE); fExp.More(); fExp.Next() )
1404 ngFaceIds.insert( occgeom.fmap.FindIndex( fExp.Current() ));
1405 if ( ngFaceIds.size() == 1 && *ngFaceIds.begin() == 0 )
1406 ngFaceIds.insert( 1 );
1408 // Get data of internal vertices and add them to ngMesh
1410 multimap< double, TIntVSoData > dist2VData; // sort vertices by distance from ng faces
1412 int i, nbFaceInit = ngMesh.GetNSE();
1414 // boundary characteristics
1415 double totSegLen = 0;
1418 const list<int>& iVertices = s2v->second;
1419 list<int>::const_iterator iv = iVertices.begin();
1420 for ( int nbV = 0; iv != iVertices.end(); ++iv, nbV++ )
1423 const TopoDS_Vertex V = TopoDS::Vertex( meshDS->IndexToShape( *iv ));
1425 // get node on vertex
1426 const SMDS_MeshNode * nV = SMESH_Algo::VertexNode( V, meshDS );
1429 SMESH_subMesh* sm = helper.GetMesh()->GetSubMesh( V );
1430 sm->ComputeStateEngine( SMESH_subMesh::COMPUTE );
1431 nV = SMESH_Algo::VertexNode( V, meshDS );
1432 if ( !nV ) continue;
1435 netgen::MeshPoint mpV( netgen::Point<3> (nV->X(), nV->Y(), nV->Z()) );
1436 ngMesh.AddPoint ( mpV, 1, netgen::FIXEDPOINT );
1437 vData.ngId = ngMesh.GetNP();
1438 nodeVec.push_back( nV );
1440 // loop on all 2d elements to find the one closest to vertex and to count
1441 // average segment length
1442 double closeDist2 = numeric_limits<double>::max(), avgDist2;
1443 for (i = 1; i <= ngMesh.GetNSE(); ++i)
1445 const netgen::Element2d& elem = ngMesh.SurfaceElement(i);
1446 if ( !ngFaceIds.count( elem.GetIndex() )) continue;
1448 multimap< double, int> dist2nID; // sort nodes of element by distance from V
1449 for ( int j = 0; j < elem.GetNP(); ++j)
1451 netgen::MeshPoint mp = ngMesh.Point( elem[j] );
1452 double d2 = dist2( mpV, mp );
1453 dist2nID.insert( make_pair( d2, elem[j] ));
1454 avgDist2 += d2 / elem.GetNP();
1456 totNbSeg++, totSegLen+= sqrt( dist2( mp, ngMesh.Point( elem[(j+1)%elem.GetNP()])));
1458 double dist = dist2nID.begin()->first; //avgDist2;
1459 if ( dist < closeDist2 )
1460 vData.ngIdClose= i, vData.ngIdCloseN= dist2nID.begin()->second, closeDist2= dist;
1462 dist2VData.insert( make_pair( closeDist2, vData ));
1465 if ( totNbSeg == 0 ) break;
1466 double avgSegLen = totSegLen / totNbSeg;
1468 // Loop on vertices to add triangles
1470 multimap< double, TIntVSoData >::iterator dist_vData = dist2VData.begin();
1471 for ( ; dist_vData != dist2VData.end(); ++dist_vData )
1473 double closeDist2 = dist_vData->first;
1474 TIntVSoData & vData = dist_vData->second;
1476 const netgen::MeshPoint& mpV = ngMesh.Point( vData.ngId );
1478 // try to find more close face among ones added for internal vertices
1479 for (i = nbFaceInit+1; i <= ngMesh.GetNSE(); ++i)
1481 double avgDist2 = 0;
1482 multimap< double, int> dist2nID;
1483 const netgen::Element2d& elem = ngMesh.SurfaceElement(i);
1484 for ( int j = 0; j < elem.GetNP(); ++j)
1486 double d = dist2( mpV, ngMesh.Point( elem[j] ));
1487 dist2nID.insert( make_pair( d, elem[j] ));
1488 avgDist2 += d / elem.GetNP();
1489 if ( avgDist2 < closeDist2 )
1490 vData.ngIdClose= i, vData.ngIdCloseN= dist2nID.begin()->second, closeDist2= avgDist2;
1493 // sort nodes of the closest face by angle with vector from V to the closest node
1494 const double tol = numeric_limits<double>::min();
1495 map< double, int > angle2ID;
1496 const netgen::Element2d& closeFace = ngMesh.SurfaceElement( vData.ngIdClose );
1497 netgen::MeshPoint mp[2];
1498 mp[0] = ngMesh.Point( vData.ngIdCloseN );
1499 gp_XYZ p1( NGPOINT_COORDS( mp[0] ));
1500 gp_XYZ pV( NGPOINT_COORDS( mpV ));
1501 gp_Vec v2p1( pV, p1 );
1502 double distN1 = v2p1.Magnitude();
1503 if ( distN1 <= tol ) continue;
1505 for ( int j = 0; j < closeFace.GetNP(); ++j)
1507 mp[1] = ngMesh.Point( closeFace[j] );
1508 gp_Vec v2p( pV, gp_Pnt( NGPOINT_COORDS( mp[1] )) );
1509 angle2ID.insert( make_pair( v2p1.Angle( v2p ), closeFace[j]));
1511 // get node with angle of 60 degrees or greater
1512 map< double, int >::iterator angle_id = angle2ID.lower_bound( 60. * M_PI / 180. );
1513 if ( angle_id == angle2ID.end() ) angle_id = --angle2ID.end();
1514 const double minAngle = 30. * M_PI / 180.;
1515 const double angle = angle_id->first;
1516 bool angleOK = ( angle > minAngle );
1518 // find points to create a triangle
1519 netgen::Element2d tri(3);
1521 tri[0] = vData.ngId;
1522 tri[1] = vData.ngIdCloseN; // to use the closest nodes
1523 tri[2] = angle_id->second; // to use the node with best angle
1525 // decide whether to use the closest node and the node with best angle or to create new ones
1526 for ( int isBestAngleN = 0; isBestAngleN < 2; ++isBestAngleN )
1528 bool createNew = !angleOK, distOK = true;
1530 int triInd = isBestAngleN ? 2 : 1;
1531 mp[isBestAngleN] = ngMesh.Point( tri[triInd] );
1536 double distN2 = sqrt( dist2( mpV, mp[isBestAngleN]));
1537 createNew = ( fabs( distN2 - distN1 ) > 0.25 * distN1 );
1539 else if ( angle < tol )
1541 v2p1.SetX( v2p1.X() + 1e-3 );
1547 double segLenHint = ngMesh.GetH( ngMesh.Point( vData.ngId ));
1548 bool avgLenOK = ( avgSegLen < 0.75 * distN1 );
1549 bool hintLenOK = ( segLenHint < 0.75 * distN1 );
1550 createNew = (createNew || avgLenOK || hintLenOK );
1551 // we create a new node not closer than 0.5 to the closest face
1552 // in order not to clash with other close face
1553 double r = min( 0.5, ( hintLenOK ? segLenHint : avgSegLen ) / distN1 );
1554 distFromV = r * distN1;
1558 // create a new point, between the node and the vertex if angleOK
1559 gp_XYZ p( NGPOINT_COORDS( mp[isBestAngleN] ));
1560 gp_Vec v2p( pV, p ); v2p.Normalize();
1561 if ( isBestAngleN && !angleOK )
1562 p = p1 + gp_Dir( v2p.XYZ() - v2p1.XYZ()).XYZ() * distN1 * 0.95;
1564 p = pV + v2p.XYZ() * distFromV;
1566 if ( !isBestAngleN ) p1 = p, distN1 = distFromV;
1568 mp[isBestAngleN].SetPoint( netgen::Point<3> (p.X(), p.Y(), p.Z()));
1569 ngMesh.AddPoint ( mp[isBestAngleN], 1, netgen::SURFACEPOINT );
1570 tri[triInd] = ngMesh.GetNP();
1571 nodeVec.push_back( helper.AddNode( p.X(), p.Y(), p.Z()) );
1574 ngMesh.AddSurfaceElement (tri);
1575 swap( tri[1], tri[2] );
1576 ngMesh.AddSurfaceElement (tri);
1578 #ifdef DUMP_TRIANGLES_SCRIPT
1579 py << "n1 = m.AddNode( "<< mpV(0)<<", "<< mpV(1)<<", "<< mpV(2)<<") "<< endl
1580 << "n2 = m.AddNode( "<< mp[0](0)<<", "<< mp[0](1)<<", "<< mp[0](2)<<") "<< endl
1581 << "n3 = m.AddNode( "<< mp[1](0)<<", "<< mp[1](1)<<", "<< mp[1](2)<<" )" << endl
1582 << "m.AddFace([n1,n2,n3])" << endl;
1584 } // loop on internal vertices of a solid
1586 } // loop on solids with internal vertices
1589 //================================================================================
1591 * \brief Fill netgen mesh with segments of a FACE
1592 * \param ngMesh - netgen mesh
1593 * \param geom - container of OCCT geometry to mesh
1594 * \param wires - data of nodes on FACE boundary
1595 * \param helper - mesher helper holding the FACE
1596 * \param nodeVec - vector of nodes in which node index == netgen ID
1597 * \retval SMESH_ComputeErrorPtr - error description
1599 //================================================================================
1601 SMESH_ComputeErrorPtr
1602 NETGENPlugin_Mesher::AddSegmentsToMesh(netgen::Mesh& ngMesh,
1603 netgen::OCCGeometry& geom,
1604 const TSideVector& wires,
1605 SMESH_MesherHelper& helper,
1606 vector< const SMDS_MeshNode* > & nodeVec,
1607 const bool overrideMinH)
1609 // ----------------------------
1610 // Check wires and count nodes
1611 // ----------------------------
1613 for ( int iW = 0; iW < wires.size(); ++iW )
1615 StdMeshers_FaceSidePtr wire = wires[ iW ];
1616 if ( wire->MissVertexNode() )
1618 // Commented for issue 0020960. It worked for the case, let's wait for case where it doesn't.
1619 // It seems that there is no reason for this limitation
1621 // (new SMESH_ComputeError(COMPERR_BAD_INPUT_MESH, "Missing nodes on vertices"));
1623 const vector<UVPtStruct>& uvPtVec = wire->GetUVPtStruct();
1624 if ( uvPtVec.size() != wire->NbPoints() )
1625 return SMESH_ComputeError::New(COMPERR_BAD_INPUT_MESH,
1626 SMESH_Comment("Unexpected nb of points on wire ") << iW
1627 << ": " << uvPtVec.size()<<" != "<<wire->NbPoints());
1628 nbNodes += wire->NbPoints();
1630 nodeVec.reserve( nodeVec.size() + nbNodes + 1 );
1631 if ( nodeVec.empty() )
1632 nodeVec.push_back( 0 );
1634 // -----------------
1636 // -----------------
1638 const bool wasNgMeshEmpty = ( ngMesh.GetNP() < 1 ); /* true => this method is called by
1639 NETGENPlugin_NETGEN_2D_ONLY */
1641 // map for nodes on vertices since they can be shared between wires
1642 // ( issue 0020676, face_int_box.brep) and nodes built by NETGEN
1643 map<const SMDS_MeshNode*, int > node2ngID;
1644 if ( !wasNgMeshEmpty ) // fill node2ngID with nodes built by NETGEN
1646 set< int > subIDs; // ids of sub-shapes of the FACE
1647 for ( int iW = 0; iW < wires.size(); ++iW )
1649 StdMeshers_FaceSidePtr wire = wires[ iW ];
1650 for ( int iE = 0, nbE = wire->NbEdges(); iE < nbE; ++iE )
1652 subIDs.insert( wire->EdgeID( iE ));
1653 subIDs.insert( helper.GetMeshDS()->ShapeToIndex( wire->FirstVertex( iE )));
1656 for ( size_t ngID = 1; ngID < nodeVec.size(); ++ngID )
1657 if ( subIDs.count( nodeVec[ngID]->getshapeId() ))
1658 node2ngID.insert( make_pair( nodeVec[ngID], ngID ));
1661 const int solidID = 0, faceID = geom.fmap.FindIndex( helper.GetSubShape() );
1662 if ( ngMesh.GetNFD() < 1 )
1663 ngMesh.AddFaceDescriptor (netgen::FaceDescriptor(faceID, solidID, solidID, 0));
1665 for ( int iW = 0; iW < wires.size(); ++iW )
1667 StdMeshers_FaceSidePtr wire = wires[ iW ];
1668 const vector<UVPtStruct>& uvPtVec = wire->GetUVPtStruct();
1669 const int nbSegments = wire->NbPoints() - 1;
1671 // assure the 1st node to be in node2ngID, which is needed to correctly
1672 // "close chain of segments" (see below) in case if the 1st node is not
1673 // onVertex because it is on a Viscous layer
1674 node2ngID.insert( make_pair( uvPtVec[ 0 ].node, ngMesh.GetNP() + 1 ));
1676 // compute length of every segment
1677 vector<double> segLen( nbSegments );
1678 for ( int i = 0; i < nbSegments; ++i )
1679 segLen[i] = SMESH_TNodeXYZ( uvPtVec[ i ].node ).Distance( uvPtVec[ i+1 ].node );
1681 int edgeID = 1, posID = -2;
1682 bool isInternalWire = false;
1683 double vertexNormPar = 0;
1684 const int prevNbNGSeg = ngMesh.GetNSeg();
1685 for ( int i = 0; i < nbSegments; ++i ) // loop on segments
1687 // Add the first point of a segment
1689 const SMDS_MeshNode * n = uvPtVec[ i ].node;
1690 const int posShapeID = n->getshapeId();
1691 bool onVertex = ( n->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX );
1692 bool onEdge = ( n->GetPosition()->GetTypeOfPosition() == SMDS_TOP_EDGE );
1694 // skip nodes on degenerated edges
1695 if ( helper.IsDegenShape( posShapeID ) &&
1696 helper.IsDegenShape( uvPtVec[ i+1 ].node->getshapeId() ))
1699 int ngID1 = ngMesh.GetNP() + 1, ngID2 = ngID1+1;
1700 if ( onVertex || ( !wasNgMeshEmpty && onEdge ))
1701 ngID1 = node2ngID.insert( make_pair( n, ngID1 )).first->second;
1702 if ( ngID1 > ngMesh.GetNP() )
1704 netgen::MeshPoint mp( netgen::Point<3> (n->X(), n->Y(), n->Z()) );
1705 ngMesh.AddPoint ( mp, 1, netgen::EDGEPOINT );
1706 nodeVec.push_back( n );
1708 else // n is in ngMesh already, and ngID2 in prev segment is wrong
1710 ngID2 = ngMesh.GetNP() + 1;
1711 if ( i > 0 ) // prev segment belongs to same wire
1713 netgen::Segment& prevSeg = ngMesh.LineSegment( ngMesh.GetNSeg() );
1720 netgen::Segment seg;
1722 seg[0] = ngID1; // ng node id
1723 seg[1] = ngID2; // ng node id
1724 seg.edgenr = ngMesh.GetNSeg() + 1; // ng segment id
1725 seg.si = faceID; // = geom.fmap.FindIndex (face);
1727 for ( int iEnd = 0; iEnd < 2; ++iEnd)
1729 const UVPtStruct& pnt = uvPtVec[ i + iEnd ];
1731 seg.epgeominfo[ iEnd ].dist = pnt.param; // param on curve
1732 seg.epgeominfo[ iEnd ].u = pnt.u;
1733 seg.epgeominfo[ iEnd ].v = pnt.v;
1735 // find out edge id and node parameter on edge
1736 onVertex = ( pnt.normParam + 1e-10 > vertexNormPar );
1737 if ( onVertex || posShapeID != posID )
1740 double normParam = pnt.normParam;
1742 normParam = 0.5 * ( uvPtVec[ i ].normParam + uvPtVec[ i+1 ].normParam );
1743 int edgeIndexInWire = wire->EdgeIndex( normParam );
1744 vertexNormPar = wire->LastParameter( edgeIndexInWire );
1745 const TopoDS_Edge& edge = wire->Edge( edgeIndexInWire );
1746 edgeID = geom.emap.FindIndex( edge );
1748 isInternalWire = ( edge.Orientation() == TopAbs_INTERNAL );
1749 // if ( onVertex ) // param on curve is different on each of two edges
1750 // seg.epgeominfo[ iEnd ].dist = helper.GetNodeU( edge, pnt.node );
1752 seg.epgeominfo[ iEnd ].edgenr = edgeID; // = geom.emap.FindIndex(edge);
1755 ngMesh.AddSegment (seg);
1757 // restrict size of elements near the segment
1758 SMESH_TNodeXYZ np1( n ), np2( uvPtVec[ i+1 ].node );
1759 // get an average size of adjacent segments to avoid sharp change of
1760 // element size (regression on issue 0020452, note 0010898)
1761 int iPrev = SMESH_MesherHelper::WrapIndex( i-1, nbSegments );
1762 int iNext = SMESH_MesherHelper::WrapIndex( i+1, nbSegments );
1763 double sumH = segLen[ iPrev ] + segLen[ i ] + segLen[ iNext ];
1764 int nbSeg = ( int( segLen[ iPrev ] > sumH / 100.) +
1765 int( segLen[ i ] > sumH / 100.) +
1766 int( segLen[ iNext ] > sumH / 100.));
1768 RestrictLocalSize( ngMesh, 0.5*(np1+np2), sumH / nbSeg, overrideMinH );
1770 if ( isInternalWire )
1772 swap (seg[0], seg[1]);
1773 swap( seg.epgeominfo[0], seg.epgeominfo[1] );
1774 seg.edgenr = ngMesh.GetNSeg() + 1; // segment id
1775 ngMesh.AddSegment (seg);
1777 } // loop on segments on a wire
1779 // close chain of segments
1780 if ( nbSegments > 0 )
1782 netgen::Segment& lastSeg = ngMesh.LineSegment( ngMesh.GetNSeg() - int( isInternalWire));
1783 const SMDS_MeshNode * lastNode = uvPtVec.back().node;
1784 lastSeg[1] = node2ngID.insert( make_pair( lastNode, lastSeg[1] )).first->second;
1785 if ( lastSeg[1] > ngMesh.GetNP() )
1787 netgen::MeshPoint mp( netgen::Point<3> (lastNode->X(), lastNode->Y(), lastNode->Z()) );
1788 ngMesh.AddPoint ( mp, 1, netgen::EDGEPOINT );
1789 nodeVec.push_back( lastNode );
1791 if ( isInternalWire )
1793 netgen::Segment& realLastSeg = ngMesh.LineSegment( ngMesh.GetNSeg() );
1794 realLastSeg[0] = lastSeg[1];
1798 #ifdef DUMP_SEGMENTS
1799 cout << "BEGIN WIRE " << iW << endl;
1800 for ( int i = prevNbNGSeg+1; i <= ngMesh.GetNSeg(); ++i )
1802 netgen::Segment& seg = ngMesh.LineSegment( i );
1804 netgen::Segment& prevSeg = ngMesh.LineSegment( i-1 );
1805 if ( seg[0] == prevSeg[1] && seg[1] == prevSeg[0] )
1807 cout << "Segment: " << seg.edgenr << endl << "\tis REVRESE of the previous one" << endl;
1811 cout << "Segment: " << seg.edgenr << endl
1812 << "\tp1: " << seg[0] << endl
1813 << "\tp2: " << seg[1] << endl
1814 << "\tp0 param: " << seg.epgeominfo[ 0 ].dist << endl
1815 << "\tp0 uv: " << seg.epgeominfo[ 0 ].u <<", "<< seg.epgeominfo[ 0 ].v << endl
1816 << "\tp0 edge: " << seg.epgeominfo[ 0 ].edgenr << endl
1817 << "\tp1 param: " << seg.epgeominfo[ 1 ].dist << endl
1818 << "\tp1 uv: " << seg.epgeominfo[ 1 ].u <<", "<< seg.epgeominfo[ 1 ].v << endl
1819 << "\tp1 edge: " << seg.epgeominfo[ 1 ].edgenr << endl;
1821 cout << "--END WIRE " << iW << endl;
1824 } // loop on WIREs of a FACE
1826 // add a segment instead of an internal vertex
1827 if ( wasNgMeshEmpty )
1829 NETGENPlugin_Internals intShapes( *helper.GetMesh(), helper.GetSubShape(), /*is3D=*/false );
1830 AddIntVerticesInFaces( geom, ngMesh, nodeVec, intShapes );
1832 ngMesh.CalcSurfacesOfNode();
1837 //================================================================================
1839 * \brief Fill SMESH mesh according to contents of netgen mesh
1840 * \param occgeo - container of OCCT geometry to mesh
1841 * \param ngMesh - netgen mesh
1842 * \param initState - bn of entities in netgen mesh before computing
1843 * \param sMesh - SMESH mesh to fill in
1844 * \param nodeVec - vector of nodes in which node index == netgen ID
1845 * \param comment - returns problem description
1846 * \param quadHelper - holder of medium nodes of sub-meshes
1847 * \retval int - error
1849 //================================================================================
1851 int NETGENPlugin_Mesher::FillSMesh(const netgen::OCCGeometry& occgeo,
1852 netgen::Mesh& ngMesh,
1853 const NETGENPlugin_ngMeshInfo& initState,
1855 std::vector<const SMDS_MeshNode*>& nodeVec,
1856 SMESH_Comment& comment,
1857 SMESH_MesherHelper* quadHelper)
1859 int nbNod = ngMesh.GetNP();
1860 int nbSeg = ngMesh.GetNSeg();
1861 int nbFac = ngMesh.GetNSE();
1862 int nbVol = ngMesh.GetNE();
1864 SMESHDS_Mesh* meshDS = sMesh.GetMeshDS();
1866 // quadHelper is used for either
1867 // 1) making quadratic elements when a lower dimention mesh is loaded
1868 // to SMESH before convertion to quadratic by NETGEN
1869 // 2) sewing of quadratic elements with quadratic elements of sub-meshes
1870 if ( quadHelper && !quadHelper->GetIsQuadratic() && quadHelper->GetTLinkNodeMap().empty() )
1873 // -------------------------------------
1874 // Create and insert nodes into nodeVec
1875 // -------------------------------------
1877 nodeVec.resize( nbNod + 1 );
1878 int i, nbInitNod = initState._nbNodes;
1879 for (i = nbInitNod+1; i <= nbNod; ++i )
1881 const netgen::MeshPoint& ngPoint = ngMesh.Point(i);
1882 SMDS_MeshNode* node = NULL;
1883 TopoDS_Vertex aVert;
1884 // First, netgen creates nodes on vertices in occgeo.vmap,
1885 // so node index corresponds to vertex index
1886 // but (issue 0020776) netgen does not create nodes with equal coordinates
1887 if ( i-nbInitNod <= occgeo.vmap.Extent() )
1889 gp_Pnt p ( NGPOINT_COORDS(ngPoint) );
1890 for (int iV = i-nbInitNod; aVert.IsNull() && iV <= occgeo.vmap.Extent(); ++iV)
1892 aVert = TopoDS::Vertex( occgeo.vmap( iV ));
1893 gp_Pnt pV = BRep_Tool::Pnt( aVert );
1894 if ( p.SquareDistance( pV ) > 1e-20 )
1897 node = const_cast<SMDS_MeshNode*>( SMESH_Algo::VertexNode( aVert, meshDS ));
1900 if (!node) // node not found on vertex
1902 node = meshDS->AddNode( NGPOINT_COORDS( ngPoint ));
1903 if (!aVert.IsNull())
1904 meshDS->SetNodeOnVertex(node, aVert);
1909 // -------------------------------------------
1910 // Create mesh segments along geometric edges
1911 // -------------------------------------------
1913 int nbInitSeg = initState._nbSegments;
1914 for (i = nbInitSeg+1; i <= nbSeg; ++i )
1916 const netgen::Segment& seg = ngMesh.LineSegment(i);
1918 int pinds[3] = { seg.pnums[0], seg.pnums[1], seg.pnums[2] };
1921 for (int j=0; j < 3; ++j)
1923 int pind = pinds[j];
1924 if (pind <= 0 || !nodeVec_ACCESS(pind))
1932 int aGeomEdgeInd = seg.epgeominfo[j].edgenr;
1933 if (aGeomEdgeInd > 0 && aGeomEdgeInd <= occgeo.emap.Extent())
1934 aEdge = TopoDS::Edge(occgeo.emap(aGeomEdgeInd));
1936 param = seg.epgeominfo[j].dist;
1939 else // middle point
1941 param = param2 * 0.5;
1943 if (!aEdge.IsNull() && nodeVec_ACCESS(pind)->getshapeId() < 1)
1945 meshDS->SetNodeOnEdge(nodeVec_ACCESS(pind), aEdge, param);
1950 SMDS_MeshEdge* edge = 0;
1951 if (nbp == 2) // second order ?
1953 if ( meshDS->FindEdge( nodeVec_ACCESS(pinds[0]), nodeVec_ACCESS(pinds[1])))
1955 if ( quadHelper ) // final mesh must be quadratic
1956 edge = quadHelper->AddEdge(nodeVec_ACCESS(pinds[0]), nodeVec_ACCESS(pinds[1]));
1958 edge = meshDS->AddEdge(nodeVec_ACCESS(pinds[0]), nodeVec_ACCESS(pinds[1]));
1962 if ( meshDS->FindEdge( nodeVec_ACCESS(pinds[0]), nodeVec_ACCESS(pinds[1]),
1963 nodeVec_ACCESS(pinds[2])))
1965 edge = meshDS->AddEdge(nodeVec_ACCESS(pinds[0]), nodeVec_ACCESS(pinds[1]),
1966 nodeVec_ACCESS(pinds[2]));
1970 if ( comment.empty() ) comment << "Cannot create a mesh edge";
1971 MESSAGE("Cannot create a mesh edge");
1972 nbSeg = nbFac = nbVol = 0;
1975 if ( !aEdge.IsNull() && edge->getshapeId() < 1 )
1976 meshDS->SetMeshElementOnShape(edge, aEdge);
1978 else if ( comment.empty() )
1980 comment << "Invalid netgen segment #" << i;
1984 // ----------------------------------------
1985 // Create mesh faces along geometric faces
1986 // ----------------------------------------
1988 int nbInitFac = initState._nbFaces;
1989 int quadFaceID = ngMesh.GetNFD() + 1;
1990 if ( nbInitFac < nbFac )
1991 // add a faces descriptor to exclude qudrangle elements generated by NETGEN
1992 // from computation of 3D mesh
1993 ngMesh.AddFaceDescriptor (netgen::FaceDescriptor(quadFaceID, /*solid1=*/0, /*solid2=*/0, 0));
1995 vector<const SMDS_MeshNode*> nodes;
1996 for (i = nbInitFac+1; i <= nbFac; ++i )
1998 const netgen::Element2d& elem = ngMesh.SurfaceElement(i);
1999 int aGeomFaceInd = elem.GetIndex();
2001 if (aGeomFaceInd > 0 && aGeomFaceInd <= occgeo.fmap.Extent())
2002 aFace = TopoDS::Face(occgeo.fmap(aGeomFaceInd));
2004 for (int j=1; j <= elem.GetNP(); ++j)
2006 int pind = elem.PNum(j);
2007 if ( pind < 1 || pind >= nodeVec.size() )
2009 if ( SMDS_MeshNode* node = nodeVec_ACCESS(pind))
2011 nodes.push_back( node );
2012 if (!aFace.IsNull() && node->getshapeId() < 1)
2014 const netgen::PointGeomInfo& pgi = elem.GeomInfoPi(j);
2015 meshDS->SetNodeOnFace(node, aFace, pgi.u, pgi.v);
2019 if ( nodes.size() != elem.GetNP() )
2021 if ( comment.empty() )
2022 comment << "Invalid netgen 2d element #" << i;
2023 continue; // bad node ids
2025 SMDS_MeshFace* face = NULL;
2026 switch (elem.GetType())
2029 if ( quadHelper ) // final mesh must be quadratic
2030 face = quadHelper->AddFace(nodes[0],nodes[1],nodes[2]);
2032 face = meshDS->AddFace(nodes[0],nodes[1],nodes[2]);
2035 if ( quadHelper ) // final mesh must be quadratic
2036 face = quadHelper->AddFace(nodes[0],nodes[1],nodes[2],nodes[3]);
2038 face = meshDS->AddFace(nodes[0],nodes[1],nodes[2],nodes[3]);
2039 // exclude qudrangle elements from computation of 3D mesh
2040 const_cast< netgen::Element2d& >( elem ).SetIndex( quadFaceID );
2043 nodes[5] = mediumNode( nodes[0],nodes[1],nodes[5], quadHelper );
2044 nodes[3] = mediumNode( nodes[1],nodes[2],nodes[3], quadHelper );
2045 nodes[4] = mediumNode( nodes[2],nodes[0],nodes[4], quadHelper );
2046 face = meshDS->AddFace(nodes[0],nodes[1],nodes[2],nodes[5],nodes[3],nodes[4]);
2049 nodes[4] = mediumNode( nodes[0],nodes[1],nodes[4], quadHelper );
2050 nodes[7] = mediumNode( nodes[1],nodes[2],nodes[7], quadHelper );
2051 nodes[5] = mediumNode( nodes[2],nodes[3],nodes[5], quadHelper );
2052 nodes[6] = mediumNode( nodes[3],nodes[0],nodes[6], quadHelper );
2053 face = meshDS->AddFace(nodes[0],nodes[1],nodes[2],nodes[3],
2054 nodes[4],nodes[7],nodes[5],nodes[6]);
2055 // exclude qudrangle elements from computation of 3D mesh
2056 const_cast< netgen::Element2d& >( elem ).SetIndex( quadFaceID );
2059 MESSAGE("NETGEN created a face of unexpected type, ignoring");
2064 if ( comment.empty() ) comment << "Cannot create a mesh face";
2065 MESSAGE("Cannot create a mesh face");
2066 nbSeg = nbFac = nbVol = 0;
2069 if (!aFace.IsNull())
2070 meshDS->SetMeshElementOnShape(face, aFace);
2073 // ------------------
2074 // Create tetrahedra
2075 // ------------------
2077 for (i = 1; i <= nbVol; ++i)
2079 const netgen::Element& elem = ngMesh.VolumeElement(i);
2080 int aSolidInd = elem.GetIndex();
2081 TopoDS_Solid aSolid;
2082 if (aSolidInd > 0 && aSolidInd <= occgeo.somap.Extent())
2083 aSolid = TopoDS::Solid(occgeo.somap(aSolidInd));
2085 for (int j=1; j <= elem.GetNP(); ++j)
2087 int pind = elem.PNum(j);
2088 if ( pind < 1 || pind >= nodeVec.size() )
2090 if ( SMDS_MeshNode* node = nodeVec_ACCESS(pind) )
2092 nodes.push_back(node);
2093 if ( !aSolid.IsNull() && node->getshapeId() < 1 )
2094 meshDS->SetNodeInVolume(node, aSolid);
2097 if ( nodes.size() != elem.GetNP() )
2099 if ( comment.empty() )
2100 comment << "Invalid netgen 3d element #" << i;
2103 SMDS_MeshVolume* vol = NULL;
2104 switch (elem.GetType())
2107 vol = meshDS->AddVolume(nodes[0],nodes[1],nodes[2],nodes[3]);
2110 nodes[4] = mediumNode( nodes[0],nodes[1],nodes[4], quadHelper );
2111 nodes[7] = mediumNode( nodes[1],nodes[2],nodes[7], quadHelper );
2112 nodes[5] = mediumNode( nodes[2],nodes[0],nodes[5], quadHelper );
2113 nodes[6] = mediumNode( nodes[0],nodes[3],nodes[6], quadHelper );
2114 nodes[8] = mediumNode( nodes[1],nodes[3],nodes[8], quadHelper );
2115 nodes[9] = mediumNode( nodes[2],nodes[3],nodes[9], quadHelper );
2116 vol = meshDS->AddVolume(nodes[0],nodes[1],nodes[2],nodes[3],
2117 nodes[4],nodes[7],nodes[5],nodes[6],nodes[8],nodes[9]);
2120 MESSAGE("NETGEN created a volume of unexpected type, ignoring");
2125 if ( comment.empty() ) comment << "Cannot create a mesh volume";
2126 MESSAGE("Cannot create a mesh volume");
2127 nbSeg = nbFac = nbVol = 0;
2130 if (!aSolid.IsNull())
2131 meshDS->SetMeshElementOnShape(vol, aSolid);
2133 return comment.empty() ? 0 : 1;
2138 //================================================================================
2140 * \brief Restrict size of elements on the given edge
2142 //================================================================================
2144 void setLocalSize(const TopoDS_Edge& edge,
2148 const int nb = 1000;
2149 Standard_Real u1, u2;
2150 Handle(Geom_Curve) curve = BRep_Tool::Curve(edge, u1, u2);
2151 if ( curve.IsNull() )
2153 TopoDS_Iterator vIt( edge );
2154 if ( !vIt.More() ) return;
2155 gp_Pnt p = BRep_Tool::Pnt( TopoDS::Vertex( vIt.Value() ));
2156 NETGENPlugin_Mesher::RestrictLocalSize( mesh, p.XYZ(), size );
2160 Standard_Real delta = (u2-u1)/nb;
2161 for(int i=0; i<nb; i++)
2163 Standard_Real u = u1 + delta*i;
2164 gp_Pnt p = curve->Value(u);
2165 NETGENPlugin_Mesher::RestrictLocalSize( mesh, p.XYZ(), size );
2166 netgen::Point3d pi(p.X(), p.Y(), p.Z());
2167 double resultSize = mesh.GetH(pi);
2168 if ( resultSize - size > 0.1*size )
2169 // netgen does restriction iff oldH/newH > 1.2 (localh.cpp:136)
2170 NETGENPlugin_Mesher::RestrictLocalSize( mesh, p.XYZ(), resultSize/1.201 );
2175 //================================================================================
2177 * \brief Convert error into text
2179 //================================================================================
2181 std::string text(int err)
2186 SMESH_Comment("Error in netgen::OCCGenerateMesh() at ") << netgen::multithread.task;
2189 //================================================================================
2191 * \brief Convert exception into text
2193 //================================================================================
2195 std::string text(Standard_Failure& ex)
2197 SMESH_Comment str("Exception in netgen::OCCGenerateMesh()");
2198 str << " at " << netgen::multithread.task
2199 << ": " << ex.DynamicType()->Name();
2200 if ( ex.GetMessageString() && strlen( ex.GetMessageString() ))
2201 str << ": " << ex.GetMessageString();
2204 //================================================================================
2206 * \brief Convert exception into text
2208 //================================================================================
2210 std::string text(netgen::NgException& ex)
2212 SMESH_Comment str("NgException");
2213 if ( strlen( netgen::multithread.task ) > 0 )
2214 str << " at " << netgen::multithread.task;
2215 str << ": " << ex.What();
2219 //================================================================================
2221 * \brief Looks for triangles lying on a SOLID
2223 //================================================================================
2225 bool hasBadElemOnSolid( const list<const SMDS_MeshElement*>& elems,
2226 SMESH_subMesh* solidSM )
2228 TopTools_IndexedMapOfShape solidSubs;
2229 TopExp::MapShapes( solidSM->GetSubShape(), solidSubs );
2230 SMESHDS_Mesh* mesh = solidSM->GetFather()->GetMeshDS();
2232 list<const SMDS_MeshElement*>::const_iterator e = elems.begin();
2233 for ( ; e != elems.end(); ++e )
2235 const SMDS_MeshElement* elem = *e;
2236 // if ( elem->GetType() != SMDSAbs_Face ) -- 23047
2238 int nbNodesOnSolid = 0, nbNodes = elem->NbNodes();
2239 SMDS_NodeIteratorPtr nIt = elem->nodeIterator();
2240 while ( nIt->more() )
2242 const SMDS_MeshNode* n = nIt->next();
2243 const TopoDS_Shape& s = mesh->IndexToShape( n->getshapeId() );
2244 nbNodesOnSolid += ( !s.IsNull() && solidSubs.Contains( s ));
2245 if ( nbNodesOnSolid > 2 ||
2246 nbNodesOnSolid == nbNodes)
2253 const double edgeMeshingTime = 0.001;
2254 const double faceMeshingTime = 0.019;
2255 const double edgeFaceMeshingTime = edgeMeshingTime + faceMeshingTime;
2256 const double faceOptimizTime = 0.06;
2257 const double voluMeshingTime = 0.15;
2258 const double volOptimizeTime = 0.77;
2261 //=============================================================================
2263 * Here we are going to use the NETGEN mesher
2265 //=============================================================================
2267 bool NETGENPlugin_Mesher::Compute()
2269 NETGENPlugin_NetgenLibWrapper ngLib;
2271 netgen::MeshingParameters& mparams = netgen::mparam;
2272 MESSAGE("Compute with:\n"
2273 " max size = " << mparams.maxh << "\n"
2274 " segments per edge = " << mparams.segmentsperedge);
2276 " growth rate = " << mparams.grading << "\n"
2277 " elements per radius = " << mparams.curvaturesafety << "\n"
2278 " second order = " << mparams.secondorder << "\n"
2279 " quad allowed = " << mparams.quad << "\n"
2280 " surface curvature = " << mparams.uselocalh << "\n"
2281 " fuse edges = " << netgen::merge_solids);
2283 SMESH_ComputeErrorPtr error = SMESH_ComputeError::New();
2284 SMESH_MesherHelper quadHelper( *_mesh );
2285 quadHelper.SetIsQuadratic( mparams.secondorder );
2287 static string debugFile = "/tmp/ngMesh.py"; /* to call toPython( _ngMesh, debugFile )
2288 while debugging netgen */
2289 // -------------------------
2290 // Prepare OCC geometry
2291 // -------------------------
2293 netgen::OCCGeometry occgeo;
2294 list< SMESH_subMesh* > meshedSM[3]; // for 0-2 dimensions
2295 NETGENPlugin_Internals internals( *_mesh, _shape, _isVolume );
2296 PrepareOCCgeometry( occgeo, _shape, *_mesh, meshedSM, &internals );
2299 _totalTime = edgeFaceMeshingTime;
2301 _totalTime += faceOptimizTime;
2303 _totalTime += voluMeshingTime + ( _optimize ? volOptimizeTime : 0 );
2304 double doneTime = 0;
2307 _curShapeIndex = -1;
2309 // -------------------------
2310 // Generate the mesh
2311 // -------------------------
2314 NETGENPlugin_ngMeshInfo initState; // it remembers size of ng mesh equal to size of Smesh
2316 SMESH_Comment comment;
2319 // vector of nodes in which node index == netgen ID
2320 vector< const SMDS_MeshNode* > nodeVec;
2328 // not to RestrictLocalH() according to curvature during MESHCONST_ANALYSE
2329 mparams.uselocalh = false;
2330 mparams.grading = 0.8; // not limitited size growth
2332 if ( _simpleHyp->GetNumberOfSegments() )
2334 mparams.maxh = occgeo.boundingbox.Diam();
2337 mparams.maxh = _simpleHyp->GetLocalLength();
2340 if ( mparams.maxh == 0.0 )
2341 mparams.maxh = occgeo.boundingbox.Diam();
2342 if ( _simpleHyp || ( mparams.minh == 0.0 && _fineness != NETGENPlugin_Hypothesis::UserDefined))
2343 mparams.minh = GetDefaultMinSize( _shape, mparams.maxh );
2345 // Local size on faces
2346 occgeo.face_maxh = mparams.maxh;
2348 // Let netgen create _ngMesh and calculate element size on not meshed shapes
2352 int startWith = netgen::MESHCONST_ANALYSE;
2353 int endWith = netgen::MESHCONST_ANALYSE;
2358 err = netgen::OCCGenerateMesh(occgeo, _ngMesh, mparams, startWith, endWith);
2360 err = netgen::OCCGenerateMesh(occgeo, _ngMesh, startWith, endWith, optstr);
2362 if(netgen::multithread.terminate)
2365 comment << text(err);
2367 catch (Standard_Failure& ex)
2369 comment << text(ex);
2371 err = 0; //- MESHCONST_ANALYSE isn't so important step
2374 ngLib.setMesh(( Ng_Mesh*) _ngMesh );
2376 _ngMesh->ClearFaceDescriptors(); // we make descriptors our-self
2380 // Pass 1D simple parameters to NETGEN
2381 // --------------------------------
2382 int nbSeg = _simpleHyp->GetNumberOfSegments();
2383 double segSize = _simpleHyp->GetLocalLength();
2384 for ( int iE = 1; iE <= occgeo.emap.Extent(); ++iE )
2386 const TopoDS_Edge& e = TopoDS::Edge( occgeo.emap(iE));
2388 segSize = SMESH_Algo::EdgeLength( e ) / ( nbSeg - 0.4 );
2389 setLocalSize( e, segSize, *_ngMesh );
2392 else // if ( ! _simpleHyp )
2394 // Local size on vertices and edges
2395 // --------------------------------
2396 for(std::map<int,double>::const_iterator it=EdgeId2LocalSize.begin(); it!=EdgeId2LocalSize.end(); it++)
2398 int key = (*it).first;
2399 double hi = (*it).second;
2400 const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
2401 const TopoDS_Edge& e = TopoDS::Edge(shape);
2402 setLocalSize( e, hi, *_ngMesh );
2404 for(std::map<int,double>::const_iterator it=VertexId2LocalSize.begin(); it!=VertexId2LocalSize.end(); it++)
2406 int key = (*it).first;
2407 double hi = (*it).second;
2408 const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
2409 const TopoDS_Vertex& v = TopoDS::Vertex(shape);
2410 gp_Pnt p = BRep_Tool::Pnt(v);
2411 NETGENPlugin_Mesher::RestrictLocalSize( *_ngMesh, p.XYZ(), hi );
2413 for(map<int,double>::const_iterator it=FaceId2LocalSize.begin();
2414 it!=FaceId2LocalSize.end(); it++)
2416 int key = (*it).first;
2417 double val = (*it).second;
2418 const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
2419 int faceNgID = occgeo.fmap.FindIndex(shape);
2420 occgeo.SetFaceMaxH(faceNgID, val);
2421 for ( TopExp_Explorer edgeExp( shape, TopAbs_EDGE ); edgeExp.More(); edgeExp.Next() )
2422 setLocalSize( TopoDS::Edge( edgeExp.Current() ), val, *_ngMesh );
2426 // Precompute internal edges (issue 0020676) in order to
2427 // add mesh on them correctly (twice) to netgen mesh
2428 if ( !err && internals.hasInternalEdges() )
2430 // load internal shapes into OCCGeometry
2431 netgen::OCCGeometry intOccgeo;
2432 internals.getInternalEdges( intOccgeo.fmap, intOccgeo.emap, intOccgeo.vmap, meshedSM );
2433 intOccgeo.boundingbox = occgeo.boundingbox;
2434 intOccgeo.shape = occgeo.shape;
2435 intOccgeo.face_maxh.SetSize(intOccgeo.fmap.Extent());
2436 intOccgeo.face_maxh = netgen::mparam.maxh;
2437 netgen::Mesh *tmpNgMesh = NULL;
2441 // compute local H on internal shapes in the main mesh
2442 //OCCSetLocalMeshSize(intOccgeo, *_ngMesh); it deletes _ngMesh->localH
2444 // let netgen create a temporary mesh
2446 netgen::OCCGenerateMesh(intOccgeo, tmpNgMesh, mparams, startWith, endWith);
2448 netgen::OCCGenerateMesh(intOccgeo, tmpNgMesh, startWith, endWith, optstr);
2450 if(netgen::multithread.terminate)
2453 // copy LocalH from the main to temporary mesh
2454 initState.transferLocalH( _ngMesh, tmpNgMesh );
2456 // compute mesh on internal edges
2457 startWith = endWith = netgen::MESHCONST_MESHEDGES;
2459 err = netgen::OCCGenerateMesh(intOccgeo, tmpNgMesh, mparams, startWith, endWith);
2461 err = netgen::OCCGenerateMesh(intOccgeo, tmpNgMesh, startWith, endWith, optstr);
2463 comment << text(err);
2465 catch (Standard_Failure& ex)
2467 comment << text(ex);
2470 initState.restoreLocalH( tmpNgMesh );
2472 // fill SMESH by netgen mesh
2473 vector< const SMDS_MeshNode* > tmpNodeVec;
2474 FillSMesh( intOccgeo, *tmpNgMesh, initState, *_mesh, tmpNodeVec, comment );
2475 err = ( err || !comment.empty() );
2477 nglib::Ng_DeleteMesh((nglib::Ng_Mesh*)tmpNgMesh);
2480 // Fill _ngMesh with nodes and segments of computed submeshes
2483 err = ! ( FillNgMesh(occgeo, *_ngMesh, nodeVec, meshedSM[ MeshDim_0D ]) &&
2484 FillNgMesh(occgeo, *_ngMesh, nodeVec, meshedSM[ MeshDim_1D ], &quadHelper));
2486 initState = NETGENPlugin_ngMeshInfo(_ngMesh);
2491 startWith = endWith = netgen::MESHCONST_MESHEDGES;
2496 err = netgen::OCCGenerateMesh(occgeo, _ngMesh, mparams, startWith, endWith);
2498 err = netgen::OCCGenerateMesh(occgeo, _ngMesh, startWith, endWith, optstr);
2500 if(netgen::multithread.terminate)
2503 comment << text(err);
2505 catch (Standard_Failure& ex)
2507 comment << text(ex);
2512 _ticTime = ( doneTime += edgeMeshingTime ) / _totalTime / _progressTic;
2514 mparams.uselocalh = true; // restore as it is used at surface optimization
2516 // ---------------------
2517 // compute surface mesh
2518 // ---------------------
2521 // Pass 2D simple parameters to NETGEN
2523 if ( double area = _simpleHyp->GetMaxElementArea() ) {
2525 mparams.maxh = sqrt(2. * area/sqrt(3.0));
2526 mparams.grading = 0.4; // moderate size growth
2529 // length from edges
2530 if ( _ngMesh->GetNSeg() ) {
2531 double edgeLength = 0;
2532 TopTools_MapOfShape visitedEdges;
2533 for ( TopExp_Explorer exp( _shape, TopAbs_EDGE ); exp.More(); exp.Next() )
2534 if( visitedEdges.Add(exp.Current()) )
2535 edgeLength += SMESH_Algo::EdgeLength( TopoDS::Edge( exp.Current() ));
2536 // we have to multiply length by 2 since for each TopoDS_Edge there
2537 // are double set of NETGEN edges, in other words, we have to
2538 // divide _ngMesh->GetNSeg() by 2.
2539 mparams.maxh = 2*edgeLength / _ngMesh->GetNSeg();
2542 mparams.maxh = 1000;
2544 mparams.grading = 0.2; // slow size growth
2546 mparams.quad = _simpleHyp->GetAllowQuadrangles();
2547 mparams.maxh = min( mparams.maxh, occgeo.boundingbox.Diam()/2 );
2548 _ngMesh->SetGlobalH (mparams.maxh);
2549 netgen::Box<3> bb = occgeo.GetBoundingBox();
2550 bb.Increase (bb.Diam()/20);
2551 _ngMesh->SetLocalH (bb.PMin(), bb.PMax(), mparams.grading);
2554 // Care of vertices internal in faces (issue 0020676)
2555 if ( internals.hasInternalVertexInFace() )
2557 // store computed segments in SMESH in order not to create SMESH
2558 // edges for ng segments added by AddIntVerticesInFaces()
2559 FillSMesh( occgeo, *_ngMesh, initState, *_mesh, nodeVec, comment );
2560 // add segments to faces with internal vertices
2561 AddIntVerticesInFaces( occgeo, *_ngMesh, nodeVec, internals );
2562 initState = NETGENPlugin_ngMeshInfo(_ngMesh);
2565 // Build viscous layers
2566 if ( _isViscousLayers2D )
2568 if ( !internals.hasInternalVertexInFace() ) {
2569 FillSMesh( occgeo, *_ngMesh, initState, *_mesh, nodeVec, comment );
2570 initState = NETGENPlugin_ngMeshInfo(_ngMesh);
2572 SMESH_ProxyMesh::Ptr viscousMesh;
2573 SMESH_MesherHelper helper( *_mesh );
2574 for ( int faceID = 1; faceID <= occgeo.fmap.Extent(); ++faceID )
2576 const TopoDS_Face& F = TopoDS::Face( occgeo.fmap( faceID ));
2577 viscousMesh = StdMeshers_ViscousLayers2D::Compute( *_mesh, F );
2580 // exclude from computation ng segments built on EDGEs of F
2581 for (int i = 1; i <= _ngMesh->GetNSeg(); i++)
2583 netgen::Segment & seg = _ngMesh->LineSegment(i);
2584 if (seg.si == faceID)
2587 // add new segments to _ngMesh instead of excluded ones
2588 helper.SetSubShape( F );
2590 StdMeshers_FaceSide::GetFaceWires( F, *_mesh, /*skipMediumNodes=*/true,
2591 error, viscousMesh );
2592 error = AddSegmentsToMesh( *_ngMesh, occgeo, wires, helper, nodeVec );
2594 if ( !error ) error = SMESH_ComputeError::New();
2596 initState = NETGENPlugin_ngMeshInfo(_ngMesh);
2599 // Let netgen compute 2D mesh
2600 startWith = netgen::MESHCONST_MESHSURFACE;
2601 endWith = _optimize ? netgen::MESHCONST_OPTSURFACE : netgen::MESHCONST_MESHSURFACE;
2606 err = netgen::OCCGenerateMesh(occgeo, _ngMesh, mparams, startWith, endWith);
2608 err = netgen::OCCGenerateMesh(occgeo, _ngMesh, startWith, endWith, optstr);
2610 if(netgen::multithread.terminate)
2613 comment << text (err);
2615 catch (Standard_Failure& ex)
2617 comment << text(ex);
2618 //err = 1; -- try to make volumes anyway
2620 catch (netgen::NgException exc)
2622 comment << text(exc);
2623 //err = 1; -- try to make volumes anyway
2628 doneTime += faceMeshingTime + ( _optimize ? faceOptimizTime : 0 );
2629 _ticTime = doneTime / _totalTime / _progressTic;
2631 // ---------------------
2632 // generate volume mesh
2633 // ---------------------
2634 // Fill _ngMesh with nodes and faces of computed 2D submeshes
2635 if ( !err && _isVolume && ( !meshedSM[ MeshDim_2D ].empty() || mparams.quad ))
2637 // load SMESH with computed segments and faces
2638 FillSMesh( occgeo, *_ngMesh, initState, *_mesh, nodeVec, comment, &quadHelper );
2640 // compute pyramids on quadrangles
2641 SMESH_ProxyMesh::Ptr proxyMesh;
2642 if ( _mesh->NbQuadrangles() > 0 )
2643 for ( int iS = 1; iS <= occgeo.somap.Extent(); ++iS )
2645 StdMeshers_QuadToTriaAdaptor* Adaptor = new StdMeshers_QuadToTriaAdaptor;
2646 proxyMesh.reset( Adaptor );
2648 int nbPyrams = _mesh->NbPyramids();
2649 Adaptor->Compute( *_mesh, occgeo.somap(iS) );
2650 if ( nbPyrams != _mesh->NbPyramids() )
2652 list< SMESH_subMesh* > quadFaceSM;
2653 for (TopExp_Explorer face(occgeo.somap(iS), TopAbs_FACE); face.More(); face.Next())
2654 if ( Adaptor->GetProxySubMesh( face.Current() ))
2656 quadFaceSM.push_back( _mesh->GetSubMesh( face.Current() ));
2657 meshedSM[ MeshDim_2D ].remove( quadFaceSM.back() );
2659 FillNgMesh(occgeo, *_ngMesh, nodeVec, quadFaceSM, &quadHelper, proxyMesh);
2662 // fill _ngMesh with faces of sub-meshes
2663 err = ! ( FillNgMesh(occgeo, *_ngMesh, nodeVec, meshedSM[ MeshDim_2D ], &quadHelper));
2664 initState = NETGENPlugin_ngMeshInfo(_ngMesh);
2665 //toPython( _ngMesh, "/tmp/ngPython.py");
2667 if (!err && _isVolume)
2669 // Pass 3D simple parameters to NETGEN
2670 const NETGENPlugin_SimpleHypothesis_3D* simple3d =
2671 dynamic_cast< const NETGENPlugin_SimpleHypothesis_3D* > ( _simpleHyp );
2673 if ( double vol = simple3d->GetMaxElementVolume() ) {
2675 mparams.maxh = pow( 72, 1/6. ) * pow( vol, 1/3. );
2676 mparams.maxh = min( mparams.maxh, occgeo.boundingbox.Diam()/2 );
2679 // length from faces
2680 mparams.maxh = _ngMesh->AverageH();
2682 _ngMesh->SetGlobalH (mparams.maxh);
2683 mparams.grading = 0.4;
2685 _ngMesh->CalcLocalH(mparams.grading);
2687 _ngMesh->CalcLocalH();
2690 // Care of vertices internal in solids and internal faces (issue 0020676)
2691 if ( internals.hasInternalVertexInSolid() || internals.hasInternalFaces() )
2693 // store computed faces in SMESH in order not to create SMESH
2694 // faces for ng faces added here
2695 FillSMesh( occgeo, *_ngMesh, initState, *_mesh, nodeVec, comment, &quadHelper );
2696 // add ng faces to solids with internal vertices
2697 AddIntVerticesInSolids( occgeo, *_ngMesh, nodeVec, internals );
2698 // duplicate mesh faces on internal faces
2699 FixIntFaces( occgeo, *_ngMesh, internals );
2700 initState = NETGENPlugin_ngMeshInfo(_ngMesh);
2702 // Let netgen compute 3D mesh
2703 startWith = endWith = netgen::MESHCONST_MESHVOLUME;
2708 err = netgen::OCCGenerateMesh(occgeo, _ngMesh, mparams, startWith, endWith);
2710 err = netgen::OCCGenerateMesh(occgeo, _ngMesh, startWith, endWith, optstr);
2712 if(netgen::multithread.terminate)
2715 if ( comment.empty() ) // do not overwrite a previos error
2716 comment << text(err);
2718 catch (Standard_Failure& ex)
2720 if ( comment.empty() ) // do not overwrite a previos error
2721 comment << text(ex);
2724 catch (netgen::NgException exc)
2726 if ( comment.empty() ) // do not overwrite a previos error
2727 comment << text(exc);
2730 _ticTime = ( doneTime += voluMeshingTime ) / _totalTime / _progressTic;
2732 // Let netgen optimize 3D mesh
2733 if ( !err && _optimize )
2735 startWith = endWith = netgen::MESHCONST_OPTVOLUME;
2740 err = netgen::OCCGenerateMesh(occgeo, _ngMesh, mparams, startWith, endWith);
2742 err = netgen::OCCGenerateMesh(occgeo, _ngMesh, startWith, endWith, optstr);
2744 if(netgen::multithread.terminate)
2747 if ( comment.empty() ) // do not overwrite a previos error
2748 comment << text(err);
2750 catch (Standard_Failure& ex)
2752 if ( comment.empty() ) // do not overwrite a previos error
2753 comment << text(ex);
2755 catch (netgen::NgException exc)
2757 if ( comment.empty() ) // do not overwrite a previos error
2758 comment << text(exc);
2762 if (!err && mparams.secondorder > 0)
2767 if ( !meshedSM[ MeshDim_1D ].empty() )
2769 // remove segments not attached to geometry (IPAL0052479)
2770 for (int i = 1; i <= _ngMesh->GetNSeg(); ++i)
2772 const netgen::Segment & seg = _ngMesh->LineSegment (i);
2773 if ( seg.epgeominfo[ 0 ].edgenr == 0 )
2774 _ngMesh->DeleteSegment( i );
2776 _ngMesh->Compress();
2778 // convert to quadratic
2779 netgen::OCCRefinementSurfaces ref (occgeo);
2780 ref.MakeSecondOrder (*_ngMesh);
2782 // care of elements already loaded to SMESH
2783 // if ( initState._nbSegments > 0 )
2784 // makeQuadratic( occgeo.emap, _mesh );
2785 // if ( initState._nbFaces > 0 )
2786 // makeQuadratic( occgeo.fmap, _mesh );
2788 catch (Standard_Failure& ex)
2790 if ( comment.empty() ) // do not overwrite a previos error
2791 comment << "Exception in netgen at passing to 2nd order ";
2793 catch (netgen::NgException exc)
2795 if ( comment.empty() ) // do not overwrite a previos error
2796 comment << exc.What();
2801 _ticTime = 0.98 / _progressTic;
2803 int nbNod = _ngMesh->GetNP();
2804 int nbSeg = _ngMesh->GetNSeg();
2805 int nbFac = _ngMesh->GetNSE();
2806 int nbVol = _ngMesh->GetNE();
2807 bool isOK = ( !err && (_isVolume ? (nbVol > 0) : (nbFac > 0)) );
2809 MESSAGE((err ? "Mesh Generation failure" : "End of Mesh Generation") <<
2810 ", nb nodes: " << nbNod <<
2811 ", nb segments: " << nbSeg <<
2812 ", nb faces: " << nbFac <<
2813 ", nb volumes: " << nbVol);
2815 // Feed back the SMESHDS with the generated Nodes and Elements
2816 if ( true /*isOK*/ ) // get whatever built
2818 FillSMesh( occgeo, *_ngMesh, initState, *_mesh, nodeVec, comment, &quadHelper );
2820 if ( quadHelper.GetIsQuadratic() ) // remove free nodes
2821 for ( size_t i = 0; i < nodeVec.size(); ++i )
2822 if ( nodeVec[i] && nodeVec[i]->NbInverseElements() == 0 )
2823 _mesh->GetMeshDS()->RemoveFreeNode( nodeVec[i], 0, /*fromGroups=*/false );
2825 SMESH_ComputeErrorPtr readErr = ReadErrors(nodeVec);
2826 if ( readErr && !readErr->myBadElements.empty() )
2829 if ( !comment.empty() && !readErr->myComment.empty() ) comment += "\n";
2830 comment += readErr->myComment;
2832 if ( error->IsOK() && ( !isOK || comment.size() > 0 ))
2833 error->myName = COMPERR_ALGO_FAILED;
2834 if ( !comment.empty() )
2835 error->myComment = comment;
2837 // SetIsAlwaysComputed( true ) to empty sub-meshes, which
2838 // appear if the geometry contains coincident sub-shape due
2839 // to bool merge_solids = 1; in netgen/libsrc/occ/occgenmesh.cpp
2840 const int nbMaps = 2;
2841 const TopTools_IndexedMapOfShape* geoMaps[nbMaps] =
2842 { & occgeo.vmap, & occgeo.emap/*, & occgeo.fmap*/ };
2843 for ( int iMap = 0; iMap < nbMaps; ++iMap )
2844 for (int i = 1; i <= geoMaps[iMap]->Extent(); i++)
2845 if ( SMESH_subMesh* sm = _mesh->GetSubMeshContaining( geoMaps[iMap]->FindKey(i)))
2846 if ( !sm->IsMeshComputed() )
2847 sm->SetIsAlwaysComputed( true );
2849 // set bad compute error to subshapes of all failed sub-shapes
2850 if ( !error->IsOK() )
2852 bool pb2D = false, pb3D = false;
2853 for (int i = 1; i <= occgeo.fmap.Extent(); i++) {
2854 int status = occgeo.facemeshstatus[i-1];
2855 if (status == 1 ) continue;
2856 if ( SMESH_subMesh* sm = _mesh->GetSubMeshContaining( occgeo.fmap( i ))) {
2857 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
2858 if ( !smError || smError->IsOK() ) {
2860 smError.reset( new SMESH_ComputeError( *error ));
2862 smError.reset( new SMESH_ComputeError( COMPERR_ALGO_FAILED, "Ignored" ));
2863 if ( SMESH_Algo::GetMeshError( sm ) == SMESH_Algo::MEr_OK )
2864 smError->myName = COMPERR_WARNING;
2866 pb2D = pb2D || smError->IsKO();
2869 if ( !pb2D ) // all faces are OK
2870 for (int i = 1; i <= occgeo.somap.Extent(); i++)
2871 if ( SMESH_subMesh* sm = _mesh->GetSubMeshContaining( occgeo.somap( i )))
2873 bool smComputed = nbVol && !sm->IsEmpty();
2874 if ( smComputed && internals.hasInternalVertexInSolid( sm->GetId() ))
2876 int nbIntV = internals.getSolidsWithVertices().find( sm->GetId() )->second.size();
2877 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
2878 smComputed = ( smDS->NbElements() > 0 || smDS->NbNodes() > nbIntV );
2880 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
2881 if ( !smComputed && ( !smError || smError->IsOK() ))
2883 smError.reset( new SMESH_ComputeError( *error ));
2884 if ( nbVol && SMESH_Algo::GetMeshError( sm ) == SMESH_Algo::MEr_OK )
2886 smError->myName = COMPERR_WARNING;
2888 else if ( !smError->myBadElements.empty() ) // bad surface mesh
2890 if ( !hasBadElemOnSolid( smError->myBadElements, sm ))
2894 pb3D = pb3D || ( smError && smError->IsKO() );
2896 if ( !pb2D && !pb3D )
2897 err = 0; // no fatal errors, only warnings
2900 ngLib._isComputeOk = !err;
2905 //=============================================================================
2909 //=============================================================================
2910 bool NETGENPlugin_Mesher::Evaluate(MapShapeNbElems& aResMap)
2912 netgen::MeshingParameters& mparams = netgen::mparam;
2915 // -------------------------
2916 // Prepare OCC geometry
2917 // -------------------------
2918 netgen::OCCGeometry occgeo;
2919 list< SMESH_subMesh* > meshedSM[4]; // for 0-3 dimensions
2920 NETGENPlugin_Internals internals( *_mesh, _shape, _isVolume );
2921 PrepareOCCgeometry( occgeo, _shape, *_mesh, meshedSM, &internals );
2923 bool tooManyElems = false;
2924 const int hugeNb = std::numeric_limits<int>::max() / 100;
2929 // pass 1D simple parameters to NETGEN
2932 // not to RestrictLocalH() according to curvature during MESHCONST_ANALYSE
2933 mparams.uselocalh = false;
2934 mparams.grading = 0.8; // not limitited size growth
2936 if ( _simpleHyp->GetNumberOfSegments() )
2938 mparams.maxh = occgeo.boundingbox.Diam();
2941 mparams.maxh = _simpleHyp->GetLocalLength();
2944 if ( mparams.maxh == 0.0 )
2945 mparams.maxh = occgeo.boundingbox.Diam();
2946 if ( _simpleHyp || ( mparams.minh == 0.0 && _fineness != NETGENPlugin_Hypothesis::UserDefined))
2947 mparams.minh = GetDefaultMinSize( _shape, mparams.maxh );
2949 // let netgen create _ngMesh and calculate element size on not meshed shapes
2950 NETGENPlugin_NetgenLibWrapper ngLib;
2951 netgen::Mesh *ngMesh = NULL;
2955 int startWith = netgen::MESHCONST_ANALYSE;
2956 int endWith = netgen::MESHCONST_MESHEDGES;
2958 int err = netgen::OCCGenerateMesh(occgeo, ngMesh, mparams, startWith, endWith);
2960 int err = netgen::OCCGenerateMesh(occgeo, ngMesh, startWith, endWith, optstr);
2963 if(netgen::multithread.terminate)
2966 ngLib.setMesh(( Ng_Mesh*) ngMesh );
2968 if ( SMESH_subMesh* sm = _mesh->GetSubMeshContaining( _shape ))
2969 sm->GetComputeError().reset( new SMESH_ComputeError( COMPERR_ALGO_FAILED ));
2974 // Pass 1D simple parameters to NETGEN
2975 // --------------------------------
2976 int nbSeg = _simpleHyp->GetNumberOfSegments();
2977 double segSize = _simpleHyp->GetLocalLength();
2978 for ( int iE = 1; iE <= occgeo.emap.Extent(); ++iE )
2980 const TopoDS_Edge& e = TopoDS::Edge( occgeo.emap(iE));
2982 segSize = SMESH_Algo::EdgeLength( e ) / ( nbSeg - 0.4 );
2983 setLocalSize( e, segSize, *ngMesh );
2986 else // if ( ! _simpleHyp )
2988 // Local size on vertices and edges
2989 // --------------------------------
2990 for(std::map<int,double>::const_iterator it=EdgeId2LocalSize.begin(); it!=EdgeId2LocalSize.end(); it++)
2992 int key = (*it).first;
2993 double hi = (*it).second;
2994 const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
2995 const TopoDS_Edge& e = TopoDS::Edge(shape);
2996 setLocalSize( e, hi, *ngMesh );
2998 for(std::map<int,double>::const_iterator it=VertexId2LocalSize.begin(); it!=VertexId2LocalSize.end(); it++)
3000 int key = (*it).first;
3001 double hi = (*it).second;
3002 const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
3003 const TopoDS_Vertex& v = TopoDS::Vertex(shape);
3004 gp_Pnt p = BRep_Tool::Pnt(v);
3005 NETGENPlugin_Mesher::RestrictLocalSize( *ngMesh, p.XYZ(), hi );
3007 for(map<int,double>::const_iterator it=FaceId2LocalSize.begin();
3008 it!=FaceId2LocalSize.end(); it++)
3010 int key = (*it).first;
3011 double val = (*it).second;
3012 const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
3013 int faceNgID = occgeo.fmap.FindIndex(shape);
3014 occgeo.SetFaceMaxH(faceNgID, val);
3015 for ( TopExp_Explorer edgeExp( shape, TopAbs_EDGE ); edgeExp.More(); edgeExp.Next() )
3016 setLocalSize( TopoDS::Edge( edgeExp.Current() ), val, *ngMesh );
3019 // calculate total nb of segments and length of edges
3020 double fullLen = 0.0;
3022 int entity = mparams.secondorder > 0 ? SMDSEntity_Quad_Edge : SMDSEntity_Edge;
3023 TopTools_DataMapOfShapeInteger Edge2NbSeg;
3024 for (TopExp_Explorer exp(_shape, TopAbs_EDGE); exp.More(); exp.Next())
3026 TopoDS_Edge E = TopoDS::Edge( exp.Current() );
3027 if( !Edge2NbSeg.Bind(E,0) )
3030 double aLen = SMESH_Algo::EdgeLength(E);
3033 vector<int>& aVec = aResMap[_mesh->GetSubMesh(E)];
3035 aVec.resize( SMDSEntity_Last, 0);
3037 fullNbSeg += aVec[ entity ];
3040 // store nb of segments computed by Netgen
3041 NCollection_Map<Link> linkMap;
3042 for (int i = 1; i <= ngMesh->GetNSeg(); ++i )
3044 const netgen::Segment& seg = ngMesh->LineSegment(i);
3045 Link link(seg[0], seg[1]);
3046 if ( !linkMap.Add( link )) continue;
3047 int aGeomEdgeInd = seg.epgeominfo[0].edgenr;
3048 if (aGeomEdgeInd > 0 && aGeomEdgeInd <= occgeo.emap.Extent())
3050 vector<int>& aVec = aResMap[_mesh->GetSubMesh(occgeo.emap(aGeomEdgeInd))];
3054 // store nb of nodes on edges computed by Netgen
3055 TopTools_DataMapIteratorOfDataMapOfShapeInteger Edge2NbSegIt(Edge2NbSeg);
3056 for (; Edge2NbSegIt.More(); Edge2NbSegIt.Next())
3058 vector<int>& aVec = aResMap[_mesh->GetSubMesh(Edge2NbSegIt.Key())];
3059 if ( aVec[ entity ] > 1 && aVec[ SMDSEntity_Node ] == 0 )
3060 aVec[SMDSEntity_Node] = mparams.secondorder > 0 ? 2*aVec[ entity ]-1 : aVec[ entity ]-1;
3062 fullNbSeg += aVec[ entity ];
3063 Edge2NbSeg( Edge2NbSegIt.Key() ) = aVec[ entity ];
3065 if ( fullNbSeg == 0 )
3072 if ( double area = _simpleHyp->GetMaxElementArea() ) {
3074 mparams.maxh = sqrt(2. * area/sqrt(3.0));
3075 mparams.grading = 0.4; // moderate size growth
3078 // length from edges
3079 mparams.maxh = fullLen/fullNbSeg;
3080 mparams.grading = 0.2; // slow size growth
3083 mparams.maxh = min( mparams.maxh, occgeo.boundingbox.Diam()/2 );
3084 mparams.maxh = min( mparams.maxh, fullLen/fullNbSeg * (1. + mparams.grading));
3086 for (TopExp_Explorer exp(_shape, TopAbs_FACE); exp.More(); exp.Next())
3088 TopoDS_Face F = TopoDS::Face( exp.Current() );
3089 SMESH_subMesh *sm = _mesh->GetSubMesh(F);
3091 BRepGProp::SurfaceProperties(F,G);
3092 double anArea = G.Mass();
3093 tooManyElems = tooManyElems || ( anArea/hugeNb > mparams.maxh*mparams.maxh );
3095 if ( !tooManyElems )
3097 TopTools_MapOfShape egdes;
3098 for (TopExp_Explorer exp1(F,TopAbs_EDGE); exp1.More(); exp1.Next())
3099 if ( egdes.Add( exp1.Current() ))
3100 nb1d += Edge2NbSeg.Find(exp1.Current());
3102 int nbFaces = tooManyElems ? hugeNb : int( 4*anArea / (mparams.maxh*mparams.maxh*sqrt(3.)));
3103 int nbNodes = tooManyElems ? hugeNb : (( nbFaces*3 - (nb1d-1)*2 ) / 6 + 1 );
3105 vector<int> aVec(SMDSEntity_Last, 0);
3106 if( mparams.secondorder > 0 ) {
3107 int nb1d_in = (nbFaces*3 - nb1d) / 2;
3108 aVec[SMDSEntity_Node] = nbNodes + nb1d_in;
3109 aVec[SMDSEntity_Quad_Triangle] = nbFaces;
3112 aVec[SMDSEntity_Node] = Max ( nbNodes, 0 );
3113 aVec[SMDSEntity_Triangle] = nbFaces;
3115 aResMap[sm].swap(aVec);
3122 // pass 3D simple parameters to NETGEN
3123 const NETGENPlugin_SimpleHypothesis_3D* simple3d =
3124 dynamic_cast< const NETGENPlugin_SimpleHypothesis_3D* > ( _simpleHyp );
3126 if ( double vol = simple3d->GetMaxElementVolume() ) {
3128 mparams.maxh = pow( 72, 1/6. ) * pow( vol, 1/3. );
3129 mparams.maxh = min( mparams.maxh, occgeo.boundingbox.Diam()/2 );
3132 // using previous length from faces
3134 mparams.grading = 0.4;
3135 mparams.maxh = min( mparams.maxh, fullLen/fullNbSeg * (1. + mparams.grading));
3138 BRepGProp::VolumeProperties(_shape,G);
3139 double aVolume = G.Mass();
3140 double tetrVol = 0.1179*mparams.maxh*mparams.maxh*mparams.maxh;
3141 tooManyElems = tooManyElems || ( aVolume/hugeNb > tetrVol );
3142 int nbVols = tooManyElems ? hugeNb : int(aVolume/tetrVol);
3143 int nb1d_in = int(( nbVols*6 - fullNbSeg ) / 6 );
3144 vector<int> aVec(SMDSEntity_Last, 0 );
3145 if ( tooManyElems ) // avoid FPE
3147 aVec[SMDSEntity_Node] = hugeNb;
3148 aVec[ mparams.secondorder > 0 ? SMDSEntity_Quad_Tetra : SMDSEntity_Tetra] = hugeNb;
3152 if( mparams.secondorder > 0 ) {
3153 aVec[SMDSEntity_Node] = nb1d_in/3 + 1 + nb1d_in;
3154 aVec[SMDSEntity_Quad_Tetra] = nbVols;
3157 aVec[SMDSEntity_Node] = nb1d_in/3 + 1;
3158 aVec[SMDSEntity_Tetra] = nbVols;
3161 SMESH_subMesh *sm = _mesh->GetSubMesh(_shape);
3162 aResMap[sm].swap(aVec);
3168 double NETGENPlugin_Mesher::GetProgress(const SMESH_Algo* holder,
3169 const int * algoProgressTic,
3170 const double * algoProgress) const
3172 ((int&) _progressTic ) = *algoProgressTic + 1;
3174 if ( !_occgeom ) return 0;
3176 double progress = -1;
3179 if ( _ticTime < 0 && netgen::multithread.task[0] == 'O'/*Optimizing surface*/ )
3181 ((double&) _ticTime ) = edgeFaceMeshingTime / _totalTime / _progressTic;
3183 else if ( !_optimize /*&& _occgeom->fmap.Extent() > 1*/ )
3185 int doneShapeIndex = -1;
3186 while ( doneShapeIndex+1 < _occgeom->facemeshstatus.Size() &&
3187 _occgeom->facemeshstatus[ doneShapeIndex+1 ])
3189 if ( doneShapeIndex+1 != _curShapeIndex )
3191 ((int&) _curShapeIndex) = doneShapeIndex+1;
3192 double doneShapeRate = _curShapeIndex / double( _occgeom->fmap.Extent() );
3193 double doneTime = edgeMeshingTime + doneShapeRate * faceMeshingTime;
3194 ((double&) _ticTime) = doneTime / _totalTime / _progressTic;
3195 // cout << "shape " << _curShapeIndex << " _ticTime " << _ticTime
3196 // << " " << doneTime / _totalTime / _progressTic << endl;
3200 else if ( !_optimize && _occgeom->somap.Extent() > 1 )
3202 int curShapeIndex = _curShapeIndex;
3203 if ( _ngMesh->GetNE() > 0 )
3205 netgen::Element el = (*_ngMesh)[netgen::ElementIndex( _ngMesh->GetNE()-1 )];
3206 curShapeIndex = el.GetIndex();
3208 if ( curShapeIndex != _curShapeIndex )
3210 ((int&) _curShapeIndex) = curShapeIndex;
3211 double doneShapeRate = _curShapeIndex / double( _occgeom->somap.Extent() );
3212 double doneTime = edgeFaceMeshingTime + doneShapeRate * voluMeshingTime;
3213 ((double&) _ticTime) = doneTime / _totalTime / _progressTic;
3214 // cout << "shape " << _curShapeIndex << " _ticTime " << _ticTime
3215 // << " " << doneTime / _totalTime / _progressTic << endl;
3219 progress = Max( *algoProgressTic * _ticTime, *algoProgress );
3222 ((int&) *algoProgressTic )++;
3223 ((double&) *algoProgress) = progress;
3225 //cout << progress << " " << *algoProgressTic << " " << netgen::multithread.task << " "<< _ticTime << endl;
3227 return Min( progress, 0.99 );
3230 //================================================================================
3232 * \brief Remove "test.out" and "problemfaces" files in current directory
3234 //================================================================================
3236 void NETGENPlugin_Mesher::RemoveTmpFiles()
3238 bool rm = SMESH_File("test.out").remove() ;
3240 if (rm && netgen::testout)
3242 delete netgen::testout;
3243 netgen::testout = 0;
3246 SMESH_File("problemfaces").remove();
3247 SMESH_File("occmesh.rep").remove();
3250 //================================================================================
3252 * \brief Read mesh entities preventing successful computation from "test.out" file
3254 //================================================================================
3256 SMESH_ComputeErrorPtr
3257 NETGENPlugin_Mesher::ReadErrors(const vector<const SMDS_MeshNode* >& nodeVec)
3259 SMESH_ComputeErrorPtr err = SMESH_ComputeError::New
3260 (COMPERR_BAD_INPUT_MESH, "Some edges multiple times in surface mesh");
3261 SMESH_File file("test.out");
3263 vector<int> three1(3), three2(3);
3264 const char* badEdgeStr = " multiple times in surface mesh";
3265 const int badEdgeStrLen = strlen( badEdgeStr );
3267 while( !file.eof() )
3269 if ( strncmp( file, "Edge ", 5 ) == 0 &&
3270 file.getInts( two ) &&
3271 strncmp( file, badEdgeStr, badEdgeStrLen ) == 0 &&
3272 two[0] < nodeVec.size() && two[1] < nodeVec.size())
3274 err->myBadElements.push_back( new SMDS_LinearEdge( nodeVec[ two[0]], nodeVec[ two[1]] ));
3275 file += badEdgeStrLen;
3277 else if ( strncmp( file, "Intersecting: ", 14 ) == 0 )
3280 // openelement 18 with open element 126
3284 const char* pos = file;
3285 bool ok = ( strncmp( file, "openelement ", 12 ) == 0 );
3286 ok = ok && file.getInts( two );
3287 ok = ok && file.getInts( three1 );
3288 ok = ok && file.getInts( three2 );
3289 for ( int i = 0; ok && i < 3; ++i )
3290 ok = ( three1[i] < nodeVec.size() && nodeVec[ three1[i]]);
3291 for ( int i = 0; ok && i < 3; ++i )
3292 ok = ( three2[i] < nodeVec.size() && nodeVec[ three2[i]]);
3295 err->myBadElements.push_back( new SMDS_FaceOfNodes( nodeVec[ three1[0]],
3296 nodeVec[ three1[1]],
3297 nodeVec[ three1[2]]));
3298 err->myBadElements.push_back( new SMDS_FaceOfNodes( nodeVec[ three2[0]],
3299 nodeVec[ three2[1]],
3300 nodeVec[ three2[2]]));
3301 err->myComment = "Intersecting triangles";
3315 size_t nbBadElems = err->myBadElements.size();
3322 //================================================================================
3324 * \brief Write a python script creating an equivalent SALOME mesh.
3325 * This is useful to see what mesh is passed as input for the next step of mesh
3326 * generation (of mesh of higher dimension)
3328 //================================================================================
3330 void NETGENPlugin_Mesher::toPython( const netgen::Mesh* ngMesh,
3331 const std::string& pyFile)
3333 ofstream outfile(pyFile.c_str(), ios::out);
3334 if ( !outfile ) return;
3336 outfile << "import SMESH" << endl
3337 << "from salome.smesh import smeshBuilder" << endl
3338 << "smesh = smeshBuilder.New(salome.myStudy)" << endl
3339 << "mesh = smesh.Mesh()" << endl << endl;
3341 using namespace netgen;
3343 for (pi = PointIndex::BASE;
3344 pi < ngMesh->GetNP()+PointIndex::BASE; pi++)
3346 outfile << "mesh.AddNode( ";
3347 outfile << (*ngMesh)[pi](0) << ", ";
3348 outfile << (*ngMesh)[pi](1) << ", ";
3349 outfile << (*ngMesh)[pi](2) << ") ## "<< pi << endl;
3352 int nbDom = ngMesh->GetNDomains();
3353 for ( int i = 0; i < nbDom; ++i )
3354 outfile<< "grp" << i+1 << " = mesh.CreateEmptyGroup( SMESH.FACE, 'domain"<< i+1 << "')"<< endl;
3356 SurfaceElementIndex sei;
3357 for (sei = 0; sei < ngMesh->GetNSE(); sei++)
3359 outfile << "mesh.AddFace([ ";
3360 Element2d sel = (*ngMesh)[sei];
3361 for (int j = 0; j < sel.GetNP(); j++)
3362 outfile << sel[j] << ( j+1 < sel.GetNP() ? ", " : " ])");
3363 if ( sel.IsDeleted() ) outfile << " ## IsDeleted ";
3366 if ((*ngMesh)[sei].GetIndex())
3368 if ( int dom1 = ngMesh->GetFaceDescriptor((*ngMesh)[sei].GetIndex ()).DomainIn())
3369 outfile << "grp"<< dom1 <<".Add([ " << (int)sei+1 << " ])" << endl;
3370 if ( int dom2 = ngMesh->GetFaceDescriptor((*ngMesh)[sei].GetIndex ()).DomainOut())
3371 outfile << "grp"<< dom2 <<".Add([ " << (int)sei+1 << " ])" << endl;
3375 for (ElementIndex ei = 0; ei < ngMesh->GetNE(); ei++)
3377 Element el = (*ngMesh)[ei];
3378 outfile << "mesh.AddVolume([ ";
3379 for (int j = 0; j < el.GetNP(); j++)
3380 outfile << el[j] << ( j+1 < el.GetNP() ? ", " : " ])");
3384 for (int i = 1; i <= ngMesh->GetNSeg(); i++)
3386 const Segment & seg = ngMesh->LineSegment (i);
3387 outfile << "mesh.AddEdge([ "
3389 << seg[1] << " ])" << endl;
3391 cout << "Write " << pyFile << endl;
3394 //================================================================================
3396 * \brief Constructor of NETGENPlugin_ngMeshInfo
3398 //================================================================================
3400 NETGENPlugin_ngMeshInfo::NETGENPlugin_ngMeshInfo( netgen::Mesh* ngMesh):
3405 _nbNodes = ngMesh->GetNP();
3406 _nbSegments = ngMesh->GetNSeg();
3407 _nbFaces = ngMesh->GetNSE();
3408 _nbVolumes = ngMesh->GetNE();
3412 _nbNodes = _nbSegments = _nbFaces = _nbVolumes = 0;
3416 //================================================================================
3418 * \brief Copy LocalH member from one netgen mesh to another
3420 //================================================================================
3422 void NETGENPlugin_ngMeshInfo::transferLocalH( netgen::Mesh* fromMesh,
3423 netgen::Mesh* toMesh )
3425 if ( !fromMesh->LocalHFunctionGenerated() ) return;
3426 if ( !toMesh->LocalHFunctionGenerated() )
3428 toMesh->CalcLocalH(netgen::mparam.grading);
3430 toMesh->CalcLocalH();
3433 const size_t size = sizeof( netgen::LocalH );
3434 _copyOfLocalH = new char[ size ];
3435 memcpy( (void*)_copyOfLocalH, (void*)&toMesh->LocalHFunction(), size );
3436 memcpy( (void*)&toMesh->LocalHFunction(), (void*)&fromMesh->LocalHFunction(), size );
3439 //================================================================================
3441 * \brief Restore LocalH member of a netgen mesh
3443 //================================================================================
3445 void NETGENPlugin_ngMeshInfo::restoreLocalH( netgen::Mesh* toMesh )
3447 if ( _copyOfLocalH )
3449 const size_t size = sizeof( netgen::LocalH );
3450 memcpy( (void*)&toMesh->LocalHFunction(), (void*)_copyOfLocalH, size );
3451 delete [] _copyOfLocalH;
3456 //================================================================================
3458 * \brief Find "internal" sub-shapes
3460 //================================================================================
3462 NETGENPlugin_Internals::NETGENPlugin_Internals( SMESH_Mesh& mesh,
3463 const TopoDS_Shape& shape,
3465 : _mesh( mesh ), _is3D( is3D )
3467 SMESHDS_Mesh* meshDS = mesh.GetMeshDS();
3469 TopExp_Explorer f,e;
3470 for ( f.Init( shape, TopAbs_FACE ); f.More(); f.Next() )
3472 int faceID = meshDS->ShapeToIndex( f.Current() );
3474 // find not computed internal edges
3476 for ( e.Init( f.Current().Oriented(TopAbs_FORWARD), TopAbs_EDGE ); e.More(); e.Next() )
3477 if ( e.Current().Orientation() == TopAbs_INTERNAL )
3479 SMESH_subMesh* eSM = mesh.GetSubMesh( e.Current() );
3480 if ( eSM->IsEmpty() )
3482 _e2face.insert( make_pair( eSM->GetId(), faceID ));
3483 for ( TopoDS_Iterator v(e.Current()); v.More(); v.Next() )
3484 _e2face.insert( make_pair( meshDS->ShapeToIndex( v.Value() ), faceID ));
3488 // find internal vertices in a face
3489 set<int> intVV; // issue 0020850 where same vertex is twice in a face
3490 for ( TopoDS_Iterator fSub( f.Current() ); fSub.More(); fSub.Next())
3491 if ( fSub.Value().ShapeType() == TopAbs_VERTEX )
3493 int vID = meshDS->ShapeToIndex( fSub.Value() );
3494 if ( intVV.insert( vID ).second )
3495 _f2v[ faceID ].push_back( vID );
3500 // find internal faces and their subshapes where nodes are to be doubled
3501 // to make a crack with non-sewed borders
3503 if ( f.Current().Orientation() == TopAbs_INTERNAL )
3505 _intShapes.insert( meshDS->ShapeToIndex( f.Current() ));
3508 list< TopoDS_Shape > edges;
3509 for ( e.Init( f.Current(), TopAbs_EDGE ); e.More(); e.Next())
3510 if ( SMESH_MesherHelper::NbAncestors( e.Current(), mesh, TopAbs_FACE ) > 1 )
3512 _intShapes.insert( meshDS->ShapeToIndex( e.Current() ));
3513 edges.push_back( e.Current() );
3514 // find border faces
3515 PShapeIteratorPtr fIt =
3516 SMESH_MesherHelper::GetAncestors( edges.back(),mesh,TopAbs_FACE );
3517 while ( const TopoDS_Shape* pFace = fIt->next() )
3518 if ( !pFace->IsSame( f.Current() ))
3519 _borderFaces.insert( meshDS->ShapeToIndex( *pFace ));
3522 // we consider vertex internal if it is shared by more than one internal edge
3523 list< TopoDS_Shape >::iterator edge = edges.begin();
3524 for ( ; edge != edges.end(); ++edge )
3525 for ( TopoDS_Iterator v( *edge ); v.More(); v.Next() )
3527 set<int> internalEdges;
3528 PShapeIteratorPtr eIt =
3529 SMESH_MesherHelper::GetAncestors( v.Value(),mesh,TopAbs_EDGE );
3530 while ( const TopoDS_Shape* pEdge = eIt->next() )
3532 int edgeID = meshDS->ShapeToIndex( *pEdge );
3533 if ( isInternalShape( edgeID ))
3534 internalEdges.insert( edgeID );
3536 if ( internalEdges.size() > 1 )
3537 _intShapes.insert( meshDS->ShapeToIndex( v.Value() ));
3541 } // loop on geom faces
3543 // find vertices internal in solids
3546 for ( TopExp_Explorer so(shape, TopAbs_SOLID); so.More(); so.Next())
3548 int soID = meshDS->ShapeToIndex( so.Current() );
3549 for ( TopoDS_Iterator soSub( so.Current() ); soSub.More(); soSub.Next())
3550 if ( soSub.Value().ShapeType() == TopAbs_VERTEX )
3551 _s2v[ soID ].push_back( meshDS->ShapeToIndex( soSub.Value() ));
3556 //================================================================================
3558 * \brief Find mesh faces on non-internal geom faces sharing internal edge
3559 * some nodes of which are to be doubled to make the second border of the "crack"
3561 //================================================================================
3563 void NETGENPlugin_Internals::findBorderElements( TIDSortedElemSet & borderElems )
3565 if ( _intShapes.empty() ) return;
3567 SMESH_Mesh& mesh = const_cast<SMESH_Mesh&>(_mesh);
3568 SMESHDS_Mesh* meshDS = mesh.GetMeshDS();
3570 // loop on internal geom edges
3571 set<int>::const_iterator intShapeId = _intShapes.begin();
3572 for ( ; intShapeId != _intShapes.end(); ++intShapeId )
3574 const TopoDS_Shape& s = meshDS->IndexToShape( *intShapeId );
3575 if ( s.ShapeType() != TopAbs_EDGE ) continue;
3577 // get internal and non-internal geom faces sharing the internal edge <s>
3579 set<int>::iterator bordFace = _borderFaces.end();
3580 PShapeIteratorPtr faces = SMESH_MesherHelper::GetAncestors( s, _mesh, TopAbs_FACE );
3581 while ( const TopoDS_Shape* pFace = faces->next() )
3583 int faceID = meshDS->ShapeToIndex( *pFace );
3584 if ( isInternalShape( faceID ))
3587 bordFace = _borderFaces.insert( faceID ).first;
3589 if ( bordFace == _borderFaces.end() || !intFace ) continue;
3591 // get all links of mesh faces on internal geom face sharing nodes on edge <s>
3592 set< SMESH_OrientedLink > links; //!< links of faces on internal geom face
3593 list<const SMDS_MeshElement*> suspectFaces[2]; //!< mesh faces on border geom faces
3594 int nbSuspectFaces = 0;
3595 SMESHDS_SubMesh* intFaceSM = meshDS->MeshElements( intFace );
3596 if ( !intFaceSM || intFaceSM->NbElements() == 0 ) continue;
3597 SMESH_subMeshIteratorPtr smIt = mesh.GetSubMesh( s )->getDependsOnIterator(true,true);
3598 while ( smIt->more() )
3600 SMESHDS_SubMesh* sm = smIt->next()->GetSubMeshDS();
3601 if ( !sm ) continue;
3602 SMDS_NodeIteratorPtr nIt = sm->GetNodes();
3603 while ( nIt->more() )
3605 const SMDS_MeshNode* nOnEdge = nIt->next();
3606 SMDS_ElemIteratorPtr fIt = nOnEdge->GetInverseElementIterator(SMDSAbs_Face);
3607 while ( fIt->more() )
3609 const SMDS_MeshElement* f = fIt->next();
3610 int nbNodes = f->NbNodes() / ( f->IsQuadratic() ? 2 : 1 );
3611 if ( intFaceSM->Contains( f ))
3613 for ( int i = 0; i < nbNodes; ++i )
3614 links.insert( SMESH_OrientedLink( f->GetNode(i), f->GetNode((i+1)%nbNodes)));
3619 for ( int i = 0; i < nbNodes; ++i )
3620 nbDblNodes += isInternalShape( f->GetNode(i)->getshapeId() );
3622 suspectFaces[ nbDblNodes < 2 ].push_back( f );
3628 // suspectFaces[0] having link with same orientation as mesh faces on
3629 // the internal geom face are <borderElems>. suspectFaces[1] have
3630 // only one node on edge <s>, we decide on them later (at the 2nd loop)
3631 // by links of <borderElems> found at the 1st and 2nd loops
3632 set< SMESH_OrientedLink > borderLinks;
3633 for ( int isPostponed = 0; isPostponed < 2; ++isPostponed )
3635 list<const SMDS_MeshElement*>::iterator fIt = suspectFaces[isPostponed].begin();
3636 for ( int nbF = 0; fIt != suspectFaces[isPostponed].end(); ++fIt, ++nbF )
3638 const SMDS_MeshElement* f = *fIt;
3639 bool isBorder = false, linkFound = false, borderLinkFound = false;
3640 list< SMESH_OrientedLink > faceLinks;
3641 int nbNodes = f->NbNodes() / ( f->IsQuadratic() ? 2 : 1 );
3642 for ( int i = 0; i < nbNodes; ++i )
3644 SMESH_OrientedLink link( f->GetNode(i), f->GetNode((i+1)%nbNodes));
3645 faceLinks.push_back( link );
3648 set< SMESH_OrientedLink >::iterator foundLink = links.find( link );
3649 if ( foundLink != links.end() )
3652 isBorder = ( foundLink->_reversed == link._reversed );
3653 if ( !isBorder && !isPostponed ) break;
3654 faceLinks.pop_back();
3656 else if ( isPostponed && !borderLinkFound )
3658 foundLink = borderLinks.find( link );
3659 if ( foundLink != borderLinks.end() )
3661 borderLinkFound = true;
3662 isBorder = ( foundLink->_reversed != link._reversed );
3669 borderElems.insert( f );
3670 borderLinks.insert( faceLinks.begin(), faceLinks.end() );
3672 else if ( !linkFound && !borderLinkFound )
3674 suspectFaces[1].push_back( f );
3675 if ( nbF > 2 * nbSuspectFaces )
3676 break; // dead loop protection
3683 //================================================================================
3685 * \brief put internal shapes in maps and fill in submeshes to precompute
3687 //================================================================================
3689 void NETGENPlugin_Internals::getInternalEdges( TopTools_IndexedMapOfShape& fmap,
3690 TopTools_IndexedMapOfShape& emap,
3691 TopTools_IndexedMapOfShape& vmap,
3692 list< SMESH_subMesh* > smToPrecompute[])
3694 if ( !hasInternalEdges() ) return;
3695 map<int,int>::const_iterator ev_face = _e2face.begin();
3696 for ( ; ev_face != _e2face.end(); ++ev_face )
3698 const TopoDS_Shape& ev = _mesh.GetMeshDS()->IndexToShape( ev_face->first );
3699 const TopoDS_Shape& face = _mesh.GetMeshDS()->IndexToShape( ev_face->second );
3701 ( ev.ShapeType() == TopAbs_EDGE ? emap : vmap ).Add( ev );
3703 //cout<<"INTERNAL EDGE or VERTEX "<<ev_face->first<<" on face "<<ev_face->second<<endl;
3705 smToPrecompute[ MeshDim_1D ].push_back( _mesh.GetSubMeshContaining( ev_face->first ));
3709 //================================================================================
3711 * \brief return shapes and submeshes to be meshed and already meshed boundary submeshes
3713 //================================================================================
3715 void NETGENPlugin_Internals::getInternalFaces( TopTools_IndexedMapOfShape& fmap,
3716 TopTools_IndexedMapOfShape& emap,
3717 list< SMESH_subMesh* >& intFaceSM,
3718 list< SMESH_subMesh* >& boundarySM)
3720 if ( !hasInternalFaces() ) return;
3722 // <fmap> and <emap> are for not yet meshed shapes
3723 // <intFaceSM> is for submeshes of faces
3724 // <boundarySM> is for meshed edges and vertices
3729 set<int> shapeIDs ( _intShapes );
3730 if ( !_borderFaces.empty() )
3731 shapeIDs.insert( _borderFaces.begin(), _borderFaces.end() );
3733 set<int>::const_iterator intS = shapeIDs.begin();
3734 for ( ; intS != shapeIDs.end(); ++intS )
3736 SMESH_subMesh* sm = _mesh.GetSubMeshContaining( *intS );
3738 if ( sm->GetSubShape().ShapeType() != TopAbs_FACE ) continue;
3740 intFaceSM.push_back( sm );
3742 // add submeshes of not computed internal faces
3743 if ( !sm->IsEmpty() ) continue;
3745 SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(true,true);
3746 while ( smIt->more() )
3749 const TopoDS_Shape& s = sm->GetSubShape();
3751 if ( sm->IsEmpty() )
3754 switch ( s.ShapeType() ) {
3755 case TopAbs_FACE: fmap.Add ( s ); break;
3756 case TopAbs_EDGE: emap.Add ( s ); break;
3762 if ( s.ShapeType() != TopAbs_FACE )
3763 boundarySM.push_back( sm );
3769 //================================================================================
3771 * \brief Return true if given shape is to be precomputed in order to be correctly
3772 * added to netgen mesh
3774 //================================================================================
3776 bool NETGENPlugin_Internals::isShapeToPrecompute(const TopoDS_Shape& s)
3778 int shapeID = _mesh.GetMeshDS()->ShapeToIndex( s );
3779 switch ( s.ShapeType() ) {
3780 case TopAbs_FACE : break; //return isInternalShape( shapeID ) || isBorderFace( shapeID );
3781 case TopAbs_EDGE : return isInternalEdge( shapeID );
3782 case TopAbs_VERTEX: break;
3788 //================================================================================
3790 * \brief Return SMESH
3792 //================================================================================
3794 SMESH_Mesh& NETGENPlugin_Internals::getMesh() const
3796 return const_cast<SMESH_Mesh&>( _mesh );
3799 //================================================================================
3801 * \brief Initialize netgen library
3803 //================================================================================
3805 NETGENPlugin_NetgenLibWrapper::NETGENPlugin_NetgenLibWrapper()
3809 _isComputeOk = false;
3811 if ( !getenv( "KEEP_NETGEN_OUTPUT" ))
3813 // redirect all netgen output (mycout,myerr,cout) to _outputFileName
3814 _outputFileName = getOutputFileName();
3815 netgen::mycout = new ofstream ( _outputFileName.c_str() );
3816 netgen::myerr = netgen::mycout;
3817 _coutBuffer = std::cout.rdbuf();
3819 cout << "NOTE: netgen output is redirected to file " << _outputFileName << endl;
3821 std::cout.rdbuf( netgen::mycout->rdbuf() );
3825 _ngMesh = Ng_NewMesh();
3828 //================================================================================
3830 * \brief Finish using netgen library
3832 //================================================================================
3834 NETGENPlugin_NetgenLibWrapper::~NETGENPlugin_NetgenLibWrapper()
3836 Ng_DeleteMesh( _ngMesh );
3838 NETGENPlugin_Mesher::RemoveTmpFiles();
3840 std::cout.rdbuf( _coutBuffer );
3847 //================================================================================
3849 * \brief Set netgen mesh to delete at destruction
3851 //================================================================================
3853 void NETGENPlugin_NetgenLibWrapper::setMesh( Ng_Mesh* mesh )
3856 Ng_DeleteMesh( _ngMesh );
3860 //================================================================================
3862 * \brief Return a unique file name
3864 //================================================================================
3866 std::string NETGENPlugin_NetgenLibWrapper::getOutputFileName()
3868 std::string aTmpDir = SALOMEDS_Tool::GetTmpDir();
3870 TCollection_AsciiString aGenericName = (char*)aTmpDir.c_str();
3871 aGenericName += "NETGEN_";
3873 aGenericName += getpid();
3875 aGenericName += _getpid();
3877 aGenericName += "_";
3878 aGenericName += Abs((Standard_Integer)(long) aGenericName.ToCString());
3879 aGenericName += ".out";
3881 return aGenericName.ToCString();
3884 //================================================================================
3886 * \brief Remove file with netgen output
3888 //================================================================================
3890 void NETGENPlugin_NetgenLibWrapper::removeOutputFile()
3892 if ( !_outputFileName.empty() )
3894 if ( netgen::mycout )
3896 delete netgen::mycout;
3900 string tmpDir = SALOMEDS_Tool::GetDirFromPath ( _outputFileName );
3901 string aFileName = SALOMEDS_Tool::GetNameFromPath( _outputFileName ) + ".out";
3902 SALOMEDS::ListOfFileNames_var aFiles = new SALOMEDS::ListOfFileNames;
3904 aFiles[0] = aFileName.c_str();
3906 SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.c_str(), aFiles.in(), true );