1 // Copyright (C) 2007-2014 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 //=============================================================================
215 void SetLocalSize(TopoDS_Shape GeomShape, double LocalSize)
217 TopAbs_ShapeEnum GeomType = GeomShape.ShapeType();
218 if (GeomType == TopAbs_COMPOUND) {
219 for (TopoDS_Iterator it (GeomShape); it.More(); it.Next()) {
220 SetLocalSize(it.Value(), LocalSize);
225 if (! ShapesWithLocalSize.Contains(GeomShape))
226 key = ShapesWithLocalSize.Add(GeomShape);
228 key = ShapesWithLocalSize.FindIndex(GeomShape);
229 if (GeomType == TopAbs_VERTEX) {
230 VertexId2LocalSize[key] = LocalSize;
231 } else if (GeomType == TopAbs_EDGE) {
232 EdgeId2LocalSize[key] = LocalSize;
233 } else if (GeomType == TopAbs_FACE) {
234 FaceId2LocalSize[key] = LocalSize;
238 //=============================================================================
240 * Pass parameters to NETGEN
242 //=============================================================================
243 void NETGENPlugin_Mesher::SetParameters(const NETGENPlugin_Hypothesis* hyp)
247 netgen::MeshingParameters& mparams = netgen::mparam;
248 // Initialize global NETGEN parameters:
249 // maximal mesh segment size
250 mparams.maxh = hyp->GetMaxSize();
251 // maximal mesh element linear size
252 mparams.minh = hyp->GetMinSize();
253 // minimal number of segments per edge
254 mparams.segmentsperedge = hyp->GetNbSegPerEdge();
255 // rate of growth of size between elements
256 mparams.grading = hyp->GetGrowthRate();
257 // safety factor for curvatures (elements per radius)
258 mparams.curvaturesafety = hyp->GetNbSegPerRadius();
259 // create elements of second order
260 mparams.secondorder = hyp->GetSecondOrder() ? 1 : 0;
261 // quad-dominated surface meshing
262 // only triangles are allowed for volumic mesh (before realizing IMP 0021676)
264 mparams.quad = hyp->GetQuadAllowed() ? 1 : 0;
265 _optimize = hyp->GetOptimize();
266 _fineness = hyp->GetFineness();
267 mparams.uselocalh = hyp->GetSurfaceCurvature();
268 netgen::merge_solids = hyp->GetFuseEdges();
271 SMESH_Gen_i* smeshGen_i = SMESH_Gen_i::GetSMESHGen();
272 CORBA::Object_var anObject = smeshGen_i->GetNS()->Resolve("/myStudyManager");
273 SALOMEDS::StudyManager_var aStudyMgr = SALOMEDS::StudyManager::_narrow(anObject);
274 SALOMEDS::Study_var myStudy = aStudyMgr->GetStudyByID(hyp->GetStudyId());
276 const NETGENPlugin_Hypothesis::TLocalSize localSizes = hyp->GetLocalSizesAndEntries();
277 NETGENPlugin_Hypothesis::TLocalSize::const_iterator it = localSizes.begin();
278 for (it ; it != localSizes.end() ; it++)
280 std::string entry = (*it).first;
281 double val = (*it).second;
283 GEOM::GEOM_Object_var aGeomObj;
284 TopoDS_Shape S = TopoDS_Shape();
285 SALOMEDS::SObject_var aSObj = myStudy->FindObjectID( entry.c_str() );
286 if (!aSObj->_is_nil()) {
287 CORBA::Object_var obj = aSObj->GetObject();
288 aGeomObj = GEOM::GEOM_Object::_narrow(obj);
291 if ( !aGeomObj->_is_nil() )
292 S = smeshGen_i->GeomObjectToShape( aGeomObj.in() );
294 SetLocalSize(S, val);
299 //=============================================================================
301 * Pass simple parameters to NETGEN
303 //=============================================================================
305 void NETGENPlugin_Mesher::SetParameters(const NETGENPlugin_SimpleHypothesis_2D* hyp)
309 SetDefaultParameters();
312 //=============================================================================
314 * Link - a pair of integer numbers
316 //=============================================================================
320 Link(int _n1, int _n2) : n1(_n1), n2(_n2) {}
321 Link() : n1(0), n2(0) {}
324 int HashCode(const Link& aLink, int aLimit)
326 return HashCode(aLink.n1 + aLink.n2, aLimit);
329 Standard_Boolean IsEqual(const Link& aLink1, const Link& aLink2)
331 return (aLink1.n1 == aLink2.n1 && aLink1.n2 == aLink2.n2 ||
332 aLink1.n1 == aLink2.n2 && aLink1.n2 == aLink2.n1);
337 //================================================================================
339 * \brief return id of netgen point corresponding to SMDS node
341 //================================================================================
342 typedef map< const SMDS_MeshNode*, int > TNode2IdMap;
344 int ngNodeId( const SMDS_MeshNode* node,
345 netgen::Mesh& ngMesh,
346 TNode2IdMap& nodeNgIdMap)
348 int newNgId = ngMesh.GetNP() + 1;
350 TNode2IdMap::iterator node_id = nodeNgIdMap.insert( make_pair( node, newNgId )).first;
352 if ( node_id->second == newNgId)
354 #if defined(DUMP_SEGMENTS) || defined(DUMP_TRIANGLES)
355 cout << "Ng " << newNgId << " - " << node;
357 netgen::MeshPoint p( netgen::Point<3> (node->X(), node->Y(), node->Z()) );
358 ngMesh.AddPoint( p );
360 return node_id->second;
363 //================================================================================
365 * \brief Return computed EDGEs connected to the given one
367 //================================================================================
369 list< TopoDS_Edge > getConnectedEdges( const TopoDS_Edge& edge,
370 const TopoDS_Face& face,
371 const set< SMESH_subMesh* > & computedSM,
372 const SMESH_MesherHelper& helper,
373 map< SMESH_subMesh*, set< int > >& addedEdgeSM2Faces)
376 list< TopoDS_Edge > edges;
377 list< int > nbEdgesInWire;
378 int nbWires = SMESH_Block::GetOrderedEdges( face, edges, nbEdgesInWire);
380 // find <edge> within <edges>
381 list< TopoDS_Edge >::iterator eItFwd = edges.begin();
382 for ( ; eItFwd != edges.end(); ++eItFwd )
383 if ( edge.IsSame( *eItFwd ))
385 if ( eItFwd == edges.end()) return list< TopoDS_Edge>();
387 if ( eItFwd->Orientation() >= TopAbs_INTERNAL )
389 // connected INTERNAL edges returned from GetOrderedEdges() are wrongly oriented
390 // so treat each INTERNAL edge separately
391 TopoDS_Edge e = *eItFwd;
393 edges.push_back( e );
397 // get all computed EDGEs connected to <edge>
399 list< TopoDS_Edge >::iterator eItBack = eItFwd, ePrev;
400 TopoDS_Vertex vCommon;
401 TopTools_MapOfShape eAdded; // map used not to add a seam edge twice to <edges>
404 // put edges before <edge> to <edges> back
405 while ( edges.begin() != eItFwd )
406 edges.splice( edges.end(), edges, edges.begin() );
410 while ( ++eItFwd != edges.end() )
412 SMESH_subMesh* sm = helper.GetMesh()->GetSubMesh( *eItFwd );
414 bool connected = TopExp::CommonVertex( *ePrev, *eItFwd, vCommon );
415 bool computed = sm->IsMeshComputed();
416 bool added = addedEdgeSM2Faces[ sm ].count( helper.GetSubShapeID() );
417 bool doubled = !eAdded.Add( *eItFwd );
418 bool orientOK = (( ePrev ->Orientation() < TopAbs_INTERNAL ) ==
419 ( eItFwd->Orientation() < TopAbs_INTERNAL ) );
420 if ( !connected || !computed || !orientOK || added || doubled )
422 // stop advancement; move edges from tail to head
423 while ( edges.back() != *ePrev )
424 edges.splice( edges.begin(), edges, --edges.end() );
430 while ( eItBack != edges.begin() )
434 SMESH_subMesh* sm = helper.GetMesh()->GetSubMesh( *eItBack );
436 bool connected = TopExp::CommonVertex( *ePrev, *eItBack, vCommon );
437 bool computed = sm->IsMeshComputed();
438 bool added = addedEdgeSM2Faces[ sm ].count( helper.GetSubShapeID() );
439 bool doubled = !eAdded.Add( *eItBack );
440 bool orientOK = (( ePrev ->Orientation() < TopAbs_INTERNAL ) ==
441 ( eItBack->Orientation() < TopAbs_INTERNAL ) );
442 if ( !connected || !computed || !orientOK || added || doubled)
445 edges.erase( edges.begin(), ePrev );
449 if ( edges.front() != edges.back() )
451 // assure that the 1st vertex is meshed
452 TopoDS_Edge eLast = edges.back();
453 while ( !SMESH_Algo::VertexNode( SMESH_MesherHelper::IthVertex( 0, edges.front()), helper.GetMeshDS())
455 edges.front() != eLast )
456 edges.splice( edges.end(), edges, edges.begin() );
461 //================================================================================
463 * \brief Make triangulation of a shape precise enough
465 //================================================================================
467 void updateTriangulation( const TopoDS_Shape& shape )
469 // static set< Poly_Triangulation* > updated;
471 // TopLoc_Location loc;
472 // TopExp_Explorer fExp( shape, TopAbs_FACE );
473 // for ( ; fExp.More(); fExp.Next() )
475 // Handle(Poly_Triangulation) triangulation =
476 // BRep_Tool::Triangulation ( TopoDS::Face( fExp.Current() ), loc);
477 // if ( triangulation.IsNull() ||
478 // updated.insert( triangulation.operator->() ).second )
480 // BRepTools::Clean (shape);
483 BRepMesh_IncrementalMesh e(shape, 0.01, true);
485 catch (Standard_Failure)
488 // updated.erase( triangulation.operator->() );
489 // triangulation = BRep_Tool::Triangulation ( TopoDS::Face( fExp.Current() ), loc);
490 // updated.insert( triangulation.operator->() );
494 //================================================================================
496 * \brief Returns a medium node either existing in SMESH of created by NETGEN
497 * \param [in] corner1 - corner node 1
498 * \param [in] corner2 - corner node 2
499 * \param [in] defaultMedium - the node created by NETGEN
500 * \param [in] helper - holder of medium nodes existing in SMESH
501 * \return const SMDS_MeshNode* - the result node
503 //================================================================================
505 const SMDS_MeshNode* mediumNode( const SMDS_MeshNode* corner1,
506 const SMDS_MeshNode* corner2,
507 const SMDS_MeshNode* defaultMedium,
508 const SMESH_MesherHelper* helper)
512 TLinkNodeMap::const_iterator l2n =
513 helper->GetTLinkNodeMap().find( SMESH_TLink( corner1, corner2 ));
514 if ( l2n != helper->GetTLinkNodeMap().end() )
515 defaultMedium = l2n->second;
517 return defaultMedium;
520 //================================================================================
522 * \brief Assure that mesh on given shapes is quadratic
524 //================================================================================
526 void makeQuadratic( const TopTools_IndexedMapOfShape& shapes,
529 for ( int i = 1; i <= shapes.Extent(); ++i )
531 SMESHDS_SubMesh* smDS = mesh->GetMeshDS()->MeshElements( shapes(i) );
532 if ( !smDS ) continue;
533 SMDS_ElemIteratorPtr elemIt = smDS->GetElements();
534 if ( !elemIt->more() ) continue;
535 const SMDS_MeshElement* e = elemIt->next();
536 if ( !e || e->IsQuadratic() )
539 TIDSortedElemSet elems;
541 while ( elemIt->more() )
542 elems.insert( elems.end(), elemIt->next() );
544 SMESH_MeshEditor( mesh ).ConvertToQuadratic( /*3d=*/false, elems, /*biQuad=*/false );
550 //================================================================================
552 * \brief Initialize netgen::OCCGeometry with OCCT shape
554 //================================================================================
556 void NETGENPlugin_Mesher::PrepareOCCgeometry(netgen::OCCGeometry& occgeo,
557 const TopoDS_Shape& shape,
559 list< SMESH_subMesh* > * meshedSM,
560 NETGENPlugin_Internals* intern)
562 updateTriangulation( shape );
565 BRepBndLib::Add (shape, bb);
566 double x1,y1,z1,x2,y2,z2;
567 bb.Get (x1,y1,z1,x2,y2,z2);
568 MESSAGE("shape bounding box:\n" <<
569 "(" << x1 << " " << y1 << " " << z1 << ") " <<
570 "(" << x2 << " " << y2 << " " << z2 << ")");
571 netgen::Point<3> p1 = netgen::Point<3> (x1,y1,z1);
572 netgen::Point<3> p2 = netgen::Point<3> (x2,y2,z2);
573 occgeo.boundingbox = netgen::Box<3> (p1,p2);
575 occgeo.shape = shape;
578 // fill maps of shapes of occgeo with not yet meshed subshapes
580 // get root submeshes
581 list< SMESH_subMesh* > rootSM;
582 const int shapeID = mesh.GetMeshDS()->ShapeToIndex( shape );
583 if ( shapeID > 0 ) { // SMESH_subMesh with ID 0 may exist, don't use it!
584 rootSM.push_back( mesh.GetSubMesh( shape ));
587 for ( TopoDS_Iterator it( shape ); it.More(); it.Next() )
588 rootSM.push_back( mesh.GetSubMesh( it.Value() ));
591 // add subshapes of empty submeshes
592 list< SMESH_subMesh* >::iterator rootIt = rootSM.begin(), rootEnd = rootSM.end();
593 for ( ; rootIt != rootEnd; ++rootIt ) {
594 SMESH_subMesh * root = *rootIt;
595 SMESH_subMeshIteratorPtr smIt = root->getDependsOnIterator(/*includeSelf=*/true,
596 /*complexShapeFirst=*/true);
597 // to find a right orientation of subshapes (PAL20462)
598 TopTools_IndexedMapOfShape subShapes;
599 TopExp::MapShapes(root->GetSubShape(), subShapes);
600 while ( smIt->more() )
602 SMESH_subMesh* sm = smIt->next();
603 TopoDS_Shape shape = sm->GetSubShape();
604 if ( intern && intern->isShapeToPrecompute( shape ))
606 if ( !meshedSM || sm->IsEmpty() )
608 if ( shape.ShapeType() != TopAbs_VERTEX )
609 shape = subShapes( subShapes.FindIndex( shape ));// shape -> index -> oriented shape
610 if ( shape.Orientation() >= TopAbs_INTERNAL )
611 shape.Orientation( TopAbs_FORWARD ); // isuue 0020676
612 switch ( shape.ShapeType() ) {
613 case TopAbs_FACE : occgeo.fmap.Add( shape ); break;
614 case TopAbs_EDGE : occgeo.emap.Add( shape ); break;
615 case TopAbs_VERTEX: occgeo.vmap.Add( shape ); break;
616 case TopAbs_SOLID :occgeo.somap.Add( shape ); break;
620 // collect submeshes of meshed shapes
623 const int dim = SMESH_Gen::GetShapeDim( shape );
624 meshedSM[ dim ].push_back( sm );
628 occgeo.facemeshstatus.SetSize (occgeo.fmap.Extent());
629 occgeo.facemeshstatus = 0;
630 occgeo.face_maxh_modified.SetSize(occgeo.fmap.Extent());
631 occgeo.face_maxh_modified = 0;
632 occgeo.face_maxh.SetSize(occgeo.fmap.Extent());
633 occgeo.face_maxh = netgen::mparam.maxh;
636 //================================================================================
638 * \brief Return a default min size value suitable for the given geometry.
640 //================================================================================
642 double NETGENPlugin_Mesher::GetDefaultMinSize(const TopoDS_Shape& geom,
643 const double maxSize)
645 updateTriangulation( geom );
649 const int* pi[4] = { &i1, &i2, &i3, &i1 };
652 TopExp_Explorer fExp( geom, TopAbs_FACE );
653 for ( ; fExp.More(); fExp.Next() )
655 Handle(Poly_Triangulation) triangulation =
656 BRep_Tool::Triangulation ( TopoDS::Face( fExp.Current() ), loc);
657 if ( triangulation.IsNull() ) continue;
658 const double fTol = BRep_Tool::Tolerance( TopoDS::Face( fExp.Current() ));
659 const TColgp_Array1OfPnt& points = triangulation->Nodes();
660 const Poly_Array1OfTriangle& trias = triangulation->Triangles();
661 for ( int iT = trias.Lower(); iT <= trias.Upper(); ++iT )
663 trias(iT).Get( i1, i2, i3 );
664 for ( int j = 0; j < 3; ++j )
666 double dist2 = points(*pi[j]).SquareDistance( points( *pi[j+1] ));
667 if ( dist2 < minh && fTol*fTol < dist2 )
669 bb.Add( points(*pi[j]));
673 if ( minh > 0.25 * bb.SquareExtent() ) // simple geometry, rough triangulation
675 minh = 1e-3 * sqrt( bb.SquareExtent());
676 //cout << "BND BOX minh = " <<minh << endl;
680 minh = 3 * sqrt( minh ); // triangulation for visualization is rather fine
681 //cout << "TRIANGULATION minh = " <<minh << endl;
683 if ( minh > 0.5 * maxSize )
689 //================================================================================
691 * \brief Restrict size of elements at a given point
693 //================================================================================
695 void NETGENPlugin_Mesher::RestrictLocalSize(netgen::Mesh& ngMesh,
698 const bool overrideMinH)
700 if ( overrideMinH && netgen::mparam.minh > size )
702 ngMesh.SetMinimalH( size );
703 netgen::mparam.minh = size;
705 netgen::Point3d pi(p.X(), p.Y(), p.Z());
706 ngMesh.RestrictLocalH( pi, size );
709 //================================================================================
711 * \brief fill ngMesh with nodes and elements of computed submeshes
713 //================================================================================
715 bool NETGENPlugin_Mesher::FillNgMesh(netgen::OCCGeometry& occgeom,
716 netgen::Mesh& ngMesh,
717 vector<const SMDS_MeshNode*>& nodeVec,
718 const list< SMESH_subMesh* > & meshedSM,
719 SMESH_MesherHelper* quadHelper,
720 SMESH_ProxyMesh::Ptr proxyMesh)
722 TNode2IdMap nodeNgIdMap;
723 for ( int i = 1; i < nodeVec.size(); ++i )
724 nodeNgIdMap.insert( make_pair( nodeVec[i], i ));
726 TopTools_MapOfShape visitedShapes;
727 map< SMESH_subMesh*, set< int > > visitedEdgeSM2Faces;
728 set< SMESH_subMesh* > computedSM( meshedSM.begin(), meshedSM.end() );
730 SMESH_MesherHelper helper (*_mesh);
732 int faceNgID = ngMesh.GetNFD();
734 list< SMESH_subMesh* >::const_iterator smIt, smEnd = meshedSM.end();
735 for ( smIt = meshedSM.begin(); smIt != smEnd; ++smIt )
737 SMESH_subMesh* sm = *smIt;
738 if ( !visitedShapes.Add( sm->GetSubShape() ))
741 const SMESHDS_SubMesh * smDS = sm->GetSubMeshDS();
742 if ( !smDS ) continue;
744 switch ( sm->GetSubShape().ShapeType() )
746 case TopAbs_EDGE: { // EDGE
747 // ----------------------
748 TopoDS_Edge geomEdge = TopoDS::Edge( sm->GetSubShape() );
749 if ( geomEdge.Orientation() >= TopAbs_INTERNAL )
750 geomEdge.Orientation( TopAbs_FORWARD ); // issue 0020676
752 // Add ng segments for each not meshed FACE the EDGE bounds
753 PShapeIteratorPtr fIt = helper.GetAncestors( geomEdge, *sm->GetFather(), TopAbs_FACE );
754 while ( const TopoDS_Shape * anc = fIt->next() )
756 faceNgID = occgeom.fmap.FindIndex( *anc );
758 continue; // meshed face
760 int faceSMDSId = helper.GetMeshDS()->ShapeToIndex( *anc );
761 if ( visitedEdgeSM2Faces[ sm ].count( faceSMDSId ))
762 continue; // already treated EDGE
764 TopoDS_Face face = TopoDS::Face( occgeom.fmap( faceNgID ));
765 if ( face.Orientation() >= TopAbs_INTERNAL )
766 face.Orientation( TopAbs_FORWARD ); // issue 0020676
768 // get all meshed EDGEs of the FACE connected to geomEdge (issue 0021140)
769 helper.SetSubShape( face );
770 list< TopoDS_Edge > edges = getConnectedEdges( geomEdge, face, computedSM, helper,
771 visitedEdgeSM2Faces );
773 continue; // wrong ancestor?
775 // find out orientation of <edges> within <face>
776 TopoDS_Edge eNotSeam = edges.front();
777 if ( helper.HasSeam() )
779 list< TopoDS_Edge >::iterator eIt = edges.begin();
780 while ( helper.IsRealSeam( *eIt )) ++eIt;
781 if ( eIt != edges.end() )
784 TopAbs_Orientation fOri = helper.GetSubShapeOri( face, eNotSeam );
785 bool isForwad = ( fOri == eNotSeam.Orientation() || fOri >= TopAbs_INTERNAL );
787 // get all nodes from connected <edges>
788 bool isQuad = smDS->NbElements() ? smDS->GetElements()->next()->IsQuadratic() : false;
789 StdMeshers_FaceSide fSide( face, edges, _mesh, isForwad, isQuad );
790 const vector<UVPtStruct>& points = fSide.GetUVPtStruct();
791 int i, nbSeg = fSide.NbSegments();
793 // remember EDGEs of fSide to treat only once
794 for ( int iE = 0; iE < fSide.NbEdges(); ++iE )
795 visitedEdgeSM2Faces[ helper.GetMesh()->GetSubMesh( fSide.Edge(iE )) ].insert(faceSMDSId);
797 double otherSeamParam = 0;
802 int prevNgId = ngNodeId( points[0].node, ngMesh, nodeNgIdMap );
804 for ( i = 0; i < nbSeg; ++i )
806 const UVPtStruct& p1 = points[ i ];
807 const UVPtStruct& p2 = points[ i+1 ];
809 if ( p1.node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX ) //an EDGE begins
812 if ( helper.IsRealSeam( p1.node->getshapeId() ))
814 TopoDS_Edge e = fSide.Edge( fSide.EdgeIndex( 0.5 * ( p1.normParam + p2.normParam )));
815 isSeam = helper.IsRealSeam( e );
818 otherSeamParam = helper.GetOtherParam( helper.GetPeriodicIndex() & 1 ? p2.u : p2.v );
825 seg[1] = prevNgId = ngNodeId( p2.node, ngMesh, nodeNgIdMap );
826 // node param on curve
827 seg.epgeominfo[ 0 ].dist = p1.param;
828 seg.epgeominfo[ 1 ].dist = p2.param;
830 seg.epgeominfo[ 0 ].u = p1.u;
831 seg.epgeominfo[ 0 ].v = p1.v;
832 seg.epgeominfo[ 1 ].u = p2.u;
833 seg.epgeominfo[ 1 ].v = p2.v;
835 //geomEdge = fSide.Edge( fSide.EdgeIndex( 0.5 * ( p1.normParam + p2.normParam )));
836 //seg.epgeominfo[ 0 ].edgenr = seg.epgeominfo[ 1 ].edgenr = occgeom.emap.FindIndex( geomEdge );
838 //seg.epgeominfo[ iEnd ].edgenr = edgeID; // = geom.emap.FindIndex(edge);
839 seg.si = faceNgID; // = geom.fmap.FindIndex (face);
840 seg.edgenr = ngMesh.GetNSeg() + 1; // segment id
841 ngMesh.AddSegment (seg);
843 SMESH_TNodeXYZ np1( p1.node ), np2( p2.node );
844 RestrictLocalSize( ngMesh, 0.5*(np1+np2), (np1-np2).Modulus() );
847 cout << "Segment: " << seg.edgenr << " on SMESH face " << helper.GetMeshDS()->ShapeToIndex( face ) << endl
848 << "\tface index: " << seg.si << endl
849 << "\tp1: " << seg[0] << endl
850 << "\tp2: " << seg[1] << endl
851 << "\tp0 param: " << seg.epgeominfo[ 0 ].dist << endl
852 << "\tp0 uv: " << seg.epgeominfo[ 0 ].u <<", "<< seg.epgeominfo[ 0 ].v << endl
853 //<< "\tp0 edge: " << seg.epgeominfo[ 0 ].edgenr << endl
854 << "\tp1 param: " << seg.epgeominfo[ 1 ].dist << endl
855 << "\tp1 uv: " << seg.epgeominfo[ 1 ].u <<", "<< seg.epgeominfo[ 1 ].v << endl;
856 //<< "\tp1 edge: " << seg.epgeominfo[ 1 ].edgenr << endl;
860 if ( helper.GetPeriodicIndex() && 1 ) {
861 seg.epgeominfo[ 0 ].u = otherSeamParam;
862 seg.epgeominfo[ 1 ].u = otherSeamParam;
863 swap (seg.epgeominfo[0].v, seg.epgeominfo[1].v);
865 seg.epgeominfo[ 0 ].v = otherSeamParam;
866 seg.epgeominfo[ 1 ].v = otherSeamParam;
867 swap (seg.epgeominfo[0].u, seg.epgeominfo[1].u);
869 swap (seg[0], seg[1]);
870 swap (seg.epgeominfo[0].dist, seg.epgeominfo[1].dist);
871 seg.edgenr = ngMesh.GetNSeg() + 1; // segment id
872 ngMesh.AddSegment (seg);
874 cout << "Segment: " << seg.edgenr << endl
875 << "\t is SEAM (reverse) of the previous. "
876 << " Other " << (helper.GetPeriodicIndex() && 1 ? "U" : "V")
877 << " = " << otherSeamParam << endl;
880 else if ( fOri == TopAbs_INTERNAL )
882 swap (seg[0], seg[1]);
883 swap( seg.epgeominfo[0], seg.epgeominfo[1] );
884 seg.edgenr = ngMesh.GetNSeg() + 1; // segment id
885 ngMesh.AddSegment (seg);
887 cout << "Segment: " << seg.edgenr << endl << "\t is REVERSE of the previous" << endl;
891 } // loop on geomEdge ancestors
893 if ( quadHelper ) // remember medium nodes of sub-meshes
895 SMDS_ElemIteratorPtr edges = smDS->GetElements();
896 while ( edges->more() )
898 const SMDS_MeshElement* e = edges->next();
899 if ( !quadHelper->AddTLinks( static_cast< const SMDS_MeshEdge*>( e )))
905 } // case TopAbs_EDGE
907 case TopAbs_FACE: { // FACE
908 // ----------------------
909 const TopoDS_Face& geomFace = TopoDS::Face( sm->GetSubShape() );
910 helper.SetSubShape( geomFace );
911 bool isInternalFace = ( geomFace.Orientation() == TopAbs_INTERNAL );
913 // Find solids the geomFace bounds
914 int solidID1 = 0, solidID2 = 0;
915 StdMeshers_QuadToTriaAdaptor* quadAdaptor =
916 dynamic_cast<StdMeshers_QuadToTriaAdaptor*>( proxyMesh.get() );
919 solidID1 = occgeom.somap.FindIndex( quadAdaptor->GetShape() );
923 PShapeIteratorPtr solidIt = helper.GetAncestors( geomFace, *sm->GetFather(), TopAbs_SOLID);
924 while ( const TopoDS_Shape * solid = solidIt->next() )
926 int id = occgeom.somap.FindIndex ( *solid );
927 if ( solidID1 && id != solidID1 ) solidID2 = id;
931 // Add ng face descriptors of meshed faces
933 ngMesh.AddFaceDescriptor (netgen::FaceDescriptor(faceNgID, solidID1, solidID2, 0));
935 // if second oreder is required, even already meshed faces must be passed to NETGEN
936 int fID = occgeom.fmap.Add( geomFace );
937 while ( fID < faceNgID ) // geomFace is already in occgeom.fmap, add a copy
938 fID = occgeom.fmap.Add( BRepBuilderAPI_Copy( geomFace, /*copyGeom=*/false ));
939 // Problem with the second order in a quadrangular mesh remains.
940 // 1) All quadrangles generated by NETGEN are moved to an inexistent face
941 // by FillSMesh() (find "AddFaceDescriptor")
942 // 2) Temporary triangles generated by StdMeshers_QuadToTriaAdaptor
943 // are on faces where quadrangles were.
944 // Due to these 2 points, wrong geom faces are used while conversion to qudratic
945 // of the mentioned above quadrangles and triangles
947 // Orient the face correctly in solidID1 (issue 0020206)
948 bool reverse = false;
950 TopoDS_Shape solid = occgeom.somap( solidID1 );
951 TopAbs_Orientation faceOriInSolid = helper.GetSubShapeOri( solid, geomFace );
952 if ( faceOriInSolid >= 0 )
954 helper.IsReversedSubMesh( TopoDS::Face( geomFace.Oriented( faceOriInSolid )));
957 // Add surface elements
959 netgen::Element2d tri(3);
960 tri.SetIndex ( faceNgID );
963 #ifdef DUMP_TRIANGLES
964 cout << "SMESH face " << helper.GetMeshDS()->ShapeToIndex( geomFace )
965 << " internal="<<isInternalFace << endl;
968 smDS = proxyMesh->GetSubMesh( geomFace );
970 SMDS_ElemIteratorPtr faces = smDS->GetElements();
971 while ( faces->more() )
973 const SMDS_MeshElement* f = faces->next();
974 if ( f->NbNodes() % 3 != 0 ) // not triangle
976 PShapeIteratorPtr solidIt=helper.GetAncestors(geomFace,*sm->GetFather(),TopAbs_SOLID);
977 if ( const TopoDS_Shape * solid = solidIt->next() )
978 sm = _mesh->GetSubMesh( *solid );
979 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
980 smError.reset( new SMESH_ComputeError(COMPERR_BAD_INPUT_MESH,"Not triangle submesh"));
981 smError->myBadElements.push_back( f );
985 for ( int i = 0; i < 3; ++i )
987 const SMDS_MeshNode* node = f->GetNode( i ), * inFaceNode=0;
989 // get node UV on face
990 int shapeID = node->getshapeId();
991 if ( helper.IsSeamShape( shapeID ))
992 if ( helper.IsSeamShape( f->GetNodeWrap( i+1 )->getshapeId() ))
993 inFaceNode = f->GetNodeWrap( i-1 );
995 inFaceNode = f->GetNodeWrap( i+1 );
996 gp_XY uv = helper.GetNodeUV( geomFace, node, inFaceNode );
998 int ind = reverse ? 3-i : i+1;
999 tri.GeomInfoPi(ind).u = uv.X();
1000 tri.GeomInfoPi(ind).v = uv.Y();
1001 tri.PNum (ind) = ngNodeId( node, ngMesh, nodeNgIdMap );
1004 ngMesh.AddSurfaceElement (tri);
1005 #ifdef DUMP_TRIANGLES
1006 cout << tri << endl;
1009 if ( isInternalFace )
1011 swap( tri[1], tri[2] );
1012 ngMesh.AddSurfaceElement (tri);
1013 #ifdef DUMP_TRIANGLES
1014 cout << tri << endl;
1019 if ( quadHelper ) // remember medium nodes of sub-meshes
1021 SMDS_ElemIteratorPtr faces = smDS->GetElements();
1022 while ( faces->more() )
1024 const SMDS_MeshElement* f = faces->next();
1025 if ( !quadHelper->AddTLinks( static_cast< const SMDS_MeshFace*>( f )))
1031 } // case TopAbs_FACE
1033 case TopAbs_VERTEX: { // VERTEX
1034 // --------------------------
1035 // issue 0021405. Add node only if a VERTEX is shared by a not meshed EDGE,
1036 // else netgen removes a free node and nodeVector becomes invalid
1037 PShapeIteratorPtr ansIt = helper.GetAncestors( sm->GetSubShape(),
1041 while ( const TopoDS_Shape* e = ansIt->next() )
1043 SMESH_subMesh* eSub = helper.GetMesh()->GetSubMesh( *e );
1044 if (( toAdd = eSub->IsEmpty() )) break;
1048 SMDS_NodeIteratorPtr nodeIt = smDS->GetNodes();
1049 if ( nodeIt->more() )
1050 ngNodeId( nodeIt->next(), ngMesh, nodeNgIdMap );
1056 } // loop on submeshes
1059 nodeVec.resize( ngMesh.GetNP() + 1 );
1060 TNode2IdMap::iterator node_NgId, nodeNgIdEnd = nodeNgIdMap.end();
1061 for ( node_NgId = nodeNgIdMap.begin(); node_NgId != nodeNgIdEnd; ++node_NgId)
1062 nodeVec[ node_NgId->second ] = node_NgId->first;
1067 //================================================================================
1069 * \brief Duplicate mesh faces on internal geom faces
1071 //================================================================================
1073 void NETGENPlugin_Mesher::FixIntFaces(const netgen::OCCGeometry& occgeom,
1074 netgen::Mesh& ngMesh,
1075 NETGENPlugin_Internals& internalShapes)
1077 SMESHDS_Mesh* meshDS = internalShapes.getMesh().GetMeshDS();
1079 // find ng indices of internal faces
1081 for ( int ngFaceID = 1; ngFaceID <= occgeom.fmap.Extent(); ++ngFaceID )
1083 int smeshID = meshDS->ShapeToIndex( occgeom.fmap( ngFaceID ));
1084 if ( internalShapes.isInternalShape( smeshID ))
1085 ngFaceIds.insert( ngFaceID );
1087 if ( !ngFaceIds.empty() )
1090 int i, nbFaces = ngMesh.GetNSE();
1091 for (int i = 1; i <= nbFaces; ++i)
1093 netgen::Element2d elem = ngMesh.SurfaceElement(i);
1094 if ( ngFaceIds.count( elem.GetIndex() ))
1096 swap( elem[1], elem[2] );
1097 ngMesh.AddSurfaceElement (elem);
1105 //================================================================================
1106 // define gp_XY_Subtracted pointer to function calling gp_XY::Subtracted(gp_XY)
1107 gp_XY_FunPtr(Subtracted);
1108 //gp_XY_FunPtr(Added);
1110 //================================================================================
1112 * \brief Evaluate distance between two 2d points along the surface
1114 //================================================================================
1116 double evalDist( const gp_XY& uv1,
1118 const Handle(Geom_Surface)& surf,
1119 const int stopHandler=-1)
1121 if ( stopHandler > 0 ) // continue recursion
1123 gp_XY mid = SMESH_MesherHelper::GetMiddleUV( surf, uv1, uv2 );
1124 return evalDist( uv1,mid, surf, stopHandler-1 ) + evalDist( mid,uv2, surf, stopHandler-1 );
1126 double dist3D = surf->Value( uv1.X(), uv1.Y() ).Distance( surf->Value( uv2.X(), uv2.Y() ));
1127 if ( stopHandler == 0 ) // stop recursion
1130 // start recursion if necessary
1131 double dist2D = SMESH_MesherHelper::applyIn2D(surf, uv1, uv2, gp_XY_Subtracted, 0).Modulus();
1132 if ( fabs( dist3D - dist2D ) < dist2D * 1e-10 )
1133 return dist3D; // equal parametrization of a planar surface
1135 return evalDist( uv1, uv2, surf, 3 ); // start recursion
1138 //================================================================================
1140 * \brief Data of vertex internal in geom face
1142 //================================================================================
1146 gp_XY uv; //!< UV in face parametric space
1147 int ngId; //!< ng id of corrsponding node
1148 gp_XY uvClose; //!< UV of closest boundary node
1149 int ngIdClose; //!< ng id of closest boundary node
1152 //================================================================================
1154 * \brief Data of vertex internal in solid
1156 //================================================================================
1160 int ngId; //!< ng id of corresponding node
1161 int ngIdClose; //!< ng id of closest 2d mesh element
1162 int ngIdCloseN; //!< ng id of closest node of the closest 2d mesh element
1165 inline double dist2(const netgen::MeshPoint& p1, const netgen::MeshPoint& p2)
1167 return gp_Pnt( NGPOINT_COORDS(p1)).SquareDistance( gp_Pnt( NGPOINT_COORDS(p2)));
1171 //================================================================================
1173 * \brief Make netgen take internal vertices in faces into account by adding
1174 * segments including internal vertices
1176 * This function works in supposition that 1D mesh is already computed in ngMesh
1178 //================================================================================
1180 void NETGENPlugin_Mesher::AddIntVerticesInFaces(const netgen::OCCGeometry& occgeom,
1181 netgen::Mesh& ngMesh,
1182 vector<const SMDS_MeshNode*>& nodeVec,
1183 NETGENPlugin_Internals& internalShapes)
1185 if ( nodeVec.size() < ngMesh.GetNP() )
1186 nodeVec.resize( ngMesh.GetNP(), 0 );
1188 SMESHDS_Mesh* meshDS = internalShapes.getMesh().GetMeshDS();
1189 SMESH_MesherHelper helper( internalShapes.getMesh() );
1191 const map<int,list<int> >& face2Vert = internalShapes.getFacesWithVertices();
1192 map<int,list<int> >::const_iterator f2v = face2Vert.begin();
1193 for ( ; f2v != face2Vert.end(); ++f2v )
1195 const TopoDS_Face& face = TopoDS::Face( meshDS->IndexToShape( f2v->first ));
1196 if ( face.IsNull() ) continue;
1197 int faceNgID = occgeom.fmap.FindIndex (face);
1198 if ( faceNgID < 0 ) continue;
1200 TopLoc_Location loc;
1201 Handle(Geom_Surface) surf = BRep_Tool::Surface(face,loc);
1203 helper.SetSubShape( face );
1204 helper.SetElementsOnShape( true );
1206 // Get data of internal vertices and add them to ngMesh
1208 multimap< double, TIntVData > dist2VData; // sort vertices by distance from boundary nodes
1210 int i, nbSegInit = ngMesh.GetNSeg();
1212 // boundary characteristics
1213 double totSegLen2D = 0;
1216 const list<int>& iVertices = f2v->second;
1217 list<int>::const_iterator iv = iVertices.begin();
1218 for ( int nbV = 0; iv != iVertices.end(); ++iv, nbV++ )
1221 // get node on vertex
1222 const TopoDS_Vertex V = TopoDS::Vertex( meshDS->IndexToShape( *iv ));
1223 const SMDS_MeshNode * nV = SMESH_Algo::VertexNode( V, meshDS );
1226 SMESH_subMesh* sm = helper.GetMesh()->GetSubMesh( V );
1227 sm->ComputeStateEngine( SMESH_subMesh::COMPUTE );
1228 nV = SMESH_Algo::VertexNode( V, meshDS );
1229 if ( !nV ) continue;
1232 netgen::MeshPoint mp( netgen::Point<3> (nV->X(), nV->Y(), nV->Z()) );
1233 ngMesh.AddPoint ( mp, 1, netgen::EDGEPOINT );
1234 vData.ngId = ngMesh.GetNP();
1235 nodeVec.push_back( nV );
1239 vData.uv = helper.GetNodeUV( face, nV, 0, &uvOK );
1240 if ( !uvOK ) helper.CheckNodeUV( face, nV, vData.uv, BRep_Tool::Tolerance(V),/*force=*/1);
1242 // loop on all segments of the face to find the node closest to vertex and to count
1243 // average segment 2d length
1244 double closeDist2 = numeric_limits<double>::max(), dist2;
1246 for (i = 1; i <= ngMesh.GetNSeg(); ++i)
1248 netgen::Segment & seg = ngMesh.LineSegment(i);
1249 if ( seg.si != faceNgID ) continue;
1251 for ( int iEnd = 0; iEnd < 2; ++iEnd)
1253 uv[iEnd].SetCoord( seg.epgeominfo[iEnd].u, seg.epgeominfo[iEnd].v );
1254 if ( ngIdLast == seg[ iEnd ] ) continue;
1255 dist2 = helper.applyIn2D(surf, uv[iEnd], vData.uv, gp_XY_Subtracted,0).SquareModulus();
1256 if ( dist2 < closeDist2 )
1257 vData.ngIdClose = seg[ iEnd ], vData.uvClose = uv[iEnd], closeDist2 = dist2;
1258 ngIdLast = seg[ iEnd ];
1262 totSegLen2D += helper.applyIn2D(surf, uv[0], uv[1], gp_XY_Subtracted, false).Modulus();
1266 dist2VData.insert( make_pair( closeDist2, vData ));
1269 if ( totNbSeg == 0 ) break;
1270 double avgSegLen2d = totSegLen2D / totNbSeg;
1272 // Loop on vertices to add segments
1274 multimap< double, TIntVData >::iterator dist_vData = dist2VData.begin();
1275 for ( ; dist_vData != dist2VData.end(); ++dist_vData )
1277 double closeDist2 = dist_vData->first, dist2;
1278 TIntVData & vData = dist_vData->second;
1280 // try to find more close node among segments added for internal vertices
1281 for (i = nbSegInit+1; i <= ngMesh.GetNSeg(); ++i)
1283 netgen::Segment & seg = ngMesh.LineSegment(i);
1284 if ( seg.si != faceNgID ) continue;
1286 for ( int iEnd = 0; iEnd < 2; ++iEnd)
1288 uv[iEnd].SetCoord( seg.epgeominfo[iEnd].u, seg.epgeominfo[iEnd].v );
1289 dist2 = helper.applyIn2D(surf, uv[iEnd], vData.uv, gp_XY_Subtracted,0).SquareModulus();
1290 if ( dist2 < closeDist2 )
1291 vData.ngIdClose = seg[ iEnd ], vData.uvClose = uv[iEnd], closeDist2 = dist2;
1294 // decide whether to use the closest node as the second end of segment or to
1295 // create a new point
1296 int segEnd1 = vData.ngId;
1297 int segEnd2 = vData.ngIdClose; // to use closest node
1298 gp_XY uvV = vData.uv, uvP = vData.uvClose;
1299 double segLenHint = ngMesh.GetH( ngMesh.Point( vData.ngId ));
1300 double nodeDist2D = sqrt( closeDist2 );
1301 double nodeDist3D = evalDist( vData.uv, vData.uvClose, surf );
1302 bool avgLenOK = ( avgSegLen2d < 0.75 * nodeDist2D );
1303 bool hintLenOK = ( segLenHint < 0.75 * nodeDist3D );
1304 //cout << "uvV " << uvV.X() <<","<<uvV.Y() << " ";
1305 if ( hintLenOK || avgLenOK )
1307 // create a point between the closest node and V
1310 double r = min( 0.5, ( hintLenOK ? segLenHint/nodeDist3D : avgSegLen2d/nodeDist2D ));
1311 // direction from V to closet node in 2D
1312 gp_Dir2d v2n( helper.applyIn2D(surf, uvP, uvV, gp_XY_Subtracted, false ));
1314 uvP = vData.uv + r * nodeDist2D * v2n.XY();
1315 gp_Pnt P = surf->Value( uvP.X(), uvP.Y() ).Transformed( loc );
1317 netgen::MeshPoint mp( netgen::Point<3> (P.X(), P.Y(), P.Z()));
1318 ngMesh.AddPoint ( mp, 1, netgen::EDGEPOINT );
1319 segEnd2 = ngMesh.GetNP();
1320 //cout << "Middle " << r << " uv " << uvP.X() << "," << uvP.Y() << "( " << ngMesh.Point(segEnd2).X()<<","<<ngMesh.Point(segEnd2).Y()<<","<<ngMesh.Point(segEnd2).Z()<<" )"<< endl;
1321 SMDS_MeshNode * nP = helper.AddNode(P.X(), P.Y(), P.Z());
1322 nodeVec.push_back( nP );
1324 //else cout << "at Node " << " uv " << uvP.X() << "," << uvP.Y() << endl;
1327 netgen::Segment seg;
1329 if ( segEnd1 > segEnd2 ) swap( segEnd1, segEnd2 ), swap( uvV, uvP );
1330 seg[0] = segEnd1; // ng node id
1331 seg[1] = segEnd2; // ng node id
1332 seg.edgenr = ngMesh.GetNSeg() + 1;// segment id
1335 seg.epgeominfo[ 0 ].dist = 0; // param on curve
1336 seg.epgeominfo[ 0 ].u = uvV.X();
1337 seg.epgeominfo[ 0 ].v = uvV.Y();
1338 seg.epgeominfo[ 1 ].dist = 1; // param on curve
1339 seg.epgeominfo[ 1 ].u = uvP.X();
1340 seg.epgeominfo[ 1 ].v = uvP.Y();
1342 // seg.epgeominfo[ 0 ].edgenr = 10; // = geom.emap.FindIndex(edge);
1343 // seg.epgeominfo[ 1 ].edgenr = 10; // = geom.emap.FindIndex(edge);
1345 ngMesh.AddSegment (seg);
1347 // add reverse segment
1348 swap (seg[0], seg[1]);
1349 swap( seg.epgeominfo[0], seg.epgeominfo[1] );
1350 seg.edgenr = ngMesh.GetNSeg() + 1; // segment id
1351 ngMesh.AddSegment (seg);
1357 //================================================================================
1359 * \brief Make netgen take internal vertices in solids into account by adding
1360 * faces including internal vertices
1362 * This function works in supposition that 2D mesh is already computed in ngMesh
1364 //================================================================================
1366 void NETGENPlugin_Mesher::AddIntVerticesInSolids(const netgen::OCCGeometry& occgeom,
1367 netgen::Mesh& ngMesh,
1368 vector<const SMDS_MeshNode*>& nodeVec,
1369 NETGENPlugin_Internals& internalShapes)
1371 #ifdef DUMP_TRIANGLES_SCRIPT
1372 // create a python script making a mesh containing triangles added for internal vertices
1373 ofstream py(DUMP_TRIANGLES_SCRIPT);
1374 py << "import SMESH"<< endl
1375 << "from salome.smesh import smeshBuilder"<<endl
1376 << "smesh = smeshBuilder.New(salome.myStudy)"
1377 << "m = smesh.Mesh(name='triangles')" << endl;
1379 if ( nodeVec.size() < ngMesh.GetNP() )
1380 nodeVec.resize( ngMesh.GetNP(), 0 );
1382 SMESHDS_Mesh* meshDS = internalShapes.getMesh().GetMeshDS();
1383 SMESH_MesherHelper helper( internalShapes.getMesh() );
1385 const map<int,list<int> >& so2Vert = internalShapes.getSolidsWithVertices();
1386 map<int,list<int> >::const_iterator s2v = so2Vert.begin();
1387 for ( ; s2v != so2Vert.end(); ++s2v )
1389 const TopoDS_Shape& solid = meshDS->IndexToShape( s2v->first );
1390 if ( solid.IsNull() ) continue;
1391 int solidNgID = occgeom.somap.FindIndex (solid);
1392 if ( solidNgID < 0 && !occgeom.somap.IsEmpty() ) continue;
1394 helper.SetSubShape( solid );
1395 helper.SetElementsOnShape( true );
1397 // find ng indices of faces within the solid
1399 for (TopExp_Explorer fExp(solid, TopAbs_FACE); fExp.More(); fExp.Next() )
1400 ngFaceIds.insert( occgeom.fmap.FindIndex( fExp.Current() ));
1401 if ( ngFaceIds.size() == 1 && *ngFaceIds.begin() == 0 )
1402 ngFaceIds.insert( 1 );
1404 // Get data of internal vertices and add them to ngMesh
1406 multimap< double, TIntVSoData > dist2VData; // sort vertices by distance from ng faces
1408 int i, nbFaceInit = ngMesh.GetNSE();
1410 // boundary characteristics
1411 double totSegLen = 0;
1414 const list<int>& iVertices = s2v->second;
1415 list<int>::const_iterator iv = iVertices.begin();
1416 for ( int nbV = 0; iv != iVertices.end(); ++iv, nbV++ )
1419 const TopoDS_Vertex V = TopoDS::Vertex( meshDS->IndexToShape( *iv ));
1421 // get node on vertex
1422 const SMDS_MeshNode * nV = SMESH_Algo::VertexNode( V, meshDS );
1425 SMESH_subMesh* sm = helper.GetMesh()->GetSubMesh( V );
1426 sm->ComputeStateEngine( SMESH_subMesh::COMPUTE );
1427 nV = SMESH_Algo::VertexNode( V, meshDS );
1428 if ( !nV ) continue;
1431 netgen::MeshPoint mpV( netgen::Point<3> (nV->X(), nV->Y(), nV->Z()) );
1432 ngMesh.AddPoint ( mpV, 1, netgen::FIXEDPOINT );
1433 vData.ngId = ngMesh.GetNP();
1434 nodeVec.push_back( nV );
1436 // loop on all 2d elements to find the one closest to vertex and to count
1437 // average segment length
1438 double closeDist2 = numeric_limits<double>::max(), avgDist2;
1439 for (i = 1; i <= ngMesh.GetNSE(); ++i)
1441 const netgen::Element2d& elem = ngMesh.SurfaceElement(i);
1442 if ( !ngFaceIds.count( elem.GetIndex() )) continue;
1444 multimap< double, int> dist2nID; // sort nodes of element by distance from V
1445 for ( int j = 0; j < elem.GetNP(); ++j)
1447 netgen::MeshPoint mp = ngMesh.Point( elem[j] );
1448 double d2 = dist2( mpV, mp );
1449 dist2nID.insert( make_pair( d2, elem[j] ));
1450 avgDist2 += d2 / elem.GetNP();
1452 totNbSeg++, totSegLen+= sqrt( dist2( mp, ngMesh.Point( elem[(j+1)%elem.GetNP()])));
1454 double dist = dist2nID.begin()->first; //avgDist2;
1455 if ( dist < closeDist2 )
1456 vData.ngIdClose= i, vData.ngIdCloseN= dist2nID.begin()->second, closeDist2= dist;
1458 dist2VData.insert( make_pair( closeDist2, vData ));
1461 if ( totNbSeg == 0 ) break;
1462 double avgSegLen = totSegLen / totNbSeg;
1464 // Loop on vertices to add triangles
1466 multimap< double, TIntVSoData >::iterator dist_vData = dist2VData.begin();
1467 for ( ; dist_vData != dist2VData.end(); ++dist_vData )
1469 double closeDist2 = dist_vData->first;
1470 TIntVSoData & vData = dist_vData->second;
1472 const netgen::MeshPoint& mpV = ngMesh.Point( vData.ngId );
1474 // try to find more close face among ones added for internal vertices
1475 for (i = nbFaceInit+1; i <= ngMesh.GetNSE(); ++i)
1477 double avgDist2 = 0;
1478 multimap< double, int> dist2nID;
1479 const netgen::Element2d& elem = ngMesh.SurfaceElement(i);
1480 for ( int j = 0; j < elem.GetNP(); ++j)
1482 double d = dist2( mpV, ngMesh.Point( elem[j] ));
1483 dist2nID.insert( make_pair( d, elem[j] ));
1484 avgDist2 += d / elem.GetNP();
1485 if ( avgDist2 < closeDist2 )
1486 vData.ngIdClose= i, vData.ngIdCloseN= dist2nID.begin()->second, closeDist2= avgDist2;
1489 // sort nodes of the closest face by angle with vector from V to the closest node
1490 const double tol = numeric_limits<double>::min();
1491 map< double, int > angle2ID;
1492 const netgen::Element2d& closeFace = ngMesh.SurfaceElement( vData.ngIdClose );
1493 netgen::MeshPoint mp[2];
1494 mp[0] = ngMesh.Point( vData.ngIdCloseN );
1495 gp_XYZ p1( NGPOINT_COORDS( mp[0] ));
1496 gp_XYZ pV( NGPOINT_COORDS( mpV ));
1497 gp_Vec v2p1( pV, p1 );
1498 double distN1 = v2p1.Magnitude();
1499 if ( distN1 <= tol ) continue;
1501 for ( int j = 0; j < closeFace.GetNP(); ++j)
1503 mp[1] = ngMesh.Point( closeFace[j] );
1504 gp_Vec v2p( pV, gp_Pnt( NGPOINT_COORDS( mp[1] )) );
1505 angle2ID.insert( make_pair( v2p1.Angle( v2p ), closeFace[j]));
1507 // get node with angle of 60 degrees or greater
1508 map< double, int >::iterator angle_id = angle2ID.lower_bound( 60. * M_PI / 180. );
1509 if ( angle_id == angle2ID.end() ) angle_id = --angle2ID.end();
1510 const double minAngle = 30. * M_PI / 180.;
1511 const double angle = angle_id->first;
1512 bool angleOK = ( angle > minAngle );
1514 // find points to create a triangle
1515 netgen::Element2d tri(3);
1517 tri[0] = vData.ngId;
1518 tri[1] = vData.ngIdCloseN; // to use the closest nodes
1519 tri[2] = angle_id->second; // to use the node with best angle
1521 // decide whether to use the closest node and the node with best angle or to create new ones
1522 for ( int isBestAngleN = 0; isBestAngleN < 2; ++isBestAngleN )
1524 bool createNew = !angleOK, distOK = true;
1526 int triInd = isBestAngleN ? 2 : 1;
1527 mp[isBestAngleN] = ngMesh.Point( tri[triInd] );
1532 double distN2 = sqrt( dist2( mpV, mp[isBestAngleN]));
1533 createNew = ( fabs( distN2 - distN1 ) > 0.25 * distN1 );
1535 else if ( angle < tol )
1537 v2p1.SetX( v2p1.X() + 1e-3 );
1543 double segLenHint = ngMesh.GetH( ngMesh.Point( vData.ngId ));
1544 bool avgLenOK = ( avgSegLen < 0.75 * distN1 );
1545 bool hintLenOK = ( segLenHint < 0.75 * distN1 );
1546 createNew = (createNew || avgLenOK || hintLenOK );
1547 // we create a new node not closer than 0.5 to the closest face
1548 // in order not to clash with other close face
1549 double r = min( 0.5, ( hintLenOK ? segLenHint : avgSegLen ) / distN1 );
1550 distFromV = r * distN1;
1554 // create a new point, between the node and the vertex if angleOK
1555 gp_XYZ p( NGPOINT_COORDS( mp[isBestAngleN] ));
1556 gp_Vec v2p( pV, p ); v2p.Normalize();
1557 if ( isBestAngleN && !angleOK )
1558 p = p1 + gp_Dir( v2p.XYZ() - v2p1.XYZ()).XYZ() * distN1 * 0.95;
1560 p = pV + v2p.XYZ() * distFromV;
1562 if ( !isBestAngleN ) p1 = p, distN1 = distFromV;
1564 mp[isBestAngleN].SetPoint( netgen::Point<3> (p.X(), p.Y(), p.Z()));
1565 ngMesh.AddPoint ( mp[isBestAngleN], 1, netgen::SURFACEPOINT );
1566 tri[triInd] = ngMesh.GetNP();
1567 nodeVec.push_back( helper.AddNode( p.X(), p.Y(), p.Z()) );
1570 ngMesh.AddSurfaceElement (tri);
1571 swap( tri[1], tri[2] );
1572 ngMesh.AddSurfaceElement (tri);
1574 #ifdef DUMP_TRIANGLES_SCRIPT
1575 py << "n1 = m.AddNode( "<< mpV.X()<<", "<< mpV.Y()<<", "<< mpV.Z()<<") "<< endl
1576 << "n2 = m.AddNode( "<< mp[0].X()<<", "<< mp[0].Y()<<", "<< mp[0].Z()<<") "<< endl
1577 << "n3 = m.AddNode( "<< mp[1].X()<<", "<< mp[1].Y()<<", "<< mp[1].Z()<<" )" << endl
1578 << "m.AddFace([n1,n2,n3])" << endl;
1580 } // loop on internal vertices of a solid
1582 } // loop on solids with internal vertices
1585 //================================================================================
1587 * \brief Fill netgen mesh with segments of a FACE
1588 * \param ngMesh - netgen mesh
1589 * \param geom - container of OCCT geometry to mesh
1590 * \param wires - data of nodes on FACE boundary
1591 * \param helper - mesher helper holding the FACE
1592 * \param nodeVec - vector of nodes in which node index == netgen ID
1593 * \retval SMESH_ComputeErrorPtr - error description
1595 //================================================================================
1597 SMESH_ComputeErrorPtr
1598 NETGENPlugin_Mesher::AddSegmentsToMesh(netgen::Mesh& ngMesh,
1599 netgen::OCCGeometry& geom,
1600 const TSideVector& wires,
1601 SMESH_MesherHelper& helper,
1602 vector< const SMDS_MeshNode* > & nodeVec,
1603 const bool overrideMinH)
1605 // ----------------------------
1606 // Check wires and count nodes
1607 // ----------------------------
1609 for ( int iW = 0; iW < wires.size(); ++iW )
1611 StdMeshers_FaceSidePtr wire = wires[ iW ];
1612 if ( wire->MissVertexNode() )
1614 // Commented for issue 0020960. It worked for the case, let's wait for case where it doesn't.
1615 // It seems that there is no reason for this limitation
1617 // (new SMESH_ComputeError(COMPERR_BAD_INPUT_MESH, "Missing nodes on vertices"));
1619 const vector<UVPtStruct>& uvPtVec = wire->GetUVPtStruct();
1620 if ( uvPtVec.size() != wire->NbPoints() )
1621 return SMESH_ComputeError::New(COMPERR_BAD_INPUT_MESH,
1622 SMESH_Comment("Unexpected nb of points on wire ") << iW
1623 << ": " << uvPtVec.size()<<" != "<<wire->NbPoints());
1624 nbNodes += wire->NbPoints();
1626 nodeVec.reserve( nodeVec.size() + nbNodes + 1 );
1627 if ( nodeVec.empty() )
1628 nodeVec.push_back( 0 );
1630 // -----------------
1632 // -----------------
1634 const bool wasNgMeshEmpty = ( ngMesh.GetNP() < 1 ); /* true => this method is called by
1635 NETGENPlugin_NETGEN_2D_ONLY */
1637 // map for nodes on vertices since they can be shared between wires
1638 // ( issue 0020676, face_int_box.brep) and nodes built by NETGEN
1639 map<const SMDS_MeshNode*, int > node2ngID;
1640 if ( !wasNgMeshEmpty ) // fill node2ngID with nodes built by NETGEN
1642 set< int > subIDs; // ids of sub-shapes of the FACE
1643 for ( int iW = 0; iW < wires.size(); ++iW )
1645 StdMeshers_FaceSidePtr wire = wires[ iW ];
1646 for ( int iE = 0, nbE = wire->NbEdges(); iE < nbE; ++iE )
1648 subIDs.insert( wire->EdgeID( iE ));
1649 subIDs.insert( helper.GetMeshDS()->ShapeToIndex( wire->FirstVertex( iE )));
1652 for ( size_t ngID = 1; ngID < nodeVec.size(); ++ngID )
1653 if ( subIDs.count( nodeVec[ngID]->getshapeId() ))
1654 node2ngID.insert( make_pair( nodeVec[ngID], ngID ));
1657 const int solidID = 0, faceID = geom.fmap.FindIndex( helper.GetSubShape() );
1658 if ( ngMesh.GetNFD() < 1 )
1659 ngMesh.AddFaceDescriptor (netgen::FaceDescriptor(faceID, solidID, solidID, 0));
1661 for ( int iW = 0; iW < wires.size(); ++iW )
1663 StdMeshers_FaceSidePtr wire = wires[ iW ];
1664 const vector<UVPtStruct>& uvPtVec = wire->GetUVPtStruct();
1665 const int nbSegments = wire->NbPoints() - 1;
1667 // assure the 1st node to be in node2ngID, which is needed to correctly
1668 // "close chain of segments" (see below) in case if the 1st node is not
1669 // onVertex because it is on a Viscous layer
1670 node2ngID.insert( make_pair( uvPtVec[ 0 ].node, ngMesh.GetNP() + 1 ));
1672 // compute length of every segment
1673 vector<double> segLen( nbSegments );
1674 for ( int i = 0; i < nbSegments; ++i )
1675 segLen[i] = SMESH_TNodeXYZ( uvPtVec[ i ].node ).Distance( uvPtVec[ i+1 ].node );
1677 int edgeID = 1, posID = -2;
1678 bool isInternalWire = false;
1679 double vertexNormPar = 0;
1680 const int prevNbNGSeg = ngMesh.GetNSeg();
1681 for ( int i = 0; i < nbSegments; ++i ) // loop on segments
1683 // Add the first point of a segment
1685 const SMDS_MeshNode * n = uvPtVec[ i ].node;
1686 const int posShapeID = n->getshapeId();
1687 bool onVertex = ( n->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX );
1688 bool onEdge = ( n->GetPosition()->GetTypeOfPosition() == SMDS_TOP_EDGE );
1690 // skip nodes on degenerated edges
1691 if ( helper.IsDegenShape( posShapeID ) &&
1692 helper.IsDegenShape( uvPtVec[ i+1 ].node->getshapeId() ))
1695 int ngID1 = ngMesh.GetNP() + 1, ngID2 = ngID1+1;
1696 if ( onVertex || ( !wasNgMeshEmpty && onEdge ))
1697 ngID1 = node2ngID.insert( make_pair( n, ngID1 )).first->second;
1698 if ( ngID1 > ngMesh.GetNP() )
1700 netgen::MeshPoint mp( netgen::Point<3> (n->X(), n->Y(), n->Z()) );
1701 ngMesh.AddPoint ( mp, 1, netgen::EDGEPOINT );
1702 nodeVec.push_back( n );
1704 else // n is in ngMesh already, and ngID2 in prev segment is wrong
1706 ngID2 = ngMesh.GetNP() + 1;
1707 if ( i > 0 ) // prev segment belongs to same wire
1709 netgen::Segment& prevSeg = ngMesh.LineSegment( ngMesh.GetNSeg() );
1716 netgen::Segment seg;
1718 seg[0] = ngID1; // ng node id
1719 seg[1] = ngID2; // ng node id
1720 seg.edgenr = ngMesh.GetNSeg() + 1; // ng segment id
1721 seg.si = faceID; // = geom.fmap.FindIndex (face);
1723 for ( int iEnd = 0; iEnd < 2; ++iEnd)
1725 const UVPtStruct& pnt = uvPtVec[ i + iEnd ];
1727 seg.epgeominfo[ iEnd ].dist = pnt.param; // param on curve
1728 seg.epgeominfo[ iEnd ].u = pnt.u;
1729 seg.epgeominfo[ iEnd ].v = pnt.v;
1731 // find out edge id and node parameter on edge
1732 onVertex = ( pnt.normParam + 1e-10 > vertexNormPar );
1733 if ( onVertex || posShapeID != posID )
1736 double normParam = pnt.normParam;
1738 normParam = 0.5 * ( uvPtVec[ i ].normParam + uvPtVec[ i+1 ].normParam );
1739 int edgeIndexInWire = wire->EdgeIndex( normParam );
1740 vertexNormPar = wire->LastParameter( edgeIndexInWire );
1741 const TopoDS_Edge& edge = wire->Edge( edgeIndexInWire );
1742 edgeID = geom.emap.FindIndex( edge );
1744 isInternalWire = ( edge.Orientation() == TopAbs_INTERNAL );
1745 // if ( onVertex ) // param on curve is different on each of two edges
1746 // seg.epgeominfo[ iEnd ].dist = helper.GetNodeU( edge, pnt.node );
1748 seg.epgeominfo[ iEnd ].edgenr = edgeID; // = geom.emap.FindIndex(edge);
1751 ngMesh.AddSegment (seg);
1753 // restrict size of elements near the segment
1754 SMESH_TNodeXYZ np1( n ), np2( uvPtVec[ i+1 ].node );
1755 // get an average size of adjacent segments to avoid sharp change of
1756 // element size (regression on issue 0020452, note 0010898)
1757 int iPrev = SMESH_MesherHelper::WrapIndex( i-1, nbSegments );
1758 int iNext = SMESH_MesherHelper::WrapIndex( i+1, nbSegments );
1759 double sumH = segLen[ iPrev ] + segLen[ i ] + segLen[ iNext ];
1760 int nbSeg = ( int( segLen[ iPrev ] > sumH / 100.) +
1761 int( segLen[ i ] > sumH / 100.) +
1762 int( segLen[ iNext ] > sumH / 100.));
1764 RestrictLocalSize( ngMesh, 0.5*(np1+np2), sumH / nbSeg, overrideMinH );
1766 if ( isInternalWire )
1768 swap (seg[0], seg[1]);
1769 swap( seg.epgeominfo[0], seg.epgeominfo[1] );
1770 seg.edgenr = ngMesh.GetNSeg() + 1; // segment id
1771 ngMesh.AddSegment (seg);
1773 } // loop on segments on a wire
1775 // close chain of segments
1776 if ( nbSegments > 0 )
1778 netgen::Segment& lastSeg = ngMesh.LineSegment( ngMesh.GetNSeg() - int( isInternalWire));
1779 const SMDS_MeshNode * lastNode = uvPtVec.back().node;
1780 lastSeg[1] = node2ngID.insert( make_pair( lastNode, lastSeg[1] )).first->second;
1781 if ( lastSeg[1] > ngMesh.GetNP() )
1783 netgen::MeshPoint mp( netgen::Point<3> (lastNode->X(), lastNode->Y(), lastNode->Z()) );
1784 ngMesh.AddPoint ( mp, 1, netgen::EDGEPOINT );
1785 nodeVec.push_back( lastNode );
1787 if ( isInternalWire )
1789 netgen::Segment& realLastSeg = ngMesh.LineSegment( ngMesh.GetNSeg() );
1790 realLastSeg[0] = lastSeg[1];
1794 #ifdef DUMP_SEGMENTS
1795 cout << "BEGIN WIRE " << iW << endl;
1796 for ( int i = prevNbNGSeg+1; i <= ngMesh.GetNSeg(); ++i )
1798 netgen::Segment& seg = ngMesh.LineSegment( i );
1800 netgen::Segment& prevSeg = ngMesh.LineSegment( i-1 );
1801 if ( seg[0] == prevSeg[1] && seg[1] == prevSeg[0] )
1803 cout << "Segment: " << seg.edgenr << endl << "\tis REVRESE of the previous one" << endl;
1807 cout << "Segment: " << seg.edgenr << endl
1808 << "\tp1: " << seg[0] << endl
1809 << "\tp2: " << seg[1] << endl
1810 << "\tp0 param: " << seg.epgeominfo[ 0 ].dist << endl
1811 << "\tp0 uv: " << seg.epgeominfo[ 0 ].u <<", "<< seg.epgeominfo[ 0 ].v << endl
1812 << "\tp0 edge: " << seg.epgeominfo[ 0 ].edgenr << endl
1813 << "\tp1 param: " << seg.epgeominfo[ 1 ].dist << endl
1814 << "\tp1 uv: " << seg.epgeominfo[ 1 ].u <<", "<< seg.epgeominfo[ 1 ].v << endl
1815 << "\tp1 edge: " << seg.epgeominfo[ 1 ].edgenr << endl;
1817 cout << "--END WIRE " << iW << endl;
1820 } // loop on WIREs of a FACE
1822 // add a segment instead of an internal vertex
1823 if ( wasNgMeshEmpty )
1825 NETGENPlugin_Internals intShapes( *helper.GetMesh(), helper.GetSubShape(), /*is3D=*/false );
1826 AddIntVerticesInFaces( geom, ngMesh, nodeVec, intShapes );
1828 ngMesh.CalcSurfacesOfNode();
1833 //================================================================================
1835 * \brief Fill SMESH mesh according to contents of netgen mesh
1836 * \param occgeo - container of OCCT geometry to mesh
1837 * \param ngMesh - netgen mesh
1838 * \param initState - bn of entities in netgen mesh before computing
1839 * \param sMesh - SMESH mesh to fill in
1840 * \param nodeVec - vector of nodes in which node index == netgen ID
1841 * \param comment - returns problem description
1842 * \param quadHelper - holder of medium nodes of sub-meshes
1843 * \retval int - error
1845 //================================================================================
1847 int NETGENPlugin_Mesher::FillSMesh(const netgen::OCCGeometry& occgeo,
1848 netgen::Mesh& ngMesh,
1849 const NETGENPlugin_ngMeshInfo& initState,
1851 std::vector<const SMDS_MeshNode*>& nodeVec,
1852 SMESH_Comment& comment,
1853 SMESH_MesherHelper* quadHelper)
1855 int nbNod = ngMesh.GetNP();
1856 int nbSeg = ngMesh.GetNSeg();
1857 int nbFac = ngMesh.GetNSE();
1858 int nbVol = ngMesh.GetNE();
1860 SMESHDS_Mesh* meshDS = sMesh.GetMeshDS();
1862 // quadHelper is used for either
1863 // 1) making quadratic elements when a lower dimention mesh is loaded
1864 // to SMESH before convertion to quadratic by NETGEN
1865 // 2) sewing of quadratic elements with quadratic elements of sub-meshes
1866 if ( quadHelper && !quadHelper->GetIsQuadratic() && quadHelper->GetTLinkNodeMap().empty() )
1869 // -------------------------------------
1870 // Create and insert nodes into nodeVec
1871 // -------------------------------------
1873 nodeVec.resize( nbNod + 1 );
1874 int i, nbInitNod = initState._nbNodes;
1875 for (i = nbInitNod+1; i <= nbNod; ++i )
1877 const netgen::MeshPoint& ngPoint = ngMesh.Point(i);
1878 SMDS_MeshNode* node = NULL;
1879 TopoDS_Vertex aVert;
1880 // First, netgen creates nodes on vertices in occgeo.vmap,
1881 // so node index corresponds to vertex index
1882 // but (issue 0020776) netgen does not create nodes with equal coordinates
1883 if ( i-nbInitNod <= occgeo.vmap.Extent() )
1885 gp_Pnt p ( NGPOINT_COORDS(ngPoint) );
1886 for (int iV = i-nbInitNod; aVert.IsNull() && iV <= occgeo.vmap.Extent(); ++iV)
1888 aVert = TopoDS::Vertex( occgeo.vmap( iV ) );
1889 gp_Pnt pV = BRep_Tool::Pnt( aVert );
1890 if ( p.SquareDistance( pV ) > 1e-20 )
1893 node = const_cast<SMDS_MeshNode*>( SMESH_Algo::VertexNode( aVert, meshDS ));
1896 if (!node) // node not found on vertex
1898 node = meshDS->AddNode( NGPOINT_COORDS( ngPoint ));
1899 if (!aVert.IsNull())
1900 meshDS->SetNodeOnVertex(node, aVert);
1905 // -------------------------------------------
1906 // Create mesh segments along geometric edges
1907 // -------------------------------------------
1909 int nbInitSeg = initState._nbSegments;
1910 for (i = nbInitSeg+1; i <= nbSeg; ++i )
1912 const netgen::Segment& seg = ngMesh.LineSegment(i);
1914 int pinds[3] = { seg.pnums[0], seg.pnums[1], seg.pnums[2] };
1917 for (int j=0; j < 3; ++j)
1919 int pind = pinds[j];
1920 if (pind <= 0 || !nodeVec_ACCESS(pind))
1928 int aGeomEdgeInd = seg.epgeominfo[j].edgenr;
1929 if (aGeomEdgeInd > 0 && aGeomEdgeInd <= occgeo.emap.Extent())
1930 aEdge = TopoDS::Edge(occgeo.emap(aGeomEdgeInd));
1932 param = seg.epgeominfo[j].dist;
1935 else // middle point
1937 param = param2 * 0.5;
1939 if (!aEdge.IsNull() && nodeVec_ACCESS(pind)->getshapeId() < 1)
1941 meshDS->SetNodeOnEdge(nodeVec_ACCESS(pind), aEdge, param);
1946 SMDS_MeshEdge* edge = 0;
1947 if (nbp == 2) // second order ?
1949 if ( meshDS->FindEdge( nodeVec_ACCESS(pinds[0]), nodeVec_ACCESS(pinds[1])))
1951 if ( quadHelper ) // final mesh must be quadratic
1952 edge = quadHelper->AddEdge(nodeVec_ACCESS(pinds[0]), nodeVec_ACCESS(pinds[1]));
1954 edge = meshDS->AddEdge(nodeVec_ACCESS(pinds[0]), nodeVec_ACCESS(pinds[1]));
1958 if ( meshDS->FindEdge( nodeVec_ACCESS(pinds[0]), nodeVec_ACCESS(pinds[1]),
1959 nodeVec_ACCESS(pinds[2])))
1961 edge = meshDS->AddEdge(nodeVec_ACCESS(pinds[0]), nodeVec_ACCESS(pinds[1]),
1962 nodeVec_ACCESS(pinds[2]));
1966 if ( comment.empty() ) comment << "Cannot create a mesh edge";
1967 MESSAGE("Cannot create a mesh edge");
1968 nbSeg = nbFac = nbVol = 0;
1971 if ( !aEdge.IsNull() && edge->getshapeId() < 1 )
1972 meshDS->SetMeshElementOnShape(edge, aEdge);
1974 else if ( comment.empty() )
1976 comment << "Invalid netgen segment #" << i;
1980 // ----------------------------------------
1981 // Create mesh faces along geometric faces
1982 // ----------------------------------------
1984 int nbInitFac = initState._nbFaces;
1985 int quadFaceID = ngMesh.GetNFD() + 1;
1986 if ( nbInitFac < nbFac )
1987 // add a faces descriptor to exclude qudrangle elements generated by NETGEN
1988 // from computation of 3D mesh
1989 ngMesh.AddFaceDescriptor (netgen::FaceDescriptor(quadFaceID, /*solid1=*/0, /*solid2=*/0, 0));
1991 vector<const SMDS_MeshNode*> nodes;
1992 for (i = nbInitFac+1; i <= nbFac; ++i )
1994 const netgen::Element2d& elem = ngMesh.SurfaceElement(i);
1995 int aGeomFaceInd = elem.GetIndex();
1997 if (aGeomFaceInd > 0 && aGeomFaceInd <= occgeo.fmap.Extent())
1998 aFace = TopoDS::Face(occgeo.fmap(aGeomFaceInd));
2000 for (int j=1; j <= elem.GetNP(); ++j)
2002 int pind = elem.PNum(j);
2003 if ( pind < 1 || pind >= nodeVec.size() )
2005 if ( SMDS_MeshNode* node = nodeVec_ACCESS(pind))
2007 nodes.push_back( node );
2008 if (!aFace.IsNull() && node->getshapeId() < 1)
2010 const netgen::PointGeomInfo& pgi = elem.GeomInfoPi(j);
2011 meshDS->SetNodeOnFace(node, aFace, pgi.u, pgi.v);
2015 if ( nodes.size() != elem.GetNP() )
2017 if ( comment.empty() )
2018 comment << "Invalid netgen 2d element #" << i;
2019 continue; // bad node ids
2021 SMDS_MeshFace* face = NULL;
2022 switch (elem.GetType())
2025 if ( quadHelper ) // final mesh must be quadratic
2026 face = quadHelper->AddFace(nodes[0],nodes[1],nodes[2]);
2028 face = meshDS->AddFace(nodes[0],nodes[1],nodes[2]);
2031 if ( quadHelper ) // final mesh must be quadratic
2032 face = quadHelper->AddFace(nodes[0],nodes[1],nodes[2],nodes[3]);
2034 face = meshDS->AddFace(nodes[0],nodes[1],nodes[2],nodes[3]);
2035 // exclude qudrangle elements from computation of 3D mesh
2036 const_cast< netgen::Element2d& >( elem ).SetIndex( quadFaceID );
2039 nodes[5] = mediumNode( nodes[0],nodes[1],nodes[5], quadHelper );
2040 nodes[3] = mediumNode( nodes[1],nodes[2],nodes[3], quadHelper );
2041 nodes[4] = mediumNode( nodes[2],nodes[0],nodes[4], quadHelper );
2042 face = meshDS->AddFace(nodes[0],nodes[1],nodes[2],nodes[5],nodes[3],nodes[4]);
2045 nodes[4] = mediumNode( nodes[0],nodes[1],nodes[4], quadHelper );
2046 nodes[7] = mediumNode( nodes[1],nodes[2],nodes[7], quadHelper );
2047 nodes[5] = mediumNode( nodes[2],nodes[3],nodes[5], quadHelper );
2048 nodes[6] = mediumNode( nodes[3],nodes[0],nodes[6], quadHelper );
2049 face = meshDS->AddFace(nodes[0],nodes[1],nodes[2],nodes[3],
2050 nodes[4],nodes[7],nodes[5],nodes[6]);
2051 // exclude qudrangle elements from computation of 3D mesh
2052 const_cast< netgen::Element2d& >( elem ).SetIndex( quadFaceID );
2055 MESSAGE("NETGEN created a face of unexpected type, ignoring");
2060 if ( comment.empty() ) comment << "Cannot create a mesh face";
2061 MESSAGE("Cannot create a mesh face");
2062 nbSeg = nbFac = nbVol = 0;
2065 if (!aFace.IsNull())
2066 meshDS->SetMeshElementOnShape(face, aFace);
2069 // ------------------
2070 // Create tetrahedra
2071 // ------------------
2073 for (i = 1; i <= nbVol; ++i)
2075 const netgen::Element& elem = ngMesh.VolumeElement(i);
2076 int aSolidInd = elem.GetIndex();
2077 TopoDS_Solid aSolid;
2078 if (aSolidInd > 0 && aSolidInd <= occgeo.somap.Extent())
2079 aSolid = TopoDS::Solid(occgeo.somap(aSolidInd));
2081 for (int j=1; j <= elem.GetNP(); ++j)
2083 int pind = elem.PNum(j);
2084 if ( pind < 1 || pind >= nodeVec.size() )
2086 if ( SMDS_MeshNode* node = nodeVec_ACCESS(pind) )
2088 nodes.push_back(node);
2089 if ( !aSolid.IsNull() && node->getshapeId() < 1 )
2090 meshDS->SetNodeInVolume(node, aSolid);
2093 if ( nodes.size() != elem.GetNP() )
2095 if ( comment.empty() )
2096 comment << "Invalid netgen 3d element #" << i;
2099 SMDS_MeshVolume* vol = NULL;
2100 switch (elem.GetType())
2103 vol = meshDS->AddVolume(nodes[0],nodes[1],nodes[2],nodes[3]);
2106 nodes[4] = mediumNode( nodes[0],nodes[1],nodes[4], quadHelper );
2107 nodes[7] = mediumNode( nodes[1],nodes[2],nodes[7], quadHelper );
2108 nodes[5] = mediumNode( nodes[2],nodes[0],nodes[5], quadHelper );
2109 nodes[6] = mediumNode( nodes[0],nodes[3],nodes[6], quadHelper );
2110 nodes[8] = mediumNode( nodes[1],nodes[3],nodes[8], quadHelper );
2111 nodes[9] = mediumNode( nodes[2],nodes[3],nodes[9], quadHelper );
2112 vol = meshDS->AddVolume(nodes[0],nodes[1],nodes[2],nodes[3],
2113 nodes[4],nodes[7],nodes[5],nodes[6],nodes[8],nodes[9]);
2116 MESSAGE("NETGEN created a volume of unexpected type, ignoring");
2121 if ( comment.empty() ) comment << "Cannot create a mesh volume";
2122 MESSAGE("Cannot create a mesh volume");
2123 nbSeg = nbFac = nbVol = 0;
2126 if (!aSolid.IsNull())
2127 meshDS->SetMeshElementOnShape(vol, aSolid);
2129 return comment.empty() ? 0 : 1;
2134 //================================================================================
2136 * \brief Restrict size of elements on the given edge
2138 //================================================================================
2140 void setLocalSize(const TopoDS_Edge& edge,
2144 const int nb = 1000;
2145 Standard_Real u1, u2;
2146 Handle(Geom_Curve) curve = BRep_Tool::Curve(edge, u1, u2);
2147 if ( curve.IsNull() )
2149 TopoDS_Iterator vIt( edge );
2150 if ( !vIt.More() ) return;
2151 gp_Pnt p = BRep_Tool::Pnt( TopoDS::Vertex( vIt.Value() ));
2152 NETGENPlugin_Mesher::RestrictLocalSize( mesh, p.XYZ(), size );
2156 Standard_Real delta = (u2-u1)/nb;
2157 for(int i=0; i<nb; i++)
2159 Standard_Real u = u1 + delta*i;
2160 gp_Pnt p = curve->Value(u);
2161 NETGENPlugin_Mesher::RestrictLocalSize( mesh, p.XYZ(), size );
2162 netgen::Point3d pi(p.X(), p.Y(), p.Z());
2163 double resultSize = mesh.GetH(pi);
2164 if ( resultSize - size > 0.1*size )
2165 // netgen does restriction iff oldH/newH > 1.2 (localh.cpp:136)
2166 NETGENPlugin_Mesher::RestrictLocalSize( mesh, p.XYZ(), resultSize/1.201 );
2171 //================================================================================
2173 * \brief Convert error into text
2175 //================================================================================
2177 std::string text(int err)
2182 SMESH_Comment("Error in netgen::OCCGenerateMesh() at ") << netgen::multithread.task;
2185 //================================================================================
2187 * \brief Convert exception into text
2189 //================================================================================
2191 std::string text(Standard_Failure& ex)
2193 SMESH_Comment str("Exception in netgen::OCCGenerateMesh()");
2194 str << " at " << netgen::multithread.task
2195 << ": " << ex.DynamicType()->Name();
2196 if ( ex.GetMessageString() && strlen( ex.GetMessageString() ))
2197 str << ": " << ex.GetMessageString();
2200 //================================================================================
2202 * \brief Convert exception into text
2204 //================================================================================
2206 std::string text(netgen::NgException& ex)
2208 SMESH_Comment str("NgException");
2209 if ( strlen( netgen::multithread.task ) > 0 )
2210 str << " at " << netgen::multithread.task;
2211 str << ": " << ex.What();
2215 //================================================================================
2217 * \brief Looks for triangles lying on a SOLID
2219 //================================================================================
2221 bool hasBadElemOnSolid( const list<const SMDS_MeshElement*>& elems,
2222 SMESH_subMesh* solidSM )
2224 TopTools_IndexedMapOfShape solidSubs;
2225 TopExp::MapShapes( solidSM->GetSubShape(), solidSubs );
2226 SMESHDS_Mesh* mesh = solidSM->GetFather()->GetMeshDS();
2228 list<const SMDS_MeshElement*>::const_iterator e = elems.begin();
2229 for ( ; e != elems.end(); ++e )
2231 const SMDS_MeshElement* elem = *e;
2232 if ( elem->GetType() != SMDSAbs_Face )
2234 int nbNodesOnSolid = 0;
2235 SMDS_NodeIteratorPtr nIt = elem->nodeIterator();
2236 while ( nIt->more() )
2238 const SMDS_MeshNode* n = nIt->next();
2239 const TopoDS_Shape& s = mesh->IndexToShape( n->getshapeId() );
2240 nbNodesOnSolid += ( !s.IsNull() && solidSubs.Contains( s ));
2241 if ( nbNodesOnSolid > 2 )
2248 const double edgeMeshingTime = 0.001;
2249 const double faceMeshingTime = 0.019;
2250 const double edgeFaceMeshingTime = edgeMeshingTime + faceMeshingTime;
2251 const double faceOptimizTime = 0.06;
2252 const double voluMeshingTime = 0.15;
2253 const double volOptimizeTime = 0.77;
2256 //=============================================================================
2258 * Here we are going to use the NETGEN mesher
2260 //=============================================================================
2262 bool NETGENPlugin_Mesher::Compute()
2264 NETGENPlugin_NetgenLibWrapper ngLib;
2266 netgen::MeshingParameters& mparams = netgen::mparam;
2267 MESSAGE("Compute with:\n"
2268 " max size = " << mparams.maxh << "\n"
2269 " segments per edge = " << mparams.segmentsperedge);
2271 " growth rate = " << mparams.grading << "\n"
2272 " elements per radius = " << mparams.curvaturesafety << "\n"
2273 " second order = " << mparams.secondorder << "\n"
2274 " quad allowed = " << mparams.quad << "\n"
2275 " surface curvature = " << mparams.uselocalh << "\n"
2276 " fuse edges = " << netgen::merge_solids);
2278 SMESH_ComputeErrorPtr error = SMESH_ComputeError::New();
2279 SMESH_MesherHelper quadHelper( *_mesh );
2280 quadHelper.SetIsQuadratic( mparams.secondorder );
2282 static string debugFile = "/tmp/ngMesh.py"; /* to call toPython( ngMesh, debugFile )
2283 while debugging netgen */
2284 // -------------------------
2285 // Prepare OCC geometry
2286 // -------------------------
2288 netgen::OCCGeometry occgeo;
2289 list< SMESH_subMesh* > meshedSM[3]; // for 0-2 dimensions
2290 NETGENPlugin_Internals internals( *_mesh, _shape, _isVolume );
2291 PrepareOCCgeometry( occgeo, _shape, *_mesh, meshedSM, &internals );
2294 _totalTime = edgeFaceMeshingTime;
2296 _totalTime += faceOptimizTime;
2298 _totalTime += voluMeshingTime + ( _optimize ? volOptimizeTime : 0 );
2299 double doneTime = 0;
2302 _curShapeIndex = -1;
2304 // -------------------------
2305 // Generate the mesh
2306 // -------------------------
2309 NETGENPlugin_ngMeshInfo initState; // it remembers size of ng mesh equal to size of Smesh
2311 SMESH_Comment comment;
2314 // vector of nodes in which node index == netgen ID
2315 vector< const SMDS_MeshNode* > nodeVec;
2323 // not to RestrictLocalH() according to curvature during MESHCONST_ANALYSE
2324 mparams.uselocalh = false;
2325 mparams.grading = 0.8; // not limitited size growth
2327 if ( _simpleHyp->GetNumberOfSegments() )
2329 mparams.maxh = occgeo.boundingbox.Diam();
2332 mparams.maxh = _simpleHyp->GetLocalLength();
2335 if ( mparams.maxh == 0.0 )
2336 mparams.maxh = occgeo.boundingbox.Diam();
2337 if ( _simpleHyp || ( mparams.minh == 0.0 && _fineness != NETGENPlugin_Hypothesis::UserDefined))
2338 mparams.minh = GetDefaultMinSize( _shape, mparams.maxh );
2340 // Local size on faces
2341 occgeo.face_maxh = mparams.maxh;
2343 // Let netgen create _ngMesh and calculate element size on not meshed shapes
2347 int startWith = netgen::MESHCONST_ANALYSE;
2348 int endWith = netgen::MESHCONST_ANALYSE;
2353 err = netgen::OCCGenerateMesh(occgeo, _ngMesh, mparams, startWith, endWith);
2355 err = netgen::OCCGenerateMesh(occgeo, _ngMesh, startWith, endWith, optstr);
2357 if(netgen::multithread.terminate)
2360 comment << text(err);
2362 catch (Standard_Failure& ex)
2364 comment << text(ex);
2366 err = 0; //- MESHCONST_ANALYSE isn't so important step
2369 ngLib.setMesh(( Ng_Mesh*) _ngMesh );
2371 _ngMesh->ClearFaceDescriptors(); // we make descriptors our-self
2375 // Pass 1D simple parameters to NETGEN
2376 // --------------------------------
2377 int nbSeg = _simpleHyp->GetNumberOfSegments();
2378 double segSize = _simpleHyp->GetLocalLength();
2379 for ( int iE = 1; iE <= occgeo.emap.Extent(); ++iE )
2381 const TopoDS_Edge& e = TopoDS::Edge( occgeo.emap(iE));
2383 segSize = SMESH_Algo::EdgeLength( e ) / ( nbSeg - 0.4 );
2384 setLocalSize( e, segSize, *_ngMesh );
2387 else // if ( ! _simpleHyp )
2389 // Local size on vertices and edges
2390 // --------------------------------
2391 for(std::map<int,double>::const_iterator it=EdgeId2LocalSize.begin(); it!=EdgeId2LocalSize.end(); it++)
2393 int key = (*it).first;
2394 double hi = (*it).second;
2395 const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
2396 const TopoDS_Edge& e = TopoDS::Edge(shape);
2397 setLocalSize( e, hi, *_ngMesh );
2399 for(std::map<int,double>::const_iterator it=VertexId2LocalSize.begin(); it!=VertexId2LocalSize.end(); it++)
2401 int key = (*it).first;
2402 double hi = (*it).second;
2403 const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
2404 const TopoDS_Vertex& v = TopoDS::Vertex(shape);
2405 gp_Pnt p = BRep_Tool::Pnt(v);
2406 NETGENPlugin_Mesher::RestrictLocalSize( *_ngMesh, p.XYZ(), hi );
2408 for(map<int,double>::const_iterator it=FaceId2LocalSize.begin();
2409 it!=FaceId2LocalSize.end(); it++)
2411 int key = (*it).first;
2412 double val = (*it).second;
2413 const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
2414 int faceNgID = occgeo.fmap.FindIndex(shape);
2415 occgeo.SetFaceMaxH(faceNgID, val);
2416 for ( TopExp_Explorer edgeExp( shape, TopAbs_EDGE ); edgeExp.More(); edgeExp.Next() )
2417 setLocalSize( TopoDS::Edge( edgeExp.Current() ), val, *_ngMesh );
2421 // Precompute internal edges (issue 0020676) in order to
2422 // add mesh on them correctly (twice) to netgen mesh
2423 if ( !err && internals.hasInternalEdges() )
2425 // load internal shapes into OCCGeometry
2426 netgen::OCCGeometry intOccgeo;
2427 internals.getInternalEdges( intOccgeo.fmap, intOccgeo.emap, intOccgeo.vmap, meshedSM );
2428 intOccgeo.boundingbox = occgeo.boundingbox;
2429 intOccgeo.shape = occgeo.shape;
2430 intOccgeo.face_maxh.SetSize(intOccgeo.fmap.Extent());
2431 intOccgeo.face_maxh = netgen::mparam.maxh;
2432 netgen::Mesh *tmpNgMesh = NULL;
2436 // compute local H on internal shapes in the main mesh
2437 //OCCSetLocalMeshSize(intOccgeo, *_ngMesh); it deletes _ngMesh->localH
2439 // let netgen create a temporary mesh
2441 netgen::OCCGenerateMesh(intOccgeo, tmpNgMesh, mparams, startWith, endWith);
2443 netgen::OCCGenerateMesh(intOccgeo, tmpNgMesh, startWith, endWith, optstr);
2445 if(netgen::multithread.terminate)
2448 // copy LocalH from the main to temporary mesh
2449 initState.transferLocalH( _ngMesh, tmpNgMesh );
2451 // compute mesh on internal edges
2452 startWith = endWith = netgen::MESHCONST_MESHEDGES;
2454 err = netgen::OCCGenerateMesh(intOccgeo, tmpNgMesh, mparams, startWith, endWith);
2456 err = netgen::OCCGenerateMesh(intOccgeo, tmpNgMesh, startWith, endWith, optstr);
2458 comment << text(err);
2460 catch (Standard_Failure& ex)
2462 comment << text(ex);
2465 initState.restoreLocalH( tmpNgMesh );
2467 // fill SMESH by netgen mesh
2468 vector< const SMDS_MeshNode* > tmpNodeVec;
2469 FillSMesh( intOccgeo, *tmpNgMesh, initState, *_mesh, tmpNodeVec, comment );
2470 err = ( err || !comment.empty() );
2472 nglib::Ng_DeleteMesh((nglib::Ng_Mesh*)tmpNgMesh);
2475 // Fill _ngMesh with nodes and segments of computed submeshes
2478 err = ! ( FillNgMesh(occgeo, *_ngMesh, nodeVec, meshedSM[ MeshDim_0D ]) &&
2479 FillNgMesh(occgeo, *_ngMesh, nodeVec, meshedSM[ MeshDim_1D ], &quadHelper));
2481 initState = NETGENPlugin_ngMeshInfo(_ngMesh);
2486 startWith = endWith = netgen::MESHCONST_MESHEDGES;
2491 err = netgen::OCCGenerateMesh(occgeo, _ngMesh, mparams, startWith, endWith);
2493 err = netgen::OCCGenerateMesh(occgeo, _ngMesh, startWith, endWith, optstr);
2495 if(netgen::multithread.terminate)
2498 comment << text(err);
2500 catch (Standard_Failure& ex)
2502 comment << text(ex);
2507 _ticTime = ( doneTime += edgeMeshingTime ) / _totalTime / _progressTic;
2509 mparams.uselocalh = true; // restore as it is used at surface optimization
2511 // ---------------------
2512 // compute surface mesh
2513 // ---------------------
2516 // Pass 2D simple parameters to NETGEN
2518 if ( double area = _simpleHyp->GetMaxElementArea() ) {
2520 mparams.maxh = sqrt(2. * area/sqrt(3.0));
2521 mparams.grading = 0.4; // moderate size growth
2524 // length from edges
2525 if ( _ngMesh->GetNSeg() ) {
2526 double edgeLength = 0;
2527 TopTools_MapOfShape visitedEdges;
2528 for ( TopExp_Explorer exp( _shape, TopAbs_EDGE ); exp.More(); exp.Next() )
2529 if( visitedEdges.Add(exp.Current()) )
2530 edgeLength += SMESH_Algo::EdgeLength( TopoDS::Edge( exp.Current() ));
2531 // we have to multiply length by 2 since for each TopoDS_Edge there
2532 // are double set of NETGEN edges, in other words, we have to
2533 // divide _ngMesh->GetNSeg() by 2.
2534 mparams.maxh = 2*edgeLength / _ngMesh->GetNSeg();
2537 mparams.maxh = 1000;
2539 mparams.grading = 0.2; // slow size growth
2541 mparams.quad = _simpleHyp->GetAllowQuadrangles();
2542 mparams.maxh = min( mparams.maxh, occgeo.boundingbox.Diam()/2 );
2543 _ngMesh->SetGlobalH (mparams.maxh);
2544 netgen::Box<3> bb = occgeo.GetBoundingBox();
2545 bb.Increase (bb.Diam()/20);
2546 _ngMesh->SetLocalH (bb.PMin(), bb.PMax(), mparams.grading);
2549 // Care of vertices internal in faces (issue 0020676)
2550 if ( internals.hasInternalVertexInFace() )
2552 // store computed segments in SMESH in order not to create SMESH
2553 // edges for ng segments added by AddIntVerticesInFaces()
2554 FillSMesh( occgeo, *_ngMesh, initState, *_mesh, nodeVec, comment );
2555 // add segments to faces with internal vertices
2556 AddIntVerticesInFaces( occgeo, *_ngMesh, nodeVec, internals );
2557 initState = NETGENPlugin_ngMeshInfo(_ngMesh);
2560 // Build viscous layers
2561 if ( _isViscousLayers2D )
2563 if ( !internals.hasInternalVertexInFace() ) {
2564 FillSMesh( occgeo, *_ngMesh, initState, *_mesh, nodeVec, comment );
2565 initState = NETGENPlugin_ngMeshInfo(_ngMesh);
2567 SMESH_ProxyMesh::Ptr viscousMesh;
2568 SMESH_MesherHelper helper( *_mesh );
2569 for ( int faceID = 1; faceID <= occgeo.fmap.Extent(); ++faceID )
2571 const TopoDS_Face& F = TopoDS::Face( occgeo.fmap( faceID ));
2572 viscousMesh = StdMeshers_ViscousLayers2D::Compute( *_mesh, F );
2575 // exclude from computation ng segments built on EDGEs of F
2576 for (int i = 1; i <= _ngMesh->GetNSeg(); i++)
2578 netgen::Segment & seg = _ngMesh->LineSegment(i);
2579 if (seg.si == faceID)
2582 // add new segments to _ngMesh instead of excluded ones
2583 helper.SetSubShape( F );
2585 StdMeshers_FaceSide::GetFaceWires( F, *_mesh, /*skipMediumNodes=*/true,
2586 error, viscousMesh );
2587 error = AddSegmentsToMesh( *_ngMesh, occgeo, wires, helper, nodeVec );
2589 if ( !error ) error = SMESH_ComputeError::New();
2591 initState = NETGENPlugin_ngMeshInfo(_ngMesh);
2594 // Let netgen compute 2D mesh
2595 startWith = netgen::MESHCONST_MESHSURFACE;
2596 endWith = _optimize ? netgen::MESHCONST_OPTSURFACE : netgen::MESHCONST_MESHSURFACE;
2601 err = netgen::OCCGenerateMesh(occgeo, _ngMesh, mparams, startWith, endWith);
2603 err = netgen::OCCGenerateMesh(occgeo, _ngMesh, startWith, endWith, optstr);
2605 if(netgen::multithread.terminate)
2608 comment << text (err);
2610 catch (Standard_Failure& ex)
2612 comment << text(ex);
2613 //err = 1; -- try to make volumes anyway
2615 catch (netgen::NgException exc)
2617 comment << text(exc);
2618 //err = 1; -- try to make volumes anyway
2623 doneTime += faceMeshingTime + ( _optimize ? faceOptimizTime : 0 );
2624 _ticTime = doneTime / _totalTime / _progressTic;
2626 // ---------------------
2627 // generate volume mesh
2628 // ---------------------
2629 // Fill _ngMesh with nodes and faces of computed 2D submeshes
2630 if ( !err && _isVolume && ( !meshedSM[ MeshDim_2D ].empty() || mparams.quad ))
2632 // load SMESH with computed segments and faces
2633 FillSMesh( occgeo, *_ngMesh, initState, *_mesh, nodeVec, comment, &quadHelper );
2635 // compute pyramids on quadrangles
2636 SMESH_ProxyMesh::Ptr proxyMesh;
2637 if ( _mesh->NbQuadrangles() > 0 )
2638 for ( int iS = 1; iS <= occgeo.somap.Extent(); ++iS )
2640 StdMeshers_QuadToTriaAdaptor* Adaptor = new StdMeshers_QuadToTriaAdaptor;
2641 proxyMesh.reset( Adaptor );
2643 int nbPyrams = _mesh->NbPyramids();
2644 Adaptor->Compute( *_mesh, occgeo.somap(iS) );
2645 if ( nbPyrams != _mesh->NbPyramids() )
2647 list< SMESH_subMesh* > quadFaceSM;
2648 for (TopExp_Explorer face(occgeo.somap(iS), TopAbs_FACE); face.More(); face.Next())
2649 if ( Adaptor->GetProxySubMesh( face.Current() ))
2651 quadFaceSM.push_back( _mesh->GetSubMesh( face.Current() ));
2652 meshedSM[ MeshDim_2D ].remove( quadFaceSM.back() );
2654 FillNgMesh(occgeo, *_ngMesh, nodeVec, quadFaceSM, &quadHelper, proxyMesh);
2657 // fill _ngMesh with faces of sub-meshes
2658 err = ! ( FillNgMesh(occgeo, *_ngMesh, nodeVec, meshedSM[ MeshDim_2D ], &quadHelper));
2659 initState = NETGENPlugin_ngMeshInfo(_ngMesh);
2660 //toPython( _ngMesh, "/tmp/ngPython.py");
2662 if (!err && _isVolume)
2664 // Pass 3D simple parameters to NETGEN
2665 const NETGENPlugin_SimpleHypothesis_3D* simple3d =
2666 dynamic_cast< const NETGENPlugin_SimpleHypothesis_3D* > ( _simpleHyp );
2668 if ( double vol = simple3d->GetMaxElementVolume() ) {
2670 mparams.maxh = pow( 72, 1/6. ) * pow( vol, 1/3. );
2671 mparams.maxh = min( mparams.maxh, occgeo.boundingbox.Diam()/2 );
2674 // length from faces
2675 mparams.maxh = _ngMesh->AverageH();
2677 _ngMesh->SetGlobalH (mparams.maxh);
2678 mparams.grading = 0.4;
2680 _ngMesh->CalcLocalH(mparams.grading);
2682 _ngMesh->CalcLocalH();
2685 // Care of vertices internal in solids and internal faces (issue 0020676)
2686 if ( internals.hasInternalVertexInSolid() || internals.hasInternalFaces() )
2688 // store computed faces in SMESH in order not to create SMESH
2689 // faces for ng faces added here
2690 FillSMesh( occgeo, *_ngMesh, initState, *_mesh, nodeVec, comment, &quadHelper );
2691 // add ng faces to solids with internal vertices
2692 AddIntVerticesInSolids( occgeo, *_ngMesh, nodeVec, internals );
2693 // duplicate mesh faces on internal faces
2694 FixIntFaces( occgeo, *_ngMesh, internals );
2695 initState = NETGENPlugin_ngMeshInfo(_ngMesh);
2697 // Let netgen compute 3D mesh
2698 startWith = endWith = netgen::MESHCONST_MESHVOLUME;
2703 err = netgen::OCCGenerateMesh(occgeo, _ngMesh, mparams, startWith, endWith);
2705 err = netgen::OCCGenerateMesh(occgeo, _ngMesh, startWith, endWith, optstr);
2707 if(netgen::multithread.terminate)
2710 if ( comment.empty() ) // do not overwrite a previos error
2711 comment << text(err);
2713 catch (Standard_Failure& ex)
2715 if ( comment.empty() ) // do not overwrite a previos error
2716 comment << text(ex);
2719 catch (netgen::NgException exc)
2721 if ( comment.empty() ) // do not overwrite a previos error
2722 comment << text(exc);
2725 _ticTime = ( doneTime += voluMeshingTime ) / _totalTime / _progressTic;
2727 // Let netgen optimize 3D mesh
2728 if ( !err && _optimize )
2730 startWith = endWith = netgen::MESHCONST_OPTVOLUME;
2735 err = netgen::OCCGenerateMesh(occgeo, _ngMesh, mparams, startWith, endWith);
2737 err = netgen::OCCGenerateMesh(occgeo, _ngMesh, startWith, endWith, optstr);
2739 if(netgen::multithread.terminate)
2742 if ( comment.empty() ) // do not overwrite a previos error
2743 comment << text(err);
2745 catch (Standard_Failure& ex)
2747 if ( comment.empty() ) // do not overwrite a previos error
2748 comment << text(ex);
2750 catch (netgen::NgException exc)
2752 if ( comment.empty() ) // do not overwrite a previos error
2753 comment << text(exc);
2757 if (!err && mparams.secondorder > 0)
2762 if ( !meshedSM[ MeshDim_1D ].empty() )
2764 // remove segments not attached to geometry (IPAL0052479)
2765 for (int i = 1; i <= _ngMesh->GetNSeg(); ++i)
2767 const netgen::Segment & seg = _ngMesh->LineSegment (i);
2768 if ( seg.epgeominfo[ 0 ].edgenr == 0 )
2769 _ngMesh->DeleteSegment( i );
2771 _ngMesh->Compress();
2773 // convert to quadratic
2774 netgen::OCCRefinementSurfaces ref (occgeo);
2775 ref.MakeSecondOrder (*_ngMesh);
2777 // care of elements already loaded to SMESH
2778 // if ( initState._nbSegments > 0 )
2779 // makeQuadratic( occgeo.emap, _mesh );
2780 // if ( initState._nbFaces > 0 )
2781 // makeQuadratic( occgeo.fmap, _mesh );
2783 catch (Standard_Failure& ex)
2785 if ( comment.empty() ) // do not overwrite a previos error
2786 comment << "Exception in netgen at passing to 2nd order ";
2788 catch (netgen::NgException exc)
2790 if ( comment.empty() ) // do not overwrite a previos error
2791 comment << exc.What();
2796 _ticTime = 0.98 / _progressTic;
2798 int nbNod = _ngMesh->GetNP();
2799 int nbSeg = _ngMesh->GetNSeg();
2800 int nbFac = _ngMesh->GetNSE();
2801 int nbVol = _ngMesh->GetNE();
2802 bool isOK = ( !err && (_isVolume ? (nbVol > 0) : (nbFac > 0)) );
2804 MESSAGE((err ? "Mesh Generation failure" : "End of Mesh Generation") <<
2805 ", nb nodes: " << nbNod <<
2806 ", nb segments: " << nbSeg <<
2807 ", nb faces: " << nbFac <<
2808 ", nb volumes: " << nbVol);
2810 // Feed back the SMESHDS with the generated Nodes and Elements
2811 if ( true /*isOK*/ ) // get whatever built
2813 FillSMesh( occgeo, *_ngMesh, initState, *_mesh, nodeVec, comment, &quadHelper );
2815 if ( quadHelper.GetIsQuadratic() ) // remove free nodes
2816 for ( size_t i = 0; i < nodeVec.size(); ++i )
2817 if ( nodeVec[i] && nodeVec[i]->NbInverseElements() == 0 )
2818 _mesh->GetMeshDS()->RemoveFreeNode( nodeVec[i], 0, /*fromGroups=*/false );
2820 SMESH_ComputeErrorPtr readErr = ReadErrors(nodeVec);
2821 if ( readErr && !readErr->myBadElements.empty() )
2824 if ( error->IsOK() && ( !isOK || comment.size() > 0 ))
2825 error->myName = COMPERR_ALGO_FAILED;
2826 if ( !comment.empty() )
2827 error->myComment = comment;
2829 // SetIsAlwaysComputed( true ) to empty sub-meshes, which
2830 // appear if the geometry contains coincident sub-shape due
2831 // to bool merge_solids = 1; in netgen/libsrc/occ/occgenmesh.cpp
2832 const int nbMaps = 2;
2833 const TopTools_IndexedMapOfShape* geoMaps[nbMaps] =
2834 { & occgeo.vmap, & occgeo.emap/*, & occgeo.fmap*/ };
2835 for ( int iMap = 0; iMap < nbMaps; ++iMap )
2836 for (int i = 1; i <= geoMaps[iMap]->Extent(); i++)
2837 if ( SMESH_subMesh* sm = _mesh->GetSubMeshContaining( geoMaps[iMap]->FindKey(i)))
2838 if ( !sm->IsMeshComputed() )
2839 sm->SetIsAlwaysComputed( true );
2841 // set bad compute error to subshapes of all failed sub-shapes
2842 if ( !error->IsOK() )
2844 bool pb2D = false, pb3D = false;
2845 for (int i = 1; i <= occgeo.fmap.Extent(); i++) {
2846 int status = occgeo.facemeshstatus[i-1];
2847 if (status == 1 ) continue;
2848 if ( SMESH_subMesh* sm = _mesh->GetSubMeshContaining( occgeo.fmap( i ))) {
2849 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
2850 if ( !smError || smError->IsOK() ) {
2852 smError.reset( new SMESH_ComputeError( *error ));
2854 smError.reset( new SMESH_ComputeError( COMPERR_ALGO_FAILED, "Ignored" ));
2855 if ( SMESH_Algo::GetMeshError( sm ) == SMESH_Algo::MEr_OK )
2856 smError->myName = COMPERR_WARNING;
2858 pb2D = pb2D || smError->IsKO();
2861 if ( !pb2D ) // all faces are OK
2862 for (int i = 1; i <= occgeo.somap.Extent(); i++)
2863 if ( SMESH_subMesh* sm = _mesh->GetSubMeshContaining( occgeo.somap( i )))
2865 bool smComputed = nbVol && !sm->IsEmpty();
2866 if ( smComputed && internals.hasInternalVertexInSolid( sm->GetId() ))
2868 int nbIntV = internals.getSolidsWithVertices().find( sm->GetId() )->second.size();
2869 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
2870 smComputed = ( smDS->NbElements() > 0 || smDS->NbNodes() > nbIntV );
2872 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
2873 if ( !smComputed && ( !smError || smError->IsOK() ))
2875 smError.reset( new SMESH_ComputeError( *error ));
2876 if ( nbVol && SMESH_Algo::GetMeshError( sm ) == SMESH_Algo::MEr_OK )
2878 smError->myName = COMPERR_WARNING;
2880 else if ( !smError->myBadElements.empty() ) // bad surface mesh
2882 if ( !hasBadElemOnSolid( smError->myBadElements, sm ))
2886 pb3D = pb3D || ( smError && smError->IsKO() );
2888 if ( !pb2D && !pb3D )
2889 err = 0; // no fatal errors, only warnings
2892 ngLib._isComputeOk = !err;
2897 //=============================================================================
2901 //=============================================================================
2902 bool NETGENPlugin_Mesher::Evaluate(MapShapeNbElems& aResMap)
2904 netgen::MeshingParameters& mparams = netgen::mparam;
2907 // -------------------------
2908 // Prepare OCC geometry
2909 // -------------------------
2910 netgen::OCCGeometry occgeo;
2911 list< SMESH_subMesh* > meshedSM[4]; // for 0-3 dimensions
2912 NETGENPlugin_Internals internals( *_mesh, _shape, _isVolume );
2913 PrepareOCCgeometry( occgeo, _shape, *_mesh, meshedSM, &internals );
2915 bool tooManyElems = false;
2916 const int hugeNb = std::numeric_limits<int>::max() / 100;
2921 // pass 1D simple parameters to NETGEN
2924 // not to RestrictLocalH() according to curvature during MESHCONST_ANALYSE
2925 mparams.uselocalh = false;
2926 mparams.grading = 0.8; // not limitited size growth
2928 if ( _simpleHyp->GetNumberOfSegments() )
2930 mparams.maxh = occgeo.boundingbox.Diam();
2933 mparams.maxh = _simpleHyp->GetLocalLength();
2936 if ( mparams.maxh == 0.0 )
2937 mparams.maxh = occgeo.boundingbox.Diam();
2938 if ( _simpleHyp || ( mparams.minh == 0.0 && _fineness != NETGENPlugin_Hypothesis::UserDefined))
2939 mparams.minh = GetDefaultMinSize( _shape, mparams.maxh );
2941 // let netgen create _ngMesh and calculate element size on not meshed shapes
2942 NETGENPlugin_NetgenLibWrapper ngLib;
2943 netgen::Mesh *ngMesh = NULL;
2947 int startWith = netgen::MESHCONST_ANALYSE;
2948 int endWith = netgen::MESHCONST_MESHEDGES;
2950 int err = netgen::OCCGenerateMesh(occgeo, ngMesh, mparams, startWith, endWith);
2952 int err = netgen::OCCGenerateMesh(occgeo, ngMesh, startWith, endWith, optstr);
2955 if(netgen::multithread.terminate)
2958 ngLib.setMesh(( Ng_Mesh*) ngMesh );
2960 if ( SMESH_subMesh* sm = _mesh->GetSubMeshContaining( _shape ))
2961 sm->GetComputeError().reset( new SMESH_ComputeError( COMPERR_ALGO_FAILED ));
2966 // Pass 1D simple parameters to NETGEN
2967 // --------------------------------
2968 int nbSeg = _simpleHyp->GetNumberOfSegments();
2969 double segSize = _simpleHyp->GetLocalLength();
2970 for ( int iE = 1; iE <= occgeo.emap.Extent(); ++iE )
2972 const TopoDS_Edge& e = TopoDS::Edge( occgeo.emap(iE));
2974 segSize = SMESH_Algo::EdgeLength( e ) / ( nbSeg - 0.4 );
2975 setLocalSize( e, segSize, *ngMesh );
2978 else // if ( ! _simpleHyp )
2980 // Local size on vertices and edges
2981 // --------------------------------
2982 for(std::map<int,double>::const_iterator it=EdgeId2LocalSize.begin(); it!=EdgeId2LocalSize.end(); it++)
2984 int key = (*it).first;
2985 double hi = (*it).second;
2986 const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
2987 const TopoDS_Edge& e = TopoDS::Edge(shape);
2988 setLocalSize( e, hi, *ngMesh );
2990 for(std::map<int,double>::const_iterator it=VertexId2LocalSize.begin(); it!=VertexId2LocalSize.end(); it++)
2992 int key = (*it).first;
2993 double hi = (*it).second;
2994 const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
2995 const TopoDS_Vertex& v = TopoDS::Vertex(shape);
2996 gp_Pnt p = BRep_Tool::Pnt(v);
2997 NETGENPlugin_Mesher::RestrictLocalSize( *ngMesh, p.XYZ(), hi );
2999 for(map<int,double>::const_iterator it=FaceId2LocalSize.begin();
3000 it!=FaceId2LocalSize.end(); it++)
3002 int key = (*it).first;
3003 double val = (*it).second;
3004 const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
3005 int faceNgID = occgeo.fmap.FindIndex(shape);
3006 occgeo.SetFaceMaxH(faceNgID, val);
3007 for ( TopExp_Explorer edgeExp( shape, TopAbs_EDGE ); edgeExp.More(); edgeExp.Next() )
3008 setLocalSize( TopoDS::Edge( edgeExp.Current() ), val, *ngMesh );
3011 // calculate total nb of segments and length of edges
3012 double fullLen = 0.0;
3014 int entity = mparams.secondorder > 0 ? SMDSEntity_Quad_Edge : SMDSEntity_Edge;
3015 TopTools_DataMapOfShapeInteger Edge2NbSeg;
3016 for (TopExp_Explorer exp(_shape, TopAbs_EDGE); exp.More(); exp.Next())
3018 TopoDS_Edge E = TopoDS::Edge( exp.Current() );
3019 if( !Edge2NbSeg.Bind(E,0) )
3022 double aLen = SMESH_Algo::EdgeLength(E);
3025 vector<int>& aVec = aResMap[_mesh->GetSubMesh(E)];
3027 aVec.resize( SMDSEntity_Last, 0);
3029 fullNbSeg += aVec[ entity ];
3032 // store nb of segments computed by Netgen
3033 NCollection_Map<Link> linkMap;
3034 for (int i = 1; i <= ngMesh->GetNSeg(); ++i )
3036 const netgen::Segment& seg = ngMesh->LineSegment(i);
3037 Link link(seg[0], seg[1]);
3038 if ( !linkMap.Add( link )) continue;
3039 int aGeomEdgeInd = seg.epgeominfo[0].edgenr;
3040 if (aGeomEdgeInd > 0 && aGeomEdgeInd <= occgeo.emap.Extent())
3042 vector<int>& aVec = aResMap[_mesh->GetSubMesh(occgeo.emap(aGeomEdgeInd))];
3046 // store nb of nodes on edges computed by Netgen
3047 TopTools_DataMapIteratorOfDataMapOfShapeInteger Edge2NbSegIt(Edge2NbSeg);
3048 for (; Edge2NbSegIt.More(); Edge2NbSegIt.Next())
3050 vector<int>& aVec = aResMap[_mesh->GetSubMesh(Edge2NbSegIt.Key())];
3051 if ( aVec[ entity ] > 1 && aVec[ SMDSEntity_Node ] == 0 )
3052 aVec[SMDSEntity_Node] = mparams.secondorder > 0 ? 2*aVec[ entity ]-1 : aVec[ entity ]-1;
3054 fullNbSeg += aVec[ entity ];
3055 Edge2NbSeg( Edge2NbSegIt.Key() ) = aVec[ entity ];
3057 if ( fullNbSeg == 0 )
3064 if ( double area = _simpleHyp->GetMaxElementArea() ) {
3066 mparams.maxh = sqrt(2. * area/sqrt(3.0));
3067 mparams.grading = 0.4; // moderate size growth
3070 // length from edges
3071 mparams.maxh = fullLen/fullNbSeg;
3072 mparams.grading = 0.2; // slow size growth
3075 mparams.maxh = min( mparams.maxh, occgeo.boundingbox.Diam()/2 );
3076 mparams.maxh = min( mparams.maxh, fullLen/fullNbSeg * (1. + mparams.grading));
3078 for (TopExp_Explorer exp(_shape, TopAbs_FACE); exp.More(); exp.Next())
3080 TopoDS_Face F = TopoDS::Face( exp.Current() );
3081 SMESH_subMesh *sm = _mesh->GetSubMesh(F);
3083 BRepGProp::SurfaceProperties(F,G);
3084 double anArea = G.Mass();
3085 tooManyElems = tooManyElems || ( anArea/hugeNb > mparams.maxh*mparams.maxh );
3087 if ( !tooManyElems )
3089 TopTools_MapOfShape egdes;
3090 for (TopExp_Explorer exp1(F,TopAbs_EDGE); exp1.More(); exp1.Next())
3091 if ( egdes.Add( exp1.Current() ))
3092 nb1d += Edge2NbSeg.Find(exp1.Current());
3094 int nbFaces = tooManyElems ? hugeNb : int( 4*anArea / (mparams.maxh*mparams.maxh*sqrt(3.)));
3095 int nbNodes = tooManyElems ? hugeNb : (( nbFaces*3 - (nb1d-1)*2 ) / 6 + 1 );
3097 vector<int> aVec(SMDSEntity_Last, 0);
3098 if( mparams.secondorder > 0 ) {
3099 int nb1d_in = (nbFaces*3 - nb1d) / 2;
3100 aVec[SMDSEntity_Node] = nbNodes + nb1d_in;
3101 aVec[SMDSEntity_Quad_Triangle] = nbFaces;
3104 aVec[SMDSEntity_Node] = Max ( nbNodes, 0 );
3105 aVec[SMDSEntity_Triangle] = nbFaces;
3107 aResMap[sm].swap(aVec);
3114 // pass 3D simple parameters to NETGEN
3115 const NETGENPlugin_SimpleHypothesis_3D* simple3d =
3116 dynamic_cast< const NETGENPlugin_SimpleHypothesis_3D* > ( _simpleHyp );
3118 if ( double vol = simple3d->GetMaxElementVolume() ) {
3120 mparams.maxh = pow( 72, 1/6. ) * pow( vol, 1/3. );
3121 mparams.maxh = min( mparams.maxh, occgeo.boundingbox.Diam()/2 );
3124 // using previous length from faces
3126 mparams.grading = 0.4;
3127 mparams.maxh = min( mparams.maxh, fullLen/fullNbSeg * (1. + mparams.grading));
3130 BRepGProp::VolumeProperties(_shape,G);
3131 double aVolume = G.Mass();
3132 double tetrVol = 0.1179*mparams.maxh*mparams.maxh*mparams.maxh;
3133 tooManyElems = tooManyElems || ( aVolume/hugeNb > tetrVol );
3134 int nbVols = tooManyElems ? hugeNb : int(aVolume/tetrVol);
3135 int nb1d_in = int(( nbVols*6 - fullNbSeg ) / 6 );
3136 vector<int> aVec(SMDSEntity_Last, 0 );
3137 if ( tooManyElems ) // avoid FPE
3139 aVec[SMDSEntity_Node] = hugeNb;
3140 aVec[ mparams.secondorder > 0 ? SMDSEntity_Quad_Tetra : SMDSEntity_Tetra] = hugeNb;
3144 if( mparams.secondorder > 0 ) {
3145 aVec[SMDSEntity_Node] = nb1d_in/3 + 1 + nb1d_in;
3146 aVec[SMDSEntity_Quad_Tetra] = nbVols;
3149 aVec[SMDSEntity_Node] = nb1d_in/3 + 1;
3150 aVec[SMDSEntity_Tetra] = nbVols;
3153 SMESH_subMesh *sm = _mesh->GetSubMesh(_shape);
3154 aResMap[sm].swap(aVec);
3160 double NETGENPlugin_Mesher::GetProgress(const SMESH_Algo* holder,
3161 const int * algoProgressTic,
3162 const double * algoProgress) const
3164 ((int&) _progressTic ) = *algoProgressTic + 1;
3166 if ( !_occgeom ) return 0;
3168 double progress = -1;
3171 if ( _ticTime < 0 && netgen::multithread.task[0] == 'O'/*Optimizing surface*/ )
3173 ((double&) _ticTime ) = edgeFaceMeshingTime / _totalTime / _progressTic;
3175 else if ( !_optimize /*&& _occgeom->fmap.Extent() > 1*/ )
3177 int doneShapeIndex = -1;
3178 while ( doneShapeIndex+1 < _occgeom->facemeshstatus.Size() &&
3179 _occgeom->facemeshstatus[ doneShapeIndex+1 ])
3181 if ( doneShapeIndex+1 != _curShapeIndex )
3183 ((int&) _curShapeIndex) = doneShapeIndex+1;
3184 double doneShapeRate = _curShapeIndex / double( _occgeom->fmap.Extent() );
3185 double doneTime = edgeMeshingTime + doneShapeRate * faceMeshingTime;
3186 ((double&) _ticTime) = doneTime / _totalTime / _progressTic;
3187 // cout << "shape " << _curShapeIndex << " _ticTime " << _ticTime
3188 // << " " << doneTime / _totalTime / _progressTic << endl;
3192 else if ( !_optimize && _occgeom->somap.Extent() > 1 )
3194 int curShapeIndex = _curShapeIndex;
3195 if ( _ngMesh->GetNE() > 0 )
3197 netgen::Element el = (*_ngMesh)[netgen::ElementIndex( _ngMesh->GetNE()-1 )];
3198 curShapeIndex = el.GetIndex();
3200 if ( curShapeIndex != _curShapeIndex )
3202 ((int&) _curShapeIndex) = curShapeIndex;
3203 double doneShapeRate = _curShapeIndex / double( _occgeom->somap.Extent() );
3204 double doneTime = edgeFaceMeshingTime + doneShapeRate * voluMeshingTime;
3205 ((double&) _ticTime) = doneTime / _totalTime / _progressTic;
3206 // cout << "shape " << _curShapeIndex << " _ticTime " << _ticTime
3207 // << " " << doneTime / _totalTime / _progressTic << endl;
3211 progress = Max( *algoProgressTic * _ticTime, *algoProgress );
3214 ((int&) *algoProgressTic )++;
3215 ((double&) *algoProgress) = progress;
3217 //cout << progress << " " << *algoProgressTic << " " << netgen::multithread.task << " "<< _ticTime << endl;
3219 return Min( progress, 0.99 );
3222 //================================================================================
3224 * \brief Remove "test.out" and "problemfaces" files in current directory
3226 //================================================================================
3228 void NETGENPlugin_Mesher::RemoveTmpFiles()
3230 bool rm = SMESH_File("test.out").remove() ;
3232 if (rm && netgen::testout)
3234 delete netgen::testout;
3235 netgen::testout = 0;
3238 SMESH_File("problemfaces").remove();
3239 SMESH_File("occmesh.rep").remove();
3242 //================================================================================
3244 * \brief Read mesh entities preventing successful computation from "test.out" file
3246 //================================================================================
3248 SMESH_ComputeErrorPtr
3249 NETGENPlugin_Mesher::ReadErrors(const vector<const SMDS_MeshNode* >& nodeVec)
3251 SMESH_ComputeErrorPtr err = SMESH_ComputeError::New
3252 (COMPERR_BAD_INPUT_MESH, "Some edges multiple times in surface mesh");
3253 SMESH_File file("test.out");
3255 const char* badEdgeStr = " multiple times in surface mesh";
3256 const int badEdgeStrLen = strlen( badEdgeStr );
3257 while( !file.eof() )
3259 if ( strncmp( file, "Edge ", 5 ) == 0 &&
3260 file.getInts( two ) &&
3261 strncmp( file, badEdgeStr, badEdgeStrLen ) == 0 &&
3262 two[0] < nodeVec.size() && two[1] < nodeVec.size())
3264 err->myBadElements.push_back( new SMDS_LinearEdge( nodeVec[ two[0]], nodeVec[ two[1]] ));
3265 file += badEdgeStrLen;
3267 else if ( strncmp( file, "Intersecting: ", 14 ) == 0 )
3270 // openelement 18 with open element 126
3273 vector<int> three1(3), three2(3);
3275 const char* pos = file;
3276 bool ok = ( strncmp( file, "openelement ", 12 ) == 0 );
3277 ok = ok && file.getInts( two );
3278 ok = ok && file.getInts( three1 );
3279 ok = ok && file.getInts( three2 );
3280 for ( int i = 0; ok && i < 3; ++i )
3281 ok = ( three1[i] < nodeVec.size() && nodeVec[ three1[i]]);
3282 for ( int i = 0; ok && i < 3; ++i )
3283 ok = ( three2[i] < nodeVec.size() && nodeVec[ three2[i]]);
3286 err->myBadElements.push_back( new SMDS_FaceOfNodes( nodeVec[ three1[0]],
3287 nodeVec[ three1[1]],
3288 nodeVec[ three1[2]]));
3289 err->myBadElements.push_back( new SMDS_FaceOfNodes( nodeVec[ three2[0]],
3290 nodeVec[ three2[1]],
3291 nodeVec[ three2[2]]));
3292 err->myComment = "Intersecting triangles";
3307 //================================================================================
3309 * \brief Write a python script creating an equivalent SALOME mesh.
3310 * This is useful to see what mesh is passed as input for the next step of mesh
3311 * generation (of mesh of higher dimension)
3313 //================================================================================
3315 void NETGENPlugin_Mesher::toPython( const netgen::Mesh* ngMesh,
3316 const std::string& pyFile)
3318 ofstream outfile(pyFile.c_str(), ios::out);
3319 if ( !outfile ) return;
3321 outfile << "import SMESH" << endl
3322 << "from salome.smesh import smeshBuilder" << endl
3323 << "smesh = smeshBuilder.New(salome.myStudy)" << endl
3324 << "mesh = smesh.Mesh()" << endl << endl;
3326 using namespace netgen;
3328 for (pi = PointIndex::BASE;
3329 pi < ngMesh->GetNP()+PointIndex::BASE; pi++)
3331 outfile << "mesh.AddNode( ";
3332 outfile << (*ngMesh)[pi](0) << ", ";
3333 outfile << (*ngMesh)[pi](1) << ", ";
3334 outfile << (*ngMesh)[pi](2) << ") ## "<< pi << endl;
3337 int nbDom = ngMesh->GetNDomains();
3338 for ( int i = 0; i < nbDom; ++i )
3339 outfile<< "grp" << i+1 << " = mesh.CreateEmptyGroup( SMESH.FACE, 'domain"<< i+1 << "')"<< endl;
3341 SurfaceElementIndex sei;
3342 for (sei = 0; sei < ngMesh->GetNSE(); sei++)
3344 outfile << "mesh.AddFace([ ";
3345 Element2d sel = (*ngMesh)[sei];
3346 for (int j = 0; j < sel.GetNP(); j++)
3347 outfile << sel[j] << ( j+1 < sel.GetNP() ? ", " : " ])");
3348 if ( sel.IsDeleted() ) outfile << " ## IsDeleted ";
3351 if ((*ngMesh)[sei].GetIndex())
3353 if ( int dom1 = ngMesh->GetFaceDescriptor((*ngMesh)[sei].GetIndex ()).DomainIn())
3354 outfile << "grp"<< dom1 <<".Add([ " << (int)sei+1 << " ])" << endl;
3355 if ( int dom2 = ngMesh->GetFaceDescriptor((*ngMesh)[sei].GetIndex ()).DomainOut())
3356 outfile << "grp"<< dom2 <<".Add([ " << (int)sei+1 << " ])" << endl;
3360 for (ElementIndex ei = 0; ei < ngMesh->GetNE(); ei++)
3362 Element el = (*ngMesh)[ei];
3363 outfile << "mesh.AddVolume([ ";
3364 for (int j = 0; j < el.GetNP(); j++)
3365 outfile << el[j] << ( j+1 < el.GetNP() ? ", " : " ])");
3369 for (int i = 1; i <= ngMesh->GetNSeg(); i++)
3371 const Segment & seg = ngMesh->LineSegment (i);
3372 outfile << "mesh.AddEdge([ "
3374 << seg[1] << " ])" << endl;
3376 cout << "Write " << pyFile << endl;
3379 //================================================================================
3381 * \brief Constructor of NETGENPlugin_ngMeshInfo
3383 //================================================================================
3385 NETGENPlugin_ngMeshInfo::NETGENPlugin_ngMeshInfo( netgen::Mesh* ngMesh):
3390 _nbNodes = ngMesh->GetNP();
3391 _nbSegments = ngMesh->GetNSeg();
3392 _nbFaces = ngMesh->GetNSE();
3393 _nbVolumes = ngMesh->GetNE();
3397 _nbNodes = _nbSegments = _nbFaces = _nbVolumes = 0;
3401 //================================================================================
3403 * \brief Copy LocalH member from one netgen mesh to another
3405 //================================================================================
3407 void NETGENPlugin_ngMeshInfo::transferLocalH( netgen::Mesh* fromMesh,
3408 netgen::Mesh* toMesh )
3410 if ( !fromMesh->LocalHFunctionGenerated() ) return;
3411 if ( !toMesh->LocalHFunctionGenerated() )
3413 toMesh->CalcLocalH(netgen::mparam.grading);
3415 toMesh->CalcLocalH();
3418 const size_t size = sizeof( netgen::LocalH );
3419 _copyOfLocalH = new char[ size ];
3420 memcpy( (void*)_copyOfLocalH, (void*)&toMesh->LocalHFunction(), size );
3421 memcpy( (void*)&toMesh->LocalHFunction(), (void*)&fromMesh->LocalHFunction(), size );
3424 //================================================================================
3426 * \brief Restore LocalH member of a netgen mesh
3428 //================================================================================
3430 void NETGENPlugin_ngMeshInfo::restoreLocalH( netgen::Mesh* toMesh )
3432 if ( _copyOfLocalH )
3434 const size_t size = sizeof( netgen::LocalH );
3435 memcpy( (void*)&toMesh->LocalHFunction(), (void*)_copyOfLocalH, size );
3436 delete [] _copyOfLocalH;
3441 //================================================================================
3443 * \brief Find "internal" sub-shapes
3445 //================================================================================
3447 NETGENPlugin_Internals::NETGENPlugin_Internals( SMESH_Mesh& mesh,
3448 const TopoDS_Shape& shape,
3450 : _mesh( mesh ), _is3D( is3D )
3452 SMESHDS_Mesh* meshDS = mesh.GetMeshDS();
3454 TopExp_Explorer f,e;
3455 for ( f.Init( shape, TopAbs_FACE ); f.More(); f.Next() )
3457 int faceID = meshDS->ShapeToIndex( f.Current() );
3459 // find not computed internal edges
3461 for ( e.Init( f.Current().Oriented(TopAbs_FORWARD), TopAbs_EDGE ); e.More(); e.Next() )
3462 if ( e.Current().Orientation() == TopAbs_INTERNAL )
3464 SMESH_subMesh* eSM = mesh.GetSubMesh( e.Current() );
3465 if ( eSM->IsEmpty() )
3467 _e2face.insert( make_pair( eSM->GetId(), faceID ));
3468 for ( TopoDS_Iterator v(e.Current()); v.More(); v.Next() )
3469 _e2face.insert( make_pair( meshDS->ShapeToIndex( v.Value() ), faceID ));
3473 // find internal vertices in a face
3474 set<int> intVV; // issue 0020850 where same vertex is twice in a face
3475 for ( TopoDS_Iterator fSub( f.Current() ); fSub.More(); fSub.Next())
3476 if ( fSub.Value().ShapeType() == TopAbs_VERTEX )
3478 int vID = meshDS->ShapeToIndex( fSub.Value() );
3479 if ( intVV.insert( vID ).second )
3480 _f2v[ faceID ].push_back( vID );
3485 // find internal faces and their subshapes where nodes are to be doubled
3486 // to make a crack with non-sewed borders
3488 if ( f.Current().Orientation() == TopAbs_INTERNAL )
3490 _intShapes.insert( meshDS->ShapeToIndex( f.Current() ));
3493 list< TopoDS_Shape > edges;
3494 for ( e.Init( f.Current(), TopAbs_EDGE ); e.More(); e.Next())
3495 if ( SMESH_MesherHelper::NbAncestors( e.Current(), mesh, TopAbs_FACE ) > 1 )
3497 _intShapes.insert( meshDS->ShapeToIndex( e.Current() ));
3498 edges.push_back( e.Current() );
3499 // find border faces
3500 PShapeIteratorPtr fIt =
3501 SMESH_MesherHelper::GetAncestors( edges.back(),mesh,TopAbs_FACE );
3502 while ( const TopoDS_Shape* pFace = fIt->next() )
3503 if ( !pFace->IsSame( f.Current() ))
3504 _borderFaces.insert( meshDS->ShapeToIndex( *pFace ));
3507 // we consider vertex internal if it is shared by more than one internal edge
3508 list< TopoDS_Shape >::iterator edge = edges.begin();
3509 for ( ; edge != edges.end(); ++edge )
3510 for ( TopoDS_Iterator v( *edge ); v.More(); v.Next() )
3512 set<int> internalEdges;
3513 PShapeIteratorPtr eIt =
3514 SMESH_MesherHelper::GetAncestors( v.Value(),mesh,TopAbs_EDGE );
3515 while ( const TopoDS_Shape* pEdge = eIt->next() )
3517 int edgeID = meshDS->ShapeToIndex( *pEdge );
3518 if ( isInternalShape( edgeID ))
3519 internalEdges.insert( edgeID );
3521 if ( internalEdges.size() > 1 )
3522 _intShapes.insert( meshDS->ShapeToIndex( v.Value() ));
3526 } // loop on geom faces
3528 // find vertices internal in solids
3531 for ( TopExp_Explorer so(shape, TopAbs_SOLID); so.More(); so.Next())
3533 int soID = meshDS->ShapeToIndex( so.Current() );
3534 for ( TopoDS_Iterator soSub( so.Current() ); soSub.More(); soSub.Next())
3535 if ( soSub.Value().ShapeType() == TopAbs_VERTEX )
3536 _s2v[ soID ].push_back( meshDS->ShapeToIndex( soSub.Value() ));
3541 //================================================================================
3543 * \brief Find mesh faces on non-internal geom faces sharing internal edge
3544 * some nodes of which are to be doubled to make the second border of the "crack"
3546 //================================================================================
3548 void NETGENPlugin_Internals::findBorderElements( TIDSortedElemSet & borderElems )
3550 if ( _intShapes.empty() ) return;
3552 SMESH_Mesh& mesh = const_cast<SMESH_Mesh&>(_mesh);
3553 SMESHDS_Mesh* meshDS = mesh.GetMeshDS();
3555 // loop on internal geom edges
3556 set<int>::const_iterator intShapeId = _intShapes.begin();
3557 for ( ; intShapeId != _intShapes.end(); ++intShapeId )
3559 const TopoDS_Shape& s = meshDS->IndexToShape( *intShapeId );
3560 if ( s.ShapeType() != TopAbs_EDGE ) continue;
3562 // get internal and non-internal geom faces sharing the internal edge <s>
3564 set<int>::iterator bordFace = _borderFaces.end();
3565 PShapeIteratorPtr faces = SMESH_MesherHelper::GetAncestors( s, _mesh, TopAbs_FACE );
3566 while ( const TopoDS_Shape* pFace = faces->next() )
3568 int faceID = meshDS->ShapeToIndex( *pFace );
3569 if ( isInternalShape( faceID ))
3572 bordFace = _borderFaces.insert( faceID ).first;
3574 if ( bordFace == _borderFaces.end() || !intFace ) continue;
3576 // get all links of mesh faces on internal geom face sharing nodes on edge <s>
3577 set< SMESH_OrientedLink > links; //!< links of faces on internal geom face
3578 list<const SMDS_MeshElement*> suspectFaces[2]; //!< mesh faces on border geom faces
3579 int nbSuspectFaces = 0;
3580 SMESHDS_SubMesh* intFaceSM = meshDS->MeshElements( intFace );
3581 if ( !intFaceSM || intFaceSM->NbElements() == 0 ) continue;
3582 SMESH_subMeshIteratorPtr smIt = mesh.GetSubMesh( s )->getDependsOnIterator(true,true);
3583 while ( smIt->more() )
3585 SMESHDS_SubMesh* sm = smIt->next()->GetSubMeshDS();
3586 if ( !sm ) continue;
3587 SMDS_NodeIteratorPtr nIt = sm->GetNodes();
3588 while ( nIt->more() )
3590 const SMDS_MeshNode* nOnEdge = nIt->next();
3591 SMDS_ElemIteratorPtr fIt = nOnEdge->GetInverseElementIterator(SMDSAbs_Face);
3592 while ( fIt->more() )
3594 const SMDS_MeshElement* f = fIt->next();
3595 int nbNodes = f->NbNodes() / ( f->IsQuadratic() ? 2 : 1 );
3596 if ( intFaceSM->Contains( f ))
3598 for ( int i = 0; i < nbNodes; ++i )
3599 links.insert( SMESH_OrientedLink( f->GetNode(i), f->GetNode((i+1)%nbNodes)));
3604 for ( int i = 0; i < nbNodes; ++i )
3605 nbDblNodes += isInternalShape( f->GetNode(i)->getshapeId() );
3607 suspectFaces[ nbDblNodes < 2 ].push_back( f );
3613 // suspectFaces[0] having link with same orientation as mesh faces on
3614 // the internal geom face are <borderElems>. suspectFaces[1] have
3615 // only one node on edge <s>, we decide on them later (at the 2nd loop)
3616 // by links of <borderElems> found at the 1st and 2nd loops
3617 set< SMESH_OrientedLink > borderLinks;
3618 for ( int isPostponed = 0; isPostponed < 2; ++isPostponed )
3620 list<const SMDS_MeshElement*>::iterator fIt = suspectFaces[isPostponed].begin();
3621 for ( int nbF = 0; fIt != suspectFaces[isPostponed].end(); ++fIt, ++nbF )
3623 const SMDS_MeshElement* f = *fIt;
3624 bool isBorder = false, linkFound = false, borderLinkFound = false;
3625 list< SMESH_OrientedLink > faceLinks;
3626 int nbNodes = f->NbNodes() / ( f->IsQuadratic() ? 2 : 1 );
3627 for ( int i = 0; i < nbNodes; ++i )
3629 SMESH_OrientedLink link( f->GetNode(i), f->GetNode((i+1)%nbNodes));
3630 faceLinks.push_back( link );
3633 set< SMESH_OrientedLink >::iterator foundLink = links.find( link );
3634 if ( foundLink != links.end() )
3637 isBorder = ( foundLink->_reversed == link._reversed );
3638 if ( !isBorder && !isPostponed ) break;
3639 faceLinks.pop_back();
3641 else if ( isPostponed && !borderLinkFound )
3643 foundLink = borderLinks.find( link );
3644 if ( foundLink != borderLinks.end() )
3646 borderLinkFound = true;
3647 isBorder = ( foundLink->_reversed != link._reversed );
3654 borderElems.insert( f );
3655 borderLinks.insert( faceLinks.begin(), faceLinks.end() );
3657 else if ( !linkFound && !borderLinkFound )
3659 suspectFaces[1].push_back( f );
3660 if ( nbF > 2 * nbSuspectFaces )
3661 break; // dead loop protection
3668 //================================================================================
3670 * \brief put internal shapes in maps and fill in submeshes to precompute
3672 //================================================================================
3674 void NETGENPlugin_Internals::getInternalEdges( TopTools_IndexedMapOfShape& fmap,
3675 TopTools_IndexedMapOfShape& emap,
3676 TopTools_IndexedMapOfShape& vmap,
3677 list< SMESH_subMesh* > smToPrecompute[])
3679 if ( !hasInternalEdges() ) return;
3680 map<int,int>::const_iterator ev_face = _e2face.begin();
3681 for ( ; ev_face != _e2face.end(); ++ev_face )
3683 const TopoDS_Shape& ev = _mesh.GetMeshDS()->IndexToShape( ev_face->first );
3684 const TopoDS_Shape& face = _mesh.GetMeshDS()->IndexToShape( ev_face->second );
3686 ( ev.ShapeType() == TopAbs_EDGE ? emap : vmap ).Add( ev );
3688 //cout<<"INTERNAL EDGE or VERTEX "<<ev_face->first<<" on face "<<ev_face->second<<endl;
3690 smToPrecompute[ MeshDim_1D ].push_back( _mesh.GetSubMeshContaining( ev_face->first ));
3694 //================================================================================
3696 * \brief return shapes and submeshes to be meshed and already meshed boundary submeshes
3698 //================================================================================
3700 void NETGENPlugin_Internals::getInternalFaces( TopTools_IndexedMapOfShape& fmap,
3701 TopTools_IndexedMapOfShape& emap,
3702 list< SMESH_subMesh* >& intFaceSM,
3703 list< SMESH_subMesh* >& boundarySM)
3705 if ( !hasInternalFaces() ) return;
3707 // <fmap> and <emap> are for not yet meshed shapes
3708 // <intFaceSM> is for submeshes of faces
3709 // <boundarySM> is for meshed edges and vertices
3714 set<int> shapeIDs ( _intShapes );
3715 if ( !_borderFaces.empty() )
3716 shapeIDs.insert( _borderFaces.begin(), _borderFaces.end() );
3718 set<int>::const_iterator intS = shapeIDs.begin();
3719 for ( ; intS != shapeIDs.end(); ++intS )
3721 SMESH_subMesh* sm = _mesh.GetSubMeshContaining( *intS );
3723 if ( sm->GetSubShape().ShapeType() != TopAbs_FACE ) continue;
3725 intFaceSM.push_back( sm );
3727 // add submeshes of not computed internal faces
3728 if ( !sm->IsEmpty() ) continue;
3730 SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(true,true);
3731 while ( smIt->more() )
3734 const TopoDS_Shape& s = sm->GetSubShape();
3736 if ( sm->IsEmpty() )
3739 switch ( s.ShapeType() ) {
3740 case TopAbs_FACE: fmap.Add ( s ); break;
3741 case TopAbs_EDGE: emap.Add ( s ); break;
3747 if ( s.ShapeType() != TopAbs_FACE )
3748 boundarySM.push_back( sm );
3754 //================================================================================
3756 * \brief Return true if given shape is to be precomputed in order to be correctly
3757 * added to netgen mesh
3759 //================================================================================
3761 bool NETGENPlugin_Internals::isShapeToPrecompute(const TopoDS_Shape& s)
3763 int shapeID = _mesh.GetMeshDS()->ShapeToIndex( s );
3764 switch ( s.ShapeType() ) {
3765 case TopAbs_FACE : break; //return isInternalShape( shapeID ) || isBorderFace( shapeID );
3766 case TopAbs_EDGE : return isInternalEdge( shapeID );
3767 case TopAbs_VERTEX: break;
3773 //================================================================================
3775 * \brief Return SMESH
3777 //================================================================================
3779 SMESH_Mesh& NETGENPlugin_Internals::getMesh() const
3781 return const_cast<SMESH_Mesh&>( _mesh );
3784 //================================================================================
3786 * \brief Initialize netgen library
3788 //================================================================================
3790 NETGENPlugin_NetgenLibWrapper::NETGENPlugin_NetgenLibWrapper()
3794 _isComputeOk = false;
3796 if ( !getenv( "KEEP_NETGEN_OUTPUT" ))
3798 // redirect all netgen output (mycout,myerr,cout) to _outputFileName
3799 _outputFileName = getOutputFileName();
3800 netgen::mycout = new ofstream ( _outputFileName.c_str() );
3801 netgen::myerr = netgen::mycout;
3802 _coutBuffer = std::cout.rdbuf();
3804 cout << "NOTE: netgen output is redirected to file " << _outputFileName << endl;
3806 std::cout.rdbuf( netgen::mycout->rdbuf() );
3810 _ngMesh = Ng_NewMesh();
3813 //================================================================================
3815 * \brief Finish using netgen library
3817 //================================================================================
3819 NETGENPlugin_NetgenLibWrapper::~NETGENPlugin_NetgenLibWrapper()
3821 Ng_DeleteMesh( _ngMesh );
3823 NETGENPlugin_Mesher::RemoveTmpFiles();
3825 std::cout.rdbuf( _coutBuffer );
3832 //================================================================================
3834 * \brief Set netgen mesh to delete at destruction
3836 //================================================================================
3838 void NETGENPlugin_NetgenLibWrapper::setMesh( Ng_Mesh* mesh )
3841 Ng_DeleteMesh( _ngMesh );
3845 //================================================================================
3847 * \brief Return a unique file name
3849 //================================================================================
3851 std::string NETGENPlugin_NetgenLibWrapper::getOutputFileName()
3853 std::string aTmpDir = SALOMEDS_Tool::GetTmpDir();
3855 TCollection_AsciiString aGenericName = (char*)aTmpDir.c_str();
3856 aGenericName += "NETGEN_";
3858 aGenericName += getpid();
3860 aGenericName += _getpid();
3862 aGenericName += "_";
3863 aGenericName += Abs((Standard_Integer)(long) aGenericName.ToCString());
3864 aGenericName += ".out";
3866 return aGenericName.ToCString();
3869 //================================================================================
3871 * \brief Remove file with netgen output
3873 //================================================================================
3875 void NETGENPlugin_NetgenLibWrapper::removeOutputFile()
3877 if ( !_outputFileName.empty() )
3879 if ( netgen::mycout )
3881 delete netgen::mycout;
3885 string tmpDir = SALOMEDS_Tool::GetDirFromPath ( _outputFileName );
3886 string aFileName = SALOMEDS_Tool::GetNameFromPath( _outputFileName ) + ".out";
3887 SALOMEDS::ListOfFileNames_var aFiles = new SALOMEDS::ListOfFileNames;
3889 aFiles[0] = aFileName.c_str();
3891 SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.c_str(), aFiles.in(), true );