1 // Copyright (C) 2007-2016 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_LinearEdge.hxx>
36 #include <SMDS_MeshElement.hxx>
37 #include <SMDS_MeshNode.hxx>
38 #include <SMESHDS_Mesh.hxx>
39 #include <SMESH_Block.hxx>
40 #include <SMESH_Comment.hxx>
41 #include <SMESH_ComputeError.hxx>
42 #include <SMESH_ControlPnt.hxx>
43 #include <SMESH_File.hxx>
44 #include <SMESH_Gen_i.hxx>
45 #include <SMESH_Mesh.hxx>
46 #include <SMESH_MesherHelper.hxx>
47 #include <SMESH_subMesh.hxx>
48 #include <StdMeshers_QuadToTriaAdaptor.hxx>
49 #include <StdMeshers_ViscousLayers2D.hxx>
51 #include <SALOMEDS_Tool.hxx>
53 #include <utilities.h>
55 #include <BRepBuilderAPI_Copy.hxx>
56 #include <BRep_Tool.hxx>
57 #include <Bnd_B3d.hxx>
58 #include <NCollection_Map.hxx>
59 #include <Standard_ErrorHandler.hxx>
60 #include <Standard_ProgramError.hxx>
61 #include <TColStd_MapOfInteger.hxx>
63 #include <TopExp_Explorer.hxx>
64 #include <TopTools_DataMapIteratorOfDataMapOfShapeInteger.hxx>
65 #include <TopTools_DataMapIteratorOfDataMapOfShapeShape.hxx>
66 #include <TopTools_DataMapOfShapeInteger.hxx>
67 #include <TopTools_DataMapOfShapeShape.hxx>
68 #include <TopTools_MapOfShape.hxx>
71 // Netgen include files
75 #include <occgeom.hpp>
76 #include <meshing.hpp>
77 //#include <ngexception.hpp>
80 extern int OCCGenerateMesh (OCCGeometry&, Mesh*&, MeshingParameters&, int, int);
82 extern int OCCGenerateMesh (OCCGeometry&, Mesh*&, int, int, char*);
84 //extern void OCCSetLocalMeshSize(OCCGeometry & geom, Mesh & mesh);
85 #if defined(NETGEN_V5) && defined(WIN32)
88 extern MeshingParameters mparam;
89 #if defined(NETGEN_V5) && defined(WIN32)
92 extern volatile multithreadt multithread;
94 #if defined(NETGEN_V5) && defined(WIN32)
97 extern bool merge_solids;
99 // values used for occgeo.facemeshstatus
100 enum EFaceMeshStatus { FACE_NOT_TREATED = 0,
112 using namespace nglib;
116 #define nodeVec_ACCESS(index) ((SMDS_MeshNode*) nodeVec.at((index)))
118 #define nodeVec_ACCESS(index) ((SMDS_MeshNode*) nodeVec[index])
121 #define NGPOINT_COORDS(p) p(0),p(1),p(2)
124 // dump elements added to ng mesh
125 //#define DUMP_SEGMENTS
126 //#define DUMP_TRIANGLES
127 //#define DUMP_TRIANGLES_SCRIPT "/tmp/trias.py" //!< debug AddIntVerticesInSolids()
130 TopTools_IndexedMapOfShape ShapesWithLocalSize;
131 std::map<int,double> VertexId2LocalSize;
132 std::map<int,double> EdgeId2LocalSize;
133 std::map<int,double> FaceId2LocalSize;
134 std::map<int,double> SolidId2LocalSize;
136 std::vector<SMESHUtils::ControlPnt> ControlPoints;
137 std::set<int> ShapesWithControlPoints; // <-- allows calling SetLocalSize() several times w/o recomputing ControlPoints
139 //=============================================================================
143 //=============================================================================
145 NETGENPlugin_Mesher::NETGENPlugin_Mesher (SMESH_Mesh* mesh,
146 const TopoDS_Shape& aShape,
152 _fineness(NETGENPlugin_Hypothesis::GetDefaultFineness()),
153 _isViscousLayers2D(false),
160 _viscousLayersHyp(NULL),
163 SetDefaultParameters();
164 ShapesWithLocalSize.Clear();
165 VertexId2LocalSize.clear();
166 EdgeId2LocalSize.clear();
167 FaceId2LocalSize.clear();
168 SolidId2LocalSize.clear();
169 ControlPoints.clear();
170 ShapesWithControlPoints.clear();
173 //================================================================================
177 //================================================================================
179 NETGENPlugin_Mesher::~NETGENPlugin_Mesher()
187 //================================================================================
189 * Set pointer to NETGENPlugin_Mesher* field of the holder, that will be
190 * nullified at destruction of this
192 //================================================================================
194 void NETGENPlugin_Mesher::SetSelfPointer( NETGENPlugin_Mesher ** ptr )
205 //================================================================================
207 * \brief Initialize global NETGEN parameters with default values
209 //================================================================================
211 void NETGENPlugin_Mesher::SetDefaultParameters()
213 netgen::MeshingParameters& mparams = netgen::mparam;
214 // maximal mesh edge size
215 mparams.maxh = 0;//NETGENPlugin_Hypothesis::GetDefaultMaxSize();
217 // minimal number of segments per edge
218 mparams.segmentsperedge = NETGENPlugin_Hypothesis::GetDefaultNbSegPerEdge();
219 // rate of growth of size between elements
220 mparams.grading = NETGENPlugin_Hypothesis::GetDefaultGrowthRate();
221 // safety factor for curvatures (elements per radius)
222 mparams.curvaturesafety = NETGENPlugin_Hypothesis::GetDefaultNbSegPerRadius();
223 // create elements of second order
224 mparams.secondorder = NETGENPlugin_Hypothesis::GetDefaultSecondOrder();
225 // quad-dominated surface meshing
229 mparams.quad = NETGENPlugin_Hypothesis_2D::GetDefaultQuadAllowed();
230 _fineness = NETGENPlugin_Hypothesis::GetDefaultFineness();
231 mparams.uselocalh = NETGENPlugin_Hypothesis::GetDefaultSurfaceCurvature();
232 netgen::merge_solids = NETGENPlugin_Hypothesis::GetDefaultFuseEdges();
235 //=============================================================================
239 //=============================================================================
241 void SetLocalSize(TopoDS_Shape GeomShape, double LocalSize)
243 if ( GeomShape.IsNull() ) return;
244 TopAbs_ShapeEnum GeomType = GeomShape.ShapeType();
245 if (GeomType == TopAbs_COMPOUND) {
246 for (TopoDS_Iterator it (GeomShape); it.More(); it.Next()) {
247 SetLocalSize(it.Value(), LocalSize);
252 if (! ShapesWithLocalSize.Contains(GeomShape))
253 key = ShapesWithLocalSize.Add(GeomShape);
255 key = ShapesWithLocalSize.FindIndex(GeomShape);
256 if (GeomType == TopAbs_VERTEX) {
257 VertexId2LocalSize[key] = LocalSize;
258 } else if (GeomType == TopAbs_EDGE) {
259 EdgeId2LocalSize[key] = LocalSize;
260 } else if (GeomType == TopAbs_FACE) {
261 FaceId2LocalSize[key] = LocalSize;
262 } else if (GeomType == TopAbs_SOLID) {
263 SolidId2LocalSize[key] = LocalSize;
267 //=============================================================================
269 * Pass parameters to NETGEN
271 //=============================================================================
272 void NETGENPlugin_Mesher::SetParameters(const NETGENPlugin_Hypothesis* hyp)
276 netgen::MeshingParameters& mparams = netgen::mparam;
277 // Initialize global NETGEN parameters:
278 // maximal mesh segment size
279 mparams.maxh = hyp->GetMaxSize();
280 // maximal mesh element linear size
281 mparams.minh = hyp->GetMinSize();
282 // minimal number of segments per edge
283 mparams.segmentsperedge = hyp->GetNbSegPerEdge();
284 // rate of growth of size between elements
285 mparams.grading = hyp->GetGrowthRate();
286 // safety factor for curvatures (elements per radius)
287 mparams.curvaturesafety = hyp->GetNbSegPerRadius();
288 // create elements of second order
289 mparams.secondorder = hyp->GetSecondOrder() ? 1 : 0;
290 // quad-dominated surface meshing
291 mparams.quad = hyp->GetQuadAllowed() ? 1 : 0;
292 _optimize = hyp->GetOptimize();
293 _fineness = hyp->GetFineness();
294 mparams.uselocalh = hyp->GetSurfaceCurvature();
295 netgen::merge_solids = hyp->GetFuseEdges();
298 mparams.meshsizefilename= hyp->GetMeshSizeFile().empty() ? 0 : hyp->GetMeshSizeFile().c_str();
300 SMESH_Gen_i* smeshGen_i = SMESH_Gen_i::GetSMESHGen();
301 CORBA::Object_var anObject = smeshGen_i->GetNS()->Resolve("/myStudyManager");
302 SALOMEDS::StudyManager_var aStudyMgr = SALOMEDS::StudyManager::_narrow(anObject);
303 SALOMEDS::Study_var myStudy = aStudyMgr->GetStudyByID(hyp->GetStudyId());
304 if ( !myStudy->_is_nil() )
306 const NETGENPlugin_Hypothesis::TLocalSize localSizes = hyp->GetLocalSizesAndEntries();
307 NETGENPlugin_Hypothesis::TLocalSize::const_iterator it = localSizes.begin();
308 for ( ; it != localSizes.end() ; it++)
310 std::string entry = (*it).first;
311 double val = (*it).second;
313 GEOM::GEOM_Object_var aGeomObj;
314 SALOMEDS::SObject_var aSObj = myStudy->FindObjectID( entry.c_str() );
315 if ( !aSObj->_is_nil() ) {
316 CORBA::Object_var obj = aSObj->GetObject();
317 aGeomObj = GEOM::GEOM_Object::_narrow(obj);
320 TopoDS_Shape S = smeshGen_i->GeomObjectToShape( aGeomObj.in() );
321 ::SetLocalSize(S, val);
327 //=============================================================================
329 * Pass simple parameters to NETGEN
331 //=============================================================================
333 void NETGENPlugin_Mesher::SetParameters(const NETGENPlugin_SimpleHypothesis_2D* hyp)
337 SetDefaultParameters();
340 //================================================================================
342 * \brief Store a Viscous Layers hypothesis
344 //================================================================================
346 void NETGENPlugin_Mesher::SetParameters(const StdMeshers_ViscousLayers* hyp )
348 _viscousLayersHyp = hyp;
351 //=============================================================================
353 * Link - a pair of integer numbers
355 //=============================================================================
359 Link(int _n1, int _n2) : n1(_n1), n2(_n2) {}
360 Link() : n1(0), n2(0) {}
361 bool Contains( int n ) const { return n == n1 || n == n2; }
362 bool IsConnected( const Link& other ) const
364 return (( Contains( other.n1 ) || Contains( other.n2 )) && ( this != &other ));
368 int HashCode(const Link& aLink, int aLimit)
370 return HashCode(aLink.n1 + aLink.n2, aLimit);
373 Standard_Boolean IsEqual(const Link& aLink1, const Link& aLink2)
375 return (( aLink1.n1 == aLink2.n1 && aLink1.n2 == aLink2.n2 ) ||
376 ( aLink1.n1 == aLink2.n2 && aLink1.n2 == aLink2.n1 ));
381 //================================================================================
383 * \brief return id of netgen point corresponding to SMDS node
385 //================================================================================
386 typedef map< const SMDS_MeshNode*, int > TNode2IdMap;
388 int ngNodeId( const SMDS_MeshNode* node,
389 netgen::Mesh& ngMesh,
390 TNode2IdMap& nodeNgIdMap)
392 int newNgId = ngMesh.GetNP() + 1;
394 TNode2IdMap::iterator node_id = nodeNgIdMap.insert( make_pair( node, newNgId )).first;
396 if ( node_id->second == newNgId)
398 #if defined(DUMP_SEGMENTS) || defined(DUMP_TRIANGLES)
399 cout << "Ng " << newNgId << " - " << node;
401 netgen::MeshPoint p( netgen::Point<3> (node->X(), node->Y(), node->Z()) );
402 ngMesh.AddPoint( p );
404 return node_id->second;
407 //================================================================================
409 * \brief Return computed EDGEs connected to the given one
411 //================================================================================
413 list< TopoDS_Edge > getConnectedEdges( const TopoDS_Edge& edge,
414 const TopoDS_Face& face,
415 const set< SMESH_subMesh* > & computedSM,
416 const SMESH_MesherHelper& helper,
417 map< SMESH_subMesh*, set< int > >& addedEdgeSM2Faces)
420 list< TopoDS_Edge > edges;
421 list< int > nbEdgesInWire;
422 /*int nbWires =*/ SMESH_Block::GetOrderedEdges( face, edges, nbEdgesInWire);
424 // find <edge> within <edges>
425 list< TopoDS_Edge >::iterator eItFwd = edges.begin();
426 for ( ; eItFwd != edges.end(); ++eItFwd )
427 if ( edge.IsSame( *eItFwd ))
429 if ( eItFwd == edges.end()) return list< TopoDS_Edge>();
431 if ( eItFwd->Orientation() >= TopAbs_INTERNAL )
433 // connected INTERNAL edges returned from GetOrderedEdges() are wrongly oriented
434 // so treat each INTERNAL edge separately
435 TopoDS_Edge e = *eItFwd;
437 edges.push_back( e );
441 // get all computed EDGEs connected to <edge>
443 list< TopoDS_Edge >::iterator eItBack = eItFwd, ePrev;
444 TopoDS_Vertex vCommon;
445 TopTools_MapOfShape eAdded; // map used not to add a seam edge twice to <edges>
448 // put edges before <edge> to <edges> back
449 while ( edges.begin() != eItFwd )
450 edges.splice( edges.end(), edges, edges.begin() );
454 while ( ++eItFwd != edges.end() )
456 SMESH_subMesh* sm = helper.GetMesh()->GetSubMesh( *eItFwd );
458 bool connected = TopExp::CommonVertex( *ePrev, *eItFwd, vCommon );
459 bool computed = sm->IsMeshComputed();
460 bool added = addedEdgeSM2Faces[ sm ].count( helper.GetSubShapeID() );
461 bool doubled = !eAdded.Add( *eItFwd );
462 bool orientOK = (( ePrev ->Orientation() < TopAbs_INTERNAL ) ==
463 ( eItFwd->Orientation() < TopAbs_INTERNAL ) );
464 if ( !connected || !computed || !orientOK || added || doubled )
466 // stop advancement; move edges from tail to head
467 while ( edges.back() != *ePrev )
468 edges.splice( edges.begin(), edges, --edges.end() );
474 while ( eItBack != edges.begin() )
478 SMESH_subMesh* sm = helper.GetMesh()->GetSubMesh( *eItBack );
480 bool connected = TopExp::CommonVertex( *ePrev, *eItBack, vCommon );
481 bool computed = sm->IsMeshComputed();
482 bool added = addedEdgeSM2Faces[ sm ].count( helper.GetSubShapeID() );
483 bool doubled = !eAdded.Add( *eItBack );
484 bool orientOK = (( ePrev ->Orientation() < TopAbs_INTERNAL ) ==
485 ( eItBack->Orientation() < TopAbs_INTERNAL ) );
486 if ( !connected || !computed || !orientOK || added || doubled)
489 edges.erase( edges.begin(), ePrev );
493 if ( edges.front() != edges.back() )
495 // assure that the 1st vertex is meshed
496 TopoDS_Edge eLast = edges.back();
497 while ( !SMESH_Algo::VertexNode( SMESH_MesherHelper::IthVertex( 0, edges.front()), helper.GetMeshDS())
499 edges.front() != eLast )
500 edges.splice( edges.end(), edges, edges.begin() );
505 //================================================================================
507 * \brief Make triangulation of a shape precise enough
509 //================================================================================
511 void updateTriangulation( const TopoDS_Shape& shape )
513 // static set< Poly_Triangulation* > updated;
515 // TopLoc_Location loc;
516 // TopExp_Explorer fExp( shape, TopAbs_FACE );
517 // for ( ; fExp.More(); fExp.Next() )
519 // Handle(Poly_Triangulation) triangulation =
520 // BRep_Tool::Triangulation ( TopoDS::Face( fExp.Current() ), loc);
521 // if ( triangulation.IsNull() ||
522 // updated.insert( triangulation.operator->() ).second )
524 // BRepTools::Clean (shape);
527 BRepMesh_IncrementalMesh e(shape, 0.01, true);
529 catch (Standard_Failure)
532 // updated.erase( triangulation.operator->() );
533 // triangulation = BRep_Tool::Triangulation ( TopoDS::Face( fExp.Current() ), loc);
534 // updated.insert( triangulation.operator->() );
538 //================================================================================
540 * \brief Returns a medium node either existing in SMESH of created by NETGEN
541 * \param [in] corner1 - corner node 1
542 * \param [in] corner2 - corner node 2
543 * \param [in] defaultMedium - the node created by NETGEN
544 * \param [in] helper - holder of medium nodes existing in SMESH
545 * \return const SMDS_MeshNode* - the result node
547 //================================================================================
549 const SMDS_MeshNode* mediumNode( const SMDS_MeshNode* corner1,
550 const SMDS_MeshNode* corner2,
551 const SMDS_MeshNode* defaultMedium,
552 const SMESH_MesherHelper* helper)
556 TLinkNodeMap::const_iterator l2n =
557 helper->GetTLinkNodeMap().find( SMESH_TLink( corner1, corner2 ));
558 if ( l2n != helper->GetTLinkNodeMap().end() )
559 defaultMedium = l2n->second;
561 return defaultMedium;
564 //================================================================================
566 * \brief Assure that mesh on given shapes is quadratic
568 //================================================================================
570 // void makeQuadratic( const TopTools_IndexedMapOfShape& shapes,
571 // SMESH_Mesh* mesh )
573 // for ( int i = 1; i <= shapes.Extent(); ++i )
575 // SMESHDS_SubMesh* smDS = mesh->GetMeshDS()->MeshElements( shapes(i) );
576 // if ( !smDS ) continue;
577 // SMDS_ElemIteratorPtr elemIt = smDS->GetElements();
578 // if ( !elemIt->more() ) continue;
579 // const SMDS_MeshElement* e = elemIt->next();
580 // if ( !e || e->IsQuadratic() )
583 // TIDSortedElemSet elems;
584 // elems.insert( e );
585 // while ( elemIt->more() )
586 // elems.insert( elems.end(), elemIt->next() );
588 // SMESH_MeshEditor( mesh ).ConvertToQuadratic( /*3d=*/false, elems, /*biQuad=*/false );
592 //================================================================================
594 * \brief Restrict size of elements on the given edge
596 //================================================================================
598 void setLocalSize(const TopoDS_Edge& edge,
602 if ( size <= std::numeric_limits<double>::min() )
604 Standard_Real u1, u2;
605 Handle(Geom_Curve) curve = BRep_Tool::Curve(edge, u1, u2);
606 if ( curve.IsNull() )
608 TopoDS_Iterator vIt( edge );
609 if ( !vIt.More() ) return;
610 gp_Pnt p = BRep_Tool::Pnt( TopoDS::Vertex( vIt.Value() ));
611 NETGENPlugin_Mesher::RestrictLocalSize( mesh, p.XYZ(), size );
615 const int nb = (int)( 1.5 * SMESH_Algo::EdgeLength( edge ) / size );
616 Standard_Real delta = (u2-u1)/nb;
617 for(int i=0; i<nb; i++)
619 Standard_Real u = u1 + delta*i;
620 gp_Pnt p = curve->Value(u);
621 NETGENPlugin_Mesher::RestrictLocalSize( mesh, p.XYZ(), size );
622 netgen::Point3d pi(p.X(), p.Y(), p.Z());
623 double resultSize = mesh.GetH(pi);
624 if ( resultSize - size > 0.1*size )
625 // netgen does restriction iff oldH/newH > 1.2 (localh.cpp:136)
626 NETGENPlugin_Mesher::RestrictLocalSize( mesh, p.XYZ(), resultSize/1.201 );
632 //================================================================================
634 * \brief Set local size on shapes defined by SetParameters()
636 //================================================================================
638 void NETGENPlugin_Mesher::SetLocalSize( netgen::OCCGeometry& occgeo,
639 netgen::Mesh& ngMesh )
641 for(std::map<int,double>::const_iterator it=EdgeId2LocalSize.begin(); it!=EdgeId2LocalSize.end(); it++)
643 int key = (*it).first;
644 double hi = (*it).second;
645 const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
646 setLocalSize( TopoDS::Edge(shape), hi, ngMesh );
648 for(std::map<int,double>::const_iterator it=VertexId2LocalSize.begin(); it!=VertexId2LocalSize.end(); it++)
650 int key = (*it).first;
651 double hi = (*it).second;
652 const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
653 gp_Pnt p = BRep_Tool::Pnt( TopoDS::Vertex(shape) );
654 NETGENPlugin_Mesher::RestrictLocalSize( ngMesh, p.XYZ(), hi );
656 for(map<int,double>::const_iterator it=FaceId2LocalSize.begin(); it!=FaceId2LocalSize.end(); it++)
658 int key = (*it).first;
659 double val = (*it).second;
660 const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
661 int faceNgID = occgeo.fmap.FindIndex(shape);
664 occgeo.SetFaceMaxH(faceNgID, val);
665 for ( TopExp_Explorer edgeExp( shape, TopAbs_EDGE ); edgeExp.More(); edgeExp.Next() )
666 setLocalSize( TopoDS::Edge( edgeExp.Current() ), val, ngMesh );
668 else if ( !ShapesWithControlPoints.count( key ))
670 SMESHUtils::createPointsSampleFromFace( TopoDS::Face( shape ), val, ControlPoints );
671 ShapesWithControlPoints.insert( key );
674 for(map<int,double>::const_iterator it=SolidId2LocalSize.begin(); it!=SolidId2LocalSize.end(); it++)
676 int key = (*it).first;
677 double val = (*it).second;
678 if ( !ShapesWithControlPoints.count( key ))
680 const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
681 SMESHUtils::createPointsSampleFromSolid( TopoDS::Solid( shape ), val, ControlPoints );
682 ShapesWithControlPoints.insert( key );
686 if ( !ControlPoints.empty() )
688 for ( size_t i = 0; i < ControlPoints.size(); ++i )
689 NETGENPlugin_Mesher::RestrictLocalSize( ngMesh, ControlPoints[i].XYZ(), ControlPoints[i].Size() );
693 //================================================================================
695 * \brief Initialize netgen::OCCGeometry with OCCT shape
697 //================================================================================
699 void NETGENPlugin_Mesher::PrepareOCCgeometry(netgen::OCCGeometry& occgeo,
700 const TopoDS_Shape& shape,
702 list< SMESH_subMesh* > * meshedSM,
703 NETGENPlugin_Internals* intern)
705 updateTriangulation( shape );
708 BRepBndLib::Add (shape, bb);
709 double x1,y1,z1,x2,y2,z2;
710 bb.Get (x1,y1,z1,x2,y2,z2);
711 netgen::Point<3> p1 = netgen::Point<3> (x1,y1,z1);
712 netgen::Point<3> p2 = netgen::Point<3> (x2,y2,z2);
713 occgeo.boundingbox = netgen::Box<3> (p1,p2);
715 occgeo.shape = shape;
718 // fill maps of shapes of occgeo with not yet meshed subshapes
720 // get root submeshes
721 list< SMESH_subMesh* > rootSM;
722 const int shapeID = mesh.GetMeshDS()->ShapeToIndex( shape );
723 if ( shapeID > 0 ) { // SMESH_subMesh with ID 0 may exist, don't use it!
724 rootSM.push_back( mesh.GetSubMesh( shape ));
727 for ( TopoDS_Iterator it( shape ); it.More(); it.Next() )
728 rootSM.push_back( mesh.GetSubMesh( it.Value() ));
733 // add subshapes of empty submeshes
734 list< SMESH_subMesh* >::iterator rootIt = rootSM.begin(), rootEnd = rootSM.end();
735 for ( ; rootIt != rootEnd; ++rootIt ) {
736 SMESH_subMesh * root = *rootIt;
737 SMESH_subMeshIteratorPtr smIt = root->getDependsOnIterator(/*includeSelf=*/true,
738 /*complexShapeFirst=*/true);
739 // to find a right orientation of subshapes (PAL20462)
740 TopTools_IndexedMapOfShape subShapes;
741 TopExp::MapShapes(root->GetSubShape(), subShapes);
742 while ( smIt->more() )
744 SMESH_subMesh* sm = smIt->next();
745 TopoDS_Shape shape = sm->GetSubShape();
746 totNbFaces += ( shape.ShapeType() == TopAbs_FACE );
747 if ( intern && intern->isShapeToPrecompute( shape ))
749 if ( !meshedSM || sm->IsEmpty() )
751 if ( shape.ShapeType() != TopAbs_VERTEX )
752 shape = subShapes( subShapes.FindIndex( shape ));// shape -> index -> oriented shape
753 if ( shape.Orientation() >= TopAbs_INTERNAL )
754 shape.Orientation( TopAbs_FORWARD ); // isuue 0020676
755 switch ( shape.ShapeType() ) {
756 case TopAbs_FACE : occgeo.fmap.Add( shape ); break;
757 case TopAbs_EDGE : occgeo.emap.Add( shape ); break;
758 case TopAbs_VERTEX: occgeo.vmap.Add( shape ); break;
759 case TopAbs_SOLID :occgeo.somap.Add( shape ); break;
763 // collect submeshes of meshed shapes
766 const int dim = SMESH_Gen::GetShapeDim( shape );
767 meshedSM[ dim ].push_back( sm );
771 occgeo.facemeshstatus.SetSize (totNbFaces);
772 occgeo.facemeshstatus = 0;
773 occgeo.face_maxh_modified.SetSize(totNbFaces);
774 occgeo.face_maxh_modified = 0;
775 occgeo.face_maxh.SetSize(totNbFaces);
776 occgeo.face_maxh = netgen::mparam.maxh;
779 //================================================================================
781 * \brief Return a default min size value suitable for the given geometry.
783 //================================================================================
785 double NETGENPlugin_Mesher::GetDefaultMinSize(const TopoDS_Shape& geom,
786 const double maxSize)
788 updateTriangulation( geom );
792 const int* pi[4] = { &i1, &i2, &i3, &i1 };
795 TopExp_Explorer fExp( geom, TopAbs_FACE );
796 for ( ; fExp.More(); fExp.Next() )
798 Handle(Poly_Triangulation) triangulation =
799 BRep_Tool::Triangulation ( TopoDS::Face( fExp.Current() ), loc);
800 if ( triangulation.IsNull() ) continue;
801 const double fTol = BRep_Tool::Tolerance( TopoDS::Face( fExp.Current() ));
802 const TColgp_Array1OfPnt& points = triangulation->Nodes();
803 const Poly_Array1OfTriangle& trias = triangulation->Triangles();
804 for ( int iT = trias.Lower(); iT <= trias.Upper(); ++iT )
806 trias(iT).Get( i1, i2, i3 );
807 for ( int j = 0; j < 3; ++j )
809 double dist2 = points(*pi[j]).SquareDistance( points( *pi[j+1] ));
810 if ( dist2 < minh && fTol*fTol < dist2 )
812 bb.Add( points(*pi[j]));
816 if ( minh > 0.25 * bb.SquareExtent() ) // simple geometry, rough triangulation
818 minh = 1e-3 * sqrt( bb.SquareExtent());
819 //cout << "BND BOX minh = " <<minh << endl;
823 minh = sqrt( minh ); // triangulation for visualization is rather fine
824 //cout << "TRIANGULATION minh = " <<minh << endl;
826 if ( minh > 0.5 * maxSize )
832 //================================================================================
834 * \brief Restrict size of elements at a given point
836 //================================================================================
838 void NETGENPlugin_Mesher::RestrictLocalSize(netgen::Mesh& ngMesh,
841 const bool overrideMinH)
843 if ( size <= std::numeric_limits<double>::min() )
845 if ( netgen::mparam.minh > size )
849 ngMesh.SetMinimalH( size );
850 netgen::mparam.minh = size;
854 size = netgen::mparam.minh;
857 netgen::Point3d pi(p.X(), p.Y(), p.Z());
858 ngMesh.RestrictLocalH( pi, size );
861 //================================================================================
863 * \brief fill ngMesh with nodes and elements of computed submeshes
865 //================================================================================
867 bool NETGENPlugin_Mesher::FillNgMesh(netgen::OCCGeometry& occgeom,
868 netgen::Mesh& ngMesh,
869 vector<const SMDS_MeshNode*>& nodeVec,
870 const list< SMESH_subMesh* > & meshedSM,
871 SMESH_MesherHelper* quadHelper,
872 SMESH_ProxyMesh::Ptr proxyMesh)
874 TNode2IdMap nodeNgIdMap;
875 for ( size_t i = 1; i < nodeVec.size(); ++i )
876 nodeNgIdMap.insert( make_pair( nodeVec[i], i ));
878 TopTools_MapOfShape visitedShapes;
879 map< SMESH_subMesh*, set< int > > visitedEdgeSM2Faces;
880 set< SMESH_subMesh* > computedSM( meshedSM.begin(), meshedSM.end() );
882 SMESH_MesherHelper helper (*_mesh);
884 int faceNgID = ngMesh.GetNFD();
886 list< SMESH_subMesh* >::const_iterator smIt, smEnd = meshedSM.end();
887 for ( smIt = meshedSM.begin(); smIt != smEnd; ++smIt )
889 SMESH_subMesh* sm = *smIt;
890 if ( !visitedShapes.Add( sm->GetSubShape() ))
893 const SMESHDS_SubMesh * smDS = sm->GetSubMeshDS();
894 if ( !smDS ) continue;
896 switch ( sm->GetSubShape().ShapeType() )
898 case TopAbs_EDGE: { // EDGE
899 // ----------------------
900 TopoDS_Edge geomEdge = TopoDS::Edge( sm->GetSubShape() );
901 if ( geomEdge.Orientation() >= TopAbs_INTERNAL )
902 geomEdge.Orientation( TopAbs_FORWARD ); // issue 0020676
904 // Add ng segments for each not meshed FACE the EDGE bounds
905 PShapeIteratorPtr fIt = helper.GetAncestors( geomEdge, *sm->GetFather(), TopAbs_FACE );
906 while ( const TopoDS_Shape * anc = fIt->next() )
908 faceNgID = occgeom.fmap.FindIndex( *anc );
910 continue; // meshed face
912 int faceSMDSId = helper.GetMeshDS()->ShapeToIndex( *anc );
913 if ( visitedEdgeSM2Faces[ sm ].count( faceSMDSId ))
914 continue; // already treated EDGE
916 TopoDS_Face face = TopoDS::Face( occgeom.fmap( faceNgID ));
917 if ( face.Orientation() >= TopAbs_INTERNAL )
918 face.Orientation( TopAbs_FORWARD ); // issue 0020676
920 // get all meshed EDGEs of the FACE connected to geomEdge (issue 0021140)
921 helper.SetSubShape( face );
922 list< TopoDS_Edge > edges = getConnectedEdges( geomEdge, face, computedSM, helper,
923 visitedEdgeSM2Faces );
925 continue; // wrong ancestor?
927 // find out orientation of <edges> within <face>
928 TopoDS_Edge eNotSeam = edges.front();
929 if ( helper.HasSeam() )
931 list< TopoDS_Edge >::iterator eIt = edges.begin();
932 while ( helper.IsRealSeam( *eIt )) ++eIt;
933 if ( eIt != edges.end() )
936 TopAbs_Orientation fOri = helper.GetSubShapeOri( face, eNotSeam );
937 bool isForwad = ( fOri == eNotSeam.Orientation() || fOri >= TopAbs_INTERNAL );
939 // get all nodes from connected <edges>
940 const bool isQuad = smDS->IsQuadratic();
941 StdMeshers_FaceSide fSide( face, edges, _mesh, isForwad, isQuad, &helper );
942 const vector<UVPtStruct>& points = fSide.GetUVPtStruct();
943 if ( points.empty() )
944 return false; // invalid node params?
945 int i, nbSeg = fSide.NbSegments();
947 // remember EDGEs of fSide to treat only once
948 for ( int iE = 0; iE < fSide.NbEdges(); ++iE )
949 visitedEdgeSM2Faces[ helper.GetMesh()->GetSubMesh( fSide.Edge(iE )) ].insert(faceSMDSId);
951 double otherSeamParam = 0;
956 int prevNgId = ngNodeId( points[0].node, ngMesh, nodeNgIdMap );
958 for ( i = 0; i < nbSeg; ++i )
960 const UVPtStruct& p1 = points[ i ];
961 const UVPtStruct& p2 = points[ i+1 ];
963 if ( p1.node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX ) //an EDGE begins
966 if ( helper.IsRealSeam( p1.node->getshapeId() ))
968 TopoDS_Edge e = fSide.Edge( fSide.EdgeIndex( 0.5 * ( p1.normParam + p2.normParam )));
969 isSeam = helper.IsRealSeam( e );
972 otherSeamParam = helper.GetOtherParam( helper.GetPeriodicIndex() & 1 ? p2.u : p2.v );
979 seg[1] = prevNgId = ngNodeId( p2.node, ngMesh, nodeNgIdMap );
980 // node param on curve
981 seg.epgeominfo[ 0 ].dist = p1.param;
982 seg.epgeominfo[ 1 ].dist = p2.param;
984 seg.epgeominfo[ 0 ].u = p1.u;
985 seg.epgeominfo[ 0 ].v = p1.v;
986 seg.epgeominfo[ 1 ].u = p2.u;
987 seg.epgeominfo[ 1 ].v = p2.v;
989 //geomEdge = fSide.Edge( fSide.EdgeIndex( 0.5 * ( p1.normParam + p2.normParam )));
990 //seg.epgeominfo[ 0 ].edgenr = seg.epgeominfo[ 1 ].edgenr = occgeom.emap.FindIndex( geomEdge );
992 //seg.epgeominfo[ iEnd ].edgenr = edgeID; // = geom.emap.FindIndex(edge);
993 seg.si = faceNgID; // = geom.fmap.FindIndex (face);
994 seg.edgenr = ngMesh.GetNSeg() + 1; // segment id
995 ngMesh.AddSegment (seg);
997 SMESH_TNodeXYZ np1( p1.node ), np2( p2.node );
998 RestrictLocalSize( ngMesh, 0.5*(np1+np2), (np1-np2).Modulus() );
1000 #ifdef DUMP_SEGMENTS
1001 cout << "Segment: " << seg.edgenr << " on SMESH face " << helper.GetMeshDS()->ShapeToIndex( face ) << endl
1002 << "\tface index: " << seg.si << endl
1003 << "\tp1: " << seg[0] << endl
1004 << "\tp2: " << seg[1] << endl
1005 << "\tp0 param: " << seg.epgeominfo[ 0 ].dist << endl
1006 << "\tp0 uv: " << seg.epgeominfo[ 0 ].u <<", "<< seg.epgeominfo[ 0 ].v << endl
1007 //<< "\tp0 edge: " << seg.epgeominfo[ 0 ].edgenr << endl
1008 << "\tp1 param: " << seg.epgeominfo[ 1 ].dist << endl
1009 << "\tp1 uv: " << seg.epgeominfo[ 1 ].u <<", "<< seg.epgeominfo[ 1 ].v << endl;
1010 //<< "\tp1 edge: " << seg.epgeominfo[ 1 ].edgenr << endl;
1014 if ( helper.GetPeriodicIndex() && 1 ) {
1015 seg.epgeominfo[ 0 ].u = otherSeamParam;
1016 seg.epgeominfo[ 1 ].u = otherSeamParam;
1017 swap (seg.epgeominfo[0].v, seg.epgeominfo[1].v);
1019 seg.epgeominfo[ 0 ].v = otherSeamParam;
1020 seg.epgeominfo[ 1 ].v = otherSeamParam;
1021 swap (seg.epgeominfo[0].u, seg.epgeominfo[1].u);
1023 swap( seg[0], seg[1] );
1024 swap( seg.epgeominfo[0].dist, seg.epgeominfo[1].dist );
1025 seg.edgenr = ngMesh.GetNSeg() + 1; // segment id
1026 ngMesh.AddSegment( seg );
1027 #ifdef DUMP_SEGMENTS
1028 cout << "Segment: " << seg.edgenr << endl
1029 << "\t is SEAM (reverse) of the previous. "
1030 << " Other " << (helper.GetPeriodicIndex() && 1 ? "U" : "V")
1031 << " = " << otherSeamParam << endl;
1034 else if ( fOri == TopAbs_INTERNAL )
1036 swap( seg[0], seg[1] );
1037 swap( seg.epgeominfo[0], seg.epgeominfo[1] );
1038 seg.edgenr = ngMesh.GetNSeg() + 1; // segment id
1039 ngMesh.AddSegment( seg );
1040 #ifdef DUMP_SEGMENTS
1041 cout << "Segment: " << seg.edgenr << endl << "\t is REVERSE of the previous" << endl;
1045 } // loop on geomEdge ancestors
1047 if ( quadHelper ) // remember medium nodes of sub-meshes
1049 SMDS_ElemIteratorPtr edges = smDS->GetElements();
1050 while ( edges->more() )
1052 const SMDS_MeshElement* e = edges->next();
1053 if ( !quadHelper->AddTLinks( static_cast< const SMDS_MeshEdge*>( e )))
1059 } // case TopAbs_EDGE
1061 case TopAbs_FACE: { // FACE
1062 // ----------------------
1063 const TopoDS_Face& geomFace = TopoDS::Face( sm->GetSubShape() );
1064 helper.SetSubShape( geomFace );
1065 bool isInternalFace = ( geomFace.Orientation() == TopAbs_INTERNAL );
1067 // Find solids the geomFace bounds
1068 int solidID1 = 0, solidID2 = 0;
1070 PShapeIteratorPtr solidIt = helper.GetAncestors( geomFace, *sm->GetFather(), TopAbs_SOLID);
1071 while ( const TopoDS_Shape * solid = solidIt->next() )
1073 int id = occgeom.somap.FindIndex ( *solid );
1074 if ( solidID1 && id != solidID1 ) solidID2 = id;
1078 if ( proxyMesh && proxyMesh->GetProxySubMesh( geomFace ))
1080 // if a proxy sub-mesh contains temporary faces, then these faces
1081 // should be used to mesh only one SOLID
1082 bool hasTmp = false;
1083 smDS = proxyMesh->GetSubMesh( geomFace );
1084 SMDS_ElemIteratorPtr faces = smDS->GetElements();
1085 while ( faces->more() )
1087 const SMDS_MeshElement* f = faces->next();
1088 if ( proxyMesh->IsTemporary( f ))
1091 std::vector<const SMDS_MeshNode*> fNodes( f->begin_nodes(), f->end_nodes() );
1092 std::vector<const SMDS_MeshElement*> vols;
1093 if ( _mesh->GetMeshDS()->GetElementsByNodes( fNodes, vols, SMDSAbs_Volume ) == 1 )
1095 int geomID = vols[0]->getshapeId();
1096 const TopoDS_Shape& solid = helper.GetMeshDS()->IndexToShape( geomID );
1097 if ( !solid.IsNull() )
1098 solidID1 = occgeom.somap.FindIndex ( solid );
1104 // exclude faces generated by NETGEN from computation of 3D mesh
1105 const int fID = occgeom.fmap.FindIndex( geomFace );
1106 if ( !hasTmp ) // shrunk mesh
1108 // move netgen points according to moved nodes
1109 SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/true);
1110 while ( smIt->more() )
1112 SMESH_subMesh* sub = smIt->next();
1113 if ( !sub->GetSubMeshDS() ) continue;
1114 SMDS_NodeIteratorPtr nodeIt = sub->GetSubMeshDS()->GetNodes();
1115 while ( nodeIt->more() )
1117 const SMDS_MeshNode* n = nodeIt->next();
1118 int ngID = ngNodeId( n, ngMesh, nodeNgIdMap );
1119 netgen::MeshPoint& ngPoint = ngMesh.Point( ngID );
1120 ngPoint(0) = n->X();
1121 ngPoint(1) = n->Y();
1122 ngPoint(2) = n->Z();
1125 // remove faces near boundary to avoid their overlapping
1126 // with shrunk faces
1127 for ( int i = 1; i <= ngMesh.GetNSE(); ++i )
1129 const netgen::Element2d& elem = ngMesh.SurfaceElement(i);
1130 if ( elem.GetIndex() == fID )
1132 for ( int iN = 0; iN < elem.GetNP(); ++iN )
1133 if ( ngMesh[ elem[ iN ]].Type() != netgen::SURFACEPOINT )
1135 ngMesh.DeleteSurfaceElement( i );
1144 ngMesh.AddFaceDescriptor( netgen::FaceDescriptor( faceNgID,/*solid1=*/0,/*solid2=*/0,0 ));
1145 for (int i = 1; i <= ngMesh.GetNSE(); ++i )
1147 const netgen::Element2d& elem = ngMesh.SurfaceElement(i);
1148 if ( elem.GetIndex() == fID )
1149 const_cast< netgen::Element2d& >( elem ).SetIndex( faceNgID );
1153 // Add ng face descriptors of meshed faces
1155 ngMesh.AddFaceDescriptor( netgen::FaceDescriptor( faceNgID, solidID1, solidID2, 0 ));
1157 // if second oreder is required, even already meshed faces must be passed to NETGEN
1158 int fID = occgeom.fmap.Add( geomFace );
1159 if ( occgeom.facemeshstatus.Size() < fID ) occgeom.facemeshstatus.SetSize( fID );
1160 occgeom.facemeshstatus[ fID-1 ] = netgen::FACE_MESHED_OK;
1161 while ( fID < faceNgID ) // geomFace is already in occgeom.fmap, add a copy
1163 fID = occgeom.fmap.Add( BRepBuilderAPI_Copy( geomFace, /*copyGeom=*/false ));
1164 if ( occgeom.facemeshstatus.Size() < fID ) occgeom.facemeshstatus.SetSize( fID );
1165 occgeom.facemeshstatus[ fID-1 ] = netgen::FACE_MESHED_OK;
1167 // Problem with the second order in a quadrangular mesh remains.
1168 // 1) All quadrangles generated by NETGEN are moved to an inexistent face
1169 // by FillSMesh() (find "AddFaceDescriptor")
1170 // 2) Temporary triangles generated by StdMeshers_QuadToTriaAdaptor
1171 // are on faces where quadrangles were.
1172 // Due to these 2 points, wrong geom faces are used while conversion to quadratic
1173 // of the mentioned above quadrangles and triangles
1175 // Orient the face correctly in solidID1 (issue 0020206)
1176 bool reverse = false;
1178 TopoDS_Shape solid = occgeom.somap( solidID1 );
1179 TopAbs_Orientation faceOriInSolid = helper.GetSubShapeOri( solid, geomFace );
1180 if ( faceOriInSolid >= 0 )
1182 helper.IsReversedSubMesh( TopoDS::Face( geomFace.Oriented( faceOriInSolid )));
1185 // Add surface elements
1187 netgen::Element2d tri(3);
1188 tri.SetIndex( faceNgID );
1189 SMESH_TNodeXYZ xyz[3];
1191 #ifdef DUMP_TRIANGLES
1192 cout << "SMESH face " << helper.GetMeshDS()->ShapeToIndex( geomFace )
1193 << " internal="<<isInternalFace << endl;
1196 SMDS_ElemIteratorPtr faces = smDS->GetElements();
1197 while ( faces->more() )
1199 const SMDS_MeshElement* f = faces->next();
1200 if ( f->NbNodes() % 3 != 0 ) // not triangle
1202 PShapeIteratorPtr solidIt=helper.GetAncestors(geomFace,*sm->GetFather(),TopAbs_SOLID);
1203 if ( const TopoDS_Shape * solid = solidIt->next() )
1204 sm = _mesh->GetSubMesh( *solid );
1205 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1206 smError.reset( new SMESH_ComputeError(COMPERR_BAD_INPUT_MESH,"Not triangle sub-mesh"));
1207 smError->myBadElements.push_back( f );
1211 for ( int i = 0; i < 3; ++i )
1213 const SMDS_MeshNode* node = f->GetNode( i ), * inFaceNode=0;
1216 // get node UV on face
1217 int shapeID = node->getshapeId();
1218 if ( helper.IsSeamShape( shapeID ))
1220 if ( helper.IsSeamShape( f->GetNodeWrap( i+1 )->getshapeId() ))
1221 inFaceNode = f->GetNodeWrap( i-1 );
1223 inFaceNode = f->GetNodeWrap( i+1 );
1225 gp_XY uv = helper.GetNodeUV( geomFace, node, inFaceNode );
1227 int ind = reverse ? 3-i : i+1;
1228 tri.GeomInfoPi(ind).u = uv.X();
1229 tri.GeomInfoPi(ind).v = uv.Y();
1230 tri.PNum (ind) = ngNodeId( node, ngMesh, nodeNgIdMap );
1233 // pass a triangle size to NG size-map
1234 double size = ( ( xyz[0] - xyz[1] ).Modulus() +
1235 ( xyz[1] - xyz[2] ).Modulus() +
1236 ( xyz[2] - xyz[0] ).Modulus() ) / 3;
1237 gp_XYZ gc = ( xyz[0] + xyz[1] + xyz[2] ) / 3;
1238 RestrictLocalSize( ngMesh, gc, size, /*overrideMinH=*/false );
1240 ngMesh.AddSurfaceElement (tri);
1241 #ifdef DUMP_TRIANGLES
1242 cout << tri << endl;
1245 if ( isInternalFace )
1247 swap( tri[1], tri[2] );
1248 ngMesh.AddSurfaceElement (tri);
1249 #ifdef DUMP_TRIANGLES
1250 cout << tri << endl;
1255 if ( quadHelper ) // remember medium nodes of sub-meshes
1257 SMDS_ElemIteratorPtr faces = smDS->GetElements();
1258 while ( faces->more() )
1260 const SMDS_MeshElement* f = faces->next();
1261 if ( !quadHelper->AddTLinks( static_cast< const SMDS_MeshFace*>( f )))
1267 } // case TopAbs_FACE
1269 case TopAbs_VERTEX: { // VERTEX
1270 // --------------------------
1271 // issue 0021405. Add node only if a VERTEX is shared by a not meshed EDGE,
1272 // else netgen removes a free node and nodeVector becomes invalid
1273 PShapeIteratorPtr ansIt = helper.GetAncestors( sm->GetSubShape(),
1277 while ( const TopoDS_Shape* e = ansIt->next() )
1279 SMESH_subMesh* eSub = helper.GetMesh()->GetSubMesh( *e );
1280 if (( toAdd = ( eSub->IsEmpty() && !SMESH_Algo::isDegenerated( TopoDS::Edge( *e )))))
1285 SMDS_NodeIteratorPtr nodeIt = smDS->GetNodes();
1286 if ( nodeIt->more() )
1287 ngNodeId( nodeIt->next(), ngMesh, nodeNgIdMap );
1293 } // loop on submeshes
1296 nodeVec.resize( ngMesh.GetNP() + 1 );
1297 TNode2IdMap::iterator node_NgId, nodeNgIdEnd = nodeNgIdMap.end();
1298 for ( node_NgId = nodeNgIdMap.begin(); node_NgId != nodeNgIdEnd; ++node_NgId)
1299 nodeVec[ node_NgId->second ] = node_NgId->first;
1304 //================================================================================
1306 * \brief Duplicate mesh faces on internal geom faces
1308 //================================================================================
1310 void NETGENPlugin_Mesher::FixIntFaces(const netgen::OCCGeometry& occgeom,
1311 netgen::Mesh& ngMesh,
1312 NETGENPlugin_Internals& internalShapes)
1314 SMESHDS_Mesh* meshDS = internalShapes.getMesh().GetMeshDS();
1316 // find ng indices of internal faces
1318 for ( int ngFaceID = 1; ngFaceID <= occgeom.fmap.Extent(); ++ngFaceID )
1320 int smeshID = meshDS->ShapeToIndex( occgeom.fmap( ngFaceID ));
1321 if ( internalShapes.isInternalShape( smeshID ))
1322 ngFaceIds.insert( ngFaceID );
1324 if ( !ngFaceIds.empty() )
1327 int i, nbFaces = ngMesh.GetNSE();
1328 for ( i = 1; i <= nbFaces; ++i)
1330 netgen::Element2d elem = ngMesh.SurfaceElement(i);
1331 if ( ngFaceIds.count( elem.GetIndex() ))
1333 swap( elem[1], elem[2] );
1334 ngMesh.AddSurfaceElement (elem);
1340 //================================================================================
1342 * \brief Tries to heal the mesh on a FACE. The FACE is supposed to be partially
1343 * meshed due to NETGEN failure
1344 * \param [in] occgeom - geometry
1345 * \param [in,out] ngMesh - the mesh to fix
1346 * \param [inout] faceID - ID of the FACE to fix the mesh on
1347 * \return bool - is mesh is or becomes OK
1349 //================================================================================
1351 bool NETGENPlugin_Mesher::FixFaceMesh(const netgen::OCCGeometry& occgeom,
1352 netgen::Mesh& ngMesh,
1355 // we address a case where the FACE is almost fully meshed except small holes
1356 // of usually triangular shape at FACE boundary (IPAL52861)
1358 // The case appeared to be not simple: holes only look triangular but
1359 // indeed are a self intersecting polygon. A reason of the bug was in coincident
1360 // NG points on a seam edge. But the code below is very nice, leave it for
1365 if ( occgeom.fmap.Extent() < faceID )
1367 //const TopoDS_Face& face = TopoDS::Face( occgeom.fmap( faceID ));
1369 // find free links on the FACE
1370 NCollection_Map<Link> linkMap;
1371 for ( int iF = 1; iF <= ngMesh.GetNSE(); ++iF )
1373 const netgen::Element2d& elem = ngMesh.SurfaceElement(iF);
1374 if ( faceID != elem.GetIndex() )
1376 int n0 = elem[ elem.GetNP() - 1 ];
1377 for ( int i = 0; i < elem.GetNP(); ++i )
1380 Link link( n0, n1 );
1381 if ( !linkMap.Add( link ))
1382 linkMap.Remove( link );
1386 // add/remove boundary links
1387 for ( int iSeg = 1; iSeg <= ngMesh.GetNSeg(); ++iSeg )
1389 const netgen::Segment& seg = ngMesh.LineSegment( iSeg );
1390 if ( seg.si != faceID ) // !edgeIDs.Contains( seg.edgenr ))
1392 Link link( seg[1], seg[0] ); // reverse!!!
1393 if ( !linkMap.Add( link ))
1394 linkMap.Remove( link );
1396 if ( linkMap.IsEmpty() )
1398 if ( linkMap.Extent() < 3 )
1401 // make triangles of the links
1403 netgen::Element2d tri(3);
1404 tri.SetIndex ( faceID );
1406 NCollection_Map<Link>::Iterator linkIt( linkMap );
1407 Link link1 = linkIt.Value();
1408 // look for a link connected to link1
1409 NCollection_Map<Link>::Iterator linkIt2 = linkIt;
1410 for ( linkIt2.Next(); linkIt2.More(); linkIt2.Next() )
1412 const Link& link2 = linkIt2.Value();
1413 if ( link2.IsConnected( link1 ))
1415 // look for a link connected to both link1 and link2
1416 NCollection_Map<Link>::Iterator linkIt3 = linkIt2;
1417 for ( linkIt3.Next(); linkIt3.More(); linkIt3.Next() )
1419 const Link& link3 = linkIt3.Value();
1420 if ( link3.IsConnected( link1 ) &&
1421 link3.IsConnected( link2 ) )
1426 tri[2] = ( link2.Contains( link1.n1 ) ? link2.n1 : link3.n1 );
1427 if ( tri[0] == tri[2] || tri[1] == tri[2] )
1429 ngMesh.AddSurfaceElement( tri );
1431 // prepare for the next tria search
1432 if ( linkMap.Extent() == 3 )
1434 linkMap.Remove( link3 );
1435 linkMap.Remove( link2 );
1437 linkMap.Remove( link1 );
1438 link1 = linkIt.Value();
1451 //================================================================================
1452 // define gp_XY_Subtracted pointer to function calling gp_XY::Subtracted(gp_XY)
1453 gp_XY_FunPtr(Subtracted);
1454 //gp_XY_FunPtr(Added);
1456 //================================================================================
1458 * \brief Evaluate distance between two 2d points along the surface
1460 //================================================================================
1462 double evalDist( const gp_XY& uv1,
1464 const Handle(Geom_Surface)& surf,
1465 const int stopHandler=-1)
1467 if ( stopHandler > 0 ) // continue recursion
1469 gp_XY mid = SMESH_MesherHelper::GetMiddleUV( surf, uv1, uv2 );
1470 return evalDist( uv1,mid, surf, stopHandler-1 ) + evalDist( mid,uv2, surf, stopHandler-1 );
1472 double dist3D = surf->Value( uv1.X(), uv1.Y() ).Distance( surf->Value( uv2.X(), uv2.Y() ));
1473 if ( stopHandler == 0 ) // stop recursion
1476 // start recursion if necessary
1477 double dist2D = SMESH_MesherHelper::ApplyIn2D(surf, uv1, uv2, gp_XY_Subtracted, 0).Modulus();
1478 if ( fabs( dist3D - dist2D ) < dist2D * 1e-10 )
1479 return dist3D; // equal parametrization of a planar surface
1481 return evalDist( uv1, uv2, surf, 3 ); // start recursion
1484 //================================================================================
1486 * \brief Data of vertex internal in geom face
1488 //================================================================================
1492 gp_XY uv; //!< UV in face parametric space
1493 int ngId; //!< ng id of corrsponding node
1494 gp_XY uvClose; //!< UV of closest boundary node
1495 int ngIdClose; //!< ng id of closest boundary node
1498 //================================================================================
1500 * \brief Data of vertex internal in solid
1502 //================================================================================
1506 int ngId; //!< ng id of corresponding node
1507 int ngIdClose; //!< ng id of closest 2d mesh element
1508 int ngIdCloseN; //!< ng id of closest node of the closest 2d mesh element
1511 inline double dist2( const netgen::MeshPoint& p1, const netgen::MeshPoint& p2 )
1513 return gp_Pnt( NGPOINT_COORDS(p1)).SquareDistance( gp_Pnt( NGPOINT_COORDS(p2)));
1516 // inline double dist2(const netgen::MeshPoint& p, const SMDS_MeshNode* n )
1518 // return gp_Pnt( NGPOINT_COORDS(p)).SquareDistance( SMESH_NodeXYZ(n));
1522 //================================================================================
1524 * \brief Make netgen take internal vertices in faces into account by adding
1525 * segments including internal vertices
1527 * This function works in supposition that 1D mesh is already computed in ngMesh
1529 //================================================================================
1531 void NETGENPlugin_Mesher::AddIntVerticesInFaces(const netgen::OCCGeometry& occgeom,
1532 netgen::Mesh& ngMesh,
1533 vector<const SMDS_MeshNode*>& nodeVec,
1534 NETGENPlugin_Internals& internalShapes)
1536 if ((int) nodeVec.size() < ngMesh.GetNP() )
1537 nodeVec.resize( ngMesh.GetNP(), 0 );
1539 SMESHDS_Mesh* meshDS = internalShapes.getMesh().GetMeshDS();
1540 SMESH_MesherHelper helper( internalShapes.getMesh() );
1542 const map<int,list<int> >& face2Vert = internalShapes.getFacesWithVertices();
1543 map<int,list<int> >::const_iterator f2v = face2Vert.begin();
1544 for ( ; f2v != face2Vert.end(); ++f2v )
1546 const TopoDS_Face& face = TopoDS::Face( meshDS->IndexToShape( f2v->first ));
1547 if ( face.IsNull() ) continue;
1548 int faceNgID = occgeom.fmap.FindIndex (face);
1549 if ( faceNgID < 0 ) continue;
1551 TopLoc_Location loc;
1552 Handle(Geom_Surface) surf = BRep_Tool::Surface(face,loc);
1554 helper.SetSubShape( face );
1555 helper.SetElementsOnShape( true );
1557 // Get data of internal vertices and add them to ngMesh
1559 multimap< double, TIntVData > dist2VData; // sort vertices by distance from boundary nodes
1561 int i, nbSegInit = ngMesh.GetNSeg();
1563 // boundary characteristics
1564 double totSegLen2D = 0;
1567 const list<int>& iVertices = f2v->second;
1568 list<int>::const_iterator iv = iVertices.begin();
1569 for ( int nbV = 0; iv != iVertices.end(); ++iv, nbV++ )
1572 // get node on vertex
1573 const TopoDS_Vertex V = TopoDS::Vertex( meshDS->IndexToShape( *iv ));
1574 const SMDS_MeshNode * nV = SMESH_Algo::VertexNode( V, meshDS );
1577 SMESH_subMesh* sm = helper.GetMesh()->GetSubMesh( V );
1578 sm->ComputeStateEngine( SMESH_subMesh::COMPUTE );
1579 nV = SMESH_Algo::VertexNode( V, meshDS );
1580 if ( !nV ) continue;
1583 netgen::MeshPoint mp( netgen::Point<3> (nV->X(), nV->Y(), nV->Z()) );
1584 ngMesh.AddPoint ( mp, 1, netgen::EDGEPOINT );
1585 vData.ngId = ngMesh.GetNP();
1586 nodeVec.push_back( nV );
1590 vData.uv = helper.GetNodeUV( face, nV, 0, &uvOK );
1591 if ( !uvOK ) helper.CheckNodeUV( face, nV, vData.uv, BRep_Tool::Tolerance(V),/*force=*/1);
1593 // loop on all segments of the face to find the node closest to vertex and to count
1594 // average segment 2d length
1595 double closeDist2 = numeric_limits<double>::max(), dist2;
1597 for (i = 1; i <= ngMesh.GetNSeg(); ++i)
1599 netgen::Segment & seg = ngMesh.LineSegment(i);
1600 if ( seg.si != faceNgID ) continue;
1602 for ( int iEnd = 0; iEnd < 2; ++iEnd)
1604 uv[iEnd].SetCoord( seg.epgeominfo[iEnd].u, seg.epgeominfo[iEnd].v );
1605 if ( ngIdLast == seg[ iEnd ] ) continue;
1606 dist2 = helper.ApplyIn2D(surf, uv[iEnd], vData.uv, gp_XY_Subtracted,0).SquareModulus();
1607 if ( dist2 < closeDist2 )
1608 vData.ngIdClose = seg[ iEnd ], vData.uvClose = uv[iEnd], closeDist2 = dist2;
1609 ngIdLast = seg[ iEnd ];
1613 totSegLen2D += helper.ApplyIn2D(surf, uv[0], uv[1], gp_XY_Subtracted, false).Modulus();
1617 dist2VData.insert( make_pair( closeDist2, vData ));
1620 if ( totNbSeg == 0 ) break;
1621 double avgSegLen2d = totSegLen2D / totNbSeg;
1623 // Loop on vertices to add segments
1625 multimap< double, TIntVData >::iterator dist_vData = dist2VData.begin();
1626 for ( ; dist_vData != dist2VData.end(); ++dist_vData )
1628 double closeDist2 = dist_vData->first, dist2;
1629 TIntVData & vData = dist_vData->second;
1631 // try to find more close node among segments added for internal vertices
1632 for (i = nbSegInit+1; i <= ngMesh.GetNSeg(); ++i)
1634 netgen::Segment & seg = ngMesh.LineSegment(i);
1635 if ( seg.si != faceNgID ) continue;
1637 for ( int iEnd = 0; iEnd < 2; ++iEnd)
1639 uv[iEnd].SetCoord( seg.epgeominfo[iEnd].u, seg.epgeominfo[iEnd].v );
1640 dist2 = helper.ApplyIn2D(surf, uv[iEnd], vData.uv, gp_XY_Subtracted,0).SquareModulus();
1641 if ( dist2 < closeDist2 )
1642 vData.ngIdClose = seg[ iEnd ], vData.uvClose = uv[iEnd], closeDist2 = dist2;
1645 // decide whether to use the closest node as the second end of segment or to
1646 // create a new point
1647 int segEnd1 = vData.ngId;
1648 int segEnd2 = vData.ngIdClose; // to use closest node
1649 gp_XY uvV = vData.uv, uvP = vData.uvClose;
1650 double segLenHint = ngMesh.GetH( ngMesh.Point( vData.ngId ));
1651 double nodeDist2D = sqrt( closeDist2 );
1652 double nodeDist3D = evalDist( vData.uv, vData.uvClose, surf );
1653 bool avgLenOK = ( avgSegLen2d < 0.75 * nodeDist2D );
1654 bool hintLenOK = ( segLenHint < 0.75 * nodeDist3D );
1655 //cout << "uvV " << uvV.X() <<","<<uvV.Y() << " ";
1656 if ( hintLenOK || avgLenOK )
1658 // create a point between the closest node and V
1661 double r = min( 0.5, ( hintLenOK ? segLenHint/nodeDist3D : avgSegLen2d/nodeDist2D ));
1662 // direction from V to closet node in 2D
1663 gp_Dir2d v2n( helper.ApplyIn2D(surf, uvP, uvV, gp_XY_Subtracted, false ));
1665 uvP = vData.uv + r * nodeDist2D * v2n.XY();
1666 gp_Pnt P = surf->Value( uvP.X(), uvP.Y() ).Transformed( loc );
1668 netgen::MeshPoint mp( netgen::Point<3> (P.X(), P.Y(), P.Z()));
1669 ngMesh.AddPoint ( mp, 1, netgen::EDGEPOINT );
1670 segEnd2 = ngMesh.GetNP();
1671 //cout << "Middle " << r << " uv " << uvP.X() << "," << uvP.Y() << "( " << ngMesh.Point(segEnd2).X()<<","<<ngMesh.Point(segEnd2).Y()<<","<<ngMesh.Point(segEnd2).Z()<<" )"<< endl;
1672 SMDS_MeshNode * nP = helper.AddNode(P.X(), P.Y(), P.Z());
1673 nodeVec.push_back( nP );
1675 //else cout << "at Node " << " uv " << uvP.X() << "," << uvP.Y() << endl;
1678 netgen::Segment seg;
1680 if ( segEnd1 > segEnd2 ) swap( segEnd1, segEnd2 ), swap( uvV, uvP );
1681 seg[0] = segEnd1; // ng node id
1682 seg[1] = segEnd2; // ng node id
1683 seg.edgenr = ngMesh.GetNSeg() + 1;// segment id
1686 seg.epgeominfo[ 0 ].dist = 0; // param on curve
1687 seg.epgeominfo[ 0 ].u = uvV.X();
1688 seg.epgeominfo[ 0 ].v = uvV.Y();
1689 seg.epgeominfo[ 1 ].dist = 1; // param on curve
1690 seg.epgeominfo[ 1 ].u = uvP.X();
1691 seg.epgeominfo[ 1 ].v = uvP.Y();
1693 // seg.epgeominfo[ 0 ].edgenr = 10; // = geom.emap.FindIndex(edge);
1694 // seg.epgeominfo[ 1 ].edgenr = 10; // = geom.emap.FindIndex(edge);
1696 ngMesh.AddSegment (seg);
1698 // add reverse segment
1699 swap( seg[0], seg[1] );
1700 swap( seg.epgeominfo[0], seg.epgeominfo[1] );
1701 seg.edgenr = ngMesh.GetNSeg() + 1; // segment id
1702 ngMesh.AddSegment (seg);
1708 //================================================================================
1710 * \brief Make netgen take internal vertices in solids into account by adding
1711 * faces including internal vertices
1713 * This function works in supposition that 2D mesh is already computed in ngMesh
1715 //================================================================================
1717 void NETGENPlugin_Mesher::AddIntVerticesInSolids(const netgen::OCCGeometry& occgeom,
1718 netgen::Mesh& ngMesh,
1719 vector<const SMDS_MeshNode*>& nodeVec,
1720 NETGENPlugin_Internals& internalShapes)
1722 #ifdef DUMP_TRIANGLES_SCRIPT
1723 // create a python script making a mesh containing triangles added for internal vertices
1724 ofstream py(DUMP_TRIANGLES_SCRIPT);
1725 py << "import SMESH"<< endl
1726 << "from salome.smesh import smeshBuilder"<<endl
1727 << "smesh = smeshBuilder.New(salome.myStudy)"<<endl
1728 << "m = smesh.Mesh(name='triangles')" << endl;
1730 if ((int) nodeVec.size() < ngMesh.GetNP() )
1731 nodeVec.resize( ngMesh.GetNP(), 0 );
1733 SMESHDS_Mesh* meshDS = internalShapes.getMesh().GetMeshDS();
1734 SMESH_MesherHelper helper( internalShapes.getMesh() );
1736 const map<int,list<int> >& so2Vert = internalShapes.getSolidsWithVertices();
1737 map<int,list<int> >::const_iterator s2v = so2Vert.begin();
1738 for ( ; s2v != so2Vert.end(); ++s2v )
1740 const TopoDS_Shape& solid = meshDS->IndexToShape( s2v->first );
1741 if ( solid.IsNull() ) continue;
1742 int solidNgID = occgeom.somap.FindIndex (solid);
1743 if ( solidNgID < 0 && !occgeom.somap.IsEmpty() ) continue;
1745 helper.SetSubShape( solid );
1746 helper.SetElementsOnShape( true );
1748 // find ng indices of faces within the solid
1750 for (TopExp_Explorer fExp(solid, TopAbs_FACE); fExp.More(); fExp.Next() )
1751 ngFaceIds.insert( occgeom.fmap.FindIndex( fExp.Current() ));
1752 if ( ngFaceIds.size() == 1 && *ngFaceIds.begin() == 0 )
1753 ngFaceIds.insert( 1 );
1755 // Get data of internal vertices and add them to ngMesh
1757 multimap< double, TIntVSoData > dist2VData; // sort vertices by distance from ng faces
1759 int i, nbFaceInit = ngMesh.GetNSE();
1761 // boundary characteristics
1762 double totSegLen = 0;
1765 const list<int>& iVertices = s2v->second;
1766 list<int>::const_iterator iv = iVertices.begin();
1767 for ( int nbV = 0; iv != iVertices.end(); ++iv, nbV++ )
1770 const TopoDS_Vertex V = TopoDS::Vertex( meshDS->IndexToShape( *iv ));
1772 // get node on vertex
1773 const SMDS_MeshNode * nV = SMESH_Algo::VertexNode( V, meshDS );
1776 SMESH_subMesh* sm = helper.GetMesh()->GetSubMesh( V );
1777 sm->ComputeStateEngine( SMESH_subMesh::COMPUTE );
1778 nV = SMESH_Algo::VertexNode( V, meshDS );
1779 if ( !nV ) continue;
1782 netgen::MeshPoint mpV( netgen::Point<3> (nV->X(), nV->Y(), nV->Z()) );
1783 ngMesh.AddPoint ( mpV, 1, netgen::FIXEDPOINT );
1784 vData.ngId = ngMesh.GetNP();
1785 nodeVec.push_back( nV );
1787 // loop on all 2d elements to find the one closest to vertex and to count
1788 // average segment length
1789 double closeDist2 = numeric_limits<double>::max(), avgDist2;
1790 for (i = 1; i <= ngMesh.GetNSE(); ++i)
1792 const netgen::Element2d& elem = ngMesh.SurfaceElement(i);
1793 if ( !ngFaceIds.count( elem.GetIndex() )) continue;
1795 multimap< double, int> dist2nID; // sort nodes of element by distance from V
1796 for ( int j = 0; j < elem.GetNP(); ++j)
1798 netgen::MeshPoint mp = ngMesh.Point( elem[j] );
1799 double d2 = dist2( mpV, mp );
1800 dist2nID.insert( make_pair( d2, elem[j] ));
1801 avgDist2 += d2 / elem.GetNP();
1803 totNbSeg++, totSegLen+= sqrt( dist2( mp, ngMesh.Point( elem[(j+1)%elem.GetNP()])));
1805 double dist = dist2nID.begin()->first; //avgDist2;
1806 if ( dist < closeDist2 )
1807 vData.ngIdClose= i, vData.ngIdCloseN= dist2nID.begin()->second, closeDist2= dist;
1809 dist2VData.insert( make_pair( closeDist2, vData ));
1812 if ( totNbSeg == 0 ) break;
1813 double avgSegLen = totSegLen / totNbSeg;
1815 // Loop on vertices to add triangles
1817 multimap< double, TIntVSoData >::iterator dist_vData = dist2VData.begin();
1818 for ( ; dist_vData != dist2VData.end(); ++dist_vData )
1820 double closeDist2 = dist_vData->first;
1821 TIntVSoData & vData = dist_vData->second;
1823 const netgen::MeshPoint& mpV = ngMesh.Point( vData.ngId );
1825 // try to find more close face among ones added for internal vertices
1826 for (i = nbFaceInit+1; i <= ngMesh.GetNSE(); ++i)
1828 double avgDist2 = 0;
1829 multimap< double, int> dist2nID;
1830 const netgen::Element2d& elem = ngMesh.SurfaceElement(i);
1831 for ( int j = 0; j < elem.GetNP(); ++j)
1833 double d = dist2( mpV, ngMesh.Point( elem[j] ));
1834 dist2nID.insert( make_pair( d, elem[j] ));
1835 avgDist2 += d / elem.GetNP();
1836 if ( avgDist2 < closeDist2 )
1837 vData.ngIdClose= i, vData.ngIdCloseN= dist2nID.begin()->second, closeDist2= avgDist2;
1840 // sort nodes of the closest face by angle with vector from V to the closest node
1841 const double tol = numeric_limits<double>::min();
1842 map< double, int > angle2ID;
1843 const netgen::Element2d& closeFace = ngMesh.SurfaceElement( vData.ngIdClose );
1844 netgen::MeshPoint mp[2];
1845 mp[0] = ngMesh.Point( vData.ngIdCloseN );
1846 gp_XYZ p1( NGPOINT_COORDS( mp[0] ));
1847 gp_XYZ pV( NGPOINT_COORDS( mpV ));
1848 gp_Vec v2p1( pV, p1 );
1849 double distN1 = v2p1.Magnitude();
1850 if ( distN1 <= tol ) continue;
1852 for ( int j = 0; j < closeFace.GetNP(); ++j)
1854 mp[1] = ngMesh.Point( closeFace[j] );
1855 gp_Vec v2p( pV, gp_Pnt( NGPOINT_COORDS( mp[1] )) );
1856 angle2ID.insert( make_pair( v2p1.Angle( v2p ), closeFace[j]));
1858 // get node with angle of 60 degrees or greater
1859 map< double, int >::iterator angle_id = angle2ID.lower_bound( 60. * M_PI / 180. );
1860 if ( angle_id == angle2ID.end() ) angle_id = --angle2ID.end();
1861 const double minAngle = 30. * M_PI / 180.;
1862 const double angle = angle_id->first;
1863 bool angleOK = ( angle > minAngle );
1865 // find points to create a triangle
1866 netgen::Element2d tri(3);
1868 tri[0] = vData.ngId;
1869 tri[1] = vData.ngIdCloseN; // to use the closest nodes
1870 tri[2] = angle_id->second; // to use the node with best angle
1872 // decide whether to use the closest node and the node with best angle or to create new ones
1873 for ( int isBestAngleN = 0; isBestAngleN < 2; ++isBestAngleN )
1875 bool createNew = !angleOK; //, distOK = true;
1877 int triInd = isBestAngleN ? 2 : 1;
1878 mp[isBestAngleN] = ngMesh.Point( tri[triInd] );
1883 double distN2 = sqrt( dist2( mpV, mp[isBestAngleN]));
1884 createNew = ( fabs( distN2 - distN1 ) > 0.25 * distN1 );
1886 else if ( angle < tol )
1888 v2p1.SetX( v2p1.X() + 1e-3 );
1894 double segLenHint = ngMesh.GetH( ngMesh.Point( vData.ngId ));
1895 bool avgLenOK = ( avgSegLen < 0.75 * distN1 );
1896 bool hintLenOK = ( segLenHint < 0.75 * distN1 );
1897 createNew = (createNew || avgLenOK || hintLenOK );
1898 // we create a new node not closer than 0.5 to the closest face
1899 // in order not to clash with other close face
1900 double r = min( 0.5, ( hintLenOK ? segLenHint : avgSegLen ) / distN1 );
1901 distFromV = r * distN1;
1905 // create a new point, between the node and the vertex if angleOK
1906 gp_XYZ p( NGPOINT_COORDS( mp[isBestAngleN] ));
1907 gp_Vec v2p( pV, p ); v2p.Normalize();
1908 if ( isBestAngleN && !angleOK )
1909 p = p1 + gp_Dir( v2p.XYZ() - v2p1.XYZ()).XYZ() * distN1 * 0.95;
1911 p = pV + v2p.XYZ() * distFromV;
1913 if ( !isBestAngleN ) p1 = p, distN1 = distFromV;
1915 mp[isBestAngleN].SetPoint( netgen::Point<3> (p.X(), p.Y(), p.Z()));
1916 ngMesh.AddPoint ( mp[isBestAngleN], 1, netgen::SURFACEPOINT );
1917 tri[triInd] = ngMesh.GetNP();
1918 nodeVec.push_back( helper.AddNode( p.X(), p.Y(), p.Z()) );
1921 ngMesh.AddSurfaceElement (tri);
1922 swap( tri[1], tri[2] );
1923 ngMesh.AddSurfaceElement (tri);
1925 #ifdef DUMP_TRIANGLES_SCRIPT
1926 py << "n1 = m.AddNode( "<< mpV(0)<<", "<< mpV(1)<<", "<< mpV(2)<<") "<< endl
1927 << "n2 = m.AddNode( "<< mp[0](0)<<", "<< mp[0](1)<<", "<< mp[0](2)<<") "<< endl
1928 << "n3 = m.AddNode( "<< mp[1](0)<<", "<< mp[1](1)<<", "<< mp[1](2)<<" )" << endl
1929 << "m.AddFace([n1,n2,n3])" << endl;
1931 } // loop on internal vertices of a solid
1933 } // loop on solids with internal vertices
1936 //================================================================================
1938 * \brief Fill netgen mesh with segments of a FACE
1939 * \param ngMesh - netgen mesh
1940 * \param geom - container of OCCT geometry to mesh
1941 * \param wires - data of nodes on FACE boundary
1942 * \param helper - mesher helper holding the FACE
1943 * \param nodeVec - vector of nodes in which node index == netgen ID
1944 * \retval SMESH_ComputeErrorPtr - error description
1946 //================================================================================
1948 SMESH_ComputeErrorPtr
1949 NETGENPlugin_Mesher::AddSegmentsToMesh(netgen::Mesh& ngMesh,
1950 netgen::OCCGeometry& geom,
1951 const TSideVector& wires,
1952 SMESH_MesherHelper& helper,
1953 vector< const SMDS_MeshNode* > & nodeVec,
1954 const bool overrideMinH)
1956 // ----------------------------
1957 // Check wires and count nodes
1958 // ----------------------------
1960 for ( size_t iW = 0; iW < wires.size(); ++iW )
1962 StdMeshers_FaceSidePtr wire = wires[ iW ];
1963 if ( wire->MissVertexNode() )
1965 // Commented for issue 0020960. It worked for the case, let's wait for case where it doesn't.
1966 // It seems that there is no reason for this limitation
1968 // (new SMESH_ComputeError(COMPERR_BAD_INPUT_MESH, "Missing nodes on vertices"));
1970 const vector<UVPtStruct>& uvPtVec = wire->GetUVPtStruct();
1971 if ((int) uvPtVec.size() != wire->NbPoints() )
1972 return SMESH_ComputeError::New(COMPERR_BAD_INPUT_MESH,
1973 SMESH_Comment("Unexpected nb of points on wire ") << iW
1974 << ": " << uvPtVec.size()<<" != "<<wire->NbPoints());
1975 nbNodes += wire->NbPoints();
1977 nodeVec.reserve( nodeVec.size() + nbNodes + 1 );
1978 if ( nodeVec.empty() )
1979 nodeVec.push_back( 0 );
1981 // -----------------
1983 // -----------------
1985 const bool wasNgMeshEmpty = ( ngMesh.GetNP() < 1 ); /* true => this method is called by
1986 NETGENPlugin_NETGEN_2D_ONLY */
1988 // map for nodes on vertices since they can be shared between wires
1989 // ( issue 0020676, face_int_box.brep) and nodes built by NETGEN
1990 map<const SMDS_MeshNode*, int > node2ngID;
1991 if ( !wasNgMeshEmpty ) // fill node2ngID with nodes built by NETGEN
1993 set< int > subIDs; // ids of sub-shapes of the FACE
1994 for ( size_t iW = 0; iW < wires.size(); ++iW )
1996 StdMeshers_FaceSidePtr wire = wires[ iW ];
1997 for ( int iE = 0, nbE = wire->NbEdges(); iE < nbE; ++iE )
1999 subIDs.insert( wire->EdgeID( iE ));
2000 subIDs.insert( helper.GetMeshDS()->ShapeToIndex( wire->FirstVertex( iE )));
2003 for ( size_t ngID = 1; ngID < nodeVec.size(); ++ngID )
2004 if ( subIDs.count( nodeVec[ngID]->getshapeId() ))
2005 node2ngID.insert( make_pair( nodeVec[ngID], ngID ));
2008 const int solidID = 0, faceID = geom.fmap.FindIndex( helper.GetSubShape() );
2009 if ( ngMesh.GetNFD() < 1 )
2010 ngMesh.AddFaceDescriptor( netgen::FaceDescriptor( faceID, solidID, solidID, 0 ));
2012 for ( size_t iW = 0; iW < wires.size(); ++iW )
2014 StdMeshers_FaceSidePtr wire = wires[ iW ];
2015 const vector<UVPtStruct>& uvPtVec = wire->GetUVPtStruct();
2016 const int nbSegments = wire->NbPoints() - 1;
2018 // assure the 1st node to be in node2ngID, which is needed to correctly
2019 // "close chain of segments" (see below) in case if the 1st node is not
2020 // onVertex because it is on a Viscous layer
2021 node2ngID.insert( make_pair( uvPtVec[ 0 ].node, ngMesh.GetNP() + 1 ));
2023 // compute length of every segment
2024 vector<double> segLen( nbSegments );
2025 for ( int i = 0; i < nbSegments; ++i )
2026 segLen[i] = SMESH_TNodeXYZ( uvPtVec[ i ].node ).Distance( uvPtVec[ i+1 ].node );
2028 int edgeID = 1, posID = -2;
2029 bool isInternalWire = false;
2030 double vertexNormPar = 0;
2031 const int prevNbNGSeg = ngMesh.GetNSeg();
2032 for ( int i = 0; i < nbSegments; ++i ) // loop on segments
2034 // Add the first point of a segment
2036 const SMDS_MeshNode * n = uvPtVec[ i ].node;
2037 const int posShapeID = n->getshapeId();
2038 bool onVertex = ( n->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX );
2039 bool onEdge = ( n->GetPosition()->GetTypeOfPosition() == SMDS_TOP_EDGE );
2041 // skip nodes on degenerated edges
2042 if ( helper.IsDegenShape( posShapeID ) &&
2043 helper.IsDegenShape( uvPtVec[ i+1 ].node->getshapeId() ))
2046 int ngID1 = ngMesh.GetNP() + 1, ngID2 = ngID1+1;
2047 if ( onVertex || ( !wasNgMeshEmpty && onEdge ) || helper.IsRealSeam( posShapeID ))
2048 ngID1 = node2ngID.insert( make_pair( n, ngID1 )).first->second;
2049 if ( ngID1 > ngMesh.GetNP() )
2051 netgen::MeshPoint mp( netgen::Point<3> (n->X(), n->Y(), n->Z()) );
2052 ngMesh.AddPoint ( mp, 1, netgen::EDGEPOINT );
2053 nodeVec.push_back( n );
2055 else // n is in ngMesh already, and ngID2 in prev segment is wrong
2057 ngID2 = ngMesh.GetNP() + 1;
2058 if ( i > 0 ) // prev segment belongs to same wire
2060 netgen::Segment& prevSeg = ngMesh.LineSegment( ngMesh.GetNSeg() );
2067 netgen::Segment seg;
2069 seg[0] = ngID1; // ng node id
2070 seg[1] = ngID2; // ng node id
2071 seg.edgenr = ngMesh.GetNSeg() + 1; // ng segment id
2072 seg.si = faceID; // = geom.fmap.FindIndex (face);
2074 for ( int iEnd = 0; iEnd < 2; ++iEnd)
2076 const UVPtStruct& pnt = uvPtVec[ i + iEnd ];
2078 seg.epgeominfo[ iEnd ].dist = pnt.param; // param on curve
2079 seg.epgeominfo[ iEnd ].u = pnt.u;
2080 seg.epgeominfo[ iEnd ].v = pnt.v;
2082 // find out edge id and node parameter on edge
2083 onVertex = ( pnt.normParam + 1e-10 > vertexNormPar );
2084 if ( onVertex || posShapeID != posID )
2087 double normParam = pnt.normParam;
2089 normParam = 0.5 * ( uvPtVec[ i ].normParam + uvPtVec[ i+1 ].normParam );
2090 int edgeIndexInWire = wire->EdgeIndex( normParam );
2091 vertexNormPar = wire->LastParameter( edgeIndexInWire );
2092 const TopoDS_Edge& edge = wire->Edge( edgeIndexInWire );
2093 edgeID = geom.emap.FindIndex( edge );
2095 isInternalWire = ( edge.Orientation() == TopAbs_INTERNAL );
2096 // if ( onVertex ) // param on curve is different on each of two edges
2097 // seg.epgeominfo[ iEnd ].dist = helper.GetNodeU( edge, pnt.node );
2099 seg.epgeominfo[ iEnd ].edgenr = edgeID; // = geom.emap.FindIndex(edge);
2102 ngMesh.AddSegment (seg);
2104 // restrict size of elements near the segment
2105 SMESH_TNodeXYZ np1( n ), np2( uvPtVec[ i+1 ].node );
2106 // get an average size of adjacent segments to avoid sharp change of
2107 // element size (regression on issue 0020452, note 0010898)
2108 int iPrev = SMESH_MesherHelper::WrapIndex( i-1, nbSegments );
2109 int iNext = SMESH_MesherHelper::WrapIndex( i+1, nbSegments );
2110 double sumH = segLen[ iPrev ] + segLen[ i ] + segLen[ iNext ];
2111 int nbSeg = ( int( segLen[ iPrev ] > sumH / 100.) +
2112 int( segLen[ i ] > sumH / 100.) +
2113 int( segLen[ iNext ] > sumH / 100.));
2115 RestrictLocalSize( ngMesh, 0.5*(np1+np2), sumH / nbSeg, overrideMinH );
2117 if ( isInternalWire )
2119 swap (seg[0], seg[1]);
2120 swap( seg.epgeominfo[0], seg.epgeominfo[1] );
2121 seg.edgenr = ngMesh.GetNSeg() + 1; // segment id
2122 ngMesh.AddSegment (seg);
2124 } // loop on segments on a wire
2126 // close chain of segments
2127 if ( nbSegments > 0 )
2129 netgen::Segment& lastSeg = ngMesh.LineSegment( ngMesh.GetNSeg() - int( isInternalWire ));
2130 const SMDS_MeshNode * lastNode = uvPtVec.back().node;
2131 lastSeg[1] = node2ngID.insert( make_pair( lastNode, lastSeg[1] )).first->second;
2132 if ( lastSeg[1] > ngMesh.GetNP() )
2134 netgen::MeshPoint mp( netgen::Point<3> (lastNode->X(), lastNode->Y(), lastNode->Z()) );
2135 ngMesh.AddPoint ( mp, 1, netgen::EDGEPOINT );
2136 nodeVec.push_back( lastNode );
2138 if ( isInternalWire )
2140 netgen::Segment& realLastSeg = ngMesh.LineSegment( ngMesh.GetNSeg() );
2141 realLastSeg[0] = lastSeg[1];
2145 #ifdef DUMP_SEGMENTS
2146 cout << "BEGIN WIRE " << iW << endl;
2147 for ( int i = prevNbNGSeg+1; i <= ngMesh.GetNSeg(); ++i )
2149 netgen::Segment& seg = ngMesh.LineSegment( i );
2151 netgen::Segment& prevSeg = ngMesh.LineSegment( i-1 );
2152 if ( seg[0] == prevSeg[1] && seg[1] == prevSeg[0] )
2154 cout << "Segment: " << seg.edgenr << endl << "\tis REVRESE of the previous one" << endl;
2158 cout << "Segment: " << seg.edgenr << endl
2159 << "\tp1: " << seg[0] << " n" << nodeVec[ seg[0]]->GetID() << endl
2160 << "\tp2: " << seg[1] << " n" << nodeVec[ seg[1]]->GetID() << endl
2161 << "\tp0 param: " << seg.epgeominfo[ 0 ].dist << endl
2162 << "\tp0 uv: " << seg.epgeominfo[ 0 ].u <<", "<< seg.epgeominfo[ 0 ].v << endl
2163 << "\tp0 edge: " << seg.epgeominfo[ 0 ].edgenr << endl
2164 << "\tp1 param: " << seg.epgeominfo[ 1 ].dist << endl
2165 << "\tp1 uv: " << seg.epgeominfo[ 1 ].u <<", "<< seg.epgeominfo[ 1 ].v << endl
2166 << "\tp1 edge: " << seg.epgeominfo[ 1 ].edgenr << endl;
2168 cout << "--END WIRE " << iW << endl;
2170 SMESH_Comment __not_unused_variable( prevNbNGSeg );
2173 } // loop on WIREs of a FACE
2175 // add a segment instead of an internal vertex
2176 if ( wasNgMeshEmpty )
2178 NETGENPlugin_Internals intShapes( *helper.GetMesh(), helper.GetSubShape(), /*is3D=*/false );
2179 AddIntVerticesInFaces( geom, ngMesh, nodeVec, intShapes );
2181 ngMesh.CalcSurfacesOfNode();
2186 //================================================================================
2188 * \brief Fill SMESH mesh according to contents of netgen mesh
2189 * \param occgeo - container of OCCT geometry to mesh
2190 * \param ngMesh - netgen mesh
2191 * \param initState - bn of entities in netgen mesh before computing
2192 * \param sMesh - SMESH mesh to fill in
2193 * \param nodeVec - vector of nodes in which node index == netgen ID
2194 * \param comment - returns problem description
2195 * \param quadHelper - holder of medium nodes of sub-meshes
2196 * \retval int - error
2198 //================================================================================
2200 int NETGENPlugin_Mesher::FillSMesh(const netgen::OCCGeometry& occgeo,
2201 netgen::Mesh& ngMesh,
2202 const NETGENPlugin_ngMeshInfo& initState,
2204 std::vector<const SMDS_MeshNode*>& nodeVec,
2205 SMESH_Comment& comment,
2206 SMESH_MesherHelper* quadHelper)
2208 int nbNod = ngMesh.GetNP();
2209 int nbSeg = ngMesh.GetNSeg();
2210 int nbFac = ngMesh.GetNSE();
2211 int nbVol = ngMesh.GetNE();
2213 SMESHDS_Mesh* meshDS = sMesh.GetMeshDS();
2215 // quadHelper is used for either
2216 // 1) making quadratic elements when a lower dimention mesh is loaded
2217 // to SMESH before convertion to quadratic by NETGEN
2218 // 2) sewing of quadratic elements with quadratic elements of sub-meshes
2219 if ( quadHelper && !quadHelper->GetIsQuadratic() && quadHelper->GetTLinkNodeMap().empty() )
2222 int i, nbInitNod = initState._nbNodes;
2223 if ( initState._elementsRemoved )
2225 // PAL23427. Update nodeVec to track removal of netgen free points as a result
2226 // of removal of faces in FillNgMesh() in the case of a shrunk sub-mesh
2227 int ngID, nodeVecSize = nodeVec.size();
2228 const double eps = std::numeric_limits<double>::min();
2229 for ( ngID = i = 1; i < nodeVecSize; ++ngID, ++i )
2231 gp_Pnt ngPnt( NGPOINT_COORDS( ngMesh.Point( ngID )));
2232 gp_Pnt node ( SMESH_NodeXYZ ( nodeVec[ i ]));
2233 if ( ngPnt.SquareDistance( node ) < eps )
2235 nodeVec[ ngID ] = nodeVec[ i ];
2242 nodeVec.resize( ngID );
2243 nbInitNod = ngID - 1;
2245 // -------------------------------------
2246 // Create and insert nodes into nodeVec
2247 // -------------------------------------
2249 nodeVec.resize( nbNod + 1 );
2250 for ( i = nbInitNod+1; i <= nbNod; ++i )
2252 const netgen::MeshPoint& ngPoint = ngMesh.Point(i);
2253 SMDS_MeshNode* node = NULL;
2254 TopoDS_Vertex aVert;
2255 // First, netgen creates nodes on vertices in occgeo.vmap,
2256 // so node index corresponds to vertex index
2257 // but (issue 0020776) netgen does not create nodes with equal coordinates
2258 if ( i-nbInitNod <= occgeo.vmap.Extent() )
2260 gp_Pnt p ( NGPOINT_COORDS(ngPoint) );
2261 for (int iV = i-nbInitNod; aVert.IsNull() && iV <= occgeo.vmap.Extent(); ++iV)
2263 aVert = TopoDS::Vertex( occgeo.vmap( iV ));
2264 gp_Pnt pV = BRep_Tool::Pnt( aVert );
2265 if ( p.SquareDistance( pV ) > 1e-20 )
2268 node = const_cast<SMDS_MeshNode*>( SMESH_Algo::VertexNode( aVert, meshDS ));
2271 if (!node) // node not found on vertex
2273 node = meshDS->AddNode( NGPOINT_COORDS( ngPoint ));
2274 if (!aVert.IsNull())
2275 meshDS->SetNodeOnVertex(node, aVert);
2280 // -------------------------------------------
2281 // Create mesh segments along geometric edges
2282 // -------------------------------------------
2284 int nbInitSeg = initState._nbSegments;
2285 for (i = nbInitSeg+1; i <= nbSeg; ++i )
2287 const netgen::Segment& seg = ngMesh.LineSegment(i);
2289 int pinds[3] = { seg.pnums[0], seg.pnums[1], seg.pnums[2] };
2292 for (int j=0; j < 3; ++j)
2294 int pind = pinds[j];
2295 if (pind <= 0 || !nodeVec_ACCESS(pind))
2303 int aGeomEdgeInd = seg.epgeominfo[j].edgenr;
2304 if (aGeomEdgeInd > 0 && aGeomEdgeInd <= occgeo.emap.Extent())
2305 aEdge = TopoDS::Edge(occgeo.emap(aGeomEdgeInd));
2307 param = seg.epgeominfo[j].dist;
2310 else // middle point
2312 param = param2 * 0.5;
2314 if (!aEdge.IsNull() && nodeVec_ACCESS(pind)->getshapeId() < 1)
2316 meshDS->SetNodeOnEdge(nodeVec_ACCESS(pind), aEdge, param);
2321 SMDS_MeshEdge* edge = 0;
2322 if (nbp == 2) // second order ?
2324 if ( meshDS->FindEdge( nodeVec_ACCESS(pinds[0]), nodeVec_ACCESS(pinds[1])))
2326 if ( quadHelper ) // final mesh must be quadratic
2327 edge = quadHelper->AddEdge(nodeVec_ACCESS(pinds[0]), nodeVec_ACCESS(pinds[1]));
2329 edge = meshDS->AddEdge(nodeVec_ACCESS(pinds[0]), nodeVec_ACCESS(pinds[1]));
2333 if ( meshDS->FindEdge( nodeVec_ACCESS(pinds[0]), nodeVec_ACCESS(pinds[1]),
2334 nodeVec_ACCESS(pinds[2])))
2336 edge = meshDS->AddEdge(nodeVec_ACCESS(pinds[0]), nodeVec_ACCESS(pinds[1]),
2337 nodeVec_ACCESS(pinds[2]));
2341 if ( comment.empty() ) comment << "Cannot create a mesh edge";
2342 MESSAGE("Cannot create a mesh edge");
2343 nbSeg = nbFac = nbVol = 0;
2346 if ( !aEdge.IsNull() && edge->getshapeId() < 1 )
2347 meshDS->SetMeshElementOnShape(edge, aEdge);
2349 else if ( comment.empty() )
2351 comment << "Invalid netgen segment #" << i;
2355 // ----------------------------------------
2356 // Create mesh faces along geometric faces
2357 // ----------------------------------------
2359 int nbInitFac = initState._nbFaces;
2360 int quadFaceID = ngMesh.GetNFD() + 1;
2361 if ( nbInitFac < nbFac )
2362 // add a faces descriptor to exclude qudrangle elements generated by NETGEN
2363 // from computation of 3D mesh
2364 ngMesh.AddFaceDescriptor (netgen::FaceDescriptor(quadFaceID, /*solid1=*/0, /*solid2=*/0, 0));
2366 vector<const SMDS_MeshNode*> nodes;
2367 for (i = nbInitFac+1; i <= nbFac; ++i )
2369 const netgen::Element2d& elem = ngMesh.SurfaceElement(i);
2370 const int aGeomFaceInd = elem.GetIndex();
2372 if (aGeomFaceInd > 0 && aGeomFaceInd <= occgeo.fmap.Extent())
2373 aFace = TopoDS::Face(occgeo.fmap(aGeomFaceInd));
2375 for ( int j = 1; j <= elem.GetNP(); ++j )
2377 int pind = elem.PNum(j);
2378 if ( pind < 1 || pind >= (int) nodeVec.size() )
2380 if ( SMDS_MeshNode* node = nodeVec_ACCESS(pind))
2382 nodes.push_back( node );
2383 if (!aFace.IsNull() && node->getshapeId() < 1)
2385 const netgen::PointGeomInfo& pgi = elem.GeomInfoPi(j);
2386 meshDS->SetNodeOnFace(node, aFace, pgi.u, pgi.v);
2390 if ((int) nodes.size() != elem.GetNP() )
2392 if ( comment.empty() )
2393 comment << "Invalid netgen 2d element #" << i;
2394 continue; // bad node ids
2396 SMDS_MeshFace* face = NULL;
2397 switch (elem.GetType())
2400 if ( quadHelper ) // final mesh must be quadratic
2401 face = quadHelper->AddFace(nodes[0],nodes[1],nodes[2]);
2403 face = meshDS->AddFace(nodes[0],nodes[1],nodes[2]);
2406 if ( quadHelper ) // final mesh must be quadratic
2407 face = quadHelper->AddFace(nodes[0],nodes[1],nodes[2],nodes[3]);
2409 face = meshDS->AddFace(nodes[0],nodes[1],nodes[2],nodes[3]);
2410 // exclude qudrangle elements from computation of 3D mesh
2411 const_cast< netgen::Element2d& >( elem ).SetIndex( quadFaceID );
2414 nodes[5] = mediumNode( nodes[0],nodes[1],nodes[5], quadHelper );
2415 nodes[3] = mediumNode( nodes[1],nodes[2],nodes[3], quadHelper );
2416 nodes[4] = mediumNode( nodes[2],nodes[0],nodes[4], quadHelper );
2417 face = meshDS->AddFace(nodes[0],nodes[1],nodes[2],nodes[5],nodes[3],nodes[4]);
2420 nodes[4] = mediumNode( nodes[0],nodes[1],nodes[4], quadHelper );
2421 nodes[7] = mediumNode( nodes[1],nodes[2],nodes[7], quadHelper );
2422 nodes[5] = mediumNode( nodes[2],nodes[3],nodes[5], quadHelper );
2423 nodes[6] = mediumNode( nodes[3],nodes[0],nodes[6], quadHelper );
2424 face = meshDS->AddFace(nodes[0],nodes[1],nodes[2],nodes[3],
2425 nodes[4],nodes[7],nodes[5],nodes[6]);
2426 // exclude qudrangle elements from computation of 3D mesh
2427 const_cast< netgen::Element2d& >( elem ).SetIndex( quadFaceID );
2430 MESSAGE("NETGEN created a face of unexpected type, ignoring");
2435 if ( comment.empty() ) comment << "Cannot create a mesh face";
2436 MESSAGE("Cannot create a mesh face");
2437 nbSeg = nbFac = nbVol = 0;
2440 if ( !aFace.IsNull() )
2441 meshDS->SetMeshElementOnShape( face, aFace );
2444 // ------------------
2445 // Create tetrahedra
2446 // ------------------
2448 for ( i = 1; i <= nbVol; ++i )
2450 const netgen::Element& elem = ngMesh.VolumeElement(i);
2451 int aSolidInd = elem.GetIndex();
2452 TopoDS_Solid aSolid;
2453 if ( aSolidInd > 0 && aSolidInd <= occgeo.somap.Extent() )
2454 aSolid = TopoDS::Solid(occgeo.somap(aSolidInd));
2456 for ( int j = 1; j <= elem.GetNP(); ++j )
2458 int pind = elem.PNum(j);
2459 if ( pind < 1 || pind >= (int)nodeVec.size() )
2461 if ( SMDS_MeshNode* node = nodeVec_ACCESS(pind) )
2463 nodes.push_back(node);
2464 if ( !aSolid.IsNull() && node->getshapeId() < 1 )
2465 meshDS->SetNodeInVolume(node, aSolid);
2468 if ((int) nodes.size() != elem.GetNP() )
2470 if ( comment.empty() )
2471 comment << "Invalid netgen 3d element #" << i;
2474 SMDS_MeshVolume* vol = NULL;
2475 switch ( elem.GetType() )
2478 vol = meshDS->AddVolume(nodes[0],nodes[1],nodes[2],nodes[3]);
2481 nodes[4] = mediumNode( nodes[0],nodes[1],nodes[4], quadHelper );
2482 nodes[7] = mediumNode( nodes[1],nodes[2],nodes[7], quadHelper );
2483 nodes[5] = mediumNode( nodes[2],nodes[0],nodes[5], quadHelper );
2484 nodes[6] = mediumNode( nodes[0],nodes[3],nodes[6], quadHelper );
2485 nodes[8] = mediumNode( nodes[1],nodes[3],nodes[8], quadHelper );
2486 nodes[9] = mediumNode( nodes[2],nodes[3],nodes[9], quadHelper );
2487 vol = meshDS->AddVolume(nodes[0],nodes[1],nodes[2],nodes[3],
2488 nodes[4],nodes[7],nodes[5],nodes[6],nodes[8],nodes[9]);
2491 MESSAGE("NETGEN created a volume of unexpected type, ignoring");
2496 if ( comment.empty() ) comment << "Cannot create a mesh volume";
2497 MESSAGE("Cannot create a mesh volume");
2498 nbSeg = nbFac = nbVol = 0;
2501 if (!aSolid.IsNull())
2502 meshDS->SetMeshElementOnShape(vol, aSolid);
2504 return comment.empty() ? 0 : 1;
2509 //================================================================================
2511 * \brief Convert error into text
2513 //================================================================================
2515 std::string text(int err)
2520 SMESH_Comment("Error in netgen::OCCGenerateMesh() at ") << netgen::multithread.task;
2523 //================================================================================
2525 * \brief Convert exception into text
2527 //================================================================================
2529 std::string text(Standard_Failure& ex)
2531 SMESH_Comment str("Exception in netgen::OCCGenerateMesh()");
2532 str << " at " << netgen::multithread.task
2533 << ": " << ex.DynamicType()->Name();
2534 if ( ex.GetMessageString() && strlen( ex.GetMessageString() ))
2535 str << ": " << ex.GetMessageString();
2538 //================================================================================
2540 * \brief Convert exception into text
2542 //================================================================================
2544 std::string text(netgen::NgException& ex)
2546 SMESH_Comment str("NgException");
2547 if ( strlen( netgen::multithread.task ) > 0 )
2548 str << " at " << netgen::multithread.task;
2549 str << ": " << ex.What();
2553 //================================================================================
2555 * \brief Looks for triangles lying on a SOLID
2557 //================================================================================
2559 bool hasBadElemOnSolid( const list<const SMDS_MeshElement*>& elems,
2560 SMESH_subMesh* solidSM )
2562 TopTools_IndexedMapOfShape solidSubs;
2563 TopExp::MapShapes( solidSM->GetSubShape(), solidSubs );
2564 SMESHDS_Mesh* mesh = solidSM->GetFather()->GetMeshDS();
2566 list<const SMDS_MeshElement*>::const_iterator e = elems.begin();
2567 for ( ; e != elems.end(); ++e )
2569 const SMDS_MeshElement* elem = *e;
2570 // if ( elem->GetType() != SMDSAbs_Face ) -- 23047
2572 int nbNodesOnSolid = 0, nbNodes = elem->NbNodes();
2573 SMDS_NodeIteratorPtr nIt = elem->nodeIterator();
2574 while ( nIt->more() )
2576 const SMDS_MeshNode* n = nIt->next();
2577 const TopoDS_Shape& s = mesh->IndexToShape( n->getshapeId() );
2578 nbNodesOnSolid += ( !s.IsNull() && solidSubs.Contains( s ));
2579 if ( nbNodesOnSolid > 2 ||
2580 nbNodesOnSolid == nbNodes)
2587 const double edgeMeshingTime = 0.001;
2588 const double faceMeshingTime = 0.019;
2589 const double edgeFaceMeshingTime = edgeMeshingTime + faceMeshingTime;
2590 const double faceOptimizTime = 0.06;
2591 const double voluMeshingTime = 0.15;
2592 const double volOptimizeTime = 0.77;
2595 //=============================================================================
2597 * Here we are going to use the NETGEN mesher
2599 //=============================================================================
2601 bool NETGENPlugin_Mesher::Compute()
2603 NETGENPlugin_NetgenLibWrapper ngLib;
2605 netgen::MeshingParameters& mparams = netgen::mparam;
2607 SMESH_ComputeErrorPtr error = SMESH_ComputeError::New();
2608 SMESH_MesherHelper quadHelper( *_mesh );
2609 quadHelper.SetIsQuadratic( mparams.secondorder );
2611 // -------------------------
2612 // Prepare OCC geometry
2613 // -------------------------
2615 netgen::OCCGeometry occgeo;
2616 list< SMESH_subMesh* > meshedSM[3]; // for 0-2 dimensions
2617 NETGENPlugin_Internals internals( *_mesh, _shape, _isVolume );
2618 PrepareOCCgeometry( occgeo, _shape, *_mesh, meshedSM, &internals );
2621 _totalTime = edgeFaceMeshingTime;
2623 _totalTime += faceOptimizTime;
2625 _totalTime += voluMeshingTime + ( _optimize ? volOptimizeTime : 0 );
2626 double doneTime = 0;
2629 _curShapeIndex = -1;
2631 // -------------------------
2632 // Generate the mesh
2633 // -------------------------
2636 NETGENPlugin_ngMeshInfo initState; // it remembers size of ng mesh equal to size of Smesh
2638 SMESH_Comment comment;
2641 // vector of nodes in which node index == netgen ID
2642 vector< const SMDS_MeshNode* > nodeVec;
2650 // not to RestrictLocalH() according to curvature during MESHCONST_ANALYSE
2651 mparams.uselocalh = false;
2652 mparams.grading = 0.8; // not limitited size growth
2654 if ( _simpleHyp->GetNumberOfSegments() )
2656 mparams.maxh = occgeo.boundingbox.Diam();
2659 mparams.maxh = _simpleHyp->GetLocalLength();
2662 if ( mparams.maxh == 0.0 )
2663 mparams.maxh = occgeo.boundingbox.Diam();
2664 if ( _simpleHyp || ( mparams.minh == 0.0 && _fineness != NETGENPlugin_Hypothesis::UserDefined))
2665 mparams.minh = GetDefaultMinSize( _shape, mparams.maxh );
2667 // Local size on faces
2668 occgeo.face_maxh = mparams.maxh;
2670 // Let netgen create _ngMesh and calculate element size on not meshed shapes
2674 int startWith = netgen::MESHCONST_ANALYSE;
2675 int endWith = netgen::MESHCONST_ANALYSE;
2680 err = netgen::OCCGenerateMesh(occgeo, _ngMesh, mparams, startWith, endWith);
2682 err = netgen::OCCGenerateMesh(occgeo, _ngMesh, startWith, endWith, optstr);
2684 if(netgen::multithread.terminate)
2687 comment << text(err);
2689 catch (Standard_Failure& ex)
2691 comment << text(ex);
2693 catch (netgen::NgException & ex)
2695 comment << text(ex);
2696 if ( mparams.meshsizefilename )
2697 throw SMESH_ComputeError(COMPERR_BAD_PARMETERS, comment );
2699 err = 0; //- MESHCONST_ANALYSE isn't so important step
2702 ngLib.setMesh(( Ng_Mesh*) _ngMesh );
2704 _ngMesh->ClearFaceDescriptors(); // we make descriptors our-self
2706 if ( !mparams.uselocalh ) // mparams.grading is not taken into account yet
2707 _ngMesh->LocalHFunction().SetGrading( mparams.grading );
2711 // Pass 1D simple parameters to NETGEN
2712 // --------------------------------
2713 int nbSeg = _simpleHyp->GetNumberOfSegments();
2714 double segSize = _simpleHyp->GetLocalLength();
2715 for ( int iE = 1; iE <= occgeo.emap.Extent(); ++iE )
2717 const TopoDS_Edge& e = TopoDS::Edge( occgeo.emap(iE));
2719 segSize = SMESH_Algo::EdgeLength( e ) / ( nbSeg - 0.4 );
2720 setLocalSize( e, segSize, *_ngMesh );
2723 else // if ( ! _simpleHyp )
2725 // Local size on shapes
2726 SetLocalSize( occgeo, *_ngMesh );
2729 // Precompute internal edges (issue 0020676) in order to
2730 // add mesh on them correctly (twice) to netgen mesh
2731 if ( !err && internals.hasInternalEdges() )
2733 // load internal shapes into OCCGeometry
2734 netgen::OCCGeometry intOccgeo;
2735 internals.getInternalEdges( intOccgeo.fmap, intOccgeo.emap, intOccgeo.vmap, meshedSM );
2736 intOccgeo.boundingbox = occgeo.boundingbox;
2737 intOccgeo.shape = occgeo.shape;
2738 intOccgeo.face_maxh.SetSize(intOccgeo.fmap.Extent());
2739 intOccgeo.face_maxh = netgen::mparam.maxh;
2740 netgen::Mesh *tmpNgMesh = NULL;
2744 // compute local H on internal shapes in the main mesh
2745 //OCCSetLocalMeshSize(intOccgeo, *_ngMesh); it deletes _ngMesh->localH
2747 // let netgen create a temporary mesh
2749 netgen::OCCGenerateMesh(intOccgeo, tmpNgMesh, mparams, startWith, endWith);
2751 netgen::OCCGenerateMesh(intOccgeo, tmpNgMesh, startWith, endWith, optstr);
2753 if(netgen::multithread.terminate)
2756 // copy LocalH from the main to temporary mesh
2757 initState.transferLocalH( _ngMesh, tmpNgMesh );
2759 // compute mesh on internal edges
2760 startWith = endWith = netgen::MESHCONST_MESHEDGES;
2762 err = netgen::OCCGenerateMesh(intOccgeo, tmpNgMesh, mparams, startWith, endWith);
2764 err = netgen::OCCGenerateMesh(intOccgeo, tmpNgMesh, startWith, endWith, optstr);
2766 comment << text(err);
2768 catch (Standard_Failure& ex)
2770 comment << text(ex);
2773 initState.restoreLocalH( tmpNgMesh );
2775 // fill SMESH by netgen mesh
2776 vector< const SMDS_MeshNode* > tmpNodeVec;
2777 FillSMesh( intOccgeo, *tmpNgMesh, initState, *_mesh, tmpNodeVec, comment );
2778 err = ( err || !comment.empty() );
2780 nglib::Ng_DeleteMesh((nglib::Ng_Mesh*)tmpNgMesh);
2783 // Fill _ngMesh with nodes and segments of computed submeshes
2786 err = ! ( FillNgMesh(occgeo, *_ngMesh, nodeVec, meshedSM[ MeshDim_0D ]) &&
2787 FillNgMesh(occgeo, *_ngMesh, nodeVec, meshedSM[ MeshDim_1D ], &quadHelper));
2789 initState = NETGENPlugin_ngMeshInfo(_ngMesh);
2794 startWith = endWith = netgen::MESHCONST_MESHEDGES;
2799 err = netgen::OCCGenerateMesh(occgeo, _ngMesh, mparams, startWith, endWith);
2801 err = netgen::OCCGenerateMesh(occgeo, _ngMesh, startWith, endWith, optstr);
2803 if(netgen::multithread.terminate)
2806 comment << text(err);
2808 catch (Standard_Failure& ex)
2810 comment << text(ex);
2815 _ticTime = ( doneTime += edgeMeshingTime ) / _totalTime / _progressTic;
2817 mparams.uselocalh = true; // restore as it is used at surface optimization
2819 // ---------------------
2820 // compute surface mesh
2821 // ---------------------
2824 // Pass 2D simple parameters to NETGEN
2826 if ( double area = _simpleHyp->GetMaxElementArea() ) {
2828 mparams.maxh = sqrt(2. * area/sqrt(3.0));
2829 mparams.grading = 0.4; // moderate size growth
2832 // length from edges
2833 if ( _ngMesh->GetNSeg() ) {
2834 double edgeLength = 0;
2835 TopTools_MapOfShape visitedEdges;
2836 for ( TopExp_Explorer exp( _shape, TopAbs_EDGE ); exp.More(); exp.Next() )
2837 if( visitedEdges.Add(exp.Current()) )
2838 edgeLength += SMESH_Algo::EdgeLength( TopoDS::Edge( exp.Current() ));
2839 // we have to multiply length by 2 since for each TopoDS_Edge there
2840 // are double set of NETGEN edges, in other words, we have to
2841 // divide _ngMesh->GetNSeg() by 2.
2842 mparams.maxh = 2*edgeLength / _ngMesh->GetNSeg();
2845 mparams.maxh = 1000;
2847 mparams.grading = 0.2; // slow size growth
2849 mparams.quad = _simpleHyp->GetAllowQuadrangles();
2850 mparams.maxh = min( mparams.maxh, occgeo.boundingbox.Diam()/2 );
2851 _ngMesh->SetGlobalH (mparams.maxh);
2852 netgen::Box<3> bb = occgeo.GetBoundingBox();
2853 bb.Increase (bb.Diam()/20);
2854 _ngMesh->SetLocalH (bb.PMin(), bb.PMax(), mparams.grading);
2857 // Care of vertices internal in faces (issue 0020676)
2858 if ( internals.hasInternalVertexInFace() )
2860 // store computed segments in SMESH in order not to create SMESH
2861 // edges for ng segments added by AddIntVerticesInFaces()
2862 FillSMesh( occgeo, *_ngMesh, initState, *_mesh, nodeVec, comment );
2863 // add segments to faces with internal vertices
2864 AddIntVerticesInFaces( occgeo, *_ngMesh, nodeVec, internals );
2865 initState = NETGENPlugin_ngMeshInfo(_ngMesh);
2868 // Build viscous layers
2869 if ( _isViscousLayers2D ||
2870 StdMeshers_ViscousLayers2D::HasProxyMesh( TopoDS::Face( occgeo.fmap(1) ), *_mesh ))
2872 if ( !internals.hasInternalVertexInFace() ) {
2873 FillSMesh( occgeo, *_ngMesh, initState, *_mesh, nodeVec, comment );
2874 initState = NETGENPlugin_ngMeshInfo(_ngMesh);
2876 SMESH_ProxyMesh::Ptr viscousMesh;
2877 SMESH_MesherHelper helper( *_mesh );
2878 for ( int faceID = 1; faceID <= occgeo.fmap.Extent(); ++faceID )
2880 const TopoDS_Face& F = TopoDS::Face( occgeo.fmap( faceID ));
2881 viscousMesh = StdMeshers_ViscousLayers2D::Compute( *_mesh, F );
2884 if ( viscousMesh->NbProxySubMeshes() == 0 )
2886 // exclude from computation ng segments built on EDGEs of F
2887 for (int i = 1; i <= _ngMesh->GetNSeg(); i++)
2889 netgen::Segment & seg = _ngMesh->LineSegment(i);
2890 if (seg.si == faceID)
2893 // add new segments to _ngMesh instead of excluded ones
2894 helper.SetSubShape( F );
2896 StdMeshers_FaceSide::GetFaceWires( F, *_mesh, /*skipMediumNodes=*/true,
2897 error, &helper, viscousMesh );
2898 error = AddSegmentsToMesh( *_ngMesh, occgeo, wires, helper, nodeVec );
2900 if ( !error ) error = SMESH_ComputeError::New();
2902 initState = NETGENPlugin_ngMeshInfo(_ngMesh);
2905 // Let netgen compute 2D mesh
2906 startWith = netgen::MESHCONST_MESHSURFACE;
2907 endWith = _optimize ? netgen::MESHCONST_OPTSURFACE : netgen::MESHCONST_MESHSURFACE;
2912 err = netgen::OCCGenerateMesh(occgeo, _ngMesh, mparams, startWith, endWith);
2914 err = netgen::OCCGenerateMesh(occgeo, _ngMesh, startWith, endWith, optstr);
2916 if(netgen::multithread.terminate)
2919 comment << text (err);
2921 catch (Standard_Failure& ex)
2923 comment << text(ex);
2924 //err = 1; -- try to make volumes anyway
2926 catch (netgen::NgException exc)
2928 comment << text(exc);
2929 //err = 1; -- try to make volumes anyway
2934 doneTime += faceMeshingTime + ( _optimize ? faceOptimizTime : 0 );
2935 _ticTime = doneTime / _totalTime / _progressTic;
2937 // ---------------------
2938 // generate volume mesh
2939 // ---------------------
2940 // Fill _ngMesh with nodes and faces of computed 2D submeshes
2941 if ( !err && _isVolume &&
2942 ( !meshedSM[ MeshDim_2D ].empty() || mparams.quad || _viscousLayersHyp ))
2944 // load SMESH with computed segments and faces
2945 FillSMesh( occgeo, *_ngMesh, initState, *_mesh, nodeVec, comment, &quadHelper );
2947 // compute prismatic boundary volumes
2948 int nbQuad = _mesh->NbQuadrangles();
2949 SMESH_ProxyMesh::Ptr viscousMesh;
2950 if ( _viscousLayersHyp )
2952 viscousMesh = _viscousLayersHyp->Compute( *_mesh, _shape );
2956 // compute pyramids on quadrangles
2957 vector<SMESH_ProxyMesh::Ptr> pyramidMeshes( occgeo.somap.Extent() );
2959 for ( int iS = 1; iS <= occgeo.somap.Extent(); ++iS )
2961 StdMeshers_QuadToTriaAdaptor* adaptor = new StdMeshers_QuadToTriaAdaptor;
2962 pyramidMeshes[ iS-1 ].reset( adaptor );
2963 bool ok = adaptor->Compute( *_mesh, occgeo.somap(iS), viscousMesh.get() );
2967 // add proxy faces to NG mesh
2968 list< SMESH_subMesh* > viscousSM;
2969 for ( int iS = 1; iS <= occgeo.somap.Extent(); ++iS )
2971 list< SMESH_subMesh* > quadFaceSM;
2972 for (TopExp_Explorer face(occgeo.somap(iS), TopAbs_FACE); face.More(); face.Next())
2973 if ( pyramidMeshes[iS-1] && pyramidMeshes[iS-1]->GetProxySubMesh( face.Current() ))
2975 quadFaceSM.push_back( _mesh->GetSubMesh( face.Current() ));
2976 meshedSM[ MeshDim_2D ].remove( quadFaceSM.back() );
2978 else if ( viscousMesh && viscousMesh->GetProxySubMesh( face.Current() ))
2980 viscousSM.push_back( _mesh->GetSubMesh( face.Current() ));
2981 meshedSM[ MeshDim_2D ].remove( viscousSM.back() );
2983 if ( !quadFaceSM.empty() )
2984 FillNgMesh(occgeo, *_ngMesh, nodeVec, quadFaceSM, &quadHelper, pyramidMeshes[iS-1]);
2986 if ( !viscousSM.empty() )
2987 FillNgMesh(occgeo, *_ngMesh, nodeVec, viscousSM, &quadHelper, viscousMesh );
2989 // fill _ngMesh with faces of sub-meshes
2990 err = ! ( FillNgMesh(occgeo, *_ngMesh, nodeVec, meshedSM[ MeshDim_2D ], &quadHelper));
2991 initState = NETGENPlugin_ngMeshInfo(_ngMesh, /*checkRemovedElems=*/true);
2992 // toPython( _ngMesh );
2994 if (!err && _isVolume)
2996 // Pass 3D simple parameters to NETGEN
2997 const NETGENPlugin_SimpleHypothesis_3D* simple3d =
2998 dynamic_cast< const NETGENPlugin_SimpleHypothesis_3D* > ( _simpleHyp );
3000 if ( double vol = simple3d->GetMaxElementVolume() ) {
3002 mparams.maxh = pow( 72, 1/6. ) * pow( vol, 1/3. );
3003 mparams.maxh = min( mparams.maxh, occgeo.boundingbox.Diam()/2 );
3006 // length from faces
3007 mparams.maxh = _ngMesh->AverageH();
3009 _ngMesh->SetGlobalH (mparams.maxh);
3010 mparams.grading = 0.4;
3012 _ngMesh->CalcLocalH(mparams.grading);
3014 _ngMesh->CalcLocalH();
3017 // Care of vertices internal in solids and internal faces (issue 0020676)
3018 if ( internals.hasInternalVertexInSolid() || internals.hasInternalFaces() )
3020 // store computed faces in SMESH in order not to create SMESH
3021 // faces for ng faces added here
3022 FillSMesh( occgeo, *_ngMesh, initState, *_mesh, nodeVec, comment, &quadHelper );
3023 // add ng faces to solids with internal vertices
3024 AddIntVerticesInSolids( occgeo, *_ngMesh, nodeVec, internals );
3025 // duplicate mesh faces on internal faces
3026 FixIntFaces( occgeo, *_ngMesh, internals );
3027 initState = NETGENPlugin_ngMeshInfo(_ngMesh);
3029 // Let netgen compute 3D mesh
3030 startWith = endWith = netgen::MESHCONST_MESHVOLUME;
3035 err = netgen::OCCGenerateMesh(occgeo, _ngMesh, mparams, startWith, endWith);
3037 err = netgen::OCCGenerateMesh(occgeo, _ngMesh, startWith, endWith, optstr);
3039 if(netgen::multithread.terminate)
3042 if ( comment.empty() ) // do not overwrite a previos error
3043 comment << text(err);
3045 catch (Standard_Failure& ex)
3047 if ( comment.empty() ) // do not overwrite a previos error
3048 comment << text(ex);
3051 catch (netgen::NgException exc)
3053 if ( comment.empty() ) // do not overwrite a previos error
3054 comment << text(exc);
3057 _ticTime = ( doneTime += voluMeshingTime ) / _totalTime / _progressTic;
3059 // Let netgen optimize 3D mesh
3060 if ( !err && _optimize )
3062 startWith = endWith = netgen::MESHCONST_OPTVOLUME;
3067 err = netgen::OCCGenerateMesh(occgeo, _ngMesh, mparams, startWith, endWith);
3069 err = netgen::OCCGenerateMesh(occgeo, _ngMesh, startWith, endWith, optstr);
3071 if(netgen::multithread.terminate)
3074 if ( comment.empty() ) // do not overwrite a previos error
3075 comment << text(err);
3077 catch (Standard_Failure& ex)
3079 if ( comment.empty() ) // do not overwrite a previos error
3080 comment << text(ex);
3082 catch (netgen::NgException exc)
3084 if ( comment.empty() ) // do not overwrite a previos error
3085 comment << text(exc);
3089 if (!err && mparams.secondorder > 0)
3094 if ( !meshedSM[ MeshDim_1D ].empty() )
3096 // remove segments not attached to geometry (IPAL0052479)
3097 for (int i = 1; i <= _ngMesh->GetNSeg(); ++i)
3099 const netgen::Segment & seg = _ngMesh->LineSegment (i);
3100 if ( seg.epgeominfo[ 0 ].edgenr == 0 )
3101 _ngMesh->DeleteSegment( i );
3103 _ngMesh->Compress();
3105 // convert to quadratic
3106 netgen::OCCRefinementSurfaces ref (occgeo);
3107 ref.MakeSecondOrder (*_ngMesh);
3109 // care of elements already loaded to SMESH
3110 // if ( initState._nbSegments > 0 )
3111 // makeQuadratic( occgeo.emap, _mesh );
3112 // if ( initState._nbFaces > 0 )
3113 // makeQuadratic( occgeo.fmap, _mesh );
3115 catch (Standard_Failure& ex)
3117 if ( comment.empty() ) // do not overwrite a previos error
3118 comment << "Exception in netgen at passing to 2nd order ";
3120 catch (netgen::NgException exc)
3122 if ( comment.empty() ) // do not overwrite a previos error
3123 comment << exc.What();
3128 _ticTime = 0.98 / _progressTic;
3130 //int nbNod = _ngMesh->GetNP();
3131 //int nbSeg = _ngMesh->GetNSeg();
3132 int nbFac = _ngMesh->GetNSE();
3133 int nbVol = _ngMesh->GetNE();
3134 bool isOK = ( !err && (_isVolume ? (nbVol > 0) : (nbFac > 0)) );
3136 // Feed back the SMESHDS with the generated Nodes and Elements
3137 if ( true /*isOK*/ ) // get whatever built
3139 FillSMesh( occgeo, *_ngMesh, initState, *_mesh, nodeVec, comment, &quadHelper );
3141 if ( quadHelper.GetIsQuadratic() ) // remove free nodes
3142 for ( size_t i = 0; i < nodeVec.size(); ++i )
3143 if ( nodeVec[i] && nodeVec[i]->NbInverseElements() == 0 )
3144 _mesh->GetMeshDS()->RemoveFreeNode( nodeVec[i], 0, /*fromGroups=*/false );
3146 SMESH_ComputeErrorPtr readErr = ReadErrors(nodeVec);
3147 if ( readErr && !readErr->myBadElements.empty() )
3150 if ( !comment.empty() && !readErr->myComment.empty() ) comment += "\n";
3151 comment += readErr->myComment;
3153 if ( error->IsOK() && ( !isOK || comment.size() > 0 ))
3154 error->myName = COMPERR_ALGO_FAILED;
3155 if ( !comment.empty() )
3156 error->myComment = comment;
3158 // SetIsAlwaysComputed( true ) to empty sub-meshes, which
3159 // appear if the geometry contains coincident sub-shape due
3160 // to bool merge_solids = 1; in netgen/libsrc/occ/occgenmesh.cpp
3161 const int nbMaps = 2;
3162 const TopTools_IndexedMapOfShape* geoMaps[nbMaps] =
3163 { & occgeo.vmap, & occgeo.emap/*, & occgeo.fmap*/ };
3164 for ( int iMap = 0; iMap < nbMaps; ++iMap )
3165 for (int i = 1; i <= geoMaps[iMap]->Extent(); i++)
3166 if ( SMESH_subMesh* sm = _mesh->GetSubMeshContaining( geoMaps[iMap]->FindKey(i)))
3167 if ( !sm->IsMeshComputed() )
3168 sm->SetIsAlwaysComputed( true );
3170 // set bad compute error to subshapes of all failed sub-shapes
3171 if ( !error->IsOK() )
3173 bool pb2D = false, pb3D = false;
3174 for (int i = 1; i <= occgeo.fmap.Extent(); i++) {
3175 int status = occgeo.facemeshstatus[i-1];
3176 if (status == netgen::FACE_MESHED_OK ) continue;
3177 if ( SMESH_subMesh* sm = _mesh->GetSubMeshContaining( occgeo.fmap( i ))) {
3178 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
3179 if ( !smError || smError->IsOK() ) {
3180 if ( status == netgen::FACE_FAILED )
3181 smError.reset( new SMESH_ComputeError( *error ));
3183 smError.reset( new SMESH_ComputeError( COMPERR_ALGO_FAILED, "Ignored" ));
3184 if ( SMESH_Algo::GetMeshError( sm ) == SMESH_Algo::MEr_OK )
3185 smError->myName = COMPERR_WARNING;
3187 pb2D = pb2D || smError->IsKO();
3190 if ( !pb2D ) // all faces are OK
3191 for (int i = 1; i <= occgeo.somap.Extent(); i++)
3192 if ( SMESH_subMesh* sm = _mesh->GetSubMeshContaining( occgeo.somap( i )))
3194 bool smComputed = nbVol && !sm->IsEmpty();
3195 if ( smComputed && internals.hasInternalVertexInSolid( sm->GetId() ))
3197 int nbIntV = internals.getSolidsWithVertices().find( sm->GetId() )->second.size();
3198 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
3199 smComputed = ( smDS->NbElements() > 0 || smDS->NbNodes() > nbIntV );
3201 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
3202 if ( !smComputed && ( !smError || smError->IsOK() ))
3204 smError.reset( new SMESH_ComputeError( *error ));
3205 if ( nbVol && SMESH_Algo::GetMeshError( sm ) == SMESH_Algo::MEr_OK )
3207 smError->myName = COMPERR_WARNING;
3209 else if ( !smError->myBadElements.empty() ) // bad surface mesh
3211 if ( !hasBadElemOnSolid( smError->myBadElements, sm ))
3215 pb3D = pb3D || ( smError && smError->IsKO() );
3217 if ( !pb2D && !pb3D )
3218 err = 0; // no fatal errors, only warnings
3221 ngLib._isComputeOk = !err;
3226 //=============================================================================
3230 //=============================================================================
3231 bool NETGENPlugin_Mesher::Evaluate(MapShapeNbElems& aResMap)
3233 netgen::MeshingParameters& mparams = netgen::mparam;
3236 // -------------------------
3237 // Prepare OCC geometry
3238 // -------------------------
3239 netgen::OCCGeometry occgeo;
3240 list< SMESH_subMesh* > meshedSM[4]; // for 0-3 dimensions
3241 NETGENPlugin_Internals internals( *_mesh, _shape, _isVolume );
3242 PrepareOCCgeometry( occgeo, _shape, *_mesh, meshedSM, &internals );
3244 bool tooManyElems = false;
3245 const int hugeNb = std::numeric_limits<int>::max() / 100;
3250 // pass 1D simple parameters to NETGEN
3253 // not to RestrictLocalH() according to curvature during MESHCONST_ANALYSE
3254 mparams.uselocalh = false;
3255 mparams.grading = 0.8; // not limitited size growth
3257 if ( _simpleHyp->GetNumberOfSegments() )
3259 mparams.maxh = occgeo.boundingbox.Diam();
3262 mparams.maxh = _simpleHyp->GetLocalLength();
3265 if ( mparams.maxh == 0.0 )
3266 mparams.maxh = occgeo.boundingbox.Diam();
3267 if ( _simpleHyp || ( mparams.minh == 0.0 && _fineness != NETGENPlugin_Hypothesis::UserDefined))
3268 mparams.minh = GetDefaultMinSize( _shape, mparams.maxh );
3270 // let netgen create _ngMesh and calculate element size on not meshed shapes
3271 NETGENPlugin_NetgenLibWrapper ngLib;
3272 netgen::Mesh *ngMesh = NULL;
3276 int startWith = netgen::MESHCONST_ANALYSE;
3277 int endWith = netgen::MESHCONST_MESHEDGES;
3279 int err = netgen::OCCGenerateMesh(occgeo, ngMesh, mparams, startWith, endWith);
3281 int err = netgen::OCCGenerateMesh(occgeo, ngMesh, startWith, endWith, optstr);
3284 if(netgen::multithread.terminate)
3287 ngLib.setMesh(( Ng_Mesh*) ngMesh );
3289 if ( SMESH_subMesh* sm = _mesh->GetSubMeshContaining( _shape ))
3290 sm->GetComputeError().reset( new SMESH_ComputeError( COMPERR_ALGO_FAILED ));
3295 // Pass 1D simple parameters to NETGEN
3296 // --------------------------------
3297 int nbSeg = _simpleHyp->GetNumberOfSegments();
3298 double segSize = _simpleHyp->GetLocalLength();
3299 for ( int iE = 1; iE <= occgeo.emap.Extent(); ++iE )
3301 const TopoDS_Edge& e = TopoDS::Edge( occgeo.emap(iE));
3303 segSize = SMESH_Algo::EdgeLength( e ) / ( nbSeg - 0.4 );
3304 setLocalSize( e, segSize, *ngMesh );
3307 else // if ( ! _simpleHyp )
3309 // Local size on shapes
3310 SetLocalSize( occgeo, *ngMesh );
3312 // calculate total nb of segments and length of edges
3313 double fullLen = 0.0;
3315 int entity = mparams.secondorder > 0 ? SMDSEntity_Quad_Edge : SMDSEntity_Edge;
3316 TopTools_DataMapOfShapeInteger Edge2NbSeg;
3317 for (TopExp_Explorer exp(_shape, TopAbs_EDGE); exp.More(); exp.Next())
3319 TopoDS_Edge E = TopoDS::Edge( exp.Current() );
3320 if( !Edge2NbSeg.Bind(E,0) )
3323 double aLen = SMESH_Algo::EdgeLength(E);
3326 vector<int>& aVec = aResMap[_mesh->GetSubMesh(E)];
3328 aVec.resize( SMDSEntity_Last, 0);
3330 fullNbSeg += aVec[ entity ];
3333 // store nb of segments computed by Netgen
3334 NCollection_Map<Link> linkMap;
3335 for (int i = 1; i <= ngMesh->GetNSeg(); ++i )
3337 const netgen::Segment& seg = ngMesh->LineSegment(i);
3338 Link link(seg[0], seg[1]);
3339 if ( !linkMap.Add( link )) continue;
3340 int aGeomEdgeInd = seg.epgeominfo[0].edgenr;
3341 if (aGeomEdgeInd > 0 && aGeomEdgeInd <= occgeo.emap.Extent())
3343 vector<int>& aVec = aResMap[_mesh->GetSubMesh(occgeo.emap(aGeomEdgeInd))];
3347 // store nb of nodes on edges computed by Netgen
3348 TopTools_DataMapIteratorOfDataMapOfShapeInteger Edge2NbSegIt(Edge2NbSeg);
3349 for (; Edge2NbSegIt.More(); Edge2NbSegIt.Next())
3351 vector<int>& aVec = aResMap[_mesh->GetSubMesh(Edge2NbSegIt.Key())];
3352 if ( aVec[ entity ] > 1 && aVec[ SMDSEntity_Node ] == 0 )
3353 aVec[SMDSEntity_Node] = mparams.secondorder > 0 ? 2*aVec[ entity ]-1 : aVec[ entity ]-1;
3355 fullNbSeg += aVec[ entity ];
3356 Edge2NbSeg( Edge2NbSegIt.Key() ) = aVec[ entity ];
3358 if ( fullNbSeg == 0 )
3365 if ( double area = _simpleHyp->GetMaxElementArea() ) {
3367 mparams.maxh = sqrt(2. * area/sqrt(3.0));
3368 mparams.grading = 0.4; // moderate size growth
3371 // length from edges
3372 mparams.maxh = fullLen/fullNbSeg;
3373 mparams.grading = 0.2; // slow size growth
3376 mparams.maxh = min( mparams.maxh, occgeo.boundingbox.Diam()/2 );
3377 mparams.maxh = min( mparams.maxh, fullLen/fullNbSeg * (1. + mparams.grading));
3379 for (TopExp_Explorer exp(_shape, TopAbs_FACE); exp.More(); exp.Next())
3381 TopoDS_Face F = TopoDS::Face( exp.Current() );
3382 SMESH_subMesh *sm = _mesh->GetSubMesh(F);
3384 BRepGProp::SurfaceProperties(F,G);
3385 double anArea = G.Mass();
3386 tooManyElems = tooManyElems || ( anArea/hugeNb > mparams.maxh*mparams.maxh );
3388 if ( !tooManyElems )
3390 TopTools_MapOfShape egdes;
3391 for (TopExp_Explorer exp1(F,TopAbs_EDGE); exp1.More(); exp1.Next())
3392 if ( egdes.Add( exp1.Current() ))
3393 nb1d += Edge2NbSeg.Find(exp1.Current());
3395 int nbFaces = tooManyElems ? hugeNb : int( 4*anArea / (mparams.maxh*mparams.maxh*sqrt(3.)));
3396 int nbNodes = tooManyElems ? hugeNb : (( nbFaces*3 - (nb1d-1)*2 ) / 6 + 1 );
3398 vector<int> aVec(SMDSEntity_Last, 0);
3399 if( mparams.secondorder > 0 ) {
3400 int nb1d_in = (nbFaces*3 - nb1d) / 2;
3401 aVec[SMDSEntity_Node] = nbNodes + nb1d_in;
3402 aVec[SMDSEntity_Quad_Triangle] = nbFaces;
3405 aVec[SMDSEntity_Node] = Max ( nbNodes, 0 );
3406 aVec[SMDSEntity_Triangle] = nbFaces;
3408 aResMap[sm].swap(aVec);
3415 // pass 3D simple parameters to NETGEN
3416 const NETGENPlugin_SimpleHypothesis_3D* simple3d =
3417 dynamic_cast< const NETGENPlugin_SimpleHypothesis_3D* > ( _simpleHyp );
3419 if ( double vol = simple3d->GetMaxElementVolume() ) {
3421 mparams.maxh = pow( 72, 1/6. ) * pow( vol, 1/3. );
3422 mparams.maxh = min( mparams.maxh, occgeo.boundingbox.Diam()/2 );
3425 // using previous length from faces
3427 mparams.grading = 0.4;
3428 mparams.maxh = min( mparams.maxh, fullLen/fullNbSeg * (1. + mparams.grading));
3431 BRepGProp::VolumeProperties(_shape,G);
3432 double aVolume = G.Mass();
3433 double tetrVol = 0.1179*mparams.maxh*mparams.maxh*mparams.maxh;
3434 tooManyElems = tooManyElems || ( aVolume/hugeNb > tetrVol );
3435 int nbVols = tooManyElems ? hugeNb : int(aVolume/tetrVol);
3436 int nb1d_in = int(( nbVols*6 - fullNbSeg ) / 6 );
3437 vector<int> aVec(SMDSEntity_Last, 0 );
3438 if ( tooManyElems ) // avoid FPE
3440 aVec[SMDSEntity_Node] = hugeNb;
3441 aVec[ mparams.secondorder > 0 ? SMDSEntity_Quad_Tetra : SMDSEntity_Tetra] = hugeNb;
3445 if( mparams.secondorder > 0 ) {
3446 aVec[SMDSEntity_Node] = nb1d_in/3 + 1 + nb1d_in;
3447 aVec[SMDSEntity_Quad_Tetra] = nbVols;
3450 aVec[SMDSEntity_Node] = nb1d_in/3 + 1;
3451 aVec[SMDSEntity_Tetra] = nbVols;
3454 SMESH_subMesh *sm = _mesh->GetSubMesh(_shape);
3455 aResMap[sm].swap(aVec);
3461 double NETGENPlugin_Mesher::GetProgress(const SMESH_Algo* holder,
3462 const int * algoProgressTic,
3463 const double * algoProgress) const
3465 ((int&) _progressTic ) = *algoProgressTic + 1;
3467 if ( !_occgeom ) return 0;
3469 double progress = -1;
3472 if ( _ticTime < 0 && netgen::multithread.task[0] == 'O'/*Optimizing surface*/ )
3474 ((double&) _ticTime ) = edgeFaceMeshingTime / _totalTime / _progressTic;
3476 else if ( !_optimize /*&& _occgeom->fmap.Extent() > 1*/ )
3478 int doneShapeIndex = -1;
3479 while ( doneShapeIndex+1 < _occgeom->facemeshstatus.Size() &&
3480 _occgeom->facemeshstatus[ doneShapeIndex+1 ])
3482 if ( doneShapeIndex+1 != _curShapeIndex )
3484 ((int&) _curShapeIndex) = doneShapeIndex+1;
3485 double doneShapeRate = _curShapeIndex / double( _occgeom->fmap.Extent() );
3486 double doneTime = edgeMeshingTime + doneShapeRate * faceMeshingTime;
3487 ((double&) _ticTime) = doneTime / _totalTime / _progressTic;
3488 // cout << "shape " << _curShapeIndex << " _ticTime " << _ticTime
3489 // << " " << doneTime / _totalTime / _progressTic << endl;
3493 else if ( !_optimize && _occgeom->somap.Extent() > 1 )
3495 int curShapeIndex = _curShapeIndex;
3496 if ( _ngMesh->GetNE() > 0 )
3498 netgen::Element el = (*_ngMesh)[netgen::ElementIndex( _ngMesh->GetNE()-1 )];
3499 curShapeIndex = el.GetIndex();
3501 if ( curShapeIndex != _curShapeIndex )
3503 ((int&) _curShapeIndex) = curShapeIndex;
3504 double doneShapeRate = _curShapeIndex / double( _occgeom->somap.Extent() );
3505 double doneTime = edgeFaceMeshingTime + doneShapeRate * voluMeshingTime;
3506 ((double&) _ticTime) = doneTime / _totalTime / _progressTic;
3507 // cout << "shape " << _curShapeIndex << " _ticTime " << _ticTime
3508 // << " " << doneTime / _totalTime / _progressTic << endl;
3513 progress = Max( *algoProgressTic * _ticTime, *algoProgress );
3518 netgen::multithread.task[0] == 'D'/*elaunay meshing*/ &&
3519 progress > voluMeshingTime )
3521 progress = voluMeshingTime;
3522 ((double&) _ticTime) = voluMeshingTime / _totalTime / _progressTic;
3524 ((int&) *algoProgressTic )++;
3525 ((double&) *algoProgress) = progress;
3527 //cout << progress << " " << *algoProgressTic << " " << netgen::multithread.task << " "<< _ticTime << endl;
3529 return Min( progress, 0.99 );
3532 //================================================================================
3534 * \brief Read mesh entities preventing successful computation from "test.out" file
3536 //================================================================================
3538 SMESH_ComputeErrorPtr
3539 NETGENPlugin_Mesher::ReadErrors(const vector<const SMDS_MeshNode* >& nodeVec)
3541 SMESH_ComputeErrorPtr err = SMESH_ComputeError::New
3542 (COMPERR_BAD_INPUT_MESH, "Some edges multiple times in surface mesh");
3543 SMESH_File file("test.out");
3545 vector<int> three1(3), three2(3);
3546 const char* badEdgeStr = " multiple times in surface mesh";
3547 const int badEdgeStrLen = strlen( badEdgeStr );
3548 const int nbNodes = nodeVec.size();
3550 while( !file.eof() )
3552 if ( strncmp( file, "Edge ", 5 ) == 0 &&
3553 file.getInts( two ) &&
3554 strncmp( file, badEdgeStr, badEdgeStrLen ) == 0 &&
3555 two[0] < nbNodes && two[1] < nbNodes )
3557 err->myBadElements.push_back( new SMDS_LinearEdge( nodeVec[ two[0]], nodeVec[ two[1]] ));
3558 file += badEdgeStrLen;
3560 else if ( strncmp( file, "Intersecting: ", 14 ) == 0 )
3563 // openelement 18 with open element 126
3567 const char* pos = file;
3568 bool ok = ( strncmp( file, "openelement ", 12 ) == 0 );
3569 ok = ok && file.getInts( two );
3570 ok = ok && file.getInts( three1 );
3571 ok = ok && file.getInts( three2 );
3572 for ( int i = 0; ok && i < 3; ++i )
3573 ok = ( three1[i] < nbNodes && nodeVec[ three1[i]]);
3574 for ( int i = 0; ok && i < 3; ++i )
3575 ok = ( three2[i] < nbNodes && nodeVec[ three2[i]]);
3578 err->myBadElements.push_back( new SMDS_FaceOfNodes( nodeVec[ three1[0]],
3579 nodeVec[ three1[1]],
3580 nodeVec[ three1[2]]));
3581 err->myBadElements.push_back( new SMDS_FaceOfNodes( nodeVec[ three2[0]],
3582 nodeVec[ three2[1]],
3583 nodeVec[ three2[2]]));
3584 err->myComment = "Intersecting triangles";
3598 size_t nbBadElems = err->myBadElements.size();
3599 if ( nbBadElems ) nbBadElems++; // avoid warning: variable set but not used
3605 //================================================================================
3607 * \brief Write a python script creating an equivalent SALOME mesh.
3608 * This is useful to see what mesh is passed as input for the next step of mesh
3609 * generation (of mesh of higher dimension)
3611 //================================================================================
3613 void NETGENPlugin_Mesher::toPython( const netgen::Mesh* ngMesh )
3615 const char* pyFile = "/tmp/ngMesh.py";
3616 ofstream outfile( pyFile, ios::out );
3617 if ( !outfile ) return;
3619 outfile << "import salome, SMESH" << endl
3620 << "from salome.smesh import smeshBuilder" << endl
3621 << "smesh = smeshBuilder.New(salome.myStudy)" << endl
3622 << "mesh = smesh.Mesh()" << endl << endl;
3624 using namespace netgen;
3626 for (pi = PointIndex::BASE;
3627 pi < ngMesh->GetNP()+PointIndex::BASE; pi++)
3629 outfile << "mesh.AddNode( ";
3630 outfile << (*ngMesh)[pi](0) << ", ";
3631 outfile << (*ngMesh)[pi](1) << ", ";
3632 outfile << (*ngMesh)[pi](2) << ") ## "<< pi << endl;
3635 int nbDom = ngMesh->GetNDomains();
3636 for ( int i = 0; i < nbDom; ++i )
3637 outfile<< "grp" << i+1 << " = mesh.CreateEmptyGroup( SMESH.FACE, 'domain"<< i+1 << "')"<< endl;
3639 SurfaceElementIndex sei;
3640 for (sei = 0; sei < ngMesh->GetNSE(); sei++)
3642 outfile << "mesh.AddFace([ ";
3643 Element2d sel = (*ngMesh)[sei];
3644 for (int j = 0; j < sel.GetNP(); j++)
3645 outfile << sel[j] << ( j+1 < sel.GetNP() ? ", " : " ])");
3646 if ( sel.IsDeleted() ) outfile << " ## IsDeleted ";
3649 if ((*ngMesh)[sei].GetIndex())
3651 if ( int dom1 = ngMesh->GetFaceDescriptor((*ngMesh)[sei].GetIndex ()).DomainIn())
3652 outfile << "grp"<< dom1 <<".Add([ " << (int)sei+1 << " ])" << endl;
3653 if ( int dom2 = ngMesh->GetFaceDescriptor((*ngMesh)[sei].GetIndex ()).DomainOut())
3654 outfile << "grp"<< dom2 <<".Add([ " << (int)sei+1 << " ])" << endl;
3658 for (ElementIndex ei = 0; ei < ngMesh->GetNE(); ei++)
3660 Element el = (*ngMesh)[ei];
3661 outfile << "mesh.AddVolume([ ";
3662 for (int j = 0; j < el.GetNP(); j++)
3663 outfile << el[j] << ( j+1 < el.GetNP() ? ", " : " ])");
3667 for (int i = 1; i <= ngMesh->GetNSeg(); i++)
3669 const Segment & seg = ngMesh->LineSegment (i);
3670 outfile << "mesh.AddEdge([ "
3672 << seg[1] << " ])" << endl;
3674 cout << "Write " << pyFile << endl;
3677 //================================================================================
3679 * \brief Constructor of NETGENPlugin_ngMeshInfo
3681 //================================================================================
3683 NETGENPlugin_ngMeshInfo::NETGENPlugin_ngMeshInfo( netgen::Mesh* ngMesh,
3684 bool checkRemovedElems):
3685 _elementsRemoved( false ), _copyOfLocalH(0)
3689 _nbNodes = ngMesh->GetNP();
3690 _nbSegments = ngMesh->GetNSeg();
3691 _nbFaces = ngMesh->GetNSE();
3692 _nbVolumes = ngMesh->GetNE();
3694 if ( checkRemovedElems )
3695 for ( int i = 1; i <= ngMesh->GetNSE() && !_elementsRemoved; ++i )
3696 _elementsRemoved = ngMesh->SurfaceElement(i).IsDeleted();
3700 _nbNodes = _nbSegments = _nbFaces = _nbVolumes = 0;
3704 //================================================================================
3706 * \brief Copy LocalH member from one netgen mesh to another
3708 //================================================================================
3710 void NETGENPlugin_ngMeshInfo::transferLocalH( netgen::Mesh* fromMesh,
3711 netgen::Mesh* toMesh )
3713 if ( !fromMesh->LocalHFunctionGenerated() ) return;
3714 if ( !toMesh->LocalHFunctionGenerated() )
3716 toMesh->CalcLocalH(netgen::mparam.grading);
3718 toMesh->CalcLocalH();
3721 const size_t size = sizeof( netgen::LocalH );
3722 _copyOfLocalH = new char[ size ];
3723 memcpy( (void*)_copyOfLocalH, (void*)&toMesh->LocalHFunction(), size );
3724 memcpy( (void*)&toMesh->LocalHFunction(), (void*)&fromMesh->LocalHFunction(), size );
3727 //================================================================================
3729 * \brief Restore LocalH member of a netgen mesh
3731 //================================================================================
3733 void NETGENPlugin_ngMeshInfo::restoreLocalH( netgen::Mesh* toMesh )
3735 if ( _copyOfLocalH )
3737 const size_t size = sizeof( netgen::LocalH );
3738 memcpy( (void*)&toMesh->LocalHFunction(), (void*)_copyOfLocalH, size );
3739 delete [] _copyOfLocalH;
3744 //================================================================================
3746 * \brief Find "internal" sub-shapes
3748 //================================================================================
3750 NETGENPlugin_Internals::NETGENPlugin_Internals( SMESH_Mesh& mesh,
3751 const TopoDS_Shape& shape,
3753 : _mesh( mesh ), _is3D( is3D )
3755 SMESHDS_Mesh* meshDS = mesh.GetMeshDS();
3757 TopExp_Explorer f,e;
3758 for ( f.Init( shape, TopAbs_FACE ); f.More(); f.Next() )
3760 int faceID = meshDS->ShapeToIndex( f.Current() );
3762 // find not computed internal edges
3764 for ( e.Init( f.Current().Oriented(TopAbs_FORWARD), TopAbs_EDGE ); e.More(); e.Next() )
3765 if ( e.Current().Orientation() == TopAbs_INTERNAL )
3767 SMESH_subMesh* eSM = mesh.GetSubMesh( e.Current() );
3768 if ( eSM->IsEmpty() )
3770 _e2face.insert( make_pair( eSM->GetId(), faceID ));
3771 for ( TopoDS_Iterator v(e.Current()); v.More(); v.Next() )
3772 _e2face.insert( make_pair( meshDS->ShapeToIndex( v.Value() ), faceID ));
3776 // find internal vertices in a face
3777 set<int> intVV; // issue 0020850 where same vertex is twice in a face
3778 for ( TopoDS_Iterator fSub( f.Current() ); fSub.More(); fSub.Next())
3779 if ( fSub.Value().ShapeType() == TopAbs_VERTEX )
3781 int vID = meshDS->ShapeToIndex( fSub.Value() );
3782 if ( intVV.insert( vID ).second )
3783 _f2v[ faceID ].push_back( vID );
3788 // find internal faces and their subshapes where nodes are to be doubled
3789 // to make a crack with non-sewed borders
3791 if ( f.Current().Orientation() == TopAbs_INTERNAL )
3793 _intShapes.insert( meshDS->ShapeToIndex( f.Current() ));
3796 list< TopoDS_Shape > edges;
3797 for ( e.Init( f.Current(), TopAbs_EDGE ); e.More(); e.Next())
3798 if ( SMESH_MesherHelper::NbAncestors( e.Current(), mesh, TopAbs_FACE ) > 1 )
3800 _intShapes.insert( meshDS->ShapeToIndex( e.Current() ));
3801 edges.push_back( e.Current() );
3802 // find border faces
3803 PShapeIteratorPtr fIt =
3804 SMESH_MesherHelper::GetAncestors( edges.back(),mesh,TopAbs_FACE );
3805 while ( const TopoDS_Shape* pFace = fIt->next() )
3806 if ( !pFace->IsSame( f.Current() ))
3807 _borderFaces.insert( meshDS->ShapeToIndex( *pFace ));
3810 // we consider vertex internal if it is shared by more than one internal edge
3811 list< TopoDS_Shape >::iterator edge = edges.begin();
3812 for ( ; edge != edges.end(); ++edge )
3813 for ( TopoDS_Iterator v( *edge ); v.More(); v.Next() )
3815 set<int> internalEdges;
3816 PShapeIteratorPtr eIt =
3817 SMESH_MesherHelper::GetAncestors( v.Value(),mesh,TopAbs_EDGE );
3818 while ( const TopoDS_Shape* pEdge = eIt->next() )
3820 int edgeID = meshDS->ShapeToIndex( *pEdge );
3821 if ( isInternalShape( edgeID ))
3822 internalEdges.insert( edgeID );
3824 if ( internalEdges.size() > 1 )
3825 _intShapes.insert( meshDS->ShapeToIndex( v.Value() ));
3829 } // loop on geom faces
3831 // find vertices internal in solids
3834 for ( TopExp_Explorer so(shape, TopAbs_SOLID); so.More(); so.Next())
3836 int soID = meshDS->ShapeToIndex( so.Current() );
3837 for ( TopoDS_Iterator soSub( so.Current() ); soSub.More(); soSub.Next())
3838 if ( soSub.Value().ShapeType() == TopAbs_VERTEX )
3839 _s2v[ soID ].push_back( meshDS->ShapeToIndex( soSub.Value() ));
3844 //================================================================================
3846 * \brief Find mesh faces on non-internal geom faces sharing internal edge
3847 * some nodes of which are to be doubled to make the second border of the "crack"
3849 //================================================================================
3851 void NETGENPlugin_Internals::findBorderElements( TIDSortedElemSet & borderElems )
3853 if ( _intShapes.empty() ) return;
3855 SMESH_Mesh& mesh = const_cast<SMESH_Mesh&>(_mesh);
3856 SMESHDS_Mesh* meshDS = mesh.GetMeshDS();
3858 // loop on internal geom edges
3859 set<int>::const_iterator intShapeId = _intShapes.begin();
3860 for ( ; intShapeId != _intShapes.end(); ++intShapeId )
3862 const TopoDS_Shape& s = meshDS->IndexToShape( *intShapeId );
3863 if ( s.ShapeType() != TopAbs_EDGE ) continue;
3865 // get internal and non-internal geom faces sharing the internal edge <s>
3867 set<int>::iterator bordFace = _borderFaces.end();
3868 PShapeIteratorPtr faces = SMESH_MesherHelper::GetAncestors( s, _mesh, TopAbs_FACE );
3869 while ( const TopoDS_Shape* pFace = faces->next() )
3871 int faceID = meshDS->ShapeToIndex( *pFace );
3872 if ( isInternalShape( faceID ))
3875 bordFace = _borderFaces.insert( faceID ).first;
3877 if ( bordFace == _borderFaces.end() || !intFace ) continue;
3879 // get all links of mesh faces on internal geom face sharing nodes on edge <s>
3880 set< SMESH_OrientedLink > links; //!< links of faces on internal geom face
3881 list<const SMDS_MeshElement*> suspectFaces[2]; //!< mesh faces on border geom faces
3882 int nbSuspectFaces = 0;
3883 SMESHDS_SubMesh* intFaceSM = meshDS->MeshElements( intFace );
3884 if ( !intFaceSM || intFaceSM->NbElements() == 0 ) continue;
3885 SMESH_subMeshIteratorPtr smIt = mesh.GetSubMesh( s )->getDependsOnIterator(true,true);
3886 while ( smIt->more() )
3888 SMESHDS_SubMesh* sm = smIt->next()->GetSubMeshDS();
3889 if ( !sm ) continue;
3890 SMDS_NodeIteratorPtr nIt = sm->GetNodes();
3891 while ( nIt->more() )
3893 const SMDS_MeshNode* nOnEdge = nIt->next();
3894 SMDS_ElemIteratorPtr fIt = nOnEdge->GetInverseElementIterator(SMDSAbs_Face);
3895 while ( fIt->more() )
3897 const SMDS_MeshElement* f = fIt->next();
3898 const int nbNodes = f->NbCornerNodes();
3899 if ( intFaceSM->Contains( f ))
3901 for ( int i = 0; i < nbNodes; ++i )
3902 links.insert( SMESH_OrientedLink( f->GetNode(i), f->GetNode((i+1)%nbNodes)));
3907 for ( int i = 0; i < nbNodes; ++i )
3908 nbDblNodes += isInternalShape( f->GetNode(i)->getshapeId() );
3910 suspectFaces[ nbDblNodes < 2 ].push_back( f );
3916 // suspectFaces[0] having link with same orientation as mesh faces on
3917 // the internal geom face are <borderElems>. suspectFaces[1] have
3918 // only one node on edge <s>, we decide on them later (at the 2nd loop)
3919 // by links of <borderElems> found at the 1st and 2nd loops
3920 set< SMESH_OrientedLink > borderLinks;
3921 for ( int isPostponed = 0; isPostponed < 2; ++isPostponed )
3923 list<const SMDS_MeshElement*>::iterator fIt = suspectFaces[isPostponed].begin();
3924 for ( int nbF = 0; fIt != suspectFaces[isPostponed].end(); ++fIt, ++nbF )
3926 const SMDS_MeshElement* f = *fIt;
3927 bool isBorder = false, linkFound = false, borderLinkFound = false;
3928 list< SMESH_OrientedLink > faceLinks;
3929 int nbNodes = f->NbCornerNodes();
3930 for ( int i = 0; i < nbNodes; ++i )
3932 SMESH_OrientedLink link( f->GetNode(i), f->GetNode((i+1)%nbNodes));
3933 faceLinks.push_back( link );
3936 set< SMESH_OrientedLink >::iterator foundLink = links.find( link );
3937 if ( foundLink != links.end() )
3940 isBorder = ( foundLink->_reversed == link._reversed );
3941 if ( !isBorder && !isPostponed ) break;
3942 faceLinks.pop_back();
3944 else if ( isPostponed && !borderLinkFound )
3946 foundLink = borderLinks.find( link );
3947 if ( foundLink != borderLinks.end() )
3949 borderLinkFound = true;
3950 isBorder = ( foundLink->_reversed != link._reversed );
3957 borderElems.insert( f );
3958 borderLinks.insert( faceLinks.begin(), faceLinks.end() );
3960 else if ( !linkFound && !borderLinkFound )
3962 suspectFaces[1].push_back( f );
3963 if ( nbF > 2 * nbSuspectFaces )
3964 break; // dead loop protection
3971 //================================================================================
3973 * \brief put internal shapes in maps and fill in submeshes to precompute
3975 //================================================================================
3977 void NETGENPlugin_Internals::getInternalEdges( TopTools_IndexedMapOfShape& fmap,
3978 TopTools_IndexedMapOfShape& emap,
3979 TopTools_IndexedMapOfShape& vmap,
3980 list< SMESH_subMesh* > smToPrecompute[])
3982 if ( !hasInternalEdges() ) return;
3983 map<int,int>::const_iterator ev_face = _e2face.begin();
3984 for ( ; ev_face != _e2face.end(); ++ev_face )
3986 const TopoDS_Shape& ev = _mesh.GetMeshDS()->IndexToShape( ev_face->first );
3987 const TopoDS_Shape& face = _mesh.GetMeshDS()->IndexToShape( ev_face->second );
3989 ( ev.ShapeType() == TopAbs_EDGE ? emap : vmap ).Add( ev );
3991 //cout<<"INTERNAL EDGE or VERTEX "<<ev_face->first<<" on face "<<ev_face->second<<endl;
3993 smToPrecompute[ MeshDim_1D ].push_back( _mesh.GetSubMeshContaining( ev_face->first ));
3997 //================================================================================
3999 * \brief return shapes and submeshes to be meshed and already meshed boundary submeshes
4001 //================================================================================
4003 void NETGENPlugin_Internals::getInternalFaces( TopTools_IndexedMapOfShape& fmap,
4004 TopTools_IndexedMapOfShape& emap,
4005 list< SMESH_subMesh* >& intFaceSM,
4006 list< SMESH_subMesh* >& boundarySM)
4008 if ( !hasInternalFaces() ) return;
4010 // <fmap> and <emap> are for not yet meshed shapes
4011 // <intFaceSM> is for submeshes of faces
4012 // <boundarySM> is for meshed edges and vertices
4017 set<int> shapeIDs ( _intShapes );
4018 if ( !_borderFaces.empty() )
4019 shapeIDs.insert( _borderFaces.begin(), _borderFaces.end() );
4021 set<int>::const_iterator intS = shapeIDs.begin();
4022 for ( ; intS != shapeIDs.end(); ++intS )
4024 SMESH_subMesh* sm = _mesh.GetSubMeshContaining( *intS );
4026 if ( sm->GetSubShape().ShapeType() != TopAbs_FACE ) continue;
4028 intFaceSM.push_back( sm );
4030 // add submeshes of not computed internal faces
4031 if ( !sm->IsEmpty() ) continue;
4033 SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(true,true);
4034 while ( smIt->more() )
4037 const TopoDS_Shape& s = sm->GetSubShape();
4039 if ( sm->IsEmpty() )
4042 switch ( s.ShapeType() ) {
4043 case TopAbs_FACE: fmap.Add ( s ); break;
4044 case TopAbs_EDGE: emap.Add ( s ); break;
4050 if ( s.ShapeType() != TopAbs_FACE )
4051 boundarySM.push_back( sm );
4057 //================================================================================
4059 * \brief Return true if given shape is to be precomputed in order to be correctly
4060 * added to netgen mesh
4062 //================================================================================
4064 bool NETGENPlugin_Internals::isShapeToPrecompute(const TopoDS_Shape& s)
4066 int shapeID = _mesh.GetMeshDS()->ShapeToIndex( s );
4067 switch ( s.ShapeType() ) {
4068 case TopAbs_FACE : break; //return isInternalShape( shapeID ) || isBorderFace( shapeID );
4069 case TopAbs_EDGE : return isInternalEdge( shapeID );
4070 case TopAbs_VERTEX: break;
4076 //================================================================================
4078 * \brief Return SMESH
4080 //================================================================================
4082 SMESH_Mesh& NETGENPlugin_Internals::getMesh() const
4084 return const_cast<SMESH_Mesh&>( _mesh );
4087 //================================================================================
4089 * \brief Access to a counter of NETGENPlugin_NetgenLibWrapper instances
4091 //================================================================================
4093 int& NETGENPlugin_NetgenLibWrapper::instanceCounter()
4095 static int theCouner = 0;
4099 //================================================================================
4101 * \brief Initialize netgen library
4103 //================================================================================
4105 NETGENPlugin_NetgenLibWrapper::NETGENPlugin_NetgenLibWrapper()
4107 if ( instanceCounter() == 0 )
4110 ++instanceCounter();
4112 _isComputeOk = false;
4116 if ( !getenv( "KEEP_NETGEN_OUTPUT" ))
4118 // redirect all netgen output (mycout,myerr,cout) to _outputFileName
4119 _outputFileName = getOutputFileName();
4120 _ngcout = netgen::mycout;
4121 _ngcerr = netgen::myerr;
4122 netgen::mycout = new ofstream ( _outputFileName.c_str() );
4123 netgen::myerr = netgen::mycout;
4124 _coutBuffer = std::cout.rdbuf();
4126 cout << "NOTE: netgen output is redirected to file " << _outputFileName << endl;
4128 std::cout.rdbuf( netgen::mycout->rdbuf() );
4132 _ngMesh = Ng_NewMesh();
4135 //================================================================================
4137 * \brief Finish using netgen library
4139 //================================================================================
4141 NETGENPlugin_NetgenLibWrapper::~NETGENPlugin_NetgenLibWrapper()
4143 --instanceCounter();
4145 Ng_DeleteMesh( _ngMesh );
4149 std::cout.rdbuf( _coutBuffer );
4156 //================================================================================
4158 * \brief Set netgen mesh to delete at destruction
4160 //================================================================================
4162 void NETGENPlugin_NetgenLibWrapper::setMesh( Ng_Mesh* mesh )
4165 Ng_DeleteMesh( _ngMesh );
4169 //================================================================================
4171 * \brief Return a unique file name
4173 //================================================================================
4175 std::string NETGENPlugin_NetgenLibWrapper::getOutputFileName()
4177 std::string aTmpDir = SALOMEDS_Tool::GetTmpDir();
4179 TCollection_AsciiString aGenericName = (char*)aTmpDir.c_str();
4180 aGenericName += "NETGEN_";
4182 aGenericName += getpid();
4184 aGenericName += _getpid();
4186 aGenericName += "_";
4187 aGenericName += Abs((Standard_Integer)(long) aGenericName.ToCString());
4188 aGenericName += ".out";
4190 return aGenericName.ToCString();
4193 //================================================================================
4195 * \brief Remove "test.out" and "problemfaces" files in current directory
4197 //================================================================================
4199 void NETGENPlugin_NetgenLibWrapper::RemoveTmpFiles()
4201 bool rm = SMESH_File("test.out").remove() ;
4203 if ( rm && netgen::testout && instanceCounter() == 0 )
4205 delete netgen::testout;
4206 netgen::testout = 0;
4209 SMESH_File("problemfaces").remove();
4210 SMESH_File("occmesh.rep").remove();
4213 //================================================================================
4215 * \brief Remove file with netgen output
4217 //================================================================================
4219 void NETGENPlugin_NetgenLibWrapper::removeOutputFile()
4221 if ( !_outputFileName.empty() )
4225 delete netgen::mycout;
4226 netgen::mycout = _ngcout;
4227 netgen::myerr = _ngcerr;
4230 string tmpDir = SALOMEDS_Tool::GetDirFromPath ( _outputFileName );
4231 string aFileName = SALOMEDS_Tool::GetNameFromPath( _outputFileName ) + ".out";
4232 SALOMEDS::ListOfFileNames_var aFiles = new SALOMEDS::ListOfFileNames;
4234 aFiles[0] = aFileName.c_str();
4236 SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.c_str(), aFiles.in(), true );