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 <BRepAdaptor_Surface.hxx>
56 #include <BRepBuilderAPI_Copy.hxx>
57 #include <BRepLProp_SLProps.hxx>
58 #include <BRepMesh_IncrementalMesh.hxx>
59 #include <BRep_Builder.hxx>
60 #include <BRep_Tool.hxx>
61 #include <Bnd_B3d.hxx>
62 #include <GeomLib_IsPlanarSurface.hxx>
63 #include <NCollection_Map.hxx>
64 #include <Poly_Triangulation.hxx>
65 #include <Standard_ErrorHandler.hxx>
66 #include <Standard_ProgramError.hxx>
67 #include <TColStd_MapOfInteger.hxx>
69 #include <TopExp_Explorer.hxx>
70 #include <TopLoc_Location.hxx>
71 #include <TopTools_DataMapIteratorOfDataMapOfShapeInteger.hxx>
72 #include <TopTools_DataMapIteratorOfDataMapOfShapeShape.hxx>
73 #include <TopTools_DataMapOfShapeInteger.hxx>
74 #include <TopTools_DataMapOfShapeShape.hxx>
75 #include <TopTools_MapOfShape.hxx>
77 #include <TopoDS_Compound.hxx>
79 // Netgen include files
83 #include <occgeom.hpp>
84 #include <meshing.hpp>
85 //#include <ngexception.hpp>
88 extern int OCCGenerateMesh (OCCGeometry&, Mesh*&, MeshingParameters&, int, int);
90 extern int OCCGenerateMesh (OCCGeometry&, Mesh*&, int, int, char*);
92 //extern void OCCSetLocalMeshSize(OCCGeometry & geom, Mesh & mesh);
93 #if defined(NETGEN_V5) && defined(WIN32)
96 extern MeshingParameters mparam;
97 #if defined(NETGEN_V5) && defined(WIN32)
100 extern volatile multithreadt multithread;
102 #if defined(NETGEN_V5) && defined(WIN32)
105 extern bool merge_solids;
107 // values used for occgeo.facemeshstatus
108 enum EFaceMeshStatus { FACE_NOT_TREATED = 0,
120 using namespace nglib;
124 #define nodeVec_ACCESS(index) ((SMDS_MeshNode*) nodeVec.at((index)))
126 #define nodeVec_ACCESS(index) ((SMDS_MeshNode*) nodeVec[index])
129 #define NGPOINT_COORDS(p) p(0),p(1),p(2)
132 // dump elements added to ng mesh
133 //#define DUMP_SEGMENTS
134 //#define DUMP_TRIANGLES
135 //#define DUMP_TRIANGLES_SCRIPT "/tmp/trias.py" //!< debug AddIntVerticesInSolids()
138 TopTools_IndexedMapOfShape ShapesWithLocalSize;
139 std::map<int,double> VertexId2LocalSize;
140 std::map<int,double> EdgeId2LocalSize;
141 std::map<int,double> FaceId2LocalSize;
142 std::map<int,double> SolidId2LocalSize;
144 std::vector<SMESHUtils::ControlPnt> ControlPoints;
145 std::set<int> ShapesWithControlPoints; // <-- allows calling SetLocalSize() several times w/o recomputing ControlPoints
147 //=============================================================================
151 //=============================================================================
153 NETGENPlugin_Mesher::NETGENPlugin_Mesher (SMESH_Mesh* mesh,
154 const TopoDS_Shape& aShape,
160 _fineness(NETGENPlugin_Hypothesis::GetDefaultFineness()),
161 _isViscousLayers2D(false),
162 _chordalError(-1), // means disabled
169 _viscousLayersHyp(NULL),
172 SetDefaultParameters();
173 ShapesWithLocalSize.Clear();
174 VertexId2LocalSize.clear();
175 EdgeId2LocalSize.clear();
176 FaceId2LocalSize.clear();
177 SolidId2LocalSize.clear();
178 ControlPoints.clear();
179 ShapesWithControlPoints.clear();
182 //================================================================================
186 //================================================================================
188 NETGENPlugin_Mesher::~NETGENPlugin_Mesher()
196 //================================================================================
198 * Set pointer to NETGENPlugin_Mesher* field of the holder, that will be
199 * nullified at destruction of this
201 //================================================================================
203 void NETGENPlugin_Mesher::SetSelfPointer( NETGENPlugin_Mesher ** ptr )
214 //================================================================================
216 * \brief Initialize global NETGEN parameters with default values
218 //================================================================================
220 void NETGENPlugin_Mesher::SetDefaultParameters()
222 netgen::MeshingParameters& mparams = netgen::mparam;
223 // maximal mesh edge size
224 mparams.maxh = 0;//NETGENPlugin_Hypothesis::GetDefaultMaxSize();
226 // minimal number of segments per edge
227 mparams.segmentsperedge = NETGENPlugin_Hypothesis::GetDefaultNbSegPerEdge();
228 // rate of growth of size between elements
229 mparams.grading = NETGENPlugin_Hypothesis::GetDefaultGrowthRate();
230 // safety factor for curvatures (elements per radius)
231 mparams.curvaturesafety = NETGENPlugin_Hypothesis::GetDefaultNbSegPerRadius();
232 // create elements of second order
233 mparams.secondorder = NETGENPlugin_Hypothesis::GetDefaultSecondOrder();
234 // quad-dominated surface meshing
238 mparams.quad = NETGENPlugin_Hypothesis_2D::GetDefaultQuadAllowed();
239 _fineness = NETGENPlugin_Hypothesis::GetDefaultFineness();
240 mparams.uselocalh = NETGENPlugin_Hypothesis::GetDefaultSurfaceCurvature();
241 netgen::merge_solids = NETGENPlugin_Hypothesis::GetDefaultFuseEdges();
244 //=============================================================================
248 //=============================================================================
250 void SetLocalSize(TopoDS_Shape GeomShape, double LocalSize)
252 if ( GeomShape.IsNull() ) return;
253 TopAbs_ShapeEnum GeomType = GeomShape.ShapeType();
254 if (GeomType == TopAbs_COMPOUND) {
255 for (TopoDS_Iterator it (GeomShape); it.More(); it.Next()) {
256 SetLocalSize(it.Value(), LocalSize);
261 if (! ShapesWithLocalSize.Contains(GeomShape))
262 key = ShapesWithLocalSize.Add(GeomShape);
264 key = ShapesWithLocalSize.FindIndex(GeomShape);
265 if (GeomType == TopAbs_VERTEX) {
266 VertexId2LocalSize[key] = LocalSize;
267 } else if (GeomType == TopAbs_EDGE) {
268 EdgeId2LocalSize[key] = LocalSize;
269 } else if (GeomType == TopAbs_FACE) {
270 FaceId2LocalSize[key] = LocalSize;
271 } else if (GeomType == TopAbs_SOLID) {
272 SolidId2LocalSize[key] = LocalSize;
276 //=============================================================================
278 * Pass parameters to NETGEN
280 //=============================================================================
281 void NETGENPlugin_Mesher::SetParameters(const NETGENPlugin_Hypothesis* hyp)
285 netgen::MeshingParameters& mparams = netgen::mparam;
286 // Initialize global NETGEN parameters:
287 // maximal mesh segment size
288 mparams.maxh = hyp->GetMaxSize();
289 // maximal mesh element linear size
290 mparams.minh = hyp->GetMinSize();
291 // minimal number of segments per edge
292 mparams.segmentsperedge = hyp->GetNbSegPerEdge();
293 // rate of growth of size between elements
294 mparams.grading = hyp->GetGrowthRate();
295 // safety factor for curvatures (elements per radius)
296 mparams.curvaturesafety = hyp->GetNbSegPerRadius();
297 // create elements of second order
298 mparams.secondorder = hyp->GetSecondOrder() ? 1 : 0;
299 // quad-dominated surface meshing
300 mparams.quad = hyp->GetQuadAllowed() ? 1 : 0;
301 _optimize = hyp->GetOptimize();
302 _fineness = hyp->GetFineness();
303 mparams.uselocalh = hyp->GetSurfaceCurvature();
304 netgen::merge_solids = hyp->GetFuseEdges();
305 _chordalError = hyp->GetChordalErrorEnabled() ? hyp->GetChordalError() : -1.;
308 mparams.meshsizefilename= hyp->GetMeshSizeFile().empty() ? 0 : hyp->GetMeshSizeFile().c_str();
310 const NETGENPlugin_Hypothesis::TLocalSize& localSizes = hyp->GetLocalSizesAndEntries();
311 if ( !localSizes.empty() )
313 SMESH_Gen_i* smeshGen_i = SMESH_Gen_i::GetSMESHGen();
314 NETGENPlugin_Hypothesis::TLocalSize::const_iterator it = localSizes.begin();
315 for ( ; it != localSizes.end() ; it++)
317 std::string entry = (*it).first;
318 double val = (*it).second;
320 GEOM::GEOM_Object_var aGeomObj;
321 SALOMEDS::SObject_var aSObj = SMESH_Gen_i::getStudyServant()->FindObjectID( entry.c_str() );
322 if ( !aSObj->_is_nil() ) {
323 CORBA::Object_var obj = aSObj->GetObject();
324 aGeomObj = GEOM::GEOM_Object::_narrow(obj);
327 TopoDS_Shape S = smeshGen_i->GeomObjectToShape( aGeomObj.in() );
328 ::SetLocalSize(S, val);
334 //=============================================================================
336 * Pass simple parameters to NETGEN
338 //=============================================================================
340 void NETGENPlugin_Mesher::SetParameters(const NETGENPlugin_SimpleHypothesis_2D* hyp)
344 SetDefaultParameters();
347 //================================================================================
349 * \brief Store a Viscous Layers hypothesis
351 //================================================================================
353 void NETGENPlugin_Mesher::SetParameters(const StdMeshers_ViscousLayers* hyp )
355 _viscousLayersHyp = hyp;
358 //=============================================================================
360 * Link - a pair of integer numbers
362 //=============================================================================
366 Link(int _n1, int _n2) : n1(_n1), n2(_n2) {}
367 Link() : n1(0), n2(0) {}
368 bool Contains( int n ) const { return n == n1 || n == n2; }
369 bool IsConnected( const Link& other ) const
371 return (( Contains( other.n1 ) || Contains( other.n2 )) && ( this != &other ));
375 int HashCode(const Link& aLink, int aLimit)
377 return HashCode(aLink.n1 + aLink.n2, aLimit);
380 Standard_Boolean IsEqual(const Link& aLink1, const Link& aLink2)
382 return (( aLink1.n1 == aLink2.n1 && aLink1.n2 == aLink2.n2 ) ||
383 ( aLink1.n1 == aLink2.n2 && aLink1.n2 == aLink2.n1 ));
388 //================================================================================
390 * \brief return id of netgen point corresponding to SMDS node
392 //================================================================================
393 typedef map< const SMDS_MeshNode*, int > TNode2IdMap;
395 int ngNodeId( const SMDS_MeshNode* node,
396 netgen::Mesh& ngMesh,
397 TNode2IdMap& nodeNgIdMap)
399 int newNgId = ngMesh.GetNP() + 1;
401 TNode2IdMap::iterator node_id = nodeNgIdMap.insert( make_pair( node, newNgId )).first;
403 if ( node_id->second == newNgId)
405 #if defined(DUMP_SEGMENTS) || defined(DUMP_TRIANGLES)
406 cout << "Ng " << newNgId << " - " << node;
408 netgen::MeshPoint p( netgen::Point<3> (node->X(), node->Y(), node->Z()) );
409 ngMesh.AddPoint( p );
411 return node_id->second;
414 //================================================================================
416 * \brief Return computed EDGEs connected to the given one
418 //================================================================================
420 list< TopoDS_Edge > getConnectedEdges( const TopoDS_Edge& edge,
421 const TopoDS_Face& face,
422 const set< SMESH_subMesh* > & computedSM,
423 const SMESH_MesherHelper& helper,
424 map< SMESH_subMesh*, set< int > >& addedEdgeSM2Faces)
427 list< TopoDS_Edge > edges;
428 list< int > nbEdgesInWire;
429 /*int nbWires =*/ SMESH_Block::GetOrderedEdges( face, edges, nbEdgesInWire);
431 // find <edge> within <edges>
432 list< TopoDS_Edge >::iterator eItFwd = edges.begin();
433 for ( ; eItFwd != edges.end(); ++eItFwd )
434 if ( edge.IsSame( *eItFwd ))
436 if ( eItFwd == edges.end()) return list< TopoDS_Edge>();
438 if ( eItFwd->Orientation() >= TopAbs_INTERNAL )
440 // connected INTERNAL edges returned from GetOrderedEdges() are wrongly oriented
441 // so treat each INTERNAL edge separately
442 TopoDS_Edge e = *eItFwd;
444 edges.push_back( e );
448 // get all computed EDGEs connected to <edge>
450 list< TopoDS_Edge >::iterator eItBack = eItFwd, ePrev;
451 TopoDS_Vertex vCommon;
452 TopTools_MapOfShape eAdded; // map used not to add a seam edge twice to <edges>
455 // put edges before <edge> to <edges> back
456 while ( edges.begin() != eItFwd )
457 edges.splice( edges.end(), edges, edges.begin() );
461 while ( ++eItFwd != edges.end() )
463 SMESH_subMesh* sm = helper.GetMesh()->GetSubMesh( *eItFwd );
465 bool connected = TopExp::CommonVertex( *ePrev, *eItFwd, vCommon );
466 bool computed = sm->IsMeshComputed();
467 bool added = addedEdgeSM2Faces[ sm ].count( helper.GetSubShapeID() );
468 bool doubled = !eAdded.Add( *eItFwd );
469 bool orientOK = (( ePrev ->Orientation() < TopAbs_INTERNAL ) ==
470 ( eItFwd->Orientation() < TopAbs_INTERNAL ) );
471 if ( !connected || !computed || !orientOK || added || doubled )
473 // stop advancement; move edges from tail to head
474 while ( edges.back() != *ePrev )
475 edges.splice( edges.begin(), edges, --edges.end() );
481 while ( eItBack != edges.begin() )
485 SMESH_subMesh* sm = helper.GetMesh()->GetSubMesh( *eItBack );
487 bool connected = TopExp::CommonVertex( *ePrev, *eItBack, vCommon );
488 bool computed = sm->IsMeshComputed();
489 bool added = addedEdgeSM2Faces[ sm ].count( helper.GetSubShapeID() );
490 bool doubled = !eAdded.Add( *eItBack );
491 bool orientOK = (( ePrev ->Orientation() < TopAbs_INTERNAL ) ==
492 ( eItBack->Orientation() < TopAbs_INTERNAL ) );
493 if ( !connected || !computed || !orientOK || added || doubled)
496 edges.erase( edges.begin(), ePrev );
500 if ( edges.front() != edges.back() )
502 // assure that the 1st vertex is meshed
503 TopoDS_Edge eLast = edges.back();
504 while ( !SMESH_Algo::VertexNode( SMESH_MesherHelper::IthVertex( 0, edges.front()), helper.GetMeshDS())
506 edges.front() != eLast )
507 edges.splice( edges.end(), edges, edges.begin() );
512 //================================================================================
514 * \brief Make triangulation of a shape precise enough
516 //================================================================================
518 void updateTriangulation( const TopoDS_Shape& shape )
520 // static set< Poly_Triangulation* > updated;
522 // TopLoc_Location loc;
523 // TopExp_Explorer fExp( shape, TopAbs_FACE );
524 // for ( ; fExp.More(); fExp.Next() )
526 // Handle(Poly_Triangulation) triangulation =
527 // BRep_Tool::Triangulation ( TopoDS::Face( fExp.Current() ), loc);
528 // if ( triangulation.IsNull() ||
529 // updated.insert( triangulation.operator->() ).second )
531 // BRepTools::Clean (shape);
534 BRepMesh_IncrementalMesh e(shape, 0.01, true);
536 catch (Standard_Failure)
539 // updated.erase( triangulation.operator->() );
540 // triangulation = BRep_Tool::Triangulation ( TopoDS::Face( fExp.Current() ), loc);
541 // updated.insert( triangulation.operator->() );
545 //================================================================================
547 * \brief Returns a medium node either existing in SMESH of created by NETGEN
548 * \param [in] corner1 - corner node 1
549 * \param [in] corner2 - corner node 2
550 * \param [in] defaultMedium - the node created by NETGEN
551 * \param [in] helper - holder of medium nodes existing in SMESH
552 * \return const SMDS_MeshNode* - the result node
554 //================================================================================
556 const SMDS_MeshNode* mediumNode( const SMDS_MeshNode* corner1,
557 const SMDS_MeshNode* corner2,
558 const SMDS_MeshNode* defaultMedium,
559 const SMESH_MesherHelper* helper)
563 TLinkNodeMap::const_iterator l2n =
564 helper->GetTLinkNodeMap().find( SMESH_TLink( corner1, corner2 ));
565 if ( l2n != helper->GetTLinkNodeMap().end() )
566 defaultMedium = l2n->second;
568 return defaultMedium;
571 //================================================================================
573 * \brief Assure that mesh on given shapes is quadratic
575 //================================================================================
577 // void makeQuadratic( const TopTools_IndexedMapOfShape& shapes,
578 // SMESH_Mesh* mesh )
580 // for ( int i = 1; i <= shapes.Extent(); ++i )
582 // SMESHDS_SubMesh* smDS = mesh->GetMeshDS()->MeshElements( shapes(i) );
583 // if ( !smDS ) continue;
584 // SMDS_ElemIteratorPtr elemIt = smDS->GetElements();
585 // if ( !elemIt->more() ) continue;
586 // const SMDS_MeshElement* e = elemIt->next();
587 // if ( !e || e->IsQuadratic() )
590 // TIDSortedElemSet elems;
591 // elems.insert( e );
592 // while ( elemIt->more() )
593 // elems.insert( elems.end(), elemIt->next() );
595 // SMESH_MeshEditor( mesh ).ConvertToQuadratic( /*3d=*/false, elems, /*biQuad=*/false );
599 //================================================================================
601 * \brief Restrict size of elements on the given edge
603 //================================================================================
605 void setLocalSize(const TopoDS_Edge& edge,
608 const bool overrideMinH = true)
610 if ( size <= std::numeric_limits<double>::min() )
612 Standard_Real u1, u2;
613 Handle(Geom_Curve) curve = BRep_Tool::Curve(edge, u1, u2);
614 if ( curve.IsNull() )
616 TopoDS_Iterator vIt( edge );
617 if ( !vIt.More() ) return;
618 gp_Pnt p = BRep_Tool::Pnt( TopoDS::Vertex( vIt.Value() ));
619 NETGENPlugin_Mesher::RestrictLocalSize( mesh, p.XYZ(), size, overrideMinH );
623 const int nb = (int)( 1.5 * SMESH_Algo::EdgeLength( edge ) / size );
624 Standard_Real delta = (u2-u1)/nb;
625 for(int i=0; i<nb; i++)
627 Standard_Real u = u1 + delta*i;
628 gp_Pnt p = curve->Value(u);
629 NETGENPlugin_Mesher::RestrictLocalSize( mesh, p.XYZ(), size, overrideMinH );
630 netgen::Point3d pi(p.X(), p.Y(), p.Z());
631 double resultSize = mesh.GetH(pi);
632 if ( resultSize - size > 0.1*size )
633 // netgen does restriction iff oldH/newH > 1.2 (localh.cpp:136)
634 NETGENPlugin_Mesher::RestrictLocalSize( mesh, p.XYZ(), resultSize/1.201, overrideMinH );
639 //================================================================================
641 * \brief Return triangle size for a given chordalError and radius of curvature
643 //================================================================================
645 double elemSizeForChordalError( double chordalError, double radius )
647 if ( 2 * radius < chordalError )
649 return Sqrt( 3 ) * Sqrt( chordalError * ( 2 * radius - chordalError ));
654 //================================================================================
656 * \brief Set local size on shapes defined by SetParameters()
658 //================================================================================
660 void NETGENPlugin_Mesher::SetLocalSize( netgen::OCCGeometry& occgeo,
661 netgen::Mesh& ngMesh)
664 std::map<int,double>::const_iterator it;
665 for( it=EdgeId2LocalSize.begin(); it!=EdgeId2LocalSize.end(); it++)
667 int key = (*it).first;
668 double hi = (*it).second;
669 const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
670 setLocalSize( TopoDS::Edge(shape), hi, ngMesh );
673 for(it=VertexId2LocalSize.begin(); it!=VertexId2LocalSize.end(); it++)
675 int key = (*it).first;
676 double hi = (*it).second;
677 const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
678 gp_Pnt p = BRep_Tool::Pnt( TopoDS::Vertex(shape) );
679 NETGENPlugin_Mesher::RestrictLocalSize( ngMesh, p.XYZ(), hi );
682 for(it=FaceId2LocalSize.begin(); it!=FaceId2LocalSize.end(); it++)
684 int key = (*it).first;
685 double val = (*it).second;
686 const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
687 int faceNgID = occgeo.fmap.FindIndex(shape);
690 occgeo.SetFaceMaxH(faceNgID, val);
691 for ( TopExp_Explorer edgeExp( shape, TopAbs_EDGE ); edgeExp.More(); edgeExp.Next() )
692 setLocalSize( TopoDS::Edge( edgeExp.Current() ), val, ngMesh );
694 else if ( !ShapesWithControlPoints.count( key ))
696 SMESHUtils::createPointsSampleFromFace( TopoDS::Face( shape ), val, ControlPoints );
697 ShapesWithControlPoints.insert( key );
701 for(it=SolidId2LocalSize.begin(); it!=SolidId2LocalSize.end(); it++)
703 int key = (*it).first;
704 double val = (*it).second;
705 if ( !ShapesWithControlPoints.count( key ))
707 const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
708 SMESHUtils::createPointsSampleFromSolid( TopoDS::Solid( shape ), val, ControlPoints );
709 ShapesWithControlPoints.insert( key );
713 if ( !ControlPoints.empty() )
715 for ( size_t i = 0; i < ControlPoints.size(); ++i )
716 NETGENPlugin_Mesher::RestrictLocalSize( ngMesh, ControlPoints[i].XYZ(), ControlPoints[i].Size() );
721 //================================================================================
723 * \brief Restrict local size to achieve a required _chordalError
725 //================================================================================
727 void NETGENPlugin_Mesher::SetLocalSizeForChordalError( netgen::OCCGeometry& occgeo,
728 netgen::Mesh& ngMesh)
730 if ( _chordalError <= 0. )
734 BRepLProp_SLProps surfProp( 2, 1e-6 );
735 const double sizeCoef = 0.95;
737 // find non-planar FACEs with non-constant curvature
738 std::vector<int> fInd;
739 for ( int i = 1; i <= occgeo.fmap.Extent(); ++i )
741 const TopoDS_Face& face = TopoDS::Face( occgeo.fmap( i ));
742 BRepAdaptor_Surface surfAd( face, false );
743 switch ( surfAd.GetType() )
747 case GeomAbs_Cylinder:
749 case GeomAbs_Torus: // constant curvature
751 surfProp.SetSurface( surfAd );
752 surfProp.SetParameters( 0, 0 );
753 double maxCurv = Max( Abs( surfProp.MaxCurvature()), Abs( surfProp.MinCurvature() ));
754 double size = elemSizeForChordalError( _chordalError, 1 / maxCurv );
755 occgeo.SetFaceMaxH( i, size * sizeCoef );
756 // limit size one edges
757 TopTools_MapOfShape edgeMap;
758 for ( TopExp_Explorer eExp( face, TopAbs_EDGE ); eExp.More(); eExp.Next() )
759 if ( edgeMap.Add( eExp.Current() ))
760 setLocalSize( TopoDS::Edge( eExp.Current() ), size, ngMesh, /*overrideMinH=*/false );
764 Handle(Geom_Surface) surf = BRep_Tool::Surface( face, loc );
765 if ( GeomLib_IsPlanarSurface( surf ).IsPlanar() )
774 TopoDS_Compound allFacesComp;
775 b.MakeCompound( allFacesComp );
776 for ( size_t i = 0; i < fInd.size(); ++i )
777 b.Add( allFacesComp, occgeo.fmap( fInd[i] ));
779 // copy the shape to avoid spoiling its triangulation
780 TopoDS_Shape allFacesCompCopy = BRepBuilderAPI_Copy( allFacesComp );
782 // create triangulation with desired chordal error
783 BRepMesh_IncrementalMesh( allFacesCompCopy,
785 /*isRelative = */Standard_False,
786 /*theAngDeflection = */ 0.5,
787 /*isInParallel = */Standard_True);
790 for ( TopExp_Explorer fExp( allFacesCompCopy, TopAbs_FACE ); fExp.More(); fExp.Next() )
792 const TopoDS_Face& face = TopoDS::Face( fExp.Current() );
793 Handle(Poly_Triangulation) triangulation = BRep_Tool::Triangulation ( face, loc );
794 if ( triangulation.IsNull() ) continue;
796 BRepAdaptor_Surface surf( face, false );
797 surfProp.SetSurface( surf );
802 for ( int i = 1; i <= triangulation->NbTriangles(); ++i )
804 Standard_Integer n1,n2,n3;
805 triangulation->Triangles()(i).Get( n1,n2,n3 );
806 p [0] = triangulation->Nodes()(n1).Transformed(loc).XYZ();
807 p [1] = triangulation->Nodes()(n2).Transformed(loc).XYZ();
808 p [2] = triangulation->Nodes()(n3).Transformed(loc).XYZ();
809 uv[0] = triangulation->UVNodes()(n1).XY();
810 uv[1] = triangulation->UVNodes()(n2).XY();
811 uv[2] = triangulation->UVNodes()(n3).XY();
812 surfProp.SetParameters( uv[0].X(), uv[0].Y() );
813 if ( !surfProp.IsCurvatureDefined() )
816 for ( int n = 0; n < 3; ++n ) // get size at triangle nodes
818 surfProp.SetParameters( uv[n].X(), uv[n].Y() );
819 double maxCurv = Max( Abs( surfProp.MaxCurvature()), Abs( surfProp.MinCurvature() ));
820 size[n] = elemSizeForChordalError( _chordalError, 1 / maxCurv );
822 for ( int n1 = 0; n1 < 3; ++n1 ) // limit size along each triangle edge
824 int n2 = ( n1 + 1 ) % 3;
825 double minSize = size[n1], maxSize = size[n2];
826 if ( size[n1] > size[n2] )
827 minSize = size[n2], maxSize = size[n1];
829 if ( maxSize / minSize < 1.2 ) // netgen ignores size difference < 1.2
831 ngMesh.RestrictLocalHLine ( netgen::Point3d( p[n1].X(), p[n1].Y(), p[n1].Z() ),
832 netgen::Point3d( p[n2].X(), p[n2].Y(), p[n2].Z() ),
833 sizeCoef * minSize );
837 gp_XY uvVec( uv[n2] - uv[n1] );
838 double len = ( p[n1] - p[n2] ).Modulus();
839 int nb = int( len / minSize ) + 1;
840 for ( int j = 0; j <= nb; ++j )
842 double r = double( j ) / nb;
843 gp_XY uvj = uv[n1] + r * uvVec;
845 surfProp.SetParameters( uvj.X(), uvj.Y() );
846 double maxCurv = Max( Abs( surfProp.MaxCurvature()), Abs( surfProp.MinCurvature() ));
847 double h = elemSizeForChordalError( _chordalError, 1 / maxCurv );
849 const gp_Pnt& pj = surfProp.Value();
850 netgen::Point3d ngP( pj.X(), pj.Y(), pj.Z());
851 ngMesh.RestrictLocalH( ngP, h * sizeCoef );
860 //================================================================================
862 * \brief Initialize netgen::OCCGeometry with OCCT shape
864 //================================================================================
866 void NETGENPlugin_Mesher::PrepareOCCgeometry(netgen::OCCGeometry& occgeo,
867 const TopoDS_Shape& shape,
869 list< SMESH_subMesh* > * meshedSM,
870 NETGENPlugin_Internals* intern)
872 updateTriangulation( shape );
875 BRepBndLib::Add (shape, bb);
876 double x1,y1,z1,x2,y2,z2;
877 bb.Get (x1,y1,z1,x2,y2,z2);
878 netgen::Point<3> p1 = netgen::Point<3> (x1,y1,z1);
879 netgen::Point<3> p2 = netgen::Point<3> (x2,y2,z2);
880 occgeo.boundingbox = netgen::Box<3> (p1,p2);
882 occgeo.shape = shape;
885 // fill maps of shapes of occgeo with not yet meshed subshapes
887 // get root submeshes
888 list< SMESH_subMesh* > rootSM;
889 const int shapeID = mesh.GetMeshDS()->ShapeToIndex( shape );
890 if ( shapeID > 0 ) { // SMESH_subMesh with ID 0 may exist, don't use it!
891 rootSM.push_back( mesh.GetSubMesh( shape ));
894 for ( TopoDS_Iterator it( shape ); it.More(); it.Next() )
895 rootSM.push_back( mesh.GetSubMesh( it.Value() ));
900 // add subshapes of empty submeshes
901 list< SMESH_subMesh* >::iterator rootIt = rootSM.begin(), rootEnd = rootSM.end();
902 for ( ; rootIt != rootEnd; ++rootIt ) {
903 SMESH_subMesh * root = *rootIt;
904 SMESH_subMeshIteratorPtr smIt = root->getDependsOnIterator(/*includeSelf=*/true,
905 /*complexShapeFirst=*/true);
906 // to find a right orientation of subshapes (PAL20462)
907 TopTools_IndexedMapOfShape subShapes;
908 TopExp::MapShapes(root->GetSubShape(), subShapes);
909 while ( smIt->more() )
911 SMESH_subMesh* sm = smIt->next();
912 TopoDS_Shape shape = sm->GetSubShape();
913 totNbFaces += ( shape.ShapeType() == TopAbs_FACE );
914 if ( intern && intern->isShapeToPrecompute( shape ))
916 if ( !meshedSM || sm->IsEmpty() )
918 if ( shape.ShapeType() != TopAbs_VERTEX )
919 shape = subShapes( subShapes.FindIndex( shape ));// shape -> index -> oriented shape
920 if ( shape.Orientation() >= TopAbs_INTERNAL )
921 shape.Orientation( TopAbs_FORWARD ); // isuue 0020676
922 switch ( shape.ShapeType() ) {
923 case TopAbs_FACE : occgeo.fmap.Add( shape ); break;
924 case TopAbs_EDGE : occgeo.emap.Add( shape ); break;
925 case TopAbs_VERTEX: occgeo.vmap.Add( shape ); break;
926 case TopAbs_SOLID :occgeo.somap.Add( shape ); break;
930 // collect submeshes of meshed shapes
933 const int dim = SMESH_Gen::GetShapeDim( shape );
934 meshedSM[ dim ].push_back( sm );
938 occgeo.facemeshstatus.SetSize (totNbFaces);
939 occgeo.facemeshstatus = 0;
940 occgeo.face_maxh_modified.SetSize(totNbFaces);
941 occgeo.face_maxh_modified = 0;
942 occgeo.face_maxh.SetSize(totNbFaces);
943 occgeo.face_maxh = netgen::mparam.maxh;
946 //================================================================================
948 * \brief Return a default min size value suitable for the given geometry.
950 //================================================================================
952 double NETGENPlugin_Mesher::GetDefaultMinSize(const TopoDS_Shape& geom,
953 const double maxSize)
955 updateTriangulation( geom );
959 const int* pi[4] = { &i1, &i2, &i3, &i1 };
962 TopExp_Explorer fExp( geom, TopAbs_FACE );
963 for ( ; fExp.More(); fExp.Next() )
965 Handle(Poly_Triangulation) triangulation =
966 BRep_Tool::Triangulation ( TopoDS::Face( fExp.Current() ), loc);
967 if ( triangulation.IsNull() ) continue;
968 const double fTol = BRep_Tool::Tolerance( TopoDS::Face( fExp.Current() ));
969 const TColgp_Array1OfPnt& points = triangulation->Nodes();
970 const Poly_Array1OfTriangle& trias = triangulation->Triangles();
971 for ( int iT = trias.Lower(); iT <= trias.Upper(); ++iT )
973 trias(iT).Get( i1, i2, i3 );
974 for ( int j = 0; j < 3; ++j )
976 double dist2 = points(*pi[j]).SquareDistance( points( *pi[j+1] ));
977 if ( dist2 < minh && fTol*fTol < dist2 )
979 bb.Add( points(*pi[j]));
983 if ( minh > 0.25 * bb.SquareExtent() ) // simple geometry, rough triangulation
985 minh = 1e-3 * sqrt( bb.SquareExtent());
986 //cout << "BND BOX minh = " <<minh << endl;
990 minh = sqrt( minh ); // triangulation for visualization is rather fine
991 //cout << "TRIANGULATION minh = " <<minh << endl;
993 if ( minh > 0.5 * maxSize )
999 //================================================================================
1001 * \brief Restrict size of elements at a given point
1003 //================================================================================
1005 void NETGENPlugin_Mesher::RestrictLocalSize(netgen::Mesh& ngMesh,
1008 const bool overrideMinH)
1010 if ( size <= std::numeric_limits<double>::min() )
1012 if ( netgen::mparam.minh > size )
1016 ngMesh.SetMinimalH( size );
1017 netgen::mparam.minh = size;
1021 size = netgen::mparam.minh;
1024 netgen::Point3d pi(p.X(), p.Y(), p.Z());
1025 ngMesh.RestrictLocalH( pi, size );
1028 //================================================================================
1030 * \brief fill ngMesh with nodes and elements of computed submeshes
1032 //================================================================================
1034 bool NETGENPlugin_Mesher::FillNgMesh(netgen::OCCGeometry& occgeom,
1035 netgen::Mesh& ngMesh,
1036 vector<const SMDS_MeshNode*>& nodeVec,
1037 const list< SMESH_subMesh* > & meshedSM,
1038 SMESH_MesherHelper* quadHelper,
1039 SMESH_ProxyMesh::Ptr proxyMesh)
1041 TNode2IdMap nodeNgIdMap;
1042 for ( size_t i = 1; i < nodeVec.size(); ++i )
1043 nodeNgIdMap.insert( make_pair( nodeVec[i], i ));
1045 TopTools_MapOfShape visitedShapes;
1046 map< SMESH_subMesh*, set< int > > visitedEdgeSM2Faces;
1047 set< SMESH_subMesh* > computedSM( meshedSM.begin(), meshedSM.end() );
1049 SMESH_MesherHelper helper (*_mesh);
1051 int faceNgID = ngMesh.GetNFD();
1053 list< SMESH_subMesh* >::const_iterator smIt, smEnd = meshedSM.end();
1054 for ( smIt = meshedSM.begin(); smIt != smEnd; ++smIt )
1056 SMESH_subMesh* sm = *smIt;
1057 if ( !visitedShapes.Add( sm->GetSubShape() ))
1060 const SMESHDS_SubMesh * smDS = sm->GetSubMeshDS();
1061 if ( !smDS ) continue;
1063 switch ( sm->GetSubShape().ShapeType() )
1065 case TopAbs_EDGE: { // EDGE
1066 // ----------------------
1067 TopoDS_Edge geomEdge = TopoDS::Edge( sm->GetSubShape() );
1068 if ( geomEdge.Orientation() >= TopAbs_INTERNAL )
1069 geomEdge.Orientation( TopAbs_FORWARD ); // issue 0020676
1071 // Add ng segments for each not meshed FACE the EDGE bounds
1072 PShapeIteratorPtr fIt = helper.GetAncestors( geomEdge, *sm->GetFather(), TopAbs_FACE );
1073 while ( const TopoDS_Shape * anc = fIt->next() )
1075 faceNgID = occgeom.fmap.FindIndex( *anc );
1077 continue; // meshed face
1079 int faceSMDSId = helper.GetMeshDS()->ShapeToIndex( *anc );
1080 if ( visitedEdgeSM2Faces[ sm ].count( faceSMDSId ))
1081 continue; // already treated EDGE
1083 TopoDS_Face face = TopoDS::Face( occgeom.fmap( faceNgID ));
1084 if ( face.Orientation() >= TopAbs_INTERNAL )
1085 face.Orientation( TopAbs_FORWARD ); // issue 0020676
1087 // get all meshed EDGEs of the FACE connected to geomEdge (issue 0021140)
1088 helper.SetSubShape( face );
1089 list< TopoDS_Edge > edges = getConnectedEdges( geomEdge, face, computedSM, helper,
1090 visitedEdgeSM2Faces );
1091 if ( edges.empty() )
1092 continue; // wrong ancestor?
1094 // find out orientation of <edges> within <face>
1095 TopoDS_Edge eNotSeam = edges.front();
1096 if ( helper.HasSeam() )
1098 list< TopoDS_Edge >::iterator eIt = edges.begin();
1099 while ( helper.IsRealSeam( *eIt )) ++eIt;
1100 if ( eIt != edges.end() )
1103 TopAbs_Orientation fOri = helper.GetSubShapeOri( face, eNotSeam );
1104 bool isForwad = ( fOri == eNotSeam.Orientation() || fOri >= TopAbs_INTERNAL );
1106 // get all nodes from connected <edges>
1107 const bool isQuad = smDS->IsQuadratic();
1108 StdMeshers_FaceSide fSide( face, edges, _mesh, isForwad, isQuad, &helper );
1109 const vector<UVPtStruct>& points = fSide.GetUVPtStruct();
1110 if ( points.empty() )
1111 return false; // invalid node params?
1112 int i, nbSeg = fSide.NbSegments();
1114 // remember EDGEs of fSide to treat only once
1115 for ( int iE = 0; iE < fSide.NbEdges(); ++iE )
1116 visitedEdgeSM2Faces[ helper.GetMesh()->GetSubMesh( fSide.Edge(iE )) ].insert(faceSMDSId);
1118 double otherSeamParam = 0;
1119 bool isSeam = false;
1123 int prevNgId = ngNodeId( points[0].node, ngMesh, nodeNgIdMap );
1125 for ( i = 0; i < nbSeg; ++i )
1127 const UVPtStruct& p1 = points[ i ];
1128 const UVPtStruct& p2 = points[ i+1 ];
1130 if ( p1.node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX ) //an EDGE begins
1133 if ( helper.IsRealSeam( p1.node->getshapeId() ))
1135 TopoDS_Edge e = fSide.Edge( fSide.EdgeIndex( 0.5 * ( p1.normParam + p2.normParam )));
1136 isSeam = helper.IsRealSeam( e );
1139 otherSeamParam = helper.GetOtherParam( helper.GetPeriodicIndex() & 1 ? p2.u : p2.v );
1143 netgen::Segment seg;
1146 seg[1] = prevNgId = ngNodeId( p2.node, ngMesh, nodeNgIdMap );
1147 // node param on curve
1148 seg.epgeominfo[ 0 ].dist = p1.param;
1149 seg.epgeominfo[ 1 ].dist = p2.param;
1151 seg.epgeominfo[ 0 ].u = p1.u;
1152 seg.epgeominfo[ 0 ].v = p1.v;
1153 seg.epgeominfo[ 1 ].u = p2.u;
1154 seg.epgeominfo[ 1 ].v = p2.v;
1156 //geomEdge = fSide.Edge( fSide.EdgeIndex( 0.5 * ( p1.normParam + p2.normParam )));
1157 //seg.epgeominfo[ 0 ].edgenr = seg.epgeominfo[ 1 ].edgenr = occgeom.emap.FindIndex( geomEdge );
1159 //seg.epgeominfo[ iEnd ].edgenr = edgeID; // = geom.emap.FindIndex(edge);
1160 seg.si = faceNgID; // = geom.fmap.FindIndex (face);
1161 seg.edgenr = ngMesh.GetNSeg() + 1; // segment id
1162 ngMesh.AddSegment (seg);
1164 SMESH_TNodeXYZ np1( p1.node ), np2( p2.node );
1165 RestrictLocalSize( ngMesh, 0.5*(np1+np2), (np1-np2).Modulus() );
1167 #ifdef DUMP_SEGMENTS
1168 cout << "Segment: " << seg.edgenr << " on SMESH face " << helper.GetMeshDS()->ShapeToIndex( face ) << endl
1169 << "\tface index: " << seg.si << endl
1170 << "\tp1: " << seg[0] << endl
1171 << "\tp2: " << seg[1] << endl
1172 << "\tp0 param: " << seg.epgeominfo[ 0 ].dist << endl
1173 << "\tp0 uv: " << seg.epgeominfo[ 0 ].u <<", "<< seg.epgeominfo[ 0 ].v << endl
1174 //<< "\tp0 edge: " << seg.epgeominfo[ 0 ].edgenr << endl
1175 << "\tp1 param: " << seg.epgeominfo[ 1 ].dist << endl
1176 << "\tp1 uv: " << seg.epgeominfo[ 1 ].u <<", "<< seg.epgeominfo[ 1 ].v << endl;
1177 //<< "\tp1 edge: " << seg.epgeominfo[ 1 ].edgenr << endl;
1181 if ( helper.GetPeriodicIndex() && 1 ) {
1182 seg.epgeominfo[ 0 ].u = otherSeamParam;
1183 seg.epgeominfo[ 1 ].u = otherSeamParam;
1184 swap (seg.epgeominfo[0].v, seg.epgeominfo[1].v);
1186 seg.epgeominfo[ 0 ].v = otherSeamParam;
1187 seg.epgeominfo[ 1 ].v = otherSeamParam;
1188 swap (seg.epgeominfo[0].u, seg.epgeominfo[1].u);
1190 swap( seg[0], seg[1] );
1191 swap( seg.epgeominfo[0].dist, seg.epgeominfo[1].dist );
1192 seg.edgenr = ngMesh.GetNSeg() + 1; // segment id
1193 ngMesh.AddSegment( seg );
1194 #ifdef DUMP_SEGMENTS
1195 cout << "Segment: " << seg.edgenr << endl
1196 << "\t is SEAM (reverse) of the previous. "
1197 << " Other " << (helper.GetPeriodicIndex() && 1 ? "U" : "V")
1198 << " = " << otherSeamParam << endl;
1201 else if ( fOri == TopAbs_INTERNAL )
1203 swap( seg[0], seg[1] );
1204 swap( seg.epgeominfo[0], seg.epgeominfo[1] );
1205 seg.edgenr = ngMesh.GetNSeg() + 1; // segment id
1206 ngMesh.AddSegment( seg );
1207 #ifdef DUMP_SEGMENTS
1208 cout << "Segment: " << seg.edgenr << endl << "\t is REVERSE of the previous" << endl;
1212 } // loop on geomEdge ancestors
1214 if ( quadHelper ) // remember medium nodes of sub-meshes
1216 SMDS_ElemIteratorPtr edges = smDS->GetElements();
1217 while ( edges->more() )
1219 const SMDS_MeshElement* e = edges->next();
1220 if ( !quadHelper->AddTLinks( static_cast< const SMDS_MeshEdge*>( e )))
1226 } // case TopAbs_EDGE
1228 case TopAbs_FACE: { // FACE
1229 // ----------------------
1230 const TopoDS_Face& geomFace = TopoDS::Face( sm->GetSubShape() );
1231 helper.SetSubShape( geomFace );
1232 bool isInternalFace = ( geomFace.Orientation() == TopAbs_INTERNAL );
1234 // Find solids the geomFace bounds
1235 int solidID1 = 0, solidID2 = 0;
1237 PShapeIteratorPtr solidIt = helper.GetAncestors( geomFace, *sm->GetFather(), TopAbs_SOLID);
1238 while ( const TopoDS_Shape * solid = solidIt->next() )
1240 int id = occgeom.somap.FindIndex ( *solid );
1241 if ( solidID1 && id != solidID1 ) solidID2 = id;
1245 if ( proxyMesh && proxyMesh->GetProxySubMesh( geomFace ))
1247 // if a proxy sub-mesh contains temporary faces, then these faces
1248 // should be used to mesh only one SOLID
1249 bool hasTmp = false;
1250 smDS = proxyMesh->GetSubMesh( geomFace );
1251 SMDS_ElemIteratorPtr faces = smDS->GetElements();
1252 while ( faces->more() )
1254 const SMDS_MeshElement* f = faces->next();
1255 if ( proxyMesh->IsTemporary( f ))
1258 std::vector<const SMDS_MeshNode*> fNodes( f->begin_nodes(), f->end_nodes() );
1259 std::vector<const SMDS_MeshElement*> vols;
1260 if ( _mesh->GetMeshDS()->GetElementsByNodes( fNodes, vols, SMDSAbs_Volume ) == 1 )
1262 int geomID = vols[0]->getshapeId();
1263 const TopoDS_Shape& solid = helper.GetMeshDS()->IndexToShape( geomID );
1264 if ( !solid.IsNull() )
1265 solidID1 = occgeom.somap.FindIndex ( solid );
1271 // exclude faces generated by NETGEN from computation of 3D mesh
1272 const int fID = occgeom.fmap.FindIndex( geomFace );
1273 if ( !hasTmp ) // shrunk mesh
1275 // move netgen points according to moved nodes
1276 SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/true);
1277 while ( smIt->more() )
1279 SMESH_subMesh* sub = smIt->next();
1280 if ( !sub->GetSubMeshDS() ) continue;
1281 SMDS_NodeIteratorPtr nodeIt = sub->GetSubMeshDS()->GetNodes();
1282 while ( nodeIt->more() )
1284 const SMDS_MeshNode* n = nodeIt->next();
1285 int ngID = ngNodeId( n, ngMesh, nodeNgIdMap );
1286 netgen::MeshPoint& ngPoint = ngMesh.Point( ngID );
1287 ngPoint(0) = n->X();
1288 ngPoint(1) = n->Y();
1289 ngPoint(2) = n->Z();
1292 // remove faces near boundary to avoid their overlapping
1293 // with shrunk faces
1294 for ( int i = 1; i <= ngMesh.GetNSE(); ++i )
1296 const netgen::Element2d& elem = ngMesh.SurfaceElement(i);
1297 if ( elem.GetIndex() == fID )
1299 for ( int iN = 0; iN < elem.GetNP(); ++iN )
1300 if ( ngMesh[ elem[ iN ]].Type() != netgen::SURFACEPOINT )
1302 ngMesh.DeleteSurfaceElement( i );
1311 ngMesh.AddFaceDescriptor( netgen::FaceDescriptor( faceNgID,/*solid1=*/0,/*solid2=*/0,0 ));
1312 for (int i = 1; i <= ngMesh.GetNSE(); ++i )
1314 const netgen::Element2d& elem = ngMesh.SurfaceElement(i);
1315 if ( elem.GetIndex() == fID )
1316 const_cast< netgen::Element2d& >( elem ).SetIndex( faceNgID );
1320 // Add ng face descriptors of meshed faces
1322 ngMesh.AddFaceDescriptor( netgen::FaceDescriptor( faceNgID, solidID1, solidID2, 0 ));
1324 // if second oreder is required, even already meshed faces must be passed to NETGEN
1325 int fID = occgeom.fmap.Add( geomFace );
1326 if ( occgeom.facemeshstatus.Size() < fID ) occgeom.facemeshstatus.SetSize( fID );
1327 occgeom.facemeshstatus[ fID-1 ] = netgen::FACE_MESHED_OK;
1328 while ( fID < faceNgID ) // geomFace is already in occgeom.fmap, add a copy
1330 fID = occgeom.fmap.Add( BRepBuilderAPI_Copy( geomFace, /*copyGeom=*/false ));
1331 if ( occgeom.facemeshstatus.Size() < fID ) occgeom.facemeshstatus.SetSize( fID );
1332 occgeom.facemeshstatus[ fID-1 ] = netgen::FACE_MESHED_OK;
1334 // Problem with the second order in a quadrangular mesh remains.
1335 // 1) All quadrangles generated by NETGEN are moved to an inexistent face
1336 // by FillSMesh() (find "AddFaceDescriptor")
1337 // 2) Temporary triangles generated by StdMeshers_QuadToTriaAdaptor
1338 // are on faces where quadrangles were.
1339 // Due to these 2 points, wrong geom faces are used while conversion to quadratic
1340 // of the mentioned above quadrangles and triangles
1342 // Orient the face correctly in solidID1 (issue 0020206)
1343 bool reverse = false;
1345 TopoDS_Shape solid = occgeom.somap( solidID1 );
1346 TopAbs_Orientation faceOriInSolid = helper.GetSubShapeOri( solid, geomFace );
1347 if ( faceOriInSolid >= 0 )
1349 helper.IsReversedSubMesh( TopoDS::Face( geomFace.Oriented( faceOriInSolid )));
1352 // Add surface elements
1354 netgen::Element2d tri(3);
1355 tri.SetIndex( faceNgID );
1356 SMESH_TNodeXYZ xyz[3];
1358 #ifdef DUMP_TRIANGLES
1359 cout << "SMESH face " << helper.GetMeshDS()->ShapeToIndex( geomFace )
1360 << " internal="<<isInternalFace << endl;
1363 SMDS_ElemIteratorPtr faces = smDS->GetElements();
1364 while ( faces->more() )
1366 const SMDS_MeshElement* f = faces->next();
1367 if ( f->NbNodes() % 3 != 0 ) // not triangle
1369 PShapeIteratorPtr solidIt=helper.GetAncestors(geomFace,*sm->GetFather(),TopAbs_SOLID);
1370 if ( const TopoDS_Shape * solid = solidIt->next() )
1371 sm = _mesh->GetSubMesh( *solid );
1372 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1373 smError.reset( new SMESH_ComputeError(COMPERR_BAD_INPUT_MESH,"Not triangle sub-mesh"));
1374 smError->myBadElements.push_back( f );
1378 for ( int i = 0; i < 3; ++i )
1380 const SMDS_MeshNode* node = f->GetNode( i ), * inFaceNode=0;
1383 // get node UV on face
1384 int shapeID = node->getshapeId();
1385 if ( helper.IsSeamShape( shapeID ))
1387 if ( helper.IsSeamShape( f->GetNodeWrap( i+1 )->getshapeId() ))
1388 inFaceNode = f->GetNodeWrap( i-1 );
1390 inFaceNode = f->GetNodeWrap( i+1 );
1392 gp_XY uv = helper.GetNodeUV( geomFace, node, inFaceNode );
1394 int ind = reverse ? 3-i : i+1;
1395 tri.GeomInfoPi(ind).u = uv.X();
1396 tri.GeomInfoPi(ind).v = uv.Y();
1397 tri.PNum (ind) = ngNodeId( node, ngMesh, nodeNgIdMap );
1400 // pass a triangle size to NG size-map
1401 double size = ( ( xyz[0] - xyz[1] ).Modulus() +
1402 ( xyz[1] - xyz[2] ).Modulus() +
1403 ( xyz[2] - xyz[0] ).Modulus() ) / 3;
1404 gp_XYZ gc = ( xyz[0] + xyz[1] + xyz[2] ) / 3;
1405 RestrictLocalSize( ngMesh, gc, size, /*overrideMinH=*/false );
1407 ngMesh.AddSurfaceElement (tri);
1408 #ifdef DUMP_TRIANGLES
1409 cout << tri << endl;
1412 if ( isInternalFace )
1414 swap( tri[1], tri[2] );
1415 ngMesh.AddSurfaceElement (tri);
1416 #ifdef DUMP_TRIANGLES
1417 cout << tri << endl;
1422 if ( quadHelper ) // remember medium nodes of sub-meshes
1424 SMDS_ElemIteratorPtr faces = smDS->GetElements();
1425 while ( faces->more() )
1427 const SMDS_MeshElement* f = faces->next();
1428 if ( !quadHelper->AddTLinks( static_cast< const SMDS_MeshFace*>( f )))
1434 } // case TopAbs_FACE
1436 case TopAbs_VERTEX: { // VERTEX
1437 // --------------------------
1438 // issue 0021405. Add node only if a VERTEX is shared by a not meshed EDGE,
1439 // else netgen removes a free node and nodeVector becomes invalid
1440 PShapeIteratorPtr ansIt = helper.GetAncestors( sm->GetSubShape(),
1444 while ( const TopoDS_Shape* e = ansIt->next() )
1446 SMESH_subMesh* eSub = helper.GetMesh()->GetSubMesh( *e );
1447 if (( toAdd = ( eSub->IsEmpty() && !SMESH_Algo::isDegenerated( TopoDS::Edge( *e )))))
1452 SMDS_NodeIteratorPtr nodeIt = smDS->GetNodes();
1453 if ( nodeIt->more() )
1454 ngNodeId( nodeIt->next(), ngMesh, nodeNgIdMap );
1460 } // loop on submeshes
1463 nodeVec.resize( ngMesh.GetNP() + 1 );
1464 TNode2IdMap::iterator node_NgId, nodeNgIdEnd = nodeNgIdMap.end();
1465 for ( node_NgId = nodeNgIdMap.begin(); node_NgId != nodeNgIdEnd; ++node_NgId)
1466 nodeVec[ node_NgId->second ] = node_NgId->first;
1471 //================================================================================
1473 * \brief Duplicate mesh faces on internal geom faces
1475 //================================================================================
1477 void NETGENPlugin_Mesher::FixIntFaces(const netgen::OCCGeometry& occgeom,
1478 netgen::Mesh& ngMesh,
1479 NETGENPlugin_Internals& internalShapes)
1481 SMESHDS_Mesh* meshDS = internalShapes.getMesh().GetMeshDS();
1483 // find ng indices of internal faces
1485 for ( int ngFaceID = 1; ngFaceID <= occgeom.fmap.Extent(); ++ngFaceID )
1487 int smeshID = meshDS->ShapeToIndex( occgeom.fmap( ngFaceID ));
1488 if ( internalShapes.isInternalShape( smeshID ))
1489 ngFaceIds.insert( ngFaceID );
1491 if ( !ngFaceIds.empty() )
1494 int i, nbFaces = ngMesh.GetNSE();
1495 for ( i = 1; i <= nbFaces; ++i)
1497 netgen::Element2d elem = ngMesh.SurfaceElement(i);
1498 if ( ngFaceIds.count( elem.GetIndex() ))
1500 swap( elem[1], elem[2] );
1501 ngMesh.AddSurfaceElement (elem);
1507 //================================================================================
1509 * \brief Tries to heal the mesh on a FACE. The FACE is supposed to be partially
1510 * meshed due to NETGEN failure
1511 * \param [in] occgeom - geometry
1512 * \param [in,out] ngMesh - the mesh to fix
1513 * \param [inout] faceID - ID of the FACE to fix the mesh on
1514 * \return bool - is mesh is or becomes OK
1516 //================================================================================
1518 bool NETGENPlugin_Mesher::FixFaceMesh(const netgen::OCCGeometry& occgeom,
1519 netgen::Mesh& ngMesh,
1522 // we address a case where the FACE is almost fully meshed except small holes
1523 // of usually triangular shape at FACE boundary (IPAL52861)
1525 // The case appeared to be not simple: holes only look triangular but
1526 // indeed are a self intersecting polygon. A reason of the bug was in coincident
1527 // NG points on a seam edge. But the code below is very nice, leave it for
1532 if ( occgeom.fmap.Extent() < faceID )
1534 //const TopoDS_Face& face = TopoDS::Face( occgeom.fmap( faceID ));
1536 // find free links on the FACE
1537 NCollection_Map<Link> linkMap;
1538 for ( int iF = 1; iF <= ngMesh.GetNSE(); ++iF )
1540 const netgen::Element2d& elem = ngMesh.SurfaceElement(iF);
1541 if ( faceID != elem.GetIndex() )
1543 int n0 = elem[ elem.GetNP() - 1 ];
1544 for ( int i = 0; i < elem.GetNP(); ++i )
1547 Link link( n0, n1 );
1548 if ( !linkMap.Add( link ))
1549 linkMap.Remove( link );
1553 // add/remove boundary links
1554 for ( int iSeg = 1; iSeg <= ngMesh.GetNSeg(); ++iSeg )
1556 const netgen::Segment& seg = ngMesh.LineSegment( iSeg );
1557 if ( seg.si != faceID ) // !edgeIDs.Contains( seg.edgenr ))
1559 Link link( seg[1], seg[0] ); // reverse!!!
1560 if ( !linkMap.Add( link ))
1561 linkMap.Remove( link );
1563 if ( linkMap.IsEmpty() )
1565 if ( linkMap.Extent() < 3 )
1568 // make triangles of the links
1570 netgen::Element2d tri(3);
1571 tri.SetIndex ( faceID );
1573 NCollection_Map<Link>::Iterator linkIt( linkMap );
1574 Link link1 = linkIt.Value();
1575 // look for a link connected to link1
1576 NCollection_Map<Link>::Iterator linkIt2 = linkIt;
1577 for ( linkIt2.Next(); linkIt2.More(); linkIt2.Next() )
1579 const Link& link2 = linkIt2.Value();
1580 if ( link2.IsConnected( link1 ))
1582 // look for a link connected to both link1 and link2
1583 NCollection_Map<Link>::Iterator linkIt3 = linkIt2;
1584 for ( linkIt3.Next(); linkIt3.More(); linkIt3.Next() )
1586 const Link& link3 = linkIt3.Value();
1587 if ( link3.IsConnected( link1 ) &&
1588 link3.IsConnected( link2 ) )
1593 tri[2] = ( link2.Contains( link1.n1 ) ? link2.n1 : link3.n1 );
1594 if ( tri[0] == tri[2] || tri[1] == tri[2] )
1596 ngMesh.AddSurfaceElement( tri );
1598 // prepare for the next tria search
1599 if ( linkMap.Extent() == 3 )
1601 linkMap.Remove( link3 );
1602 linkMap.Remove( link2 );
1604 linkMap.Remove( link1 );
1605 link1 = linkIt.Value();
1618 //================================================================================
1619 // define gp_XY_Subtracted pointer to function calling gp_XY::Subtracted(gp_XY)
1620 gp_XY_FunPtr(Subtracted);
1621 //gp_XY_FunPtr(Added);
1623 //================================================================================
1625 * \brief Evaluate distance between two 2d points along the surface
1627 //================================================================================
1629 double evalDist( const gp_XY& uv1,
1631 const Handle(Geom_Surface)& surf,
1632 const int stopHandler=-1)
1634 if ( stopHandler > 0 ) // continue recursion
1636 gp_XY mid = SMESH_MesherHelper::GetMiddleUV( surf, uv1, uv2 );
1637 return evalDist( uv1,mid, surf, stopHandler-1 ) + evalDist( mid,uv2, surf, stopHandler-1 );
1639 double dist3D = surf->Value( uv1.X(), uv1.Y() ).Distance( surf->Value( uv2.X(), uv2.Y() ));
1640 if ( stopHandler == 0 ) // stop recursion
1643 // start recursion if necessary
1644 double dist2D = SMESH_MesherHelper::ApplyIn2D(surf, uv1, uv2, gp_XY_Subtracted, 0).Modulus();
1645 if ( fabs( dist3D - dist2D ) < dist2D * 1e-10 )
1646 return dist3D; // equal parametrization of a planar surface
1648 return evalDist( uv1, uv2, surf, 3 ); // start recursion
1651 //================================================================================
1653 * \brief Data of vertex internal in geom face
1655 //================================================================================
1659 gp_XY uv; //!< UV in face parametric space
1660 int ngId; //!< ng id of corrsponding node
1661 gp_XY uvClose; //!< UV of closest boundary node
1662 int ngIdClose; //!< ng id of closest boundary node
1665 //================================================================================
1667 * \brief Data of vertex internal in solid
1669 //================================================================================
1673 int ngId; //!< ng id of corresponding node
1674 int ngIdClose; //!< ng id of closest 2d mesh element
1675 int ngIdCloseN; //!< ng id of closest node of the closest 2d mesh element
1678 inline double dist2( const netgen::MeshPoint& p1, const netgen::MeshPoint& p2 )
1680 return gp_Pnt( NGPOINT_COORDS(p1)).SquareDistance( gp_Pnt( NGPOINT_COORDS(p2)));
1683 // inline double dist2(const netgen::MeshPoint& p, const SMDS_MeshNode* n )
1685 // return gp_Pnt( NGPOINT_COORDS(p)).SquareDistance( SMESH_NodeXYZ(n));
1689 //================================================================================
1691 * \brief Make netgen take internal vertices in faces into account by adding
1692 * segments including internal vertices
1694 * This function works in supposition that 1D mesh is already computed in ngMesh
1696 //================================================================================
1698 void NETGENPlugin_Mesher::AddIntVerticesInFaces(const netgen::OCCGeometry& occgeom,
1699 netgen::Mesh& ngMesh,
1700 vector<const SMDS_MeshNode*>& nodeVec,
1701 NETGENPlugin_Internals& internalShapes)
1703 if ((int) nodeVec.size() < ngMesh.GetNP() )
1704 nodeVec.resize( ngMesh.GetNP(), 0 );
1706 SMESHDS_Mesh* meshDS = internalShapes.getMesh().GetMeshDS();
1707 SMESH_MesherHelper helper( internalShapes.getMesh() );
1709 const map<int,list<int> >& face2Vert = internalShapes.getFacesWithVertices();
1710 map<int,list<int> >::const_iterator f2v = face2Vert.begin();
1711 for ( ; f2v != face2Vert.end(); ++f2v )
1713 const TopoDS_Face& face = TopoDS::Face( meshDS->IndexToShape( f2v->first ));
1714 if ( face.IsNull() ) continue;
1715 int faceNgID = occgeom.fmap.FindIndex (face);
1716 if ( faceNgID < 0 ) continue;
1718 TopLoc_Location loc;
1719 Handle(Geom_Surface) surf = BRep_Tool::Surface(face,loc);
1721 helper.SetSubShape( face );
1722 helper.SetElementsOnShape( true );
1724 // Get data of internal vertices and add them to ngMesh
1726 multimap< double, TIntVData > dist2VData; // sort vertices by distance from boundary nodes
1728 int i, nbSegInit = ngMesh.GetNSeg();
1730 // boundary characteristics
1731 double totSegLen2D = 0;
1734 const list<int>& iVertices = f2v->second;
1735 list<int>::const_iterator iv = iVertices.begin();
1736 for ( int nbV = 0; iv != iVertices.end(); ++iv, nbV++ )
1739 // get node on vertex
1740 const TopoDS_Vertex V = TopoDS::Vertex( meshDS->IndexToShape( *iv ));
1741 const SMDS_MeshNode * nV = SMESH_Algo::VertexNode( V, meshDS );
1744 SMESH_subMesh* sm = helper.GetMesh()->GetSubMesh( V );
1745 sm->ComputeStateEngine( SMESH_subMesh::COMPUTE );
1746 nV = SMESH_Algo::VertexNode( V, meshDS );
1747 if ( !nV ) continue;
1750 netgen::MeshPoint mp( netgen::Point<3> (nV->X(), nV->Y(), nV->Z()) );
1751 ngMesh.AddPoint ( mp, 1, netgen::EDGEPOINT );
1752 vData.ngId = ngMesh.GetNP();
1753 nodeVec.push_back( nV );
1757 vData.uv = helper.GetNodeUV( face, nV, 0, &uvOK );
1758 if ( !uvOK ) helper.CheckNodeUV( face, nV, vData.uv, BRep_Tool::Tolerance(V),/*force=*/1);
1760 // loop on all segments of the face to find the node closest to vertex and to count
1761 // average segment 2d length
1762 double closeDist2 = numeric_limits<double>::max(), dist2;
1764 for (i = 1; i <= ngMesh.GetNSeg(); ++i)
1766 netgen::Segment & seg = ngMesh.LineSegment(i);
1767 if ( seg.si != faceNgID ) continue;
1769 for ( int iEnd = 0; iEnd < 2; ++iEnd)
1771 uv[iEnd].SetCoord( seg.epgeominfo[iEnd].u, seg.epgeominfo[iEnd].v );
1772 if ( ngIdLast == seg[ iEnd ] ) continue;
1773 dist2 = helper.ApplyIn2D(surf, uv[iEnd], vData.uv, gp_XY_Subtracted,0).SquareModulus();
1774 if ( dist2 < closeDist2 )
1775 vData.ngIdClose = seg[ iEnd ], vData.uvClose = uv[iEnd], closeDist2 = dist2;
1776 ngIdLast = seg[ iEnd ];
1780 totSegLen2D += helper.ApplyIn2D(surf, uv[0], uv[1], gp_XY_Subtracted, false).Modulus();
1784 dist2VData.insert( make_pair( closeDist2, vData ));
1787 if ( totNbSeg == 0 ) break;
1788 double avgSegLen2d = totSegLen2D / totNbSeg;
1790 // Loop on vertices to add segments
1792 multimap< double, TIntVData >::iterator dist_vData = dist2VData.begin();
1793 for ( ; dist_vData != dist2VData.end(); ++dist_vData )
1795 double closeDist2 = dist_vData->first, dist2;
1796 TIntVData & vData = dist_vData->second;
1798 // try to find more close node among segments added for internal vertices
1799 for (i = nbSegInit+1; i <= ngMesh.GetNSeg(); ++i)
1801 netgen::Segment & seg = ngMesh.LineSegment(i);
1802 if ( seg.si != faceNgID ) continue;
1804 for ( int iEnd = 0; iEnd < 2; ++iEnd)
1806 uv[iEnd].SetCoord( seg.epgeominfo[iEnd].u, seg.epgeominfo[iEnd].v );
1807 dist2 = helper.ApplyIn2D(surf, uv[iEnd], vData.uv, gp_XY_Subtracted,0).SquareModulus();
1808 if ( dist2 < closeDist2 )
1809 vData.ngIdClose = seg[ iEnd ], vData.uvClose = uv[iEnd], closeDist2 = dist2;
1812 // decide whether to use the closest node as the second end of segment or to
1813 // create a new point
1814 int segEnd1 = vData.ngId;
1815 int segEnd2 = vData.ngIdClose; // to use closest node
1816 gp_XY uvV = vData.uv, uvP = vData.uvClose;
1817 double segLenHint = ngMesh.GetH( ngMesh.Point( vData.ngId ));
1818 double nodeDist2D = sqrt( closeDist2 );
1819 double nodeDist3D = evalDist( vData.uv, vData.uvClose, surf );
1820 bool avgLenOK = ( avgSegLen2d < 0.75 * nodeDist2D );
1821 bool hintLenOK = ( segLenHint < 0.75 * nodeDist3D );
1822 //cout << "uvV " << uvV.X() <<","<<uvV.Y() << " ";
1823 if ( hintLenOK || avgLenOK )
1825 // create a point between the closest node and V
1828 double r = min( 0.5, ( hintLenOK ? segLenHint/nodeDist3D : avgSegLen2d/nodeDist2D ));
1829 // direction from V to closet node in 2D
1830 gp_Dir2d v2n( helper.ApplyIn2D(surf, uvP, uvV, gp_XY_Subtracted, false ));
1832 uvP = vData.uv + r * nodeDist2D * v2n.XY();
1833 gp_Pnt P = surf->Value( uvP.X(), uvP.Y() ).Transformed( loc );
1835 netgen::MeshPoint mp( netgen::Point<3> (P.X(), P.Y(), P.Z()));
1836 ngMesh.AddPoint ( mp, 1, netgen::EDGEPOINT );
1837 segEnd2 = ngMesh.GetNP();
1838 //cout << "Middle " << r << " uv " << uvP.X() << "," << uvP.Y() << "( " << ngMesh.Point(segEnd2).X()<<","<<ngMesh.Point(segEnd2).Y()<<","<<ngMesh.Point(segEnd2).Z()<<" )"<< endl;
1839 SMDS_MeshNode * nP = helper.AddNode(P.X(), P.Y(), P.Z());
1840 nodeVec.push_back( nP );
1842 //else cout << "at Node " << " uv " << uvP.X() << "," << uvP.Y() << endl;
1845 netgen::Segment seg;
1847 if ( segEnd1 > segEnd2 ) swap( segEnd1, segEnd2 ), swap( uvV, uvP );
1848 seg[0] = segEnd1; // ng node id
1849 seg[1] = segEnd2; // ng node id
1850 seg.edgenr = ngMesh.GetNSeg() + 1;// segment id
1853 seg.epgeominfo[ 0 ].dist = 0; // param on curve
1854 seg.epgeominfo[ 0 ].u = uvV.X();
1855 seg.epgeominfo[ 0 ].v = uvV.Y();
1856 seg.epgeominfo[ 1 ].dist = 1; // param on curve
1857 seg.epgeominfo[ 1 ].u = uvP.X();
1858 seg.epgeominfo[ 1 ].v = uvP.Y();
1860 // seg.epgeominfo[ 0 ].edgenr = 10; // = geom.emap.FindIndex(edge);
1861 // seg.epgeominfo[ 1 ].edgenr = 10; // = geom.emap.FindIndex(edge);
1863 ngMesh.AddSegment (seg);
1865 // add reverse segment
1866 swap( seg[0], seg[1] );
1867 swap( seg.epgeominfo[0], seg.epgeominfo[1] );
1868 seg.edgenr = ngMesh.GetNSeg() + 1; // segment id
1869 ngMesh.AddSegment (seg);
1875 //================================================================================
1877 * \brief Make netgen take internal vertices in solids into account by adding
1878 * faces including internal vertices
1880 * This function works in supposition that 2D mesh is already computed in ngMesh
1882 //================================================================================
1884 void NETGENPlugin_Mesher::AddIntVerticesInSolids(const netgen::OCCGeometry& occgeom,
1885 netgen::Mesh& ngMesh,
1886 vector<const SMDS_MeshNode*>& nodeVec,
1887 NETGENPlugin_Internals& internalShapes)
1889 #ifdef DUMP_TRIANGLES_SCRIPT
1890 // create a python script making a mesh containing triangles added for internal vertices
1891 ofstream py(DUMP_TRIANGLES_SCRIPT);
1892 py << "import SMESH"<< endl
1893 << "from salome.smesh import smeshBuilder"<<endl
1894 << "smesh = smeshBuilder.New()"<<endl
1895 << "m = smesh.Mesh(name='triangles')" << endl;
1897 if ((int) nodeVec.size() < ngMesh.GetNP() )
1898 nodeVec.resize( ngMesh.GetNP(), 0 );
1900 SMESHDS_Mesh* meshDS = internalShapes.getMesh().GetMeshDS();
1901 SMESH_MesherHelper helper( internalShapes.getMesh() );
1903 const map<int,list<int> >& so2Vert = internalShapes.getSolidsWithVertices();
1904 map<int,list<int> >::const_iterator s2v = so2Vert.begin();
1905 for ( ; s2v != so2Vert.end(); ++s2v )
1907 const TopoDS_Shape& solid = meshDS->IndexToShape( s2v->first );
1908 if ( solid.IsNull() ) continue;
1909 int solidNgID = occgeom.somap.FindIndex (solid);
1910 if ( solidNgID < 0 && !occgeom.somap.IsEmpty() ) continue;
1912 helper.SetSubShape( solid );
1913 helper.SetElementsOnShape( true );
1915 // find ng indices of faces within the solid
1917 for (TopExp_Explorer fExp(solid, TopAbs_FACE); fExp.More(); fExp.Next() )
1918 ngFaceIds.insert( occgeom.fmap.FindIndex( fExp.Current() ));
1919 if ( ngFaceIds.size() == 1 && *ngFaceIds.begin() == 0 )
1920 ngFaceIds.insert( 1 );
1922 // Get data of internal vertices and add them to ngMesh
1924 multimap< double, TIntVSoData > dist2VData; // sort vertices by distance from ng faces
1926 int i, nbFaceInit = ngMesh.GetNSE();
1928 // boundary characteristics
1929 double totSegLen = 0;
1932 const list<int>& iVertices = s2v->second;
1933 list<int>::const_iterator iv = iVertices.begin();
1934 for ( int nbV = 0; iv != iVertices.end(); ++iv, nbV++ )
1937 const TopoDS_Vertex V = TopoDS::Vertex( meshDS->IndexToShape( *iv ));
1939 // get node on vertex
1940 const SMDS_MeshNode * nV = SMESH_Algo::VertexNode( V, meshDS );
1943 SMESH_subMesh* sm = helper.GetMesh()->GetSubMesh( V );
1944 sm->ComputeStateEngine( SMESH_subMesh::COMPUTE );
1945 nV = SMESH_Algo::VertexNode( V, meshDS );
1946 if ( !nV ) continue;
1949 netgen::MeshPoint mpV( netgen::Point<3> (nV->X(), nV->Y(), nV->Z()) );
1950 ngMesh.AddPoint ( mpV, 1, netgen::FIXEDPOINT );
1951 vData.ngId = ngMesh.GetNP();
1952 nodeVec.push_back( nV );
1954 // loop on all 2d elements to find the one closest to vertex and to count
1955 // average segment length
1956 double closeDist2 = numeric_limits<double>::max(), avgDist2;
1957 for (i = 1; i <= ngMesh.GetNSE(); ++i)
1959 const netgen::Element2d& elem = ngMesh.SurfaceElement(i);
1960 if ( !ngFaceIds.count( elem.GetIndex() )) continue;
1962 multimap< double, int> dist2nID; // sort nodes of element by distance from V
1963 for ( int j = 0; j < elem.GetNP(); ++j)
1965 netgen::MeshPoint mp = ngMesh.Point( elem[j] );
1966 double d2 = dist2( mpV, mp );
1967 dist2nID.insert( make_pair( d2, elem[j] ));
1968 avgDist2 += d2 / elem.GetNP();
1970 totNbSeg++, totSegLen+= sqrt( dist2( mp, ngMesh.Point( elem[(j+1)%elem.GetNP()])));
1972 double dist = dist2nID.begin()->first; //avgDist2;
1973 if ( dist < closeDist2 )
1974 vData.ngIdClose= i, vData.ngIdCloseN= dist2nID.begin()->second, closeDist2= dist;
1976 dist2VData.insert( make_pair( closeDist2, vData ));
1979 if ( totNbSeg == 0 ) break;
1980 double avgSegLen = totSegLen / totNbSeg;
1982 // Loop on vertices to add triangles
1984 multimap< double, TIntVSoData >::iterator dist_vData = dist2VData.begin();
1985 for ( ; dist_vData != dist2VData.end(); ++dist_vData )
1987 double closeDist2 = dist_vData->first;
1988 TIntVSoData & vData = dist_vData->second;
1990 const netgen::MeshPoint& mpV = ngMesh.Point( vData.ngId );
1992 // try to find more close face among ones added for internal vertices
1993 for (i = nbFaceInit+1; i <= ngMesh.GetNSE(); ++i)
1995 double avgDist2 = 0;
1996 multimap< double, int> dist2nID;
1997 const netgen::Element2d& elem = ngMesh.SurfaceElement(i);
1998 for ( int j = 0; j < elem.GetNP(); ++j)
2000 double d = dist2( mpV, ngMesh.Point( elem[j] ));
2001 dist2nID.insert( make_pair( d, elem[j] ));
2002 avgDist2 += d / elem.GetNP();
2003 if ( avgDist2 < closeDist2 )
2004 vData.ngIdClose= i, vData.ngIdCloseN= dist2nID.begin()->second, closeDist2= avgDist2;
2007 // sort nodes of the closest face by angle with vector from V to the closest node
2008 const double tol = numeric_limits<double>::min();
2009 map< double, int > angle2ID;
2010 const netgen::Element2d& closeFace = ngMesh.SurfaceElement( vData.ngIdClose );
2011 netgen::MeshPoint mp[2];
2012 mp[0] = ngMesh.Point( vData.ngIdCloseN );
2013 gp_XYZ p1( NGPOINT_COORDS( mp[0] ));
2014 gp_XYZ pV( NGPOINT_COORDS( mpV ));
2015 gp_Vec v2p1( pV, p1 );
2016 double distN1 = v2p1.Magnitude();
2017 if ( distN1 <= tol ) continue;
2019 for ( int j = 0; j < closeFace.GetNP(); ++j)
2021 mp[1] = ngMesh.Point( closeFace[j] );
2022 gp_Vec v2p( pV, gp_Pnt( NGPOINT_COORDS( mp[1] )) );
2023 angle2ID.insert( make_pair( v2p1.Angle( v2p ), closeFace[j]));
2025 // get node with angle of 60 degrees or greater
2026 map< double, int >::iterator angle_id = angle2ID.lower_bound( 60. * M_PI / 180. );
2027 if ( angle_id == angle2ID.end() ) angle_id = --angle2ID.end();
2028 const double minAngle = 30. * M_PI / 180.;
2029 const double angle = angle_id->first;
2030 bool angleOK = ( angle > minAngle );
2032 // find points to create a triangle
2033 netgen::Element2d tri(3);
2035 tri[0] = vData.ngId;
2036 tri[1] = vData.ngIdCloseN; // to use the closest nodes
2037 tri[2] = angle_id->second; // to use the node with best angle
2039 // decide whether to use the closest node and the node with best angle or to create new ones
2040 for ( int isBestAngleN = 0; isBestAngleN < 2; ++isBestAngleN )
2042 bool createNew = !angleOK; //, distOK = true;
2044 int triInd = isBestAngleN ? 2 : 1;
2045 mp[isBestAngleN] = ngMesh.Point( tri[triInd] );
2050 double distN2 = sqrt( dist2( mpV, mp[isBestAngleN]));
2051 createNew = ( fabs( distN2 - distN1 ) > 0.25 * distN1 );
2053 else if ( angle < tol )
2055 v2p1.SetX( v2p1.X() + 1e-3 );
2061 double segLenHint = ngMesh.GetH( ngMesh.Point( vData.ngId ));
2062 bool avgLenOK = ( avgSegLen < 0.75 * distN1 );
2063 bool hintLenOK = ( segLenHint < 0.75 * distN1 );
2064 createNew = (createNew || avgLenOK || hintLenOK );
2065 // we create a new node not closer than 0.5 to the closest face
2066 // in order not to clash with other close face
2067 double r = min( 0.5, ( hintLenOK ? segLenHint : avgSegLen ) / distN1 );
2068 distFromV = r * distN1;
2072 // create a new point, between the node and the vertex if angleOK
2073 gp_XYZ p( NGPOINT_COORDS( mp[isBestAngleN] ));
2074 gp_Vec v2p( pV, p ); v2p.Normalize();
2075 if ( isBestAngleN && !angleOK )
2076 p = p1 + gp_Dir( v2p.XYZ() - v2p1.XYZ()).XYZ() * distN1 * 0.95;
2078 p = pV + v2p.XYZ() * distFromV;
2080 if ( !isBestAngleN ) p1 = p, distN1 = distFromV;
2082 mp[isBestAngleN].SetPoint( netgen::Point<3> (p.X(), p.Y(), p.Z()));
2083 ngMesh.AddPoint ( mp[isBestAngleN], 1, netgen::SURFACEPOINT );
2084 tri[triInd] = ngMesh.GetNP();
2085 nodeVec.push_back( helper.AddNode( p.X(), p.Y(), p.Z()) );
2088 ngMesh.AddSurfaceElement (tri);
2089 swap( tri[1], tri[2] );
2090 ngMesh.AddSurfaceElement (tri);
2092 #ifdef DUMP_TRIANGLES_SCRIPT
2093 py << "n1 = m.AddNode( "<< mpV(0)<<", "<< mpV(1)<<", "<< mpV(2)<<") "<< endl
2094 << "n2 = m.AddNode( "<< mp[0](0)<<", "<< mp[0](1)<<", "<< mp[0](2)<<") "<< endl
2095 << "n3 = m.AddNode( "<< mp[1](0)<<", "<< mp[1](1)<<", "<< mp[1](2)<<" )" << endl
2096 << "m.AddFace([n1,n2,n3])" << endl;
2098 } // loop on internal vertices of a solid
2100 } // loop on solids with internal vertices
2103 //================================================================================
2105 * \brief Fill netgen mesh with segments of a FACE
2106 * \param ngMesh - netgen mesh
2107 * \param geom - container of OCCT geometry to mesh
2108 * \param wires - data of nodes on FACE boundary
2109 * \param helper - mesher helper holding the FACE
2110 * \param nodeVec - vector of nodes in which node index == netgen ID
2111 * \retval SMESH_ComputeErrorPtr - error description
2113 //================================================================================
2115 SMESH_ComputeErrorPtr
2116 NETGENPlugin_Mesher::AddSegmentsToMesh(netgen::Mesh& ngMesh,
2117 netgen::OCCGeometry& geom,
2118 const TSideVector& wires,
2119 SMESH_MesherHelper& helper,
2120 vector< const SMDS_MeshNode* > & nodeVec,
2121 const bool overrideMinH)
2123 // ----------------------------
2124 // Check wires and count nodes
2125 // ----------------------------
2127 for ( size_t iW = 0; iW < wires.size(); ++iW )
2129 StdMeshers_FaceSidePtr wire = wires[ iW ];
2130 if ( wire->MissVertexNode() )
2132 // Commented for issue 0020960. It worked for the case, let's wait for case where it doesn't.
2133 // It seems that there is no reason for this limitation
2135 // (new SMESH_ComputeError(COMPERR_BAD_INPUT_MESH, "Missing nodes on vertices"));
2137 const vector<UVPtStruct>& uvPtVec = wire->GetUVPtStruct();
2138 if ((int) uvPtVec.size() != wire->NbPoints() )
2139 return SMESH_ComputeError::New(COMPERR_BAD_INPUT_MESH,
2140 SMESH_Comment("Unexpected nb of points on wire ") << iW
2141 << ": " << uvPtVec.size()<<" != "<<wire->NbPoints());
2142 nbNodes += wire->NbPoints();
2144 nodeVec.reserve( nodeVec.size() + nbNodes + 1 );
2145 if ( nodeVec.empty() )
2146 nodeVec.push_back( 0 );
2148 // -----------------
2150 // -----------------
2152 const bool wasNgMeshEmpty = ( ngMesh.GetNP() < 1 ); /* true => this method is called by
2153 NETGENPlugin_NETGEN_2D_ONLY */
2155 // map for nodes on vertices since they can be shared between wires
2156 // ( issue 0020676, face_int_box.brep) and nodes built by NETGEN
2157 map<const SMDS_MeshNode*, int > node2ngID;
2158 if ( !wasNgMeshEmpty ) // fill node2ngID with nodes built by NETGEN
2160 set< int > subIDs; // ids of sub-shapes of the FACE
2161 for ( size_t iW = 0; iW < wires.size(); ++iW )
2163 StdMeshers_FaceSidePtr wire = wires[ iW ];
2164 for ( int iE = 0, nbE = wire->NbEdges(); iE < nbE; ++iE )
2166 subIDs.insert( wire->EdgeID( iE ));
2167 subIDs.insert( helper.GetMeshDS()->ShapeToIndex( wire->FirstVertex( iE )));
2170 for ( size_t ngID = 1; ngID < nodeVec.size(); ++ngID )
2171 if ( subIDs.count( nodeVec[ngID]->getshapeId() ))
2172 node2ngID.insert( make_pair( nodeVec[ngID], ngID ));
2175 const int solidID = 0, faceID = geom.fmap.FindIndex( helper.GetSubShape() );
2176 if ( ngMesh.GetNFD() < 1 )
2177 ngMesh.AddFaceDescriptor( netgen::FaceDescriptor( faceID, solidID, solidID, 0 ));
2179 for ( size_t iW = 0; iW < wires.size(); ++iW )
2181 StdMeshers_FaceSidePtr wire = wires[ iW ];
2182 const vector<UVPtStruct>& uvPtVec = wire->GetUVPtStruct();
2183 const int nbSegments = wire->NbPoints() - 1;
2185 // assure the 1st node to be in node2ngID, which is needed to correctly
2186 // "close chain of segments" (see below) in case if the 1st node is not
2187 // onVertex because it is on a Viscous layer
2188 node2ngID.insert( make_pair( uvPtVec[ 0 ].node, ngMesh.GetNP() + 1 ));
2190 // compute length of every segment
2191 vector<double> segLen( nbSegments );
2192 for ( int i = 0; i < nbSegments; ++i )
2193 segLen[i] = SMESH_TNodeXYZ( uvPtVec[ i ].node ).Distance( uvPtVec[ i+1 ].node );
2195 int edgeID = 1, posID = -2;
2196 bool isInternalWire = false;
2197 double vertexNormPar = 0;
2198 const int prevNbNGSeg = ngMesh.GetNSeg();
2199 for ( int i = 0; i < nbSegments; ++i ) // loop on segments
2201 // Add the first point of a segment
2203 const SMDS_MeshNode * n = uvPtVec[ i ].node;
2204 const int posShapeID = n->getshapeId();
2205 bool onVertex = ( n->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX );
2206 bool onEdge = ( n->GetPosition()->GetTypeOfPosition() == SMDS_TOP_EDGE );
2208 // skip nodes on degenerated edges
2209 if ( helper.IsDegenShape( posShapeID ) &&
2210 helper.IsDegenShape( uvPtVec[ i+1 ].node->getshapeId() ))
2213 int ngID1 = ngMesh.GetNP() + 1, ngID2 = ngID1+1;
2214 if ( onVertex || ( !wasNgMeshEmpty && onEdge ) || helper.IsRealSeam( posShapeID ))
2215 ngID1 = node2ngID.insert( make_pair( n, ngID1 )).first->second;
2216 if ( ngID1 > ngMesh.GetNP() )
2218 netgen::MeshPoint mp( netgen::Point<3> (n->X(), n->Y(), n->Z()) );
2219 ngMesh.AddPoint ( mp, 1, netgen::EDGEPOINT );
2220 nodeVec.push_back( n );
2222 else // n is in ngMesh already, and ngID2 in prev segment is wrong
2224 ngID2 = ngMesh.GetNP() + 1;
2225 if ( i > 0 ) // prev segment belongs to same wire
2227 netgen::Segment& prevSeg = ngMesh.LineSegment( ngMesh.GetNSeg() );
2234 netgen::Segment seg;
2236 seg[0] = ngID1; // ng node id
2237 seg[1] = ngID2; // ng node id
2238 seg.edgenr = ngMesh.GetNSeg() + 1; // ng segment id
2239 seg.si = faceID; // = geom.fmap.FindIndex (face);
2241 for ( int iEnd = 0; iEnd < 2; ++iEnd)
2243 const UVPtStruct& pnt = uvPtVec[ i + iEnd ];
2245 seg.epgeominfo[ iEnd ].dist = pnt.param; // param on curve
2246 seg.epgeominfo[ iEnd ].u = pnt.u;
2247 seg.epgeominfo[ iEnd ].v = pnt.v;
2249 // find out edge id and node parameter on edge
2250 onVertex = ( pnt.normParam + 1e-10 > vertexNormPar );
2251 if ( onVertex || posShapeID != posID )
2254 double normParam = pnt.normParam;
2256 normParam = 0.5 * ( uvPtVec[ i ].normParam + uvPtVec[ i+1 ].normParam );
2257 int edgeIndexInWire = wire->EdgeIndex( normParam );
2258 vertexNormPar = wire->LastParameter( edgeIndexInWire );
2259 const TopoDS_Edge& edge = wire->Edge( edgeIndexInWire );
2260 edgeID = geom.emap.FindIndex( edge );
2262 isInternalWire = ( edge.Orientation() == TopAbs_INTERNAL );
2263 // if ( onVertex ) // param on curve is different on each of two edges
2264 // seg.epgeominfo[ iEnd ].dist = helper.GetNodeU( edge, pnt.node );
2266 seg.epgeominfo[ iEnd ].edgenr = edgeID; // = geom.emap.FindIndex(edge);
2269 ngMesh.AddSegment (seg);
2271 // restrict size of elements near the segment
2272 SMESH_TNodeXYZ np1( n ), np2( uvPtVec[ i+1 ].node );
2273 // get an average size of adjacent segments to avoid sharp change of
2274 // element size (regression on issue 0020452, note 0010898)
2275 int iPrev = SMESH_MesherHelper::WrapIndex( i-1, nbSegments );
2276 int iNext = SMESH_MesherHelper::WrapIndex( i+1, nbSegments );
2277 double sumH = segLen[ iPrev ] + segLen[ i ] + segLen[ iNext ];
2278 int nbSeg = ( int( segLen[ iPrev ] > sumH / 100.) +
2279 int( segLen[ i ] > sumH / 100.) +
2280 int( segLen[ iNext ] > sumH / 100.));
2282 RestrictLocalSize( ngMesh, 0.5*(np1+np2), sumH / nbSeg, overrideMinH );
2284 if ( isInternalWire )
2286 swap (seg[0], seg[1]);
2287 swap( seg.epgeominfo[0], seg.epgeominfo[1] );
2288 seg.edgenr = ngMesh.GetNSeg() + 1; // segment id
2289 ngMesh.AddSegment (seg);
2291 } // loop on segments on a wire
2293 // close chain of segments
2294 if ( nbSegments > 0 )
2296 netgen::Segment& lastSeg = ngMesh.LineSegment( ngMesh.GetNSeg() - int( isInternalWire ));
2297 const SMDS_MeshNode * lastNode = uvPtVec.back().node;
2298 lastSeg[1] = node2ngID.insert( make_pair( lastNode, lastSeg[1] )).first->second;
2299 if ( lastSeg[1] > ngMesh.GetNP() )
2301 netgen::MeshPoint mp( netgen::Point<3> (lastNode->X(), lastNode->Y(), lastNode->Z()) );
2302 ngMesh.AddPoint ( mp, 1, netgen::EDGEPOINT );
2303 nodeVec.push_back( lastNode );
2305 if ( isInternalWire )
2307 netgen::Segment& realLastSeg = ngMesh.LineSegment( ngMesh.GetNSeg() );
2308 realLastSeg[0] = lastSeg[1];
2312 #ifdef DUMP_SEGMENTS
2313 cout << "BEGIN WIRE " << iW << endl;
2314 for ( int i = prevNbNGSeg+1; i <= ngMesh.GetNSeg(); ++i )
2316 netgen::Segment& seg = ngMesh.LineSegment( i );
2318 netgen::Segment& prevSeg = ngMesh.LineSegment( i-1 );
2319 if ( seg[0] == prevSeg[1] && seg[1] == prevSeg[0] )
2321 cout << "Segment: " << seg.edgenr << endl << "\tis REVERSE of the previous one" << endl;
2325 cout << "Segment: " << seg.edgenr << endl
2326 << "\tp1: " << seg[0] << " n" << nodeVec[ seg[0]]->GetID() << endl
2327 << "\tp2: " << seg[1] << " n" << nodeVec[ seg[1]]->GetID() << endl
2328 << "\tp0 param: " << seg.epgeominfo[ 0 ].dist << endl
2329 << "\tp0 uv: " << seg.epgeominfo[ 0 ].u <<", "<< seg.epgeominfo[ 0 ].v << endl
2330 << "\tp0 edge: " << seg.epgeominfo[ 0 ].edgenr << endl
2331 << "\tp1 param: " << seg.epgeominfo[ 1 ].dist << endl
2332 << "\tp1 uv: " << seg.epgeominfo[ 1 ].u <<", "<< seg.epgeominfo[ 1 ].v << endl
2333 << "\tp1 edge: " << seg.epgeominfo[ 1 ].edgenr << endl;
2335 cout << "--END WIRE " << iW << endl;
2337 SMESH_Comment __not_unused_variable( prevNbNGSeg );
2340 } // loop on WIREs of a FACE
2342 // add a segment instead of an internal vertex
2343 if ( wasNgMeshEmpty )
2345 NETGENPlugin_Internals intShapes( *helper.GetMesh(), helper.GetSubShape(), /*is3D=*/false );
2346 AddIntVerticesInFaces( geom, ngMesh, nodeVec, intShapes );
2348 ngMesh.CalcSurfacesOfNode();
2353 //================================================================================
2355 * \brief Fill SMESH mesh according to contents of netgen mesh
2356 * \param occgeo - container of OCCT geometry to mesh
2357 * \param ngMesh - netgen mesh
2358 * \param initState - bn of entities in netgen mesh before computing
2359 * \param sMesh - SMESH mesh to fill in
2360 * \param nodeVec - vector of nodes in which node index == netgen ID
2361 * \param comment - returns problem description
2362 * \param quadHelper - holder of medium nodes of sub-meshes
2363 * \retval int - error
2365 //================================================================================
2367 int NETGENPlugin_Mesher::FillSMesh(const netgen::OCCGeometry& occgeo,
2368 netgen::Mesh& ngMesh,
2369 const NETGENPlugin_ngMeshInfo& initState,
2371 std::vector<const SMDS_MeshNode*>& nodeVec,
2372 SMESH_Comment& comment,
2373 SMESH_MesherHelper* quadHelper)
2375 int nbNod = ngMesh.GetNP();
2376 int nbSeg = ngMesh.GetNSeg();
2377 int nbFac = ngMesh.GetNSE();
2378 int nbVol = ngMesh.GetNE();
2380 SMESHDS_Mesh* meshDS = sMesh.GetMeshDS();
2382 // quadHelper is used for either
2383 // 1) making quadratic elements when a lower dimension mesh is loaded
2384 // to SMESH before conversion to quadratic by NETGEN
2385 // 2) sewing of quadratic elements with quadratic elements of sub-meshes
2386 if ( quadHelper && !quadHelper->GetIsQuadratic() && quadHelper->GetTLinkNodeMap().empty() )
2389 int i, nbInitNod = initState._nbNodes;
2390 if ( initState._elementsRemoved )
2392 // PAL23427. Update nodeVec to track removal of netgen free points as a result
2393 // of removal of faces in FillNgMesh() in the case of a shrunk sub-mesh
2394 int ngID, nodeVecSize = nodeVec.size();
2395 const double eps = std::numeric_limits<double>::min();
2396 for ( ngID = i = 1; i < nodeVecSize; ++ngID, ++i )
2398 gp_Pnt ngPnt( NGPOINT_COORDS( ngMesh.Point( ngID )));
2399 gp_Pnt node ( SMESH_NodeXYZ ( nodeVec[ i ]));
2400 if ( ngPnt.SquareDistance( node ) < eps )
2402 nodeVec[ ngID ] = nodeVec[ i ];
2409 nodeVec.resize( ngID );
2410 nbInitNod = ngID - 1;
2412 // -------------------------------------
2413 // Create and insert nodes into nodeVec
2414 // -------------------------------------
2416 nodeVec.resize( nbNod + 1 );
2417 for ( i = nbInitNod+1; i <= nbNod; ++i )
2419 const netgen::MeshPoint& ngPoint = ngMesh.Point(i);
2420 SMDS_MeshNode* node = NULL;
2421 TopoDS_Vertex aVert;
2422 // First, netgen creates nodes on vertices in occgeo.vmap,
2423 // so node index corresponds to vertex index
2424 // but (issue 0020776) netgen does not create nodes with equal coordinates
2425 if ( i-nbInitNod <= occgeo.vmap.Extent() )
2427 gp_Pnt p ( NGPOINT_COORDS(ngPoint) );
2428 for (int iV = i-nbInitNod; aVert.IsNull() && iV <= occgeo.vmap.Extent(); ++iV)
2430 aVert = TopoDS::Vertex( occgeo.vmap( iV ));
2431 gp_Pnt pV = BRep_Tool::Pnt( aVert );
2432 if ( p.SquareDistance( pV ) > 1e-20 )
2435 node = const_cast<SMDS_MeshNode*>( SMESH_Algo::VertexNode( aVert, meshDS ));
2438 if (!node) // node not found on vertex
2440 node = meshDS->AddNode( NGPOINT_COORDS( ngPoint ));
2441 if (!aVert.IsNull())
2442 meshDS->SetNodeOnVertex(node, aVert);
2447 // -------------------------------------------
2448 // Create mesh segments along geometric edges
2449 // -------------------------------------------
2451 int nbInitSeg = initState._nbSegments;
2452 for (i = nbInitSeg+1; i <= nbSeg; ++i )
2454 const netgen::Segment& seg = ngMesh.LineSegment(i);
2456 int pinds[3] = { seg.pnums[0], seg.pnums[1], seg.pnums[2] };
2459 for (int j=0; j < 3; ++j)
2461 int pind = pinds[j];
2462 if (pind <= 0 || !nodeVec_ACCESS(pind))
2470 int aGeomEdgeInd = seg.epgeominfo[j].edgenr;
2471 if (aGeomEdgeInd > 0 && aGeomEdgeInd <= occgeo.emap.Extent())
2472 aEdge = TopoDS::Edge(occgeo.emap(aGeomEdgeInd));
2474 param = seg.epgeominfo[j].dist;
2477 else // middle point
2479 param = param2 * 0.5;
2481 if (!aEdge.IsNull() && nodeVec_ACCESS(pind)->getshapeId() < 1)
2483 meshDS->SetNodeOnEdge(nodeVec_ACCESS(pind), aEdge, param);
2488 SMDS_MeshEdge* edge = 0;
2489 if (nbp == 2) // second order ?
2491 if ( meshDS->FindEdge( nodeVec_ACCESS(pinds[0]), nodeVec_ACCESS(pinds[1])))
2493 if ( quadHelper ) // final mesh must be quadratic
2494 edge = quadHelper->AddEdge(nodeVec_ACCESS(pinds[0]), nodeVec_ACCESS(pinds[1]));
2496 edge = meshDS->AddEdge(nodeVec_ACCESS(pinds[0]), nodeVec_ACCESS(pinds[1]));
2500 if ( meshDS->FindEdge( nodeVec_ACCESS(pinds[0]), nodeVec_ACCESS(pinds[1]),
2501 nodeVec_ACCESS(pinds[2])))
2503 edge = meshDS->AddEdge(nodeVec_ACCESS(pinds[0]), nodeVec_ACCESS(pinds[1]),
2504 nodeVec_ACCESS(pinds[2]));
2508 if ( comment.empty() ) comment << "Cannot create a mesh edge";
2509 MESSAGE("Cannot create a mesh edge");
2510 nbSeg = nbFac = nbVol = 0;
2513 if ( !aEdge.IsNull() && edge->getshapeId() < 1 )
2514 meshDS->SetMeshElementOnShape(edge, aEdge);
2516 else if ( comment.empty() )
2518 comment << "Invalid netgen segment #" << i;
2522 // ----------------------------------------
2523 // Create mesh faces along geometric faces
2524 // ----------------------------------------
2526 int nbInitFac = initState._nbFaces;
2527 int quadFaceID = ngMesh.GetNFD() + 1;
2528 if ( nbInitFac < nbFac )
2529 // add a faces descriptor to exclude qudrangle elements generated by NETGEN
2530 // from computation of 3D mesh
2531 ngMesh.AddFaceDescriptor (netgen::FaceDescriptor(quadFaceID, /*solid1=*/0, /*solid2=*/0, 0));
2533 vector<const SMDS_MeshNode*> nodes;
2534 for (i = nbInitFac+1; i <= nbFac; ++i )
2536 const netgen::Element2d& elem = ngMesh.SurfaceElement(i);
2537 const int aGeomFaceInd = elem.GetIndex();
2539 if (aGeomFaceInd > 0 && aGeomFaceInd <= occgeo.fmap.Extent())
2540 aFace = TopoDS::Face(occgeo.fmap(aGeomFaceInd));
2542 for ( int j = 1; j <= elem.GetNP(); ++j )
2544 int pind = elem.PNum(j);
2545 if ( pind < 1 || pind >= (int) nodeVec.size() )
2547 if ( SMDS_MeshNode* node = nodeVec_ACCESS(pind))
2549 nodes.push_back( node );
2550 if (!aFace.IsNull() && node->getshapeId() < 1)
2552 const netgen::PointGeomInfo& pgi = elem.GeomInfoPi(j);
2553 meshDS->SetNodeOnFace(node, aFace, pgi.u, pgi.v);
2557 if ((int) nodes.size() != elem.GetNP() )
2559 if ( comment.empty() )
2560 comment << "Invalid netgen 2d element #" << i;
2561 continue; // bad node ids
2563 SMDS_MeshFace* face = NULL;
2564 switch (elem.GetType())
2567 if ( quadHelper ) // final mesh must be quadratic
2568 face = quadHelper->AddFace(nodes[0],nodes[1],nodes[2]);
2570 face = meshDS->AddFace(nodes[0],nodes[1],nodes[2]);
2573 if ( quadHelper ) // final mesh must be quadratic
2574 face = quadHelper->AddFace(nodes[0],nodes[1],nodes[2],nodes[3]);
2576 face = meshDS->AddFace(nodes[0],nodes[1],nodes[2],nodes[3]);
2577 // exclude qudrangle elements from computation of 3D mesh
2578 const_cast< netgen::Element2d& >( elem ).SetIndex( quadFaceID );
2581 nodes[5] = mediumNode( nodes[0],nodes[1],nodes[5], quadHelper );
2582 nodes[3] = mediumNode( nodes[1],nodes[2],nodes[3], quadHelper );
2583 nodes[4] = mediumNode( nodes[2],nodes[0],nodes[4], quadHelper );
2584 face = meshDS->AddFace(nodes[0],nodes[1],nodes[2],nodes[5],nodes[3],nodes[4]);
2587 nodes[4] = mediumNode( nodes[0],nodes[1],nodes[4], quadHelper );
2588 nodes[7] = mediumNode( nodes[1],nodes[2],nodes[7], quadHelper );
2589 nodes[5] = mediumNode( nodes[2],nodes[3],nodes[5], quadHelper );
2590 nodes[6] = mediumNode( nodes[3],nodes[0],nodes[6], quadHelper );
2591 face = meshDS->AddFace(nodes[0],nodes[1],nodes[2],nodes[3],
2592 nodes[4],nodes[7],nodes[5],nodes[6]);
2593 // exclude qudrangle elements from computation of 3D mesh
2594 const_cast< netgen::Element2d& >( elem ).SetIndex( quadFaceID );
2597 MESSAGE("NETGEN created a face of unexpected type, ignoring");
2602 if ( comment.empty() ) comment << "Cannot create a mesh face";
2603 MESSAGE("Cannot create a mesh face");
2604 nbSeg = nbFac = nbVol = 0;
2607 if ( !aFace.IsNull() )
2608 meshDS->SetMeshElementOnShape( face, aFace );
2611 // ------------------
2612 // Create tetrahedra
2613 // ------------------
2615 for ( i = 1; i <= nbVol; ++i )
2617 const netgen::Element& elem = ngMesh.VolumeElement(i);
2618 int aSolidInd = elem.GetIndex();
2619 TopoDS_Solid aSolid;
2620 if ( aSolidInd > 0 && aSolidInd <= occgeo.somap.Extent() )
2621 aSolid = TopoDS::Solid(occgeo.somap(aSolidInd));
2623 for ( int j = 1; j <= elem.GetNP(); ++j )
2625 int pind = elem.PNum(j);
2626 if ( pind < 1 || pind >= (int)nodeVec.size() )
2628 if ( SMDS_MeshNode* node = nodeVec_ACCESS(pind) )
2630 nodes.push_back(node);
2631 if ( !aSolid.IsNull() && node->getshapeId() < 1 )
2632 meshDS->SetNodeInVolume(node, aSolid);
2635 if ((int) nodes.size() != elem.GetNP() )
2637 if ( comment.empty() )
2638 comment << "Invalid netgen 3d element #" << i;
2641 SMDS_MeshVolume* vol = NULL;
2642 switch ( elem.GetType() )
2645 vol = meshDS->AddVolume(nodes[0],nodes[1],nodes[2],nodes[3]);
2648 nodes[4] = mediumNode( nodes[0],nodes[1],nodes[4], quadHelper );
2649 nodes[7] = mediumNode( nodes[1],nodes[2],nodes[7], quadHelper );
2650 nodes[5] = mediumNode( nodes[2],nodes[0],nodes[5], quadHelper );
2651 nodes[6] = mediumNode( nodes[0],nodes[3],nodes[6], quadHelper );
2652 nodes[8] = mediumNode( nodes[1],nodes[3],nodes[8], quadHelper );
2653 nodes[9] = mediumNode( nodes[2],nodes[3],nodes[9], quadHelper );
2654 vol = meshDS->AddVolume(nodes[0],nodes[1],nodes[2],nodes[3],
2655 nodes[4],nodes[7],nodes[5],nodes[6],nodes[8],nodes[9]);
2658 MESSAGE("NETGEN created a volume of unexpected type, ignoring");
2663 if ( comment.empty() ) comment << "Cannot create a mesh volume";
2664 MESSAGE("Cannot create a mesh volume");
2665 nbSeg = nbFac = nbVol = 0;
2668 if (!aSolid.IsNull())
2669 meshDS->SetMeshElementOnShape(vol, aSolid);
2671 return comment.empty() ? 0 : 1;
2676 //================================================================================
2678 * \brief Convert error into text
2680 //================================================================================
2682 std::string text(int err)
2687 SMESH_Comment("Error in netgen::OCCGenerateMesh() at ") << netgen::multithread.task;
2690 //================================================================================
2692 * \brief Convert exception into text
2694 //================================================================================
2696 std::string text(Standard_Failure& ex)
2698 SMESH_Comment str("Exception in netgen::OCCGenerateMesh()");
2699 str << " at " << netgen::multithread.task
2700 << ": " << ex.DynamicType()->Name();
2701 if ( ex.GetMessageString() && strlen( ex.GetMessageString() ))
2702 str << ": " << ex.GetMessageString();
2705 //================================================================================
2707 * \brief Convert exception into text
2709 //================================================================================
2711 std::string text(netgen::NgException& ex)
2713 SMESH_Comment str("NgException");
2714 if ( strlen( netgen::multithread.task ) > 0 )
2715 str << " at " << netgen::multithread.task;
2716 str << ": " << ex.What();
2720 //================================================================================
2722 * \brief Looks for triangles lying on a SOLID
2724 //================================================================================
2726 bool hasBadElemOnSolid( const list<const SMDS_MeshElement*>& elems,
2727 SMESH_subMesh* solidSM )
2729 TopTools_IndexedMapOfShape solidSubs;
2730 TopExp::MapShapes( solidSM->GetSubShape(), solidSubs );
2731 SMESHDS_Mesh* mesh = solidSM->GetFather()->GetMeshDS();
2733 list<const SMDS_MeshElement*>::const_iterator e = elems.begin();
2734 for ( ; e != elems.end(); ++e )
2736 const SMDS_MeshElement* elem = *e;
2737 // if ( elem->GetType() != SMDSAbs_Face ) -- 23047
2739 int nbNodesOnSolid = 0, nbNodes = elem->NbNodes();
2740 SMDS_NodeIteratorPtr nIt = elem->nodeIterator();
2741 while ( nIt->more() )
2743 const SMDS_MeshNode* n = nIt->next();
2744 const TopoDS_Shape& s = mesh->IndexToShape( n->getshapeId() );
2745 nbNodesOnSolid += ( !s.IsNull() && solidSubs.Contains( s ));
2746 if ( nbNodesOnSolid > 2 ||
2747 nbNodesOnSolid == nbNodes)
2754 const double edgeMeshingTime = 0.001;
2755 const double faceMeshingTime = 0.019;
2756 const double edgeFaceMeshingTime = edgeMeshingTime + faceMeshingTime;
2757 const double faceOptimizTime = 0.06;
2758 const double voluMeshingTime = 0.15;
2759 const double volOptimizeTime = 0.77;
2762 //=============================================================================
2764 * Here we are going to use the NETGEN mesher
2766 //=============================================================================
2768 bool NETGENPlugin_Mesher::Compute()
2770 NETGENPlugin_NetgenLibWrapper ngLib;
2772 netgen::MeshingParameters& mparams = netgen::mparam;
2774 SMESH_ComputeErrorPtr error = SMESH_ComputeError::New();
2775 SMESH_MesherHelper quadHelper( *_mesh );
2776 quadHelper.SetIsQuadratic( mparams.secondorder );
2778 // -------------------------
2779 // Prepare OCC geometry
2780 // -------------------------
2782 netgen::OCCGeometry occgeo;
2783 list< SMESH_subMesh* > meshedSM[3]; // for 0-2 dimensions
2784 NETGENPlugin_Internals internals( *_mesh, _shape, _isVolume );
2785 PrepareOCCgeometry( occgeo, _shape, *_mesh, meshedSM, &internals );
2788 _totalTime = edgeFaceMeshingTime;
2790 _totalTime += faceOptimizTime;
2792 _totalTime += voluMeshingTime + ( _optimize ? volOptimizeTime : 0 );
2793 double doneTime = 0;
2796 _curShapeIndex = -1;
2798 // -------------------------
2799 // Generate the mesh
2800 // -------------------------
2803 NETGENPlugin_ngMeshInfo initState; // it remembers size of ng mesh equal to size of Smesh
2805 SMESH_Comment comment;
2808 // vector of nodes in which node index == netgen ID
2809 vector< const SMDS_MeshNode* > nodeVec;
2817 // not to RestrictLocalH() according to curvature during MESHCONST_ANALYSE
2818 mparams.uselocalh = false;
2819 mparams.grading = 0.8; // not limitited size growth
2821 if ( _simpleHyp->GetNumberOfSegments() )
2823 mparams.maxh = occgeo.boundingbox.Diam();
2826 mparams.maxh = _simpleHyp->GetLocalLength();
2829 if ( mparams.maxh == 0.0 )
2830 mparams.maxh = occgeo.boundingbox.Diam();
2831 if ( _simpleHyp || ( mparams.minh == 0.0 && _fineness != NETGENPlugin_Hypothesis::UserDefined))
2832 mparams.minh = GetDefaultMinSize( _shape, mparams.maxh );
2834 // Local size on faces
2835 occgeo.face_maxh = mparams.maxh;
2837 // Let netgen create _ngMesh and calculate element size on not meshed shapes
2841 int startWith = netgen::MESHCONST_ANALYSE;
2842 int endWith = netgen::MESHCONST_ANALYSE;
2847 err = netgen::OCCGenerateMesh(occgeo, _ngMesh, mparams, startWith, endWith);
2849 err = netgen::OCCGenerateMesh(occgeo, _ngMesh, startWith, endWith, optstr);
2851 if(netgen::multithread.terminate)
2854 comment << text(err);
2856 catch (Standard_Failure& ex)
2858 comment << text(ex);
2860 catch (netgen::NgException & ex)
2862 comment << text(ex);
2863 if ( mparams.meshsizefilename )
2864 throw SMESH_ComputeError(COMPERR_BAD_PARMETERS, comment );
2866 err = 0; //- MESHCONST_ANALYSE isn't so important step
2869 ngLib.setMesh(( Ng_Mesh*) _ngMesh );
2871 _ngMesh->ClearFaceDescriptors(); // we make descriptors our-self
2873 if ( !mparams.uselocalh ) // mparams.grading is not taken into account yet
2874 _ngMesh->LocalHFunction().SetGrading( mparams.grading );
2878 // Pass 1D simple parameters to NETGEN
2879 // --------------------------------
2880 int nbSeg = _simpleHyp->GetNumberOfSegments();
2881 double segSize = _simpleHyp->GetLocalLength();
2882 for ( int iE = 1; iE <= occgeo.emap.Extent(); ++iE )
2884 const TopoDS_Edge& e = TopoDS::Edge( occgeo.emap(iE));
2886 segSize = SMESH_Algo::EdgeLength( e ) / ( nbSeg - 0.4 );
2887 setLocalSize( e, segSize, *_ngMesh );
2890 else // if ( ! _simpleHyp )
2892 // Local size on shapes
2893 SetLocalSize( occgeo, *_ngMesh );
2894 SetLocalSizeForChordalError( occgeo, *_ngMesh );
2897 // Precompute internal edges (issue 0020676) in order to
2898 // add mesh on them correctly (twice) to netgen mesh
2899 if ( !err && internals.hasInternalEdges() )
2901 // load internal shapes into OCCGeometry
2902 netgen::OCCGeometry intOccgeo;
2903 internals.getInternalEdges( intOccgeo.fmap, intOccgeo.emap, intOccgeo.vmap, meshedSM );
2904 intOccgeo.boundingbox = occgeo.boundingbox;
2905 intOccgeo.shape = occgeo.shape;
2906 intOccgeo.face_maxh.SetSize(intOccgeo.fmap.Extent());
2907 intOccgeo.face_maxh = netgen::mparam.maxh;
2908 netgen::Mesh *tmpNgMesh = NULL;
2912 // compute local H on internal shapes in the main mesh
2913 //OCCSetLocalMeshSize(intOccgeo, *_ngMesh); it deletes _ngMesh->localH
2915 // let netgen create a temporary mesh
2917 netgen::OCCGenerateMesh(intOccgeo, tmpNgMesh, mparams, startWith, endWith);
2919 netgen::OCCGenerateMesh(intOccgeo, tmpNgMesh, startWith, endWith, optstr);
2921 if(netgen::multithread.terminate)
2924 // copy LocalH from the main to temporary mesh
2925 initState.transferLocalH( _ngMesh, tmpNgMesh );
2927 // compute mesh on internal edges
2928 startWith = endWith = netgen::MESHCONST_MESHEDGES;
2930 err = netgen::OCCGenerateMesh(intOccgeo, tmpNgMesh, mparams, startWith, endWith);
2932 err = netgen::OCCGenerateMesh(intOccgeo, tmpNgMesh, startWith, endWith, optstr);
2934 comment << text(err);
2936 catch (Standard_Failure& ex)
2938 comment << text(ex);
2941 initState.restoreLocalH( tmpNgMesh );
2943 // fill SMESH by netgen mesh
2944 vector< const SMDS_MeshNode* > tmpNodeVec;
2945 FillSMesh( intOccgeo, *tmpNgMesh, initState, *_mesh, tmpNodeVec, comment );
2946 err = ( err || !comment.empty() );
2948 nglib::Ng_DeleteMesh((nglib::Ng_Mesh*)tmpNgMesh);
2951 // Fill _ngMesh with nodes and segments of computed submeshes
2954 err = ! ( FillNgMesh(occgeo, *_ngMesh, nodeVec, meshedSM[ MeshDim_0D ]) &&
2955 FillNgMesh(occgeo, *_ngMesh, nodeVec, meshedSM[ MeshDim_1D ], &quadHelper));
2957 initState = NETGENPlugin_ngMeshInfo(_ngMesh);
2962 startWith = endWith = netgen::MESHCONST_MESHEDGES;
2967 err = netgen::OCCGenerateMesh(occgeo, _ngMesh, mparams, startWith, endWith);
2969 err = netgen::OCCGenerateMesh(occgeo, _ngMesh, startWith, endWith, optstr);
2971 if(netgen::multithread.terminate)
2974 comment << text(err);
2976 catch (Standard_Failure& ex)
2978 comment << text(ex);
2983 _ticTime = ( doneTime += edgeMeshingTime ) / _totalTime / _progressTic;
2985 mparams.uselocalh = true; // restore as it is used at surface optimization
2987 // ---------------------
2988 // compute surface mesh
2989 // ---------------------
2992 // Pass 2D simple parameters to NETGEN
2994 if ( double area = _simpleHyp->GetMaxElementArea() ) {
2996 mparams.maxh = sqrt(2. * area/sqrt(3.0));
2997 mparams.grading = 0.4; // moderate size growth
3000 // length from edges
3001 if ( _ngMesh->GetNSeg() ) {
3002 double edgeLength = 0;
3003 TopTools_MapOfShape visitedEdges;
3004 for ( TopExp_Explorer exp( _shape, TopAbs_EDGE ); exp.More(); exp.Next() )
3005 if( visitedEdges.Add(exp.Current()) )
3006 edgeLength += SMESH_Algo::EdgeLength( TopoDS::Edge( exp.Current() ));
3007 // we have to multiply length by 2 since for each TopoDS_Edge there
3008 // are double set of NETGEN edges, in other words, we have to
3009 // divide _ngMesh->GetNSeg() by 2.
3010 mparams.maxh = 2*edgeLength / _ngMesh->GetNSeg();
3013 mparams.maxh = 1000;
3015 mparams.grading = 0.2; // slow size growth
3017 mparams.quad = _simpleHyp->GetAllowQuadrangles();
3018 mparams.maxh = min( mparams.maxh, occgeo.boundingbox.Diam()/2 );
3019 _ngMesh->SetGlobalH (mparams.maxh);
3020 netgen::Box<3> bb = occgeo.GetBoundingBox();
3021 bb.Increase (bb.Diam()/20);
3022 _ngMesh->SetLocalH (bb.PMin(), bb.PMax(), mparams.grading);
3025 // Care of vertices internal in faces (issue 0020676)
3026 if ( internals.hasInternalVertexInFace() )
3028 // store computed segments in SMESH in order not to create SMESH
3029 // edges for ng segments added by AddIntVerticesInFaces()
3030 FillSMesh( occgeo, *_ngMesh, initState, *_mesh, nodeVec, comment );
3031 // add segments to faces with internal vertices
3032 AddIntVerticesInFaces( occgeo, *_ngMesh, nodeVec, internals );
3033 initState = NETGENPlugin_ngMeshInfo(_ngMesh);
3036 // Build viscous layers
3037 if ( _isViscousLayers2D ||
3038 StdMeshers_ViscousLayers2D::HasProxyMesh( TopoDS::Face( occgeo.fmap(1) ), *_mesh ))
3040 if ( !internals.hasInternalVertexInFace() ) {
3041 FillSMesh( occgeo, *_ngMesh, initState, *_mesh, nodeVec, comment );
3042 initState = NETGENPlugin_ngMeshInfo(_ngMesh);
3044 SMESH_ProxyMesh::Ptr viscousMesh;
3045 SMESH_MesherHelper helper( *_mesh );
3046 for ( int faceID = 1; faceID <= occgeo.fmap.Extent(); ++faceID )
3048 const TopoDS_Face& F = TopoDS::Face( occgeo.fmap( faceID ));
3049 viscousMesh = StdMeshers_ViscousLayers2D::Compute( *_mesh, F );
3052 if ( viscousMesh->NbProxySubMeshes() == 0 )
3054 // exclude from computation ng segments built on EDGEs of F
3055 for (int i = 1; i <= _ngMesh->GetNSeg(); i++)
3057 netgen::Segment & seg = _ngMesh->LineSegment(i);
3058 if (seg.si == faceID)
3061 // add new segments to _ngMesh instead of excluded ones
3062 helper.SetSubShape( F );
3064 StdMeshers_FaceSide::GetFaceWires( F, *_mesh, /*skipMediumNodes=*/true,
3065 error, &helper, viscousMesh );
3066 error = AddSegmentsToMesh( *_ngMesh, occgeo, wires, helper, nodeVec );
3068 if ( !error ) error = SMESH_ComputeError::New();
3070 initState = NETGENPlugin_ngMeshInfo(_ngMesh);
3073 // Let netgen compute 2D mesh
3074 startWith = netgen::MESHCONST_MESHSURFACE;
3075 endWith = _optimize ? netgen::MESHCONST_OPTSURFACE : netgen::MESHCONST_MESHSURFACE;
3080 err = netgen::OCCGenerateMesh(occgeo, _ngMesh, mparams, startWith, endWith);
3082 err = netgen::OCCGenerateMesh(occgeo, _ngMesh, startWith, endWith, optstr);
3084 if(netgen::multithread.terminate)
3087 comment << text (err);
3089 catch (Standard_Failure& ex)
3091 comment << text(ex);
3092 //err = 1; -- try to make volumes anyway
3094 catch (netgen::NgException exc)
3096 comment << text(exc);
3097 //err = 1; -- try to make volumes anyway
3102 doneTime += faceMeshingTime + ( _optimize ? faceOptimizTime : 0 );
3103 _ticTime = doneTime / _totalTime / _progressTic;
3105 // ---------------------
3106 // generate volume mesh
3107 // ---------------------
3108 // Fill _ngMesh with nodes and faces of computed 2D submeshes
3109 if ( !err && _isVolume &&
3110 ( !meshedSM[ MeshDim_2D ].empty() || mparams.quad || _viscousLayersHyp ))
3112 // load SMESH with computed segments and faces
3113 FillSMesh( occgeo, *_ngMesh, initState, *_mesh, nodeVec, comment, &quadHelper );
3115 // compute prismatic boundary volumes
3116 int nbQuad = _mesh->NbQuadrangles();
3117 SMESH_ProxyMesh::Ptr viscousMesh;
3118 if ( _viscousLayersHyp )
3120 viscousMesh = _viscousLayersHyp->Compute( *_mesh, _shape );
3124 // compute pyramids on quadrangles
3125 vector<SMESH_ProxyMesh::Ptr> pyramidMeshes( occgeo.somap.Extent() );
3127 for ( int iS = 1; iS <= occgeo.somap.Extent(); ++iS )
3129 StdMeshers_QuadToTriaAdaptor* adaptor = new StdMeshers_QuadToTriaAdaptor;
3130 pyramidMeshes[ iS-1 ].reset( adaptor );
3131 bool ok = adaptor->Compute( *_mesh, occgeo.somap(iS), viscousMesh.get() );
3135 // add proxy faces to NG mesh
3136 list< SMESH_subMesh* > viscousSM;
3137 for ( int iS = 1; iS <= occgeo.somap.Extent(); ++iS )
3139 list< SMESH_subMesh* > quadFaceSM;
3140 for (TopExp_Explorer face(occgeo.somap(iS), TopAbs_FACE); face.More(); face.Next())
3141 if ( pyramidMeshes[iS-1] && pyramidMeshes[iS-1]->GetProxySubMesh( face.Current() ))
3143 quadFaceSM.push_back( _mesh->GetSubMesh( face.Current() ));
3144 meshedSM[ MeshDim_2D ].remove( quadFaceSM.back() );
3146 else if ( viscousMesh && viscousMesh->GetProxySubMesh( face.Current() ))
3148 viscousSM.push_back( _mesh->GetSubMesh( face.Current() ));
3149 meshedSM[ MeshDim_2D ].remove( viscousSM.back() );
3151 if ( !quadFaceSM.empty() )
3152 FillNgMesh(occgeo, *_ngMesh, nodeVec, quadFaceSM, &quadHelper, pyramidMeshes[iS-1]);
3154 if ( !viscousSM.empty() )
3155 FillNgMesh(occgeo, *_ngMesh, nodeVec, viscousSM, &quadHelper, viscousMesh );
3157 // fill _ngMesh with faces of sub-meshes
3158 err = ! ( FillNgMesh(occgeo, *_ngMesh, nodeVec, meshedSM[ MeshDim_2D ], &quadHelper));
3159 initState = NETGENPlugin_ngMeshInfo(_ngMesh, /*checkRemovedElems=*/true);
3160 // toPython( _ngMesh );
3162 if (!err && _isVolume)
3164 // Pass 3D simple parameters to NETGEN
3165 const NETGENPlugin_SimpleHypothesis_3D* simple3d =
3166 dynamic_cast< const NETGENPlugin_SimpleHypothesis_3D* > ( _simpleHyp );
3168 if ( double vol = simple3d->GetMaxElementVolume() ) {
3170 mparams.maxh = pow( 72, 1/6. ) * pow( vol, 1/3. );
3171 mparams.maxh = min( mparams.maxh, occgeo.boundingbox.Diam()/2 );
3174 // length from faces
3175 mparams.maxh = _ngMesh->AverageH();
3177 _ngMesh->SetGlobalH (mparams.maxh);
3178 mparams.grading = 0.4;
3180 _ngMesh->CalcLocalH(mparams.grading);
3182 _ngMesh->CalcLocalH();
3185 // Care of vertices internal in solids and internal faces (issue 0020676)
3186 if ( internals.hasInternalVertexInSolid() || internals.hasInternalFaces() )
3188 // store computed faces in SMESH in order not to create SMESH
3189 // faces for ng faces added here
3190 FillSMesh( occgeo, *_ngMesh, initState, *_mesh, nodeVec, comment, &quadHelper );
3191 // add ng faces to solids with internal vertices
3192 AddIntVerticesInSolids( occgeo, *_ngMesh, nodeVec, internals );
3193 // duplicate mesh faces on internal faces
3194 FixIntFaces( occgeo, *_ngMesh, internals );
3195 initState = NETGENPlugin_ngMeshInfo(_ngMesh);
3197 // Let netgen compute 3D mesh
3198 startWith = endWith = netgen::MESHCONST_MESHVOLUME;
3203 err = netgen::OCCGenerateMesh(occgeo, _ngMesh, mparams, startWith, endWith);
3205 err = netgen::OCCGenerateMesh(occgeo, _ngMesh, startWith, endWith, optstr);
3207 if(netgen::multithread.terminate)
3210 if ( comment.empty() ) // do not overwrite a previos error
3211 comment << text(err);
3213 catch (Standard_Failure& ex)
3215 if ( comment.empty() ) // do not overwrite a previos error
3216 comment << text(ex);
3219 catch (netgen::NgException exc)
3221 if ( comment.empty() ) // do not overwrite a previos error
3222 comment << text(exc);
3225 _ticTime = ( doneTime += voluMeshingTime ) / _totalTime / _progressTic;
3227 // Let netgen optimize 3D mesh
3228 if ( !err && _optimize )
3230 startWith = endWith = netgen::MESHCONST_OPTVOLUME;
3235 err = netgen::OCCGenerateMesh(occgeo, _ngMesh, mparams, startWith, endWith);
3237 err = netgen::OCCGenerateMesh(occgeo, _ngMesh, startWith, endWith, optstr);
3239 if(netgen::multithread.terminate)
3242 if ( comment.empty() ) // do not overwrite a previos error
3243 comment << text(err);
3245 catch (Standard_Failure& ex)
3247 if ( comment.empty() ) // do not overwrite a previos error
3248 comment << text(ex);
3250 catch (netgen::NgException exc)
3252 if ( comment.empty() ) // do not overwrite a previos error
3253 comment << text(exc);
3257 if (!err && mparams.secondorder > 0)
3262 if ( !meshedSM[ MeshDim_1D ].empty() )
3264 // remove segments not attached to geometry (IPAL0052479)
3265 for (int i = 1; i <= _ngMesh->GetNSeg(); ++i)
3267 const netgen::Segment & seg = _ngMesh->LineSegment (i);
3268 if ( seg.epgeominfo[ 0 ].edgenr == 0 )
3269 _ngMesh->DeleteSegment( i );
3271 _ngMesh->Compress();
3273 // convert to quadratic
3274 netgen::OCCRefinementSurfaces ref (occgeo);
3275 ref.MakeSecondOrder (*_ngMesh);
3277 // care of elements already loaded to SMESH
3278 // if ( initState._nbSegments > 0 )
3279 // makeQuadratic( occgeo.emap, _mesh );
3280 // if ( initState._nbFaces > 0 )
3281 // makeQuadratic( occgeo.fmap, _mesh );
3283 catch (Standard_Failure& ex)
3285 if ( comment.empty() ) // do not overwrite a previos error
3286 comment << "Exception in netgen at passing to 2nd order ";
3288 catch (netgen::NgException exc)
3290 if ( comment.empty() ) // do not overwrite a previos error
3291 comment << exc.What();
3296 _ticTime = 0.98 / _progressTic;
3298 //int nbNod = _ngMesh->GetNP();
3299 //int nbSeg = _ngMesh->GetNSeg();
3300 int nbFac = _ngMesh->GetNSE();
3301 int nbVol = _ngMesh->GetNE();
3302 bool isOK = ( !err && (_isVolume ? (nbVol > 0) : (nbFac > 0)) );
3304 // Feed back the SMESHDS with the generated Nodes and Elements
3305 if ( true /*isOK*/ ) // get whatever built
3307 FillSMesh( occgeo, *_ngMesh, initState, *_mesh, nodeVec, comment, &quadHelper );
3309 if ( quadHelper.GetIsQuadratic() ) // remove free nodes
3310 for ( size_t i = 0; i < nodeVec.size(); ++i )
3311 if ( nodeVec[i] && nodeVec[i]->NbInverseElements() == 0 )
3312 _mesh->GetMeshDS()->RemoveFreeNode( nodeVec[i], 0, /*fromGroups=*/false );
3314 SMESH_ComputeErrorPtr readErr = ReadErrors(nodeVec);
3315 if ( readErr && !readErr->myBadElements.empty() )
3318 if ( !comment.empty() && !readErr->myComment.empty() ) comment += "\n";
3319 comment += readErr->myComment;
3321 if ( error->IsOK() && ( !isOK || comment.size() > 0 ))
3322 error->myName = COMPERR_ALGO_FAILED;
3323 if ( !comment.empty() )
3324 error->myComment = comment;
3326 // SetIsAlwaysComputed( true ) to empty sub-meshes, which
3327 // appear if the geometry contains coincident sub-shape due
3328 // to bool merge_solids = 1; in netgen/libsrc/occ/occgenmesh.cpp
3329 const int nbMaps = 2;
3330 const TopTools_IndexedMapOfShape* geoMaps[nbMaps] =
3331 { & occgeo.vmap, & occgeo.emap/*, & occgeo.fmap*/ };
3332 for ( int iMap = 0; iMap < nbMaps; ++iMap )
3333 for (int i = 1; i <= geoMaps[iMap]->Extent(); i++)
3334 if ( SMESH_subMesh* sm = _mesh->GetSubMeshContaining( geoMaps[iMap]->FindKey(i)))
3335 if ( !sm->IsMeshComputed() )
3336 sm->SetIsAlwaysComputed( true );
3338 // set bad compute error to subshapes of all failed sub-shapes
3339 if ( !error->IsOK() )
3341 bool pb2D = false, pb3D = false;
3342 for (int i = 1; i <= occgeo.fmap.Extent(); i++) {
3343 int status = occgeo.facemeshstatus[i-1];
3344 if (status == netgen::FACE_MESHED_OK ) continue;
3345 if ( SMESH_subMesh* sm = _mesh->GetSubMeshContaining( occgeo.fmap( i ))) {
3346 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
3347 if ( !smError || smError->IsOK() ) {
3348 if ( status == netgen::FACE_FAILED )
3349 smError.reset( new SMESH_ComputeError( *error ));
3351 smError.reset( new SMESH_ComputeError( COMPERR_ALGO_FAILED, "Ignored" ));
3352 if ( SMESH_Algo::GetMeshError( sm ) == SMESH_Algo::MEr_OK )
3353 smError->myName = COMPERR_WARNING;
3355 pb2D = pb2D || smError->IsKO();
3358 if ( !pb2D ) // all faces are OK
3359 for (int i = 1; i <= occgeo.somap.Extent(); i++)
3360 if ( SMESH_subMesh* sm = _mesh->GetSubMeshContaining( occgeo.somap( i )))
3362 bool smComputed = nbVol && !sm->IsEmpty();
3363 if ( smComputed && internals.hasInternalVertexInSolid( sm->GetId() ))
3365 int nbIntV = internals.getSolidsWithVertices().find( sm->GetId() )->second.size();
3366 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
3367 smComputed = ( smDS->NbElements() > 0 || smDS->NbNodes() > nbIntV );
3369 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
3370 if ( !smComputed && ( !smError || smError->IsOK() ))
3372 smError.reset( new SMESH_ComputeError( *error ));
3373 if ( nbVol && SMESH_Algo::GetMeshError( sm ) == SMESH_Algo::MEr_OK )
3375 smError->myName = COMPERR_WARNING;
3377 else if ( !smError->myBadElements.empty() ) // bad surface mesh
3379 if ( !hasBadElemOnSolid( smError->myBadElements, sm ))
3383 pb3D = pb3D || ( smError && smError->IsKO() );
3385 if ( !pb2D && !pb3D )
3386 err = 0; // no fatal errors, only warnings
3389 ngLib._isComputeOk = !err;
3394 //=============================================================================
3398 //=============================================================================
3399 bool NETGENPlugin_Mesher::Evaluate(MapShapeNbElems& aResMap)
3401 netgen::MeshingParameters& mparams = netgen::mparam;
3404 // -------------------------
3405 // Prepare OCC geometry
3406 // -------------------------
3407 netgen::OCCGeometry occgeo;
3408 list< SMESH_subMesh* > meshedSM[4]; // for 0-3 dimensions
3409 NETGENPlugin_Internals internals( *_mesh, _shape, _isVolume );
3410 PrepareOCCgeometry( occgeo, _shape, *_mesh, meshedSM, &internals );
3412 bool tooManyElems = false;
3413 const int hugeNb = std::numeric_limits<int>::max() / 100;
3418 // pass 1D simple parameters to NETGEN
3421 // not to RestrictLocalH() according to curvature during MESHCONST_ANALYSE
3422 mparams.uselocalh = false;
3423 mparams.grading = 0.8; // not limitited size growth
3425 if ( _simpleHyp->GetNumberOfSegments() )
3427 mparams.maxh = occgeo.boundingbox.Diam();
3430 mparams.maxh = _simpleHyp->GetLocalLength();
3433 if ( mparams.maxh == 0.0 )
3434 mparams.maxh = occgeo.boundingbox.Diam();
3435 if ( _simpleHyp || ( mparams.minh == 0.0 && _fineness != NETGENPlugin_Hypothesis::UserDefined))
3436 mparams.minh = GetDefaultMinSize( _shape, mparams.maxh );
3438 // let netgen create _ngMesh and calculate element size on not meshed shapes
3439 NETGENPlugin_NetgenLibWrapper ngLib;
3440 netgen::Mesh *ngMesh = NULL;
3444 int startWith = netgen::MESHCONST_ANALYSE;
3445 int endWith = netgen::MESHCONST_MESHEDGES;
3447 int err = netgen::OCCGenerateMesh(occgeo, ngMesh, mparams, startWith, endWith);
3449 int err = netgen::OCCGenerateMesh(occgeo, ngMesh, startWith, endWith, optstr);
3452 if(netgen::multithread.terminate)
3455 ngLib.setMesh(( Ng_Mesh*) ngMesh );
3457 if ( SMESH_subMesh* sm = _mesh->GetSubMeshContaining( _shape ))
3458 sm->GetComputeError().reset( new SMESH_ComputeError( COMPERR_ALGO_FAILED ));
3461 // if ( _simpleHyp )
3463 // // Pass 1D simple parameters to NETGEN
3464 // // --------------------------------
3465 // int nbSeg = _simpleHyp->GetNumberOfSegments();
3466 // double segSize = _simpleHyp->GetLocalLength();
3467 // for ( int iE = 1; iE <= occgeo.emap.Extent(); ++iE )
3469 // const TopoDS_Edge& e = TopoDS::Edge( occgeo.emap(iE));
3471 // segSize = SMESH_Algo::EdgeLength( e ) / ( nbSeg - 0.4 );
3472 // setLocalSize( e, segSize, *ngMesh );
3475 // else // if ( ! _simpleHyp )
3477 // // Local size on shapes
3478 // SetLocalSize( occgeo, *ngMesh );
3480 // calculate total nb of segments and length of edges
3481 double fullLen = 0.0;
3483 int entity = mparams.secondorder > 0 ? SMDSEntity_Quad_Edge : SMDSEntity_Edge;
3484 TopTools_DataMapOfShapeInteger Edge2NbSeg;
3485 for (TopExp_Explorer exp(_shape, TopAbs_EDGE); exp.More(); exp.Next())
3487 TopoDS_Edge E = TopoDS::Edge( exp.Current() );
3488 if( !Edge2NbSeg.Bind(E,0) )
3491 double aLen = SMESH_Algo::EdgeLength(E);
3494 vector<int>& aVec = aResMap[_mesh->GetSubMesh(E)];
3496 aVec.resize( SMDSEntity_Last, 0);
3498 fullNbSeg += aVec[ entity ];
3501 // store nb of segments computed by Netgen
3502 NCollection_Map<Link> linkMap;
3503 for (int i = 1; i <= ngMesh->GetNSeg(); ++i )
3505 const netgen::Segment& seg = ngMesh->LineSegment(i);
3506 Link link(seg[0], seg[1]);
3507 if ( !linkMap.Add( link )) continue;
3508 int aGeomEdgeInd = seg.epgeominfo[0].edgenr;
3509 if (aGeomEdgeInd > 0 && aGeomEdgeInd <= occgeo.emap.Extent())
3511 vector<int>& aVec = aResMap[_mesh->GetSubMesh(occgeo.emap(aGeomEdgeInd))];
3515 // store nb of nodes on edges computed by Netgen
3516 TopTools_DataMapIteratorOfDataMapOfShapeInteger Edge2NbSegIt(Edge2NbSeg);
3517 for (; Edge2NbSegIt.More(); Edge2NbSegIt.Next())
3519 vector<int>& aVec = aResMap[_mesh->GetSubMesh(Edge2NbSegIt.Key())];
3520 if ( aVec[ entity ] > 1 && aVec[ SMDSEntity_Node ] == 0 )
3521 aVec[SMDSEntity_Node] = mparams.secondorder > 0 ? 2*aVec[ entity ]-1 : aVec[ entity ]-1;
3523 fullNbSeg += aVec[ entity ];
3524 Edge2NbSeg( Edge2NbSegIt.Key() ) = aVec[ entity ];
3526 if ( fullNbSeg == 0 )
3533 if ( double area = _simpleHyp->GetMaxElementArea() ) {
3535 mparams.maxh = sqrt(2. * area/sqrt(3.0));
3536 mparams.grading = 0.4; // moderate size growth
3539 // length from edges
3540 mparams.maxh = fullLen/fullNbSeg;
3541 mparams.grading = 0.2; // slow size growth
3544 mparams.maxh = min( mparams.maxh, occgeo.boundingbox.Diam()/2 );
3545 mparams.maxh = min( mparams.maxh, fullLen/fullNbSeg * (1. + mparams.grading));
3547 for (TopExp_Explorer exp(_shape, TopAbs_FACE); exp.More(); exp.Next())
3549 TopoDS_Face F = TopoDS::Face( exp.Current() );
3550 SMESH_subMesh *sm = _mesh->GetSubMesh(F);
3552 BRepGProp::SurfaceProperties(F,G);
3553 double anArea = G.Mass();
3554 tooManyElems = tooManyElems || ( anArea/hugeNb > mparams.maxh*mparams.maxh );
3556 if ( !tooManyElems )
3558 TopTools_MapOfShape egdes;
3559 for (TopExp_Explorer exp1(F,TopAbs_EDGE); exp1.More(); exp1.Next())
3560 if ( egdes.Add( exp1.Current() ))
3561 nb1d += Edge2NbSeg.Find(exp1.Current());
3563 int nbFaces = tooManyElems ? hugeNb : int( 4*anArea / (mparams.maxh*mparams.maxh*sqrt(3.)));
3564 int nbNodes = tooManyElems ? hugeNb : (( nbFaces*3 - (nb1d-1)*2 ) / 6 + 1 );
3566 vector<int> aVec(SMDSEntity_Last, 0);
3567 if( mparams.secondorder > 0 ) {
3568 int nb1d_in = (nbFaces*3 - nb1d) / 2;
3569 aVec[SMDSEntity_Node] = nbNodes + nb1d_in;
3570 aVec[SMDSEntity_Quad_Triangle] = nbFaces;
3573 aVec[SMDSEntity_Node] = Max ( nbNodes, 0 );
3574 aVec[SMDSEntity_Triangle] = nbFaces;
3576 aResMap[sm].swap(aVec);
3583 // pass 3D simple parameters to NETGEN
3584 const NETGENPlugin_SimpleHypothesis_3D* simple3d =
3585 dynamic_cast< const NETGENPlugin_SimpleHypothesis_3D* > ( _simpleHyp );
3587 if ( double vol = simple3d->GetMaxElementVolume() ) {
3589 mparams.maxh = pow( 72, 1/6. ) * pow( vol, 1/3. );
3590 mparams.maxh = min( mparams.maxh, occgeo.boundingbox.Diam()/2 );
3593 // using previous length from faces
3595 mparams.grading = 0.4;
3596 mparams.maxh = min( mparams.maxh, fullLen/fullNbSeg * (1. + mparams.grading));
3599 BRepGProp::VolumeProperties(_shape,G);
3600 double aVolume = G.Mass();
3601 double tetrVol = 0.1179*mparams.maxh*mparams.maxh*mparams.maxh;
3602 tooManyElems = tooManyElems || ( aVolume/hugeNb > tetrVol );
3603 int nbVols = tooManyElems ? hugeNb : int(aVolume/tetrVol);
3604 int nb1d_in = int(( nbVols*6 - fullNbSeg ) / 6 );
3605 vector<int> aVec(SMDSEntity_Last, 0 );
3606 if ( tooManyElems ) // avoid FPE
3608 aVec[SMDSEntity_Node] = hugeNb;
3609 aVec[ mparams.secondorder > 0 ? SMDSEntity_Quad_Tetra : SMDSEntity_Tetra] = hugeNb;
3613 if( mparams.secondorder > 0 ) {
3614 aVec[SMDSEntity_Node] = nb1d_in/3 + 1 + nb1d_in;
3615 aVec[SMDSEntity_Quad_Tetra] = nbVols;
3618 aVec[SMDSEntity_Node] = nb1d_in/3 + 1;
3619 aVec[SMDSEntity_Tetra] = nbVols;
3622 SMESH_subMesh *sm = _mesh->GetSubMesh(_shape);
3623 aResMap[sm].swap(aVec);
3629 double NETGENPlugin_Mesher::GetProgress(const SMESH_Algo* holder,
3630 const int * algoProgressTic,
3631 const double * algoProgress) const
3633 ((int&) _progressTic ) = *algoProgressTic + 1;
3635 if ( !_occgeom ) return 0;
3637 double progress = -1;
3640 if ( _ticTime < 0 && netgen::multithread.task[0] == 'O'/*Optimizing surface*/ )
3642 ((double&) _ticTime ) = edgeFaceMeshingTime / _totalTime / _progressTic;
3644 else if ( !_optimize /*&& _occgeom->fmap.Extent() > 1*/ )
3646 int doneShapeIndex = -1;
3647 while ( doneShapeIndex+1 < _occgeom->facemeshstatus.Size() &&
3648 _occgeom->facemeshstatus[ doneShapeIndex+1 ])
3650 if ( doneShapeIndex+1 != _curShapeIndex )
3652 ((int&) _curShapeIndex) = doneShapeIndex+1;
3653 double doneShapeRate = _curShapeIndex / double( _occgeom->fmap.Extent() );
3654 double doneTime = edgeMeshingTime + doneShapeRate * faceMeshingTime;
3655 ((double&) _ticTime) = doneTime / _totalTime / _progressTic;
3656 // cout << "shape " << _curShapeIndex << " _ticTime " << _ticTime
3657 // << " " << doneTime / _totalTime / _progressTic << endl;
3661 else if ( !_optimize && _occgeom->somap.Extent() > 1 )
3663 int curShapeIndex = _curShapeIndex;
3664 if ( _ngMesh->GetNE() > 0 )
3666 netgen::Element el = (*_ngMesh)[netgen::ElementIndex( _ngMesh->GetNE()-1 )];
3667 curShapeIndex = el.GetIndex();
3669 if ( curShapeIndex != _curShapeIndex )
3671 ((int&) _curShapeIndex) = curShapeIndex;
3672 double doneShapeRate = _curShapeIndex / double( _occgeom->somap.Extent() );
3673 double doneTime = edgeFaceMeshingTime + doneShapeRate * voluMeshingTime;
3674 ((double&) _ticTime) = doneTime / _totalTime / _progressTic;
3675 // cout << "shape " << _curShapeIndex << " _ticTime " << _ticTime
3676 // << " " << doneTime / _totalTime / _progressTic << endl;
3681 progress = Max( *algoProgressTic * _ticTime, *algoProgress );
3686 netgen::multithread.task[0] == 'D'/*elaunay meshing*/ &&
3687 progress > voluMeshingTime )
3689 progress = voluMeshingTime;
3690 ((double&) _ticTime) = voluMeshingTime / _totalTime / _progressTic;
3692 ((int&) *algoProgressTic )++;
3693 ((double&) *algoProgress) = progress;
3695 //cout << progress << " " << *algoProgressTic << " " << netgen::multithread.task << " "<< _ticTime << endl;
3697 return Min( progress, 0.99 );
3700 //================================================================================
3702 * \brief Read mesh entities preventing successful computation from "test.out" file
3704 //================================================================================
3706 SMESH_ComputeErrorPtr
3707 NETGENPlugin_Mesher::ReadErrors(const vector<const SMDS_MeshNode* >& nodeVec)
3709 SMESH_ComputeErrorPtr err = SMESH_ComputeError::New
3710 (COMPERR_BAD_INPUT_MESH, "Some edges multiple times in surface mesh");
3711 SMESH_File file("test.out");
3713 vector<int> three1(3), three2(3);
3714 const char* badEdgeStr = " multiple times in surface mesh";
3715 const int badEdgeStrLen = strlen( badEdgeStr );
3716 const int nbNodes = nodeVec.size();
3718 while( !file.eof() )
3720 if ( strncmp( file, "Edge ", 5 ) == 0 &&
3721 file.getInts( two ) &&
3722 strncmp( file, badEdgeStr, badEdgeStrLen ) == 0 &&
3723 two[0] < nbNodes && two[1] < nbNodes )
3725 err->myBadElements.push_back( new SMDS_LinearEdge( nodeVec[ two[0]], nodeVec[ two[1]] ));
3726 file += badEdgeStrLen;
3728 else if ( strncmp( file, "Intersecting: ", 14 ) == 0 )
3731 // openelement 18 with open element 126
3735 const char* pos = file;
3736 bool ok = ( strncmp( file, "openelement ", 12 ) == 0 );
3737 ok = ok && file.getInts( two );
3738 ok = ok && file.getInts( three1 );
3739 ok = ok && file.getInts( three2 );
3740 for ( int i = 0; ok && i < 3; ++i )
3741 ok = ( three1[i] < nbNodes && nodeVec[ three1[i]]);
3742 for ( int i = 0; ok && i < 3; ++i )
3743 ok = ( three2[i] < nbNodes && nodeVec[ three2[i]]);
3746 err->myBadElements.push_back( new SMDS_FaceOfNodes( nodeVec[ three1[0]],
3747 nodeVec[ three1[1]],
3748 nodeVec[ three1[2]]));
3749 err->myBadElements.push_back( new SMDS_FaceOfNodes( nodeVec[ three2[0]],
3750 nodeVec[ three2[1]],
3751 nodeVec[ three2[2]]));
3752 err->myComment = "Intersecting triangles";
3766 size_t nbBadElems = err->myBadElements.size();
3767 if ( nbBadElems ) nbBadElems++; // avoid warning: variable set but not used
3773 //================================================================================
3775 * \brief Write a python script creating an equivalent SALOME mesh.
3776 * This is useful to see what mesh is passed as input for the next step of mesh
3777 * generation (of mesh of higher dimension)
3779 //================================================================================
3781 void NETGENPlugin_Mesher::toPython( const netgen::Mesh* ngMesh )
3783 const char* pyFile = "/tmp/ngMesh.py";
3784 ofstream outfile( pyFile, ios::out );
3785 if ( !outfile ) return;
3787 outfile << "import salome, SMESH" << endl
3788 << "from salome.smesh import smeshBuilder" << endl
3789 << "smesh = smeshBuilder.New()" << endl
3790 << "mesh = smesh.Mesh()" << endl << endl;
3792 using namespace netgen;
3794 for (pi = PointIndex::BASE;
3795 pi < ngMesh->GetNP()+PointIndex::BASE; pi++)
3797 outfile << "mesh.AddNode( ";
3798 outfile << (*ngMesh)[pi](0) << ", ";
3799 outfile << (*ngMesh)[pi](1) << ", ";
3800 outfile << (*ngMesh)[pi](2) << ") ## "<< pi << endl;
3803 int nbDom = ngMesh->GetNDomains();
3804 for ( int i = 0; i < nbDom; ++i )
3805 outfile<< "grp" << i+1 << " = mesh.CreateEmptyGroup( SMESH.FACE, 'domain"<< i+1 << "')"<< endl;
3807 SurfaceElementIndex sei;
3808 for (sei = 0; sei < ngMesh->GetNSE(); sei++)
3810 outfile << "mesh.AddFace([ ";
3811 Element2d sel = (*ngMesh)[sei];
3812 for (int j = 0; j < sel.GetNP(); j++)
3813 outfile << sel[j] << ( j+1 < sel.GetNP() ? ", " : " ])");
3814 if ( sel.IsDeleted() ) outfile << " ## IsDeleted ";
3817 if ((*ngMesh)[sei].GetIndex())
3819 if ( int dom1 = ngMesh->GetFaceDescriptor((*ngMesh)[sei].GetIndex ()).DomainIn())
3820 outfile << "grp"<< dom1 <<".Add([ " << (int)sei+1 << " ])" << endl;
3821 if ( int dom2 = ngMesh->GetFaceDescriptor((*ngMesh)[sei].GetIndex ()).DomainOut())
3822 outfile << "grp"<< dom2 <<".Add([ " << (int)sei+1 << " ])" << endl;
3826 for (ElementIndex ei = 0; ei < ngMesh->GetNE(); ei++)
3828 Element el = (*ngMesh)[ei];
3829 outfile << "mesh.AddVolume([ ";
3830 for (int j = 0; j < el.GetNP(); j++)
3831 outfile << el[j] << ( j+1 < el.GetNP() ? ", " : " ])");
3835 for (int i = 1; i <= ngMesh->GetNSeg(); i++)
3837 const Segment & seg = ngMesh->LineSegment (i);
3838 outfile << "mesh.AddEdge([ "
3840 << seg[1] << " ])" << endl;
3842 cout << "Write " << pyFile << endl;
3845 //================================================================================
3847 * \brief Constructor of NETGENPlugin_ngMeshInfo
3849 //================================================================================
3851 NETGENPlugin_ngMeshInfo::NETGENPlugin_ngMeshInfo( netgen::Mesh* ngMesh,
3852 bool checkRemovedElems):
3853 _elementsRemoved( false ), _copyOfLocalH(0)
3857 _nbNodes = ngMesh->GetNP();
3858 _nbSegments = ngMesh->GetNSeg();
3859 _nbFaces = ngMesh->GetNSE();
3860 _nbVolumes = ngMesh->GetNE();
3862 if ( checkRemovedElems )
3863 for ( int i = 1; i <= ngMesh->GetNSE() && !_elementsRemoved; ++i )
3864 _elementsRemoved = ngMesh->SurfaceElement(i).IsDeleted();
3868 _nbNodes = _nbSegments = _nbFaces = _nbVolumes = 0;
3872 //================================================================================
3874 * \brief Copy LocalH member from one netgen mesh to another
3876 //================================================================================
3878 void NETGENPlugin_ngMeshInfo::transferLocalH( netgen::Mesh* fromMesh,
3879 netgen::Mesh* toMesh )
3881 if ( !fromMesh->LocalHFunctionGenerated() ) return;
3882 if ( !toMesh->LocalHFunctionGenerated() )
3884 toMesh->CalcLocalH(netgen::mparam.grading);
3886 toMesh->CalcLocalH();
3889 const size_t size = sizeof( netgen::LocalH );
3890 _copyOfLocalH = new char[ size ];
3891 memcpy( (void*)_copyOfLocalH, (void*)&toMesh->LocalHFunction(), size );
3892 memcpy( (void*)&toMesh->LocalHFunction(), (void*)&fromMesh->LocalHFunction(), size );
3895 //================================================================================
3897 * \brief Restore LocalH member of a netgen mesh
3899 //================================================================================
3901 void NETGENPlugin_ngMeshInfo::restoreLocalH( netgen::Mesh* toMesh )
3903 if ( _copyOfLocalH )
3905 const size_t size = sizeof( netgen::LocalH );
3906 memcpy( (void*)&toMesh->LocalHFunction(), (void*)_copyOfLocalH, size );
3907 delete [] _copyOfLocalH;
3912 //================================================================================
3914 * \brief Find "internal" sub-shapes
3916 //================================================================================
3918 NETGENPlugin_Internals::NETGENPlugin_Internals( SMESH_Mesh& mesh,
3919 const TopoDS_Shape& shape,
3921 : _mesh( mesh ), _is3D( is3D )
3923 SMESHDS_Mesh* meshDS = mesh.GetMeshDS();
3925 TopExp_Explorer f,e;
3926 for ( f.Init( shape, TopAbs_FACE ); f.More(); f.Next() )
3928 int faceID = meshDS->ShapeToIndex( f.Current() );
3930 // find not computed internal edges
3932 for ( e.Init( f.Current().Oriented(TopAbs_FORWARD), TopAbs_EDGE ); e.More(); e.Next() )
3933 if ( e.Current().Orientation() == TopAbs_INTERNAL )
3935 SMESH_subMesh* eSM = mesh.GetSubMesh( e.Current() );
3936 if ( eSM->IsEmpty() )
3938 _e2face.insert( make_pair( eSM->GetId(), faceID ));
3939 for ( TopoDS_Iterator v(e.Current()); v.More(); v.Next() )
3940 _e2face.insert( make_pair( meshDS->ShapeToIndex( v.Value() ), faceID ));
3944 // find internal vertices in a face
3945 set<int> intVV; // issue 0020850 where same vertex is twice in a face
3946 for ( TopoDS_Iterator fSub( f.Current() ); fSub.More(); fSub.Next())
3947 if ( fSub.Value().ShapeType() == TopAbs_VERTEX )
3949 int vID = meshDS->ShapeToIndex( fSub.Value() );
3950 if ( intVV.insert( vID ).second )
3951 _f2v[ faceID ].push_back( vID );
3956 // find internal faces and their subshapes where nodes are to be doubled
3957 // to make a crack with non-sewed borders
3959 if ( f.Current().Orientation() == TopAbs_INTERNAL )
3961 _intShapes.insert( meshDS->ShapeToIndex( f.Current() ));
3964 list< TopoDS_Shape > edges;
3965 for ( e.Init( f.Current(), TopAbs_EDGE ); e.More(); e.Next())
3966 if ( SMESH_MesherHelper::NbAncestors( e.Current(), mesh, TopAbs_FACE ) > 1 )
3968 _intShapes.insert( meshDS->ShapeToIndex( e.Current() ));
3969 edges.push_back( e.Current() );
3970 // find border faces
3971 PShapeIteratorPtr fIt =
3972 SMESH_MesherHelper::GetAncestors( edges.back(),mesh,TopAbs_FACE );
3973 while ( const TopoDS_Shape* pFace = fIt->next() )
3974 if ( !pFace->IsSame( f.Current() ))
3975 _borderFaces.insert( meshDS->ShapeToIndex( *pFace ));
3978 // we consider vertex internal if it is shared by more than one internal edge
3979 list< TopoDS_Shape >::iterator edge = edges.begin();
3980 for ( ; edge != edges.end(); ++edge )
3981 for ( TopoDS_Iterator v( *edge ); v.More(); v.Next() )
3983 set<int> internalEdges;
3984 PShapeIteratorPtr eIt =
3985 SMESH_MesherHelper::GetAncestors( v.Value(),mesh,TopAbs_EDGE );
3986 while ( const TopoDS_Shape* pEdge = eIt->next() )
3988 int edgeID = meshDS->ShapeToIndex( *pEdge );
3989 if ( isInternalShape( edgeID ))
3990 internalEdges.insert( edgeID );
3992 if ( internalEdges.size() > 1 )
3993 _intShapes.insert( meshDS->ShapeToIndex( v.Value() ));
3997 } // loop on geom faces
3999 // find vertices internal in solids
4002 for ( TopExp_Explorer so(shape, TopAbs_SOLID); so.More(); so.Next())
4004 int soID = meshDS->ShapeToIndex( so.Current() );
4005 for ( TopoDS_Iterator soSub( so.Current() ); soSub.More(); soSub.Next())
4006 if ( soSub.Value().ShapeType() == TopAbs_VERTEX )
4007 _s2v[ soID ].push_back( meshDS->ShapeToIndex( soSub.Value() ));
4012 //================================================================================
4014 * \brief Find mesh faces on non-internal geom faces sharing internal edge
4015 * some nodes of which are to be doubled to make the second border of the "crack"
4017 //================================================================================
4019 void NETGENPlugin_Internals::findBorderElements( TIDSortedElemSet & borderElems )
4021 if ( _intShapes.empty() ) return;
4023 SMESH_Mesh& mesh = const_cast<SMESH_Mesh&>(_mesh);
4024 SMESHDS_Mesh* meshDS = mesh.GetMeshDS();
4026 // loop on internal geom edges
4027 set<int>::const_iterator intShapeId = _intShapes.begin();
4028 for ( ; intShapeId != _intShapes.end(); ++intShapeId )
4030 const TopoDS_Shape& s = meshDS->IndexToShape( *intShapeId );
4031 if ( s.ShapeType() != TopAbs_EDGE ) continue;
4033 // get internal and non-internal geom faces sharing the internal edge <s>
4035 set<int>::iterator bordFace = _borderFaces.end();
4036 PShapeIteratorPtr faces = SMESH_MesherHelper::GetAncestors( s, _mesh, TopAbs_FACE );
4037 while ( const TopoDS_Shape* pFace = faces->next() )
4039 int faceID = meshDS->ShapeToIndex( *pFace );
4040 if ( isInternalShape( faceID ))
4043 bordFace = _borderFaces.insert( faceID ).first;
4045 if ( bordFace == _borderFaces.end() || !intFace ) continue;
4047 // get all links of mesh faces on internal geom face sharing nodes on edge <s>
4048 set< SMESH_OrientedLink > links; //!< links of faces on internal geom face
4049 list<const SMDS_MeshElement*> suspectFaces[2]; //!< mesh faces on border geom faces
4050 int nbSuspectFaces = 0;
4051 SMESHDS_SubMesh* intFaceSM = meshDS->MeshElements( intFace );
4052 if ( !intFaceSM || intFaceSM->NbElements() == 0 ) continue;
4053 SMESH_subMeshIteratorPtr smIt = mesh.GetSubMesh( s )->getDependsOnIterator(true,true);
4054 while ( smIt->more() )
4056 SMESHDS_SubMesh* sm = smIt->next()->GetSubMeshDS();
4057 if ( !sm ) continue;
4058 SMDS_NodeIteratorPtr nIt = sm->GetNodes();
4059 while ( nIt->more() )
4061 const SMDS_MeshNode* nOnEdge = nIt->next();
4062 SMDS_ElemIteratorPtr fIt = nOnEdge->GetInverseElementIterator(SMDSAbs_Face);
4063 while ( fIt->more() )
4065 const SMDS_MeshElement* f = fIt->next();
4066 const int nbNodes = f->NbCornerNodes();
4067 if ( intFaceSM->Contains( f ))
4069 for ( int i = 0; i < nbNodes; ++i )
4070 links.insert( SMESH_OrientedLink( f->GetNode(i), f->GetNode((i+1)%nbNodes)));
4075 for ( int i = 0; i < nbNodes; ++i )
4076 nbDblNodes += isInternalShape( f->GetNode(i)->getshapeId() );
4078 suspectFaces[ nbDblNodes < 2 ].push_back( f );
4084 // suspectFaces[0] having link with same orientation as mesh faces on
4085 // the internal geom face are <borderElems>. suspectFaces[1] have
4086 // only one node on edge <s>, we decide on them later (at the 2nd loop)
4087 // by links of <borderElems> found at the 1st and 2nd loops
4088 set< SMESH_OrientedLink > borderLinks;
4089 for ( int isPostponed = 0; isPostponed < 2; ++isPostponed )
4091 list<const SMDS_MeshElement*>::iterator fIt = suspectFaces[isPostponed].begin();
4092 for ( int nbF = 0; fIt != suspectFaces[isPostponed].end(); ++fIt, ++nbF )
4094 const SMDS_MeshElement* f = *fIt;
4095 bool isBorder = false, linkFound = false, borderLinkFound = false;
4096 list< SMESH_OrientedLink > faceLinks;
4097 int nbNodes = f->NbCornerNodes();
4098 for ( int i = 0; i < nbNodes; ++i )
4100 SMESH_OrientedLink link( f->GetNode(i), f->GetNode((i+1)%nbNodes));
4101 faceLinks.push_back( link );
4104 set< SMESH_OrientedLink >::iterator foundLink = links.find( link );
4105 if ( foundLink != links.end() )
4108 isBorder = ( foundLink->_reversed == link._reversed );
4109 if ( !isBorder && !isPostponed ) break;
4110 faceLinks.pop_back();
4112 else if ( isPostponed && !borderLinkFound )
4114 foundLink = borderLinks.find( link );
4115 if ( foundLink != borderLinks.end() )
4117 borderLinkFound = true;
4118 isBorder = ( foundLink->_reversed != link._reversed );
4125 borderElems.insert( f );
4126 borderLinks.insert( faceLinks.begin(), faceLinks.end() );
4128 else if ( !linkFound && !borderLinkFound )
4130 suspectFaces[1].push_back( f );
4131 if ( nbF > 2 * nbSuspectFaces )
4132 break; // dead loop protection
4139 //================================================================================
4141 * \brief put internal shapes in maps and fill in submeshes to precompute
4143 //================================================================================
4145 void NETGENPlugin_Internals::getInternalEdges( TopTools_IndexedMapOfShape& fmap,
4146 TopTools_IndexedMapOfShape& emap,
4147 TopTools_IndexedMapOfShape& vmap,
4148 list< SMESH_subMesh* > smToPrecompute[])
4150 if ( !hasInternalEdges() ) return;
4151 map<int,int>::const_iterator ev_face = _e2face.begin();
4152 for ( ; ev_face != _e2face.end(); ++ev_face )
4154 const TopoDS_Shape& ev = _mesh.GetMeshDS()->IndexToShape( ev_face->first );
4155 const TopoDS_Shape& face = _mesh.GetMeshDS()->IndexToShape( ev_face->second );
4157 ( ev.ShapeType() == TopAbs_EDGE ? emap : vmap ).Add( ev );
4159 //cout<<"INTERNAL EDGE or VERTEX "<<ev_face->first<<" on face "<<ev_face->second<<endl;
4161 smToPrecompute[ MeshDim_1D ].push_back( _mesh.GetSubMeshContaining( ev_face->first ));
4165 //================================================================================
4167 * \brief return shapes and submeshes to be meshed and already meshed boundary submeshes
4169 //================================================================================
4171 void NETGENPlugin_Internals::getInternalFaces( TopTools_IndexedMapOfShape& fmap,
4172 TopTools_IndexedMapOfShape& emap,
4173 list< SMESH_subMesh* >& intFaceSM,
4174 list< SMESH_subMesh* >& boundarySM)
4176 if ( !hasInternalFaces() ) return;
4178 // <fmap> and <emap> are for not yet meshed shapes
4179 // <intFaceSM> is for submeshes of faces
4180 // <boundarySM> is for meshed edges and vertices
4185 set<int> shapeIDs ( _intShapes );
4186 if ( !_borderFaces.empty() )
4187 shapeIDs.insert( _borderFaces.begin(), _borderFaces.end() );
4189 set<int>::const_iterator intS = shapeIDs.begin();
4190 for ( ; intS != shapeIDs.end(); ++intS )
4192 SMESH_subMesh* sm = _mesh.GetSubMeshContaining( *intS );
4194 if ( sm->GetSubShape().ShapeType() != TopAbs_FACE ) continue;
4196 intFaceSM.push_back( sm );
4198 // add submeshes of not computed internal faces
4199 if ( !sm->IsEmpty() ) continue;
4201 SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(true,true);
4202 while ( smIt->more() )
4205 const TopoDS_Shape& s = sm->GetSubShape();
4207 if ( sm->IsEmpty() )
4210 switch ( s.ShapeType() ) {
4211 case TopAbs_FACE: fmap.Add ( s ); break;
4212 case TopAbs_EDGE: emap.Add ( s ); break;
4218 if ( s.ShapeType() != TopAbs_FACE )
4219 boundarySM.push_back( sm );
4225 //================================================================================
4227 * \brief Return true if given shape is to be precomputed in order to be correctly
4228 * added to netgen mesh
4230 //================================================================================
4232 bool NETGENPlugin_Internals::isShapeToPrecompute(const TopoDS_Shape& s)
4234 int shapeID = _mesh.GetMeshDS()->ShapeToIndex( s );
4235 switch ( s.ShapeType() ) {
4236 case TopAbs_FACE : break; //return isInternalShape( shapeID ) || isBorderFace( shapeID );
4237 case TopAbs_EDGE : return isInternalEdge( shapeID );
4238 case TopAbs_VERTEX: break;
4244 //================================================================================
4246 * \brief Return SMESH
4248 //================================================================================
4250 SMESH_Mesh& NETGENPlugin_Internals::getMesh() const
4252 return const_cast<SMESH_Mesh&>( _mesh );
4255 //================================================================================
4257 * \brief Access to a counter of NETGENPlugin_NetgenLibWrapper instances
4259 //================================================================================
4261 int& NETGENPlugin_NetgenLibWrapper::instanceCounter()
4263 static int theCouner = 0;
4267 //================================================================================
4269 * \brief Initialize netgen library
4271 //================================================================================
4273 NETGENPlugin_NetgenLibWrapper::NETGENPlugin_NetgenLibWrapper()
4275 if ( instanceCounter() == 0 )
4278 ++instanceCounter();
4280 _isComputeOk = false;
4284 if ( !getenv( "KEEP_NETGEN_OUTPUT" ))
4286 // redirect all netgen output (mycout,myerr,cout) to _outputFileName
4287 _outputFileName = getOutputFileName();
4288 _ngcout = netgen::mycout;
4289 _ngcerr = netgen::myerr;
4290 netgen::mycout = new ofstream ( _outputFileName.c_str() );
4291 netgen::myerr = netgen::mycout;
4292 _coutBuffer = std::cout.rdbuf();
4294 cout << "NOTE: netgen output is redirected to file " << _outputFileName << endl;
4296 std::cout.rdbuf( netgen::mycout->rdbuf() );
4300 _ngMesh = Ng_NewMesh();
4303 //================================================================================
4305 * \brief Finish using netgen library
4307 //================================================================================
4309 NETGENPlugin_NetgenLibWrapper::~NETGENPlugin_NetgenLibWrapper()
4311 --instanceCounter();
4313 Ng_DeleteMesh( _ngMesh );
4317 std::cout.rdbuf( _coutBuffer );
4324 //================================================================================
4326 * \brief Set netgen mesh to delete at destruction
4328 //================================================================================
4330 void NETGENPlugin_NetgenLibWrapper::setMesh( Ng_Mesh* mesh )
4333 Ng_DeleteMesh( _ngMesh );
4337 //================================================================================
4339 * \brief Return a unique file name
4341 //================================================================================
4343 std::string NETGENPlugin_NetgenLibWrapper::getOutputFileName()
4345 std::string aTmpDir = SALOMEDS_Tool::GetTmpDir();
4347 TCollection_AsciiString aGenericName = (char*)aTmpDir.c_str();
4348 aGenericName += "NETGEN_";
4350 aGenericName += getpid();
4352 aGenericName += _getpid();
4354 aGenericName += "_";
4355 aGenericName += Abs((Standard_Integer)(long) aGenericName.ToCString());
4356 aGenericName += ".out";
4358 return aGenericName.ToCString();
4361 //================================================================================
4363 * \brief Remove "test.out" and "problemfaces" files in current directory
4365 //================================================================================
4367 void NETGENPlugin_NetgenLibWrapper::RemoveTmpFiles()
4369 bool rm = SMESH_File("test.out").remove() ;
4371 if ( rm && netgen::testout && instanceCounter() == 0 )
4373 delete netgen::testout;
4374 netgen::testout = 0;
4377 SMESH_File("problemfaces").remove();
4378 SMESH_File("occmesh.rep").remove();
4381 //================================================================================
4383 * \brief Remove file with netgen output
4385 //================================================================================
4387 void NETGENPlugin_NetgenLibWrapper::removeOutputFile()
4389 if ( !_outputFileName.empty() )
4393 delete netgen::mycout;
4394 netgen::mycout = _ngcout;
4395 netgen::myerr = _ngcerr;
4398 string tmpDir = SALOMEDS_Tool::GetDirFromPath ( _outputFileName );
4399 string aFileName = SALOMEDS_Tool::GetNameFromPath( _outputFileName ) + ".out";
4400 SALOMEDS_Tool::ListOfFiles aFiles;
4402 aFiles.push_back(aFileName.c_str());
4404 SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.c_str(), aFiles, true );