1 // Copyright (C) 2007-2021 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 NETGENPLUGIN_DLL_HEADER
89 extern MeshingParameters mparam;
91 NETGENPLUGIN_DLL_HEADER
92 extern volatile multithreadt multithread;
94 NETGENPLUGIN_DLL_HEADER
95 extern bool merge_solids;
97 // values used for occgeo.facemeshstatus
98 enum EFaceMeshStatus { FACE_NOT_TREATED = 0,
110 using namespace nglib;
114 #define nodeVec_ACCESS(index) ((SMDS_MeshNode*) nodeVec.at((index)))
116 #define nodeVec_ACCESS(index) ((SMDS_MeshNode*) nodeVec[index])
119 #define NGPOINT_COORDS(p) p(0),p(1),p(2)
122 // dump elements added to ng mesh
123 //#define DUMP_SEGMENTS
124 //#define DUMP_TRIANGLES
125 //#define DUMP_TRIANGLES_SCRIPT "/tmp/trias.py" //!< debug AddIntVerticesInSolids()
128 TopTools_IndexedMapOfShape ShapesWithLocalSize;
129 std::map<int,double> VertexId2LocalSize;
130 std::map<int,double> EdgeId2LocalSize;
131 std::map<int,double> FaceId2LocalSize;
132 std::map<int,double> SolidId2LocalSize;
134 std::vector<SMESHUtils::ControlPnt> ControlPoints;
135 std::set<int> ShapesWithControlPoints; // <-- allows calling SetLocalSize() several times w/o recomputing ControlPoints
139 inline void NOOP_Deleter(void *) { ; }
141 //=============================================================================
143 * Link - a pair of integer numbers
145 //=============================================================================
149 Link(int _n1, int _n2) : n1(_n1), n2(_n2) {}
150 Link() : n1(0), n2(0) {}
151 bool Contains( int n ) const { return n == n1 || n == n2; }
152 bool IsConnected( const Link& other ) const
154 return (( Contains( other.n1 ) || Contains( other.n2 )) && ( this != &other ));
156 static int HashCode(const Link& aLink, int aLimit)
158 return ::HashCode(aLink.n1 + aLink.n2, aLimit);
161 static Standard_Boolean IsEqual(const Link& aLink1, const Link& aLink2)
163 return (( aLink1.n1 == aLink2.n1 && aLink1.n2 == aLink2.n2 ) ||
164 ( aLink1.n1 == aLink2.n2 && aLink1.n2 == aLink2.n1 ));
168 typedef NCollection_Map<Link,Link> TLinkMap;
170 //================================================================================
172 * \brief return id of netgen point corresponding to SMDS node
174 //================================================================================
175 typedef map< const SMDS_MeshNode*, int > TNode2IdMap;
177 int ngNodeId( const SMDS_MeshNode* node,
178 netgen::Mesh& ngMesh,
179 TNode2IdMap& nodeNgIdMap)
181 int newNgId = ngMesh.GetNP() + 1;
183 TNode2IdMap::iterator node_id = nodeNgIdMap.insert( make_pair( node, newNgId )).first;
185 if ( node_id->second == newNgId)
187 #if defined(DUMP_SEGMENTS) || defined(DUMP_TRIANGLES)
188 cout << "Ng " << newNgId << " - " << node;
190 netgen::MeshPoint p( netgen::Point<3> (node->X(), node->Y(), node->Z()) );
191 ngMesh.AddPoint( p );
193 return node_id->second;
196 //================================================================================
198 * \brief Return computed EDGEs connected to the given one
200 //================================================================================
202 list< TopoDS_Edge > getConnectedEdges( const TopoDS_Edge& edge,
203 const TopoDS_Face& face,
204 const set< SMESH_subMesh* > & /*computedSM*/,
205 const SMESH_MesherHelper& helper,
206 map< SMESH_subMesh*, set< int > >& addedEdgeSM2Faces)
209 list< TopoDS_Edge > edges;
210 list< int > nbEdgesInWire;
211 /*int nbWires =*/ SMESH_Block::GetOrderedEdges( face, edges, nbEdgesInWire);
213 // find <edge> within <edges>
214 list< TopoDS_Edge >::iterator eItFwd = edges.begin();
215 for ( ; eItFwd != edges.end(); ++eItFwd )
216 if ( edge.IsSame( *eItFwd ))
218 if ( eItFwd == edges.end()) return list< TopoDS_Edge>();
220 if ( eItFwd->Orientation() >= TopAbs_INTERNAL )
222 // connected INTERNAL edges returned from GetOrderedEdges() are wrongly oriented
223 // so treat each INTERNAL edge separately
224 TopoDS_Edge e = *eItFwd;
226 edges.push_back( e );
230 // get all computed EDGEs connected to <edge>
232 list< TopoDS_Edge >::iterator eItBack = eItFwd, ePrev;
233 TopoDS_Vertex vCommon;
234 TopTools_MapOfShape eAdded; // map used not to add a seam edge twice to <edges>
237 // put edges before <edge> to <edges> back
238 while ( edges.begin() != eItFwd )
239 edges.splice( edges.end(), edges, edges.begin() );
243 while ( ++eItFwd != edges.end() )
245 SMESH_subMesh* sm = helper.GetMesh()->GetSubMesh( *eItFwd );
247 bool connected = TopExp::CommonVertex( *ePrev, *eItFwd, vCommon );
248 bool computed = !sm->IsEmpty();
249 bool added = addedEdgeSM2Faces[ sm ].count( helper.GetSubShapeID() );
250 bool doubled = !eAdded.Add( *eItFwd );
251 bool orientOK = (( ePrev ->Orientation() < TopAbs_INTERNAL ) ==
252 ( eItFwd->Orientation() < TopAbs_INTERNAL ) );
253 if ( !connected || !computed || !orientOK || added || doubled )
255 // stop advancement; move edges from tail to head
256 while ( edges.back() != *ePrev )
257 edges.splice( edges.begin(), edges, --edges.end() );
263 while ( eItBack != edges.begin() )
267 SMESH_subMesh* sm = helper.GetMesh()->GetSubMesh( *eItBack );
269 bool connected = TopExp::CommonVertex( *ePrev, *eItBack, vCommon );
270 bool computed = !sm->IsEmpty();
271 bool added = addedEdgeSM2Faces[ sm ].count( helper.GetSubShapeID() );
272 bool doubled = !eAdded.Add( *eItBack );
273 bool orientOK = (( ePrev ->Orientation() < TopAbs_INTERNAL ) ==
274 ( eItBack->Orientation() < TopAbs_INTERNAL ) );
275 if ( !connected || !computed || !orientOK || added || doubled)
278 edges.erase( edges.begin(), ePrev );
282 if ( edges.front() != edges.back() )
284 // assure that the 1st vertex is meshed
285 TopoDS_Edge eLast = edges.back();
286 while ( !SMESH_Algo::VertexNode( SMESH_MesherHelper::IthVertex( 0, edges.front()), helper.GetMeshDS())
288 edges.front() != eLast )
289 edges.splice( edges.end(), edges, edges.begin() );
294 //================================================================================
296 * \brief Make triangulation of a shape precise enough
298 //================================================================================
300 void updateTriangulation( const TopoDS_Shape& shape )
302 // static set< Poly_Triangulation* > updated;
304 // TopLoc_Location loc;
305 // TopExp_Explorer fExp( shape, TopAbs_FACE );
306 // for ( ; fExp.More(); fExp.Next() )
308 // Handle(Poly_Triangulation) triangulation =
309 // BRep_Tool::Triangulation ( TopoDS::Face( fExp.Current() ), loc);
310 // if ( triangulation.IsNull() ||
311 // updated.insert( triangulation.operator->() ).second )
313 // BRepTools::Clean (shape);
316 BRepMesh_IncrementalMesh e(shape, 0.01, true);
318 catch (Standard_Failure&)
321 // updated.erase( triangulation.operator->() );
322 // triangulation = BRep_Tool::Triangulation ( TopoDS::Face( fExp.Current() ), loc);
323 // updated.insert( triangulation.operator->() );
327 //================================================================================
329 * \brief Returns a medium node either existing in SMESH of created by NETGEN
330 * \param [in] corner1 - corner node 1
331 * \param [in] corner2 - corner node 2
332 * \param [in] defaultMedium - the node created by NETGEN
333 * \param [in] helper - holder of medium nodes existing in SMESH
334 * \return const SMDS_MeshNode* - the result node
336 //================================================================================
338 const SMDS_MeshNode* mediumNode( const SMDS_MeshNode* corner1,
339 const SMDS_MeshNode* corner2,
340 const SMDS_MeshNode* defaultMedium,
341 const SMESH_MesherHelper* helper)
345 TLinkNodeMap::const_iterator l2n =
346 helper->GetTLinkNodeMap().find( SMESH_TLink( corner1, corner2 ));
347 if ( l2n != helper->GetTLinkNodeMap().end() )
348 defaultMedium = l2n->second;
350 return defaultMedium;
353 //================================================================================
355 * \brief Assure that mesh on given shapes is quadratic
357 //================================================================================
359 // void makeQuadratic( const TopTools_IndexedMapOfShape& shapes,
360 // SMESH_Mesh* mesh )
362 // for ( int i = 1; i <= shapes.Extent(); ++i )
364 // SMESHDS_SubMesh* smDS = mesh->GetMeshDS()->MeshElements( shapes(i) );
365 // if ( !smDS ) continue;
366 // SMDS_ElemIteratorPtr elemIt = smDS->GetElements();
367 // if ( !elemIt->more() ) continue;
368 // const SMDS_MeshElement* e = elemIt->next();
369 // if ( !e || e->IsQuadratic() )
372 // TIDSortedElemSet elems;
373 // elems.insert( e );
374 // while ( elemIt->more() )
375 // elems.insert( elems.end(), elemIt->next() );
377 // SMESH_MeshEditor( mesh ).ConvertToQuadratic( /*3d=*/false, elems, /*biQuad=*/false );
381 //================================================================================
383 * \brief Restrict size of elements on the given edge
385 //================================================================================
387 void setLocalSize(const TopoDS_Edge& edge,
390 const bool overrideMinH = true)
392 if ( size <= std::numeric_limits<double>::min() )
394 Standard_Real u1, u2;
395 Handle(Geom_Curve) curve = BRep_Tool::Curve(edge, u1, u2);
396 if ( curve.IsNull() )
398 TopoDS_Iterator vIt( edge );
399 if ( !vIt.More() ) return;
400 gp_Pnt p = BRep_Tool::Pnt( TopoDS::Vertex( vIt.Value() ));
401 NETGENPlugin_Mesher::RestrictLocalSize( mesh, p.XYZ(), size, overrideMinH );
405 const int nb = (int)( 1.5 * SMESH_Algo::EdgeLength( edge ) / size );
406 Standard_Real delta = (u2-u1)/nb;
407 for(int i=0; i<nb; i++)
409 Standard_Real u = u1 + delta*i;
410 gp_Pnt p = curve->Value(u);
411 NETGENPlugin_Mesher::RestrictLocalSize( mesh, p.XYZ(), size, overrideMinH );
412 netgen::Point3d pi(p.X(), p.Y(), p.Z());
413 double resultSize = mesh.GetH(pi);
414 if ( resultSize - size > 0.1*size )
415 // netgen does restriction iff oldH/newH > 1.2 (localh.cpp:136)
416 NETGENPlugin_Mesher::RestrictLocalSize( mesh, p.XYZ(), resultSize/1.201, overrideMinH );
421 //================================================================================
423 * \brief Return triangle size for a given chordalError and radius of curvature
425 //================================================================================
427 double elemSizeForChordalError( double chordalError, double radius )
429 if ( 2 * radius < chordalError )
431 return Sqrt( 3 ) * Sqrt( chordalError * ( 2 * radius - chordalError ));
434 //=============================================================================
438 //=============================================================================
440 void setLocalSize(const TopoDS_Shape& GeomShape, double LocalSize)
442 if ( GeomShape.IsNull() ) return;
443 TopAbs_ShapeEnum GeomType = GeomShape.ShapeType();
444 if (GeomType == TopAbs_COMPOUND) {
445 for (TopoDS_Iterator it (GeomShape); it.More(); it.Next()) {
446 setLocalSize(it.Value(), LocalSize);
451 if (! ShapesWithLocalSize.Contains(GeomShape))
452 key = ShapesWithLocalSize.Add(GeomShape);
454 key = ShapesWithLocalSize.FindIndex(GeomShape);
455 if (GeomType == TopAbs_VERTEX) {
456 VertexId2LocalSize[key] = LocalSize;
457 } else if (GeomType == TopAbs_EDGE) {
458 EdgeId2LocalSize[key] = LocalSize;
459 } else if (GeomType == TopAbs_FACE) {
460 FaceId2LocalSize[key] = LocalSize;
461 } else if (GeomType == TopAbs_SOLID) {
462 SolidId2LocalSize[key] = LocalSize;
467 //================================================================================
469 * \brief Return faceNgID or faceNgID-1 depending on side the given proxy face lies
470 * \param [in] f - proxy face
471 * \param [in] solidSMDSIDs - IDs of SOLIDs sharing the FACE on which face lies
472 * \param [in] faceNgID - NETGEN ID of the FACE
473 * \return int - NETGEN ID of the FACE
475 //================================================================================
477 int getFaceNgID( const SMDS_MeshElement* face,
478 const int * solidSMDSIDs,
481 for ( int i = 0; i < 3; ++i )
483 const SMDS_MeshNode* n = face->GetNode( i );
484 const int shapeID = n->GetShapeID();
485 if ( shapeID == solidSMDSIDs[0] )
487 if ( shapeID == solidSMDSIDs[1] )
490 std::vector<const SMDS_MeshNode*> fNodes( face->begin_nodes(), face->end_nodes() );
491 std::vector<const SMDS_MeshElement*> vols;
492 if ( SMDS_Mesh::GetElementsByNodes( fNodes, vols, SMDSAbs_Volume ))
493 for ( size_t i = 0; i < vols.size(); ++i )
495 const int shapeID = vols[i]->GetShapeID();
496 if ( shapeID == solidSMDSIDs[0] )
498 if ( shapeID == solidSMDSIDs[1] )
506 //=============================================================================
510 //=============================================================================
512 NETGENPlugin_Mesher::NETGENPlugin_Mesher (SMESH_Mesh* mesh,
513 const TopoDS_Shape& aShape,
519 _fineness(NETGENPlugin_Hypothesis::GetDefaultFineness()),
520 _isViscousLayers2D(false),
521 _chordalError(-1), // means disabled
528 _viscousLayersHyp(NULL),
531 SetDefaultParameters();
532 ShapesWithLocalSize.Clear();
533 VertexId2LocalSize.clear();
534 EdgeId2LocalSize.clear();
535 FaceId2LocalSize.clear();
536 SolidId2LocalSize.clear();
537 ControlPoints.clear();
538 ShapesWithControlPoints.clear();
541 //================================================================================
545 //================================================================================
547 NETGENPlugin_Mesher::~NETGENPlugin_Mesher()
555 //================================================================================
557 * Set pointer to NETGENPlugin_Mesher* field of the holder, that will be
558 * nullified at destruction of this
560 //================================================================================
562 void NETGENPlugin_Mesher::SetSelfPointer( NETGENPlugin_Mesher ** ptr )
573 //================================================================================
575 * \brief Initialize global NETGEN parameters with default values
577 //================================================================================
579 void NETGENPlugin_Mesher::SetDefaultParameters()
581 netgen::MeshingParameters& mparams = netgen::mparam;
582 mparams = netgen::MeshingParameters();
583 // maximal mesh edge size
584 mparams.maxh = 0;//NETGENPlugin_Hypothesis::GetDefaultMaxSize();
586 // minimal number of segments per edge
587 mparams.segmentsperedge = NETGENPlugin_Hypothesis::GetDefaultNbSegPerEdge();
588 // rate of growth of size between elements
589 mparams.grading = NETGENPlugin_Hypothesis::GetDefaultGrowthRate();
590 // safety factor for curvatures (elements per radius)
591 mparams.curvaturesafety = NETGENPlugin_Hypothesis::GetDefaultNbSegPerRadius();
592 // create elements of second order
593 mparams.secondorder = NETGENPlugin_Hypothesis::GetDefaultSecondOrder();
594 // quad-dominated surface meshing
598 mparams.quad = NETGENPlugin_Hypothesis_2D::GetDefaultQuadAllowed();
599 _fineness = NETGENPlugin_Hypothesis::GetDefaultFineness();
600 mparams.uselocalh = NETGENPlugin_Hypothesis::GetDefaultSurfaceCurvature();
601 netgen::merge_solids = NETGENPlugin_Hypothesis::GetDefaultFuseEdges();
604 //=============================================================================
606 * Pass parameters to NETGEN
608 //=============================================================================
609 void NETGENPlugin_Mesher::SetParameters(const NETGENPlugin_Hypothesis* hyp)
613 netgen::MeshingParameters& mparams = netgen::mparam;
614 // Initialize global NETGEN parameters:
615 // maximal mesh segment size
616 mparams.maxh = hyp->GetMaxSize();
617 // maximal mesh element linear size
618 mparams.minh = hyp->GetMinSize();
619 // minimal number of segments per edge
620 mparams.segmentsperedge = hyp->GetNbSegPerEdge();
621 // rate of growth of size between elements
622 mparams.grading = hyp->GetGrowthRate();
623 // safety factor for curvatures (elements per radius)
624 mparams.curvaturesafety = hyp->GetNbSegPerRadius();
625 // create elements of second order
626 mparams.secondorder = hyp->GetSecondOrder() ? 1 : 0;
627 // quad-dominated surface meshing
628 mparams.quad = hyp->GetQuadAllowed() ? 1 : 0;
629 _optimize = hyp->GetOptimize();
630 _fineness = hyp->GetFineness();
631 mparams.uselocalh = hyp->GetSurfaceCurvature();
632 netgen::merge_solids = hyp->GetFuseEdges();
633 _chordalError = hyp->GetChordalErrorEnabled() ? hyp->GetChordalError() : -1.;
634 mparams.optsteps2d = _optimize ? hyp->GetNbSurfOptSteps() : 0;
635 mparams.optsteps3d = _optimize ? hyp->GetNbVolOptSteps() : 0;
636 mparams.elsizeweight = hyp->GetElemSizeWeight();
637 mparams.opterrpow = hyp->GetWorstElemMeasure();
638 mparams.delaunay = hyp->GetUseDelauney();
639 mparams.checkoverlap = hyp->GetCheckOverlapping();
640 mparams.checkchartboundary = hyp->GetCheckChartBoundary();
645 mparams.meshsizefilename = hyp->GetMeshSizeFile();
648 mparams.meshsizefilename= hyp->GetMeshSizeFile().empty() ? 0 : hyp->GetMeshSizeFile().c_str();
650 const NETGENPlugin_Hypothesis::TLocalSize& localSizes = hyp->GetLocalSizesAndEntries();
651 if ( !localSizes.empty() )
653 SMESH_Gen_i* smeshGen_i = SMESH_Gen_i::GetSMESHGen();
654 NETGENPlugin_Hypothesis::TLocalSize::const_iterator it = localSizes.begin();
655 for ( ; it != localSizes.end() ; it++)
657 std::string entry = (*it).first;
658 double val = (*it).second;
660 GEOM::GEOM_Object_var aGeomObj;
661 SALOMEDS::SObject_var aSObj = SMESH_Gen_i::GetSMESHGen()->getStudyServant()->FindObjectID( entry.c_str() );
662 if ( !aSObj->_is_nil() ) {
663 CORBA::Object_var obj = aSObj->GetObject();
664 aGeomObj = GEOM::GEOM_Object::_narrow(obj);
667 TopoDS_Shape S = smeshGen_i->GeomObjectToShape( aGeomObj.in() );
668 setLocalSize(S, val);
674 //=============================================================================
676 * Pass simple parameters to NETGEN
678 //=============================================================================
680 void NETGENPlugin_Mesher::SetParameters(const NETGENPlugin_SimpleHypothesis_2D* hyp)
684 SetDefaultParameters();
687 //================================================================================
689 * \brief Store a Viscous Layers hypothesis
691 //================================================================================
693 void NETGENPlugin_Mesher::SetParameters(const StdMeshers_ViscousLayers* hyp )
695 _viscousLayersHyp = hyp;
698 //================================================================================
700 * \brief Set local size on shapes defined by SetParameters()
702 //================================================================================
704 void NETGENPlugin_Mesher::SetLocalSize( netgen::OCCGeometry& occgeo,
705 netgen::Mesh& ngMesh)
708 std::map<int,double>::const_iterator it;
709 for( it=EdgeId2LocalSize.begin(); it!=EdgeId2LocalSize.end(); it++)
711 int key = (*it).first;
712 double hi = (*it).second;
713 const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
714 setLocalSize( TopoDS::Edge(shape), hi, ngMesh );
717 for(it=VertexId2LocalSize.begin(); it!=VertexId2LocalSize.end(); it++)
719 int key = (*it).first;
720 double hi = (*it).second;
721 const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
722 gp_Pnt p = BRep_Tool::Pnt( TopoDS::Vertex(shape) );
723 NETGENPlugin_Mesher::RestrictLocalSize( ngMesh, p.XYZ(), hi );
726 for(it=FaceId2LocalSize.begin(); it!=FaceId2LocalSize.end(); it++)
728 int key = (*it).first;
729 double val = (*it).second;
730 const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
731 int faceNgID = occgeo.fmap.FindIndex(shape);
735 occgeo.SetFaceMaxH(faceNgID-1, val);
737 occgeo.SetFaceMaxH(faceNgID, val);
739 for ( TopExp_Explorer edgeExp( shape, TopAbs_EDGE ); edgeExp.More(); edgeExp.Next() )
740 setLocalSize( TopoDS::Edge( edgeExp.Current() ), val, ngMesh );
742 else if ( !ShapesWithControlPoints.count( key ))
744 SMESHUtils::createPointsSampleFromFace( TopoDS::Face( shape ), val, ControlPoints );
745 ShapesWithControlPoints.insert( key );
749 for(it=SolidId2LocalSize.begin(); it!=SolidId2LocalSize.end(); it++)
751 int key = (*it).first;
752 double val = (*it).second;
753 if ( !ShapesWithControlPoints.count( key ))
755 const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
756 SMESHUtils::createPointsSampleFromSolid( TopoDS::Solid( shape ), val, ControlPoints );
757 ShapesWithControlPoints.insert( key );
761 if ( !ControlPoints.empty() )
763 for ( size_t i = 0; i < ControlPoints.size(); ++i )
764 NETGENPlugin_Mesher::RestrictLocalSize( ngMesh, ControlPoints[i].XYZ(), ControlPoints[i].Size() );
769 //================================================================================
771 * \brief Restrict local size to achieve a required _chordalError
773 //================================================================================
775 void NETGENPlugin_Mesher::SetLocalSizeForChordalError( netgen::OCCGeometry& occgeo,
776 netgen::Mesh& ngMesh)
778 if ( _chordalError <= 0. )
782 BRepLProp_SLProps surfProp( 2, 1e-6 );
783 const double sizeCoef = 0.95;
785 // find non-planar FACEs with non-constant curvature
786 std::vector<int> fInd;
787 for ( int i = 1; i <= occgeo.fmap.Extent(); ++i )
789 const TopoDS_Face& face = TopoDS::Face( occgeo.fmap( i ));
790 BRepAdaptor_Surface surfAd( face, false );
791 switch ( surfAd.GetType() )
795 case GeomAbs_Cylinder:
797 case GeomAbs_Torus: // constant curvature
799 surfProp.SetSurface( surfAd );
800 surfProp.SetParameters( 0, 0 );
801 double maxCurv = Max( Abs( surfProp.MaxCurvature()), Abs( surfProp.MinCurvature() ));
802 double size = elemSizeForChordalError( _chordalError, 1 / maxCurv );
804 occgeo.SetFaceMaxH( i-1, size * sizeCoef );
806 occgeo.SetFaceMaxH( i, size * sizeCoef );
808 // limit size one edges
809 TopTools_MapOfShape edgeMap;
810 for ( TopExp_Explorer eExp( face, TopAbs_EDGE ); eExp.More(); eExp.Next() )
811 if ( edgeMap.Add( eExp.Current() ))
812 setLocalSize( TopoDS::Edge( eExp.Current() ), size, ngMesh, /*overrideMinH=*/false );
816 Handle(Geom_Surface) surf = BRep_Tool::Surface( face, loc );
817 if ( GeomLib_IsPlanarSurface( surf ).IsPlanar() )
826 TopoDS_Compound allFacesComp;
827 b.MakeCompound( allFacesComp );
828 for ( size_t i = 0; i < fInd.size(); ++i )
829 b.Add( allFacesComp, occgeo.fmap( fInd[i] ));
831 // copy the shape to avoid spoiling its triangulation
832 TopoDS_Shape allFacesCompCopy = BRepBuilderAPI_Copy( allFacesComp );
834 // create triangulation with desired chordal error
835 BRepMesh_IncrementalMesh( allFacesCompCopy,
837 /*isRelative = */Standard_False,
838 /*theAngDeflection = */ 0.5,
839 /*isInParallel = */Standard_True);
842 for ( TopExp_Explorer fExp( allFacesCompCopy, TopAbs_FACE ); fExp.More(); fExp.Next() )
844 const TopoDS_Face& face = TopoDS::Face( fExp.Current() );
845 Handle(Poly_Triangulation) triangulation = BRep_Tool::Triangulation ( face, loc );
846 if ( triangulation.IsNull() ) continue;
848 BRepAdaptor_Surface surf( face, false );
849 surfProp.SetSurface( surf );
854 for ( int i = 1; i <= triangulation->NbTriangles(); ++i )
856 Standard_Integer n1,n2,n3;
857 triangulation->Triangles()(i).Get( n1,n2,n3 );
858 p [0] = triangulation->Nodes()(n1).Transformed(loc).XYZ();
859 p [1] = triangulation->Nodes()(n2).Transformed(loc).XYZ();
860 p [2] = triangulation->Nodes()(n3).Transformed(loc).XYZ();
861 uv[0] = triangulation->UVNodes()(n1).XY();
862 uv[1] = triangulation->UVNodes()(n2).XY();
863 uv[2] = triangulation->UVNodes()(n3).XY();
864 surfProp.SetParameters( uv[0].X(), uv[0].Y() );
865 if ( !surfProp.IsCurvatureDefined() )
868 for ( int n = 0; n < 3; ++n ) // get size at triangle nodes
870 surfProp.SetParameters( uv[n].X(), uv[n].Y() );
871 double maxCurv = Max( Abs( surfProp.MaxCurvature()), Abs( surfProp.MinCurvature() ));
872 size[n] = elemSizeForChordalError( _chordalError, 1 / maxCurv );
874 for ( int n1 = 0; n1 < 3; ++n1 ) // limit size along each triangle edge
876 int n2 = ( n1 + 1 ) % 3;
877 double minSize = size[n1], maxSize = size[n2];
878 if ( size[n1] > size[n2] )
879 minSize = size[n2], maxSize = size[n1];
881 if ( maxSize / minSize < 1.2 ) // netgen ignores size difference < 1.2
883 ngMesh.RestrictLocalHLine ( netgen::Point3d( p[n1].X(), p[n1].Y(), p[n1].Z() ),
884 netgen::Point3d( p[n2].X(), p[n2].Y(), p[n2].Z() ),
885 sizeCoef * minSize );
889 gp_XY uvVec( uv[n2] - uv[n1] );
890 double len = ( p[n1] - p[n2] ).Modulus();
891 int nb = int( len / minSize ) + 1;
892 for ( int j = 0; j <= nb; ++j )
894 double r = double( j ) / nb;
895 gp_XY uvj = uv[n1] + r * uvVec;
897 surfProp.SetParameters( uvj.X(), uvj.Y() );
898 double maxCurv = Max( Abs( surfProp.MaxCurvature()), Abs( surfProp.MinCurvature() ));
899 double h = elemSizeForChordalError( _chordalError, 1 / maxCurv );
901 const gp_Pnt& pj = surfProp.Value();
902 netgen::Point3d ngP( pj.X(), pj.Y(), pj.Z());
903 ngMesh.RestrictLocalH( ngP, h * sizeCoef );
912 //================================================================================
914 * \brief Initialize netgen::OCCGeometry with OCCT shape
916 //================================================================================
918 void NETGENPlugin_Mesher::PrepareOCCgeometry(netgen::OCCGeometry& occgeo,
919 const TopoDS_Shape& shape,
921 list< SMESH_subMesh* > * meshedSM,
922 NETGENPlugin_Internals* intern)
924 updateTriangulation( shape );
927 BRepBndLib::Add (shape, bb);
928 double x1,y1,z1,x2,y2,z2;
929 bb.Get (x1,y1,z1,x2,y2,z2);
930 netgen::Point<3> p1 = netgen::Point<3> (x1,y1,z1);
931 netgen::Point<3> p2 = netgen::Point<3> (x2,y2,z2);
932 occgeo.boundingbox = netgen::Box<3> (p1,p2);
934 occgeo.shape = shape;
937 // fill maps of shapes of occgeo with not yet meshed subshapes
939 // get root submeshes
940 list< SMESH_subMesh* > rootSM;
941 const int shapeID = mesh.GetMeshDS()->ShapeToIndex( shape );
942 if ( shapeID > 0 ) { // SMESH_subMesh with ID 0 may exist, don't use it!
943 rootSM.push_back( mesh.GetSubMesh( shape ));
946 for ( TopoDS_Iterator it( shape ); it.More(); it.Next() )
947 rootSM.push_back( mesh.GetSubMesh( it.Value() ));
952 // add subshapes of empty submeshes
953 list< SMESH_subMesh* >::iterator rootIt = rootSM.begin(), rootEnd = rootSM.end();
954 for ( ; rootIt != rootEnd; ++rootIt ) {
955 SMESH_subMesh * root = *rootIt;
956 SMESH_subMeshIteratorPtr smIt = root->getDependsOnIterator(/*includeSelf=*/true,
957 /*complexShapeFirst=*/true);
958 // to find a right orientation of subshapes (PAL20462)
959 TopTools_IndexedMapOfShape subShapes;
960 TopExp::MapShapes(root->GetSubShape(), subShapes);
961 while ( smIt->more() )
963 SMESH_subMesh* sm = smIt->next();
964 TopoDS_Shape shape = sm->GetSubShape();
965 totNbFaces += ( shape.ShapeType() == TopAbs_FACE );
966 if ( intern && intern->isShapeToPrecompute( shape ))
968 if ( !meshedSM || sm->IsEmpty() )
970 if ( shape.ShapeType() != TopAbs_VERTEX )
971 shape = subShapes( subShapes.FindIndex( shape ));// shape -> index -> oriented shape
972 if ( shape.Orientation() >= TopAbs_INTERNAL )
973 shape.Orientation( TopAbs_FORWARD ); // issue 0020676
974 switch ( shape.ShapeType() ) {
975 case TopAbs_FACE : occgeo.fmap.Add( shape ); break;
976 case TopAbs_EDGE : occgeo.emap.Add( shape ); break;
977 case TopAbs_VERTEX: occgeo.vmap.Add( shape ); break;
978 case TopAbs_SOLID :occgeo.somap.Add( shape ); break;
982 // collect submeshes of meshed shapes
985 const int dim = SMESH_Gen::GetShapeDim( shape );
986 meshedSM[ dim ].push_back( sm );
990 occgeo.facemeshstatus.SetSize (totNbFaces);
991 occgeo.facemeshstatus = 0;
992 occgeo.face_maxh_modified.SetSize(totNbFaces);
993 occgeo.face_maxh_modified = 0;
994 occgeo.face_maxh.SetSize(totNbFaces);
995 occgeo.face_maxh = netgen::mparam.maxh;
998 //================================================================================
1000 * \brief Return a default min size value suitable for the given geometry.
1002 //================================================================================
1004 double NETGENPlugin_Mesher::GetDefaultMinSize(const TopoDS_Shape& geom,
1005 const double maxSize)
1007 updateTriangulation( geom );
1009 TopLoc_Location loc;
1011 const int* pi[4] = { &i1, &i2, &i3, &i1 };
1012 double minh = 1e100;
1014 TopExp_Explorer fExp( geom, TopAbs_FACE );
1015 for ( ; fExp.More(); fExp.Next() )
1017 Handle(Poly_Triangulation) triangulation =
1018 BRep_Tool::Triangulation ( TopoDS::Face( fExp.Current() ), loc);
1019 if ( triangulation.IsNull() ) continue;
1020 const double fTol = BRep_Tool::Tolerance( TopoDS::Face( fExp.Current() ));
1021 const TColgp_Array1OfPnt& points = triangulation->Nodes();
1022 const Poly_Array1OfTriangle& trias = triangulation->Triangles();
1023 for ( int iT = trias.Lower(); iT <= trias.Upper(); ++iT )
1025 trias(iT).Get( i1, i2, i3 );
1026 for ( int j = 0; j < 3; ++j )
1028 double dist2 = points(*pi[j]).SquareDistance( points( *pi[j+1] ));
1029 if ( dist2 < minh && fTol*fTol < dist2 )
1031 bb.Add( points(*pi[j]));
1035 if ( minh > 0.25 * bb.SquareExtent() ) // simple geometry, rough triangulation
1037 minh = 1e-3 * sqrt( bb.SquareExtent());
1038 //cout << "BND BOX minh = " <<minh << endl;
1042 minh = sqrt( minh ); // triangulation for visualization is rather fine
1043 //cout << "TRIANGULATION minh = " <<minh << endl;
1045 if ( minh > 0.5 * maxSize )
1046 minh = maxSize / 3.;
1051 //================================================================================
1053 * \brief Restrict size of elements at a given point
1055 //================================================================================
1057 void NETGENPlugin_Mesher::RestrictLocalSize(netgen::Mesh& ngMesh,
1060 const bool overrideMinH)
1062 if ( size <= std::numeric_limits<double>::min() )
1064 if ( netgen::mparam.minh > size )
1068 ngMesh.SetMinimalH( size );
1069 netgen::mparam.minh = size;
1073 size = netgen::mparam.minh;
1076 netgen::Point3d pi(p.X(), p.Y(), p.Z());
1077 ngMesh.RestrictLocalH( pi, size );
1080 //================================================================================
1082 * \brief fill ngMesh with nodes and elements of computed submeshes
1084 //================================================================================
1086 bool NETGENPlugin_Mesher::FillNgMesh(netgen::OCCGeometry& occgeom,
1087 netgen::Mesh& ngMesh,
1088 vector<const SMDS_MeshNode*>& nodeVec,
1089 const list< SMESH_subMesh* > & meshedSM,
1090 SMESH_MesherHelper* quadHelper,
1091 SMESH_ProxyMesh::Ptr proxyMesh)
1093 TNode2IdMap nodeNgIdMap;
1094 for ( size_t i = 1; i < nodeVec.size(); ++i )
1095 nodeNgIdMap.insert( make_pair( nodeVec[i], i ));
1097 TopTools_MapOfShape visitedShapes;
1098 map< SMESH_subMesh*, set< int > > visitedEdgeSM2Faces;
1099 set< SMESH_subMesh* > computedSM( meshedSM.begin(), meshedSM.end() );
1101 SMESH_MesherHelper helper (*_mesh);
1102 SMESHDS_Mesh* meshDS = _mesh->GetMeshDS();
1104 int faceNgID = ngMesh.GetNFD();
1106 list< SMESH_subMesh* >::const_iterator smIt, smEnd = meshedSM.end();
1107 for ( smIt = meshedSM.begin(); smIt != smEnd; ++smIt )
1109 SMESH_subMesh* sm = *smIt;
1110 if ( !visitedShapes.Add( sm->GetSubShape() ))
1113 const SMESHDS_SubMesh * smDS = sm->GetSubMeshDS();
1114 if ( !smDS ) continue;
1116 switch ( sm->GetSubShape().ShapeType() )
1118 case TopAbs_EDGE: { // EDGE
1119 // ----------------------
1120 TopoDS_Edge geomEdge = TopoDS::Edge( sm->GetSubShape() );
1121 if ( geomEdge.Orientation() >= TopAbs_INTERNAL )
1122 geomEdge.Orientation( TopAbs_FORWARD ); // issue 0020676
1124 // Add ng segments for each not meshed FACE the EDGE bounds
1125 PShapeIteratorPtr fIt = helper.GetAncestors( geomEdge, *sm->GetFather(), TopAbs_FACE );
1126 while ( const TopoDS_Shape * anc = fIt->next() )
1128 faceNgID = occgeom.fmap.FindIndex( *anc );
1130 continue; // meshed face
1132 int faceSMDSId = meshDS->ShapeToIndex( *anc );
1133 if ( visitedEdgeSM2Faces[ sm ].count( faceSMDSId ))
1134 continue; // already treated EDGE
1136 TopoDS_Face face = TopoDS::Face( occgeom.fmap( faceNgID ));
1137 if ( face.Orientation() >= TopAbs_INTERNAL )
1138 face.Orientation( TopAbs_FORWARD ); // issue 0020676
1140 // get all meshed EDGEs of the FACE connected to geomEdge (issue 0021140)
1141 helper.SetSubShape( face );
1142 list< TopoDS_Edge > edges = getConnectedEdges( geomEdge, face, computedSM, helper,
1143 visitedEdgeSM2Faces );
1144 if ( edges.empty() )
1145 continue; // wrong ancestor?
1147 // find out orientation of <edges> within <face>
1148 TopoDS_Edge eNotSeam = edges.front();
1149 if ( helper.HasSeam() )
1151 list< TopoDS_Edge >::iterator eIt = edges.begin();
1152 while ( helper.IsRealSeam( *eIt )) ++eIt;
1153 if ( eIt != edges.end() )
1156 TopAbs_Orientation fOri = helper.GetSubShapeOri( face, eNotSeam );
1157 bool isForwad = ( fOri == eNotSeam.Orientation() || fOri >= TopAbs_INTERNAL );
1159 // get all nodes from connected <edges>
1160 const bool skipMedium = netgen::mparam.secondorder;//smDS->IsQuadratic();
1161 StdMeshers_FaceSide fSide( face, edges, _mesh, isForwad, skipMedium, &helper );
1162 const vector<UVPtStruct>& points = fSide.GetUVPtStruct();
1163 if ( points.empty() )
1164 return false; // invalid node params?
1165 smIdType i, nbSeg = fSide.NbSegments();
1167 // remember EDGEs of fSide to treat only once
1168 for ( int iE = 0; iE < fSide.NbEdges(); ++iE )
1169 visitedEdgeSM2Faces[ helper.GetMesh()->GetSubMesh( fSide.Edge(iE )) ].insert(faceSMDSId);
1171 double otherSeamParam = 0;
1172 bool isSeam = false;
1176 int prevNgId = ngNodeId( points[0].node, ngMesh, nodeNgIdMap );
1178 for ( i = 0; i < nbSeg; ++i )
1180 const UVPtStruct& p1 = points[ i ];
1181 const UVPtStruct& p2 = points[ i+1 ];
1183 if ( p1.node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX ) //an EDGE begins
1186 if ( helper.IsRealSeam( p1.node->GetShapeID() ))
1188 TopoDS_Edge e = fSide.Edge( fSide.EdgeIndex( 0.5 * ( p1.normParam + p2.normParam )));
1189 isSeam = helper.IsRealSeam( e );
1192 otherSeamParam = helper.GetOtherParam( helper.GetPeriodicIndex() & 1 ? p2.u : p2.v );
1196 netgen::Segment seg;
1199 seg[1] = prevNgId = ngNodeId( p2.node, ngMesh, nodeNgIdMap );
1200 // node param on curve
1201 seg.epgeominfo[ 0 ].dist = p1.param;
1202 seg.epgeominfo[ 1 ].dist = p2.param;
1204 seg.epgeominfo[ 0 ].u = p1.u;
1205 seg.epgeominfo[ 0 ].v = p1.v;
1206 seg.epgeominfo[ 1 ].u = p2.u;
1207 seg.epgeominfo[ 1 ].v = p2.v;
1209 //geomEdge = fSide.Edge( fSide.EdgeIndex( 0.5 * ( p1.normParam + p2.normParam )));
1210 //seg.epgeominfo[ 0 ].edgenr = seg.epgeominfo[ 1 ].edgenr = occgeom.emap.FindIndex( geomEdge );
1212 //seg.epgeominfo[ iEnd ].edgenr = edgeID; // = geom.emap.FindIndex(edge);
1213 seg.si = faceNgID; // = geom.fmap.FindIndex (face);
1214 seg.edgenr = ngMesh.GetNSeg() + 1; // segment id
1215 ngMesh.AddSegment (seg);
1217 SMESH_TNodeXYZ np1( p1.node ), np2( p2.node );
1218 RestrictLocalSize( ngMesh, 0.5*(np1+np2), (np1-np2).Modulus() );
1220 #ifdef DUMP_SEGMENTS
1221 cout << "Segment: " << seg.edgenr << " on SMESH face " << meshDS->ShapeToIndex( face ) << endl
1222 << "\tface index: " << seg.si << endl
1223 << "\tp1: " << seg[0] << endl
1224 << "\tp2: " << seg[1] << endl
1225 << "\tp0 param: " << seg.epgeominfo[ 0 ].dist << endl
1226 << "\tp0 uv: " << seg.epgeominfo[ 0 ].u <<", "<< seg.epgeominfo[ 0 ].v << endl
1227 //<< "\tp0 edge: " << seg.epgeominfo[ 0 ].edgenr << endl
1228 << "\tp1 param: " << seg.epgeominfo[ 1 ].dist << endl
1229 << "\tp1 uv: " << seg.epgeominfo[ 1 ].u <<", "<< seg.epgeominfo[ 1 ].v << endl;
1230 //<< "\tp1 edge: " << seg.epgeominfo[ 1 ].edgenr << endl;
1234 if ( helper.GetPeriodicIndex() && 1 ) {
1235 seg.epgeominfo[ 0 ].u = otherSeamParam;
1236 seg.epgeominfo[ 1 ].u = otherSeamParam;
1237 swap (seg.epgeominfo[0].v, seg.epgeominfo[1].v);
1239 seg.epgeominfo[ 0 ].v = otherSeamParam;
1240 seg.epgeominfo[ 1 ].v = otherSeamParam;
1241 swap (seg.epgeominfo[0].u, seg.epgeominfo[1].u);
1243 swap( seg[0], seg[1] );
1244 swap( seg.epgeominfo[0].dist, seg.epgeominfo[1].dist );
1245 seg.edgenr = ngMesh.GetNSeg() + 1; // segment id
1246 ngMesh.AddSegment( seg );
1247 #ifdef DUMP_SEGMENTS
1248 cout << "Segment: " << seg.edgenr << endl
1249 << "\t is SEAM (reverse) of the previous. "
1250 << " Other " << (helper.GetPeriodicIndex() && 1 ? "U" : "V")
1251 << " = " << otherSeamParam << endl;
1254 else if ( fOri == TopAbs_INTERNAL )
1256 swap( seg[0], seg[1] );
1257 swap( seg.epgeominfo[0], seg.epgeominfo[1] );
1258 seg.edgenr = ngMesh.GetNSeg() + 1; // segment id
1259 ngMesh.AddSegment( seg );
1260 #ifdef DUMP_SEGMENTS
1261 cout << "Segment: " << seg.edgenr << endl << "\t is REVERSE of the previous" << endl;
1265 } // loop on geomEdge ancestors
1267 if ( quadHelper ) // remember medium nodes of sub-meshes
1269 SMDS_ElemIteratorPtr edges = smDS->GetElements();
1270 while ( edges->more() )
1272 const SMDS_MeshElement* e = edges->next();
1273 if ( !quadHelper->AddTLinks( static_cast< const SMDS_MeshEdge*>( e )))
1279 } // case TopAbs_EDGE
1281 case TopAbs_FACE: { // FACE
1282 // ----------------------
1283 const TopoDS_Face& geomFace = TopoDS::Face( sm->GetSubShape() );
1284 helper.SetSubShape( geomFace );
1285 bool isInternalFace = ( geomFace.Orientation() == TopAbs_INTERNAL );
1287 // Find solids the geomFace bounds
1288 int solidID1 = 0, solidID2 = 0; // ng IDs
1289 int solidSMDSIDs[2] = { 0,0 }; // smds IDs
1291 PShapeIteratorPtr solidIt = helper.GetAncestors( geomFace, *sm->GetFather(), TopAbs_SOLID);
1292 while ( const TopoDS_Shape * solid = solidIt->next() )
1294 int id = occgeom.somap.FindIndex ( *solid );
1295 if ( solidID1 && id != solidID1 ) solidID2 = id;
1297 if ( id ) solidSMDSIDs[ bool( solidSMDSIDs[0] )] = meshDS->ShapeToIndex( *solid );
1300 if ( proxyMesh && proxyMesh->GetProxySubMesh( geomFace ))
1302 // if a proxy sub-mesh contains temporary faces, then these faces
1303 // should be used to mesh only one SOLID
1304 bool hasTmp = false;
1305 smDS = proxyMesh->GetSubMesh( geomFace );
1306 SMDS_ElemIteratorPtr faces = smDS->GetElements();
1307 while ( faces->more() )
1309 const SMDS_MeshElement* f = faces->next();
1310 if ( proxyMesh->IsTemporary( f ))
1313 if ( solidSMDSIDs[1] && proxyMesh->HasPrismsOnTwoSides( meshDS->MeshElements( geomFace )))
1316 solidSMDSIDs[1] = 0;
1317 std::vector<const SMDS_MeshNode*> fNodes( f->begin_nodes(), f->end_nodes() );
1318 std::vector<const SMDS_MeshElement*> vols;
1319 if ( meshDS->GetElementsByNodes( fNodes, vols, SMDSAbs_Volume ) == 1 )
1321 int geomID = vols[0]->GetShapeID();
1322 const TopoDS_Shape& solid = meshDS->IndexToShape( geomID );
1323 if ( !solid.IsNull() )
1324 solidID1 = occgeom.somap.FindIndex ( solid );
1330 const int fID = occgeom.fmap.FindIndex( geomFace );
1331 if ( !hasTmp ) // shrunk mesh
1333 // move netgen points according to moved nodes
1334 SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/true);
1335 while ( smIt->more() )
1337 SMESH_subMesh* sub = smIt->next();
1338 if ( !sub->GetSubMeshDS() ) continue;
1339 SMDS_NodeIteratorPtr nodeIt = sub->GetSubMeshDS()->GetNodes();
1340 while ( nodeIt->more() )
1342 const SMDS_MeshNode* n = nodeIt->next();
1343 int ngID = ngNodeId( n, ngMesh, nodeNgIdMap );
1344 netgen::MeshPoint& ngPoint = ngMesh.Point( ngID );
1345 ngPoint(0) = n->X();
1346 ngPoint(1) = n->Y();
1347 ngPoint(2) = n->Z();
1350 // remove faces near boundary to avoid their overlapping
1351 // with shrunk faces
1352 for ( int i = 1; i <= ngMesh.GetNSE(); ++i )
1354 const netgen::Element2d& elem = ngMesh.SurfaceElement(i);
1355 if ( elem.GetIndex() == fID )
1357 for ( int iN = 0; iN < elem.GetNP(); ++iN )
1358 if ( ngMesh[ elem[ iN ]].Type() != netgen::SURFACEPOINT )
1360 ngMesh.DeleteSurfaceElement( i );
1366 // exclude faces generated by NETGEN from computation of 3D mesh
1370 ngMesh.AddFaceDescriptor( netgen::FaceDescriptor( faceNgID,/*solid1=*/0,/*solid2=*/0,0 ));
1371 for (int i = 1; i <= ngMesh.GetNSE(); ++i )
1373 const netgen::Element2d& elem = ngMesh.SurfaceElement(i);
1374 if ( elem.GetIndex() == fID )
1375 const_cast< netgen::Element2d& >( elem ).SetIndex( faceNgID );
1381 solidSMDSIDs[1] = 0;
1383 const bool hasVLOn2Sides = ( solidSMDSIDs[1] > 0 );
1385 // Add ng face descriptors of meshed faces
1387 if ( hasVLOn2Sides )
1389 // viscous layers are on two sides of the FACE
1390 ngMesh.AddFaceDescriptor( netgen::FaceDescriptor( faceNgID, solidID1, 0, 0 ));
1392 ngMesh.AddFaceDescriptor( netgen::FaceDescriptor( faceNgID, 0, solidID2, 0 ));
1396 ngMesh.AddFaceDescriptor( netgen::FaceDescriptor( faceNgID, solidID1, solidID2, 0 ));
1398 // if second oreder is required, even already meshed faces must be passed to NETGEN
1399 int fID = occgeom.fmap.Add( geomFace );
1400 if ( occgeom.facemeshstatus.Size() < fID ) occgeom.facemeshstatus.SetSize( fID );
1401 occgeom.facemeshstatus[ fID-1 ] = netgen::FACE_MESHED_OK;
1402 while ( fID < faceNgID ) // geomFace is already in occgeom.fmap, add a copy
1404 fID = occgeom.fmap.Add( BRepBuilderAPI_Copy( geomFace, /*copyGeom=*/false ));
1405 if ( occgeom.facemeshstatus.Size() < fID ) occgeom.facemeshstatus.SetSize( fID );
1406 occgeom.facemeshstatus[ fID-1 ] = netgen::FACE_MESHED_OK;
1408 // Problem with the second order in a quadrangular mesh remains.
1409 // 1) All quadrangles generated by NETGEN are moved to an inexistent face
1410 // by FillSMesh() (find "AddFaceDescriptor")
1411 // 2) Temporary triangles generated by StdMeshers_QuadToTriaAdaptor
1412 // are on faces where quadrangles were.
1413 // Due to these 2 points, wrong geom faces are used while conversion to quadratic
1414 // of the mentioned above quadrangles and triangles
1416 // Orient the face correctly in solidID1 (issue 0020206)
1417 bool reverse = false;
1419 TopoDS_Shape solid = occgeom.somap( solidID1 );
1420 TopAbs_Orientation faceOriInSolid = helper.GetSubShapeOri( solid, geomFace );
1421 if ( faceOriInSolid >= 0 )
1423 helper.IsReversedSubMesh( TopoDS::Face( geomFace.Oriented( faceOriInSolid )));
1426 // Add surface elements
1428 netgen::Element2d tri(3);
1429 tri.SetIndex( faceNgID );
1430 SMESH_TNodeXYZ xyz[3];
1432 #ifdef DUMP_TRIANGLES
1433 cout << "SMESH face " << meshDS->ShapeToIndex( geomFace )
1434 << " internal="<<isInternalFace << endl;
1437 SMDS_ElemIteratorPtr faces = smDS->GetElements();
1438 while ( faces->more() )
1440 const SMDS_MeshElement* f = faces->next();
1441 if ( f->NbNodes() % 3 != 0 ) // not triangle
1443 PShapeIteratorPtr solidIt=helper.GetAncestors(geomFace,*sm->GetFather(),TopAbs_SOLID);
1444 if ( const TopoDS_Shape * solid = solidIt->next() )
1445 sm = _mesh->GetSubMesh( *solid );
1446 SMESH_BadInputElements* badElems =
1447 new SMESH_BadInputElements( meshDS, COMPERR_BAD_INPUT_MESH, "Not triangle sub-mesh");
1449 sm->GetComputeError().reset( badElems );
1453 if ( hasVLOn2Sides )
1454 tri.SetIndex( getFaceNgID( f, solidSMDSIDs, faceNgID ));
1456 for ( int i = 0; i < 3; ++i )
1458 const SMDS_MeshNode* node = f->GetNode( i ), * inFaceNode=0;
1461 // get node UV on face
1462 int shapeID = node->GetShapeID();
1463 if ( helper.IsSeamShape( shapeID ))
1465 if ( helper.IsSeamShape( f->GetNodeWrap( i+1 )->GetShapeID() ))
1466 inFaceNode = f->GetNodeWrap( i-1 );
1468 inFaceNode = f->GetNodeWrap( i+1 );
1470 gp_XY uv = helper.GetNodeUV( geomFace, node, inFaceNode );
1472 int ind = reverse ? 3-i : i+1;
1473 tri.GeomInfoPi(ind).u = uv.X();
1474 tri.GeomInfoPi(ind).v = uv.Y();
1475 tri.PNum (ind) = ngNodeId( node, ngMesh, nodeNgIdMap );
1478 // pass a triangle size to NG size-map
1479 double size = ( ( xyz[0] - xyz[1] ).Modulus() +
1480 ( xyz[1] - xyz[2] ).Modulus() +
1481 ( xyz[2] - xyz[0] ).Modulus() ) / 3;
1482 gp_XYZ gc = ( xyz[0] + xyz[1] + xyz[2] ) / 3;
1483 RestrictLocalSize( ngMesh, gc, size, /*overrideMinH=*/false );
1485 ngMesh.AddSurfaceElement (tri);
1486 #ifdef DUMP_TRIANGLES
1487 cout << tri << endl;
1490 if ( isInternalFace )
1492 swap( tri[1], tri[2] );
1493 ngMesh.AddSurfaceElement (tri);
1494 #ifdef DUMP_TRIANGLES
1495 cout << tri << endl;
1498 } // loop on sub-mesh faces
1500 if ( quadHelper ) // remember medium nodes of sub-meshes
1502 SMDS_ElemIteratorPtr faces = smDS->GetElements();
1503 while ( faces->more() )
1505 const SMDS_MeshElement* f = faces->next();
1506 if ( !quadHelper->AddTLinks( static_cast< const SMDS_MeshFace*>( f )))
1512 } // case TopAbs_FACE
1514 case TopAbs_VERTEX: { // VERTEX
1515 // --------------------------
1516 // issue 0021405. Add node only if a VERTEX is shared by a not meshed EDGE,
1517 // else netgen removes a free node and nodeVector becomes invalid
1518 PShapeIteratorPtr ansIt = helper.GetAncestors( sm->GetSubShape(),
1522 while ( const TopoDS_Shape* e = ansIt->next() )
1524 SMESH_subMesh* eSub = helper.GetMesh()->GetSubMesh( *e );
1525 if (( toAdd = ( eSub->IsEmpty() && !SMESH_Algo::isDegenerated( TopoDS::Edge( *e )))))
1530 SMDS_NodeIteratorPtr nodeIt = smDS->GetNodes();
1531 if ( nodeIt->more() )
1532 ngNodeId( nodeIt->next(), ngMesh, nodeNgIdMap );
1538 } // loop on submeshes
1541 nodeVec.resize( ngMesh.GetNP() + 1 );
1542 TNode2IdMap::iterator node_NgId, nodeNgIdEnd = nodeNgIdMap.end();
1543 for ( node_NgId = nodeNgIdMap.begin(); node_NgId != nodeNgIdEnd; ++node_NgId)
1544 nodeVec[ node_NgId->second ] = node_NgId->first;
1549 //================================================================================
1551 * \brief Duplicate mesh faces on internal geom faces
1553 //================================================================================
1555 void NETGENPlugin_Mesher::FixIntFaces(const netgen::OCCGeometry& occgeom,
1556 netgen::Mesh& ngMesh,
1557 NETGENPlugin_Internals& internalShapes)
1559 SMESHDS_Mesh* meshDS = internalShapes.getMesh().GetMeshDS();
1561 // find ng indices of internal faces
1563 for ( int ngFaceID = 1; ngFaceID <= occgeom.fmap.Extent(); ++ngFaceID )
1565 int smeshID = meshDS->ShapeToIndex( occgeom.fmap( ngFaceID ));
1566 if ( internalShapes.isInternalShape( smeshID ))
1567 ngFaceIds.insert( ngFaceID );
1569 if ( !ngFaceIds.empty() )
1572 int i, nbFaces = ngMesh.GetNSE();
1573 for ( i = 1; i <= nbFaces; ++i)
1575 netgen::Element2d elem = ngMesh.SurfaceElement(i);
1576 if ( ngFaceIds.count( elem.GetIndex() ))
1578 swap( elem[1], elem[2] );
1579 ngMesh.AddSurfaceElement (elem);
1585 //================================================================================
1587 * \brief Tries to heal the mesh on a FACE. The FACE is supposed to be partially
1588 * meshed due to NETGEN failure
1589 * \param [in] occgeom - geometry
1590 * \param [in,out] ngMesh - the mesh to fix
1591 * \param [inout] faceID - ID of the FACE to fix the mesh on
1592 * \return bool - is mesh is or becomes OK
1594 //================================================================================
1596 bool NETGENPlugin_Mesher::FixFaceMesh(const netgen::OCCGeometry& occgeom,
1597 netgen::Mesh& ngMesh,
1600 // we address a case where the FACE is almost fully meshed except small holes
1601 // of usually triangular shape at FACE boundary (IPAL52861)
1603 // The case appeared to be not simple: holes only look triangular but
1604 // indeed are a self intersecting polygon. A reason of the bug was in coincident
1605 // NG points on a seam edge. But the code below is very nice, leave it for
1610 if ( occgeom.fmap.Extent() < faceID )
1612 //const TopoDS_Face& face = TopoDS::Face( occgeom.fmap( faceID ));
1614 // find free links on the FACE
1616 for ( int iF = 1; iF <= ngMesh.GetNSE(); ++iF )
1618 const netgen::Element2d& elem = ngMesh.SurfaceElement(iF);
1619 if ( faceID != elem.GetIndex() )
1621 int n0 = elem[ elem.GetNP() - 1 ];
1622 for ( int i = 0; i < elem.GetNP(); ++i )
1625 Link link( n0, n1 );
1626 if ( !linkMap.Add( link ))
1627 linkMap.Remove( link );
1631 // add/remove boundary links
1632 for ( int iSeg = 1; iSeg <= ngMesh.GetNSeg(); ++iSeg )
1634 const netgen::Segment& seg = ngMesh.LineSegment( iSeg );
1635 if ( seg.si != faceID ) // !edgeIDs.Contains( seg.edgenr ))
1637 Link link( seg[1], seg[0] ); // reverse!!!
1638 if ( !linkMap.Add( link ))
1639 linkMap.Remove( link );
1641 if ( linkMap.IsEmpty() )
1643 if ( linkMap.Extent() < 3 )
1646 // make triangles of the links
1648 netgen::Element2d tri(3);
1649 tri.SetIndex ( faceID );
1651 TLinkMap::Iterator linkIt( linkMap );
1652 Link link1 = linkIt.Value();
1653 // look for a link connected to link1
1654 TLinkMap::Iterator linkIt2 = linkIt;
1655 for ( linkIt2.Next(); linkIt2.More(); linkIt2.Next() )
1657 const Link& link2 = linkIt2.Value();
1658 if ( link2.IsConnected( link1 ))
1660 // look for a link connected to both link1 and link2
1661 TLinkMap::Iterator linkIt3 = linkIt2;
1662 for ( linkIt3.Next(); linkIt3.More(); linkIt3.Next() )
1664 const Link& link3 = linkIt3.Value();
1665 if ( link3.IsConnected( link1 ) &&
1666 link3.IsConnected( link2 ) )
1671 tri[2] = ( link2.Contains( link1.n1 ) ? link2.n1 : link3.n1 );
1672 if ( tri[0] == tri[2] || tri[1] == tri[2] )
1674 ngMesh.AddSurfaceElement( tri );
1676 // prepare for the next tria search
1677 if ( linkMap.Extent() == 3 )
1679 linkMap.Remove( link3 );
1680 linkMap.Remove( link2 );
1682 linkMap.Remove( link1 );
1683 link1 = linkIt.Value();
1696 //================================================================================
1697 // define gp_XY_Subtracted pointer to function calling gp_XY::Subtracted(gp_XY)
1698 gp_XY_FunPtr(Subtracted);
1699 //gp_XY_FunPtr(Added);
1701 //================================================================================
1703 * \brief Evaluate distance between two 2d points along the surface
1705 //================================================================================
1707 double evalDist( const gp_XY& uv1,
1709 const Handle(Geom_Surface)& surf,
1710 const int stopHandler=-1)
1712 if ( stopHandler > 0 ) // continue recursion
1714 gp_XY mid = SMESH_MesherHelper::GetMiddleUV( surf, uv1, uv2 );
1715 return evalDist( uv1,mid, surf, stopHandler-1 ) + evalDist( mid,uv2, surf, stopHandler-1 );
1717 double dist3D = surf->Value( uv1.X(), uv1.Y() ).Distance( surf->Value( uv2.X(), uv2.Y() ));
1718 if ( stopHandler == 0 ) // stop recursion
1721 // start recursion if necessary
1722 double dist2D = SMESH_MesherHelper::ApplyIn2D(surf, uv1, uv2, gp_XY_Subtracted, 0).Modulus();
1723 if ( fabs( dist3D - dist2D ) < dist2D * 1e-10 )
1724 return dist3D; // equal parametrization of a planar surface
1726 return evalDist( uv1, uv2, surf, 3 ); // start recursion
1729 //================================================================================
1731 * \brief Data of vertex internal in geom face
1733 //================================================================================
1737 gp_XY uv; //!< UV in face parametric space
1738 int ngId; //!< ng id of corresponding node
1739 gp_XY uvClose; //!< UV of closest boundary node
1740 int ngIdClose; //!< ng id of closest boundary node
1743 //================================================================================
1745 * \brief Data of vertex internal in solid
1747 //================================================================================
1751 int ngId; //!< ng id of corresponding node
1752 int ngIdClose; //!< ng id of closest 2d mesh element
1753 int ngIdCloseN; //!< ng id of closest node of the closest 2d mesh element
1756 inline double dist2( const netgen::MeshPoint& p1, const netgen::MeshPoint& p2 )
1758 return gp_Pnt( NGPOINT_COORDS(p1)).SquareDistance( gp_Pnt( NGPOINT_COORDS(p2)));
1761 // inline double dist2(const netgen::MeshPoint& p, const SMDS_MeshNode* n )
1763 // return gp_Pnt( NGPOINT_COORDS(p)).SquareDistance( SMESH_NodeXYZ(n));
1767 //================================================================================
1769 * \brief Make netgen take internal vertices in faces into account by adding
1770 * segments including internal vertices
1772 * This function works in supposition that 1D mesh is already computed in ngMesh
1774 //================================================================================
1776 void NETGENPlugin_Mesher::AddIntVerticesInFaces(const netgen::OCCGeometry& occgeom,
1777 netgen::Mesh& ngMesh,
1778 vector<const SMDS_MeshNode*>& nodeVec,
1779 NETGENPlugin_Internals& internalShapes)
1781 if ((int) nodeVec.size() < ngMesh.GetNP() )
1782 nodeVec.resize( ngMesh.GetNP(), 0 );
1784 SMESHDS_Mesh* meshDS = internalShapes.getMesh().GetMeshDS();
1785 SMESH_MesherHelper helper( internalShapes.getMesh() );
1787 const map<int,list<int> >& face2Vert = internalShapes.getFacesWithVertices();
1788 map<int,list<int> >::const_iterator f2v = face2Vert.begin();
1789 for ( ; f2v != face2Vert.end(); ++f2v )
1791 const TopoDS_Face& face = TopoDS::Face( meshDS->IndexToShape( f2v->first ));
1792 if ( face.IsNull() ) continue;
1793 int faceNgID = occgeom.fmap.FindIndex (face);
1794 if ( faceNgID < 0 ) continue;
1796 TopLoc_Location loc;
1797 Handle(Geom_Surface) surf = BRep_Tool::Surface(face,loc);
1799 helper.SetSubShape( face );
1800 helper.SetElementsOnShape( true );
1802 // Get data of internal vertices and add them to ngMesh
1804 multimap< double, TIntVData > dist2VData; // sort vertices by distance from boundary nodes
1806 int i, nbSegInit = ngMesh.GetNSeg();
1808 // boundary characteristics
1809 double totSegLen2D = 0;
1812 const list<int>& iVertices = f2v->second;
1813 list<int>::const_iterator iv = iVertices.begin();
1814 for ( int nbV = 0; iv != iVertices.end(); ++iv, nbV++ )
1817 // get node on vertex
1818 const TopoDS_Vertex V = TopoDS::Vertex( meshDS->IndexToShape( *iv ));
1819 const SMDS_MeshNode * nV = SMESH_Algo::VertexNode( V, meshDS );
1822 SMESH_subMesh* sm = helper.GetMesh()->GetSubMesh( V );
1823 sm->ComputeStateEngine( SMESH_subMesh::COMPUTE );
1824 nV = SMESH_Algo::VertexNode( V, meshDS );
1825 if ( !nV ) continue;
1828 netgen::MeshPoint mp( netgen::Point<3> (nV->X(), nV->Y(), nV->Z()) );
1829 ngMesh.AddPoint ( mp, 1, netgen::EDGEPOINT );
1830 vData.ngId = ngMesh.GetNP();
1831 nodeVec.push_back( nV );
1835 vData.uv = helper.GetNodeUV( face, nV, 0, &uvOK );
1836 if ( !uvOK ) helper.CheckNodeUV( face, nV, vData.uv, BRep_Tool::Tolerance(V),/*force=*/1);
1838 // loop on all segments of the face to find the node closest to vertex and to count
1839 // average segment 2d length
1840 double closeDist2 = numeric_limits<double>::max(), dist2;
1842 for (i = 1; i <= ngMesh.GetNSeg(); ++i)
1844 netgen::Segment & seg = ngMesh.LineSegment(i);
1845 if ( seg.si != faceNgID ) continue;
1847 for ( int iEnd = 0; iEnd < 2; ++iEnd)
1849 uv[iEnd].SetCoord( seg.epgeominfo[iEnd].u, seg.epgeominfo[iEnd].v );
1850 if ( ngIdLast == seg[ iEnd ] ) continue;
1851 dist2 = helper.ApplyIn2D(surf, uv[iEnd], vData.uv, gp_XY_Subtracted,0).SquareModulus();
1852 if ( dist2 < closeDist2 )
1853 vData.ngIdClose = seg[ iEnd ], vData.uvClose = uv[iEnd], closeDist2 = dist2;
1854 ngIdLast = seg[ iEnd ];
1858 totSegLen2D += helper.ApplyIn2D(surf, uv[0], uv[1], gp_XY_Subtracted, false).Modulus();
1862 dist2VData.insert( make_pair( closeDist2, vData ));
1865 if ( totNbSeg == 0 ) break;
1866 double avgSegLen2d = totSegLen2D / totNbSeg;
1868 // Loop on vertices to add segments
1870 multimap< double, TIntVData >::iterator dist_vData = dist2VData.begin();
1871 for ( ; dist_vData != dist2VData.end(); ++dist_vData )
1873 double closeDist2 = dist_vData->first, dist2;
1874 TIntVData & vData = dist_vData->second;
1876 // try to find more close node among segments added for internal vertices
1877 for (i = nbSegInit+1; i <= ngMesh.GetNSeg(); ++i)
1879 netgen::Segment & seg = ngMesh.LineSegment(i);
1880 if ( seg.si != faceNgID ) continue;
1882 for ( int iEnd = 0; iEnd < 2; ++iEnd)
1884 uv[iEnd].SetCoord( seg.epgeominfo[iEnd].u, seg.epgeominfo[iEnd].v );
1885 dist2 = helper.ApplyIn2D(surf, uv[iEnd], vData.uv, gp_XY_Subtracted,0).SquareModulus();
1886 if ( dist2 < closeDist2 )
1887 vData.ngIdClose = seg[ iEnd ], vData.uvClose = uv[iEnd], closeDist2 = dist2;
1890 // decide whether to use the closest node as the second end of segment or to
1891 // create a new point
1892 int segEnd1 = vData.ngId;
1893 int segEnd2 = vData.ngIdClose; // to use closest node
1894 gp_XY uvV = vData.uv, uvP = vData.uvClose;
1895 double segLenHint = ngMesh.GetH( ngMesh.Point( vData.ngId ));
1896 double nodeDist2D = sqrt( closeDist2 );
1897 double nodeDist3D = evalDist( vData.uv, vData.uvClose, surf );
1898 bool avgLenOK = ( avgSegLen2d < 0.75 * nodeDist2D );
1899 bool hintLenOK = ( segLenHint < 0.75 * nodeDist3D );
1900 //cout << "uvV " << uvV.X() <<","<<uvV.Y() << " ";
1901 if ( hintLenOK || avgLenOK )
1903 // create a point between the closest node and V
1906 double r = min( 0.5, ( hintLenOK ? segLenHint/nodeDist3D : avgSegLen2d/nodeDist2D ));
1907 // direction from V to closet node in 2D
1908 gp_Dir2d v2n( helper.ApplyIn2D(surf, uvP, uvV, gp_XY_Subtracted, false ));
1910 uvP = vData.uv + r * nodeDist2D * v2n.XY();
1911 gp_Pnt P = surf->Value( uvP.X(), uvP.Y() ).Transformed( loc );
1913 netgen::MeshPoint mp( netgen::Point<3> (P.X(), P.Y(), P.Z()));
1914 ngMesh.AddPoint ( mp, 1, netgen::EDGEPOINT );
1915 segEnd2 = ngMesh.GetNP();
1916 //cout << "Middle " << r << " uv " << uvP.X() << "," << uvP.Y() << "( " << ngMesh.Point(segEnd2).X()<<","<<ngMesh.Point(segEnd2).Y()<<","<<ngMesh.Point(segEnd2).Z()<<" )"<< endl;
1917 SMDS_MeshNode * nP = helper.AddNode(P.X(), P.Y(), P.Z());
1918 nodeVec.push_back( nP );
1920 //else cout << "at Node " << " uv " << uvP.X() << "," << uvP.Y() << endl;
1923 netgen::Segment seg;
1925 if ( segEnd1 > segEnd2 ) swap( segEnd1, segEnd2 ), swap( uvV, uvP );
1926 seg[0] = segEnd1; // ng node id
1927 seg[1] = segEnd2; // ng node id
1928 seg.edgenr = ngMesh.GetNSeg() + 1;// segment id
1931 seg.epgeominfo[ 0 ].dist = 0; // param on curve
1932 seg.epgeominfo[ 0 ].u = uvV.X();
1933 seg.epgeominfo[ 0 ].v = uvV.Y();
1934 seg.epgeominfo[ 1 ].dist = 1; // param on curve
1935 seg.epgeominfo[ 1 ].u = uvP.X();
1936 seg.epgeominfo[ 1 ].v = uvP.Y();
1938 // seg.epgeominfo[ 0 ].edgenr = 10; // = geom.emap.FindIndex(edge);
1939 // seg.epgeominfo[ 1 ].edgenr = 10; // = geom.emap.FindIndex(edge);
1941 ngMesh.AddSegment (seg);
1943 // add reverse segment
1944 swap( seg[0], seg[1] );
1945 swap( seg.epgeominfo[0], seg.epgeominfo[1] );
1946 seg.edgenr = ngMesh.GetNSeg() + 1; // segment id
1947 ngMesh.AddSegment (seg);
1951 ngMesh.CalcSurfacesOfNode();
1954 //================================================================================
1956 * \brief Make netgen take internal vertices in solids into account by adding
1957 * faces including internal vertices
1959 * This function works in supposition that 2D mesh is already computed in ngMesh
1961 //================================================================================
1963 void NETGENPlugin_Mesher::AddIntVerticesInSolids(const netgen::OCCGeometry& occgeom,
1964 netgen::Mesh& ngMesh,
1965 vector<const SMDS_MeshNode*>& nodeVec,
1966 NETGENPlugin_Internals& internalShapes)
1968 #ifdef DUMP_TRIANGLES_SCRIPT
1969 // create a python script making a mesh containing triangles added for internal vertices
1970 ofstream py(DUMP_TRIANGLES_SCRIPT);
1971 py << "import SMESH"<< endl
1972 << "from salome.smesh import smeshBuilder"<<endl
1973 << "smesh = smeshBuilder.New()"<<endl
1974 << "m = smesh.Mesh(name='triangles')" << endl;
1976 if ((int) nodeVec.size() < ngMesh.GetNP() )
1977 nodeVec.resize( ngMesh.GetNP(), 0 );
1979 SMESHDS_Mesh* meshDS = internalShapes.getMesh().GetMeshDS();
1980 SMESH_MesherHelper helper( internalShapes.getMesh() );
1982 const map<int,list<int> >& so2Vert = internalShapes.getSolidsWithVertices();
1983 map<int,list<int> >::const_iterator s2v = so2Vert.begin();
1984 for ( ; s2v != so2Vert.end(); ++s2v )
1986 const TopoDS_Shape& solid = meshDS->IndexToShape( s2v->first );
1987 if ( solid.IsNull() ) continue;
1988 int solidNgID = occgeom.somap.FindIndex (solid);
1989 if ( solidNgID < 0 && !occgeom.somap.IsEmpty() ) continue;
1991 helper.SetSubShape( solid );
1992 helper.SetElementsOnShape( true );
1994 // find ng indices of faces within the solid
1996 for (TopExp_Explorer fExp(solid, TopAbs_FACE); fExp.More(); fExp.Next() )
1997 ngFaceIds.insert( occgeom.fmap.FindIndex( fExp.Current() ));
1998 if ( ngFaceIds.size() == 1 && *ngFaceIds.begin() == 0 )
1999 ngFaceIds.insert( 1 );
2001 // Get data of internal vertices and add them to ngMesh
2003 multimap< double, TIntVSoData > dist2VData; // sort vertices by distance from ng faces
2005 int i, nbFaceInit = ngMesh.GetNSE();
2007 // boundary characteristics
2008 double totSegLen = 0;
2011 const list<int>& iVertices = s2v->second;
2012 list<int>::const_iterator iv = iVertices.begin();
2013 for ( int nbV = 0; iv != iVertices.end(); ++iv, nbV++ )
2016 const TopoDS_Vertex V = TopoDS::Vertex( meshDS->IndexToShape( *iv ));
2018 // get node on vertex
2019 const SMDS_MeshNode * nV = SMESH_Algo::VertexNode( V, meshDS );
2022 SMESH_subMesh* sm = helper.GetMesh()->GetSubMesh( V );
2023 sm->ComputeStateEngine( SMESH_subMesh::COMPUTE );
2024 nV = SMESH_Algo::VertexNode( V, meshDS );
2025 if ( !nV ) continue;
2028 netgen::MeshPoint mpV( netgen::Point<3> (nV->X(), nV->Y(), nV->Z()) );
2029 ngMesh.AddPoint ( mpV, 1, netgen::FIXEDPOINT );
2030 vData.ngId = ngMesh.GetNP();
2031 nodeVec.push_back( nV );
2033 // loop on all 2d elements to find the one closest to vertex and to count
2034 // average segment length
2035 double closeDist2 = numeric_limits<double>::max(), avgDist2;
2036 for (i = 1; i <= ngMesh.GetNSE(); ++i)
2038 const netgen::Element2d& elem = ngMesh.SurfaceElement(i);
2039 if ( !ngFaceIds.count( elem.GetIndex() )) continue;
2041 multimap< double, int> dist2nID; // sort nodes of element by distance from V
2042 for ( int j = 0; j < elem.GetNP(); ++j)
2044 netgen::MeshPoint mp = ngMesh.Point( elem[j] );
2045 double d2 = dist2( mpV, mp );
2046 dist2nID.insert( make_pair( d2, elem[j] ));
2047 avgDist2 += d2 / elem.GetNP();
2049 totNbSeg++, totSegLen+= sqrt( dist2( mp, ngMesh.Point( elem[(j+1)%elem.GetNP()])));
2051 double dist = dist2nID.begin()->first; //avgDist2;
2052 if ( dist < closeDist2 )
2053 vData.ngIdClose= i, vData.ngIdCloseN= dist2nID.begin()->second, closeDist2= dist;
2055 dist2VData.insert( make_pair( closeDist2, vData ));
2058 if ( totNbSeg == 0 ) break;
2059 double avgSegLen = totSegLen / totNbSeg;
2061 // Loop on vertices to add triangles
2063 multimap< double, TIntVSoData >::iterator dist_vData = dist2VData.begin();
2064 for ( ; dist_vData != dist2VData.end(); ++dist_vData )
2066 double closeDist2 = dist_vData->first;
2067 TIntVSoData & vData = dist_vData->second;
2069 const netgen::MeshPoint& mpV = ngMesh.Point( vData.ngId );
2071 // try to find more close face among ones added for internal vertices
2072 for (i = nbFaceInit+1; i <= ngMesh.GetNSE(); ++i)
2074 double avgDist2 = 0;
2075 multimap< double, int> dist2nID;
2076 const netgen::Element2d& elem = ngMesh.SurfaceElement(i);
2077 for ( int j = 0; j < elem.GetNP(); ++j)
2079 double d = dist2( mpV, ngMesh.Point( elem[j] ));
2080 dist2nID.insert( make_pair( d, elem[j] ));
2081 avgDist2 += d / elem.GetNP();
2082 if ( avgDist2 < closeDist2 )
2083 vData.ngIdClose= i, vData.ngIdCloseN= dist2nID.begin()->second, closeDist2= avgDist2;
2086 // sort nodes of the closest face by angle with vector from V to the closest node
2087 const double tol = numeric_limits<double>::min();
2088 map< double, int > angle2ID;
2089 const netgen::Element2d& closeFace = ngMesh.SurfaceElement( vData.ngIdClose );
2090 netgen::MeshPoint mp[2];
2091 mp[0] = ngMesh.Point( vData.ngIdCloseN );
2092 gp_XYZ p1( NGPOINT_COORDS( mp[0] ));
2093 gp_XYZ pV( NGPOINT_COORDS( mpV ));
2094 gp_Vec v2p1( pV, p1 );
2095 double distN1 = v2p1.Magnitude();
2096 if ( distN1 <= tol ) continue;
2098 for ( int j = 0; j < closeFace.GetNP(); ++j)
2100 mp[1] = ngMesh.Point( closeFace[j] );
2101 gp_Vec v2p( pV, gp_Pnt( NGPOINT_COORDS( mp[1] )) );
2102 angle2ID.insert( make_pair( v2p1.Angle( v2p ), closeFace[j]));
2104 // get node with angle of 60 degrees or greater
2105 map< double, int >::iterator angle_id = angle2ID.lower_bound( 60. * M_PI / 180. );
2106 if ( angle_id == angle2ID.end() ) angle_id = --angle2ID.end();
2107 const double minAngle = 30. * M_PI / 180.;
2108 const double angle = angle_id->first;
2109 bool angleOK = ( angle > minAngle );
2111 // find points to create a triangle
2112 netgen::Element2d tri(3);
2114 tri[0] = vData.ngId;
2115 tri[1] = vData.ngIdCloseN; // to use the closest nodes
2116 tri[2] = angle_id->second; // to use the node with best angle
2118 // decide whether to use the closest node and the node with best angle or to create new ones
2119 for ( int isBestAngleN = 0; isBestAngleN < 2; ++isBestAngleN )
2121 bool createNew = !angleOK; //, distOK = true;
2123 int triInd = isBestAngleN ? 2 : 1;
2124 mp[isBestAngleN] = ngMesh.Point( tri[triInd] );
2129 double distN2 = sqrt( dist2( mpV, mp[isBestAngleN]));
2130 createNew = ( fabs( distN2 - distN1 ) > 0.25 * distN1 );
2132 else if ( angle < tol )
2134 v2p1.SetX( v2p1.X() + 1e-3 );
2140 double segLenHint = ngMesh.GetH( ngMesh.Point( vData.ngId ));
2141 bool avgLenOK = ( avgSegLen < 0.75 * distN1 );
2142 bool hintLenOK = ( segLenHint < 0.75 * distN1 );
2143 createNew = (createNew || avgLenOK || hintLenOK );
2144 // we create a new node not closer than 0.5 to the closest face
2145 // in order not to clash with other close face
2146 double r = min( 0.5, ( hintLenOK ? segLenHint : avgSegLen ) / distN1 );
2147 distFromV = r * distN1;
2151 // create a new point, between the node and the vertex if angleOK
2152 gp_XYZ p( NGPOINT_COORDS( mp[isBestAngleN] ));
2153 gp_Vec v2p( pV, p ); v2p.Normalize();
2154 if ( isBestAngleN && !angleOK )
2155 p = p1 + gp_Dir( v2p.XYZ() - v2p1.XYZ()).XYZ() * distN1 * 0.95;
2157 p = pV + v2p.XYZ() * distFromV;
2159 if ( !isBestAngleN ) p1 = p, distN1 = distFromV;
2161 mp[isBestAngleN].SetPoint( netgen::Point<3> (p.X(), p.Y(), p.Z()));
2162 ngMesh.AddPoint ( mp[isBestAngleN], 1, netgen::SURFACEPOINT );
2163 tri[triInd] = ngMesh.GetNP();
2164 nodeVec.push_back( helper.AddNode( p.X(), p.Y(), p.Z()) );
2167 ngMesh.AddSurfaceElement (tri);
2168 swap( tri[1], tri[2] );
2169 ngMesh.AddSurfaceElement (tri);
2171 #ifdef DUMP_TRIANGLES_SCRIPT
2172 py << "n1 = m.AddNode( "<< mpV(0)<<", "<< mpV(1)<<", "<< mpV(2)<<") "<< endl
2173 << "n2 = m.AddNode( "<< mp[0](0)<<", "<< mp[0](1)<<", "<< mp[0](2)<<") "<< endl
2174 << "n3 = m.AddNode( "<< mp[1](0)<<", "<< mp[1](1)<<", "<< mp[1](2)<<" )" << endl
2175 << "m.AddFace([n1,n2,n3])" << endl;
2177 } // loop on internal vertices of a solid
2179 } // loop on solids with internal vertices
2182 //================================================================================
2184 * \brief Fill netgen mesh with segments of a FACE
2185 * \param ngMesh - netgen mesh
2186 * \param geom - container of OCCT geometry to mesh
2187 * \param wires - data of nodes on FACE boundary
2188 * \param helper - mesher helper holding the FACE
2189 * \param nodeVec - vector of nodes in which node index == netgen ID
2190 * \retval SMESH_ComputeErrorPtr - error description
2192 //================================================================================
2194 SMESH_ComputeErrorPtr
2195 NETGENPlugin_Mesher::AddSegmentsToMesh(netgen::Mesh& ngMesh,
2196 netgen::OCCGeometry& geom,
2197 const TSideVector& wires,
2198 SMESH_MesherHelper& helper,
2199 vector< const SMDS_MeshNode* > & nodeVec,
2200 const bool overrideMinH)
2202 // ----------------------------
2203 // Check wires and count nodes
2204 // ----------------------------
2205 smIdType nbNodes = 0;
2206 for ( size_t iW = 0; iW < wires.size(); ++iW )
2208 StdMeshers_FaceSidePtr wire = wires[ iW ];
2209 if ( wire->MissVertexNode() )
2211 // Commented for issue 0020960. It worked for the case, let's wait for case where it doesn't.
2212 // It seems that there is no reason for this limitation
2214 // (new SMESH_ComputeError(COMPERR_BAD_INPUT_MESH, "Missing nodes on vertices"));
2216 const vector<UVPtStruct>& uvPtVec = wire->GetUVPtStruct();
2217 if ((int) uvPtVec.size() != wire->NbPoints() )
2218 return SMESH_ComputeError::New(COMPERR_BAD_INPUT_MESH,
2219 SMESH_Comment("Unexpected nb of points on wire ") << iW
2220 << ": " << uvPtVec.size()<<" != "<<wire->NbPoints());
2221 nbNodes += wire->NbPoints();
2223 nodeVec.reserve( nodeVec.size() + nbNodes + 1 );
2224 if ( nodeVec.empty() )
2225 nodeVec.push_back( 0 );
2227 // -----------------
2229 // -----------------
2231 const bool wasNgMeshEmpty = ( ngMesh.GetNP() < 1 ); /* true => this method is called by
2232 NETGENPlugin_NETGEN_2D_ONLY */
2234 // map for nodes on vertices since they can be shared between wires
2235 // ( issue 0020676, face_int_box.brep) and nodes built by NETGEN
2236 map<const SMDS_MeshNode*, int > node2ngID;
2237 if ( !wasNgMeshEmpty ) // fill node2ngID with nodes built by NETGEN
2239 set< int > subIDs; // ids of sub-shapes of the FACE
2240 for ( size_t iW = 0; iW < wires.size(); ++iW )
2242 StdMeshers_FaceSidePtr wire = wires[ iW ];
2243 for ( int iE = 0, nbE = wire->NbEdges(); iE < nbE; ++iE )
2245 subIDs.insert( wire->EdgeID( iE ));
2246 subIDs.insert( helper.GetMeshDS()->ShapeToIndex( wire->FirstVertex( iE )));
2249 for ( size_t ngID = 1; ngID < nodeVec.size(); ++ngID )
2250 if ( subIDs.count( nodeVec[ngID]->GetShapeID() ))
2251 node2ngID.insert( make_pair( nodeVec[ngID], ngID ));
2254 const int solidID = 0, faceID = geom.fmap.FindIndex( helper.GetSubShape() );
2255 if ( ngMesh.GetNFD() < 1 )
2256 ngMesh.AddFaceDescriptor( netgen::FaceDescriptor( faceID, solidID, solidID, 0 ));
2258 for ( size_t iW = 0; iW < wires.size(); ++iW )
2260 StdMeshers_FaceSidePtr wire = wires[ iW ];
2261 const vector<UVPtStruct>& uvPtVec = wire->GetUVPtStruct();
2262 const smIdType nbSegments = wire->NbPoints() - 1;
2264 // assure the 1st node to be in node2ngID, which is needed to correctly
2265 // "close chain of segments" (see below) in case if the 1st node is not
2266 // onVertex because it is on a Viscous layer
2267 node2ngID.insert( make_pair( uvPtVec[ 0 ].node, ngMesh.GetNP() + 1 ));
2269 // compute length of every segment
2270 vector<double> segLen( nbSegments );
2271 for ( int i = 0; i < nbSegments; ++i )
2272 segLen[i] = SMESH_TNodeXYZ( uvPtVec[ i ].node ).Distance( uvPtVec[ i+1 ].node );
2274 int edgeID = 1, posID = -2;
2275 bool isInternalWire = false;
2276 double vertexNormPar = 0;
2277 const int prevNbNGSeg = ngMesh.GetNSeg();
2278 for ( int i = 0; i < nbSegments; ++i ) // loop on segments
2280 // Add the first point of a segment
2282 const SMDS_MeshNode * n = uvPtVec[ i ].node;
2283 const int posShapeID = n->GetShapeID();
2284 bool onVertex = ( n->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX );
2285 bool onEdge = ( n->GetPosition()->GetTypeOfPosition() == SMDS_TOP_EDGE );
2287 // skip nodes on degenerated edges
2288 if ( helper.IsDegenShape( posShapeID ) &&
2289 helper.IsDegenShape( uvPtVec[ i+1 ].node->GetShapeID() ))
2292 int ngID1 = ngMesh.GetNP() + 1, ngID2 = ngID1+1;
2293 if ( onVertex || ( !wasNgMeshEmpty && onEdge ) || helper.IsRealSeam( posShapeID ))
2294 ngID1 = node2ngID.insert( make_pair( n, ngID1 )).first->second;
2295 if ( ngID1 > ngMesh.GetNP() )
2297 netgen::MeshPoint mp( netgen::Point<3> (n->X(), n->Y(), n->Z()) );
2298 ngMesh.AddPoint ( mp, 1, netgen::EDGEPOINT );
2299 nodeVec.push_back( n );
2301 else // n is in ngMesh already, and ngID2 in prev segment is wrong
2303 ngID2 = ngMesh.GetNP() + 1;
2304 if ( i > 0 ) // prev segment belongs to same wire
2306 netgen::Segment& prevSeg = ngMesh.LineSegment( ngMesh.GetNSeg() );
2313 netgen::Segment seg;
2315 seg[0] = ngID1; // ng node id
2316 seg[1] = ngID2; // ng node id
2317 seg.edgenr = ngMesh.GetNSeg() + 1; // ng segment id
2318 seg.si = faceID; // = geom.fmap.FindIndex (face);
2320 for ( int iEnd = 0; iEnd < 2; ++iEnd)
2322 const UVPtStruct& pnt = uvPtVec[ i + iEnd ];
2324 seg.epgeominfo[ iEnd ].dist = pnt.param; // param on curve
2325 seg.epgeominfo[ iEnd ].u = pnt.u;
2326 seg.epgeominfo[ iEnd ].v = pnt.v;
2328 // find out edge id and node parameter on edge
2329 onVertex = ( pnt.normParam + 1e-10 > vertexNormPar );
2330 if ( onVertex || posShapeID != posID )
2333 double normParam = pnt.normParam;
2335 normParam = 0.5 * ( uvPtVec[ i ].normParam + uvPtVec[ i+1 ].normParam );
2336 int edgeIndexInWire = wire->EdgeIndex( normParam );
2337 vertexNormPar = wire->LastParameter( edgeIndexInWire );
2338 const TopoDS_Edge& edge = wire->Edge( edgeIndexInWire );
2339 edgeID = geom.emap.FindIndex( edge );
2341 isInternalWire = ( edge.Orientation() == TopAbs_INTERNAL );
2342 // if ( onVertex ) // param on curve is different on each of two edges
2343 // seg.epgeominfo[ iEnd ].dist = helper.GetNodeU( edge, pnt.node );
2345 seg.epgeominfo[ iEnd ].edgenr = edgeID; // = geom.emap.FindIndex(edge);
2348 ngMesh.AddSegment (seg);
2350 // restrict size of elements near the segment
2351 SMESH_TNodeXYZ np1( n ), np2( uvPtVec[ i+1 ].node );
2352 // get an average size of adjacent segments to avoid sharp change of
2353 // element size (regression on issue 0020452, note 0010898)
2354 int iPrev = SMESH_MesherHelper::WrapIndex( i-1, (int) nbSegments );
2355 int iNext = SMESH_MesherHelper::WrapIndex( i+1, (int) nbSegments );
2356 double sumH = segLen[ iPrev ] + segLen[ i ] + segLen[ iNext ];
2357 int nbSeg = ( int( segLen[ iPrev ] > sumH / 100.) +
2358 int( segLen[ i ] > sumH / 100.) +
2359 int( segLen[ iNext ] > sumH / 100.));
2361 RestrictLocalSize( ngMesh, 0.5*(np1+np2), sumH / nbSeg, overrideMinH );
2363 if ( isInternalWire )
2365 swap (seg[0], seg[1]);
2366 swap( seg.epgeominfo[0], seg.epgeominfo[1] );
2367 seg.edgenr = ngMesh.GetNSeg() + 1; // segment id
2368 ngMesh.AddSegment (seg);
2370 } // loop on segments on a wire
2372 // close chain of segments
2373 if ( nbSegments > 0 )
2375 netgen::Segment& lastSeg = ngMesh.LineSegment( ngMesh.GetNSeg() - int( isInternalWire ));
2376 const SMDS_MeshNode * lastNode = uvPtVec.back().node;
2377 lastSeg[1] = node2ngID.insert( make_pair( lastNode, lastSeg[1] )).first->second;
2378 if ( lastSeg[1] > ngMesh.GetNP() )
2380 netgen::MeshPoint mp( netgen::Point<3> (lastNode->X(), lastNode->Y(), lastNode->Z()) );
2381 ngMesh.AddPoint ( mp, 1, netgen::EDGEPOINT );
2382 nodeVec.push_back( lastNode );
2384 if ( isInternalWire )
2386 netgen::Segment& realLastSeg = ngMesh.LineSegment( ngMesh.GetNSeg() );
2387 realLastSeg[0] = lastSeg[1];
2391 #ifdef DUMP_SEGMENTS
2392 cout << "BEGIN WIRE " << iW << endl;
2393 for ( int i = prevNbNGSeg+1; i <= ngMesh.GetNSeg(); ++i )
2395 netgen::Segment& seg = ngMesh.LineSegment( i );
2397 netgen::Segment& prevSeg = ngMesh.LineSegment( i-1 );
2398 if ( seg[0] == prevSeg[1] && seg[1] == prevSeg[0] )
2400 cout << "Segment: " << seg.edgenr << endl << "\tis REVERSE of the previous one" << endl;
2404 cout << "Segment: " << seg.edgenr << endl
2405 << "\tp1: " << seg[0] << " n" << nodeVec[ seg[0]]->GetID() << endl
2406 << "\tp2: " << seg[1] << " n" << nodeVec[ seg[1]]->GetID() << endl
2407 << "\tp0 param: " << seg.epgeominfo[ 0 ].dist << endl
2408 << "\tp0 uv: " << seg.epgeominfo[ 0 ].u <<", "<< seg.epgeominfo[ 0 ].v << endl
2409 << "\tp0 edge: " << seg.epgeominfo[ 0 ].edgenr << endl
2410 << "\tp1 param: " << seg.epgeominfo[ 1 ].dist << endl
2411 << "\tp1 uv: " << seg.epgeominfo[ 1 ].u <<", "<< seg.epgeominfo[ 1 ].v << endl
2412 << "\tp1 edge: " << seg.epgeominfo[ 1 ].edgenr << endl;
2414 cout << "--END WIRE " << iW << endl;
2416 SMESH_Comment __not_unused_variable( prevNbNGSeg );
2419 } // loop on WIREs of a FACE
2421 // add a segment instead of an internal vertex
2422 if ( wasNgMeshEmpty )
2424 NETGENPlugin_Internals intShapes( *helper.GetMesh(), helper.GetSubShape(), /*is3D=*/false );
2425 AddIntVerticesInFaces( geom, ngMesh, nodeVec, intShapes );
2427 ngMesh.CalcSurfacesOfNode();
2432 //================================================================================
2434 * \brief Fill SMESH mesh according to contents of netgen mesh
2435 * \param occgeo - container of OCCT geometry to mesh
2436 * \param ngMesh - netgen mesh
2437 * \param initState - bn of entities in netgen mesh before computing
2438 * \param sMesh - SMESH mesh to fill in
2439 * \param nodeVec - vector of nodes in which node index == netgen ID
2440 * \param comment - returns problem description
2441 * \param quadHelper - holder of medium nodes of sub-meshes
2442 * \retval int - error
2444 //================================================================================
2446 int NETGENPlugin_Mesher::FillSMesh(const netgen::OCCGeometry& occgeo,
2447 netgen::Mesh& ngMesh,
2448 const NETGENPlugin_ngMeshInfo& initState,
2450 std::vector<const SMDS_MeshNode*>& nodeVec,
2451 SMESH_Comment& comment,
2452 SMESH_MesherHelper* quadHelper)
2454 int nbNod = ngMesh.GetNP();
2455 int nbSeg = ngMesh.GetNSeg();
2456 int nbFac = ngMesh.GetNSE();
2457 int nbVol = ngMesh.GetNE();
2459 SMESHDS_Mesh* meshDS = sMesh.GetMeshDS();
2461 // quadHelper is used for either
2462 // 1) making quadratic elements when a lower dimension mesh is loaded
2463 // to SMESH before conversion to quadratic by NETGEN
2464 // 2) sewing of quadratic elements with quadratic elements of sub-meshes
2465 if ( quadHelper && !quadHelper->GetIsQuadratic() && quadHelper->GetTLinkNodeMap().empty() )
2468 int ngID, nbInitNod = initState._nbNodes;
2469 if ( initState._elementsRemoved )
2471 // PAL23427. Update nodeVec to track removal of netgen free points as a result
2472 // of removal of faces in FillNgMesh() in the case of a shrunk sub-mesh
2473 size_t i, nodeVecSize = nodeVec.size();
2474 const double eps = std::numeric_limits<double>::min();
2475 for ( i = ngID = 1; i < nodeVecSize; ++ngID, ++i )
2477 gp_Pnt ngPnt( NGPOINT_COORDS( ngMesh.Point( ngID )));
2478 gp_Pnt node ( SMESH_NodeXYZ (nodeVec_ACCESS(i) ));
2479 if ( ngPnt.SquareDistance( node ) < eps )
2481 nodeVec[ ngID ] = nodeVec[ i ];
2488 nodeVec.resize( ngID );
2489 nbInitNod = ngID - 1;
2491 // -------------------------------------
2492 // Create and insert nodes into nodeVec
2493 // -------------------------------------
2495 if ( nbNod > nbInitNod )
2496 nodeVec.resize( nbNod + 1 );
2497 for ( int i = nbInitNod+1; i <= nbNod; ++i )
2499 const netgen::MeshPoint& ngPoint = ngMesh.Point(i);
2500 SMDS_MeshNode* node = NULL;
2501 TopoDS_Vertex aVert;
2502 // First, netgen creates nodes on vertices in occgeo.vmap,
2503 // so node index corresponds to vertex index
2504 // but (issue 0020776) netgen does not create nodes with equal coordinates
2505 if ( i-nbInitNod <= occgeo.vmap.Extent() )
2507 gp_Pnt p ( NGPOINT_COORDS(ngPoint) );
2508 for (int iV = i-nbInitNod; aVert.IsNull() && iV <= occgeo.vmap.Extent(); ++iV)
2510 aVert = TopoDS::Vertex( occgeo.vmap( iV ));
2511 gp_Pnt pV = BRep_Tool::Pnt( aVert );
2512 if ( p.SquareDistance( pV ) > 1e-20 )
2515 node = const_cast<SMDS_MeshNode*>( SMESH_Algo::VertexNode( aVert, meshDS ));
2518 if (!node) // node not found on vertex
2520 node = meshDS->AddNode( NGPOINT_COORDS( ngPoint ));
2521 if (!aVert.IsNull())
2522 meshDS->SetNodeOnVertex(node, aVert);
2527 // -------------------------------------------
2528 // Create mesh segments along geometric edges
2529 // -------------------------------------------
2531 int nbInitSeg = initState._nbSegments;
2532 for ( int i = nbInitSeg+1; i <= nbSeg; ++i )
2534 const netgen::Segment& seg = ngMesh.LineSegment(i);
2536 int pinds[3] = { seg.pnums[0], seg.pnums[1], seg.pnums[2] };
2539 for (int j=0; j < 3; ++j)
2541 int pind = pinds[j];
2542 if (pind <= 0 || !nodeVec_ACCESS(pind))
2550 int aGeomEdgeInd = seg.epgeominfo[j].edgenr;
2551 if (aGeomEdgeInd > 0 && aGeomEdgeInd <= occgeo.emap.Extent())
2552 aEdge = TopoDS::Edge(occgeo.emap(aGeomEdgeInd));
2554 param = seg.epgeominfo[j].dist;
2557 else // middle point
2559 param = param2 * 0.5;
2561 if (!aEdge.IsNull() && nodeVec_ACCESS(pind)->GetShapeID() < 1)
2563 meshDS->SetNodeOnEdge(nodeVec_ACCESS(pind), aEdge, param);
2568 SMDS_MeshEdge* edge = 0;
2569 if (nbp == 2) // second order ?
2571 if ( meshDS->FindEdge( nodeVec_ACCESS(pinds[0]), nodeVec_ACCESS(pinds[1])))
2573 if ( quadHelper ) // final mesh must be quadratic
2574 edge = quadHelper->AddEdge(nodeVec_ACCESS(pinds[0]), nodeVec_ACCESS(pinds[1]));
2576 edge = meshDS->AddEdge(nodeVec_ACCESS(pinds[0]), nodeVec_ACCESS(pinds[1]));
2580 if ( meshDS->FindEdge( nodeVec_ACCESS(pinds[0]), nodeVec_ACCESS(pinds[1]),
2581 nodeVec_ACCESS(pinds[2])))
2583 edge = meshDS->AddEdge(nodeVec_ACCESS(pinds[0]), nodeVec_ACCESS(pinds[1]),
2584 nodeVec_ACCESS(pinds[2]));
2588 if ( comment.empty() ) comment << "Cannot create a mesh edge";
2589 MESSAGE("Cannot create a mesh edge");
2590 nbSeg = nbFac = nbVol = 0;
2593 if ( !aEdge.IsNull() && edge->GetShapeID() < 1 )
2594 meshDS->SetMeshElementOnShape(edge, aEdge);
2596 else if ( comment.empty() )
2598 comment << "Invalid netgen segment #" << i;
2602 // ----------------------------------------
2603 // Create mesh faces along geometric faces
2604 // ----------------------------------------
2606 int nbInitFac = initState._nbFaces;
2607 int quadFaceID = ngMesh.GetNFD() + 1;
2608 if ( nbInitFac < nbFac )
2609 // add a faces descriptor to exclude qudrangle elements generated by NETGEN
2610 // from computation of 3D mesh
2611 ngMesh.AddFaceDescriptor (netgen::FaceDescriptor(quadFaceID, /*solid1=*/0, /*solid2=*/0, 0));
2613 vector<const SMDS_MeshNode*> nodes;
2614 for ( int i = nbInitFac+1; i <= nbFac; ++i )
2616 const netgen::Element2d& elem = ngMesh.SurfaceElement(i);
2617 const int aGeomFaceInd = elem.GetIndex();
2619 if (aGeomFaceInd > 0 && aGeomFaceInd <= occgeo.fmap.Extent())
2620 aFace = TopoDS::Face(occgeo.fmap(aGeomFaceInd));
2622 for ( int j = 1; j <= elem.GetNP(); ++j )
2624 int pind = elem.PNum(j);
2625 if ( pind < 1 || pind >= (int) nodeVec.size() )
2627 if ( SMDS_MeshNode* node = nodeVec_ACCESS(pind))
2629 nodes.push_back( node );
2630 if (!aFace.IsNull() && node->GetShapeID() < 1)
2632 const netgen::PointGeomInfo& pgi = elem.GeomInfoPi(j);
2633 meshDS->SetNodeOnFace(node, aFace, pgi.u, pgi.v);
2637 if ((int) nodes.size() != elem.GetNP() )
2639 if ( comment.empty() )
2640 comment << "Invalid netgen 2d element #" << i;
2641 continue; // bad node ids
2643 SMDS_MeshFace* face = NULL;
2644 switch (elem.GetType())
2647 if ( quadHelper ) // final mesh must be quadratic
2648 face = quadHelper->AddFace(nodes[0],nodes[1],nodes[2]);
2650 face = meshDS->AddFace(nodes[0],nodes[1],nodes[2]);
2653 if ( quadHelper ) // final mesh must be quadratic
2654 face = quadHelper->AddFace(nodes[0],nodes[1],nodes[2],nodes[3]);
2656 face = meshDS->AddFace(nodes[0],nodes[1],nodes[2],nodes[3]);
2657 // exclude qudrangle elements from computation of 3D mesh
2658 const_cast< netgen::Element2d& >( elem ).SetIndex( quadFaceID );
2661 nodes[5] = mediumNode( nodes[0],nodes[1],nodes[5], quadHelper );
2662 nodes[3] = mediumNode( nodes[1],nodes[2],nodes[3], quadHelper );
2663 nodes[4] = mediumNode( nodes[2],nodes[0],nodes[4], quadHelper );
2664 face = meshDS->AddFace(nodes[0],nodes[1],nodes[2],nodes[5],nodes[3],nodes[4]);
2667 nodes[4] = mediumNode( nodes[0],nodes[1],nodes[4], quadHelper );
2668 nodes[7] = mediumNode( nodes[1],nodes[2],nodes[7], quadHelper );
2669 nodes[5] = mediumNode( nodes[2],nodes[3],nodes[5], quadHelper );
2670 nodes[6] = mediumNode( nodes[3],nodes[0],nodes[6], quadHelper );
2671 face = meshDS->AddFace(nodes[0],nodes[1],nodes[2],nodes[3],
2672 nodes[4],nodes[7],nodes[5],nodes[6]);
2673 // exclude qudrangle elements from computation of 3D mesh
2674 const_cast< netgen::Element2d& >( elem ).SetIndex( quadFaceID );
2677 MESSAGE("NETGEN created a face of unexpected type, ignoring");
2682 if ( comment.empty() ) comment << "Cannot create a mesh face";
2683 MESSAGE("Cannot create a mesh face");
2684 nbSeg = nbFac = nbVol = 0;
2687 if ( !aFace.IsNull() )
2688 meshDS->SetMeshElementOnShape( face, aFace );
2691 // ------------------
2692 // Create tetrahedra
2693 // ------------------
2695 for ( int i = 1; i <= nbVol; ++i )
2697 const netgen::Element& elem = ngMesh.VolumeElement(i);
2698 int aSolidInd = elem.GetIndex();
2699 TopoDS_Solid aSolid;
2700 if ( aSolidInd > 0 && aSolidInd <= occgeo.somap.Extent() )
2701 aSolid = TopoDS::Solid(occgeo.somap(aSolidInd));
2703 for ( int j = 1; j <= elem.GetNP(); ++j )
2705 int pind = elem.PNum(j);
2706 if ( pind < 1 || pind >= (int)nodeVec.size() )
2708 if ( SMDS_MeshNode* node = nodeVec_ACCESS(pind) )
2710 nodes.push_back(node);
2711 if ( !aSolid.IsNull() && node->GetShapeID() < 1 )
2712 meshDS->SetNodeInVolume(node, aSolid);
2715 if ((int) nodes.size() != elem.GetNP() )
2717 if ( comment.empty() )
2718 comment << "Invalid netgen 3d element #" << i;
2721 SMDS_MeshVolume* vol = NULL;
2722 switch ( elem.GetType() )
2725 vol = meshDS->AddVolume(nodes[0],nodes[1],nodes[2],nodes[3]);
2728 nodes[4] = mediumNode( nodes[0],nodes[1],nodes[4], quadHelper );
2729 nodes[7] = mediumNode( nodes[1],nodes[2],nodes[7], quadHelper );
2730 nodes[5] = mediumNode( nodes[2],nodes[0],nodes[5], quadHelper );
2731 nodes[6] = mediumNode( nodes[0],nodes[3],nodes[6], quadHelper );
2732 nodes[8] = mediumNode( nodes[1],nodes[3],nodes[8], quadHelper );
2733 nodes[9] = mediumNode( nodes[2],nodes[3],nodes[9], quadHelper );
2734 vol = meshDS->AddVolume(nodes[0],nodes[1],nodes[2],nodes[3],
2735 nodes[4],nodes[7],nodes[5],nodes[6],nodes[8],nodes[9]);
2738 MESSAGE("NETGEN created a volume of unexpected type, ignoring");
2743 if ( comment.empty() ) comment << "Cannot create a mesh volume";
2744 MESSAGE("Cannot create a mesh volume");
2745 nbSeg = nbFac = nbVol = 0;
2748 if (!aSolid.IsNull())
2749 meshDS->SetMeshElementOnShape(vol, aSolid);
2751 return comment.empty() ? 0 : 1;
2756 //================================================================================
2758 * \brief Convert error into text
2760 //================================================================================
2762 std::string text(int err)
2767 SMESH_Comment("Error in netgen::OCCGenerateMesh() at ") << netgen::multithread.task;
2770 //================================================================================
2772 * \brief Convert exception into text
2774 //================================================================================
2776 std::string text(Standard_Failure& ex)
2778 SMESH_Comment str("Exception in netgen::OCCGenerateMesh()");
2779 str << " at " << netgen::multithread.task
2780 << ": " << ex.DynamicType()->Name();
2781 if ( ex.GetMessageString() && strlen( ex.GetMessageString() ))
2782 str << ": " << ex.GetMessageString();
2785 //================================================================================
2787 * \brief Convert exception into text
2789 //================================================================================
2791 std::string text(netgen::NgException& ex)
2793 SMESH_Comment str("NgException");
2794 if ( strlen( netgen::multithread.task ) > 0 )
2795 str << " at " << netgen::multithread.task;
2796 str << ": " << ex.What();
2800 //================================================================================
2802 * \brief Looks for triangles lying on a SOLID
2804 //================================================================================
2806 bool hasBadElemOnSolid( const list<const SMDS_MeshElement*>& elems,
2807 SMESH_subMesh* solidSM )
2809 TopTools_IndexedMapOfShape solidSubs;
2810 TopExp::MapShapes( solidSM->GetSubShape(), solidSubs );
2811 SMESHDS_Mesh* mesh = solidSM->GetFather()->GetMeshDS();
2813 list<const SMDS_MeshElement*>::const_iterator e = elems.begin();
2814 for ( ; e != elems.end(); ++e )
2816 const SMDS_MeshElement* elem = *e;
2817 // if ( elem->GetType() != SMDSAbs_Face ) -- 23047
2819 int nbNodesOnSolid = 0, nbNodes = elem->NbNodes();
2820 SMDS_NodeIteratorPtr nIt = elem->nodeIterator();
2821 while ( nIt->more() )
2823 const SMDS_MeshNode* n = nIt->next();
2824 const TopoDS_Shape& s = mesh->IndexToShape( n->GetShapeID() );
2825 nbNodesOnSolid += ( !s.IsNull() && solidSubs.Contains( s ));
2826 if ( nbNodesOnSolid > 2 ||
2827 nbNodesOnSolid == nbNodes)
2834 const double edgeMeshingTime = 0.001;
2835 const double faceMeshingTime = 0.019;
2836 const double edgeFaceMeshingTime = edgeMeshingTime + faceMeshingTime;
2837 const double faceOptimizTime = 0.06;
2838 const double voluMeshingTime = 0.15;
2839 const double volOptimizeTime = 0.77;
2842 //=============================================================================
2844 * Here we are going to use the NETGEN mesher
2846 //=============================================================================
2848 bool NETGENPlugin_Mesher::Compute()
2850 NETGENPlugin_NetgenLibWrapper ngLib;
2852 netgen::MeshingParameters& mparams = netgen::mparam;
2854 SMESH_ComputeErrorPtr error = SMESH_ComputeError::New();
2855 SMESH_MesherHelper quadHelper( *_mesh );
2856 quadHelper.SetIsQuadratic( mparams.secondorder );
2858 // -------------------------
2859 // Prepare OCC geometry
2860 // -------------------------
2862 netgen::OCCGeometry occgeo;
2863 list< SMESH_subMesh* > meshedSM[3]; // for 0-2 dimensions
2864 NETGENPlugin_Internals internals( *_mesh, _shape, _isVolume );
2865 PrepareOCCgeometry( occgeo, _shape, *_mesh, meshedSM, &internals );
2868 _totalTime = edgeFaceMeshingTime;
2870 _totalTime += faceOptimizTime;
2872 _totalTime += voluMeshingTime + ( _optimize ? volOptimizeTime : 0 );
2873 double doneTime = 0;
2876 _curShapeIndex = -1;
2878 // -------------------------
2879 // Generate the mesh
2880 // -------------------------
2883 NETGENPlugin_ngMeshInfo initState; // it remembers size of ng mesh equal to size of Smesh
2885 SMESH_Comment comment;
2888 // vector of nodes in which node index == netgen ID
2889 vector< const SMDS_MeshNode* > nodeVec;
2897 // not to RestrictLocalH() according to curvature during MESHCONST_ANALYSE
2898 mparams.uselocalh = false;
2899 mparams.grading = 0.8; // not limitited size growth
2901 if ( _simpleHyp->GetNumberOfSegments() )
2903 mparams.maxh = occgeo.boundingbox.Diam();
2906 mparams.maxh = _simpleHyp->GetLocalLength();
2909 if ( mparams.maxh == 0.0 )
2910 mparams.maxh = occgeo.boundingbox.Diam();
2911 if ( _simpleHyp || ( mparams.minh == 0.0 && _fineness != NETGENPlugin_Hypothesis::UserDefined))
2912 mparams.minh = GetDefaultMinSize( _shape, mparams.maxh );
2914 // Local size on faces
2915 occgeo.face_maxh = mparams.maxh;
2917 // Let netgen create _ngMesh and calculate element size on not meshed shapes
2918 int startWith = netgen::MESHCONST_ANALYSE;
2919 int endWith = netgen::MESHCONST_ANALYSE;
2924 err = ngLib.GenerateMesh(occgeo, startWith, endWith, _ngMesh);
2926 if(netgen::multithread.terminate)
2929 comment << text(err);
2931 catch (Standard_Failure& ex)
2933 comment << text(ex);
2935 catch (netgen::NgException & ex)
2937 comment << text(ex);
2939 bool hasSizeFile = !mparams.meshsizefilename.empty();
2941 bool hasSizeFile = mparams.meshsizefilename;
2944 throw SMESH_ComputeError(COMPERR_BAD_PARMETERS, comment );
2946 err = 0; //- MESHCONST_ANALYSE isn't so important step
2949 ngLib.setMesh(( Ng_Mesh*) _ngMesh );
2951 _ngMesh->ClearFaceDescriptors(); // we make descriptors our-self
2953 if ( !mparams.uselocalh ) // mparams.grading is not taken into account yet
2954 _ngMesh->LocalHFunction().SetGrading( mparams.grading );
2958 // Pass 1D simple parameters to NETGEN
2959 // --------------------------------
2960 double nbSeg = (double) _simpleHyp->GetNumberOfSegments();
2961 double segSize = _simpleHyp->GetLocalLength();
2962 for ( int iE = 1; iE <= occgeo.emap.Extent(); ++iE )
2964 const TopoDS_Edge& e = TopoDS::Edge( occgeo.emap(iE));
2966 segSize = SMESH_Algo::EdgeLength( e ) / ( nbSeg - 0.4 );
2967 setLocalSize( e, segSize, *_ngMesh );
2970 else // if ( ! _simpleHyp )
2972 // Local size on shapes
2973 SetLocalSize( occgeo, *_ngMesh );
2974 SetLocalSizeForChordalError( occgeo, *_ngMesh );
2977 // Precompute internal edges (issue 0020676) in order to
2978 // add mesh on them correctly (twice) to netgen mesh
2979 if ( !err && internals.hasInternalEdges() )
2981 // load internal shapes into OCCGeometry
2982 netgen::OCCGeometry intOccgeo;
2983 internals.getInternalEdges( intOccgeo.fmap, intOccgeo.emap, intOccgeo.vmap, meshedSM );
2984 intOccgeo.boundingbox = occgeo.boundingbox;
2985 intOccgeo.shape = occgeo.shape;
2986 intOccgeo.face_maxh.SetSize(intOccgeo.fmap.Extent());
2987 intOccgeo.face_maxh = netgen::mparam.maxh;
2988 netgen::Mesh *tmpNgMesh = NULL;
2992 // compute local H on internal shapes in the main mesh
2993 //OCCSetLocalMeshSize(intOccgeo, *_ngMesh); it deletes _ngMesh->localH
2995 // let netgen create a temporary mesh
2996 ngLib.GenerateMesh(intOccgeo, startWith, endWith, tmpNgMesh);
2998 if ( netgen::multithread.terminate )
3001 // copy LocalH from the main to temporary mesh
3002 initState.transferLocalH( _ngMesh, tmpNgMesh );
3004 // compute mesh on internal edges
3005 startWith = endWith = netgen::MESHCONST_MESHEDGES;
3006 err = ngLib.GenerateMesh(intOccgeo, startWith, endWith, tmpNgMesh);
3008 comment << text(err);
3010 catch (Standard_Failure& ex)
3012 comment << text(ex);
3015 initState.restoreLocalH( tmpNgMesh );
3017 // fill SMESH by netgen mesh
3018 vector< const SMDS_MeshNode* > tmpNodeVec;
3019 FillSMesh( intOccgeo, *tmpNgMesh, initState, *_mesh, tmpNodeVec, comment );
3020 err = ( err || !comment.empty() );
3022 nglib::Ng_DeleteMesh((nglib::Ng_Mesh*)tmpNgMesh);
3025 // Fill _ngMesh with nodes and segments of computed submeshes
3028 err = ! ( FillNgMesh(occgeo, *_ngMesh, nodeVec, meshedSM[ MeshDim_0D ]) &&
3029 FillNgMesh(occgeo, *_ngMesh, nodeVec, meshedSM[ MeshDim_1D ], &quadHelper));
3031 initState = NETGENPlugin_ngMeshInfo(_ngMesh);
3036 startWith = endWith = netgen::MESHCONST_MESHEDGES;
3041 err = ngLib.GenerateMesh(occgeo, startWith, endWith);
3043 if ( netgen::multithread.terminate )
3046 comment << text(err);
3048 catch (Standard_Failure& ex)
3050 comment << text(ex);
3055 _ticTime = ( doneTime += edgeMeshingTime ) / _totalTime / _progressTic;
3057 mparams.uselocalh = true; // restore as it is used at surface optimization
3059 // ---------------------
3060 // compute surface mesh
3061 // ---------------------
3064 // Pass 2D simple parameters to NETGEN
3066 if ( double area = _simpleHyp->GetMaxElementArea() ) {
3068 mparams.maxh = sqrt(2. * area/sqrt(3.0));
3069 mparams.grading = 0.4; // moderate size growth
3072 // length from edges
3073 if ( _ngMesh->GetNSeg() ) {
3074 double edgeLength = 0;
3075 TopTools_MapOfShape visitedEdges;
3076 for ( TopExp_Explorer exp( _shape, TopAbs_EDGE ); exp.More(); exp.Next() )
3077 if( visitedEdges.Add(exp.Current()) )
3078 edgeLength += SMESH_Algo::EdgeLength( TopoDS::Edge( exp.Current() ));
3079 // we have to multiply length by 2 since for each TopoDS_Edge there
3080 // are double set of NETGEN edges, in other words, we have to
3081 // divide _ngMesh->GetNSeg() by 2.
3082 mparams.maxh = 2*edgeLength / _ngMesh->GetNSeg();
3085 mparams.maxh = 1000;
3087 mparams.grading = 0.2; // slow size growth
3089 mparams.quad = _simpleHyp->GetAllowQuadrangles();
3090 mparams.maxh = min( mparams.maxh, occgeo.boundingbox.Diam()/2 );
3091 _ngMesh->SetGlobalH (mparams.maxh);
3092 netgen::Box<3> bb = occgeo.GetBoundingBox();
3093 bb.Increase (bb.Diam()/20);
3094 _ngMesh->SetLocalH (bb.PMin(), bb.PMax(), mparams.grading);
3097 // Care of vertices internal in faces (issue 0020676)
3098 if ( internals.hasInternalVertexInFace() )
3100 // store computed segments in SMESH in order not to create SMESH
3101 // edges for ng segments added by AddIntVerticesInFaces()
3102 FillSMesh( occgeo, *_ngMesh, initState, *_mesh, nodeVec, comment );
3103 // add segments to faces with internal vertices
3104 AddIntVerticesInFaces( occgeo, *_ngMesh, nodeVec, internals );
3105 initState = NETGENPlugin_ngMeshInfo(_ngMesh);
3108 // Build viscous layers
3109 if (( _isViscousLayers2D ) ||
3110 ( !occgeo.fmap.IsEmpty() &&
3111 StdMeshers_ViscousLayers2D::HasProxyMesh( TopoDS::Face( occgeo.fmap(1) ), *_mesh )))
3113 if ( !internals.hasInternalVertexInFace() ) {
3114 FillSMesh( occgeo, *_ngMesh, initState, *_mesh, nodeVec, comment );
3115 initState = NETGENPlugin_ngMeshInfo(_ngMesh);
3117 SMESH_ProxyMesh::Ptr viscousMesh;
3118 SMESH_MesherHelper helper( *_mesh );
3119 for ( int faceID = 1; faceID <= occgeo.fmap.Extent(); ++faceID )
3121 const TopoDS_Face& F = TopoDS::Face( occgeo.fmap( faceID ));
3122 viscousMesh = StdMeshers_ViscousLayers2D::Compute( *_mesh, F );
3125 if ( viscousMesh->NbProxySubMeshes() == 0 )
3127 // exclude from computation ng segments built on EDGEs of F
3128 for (int i = 1; i <= _ngMesh->GetNSeg(); i++)
3130 netgen::Segment & seg = _ngMesh->LineSegment(i);
3131 if (seg.si == faceID)
3134 // add new segments to _ngMesh instead of excluded ones
3135 helper.SetSubShape( F );
3137 StdMeshers_FaceSide::GetFaceWires( F, *_mesh, /*skipMediumNodes=*/true,
3138 error, &helper, viscousMesh );
3139 error = AddSegmentsToMesh( *_ngMesh, occgeo, wires, helper, nodeVec );
3141 if ( !error ) error = SMESH_ComputeError::New();
3143 initState = NETGENPlugin_ngMeshInfo(_ngMesh);
3146 // Let netgen compute 2D mesh
3147 startWith = netgen::MESHCONST_MESHSURFACE;
3148 endWith = _optimize ? netgen::MESHCONST_OPTSURFACE : netgen::MESHCONST_MESHSURFACE;
3153 err = ngLib.GenerateMesh(occgeo, startWith, endWith);
3155 if ( netgen::multithread.terminate )
3158 comment << text (err);
3160 catch (Standard_Failure& ex)
3162 comment << text(ex);
3163 //err = 1; -- try to make volumes anyway
3165 catch (netgen::NgException& exc)
3167 comment << text(exc);
3168 //err = 1; -- try to make volumes anyway
3173 doneTime += faceMeshingTime + ( _optimize ? faceOptimizTime : 0 );
3174 _ticTime = doneTime / _totalTime / _progressTic;
3176 // ---------------------
3177 // generate volume mesh
3178 // ---------------------
3179 // Fill _ngMesh with nodes and faces of computed 2D submeshes
3180 if ( !err && _isVolume &&
3181 ( !meshedSM[ MeshDim_2D ].empty() || mparams.quad || _viscousLayersHyp ))
3183 // load SMESH with computed segments and faces
3184 FillSMesh( occgeo, *_ngMesh, initState, *_mesh, nodeVec, comment, &quadHelper );
3186 // compute prismatic boundary volumes
3187 smIdType nbQuad = _mesh->NbQuadrangles();
3188 SMESH_ProxyMesh::Ptr viscousMesh;
3189 if ( _viscousLayersHyp )
3191 viscousMesh = _viscousLayersHyp->Compute( *_mesh, _shape );
3195 // compute pyramids on quadrangles
3196 vector<SMESH_ProxyMesh::Ptr> pyramidMeshes( occgeo.somap.Extent() );
3198 for ( int iS = 1; iS <= occgeo.somap.Extent(); ++iS )
3200 StdMeshers_QuadToTriaAdaptor* adaptor = new StdMeshers_QuadToTriaAdaptor;
3201 pyramidMeshes[ iS-1 ].reset( adaptor );
3202 bool ok = adaptor->Compute( *_mesh, occgeo.somap(iS), viscousMesh.get() );
3206 // add proxy faces to NG mesh
3207 list< SMESH_subMesh* > viscousSM;
3208 for ( int iS = 1; iS <= occgeo.somap.Extent(); ++iS )
3210 list< SMESH_subMesh* > quadFaceSM;
3211 for (TopExp_Explorer face(occgeo.somap(iS), TopAbs_FACE); face.More(); face.Next())
3212 if ( pyramidMeshes[iS-1] && pyramidMeshes[iS-1]->GetProxySubMesh( face.Current() ))
3214 quadFaceSM.push_back( _mesh->GetSubMesh( face.Current() ));
3215 meshedSM[ MeshDim_2D ].remove( quadFaceSM.back() );
3217 else if ( viscousMesh && viscousMesh->GetProxySubMesh( face.Current() ))
3219 viscousSM.push_back( _mesh->GetSubMesh( face.Current() ));
3220 meshedSM[ MeshDim_2D ].remove( viscousSM.back() );
3222 if ( !quadFaceSM.empty() )
3223 FillNgMesh(occgeo, *_ngMesh, nodeVec, quadFaceSM, &quadHelper, pyramidMeshes[iS-1]);
3225 if ( !viscousSM.empty() )
3226 FillNgMesh(occgeo, *_ngMesh, nodeVec, viscousSM, &quadHelper, viscousMesh );
3228 // fill _ngMesh with faces of sub-meshes
3229 err = ! ( FillNgMesh(occgeo, *_ngMesh, nodeVec, meshedSM[ MeshDim_2D ], &quadHelper));
3230 initState = NETGENPlugin_ngMeshInfo(_ngMesh, /*checkRemovedElems=*/true);
3231 // toPython( _ngMesh );
3233 if (!err && _isVolume)
3235 // Pass 3D simple parameters to NETGEN
3236 const NETGENPlugin_SimpleHypothesis_3D* simple3d =
3237 dynamic_cast< const NETGENPlugin_SimpleHypothesis_3D* > ( _simpleHyp );
3239 _ngMesh->Compress();
3240 if ( double vol = simple3d->GetMaxElementVolume() ) {
3242 mparams.maxh = pow( 72, 1/6. ) * pow( vol, 1/3. );
3243 mparams.maxh = min( mparams.maxh, occgeo.boundingbox.Diam()/2 );
3246 // length from faces
3247 mparams.maxh = _ngMesh->AverageH();
3249 _ngMesh->SetGlobalH (mparams.maxh);
3250 mparams.grading = 0.4;
3251 ngLib.CalcLocalH( ngLib._ngMesh );
3253 // Care of vertices internal in solids and internal faces (issue 0020676)
3254 if ( internals.hasInternalVertexInSolid() || internals.hasInternalFaces() )
3256 // store computed faces in SMESH in order not to create SMESH
3257 // faces for ng faces added here
3258 FillSMesh( occgeo, *_ngMesh, initState, *_mesh, nodeVec, comment, &quadHelper );
3259 // add ng faces to solids with internal vertices
3260 AddIntVerticesInSolids( occgeo, *_ngMesh, nodeVec, internals );
3261 // duplicate mesh faces on internal faces
3262 FixIntFaces( occgeo, *_ngMesh, internals );
3263 initState = NETGENPlugin_ngMeshInfo(_ngMesh);
3265 // Let netgen compute 3D mesh
3266 startWith = endWith = netgen::MESHCONST_MESHVOLUME;
3271 err = ngLib.GenerateMesh(occgeo, startWith, endWith);
3273 if ( netgen::multithread.terminate )
3276 if ( comment.empty() ) // do not overwrite a previous error
3277 comment << text(err);
3279 catch (Standard_Failure& ex)
3281 if ( comment.empty() ) // do not overwrite a previous error
3282 comment << text(ex);
3285 catch (netgen::NgException& exc)
3287 if ( comment.empty() ) // do not overwrite a previous error
3288 comment << text(exc);
3291 _ticTime = ( doneTime += voluMeshingTime ) / _totalTime / _progressTic;
3293 // Let netgen optimize 3D mesh
3294 if ( !err && _optimize )
3296 startWith = endWith = netgen::MESHCONST_OPTVOLUME;
3301 err = ngLib.GenerateMesh(occgeo, startWith, endWith);
3303 if ( netgen::multithread.terminate )
3306 if ( comment.empty() ) // do not overwrite a previous error
3307 comment << text(err);
3309 catch (Standard_Failure& ex)
3311 if ( comment.empty() ) // do not overwrite a previous error
3312 comment << text(ex);
3314 catch (netgen::NgException& exc)
3316 if ( comment.empty() ) // do not overwrite a previous error
3317 comment << text(exc);
3321 if (!err && mparams.secondorder > 0)
3326 if ( !meshedSM[ MeshDim_1D ].empty() )
3328 // remove segments not attached to geometry (IPAL0052479)
3329 for (int i = 1; i <= _ngMesh->GetNSeg(); ++i)
3331 const netgen::Segment & seg = _ngMesh->LineSegment (i);
3332 if ( seg.epgeominfo[ 0 ].edgenr == 0 )
3334 _ngMesh->DeleteSegment( i );
3335 initState._nbSegments--;
3338 _ngMesh->Compress();
3340 // convert to quadratic
3342 occgeo.GetRefinement().MakeSecondOrder(*_ngMesh);
3344 netgen::OCCRefinementSurfaces(occgeo).MakeSecondOrder(*_ngMesh);
3347 // care of elements already loaded to SMESH
3348 // if ( initState._nbSegments > 0 )
3349 // makeQuadratic( occgeo.emap, _mesh );
3350 // if ( initState._nbFaces > 0 )
3351 // makeQuadratic( occgeo.fmap, _mesh );
3353 catch (Standard_Failure& ex)
3355 if ( comment.empty() ) // do not overwrite a previous error
3356 comment << "Exception in netgen at passing to 2nd order ";
3358 catch (netgen::NgException& exc)
3360 if ( comment.empty() ) // do not overwrite a previous error
3361 comment << exc.What();
3366 _ticTime = 0.98 / _progressTic;
3368 //int nbNod = _ngMesh->GetNP();
3369 //int nbSeg = _ngMesh->GetNSeg();
3370 int nbFac = _ngMesh->GetNSE();
3371 int nbVol = _ngMesh->GetNE();
3372 bool isOK = ( !err && (_isVolume ? (nbVol > 0) : (nbFac > 0)) );
3374 // Feed back the SMESHDS with the generated Nodes and Elements
3375 if ( true /*isOK*/ ) // get whatever built
3377 FillSMesh( occgeo, *_ngMesh, initState, *_mesh, nodeVec, comment, &quadHelper );
3379 if ( quadHelper.GetIsQuadratic() ) // remove free nodes
3381 for ( size_t i = 0; i < nodeVec.size(); ++i )
3382 if ( nodeVec[i] && nodeVec[i]->NbInverseElements() == 0 )
3384 _mesh->GetMeshDS()->RemoveFreeNode( nodeVec[i], 0, /*fromGroups=*/false );
3387 for ( size_t i = nodeVec.size()-1; i > 0; --i ) // remove trailing removed nodes
3389 nodeVec.resize( i );
3394 SMESH_ComputeErrorPtr readErr = ReadErrors(nodeVec);
3395 if ( readErr && readErr->HasBadElems() )
3398 if ( !comment.empty() && !readErr->myComment.empty() ) comment += "\n";
3399 comment += readErr->myComment;
3401 if ( error->IsOK() && ( !isOK || comment.size() > 0 ))
3402 error->myName = COMPERR_ALGO_FAILED;
3403 if ( !comment.empty() )
3404 error->myComment = comment;
3406 // SetIsAlwaysComputed( true ) to empty sub-meshes, which
3407 // appear if the geometry contains coincident sub-shape due
3408 // to bool merge_solids = 1; in netgen/libsrc/occ/occgenmesh.cpp
3409 const int nbMaps = 2;
3410 const TopTools_IndexedMapOfShape* geoMaps[nbMaps] =
3411 { & occgeo.vmap, & occgeo.emap/*, & occgeo.fmap*/ };
3412 for ( int iMap = 0; iMap < nbMaps; ++iMap )
3413 for (int i = 1; i <= geoMaps[iMap]->Extent(); i++)
3414 if ( SMESH_subMesh* sm = _mesh->GetSubMeshContaining( geoMaps[iMap]->FindKey(i)))
3415 if ( !sm->IsMeshComputed() )
3416 sm->SetIsAlwaysComputed( true );
3418 // set bad compute error to subshapes of all failed sub-shapes
3419 if ( !error->IsOK() )
3421 bool pb2D = false, pb3D = false;
3422 for (int i = 1; i <= occgeo.fmap.Extent(); i++) {
3423 int status = occgeo.facemeshstatus[i-1];
3424 if (status == netgen::FACE_MESHED_OK ) continue;
3425 if ( SMESH_subMesh* sm = _mesh->GetSubMeshContaining( occgeo.fmap( i ))) {
3426 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
3427 if ( !smError || smError->IsOK() ) {
3428 if ( status == netgen::FACE_FAILED )
3429 smError.reset( new SMESH_ComputeError( *error ));
3431 smError.reset( new SMESH_ComputeError( COMPERR_ALGO_FAILED, "Ignored" ));
3432 if ( SMESH_Algo::GetMeshError( sm ) == SMESH_Algo::MEr_OK )
3433 smError->myName = COMPERR_WARNING;
3435 pb2D = pb2D || smError->IsKO();
3438 if ( !pb2D ) // all faces are OK
3439 for (int i = 1; i <= occgeo.somap.Extent(); i++)
3440 if ( SMESH_subMesh* sm = _mesh->GetSubMeshContaining( occgeo.somap( i )))
3442 bool smComputed = nbVol && !sm->IsEmpty();
3443 if ( smComputed && internals.hasInternalVertexInSolid( sm->GetId() ))
3445 size_t nbIntV = internals.getSolidsWithVertices().find( sm->GetId() )->second.size();
3446 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
3447 smComputed = ( smDS->NbElements() > 0 || smDS->NbNodes() > (smIdType) nbIntV );
3449 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
3450 if ( !smComputed && ( !smError || smError->IsOK() ))
3453 if ( nbVol && SMESH_Algo::GetMeshError( sm ) == SMESH_Algo::MEr_OK )
3455 smError->myName = COMPERR_WARNING;
3457 else if ( smError->HasBadElems() ) // bad surface mesh
3459 if ( !hasBadElemOnSolid
3460 ( static_cast<SMESH_BadInputElements*>( smError.get() )->myBadElements, sm ))
3464 pb3D = pb3D || ( smError && smError->IsKO() );
3466 if ( !pb2D && !pb3D )
3467 err = 0; // no fatal errors, only warnings
3470 ngLib._isComputeOk = !err;
3475 //=============================================================================
3479 //=============================================================================
3480 bool NETGENPlugin_Mesher::Evaluate(MapShapeNbElems& aResMap)
3482 netgen::MeshingParameters& mparams = netgen::mparam;
3485 // -------------------------
3486 // Prepare OCC geometry
3487 // -------------------------
3488 netgen::OCCGeometry occgeo;
3489 NETGENPlugin_Internals internals( *_mesh, _shape, _isVolume );
3490 PrepareOCCgeometry( occgeo, _shape, *_mesh, 0, &internals );
3492 bool tooManyElems = false;
3493 const int hugeNb = std::numeric_limits<int>::max() / 100;
3498 // pass 1D simple parameters to NETGEN
3501 // not to RestrictLocalH() according to curvature during MESHCONST_ANALYSE
3502 mparams.uselocalh = false;
3503 mparams.grading = 0.8; // not limitited size growth
3505 if ( _simpleHyp->GetNumberOfSegments() )
3507 mparams.maxh = occgeo.boundingbox.Diam();
3510 mparams.maxh = _simpleHyp->GetLocalLength();
3513 if ( mparams.maxh == 0.0 )
3514 mparams.maxh = occgeo.boundingbox.Diam();
3515 if ( _simpleHyp || ( mparams.minh == 0.0 && _fineness != NETGENPlugin_Hypothesis::UserDefined))
3516 mparams.minh = GetDefaultMinSize( _shape, mparams.maxh );
3518 // let netgen create _ngMesh and calculate element size on not meshed shapes
3519 NETGENPlugin_NetgenLibWrapper ngLib;
3520 netgen::Mesh *ngMesh = NULL;
3521 int startWith = netgen::MESHCONST_ANALYSE;
3522 int endWith = netgen::MESHCONST_MESHEDGES;
3523 int err = ngLib.GenerateMesh(occgeo, startWith, endWith, ngMesh);
3525 if(netgen::multithread.terminate)
3528 ngLib.setMesh(( Ng_Mesh*) ngMesh );
3530 if ( SMESH_subMesh* sm = _mesh->GetSubMeshContaining( _shape ))
3531 sm->GetComputeError().reset( new SMESH_ComputeError( COMPERR_ALGO_FAILED ));
3534 // if ( _simpleHyp )
3536 // // Pass 1D simple parameters to NETGEN
3537 // // --------------------------------
3538 // int nbSeg = _simpleHyp->GetNumberOfSegments();
3539 // double segSize = _simpleHyp->GetLocalLength();
3540 // for ( int iE = 1; iE <= occgeo.emap.Extent(); ++iE )
3542 // const TopoDS_Edge& e = TopoDS::Edge( occgeo.emap(iE));
3544 // segSize = SMESH_Algo::EdgeLength( e ) / ( nbSeg - 0.4 );
3545 // setLocalSize( e, segSize, *ngMesh );
3548 // else // if ( ! _simpleHyp )
3550 // // Local size on shapes
3551 // SetLocalSize( occgeo, *ngMesh );
3553 // calculate total nb of segments and length of edges
3554 double fullLen = 0.0;
3555 smIdType fullNbSeg = 0;
3556 int entity = mparams.secondorder > 0 ? SMDSEntity_Quad_Edge : SMDSEntity_Edge;
3557 TopTools_DataMapOfShapeInteger Edge2NbSeg;
3558 for (TopExp_Explorer exp(_shape, TopAbs_EDGE); exp.More(); exp.Next())
3560 TopoDS_Edge E = TopoDS::Edge( exp.Current() );
3561 if( !Edge2NbSeg.Bind(E,0) )
3564 double aLen = SMESH_Algo::EdgeLength(E);
3567 vector<smIdType>& aVec = aResMap[_mesh->GetSubMesh(E)];
3569 aVec.resize( SMDSEntity_Last, 0);
3571 fullNbSeg += aVec[ entity ];
3574 // store nb of segments computed by Netgen
3576 for (int i = 1; i <= ngMesh->GetNSeg(); ++i )
3578 const netgen::Segment& seg = ngMesh->LineSegment(i);
3579 Link link(seg[0], seg[1]);
3580 if ( !linkMap.Add( link )) continue;
3581 int aGeomEdgeInd = seg.epgeominfo[0].edgenr;
3582 if (aGeomEdgeInd > 0 && aGeomEdgeInd <= occgeo.emap.Extent())
3584 vector<smIdType>& aVec = aResMap[_mesh->GetSubMesh(occgeo.emap(aGeomEdgeInd))];
3588 // store nb of nodes on edges computed by Netgen
3589 TopTools_DataMapIteratorOfDataMapOfShapeInteger Edge2NbSegIt(Edge2NbSeg);
3590 for (; Edge2NbSegIt.More(); Edge2NbSegIt.Next())
3592 vector<smIdType>& aVec = aResMap[_mesh->GetSubMesh(Edge2NbSegIt.Key())];
3593 if ( aVec[ entity ] > 1 && aVec[ SMDSEntity_Node ] == 0 )
3594 aVec[SMDSEntity_Node] = mparams.secondorder > 0 ? 2*aVec[ entity ]-1 : aVec[ entity ]-1;
3596 fullNbSeg += aVec[ entity ];
3597 Edge2NbSeg( Edge2NbSegIt.Key() ) = (int) aVec[ entity ];
3599 if ( fullNbSeg == 0 )
3606 if ( double area = _simpleHyp->GetMaxElementArea() ) {
3608 mparams.maxh = sqrt(2. * area/sqrt(3.0));
3609 mparams.grading = 0.4; // moderate size growth
3612 // length from edges
3613 mparams.maxh = fullLen / double( fullNbSeg );
3614 mparams.grading = 0.2; // slow size growth
3617 mparams.maxh = min( mparams.maxh, occgeo.boundingbox.Diam()/2 );
3618 mparams.maxh = min( mparams.maxh, fullLen / double( fullNbSeg ) * (1. + mparams.grading));
3620 for (TopExp_Explorer exp(_shape, TopAbs_FACE); exp.More(); exp.Next())
3622 TopoDS_Face F = TopoDS::Face( exp.Current() );
3623 SMESH_subMesh *sm = _mesh->GetSubMesh(F);
3625 BRepGProp::SurfaceProperties(F,G);
3626 double anArea = G.Mass();
3627 tooManyElems = tooManyElems || ( anArea/hugeNb > mparams.maxh*mparams.maxh );
3629 if ( !tooManyElems )
3631 TopTools_MapOfShape edges;
3632 for (TopExp_Explorer exp1(F,TopAbs_EDGE); exp1.More(); exp1.Next())
3633 if ( edges.Add( exp1.Current() ))
3634 nb1d += Edge2NbSeg.Find(exp1.Current());
3636 int nbFaces = tooManyElems ? hugeNb : int( 4*anArea / (mparams.maxh*mparams.maxh*sqrt(3.)));
3637 int nbNodes = tooManyElems ? hugeNb : (( nbFaces*3 - (nb1d-1)*2 ) / 6 + 1 );
3639 vector<smIdType> aVec(SMDSEntity_Last, 0);
3640 if( mparams.secondorder > 0 ) {
3641 int nb1d_in = (nbFaces*3 - nb1d) / 2;
3642 aVec[SMDSEntity_Node] = nbNodes + nb1d_in;
3643 aVec[SMDSEntity_Quad_Triangle] = nbFaces;
3646 aVec[SMDSEntity_Node] = Max ( nbNodes, 0 );
3647 aVec[SMDSEntity_Triangle] = nbFaces;
3649 aResMap[sm].swap(aVec);
3656 // pass 3D simple parameters to NETGEN
3657 const NETGENPlugin_SimpleHypothesis_3D* simple3d =
3658 dynamic_cast< const NETGENPlugin_SimpleHypothesis_3D* > ( _simpleHyp );
3660 if ( double vol = simple3d->GetMaxElementVolume() ) {
3662 mparams.maxh = pow( 72, 1/6. ) * pow( vol, 1/3. );
3663 mparams.maxh = min( mparams.maxh, occgeo.boundingbox.Diam()/2 );
3666 // using previous length from faces
3668 mparams.grading = 0.4;
3669 mparams.maxh = min( mparams.maxh, fullLen / double( fullNbSeg ) * (1. + mparams.grading));
3672 BRepGProp::VolumeProperties(_shape,G);
3673 double aVolume = G.Mass();
3674 double tetrVol = 0.1179*mparams.maxh*mparams.maxh*mparams.maxh;
3675 tooManyElems = tooManyElems || ( aVolume/hugeNb > tetrVol );
3676 int nbVols = tooManyElems ? hugeNb : int(aVolume/tetrVol);
3677 int nb1d_in = int(( nbVols*6 - fullNbSeg ) / 6 );
3678 vector<smIdType> aVec(SMDSEntity_Last, 0 );
3679 if ( tooManyElems ) // avoid FPE
3681 aVec[SMDSEntity_Node] = hugeNb;
3682 aVec[ mparams.secondorder > 0 ? SMDSEntity_Quad_Tetra : SMDSEntity_Tetra] = hugeNb;
3686 if( mparams.secondorder > 0 ) {
3687 aVec[SMDSEntity_Node] = nb1d_in/3 + 1 + nb1d_in;
3688 aVec[SMDSEntity_Quad_Tetra] = nbVols;
3691 aVec[SMDSEntity_Node] = nb1d_in/3 + 1;
3692 aVec[SMDSEntity_Tetra] = nbVols;
3695 SMESH_subMesh *sm = _mesh->GetSubMesh(_shape);
3696 aResMap[sm].swap(aVec);
3702 double NETGENPlugin_Mesher::GetProgress(const SMESH_Algo* /*holder*/,
3703 const int * algoProgressTic,
3704 const double * algoProgress) const
3706 ((int&) _progressTic ) = *algoProgressTic + 1;
3708 if ( !_occgeom ) return 0;
3710 double progress = -1;
3713 if ( _ticTime < 0 && netgen::multithread.task[0] == 'O'/*Optimizing surface*/ )
3715 ((double&) _ticTime ) = edgeFaceMeshingTime / _totalTime / _progressTic;
3717 else if ( !_optimize /*&& _occgeom->fmap.Extent() > 1*/ )
3719 int doneShapeIndex = -1;
3720 while ( doneShapeIndex+1 < _occgeom->facemeshstatus.Size() &&
3721 _occgeom->facemeshstatus[ doneShapeIndex+1 ])
3723 if ( doneShapeIndex+1 != _curShapeIndex )
3725 ((int&) _curShapeIndex) = doneShapeIndex+1;
3726 double doneShapeRate = _curShapeIndex / double( _occgeom->fmap.Extent() );
3727 double doneTime = edgeMeshingTime + doneShapeRate * faceMeshingTime;
3728 ((double&) _ticTime) = doneTime / _totalTime / _progressTic;
3729 // cout << "shape " << _curShapeIndex << " _ticTime " << _ticTime
3730 // << " " << doneTime / _totalTime / _progressTic << endl;
3734 else if ( !_optimize && _occgeom->somap.Extent() > 1 )
3736 int curShapeIndex = _curShapeIndex;
3737 if ( _ngMesh->GetNE() > 0 )
3739 netgen::Element el = (*_ngMesh)[netgen::ElementIndex( _ngMesh->GetNE()-1 )];
3740 curShapeIndex = el.GetIndex();
3742 if ( curShapeIndex != _curShapeIndex )
3744 ((int&) _curShapeIndex) = curShapeIndex;
3745 double doneShapeRate = _curShapeIndex / double( _occgeom->somap.Extent() );
3746 double doneTime = edgeFaceMeshingTime + doneShapeRate * voluMeshingTime;
3747 ((double&) _ticTime) = doneTime / _totalTime / _progressTic;
3748 // cout << "shape " << _curShapeIndex << " _ticTime " << _ticTime
3749 // << " " << doneTime / _totalTime / _progressTic << endl;
3754 progress = Max( *algoProgressTic * _ticTime, *algoProgress );
3759 netgen::multithread.task[0] == 'D'/*elaunay meshing*/ &&
3760 progress > voluMeshingTime )
3762 progress = voluMeshingTime;
3763 ((double&) _ticTime) = voluMeshingTime / _totalTime / _progressTic;
3765 ((int&) *algoProgressTic )++;
3766 ((double&) *algoProgress) = progress;
3768 //cout << progress << " " << *algoProgressTic << " " << netgen::multithread.task << " "<< _ticTime << endl;
3770 return Min( progress, 0.99 );
3773 //================================================================================
3775 * \brief Read mesh entities preventing successful computation from "test.out" file
3777 //================================================================================
3779 SMESH_ComputeErrorPtr
3780 NETGENPlugin_Mesher::ReadErrors(const vector<const SMDS_MeshNode* >& nodeVec)
3782 if ( nodeVec.size() < 2 ) return SMESH_ComputeErrorPtr();
3783 SMESH_BadInputElements* err =
3784 new SMESH_BadInputElements( nodeVec.back()->GetMesh(), COMPERR_BAD_INPUT_MESH,
3785 "Some edges multiple times in surface mesh");
3786 SMESH_File file("test.out");
3788 vector<int> three1(3), three2(3);
3789 const char* badEdgeStr = " multiple times in surface mesh";
3790 const int badEdgeStrLen = (int) strlen( badEdgeStr );
3791 const int nbNodes = (int) nodeVec.size();
3793 while( !file.eof() )
3795 if ( strncmp( file, "Edge ", 5 ) == 0 &&
3796 file.getInts( two ) &&
3797 strncmp( file, badEdgeStr, badEdgeStrLen ) == 0 &&
3798 two[0] < nbNodes && two[1] < nbNodes )
3800 err->myBadElements.push_back( new SMDS_LinearEdge( nodeVec[ two[0]], nodeVec[ two[1]] ));
3801 file += (int) badEdgeStrLen;
3803 else if ( strncmp( file, "Intersecting: ", 14 ) == 0 )
3806 // openelement 18 with open element 126
3810 const char* pos = file;
3811 bool ok = ( strncmp( file, "openelement ", 12 ) == 0 );
3812 ok = ok && file.getInts( two );
3813 ok = ok && file.getInts( three1 );
3814 ok = ok && file.getInts( three2 );
3815 for ( int i = 0; ok && i < 3; ++i )
3816 ok = ( three1[i] < nbNodes && nodeVec[ three1[i]]);
3817 for ( int i = 0; ok && i < 3; ++i )
3818 ok = ( three2[i] < nbNodes && nodeVec[ three2[i]]);
3821 err->myBadElements.push_back( new SMDS_FaceOfNodes( nodeVec[ three1[0]],
3822 nodeVec[ three1[1]],
3823 nodeVec[ three1[2]]));
3824 err->myBadElements.push_back( new SMDS_FaceOfNodes( nodeVec[ three2[0]],
3825 nodeVec[ three2[1]],
3826 nodeVec[ three2[2]]));
3827 err->myComment = "Intersecting triangles";
3841 size_t nbBadElems = err->myBadElements.size();
3842 if ( nbBadElems ) nbBadElems++; // avoid warning: variable set but not used
3845 return SMESH_ComputeErrorPtr( err );
3848 //================================================================================
3850 * \brief Write a python script creating an equivalent SALOME mesh.
3851 * This is useful to see what mesh is passed as input for the next step of mesh
3852 * generation (of mesh of higher dimension)
3854 //================================================================================
3856 void NETGENPlugin_Mesher::toPython( const netgen::Mesh* ngMesh )
3858 const char* pyFile = "/tmp/ngMesh.py";
3859 ofstream outfile( pyFile, ios::out );
3860 if ( !outfile ) return;
3862 outfile << "import salome, SMESH" << std::endl
3863 << "from salome.smesh import smeshBuilder" << std::endl
3864 << "smesh = smeshBuilder.New()" << std::endl
3865 << "mesh = smesh.Mesh()" << std::endl << std::endl;
3867 using namespace netgen;
3869 for (pi = PointIndex::BASE;
3870 pi < ngMesh->GetNP()+PointIndex::BASE; pi++)
3872 outfile << "mesh.AddNode( ";
3873 outfile << (*ngMesh)[pi](0) << ", ";
3874 outfile << (*ngMesh)[pi](1) << ", ";
3875 outfile << (*ngMesh)[pi](2) << ") ## "<< pi << std::endl;
3878 int nbDom = ngMesh->GetNDomains();
3879 for ( int i = 0; i < nbDom; ++i )
3880 outfile<< "grp" << i+1 << " = mesh.CreateEmptyGroup( SMESH.FACE, 'domain"<< i+1 << "')"<< std::endl;
3882 SurfaceElementIndex sei;
3883 for (sei = 0; sei < ngMesh->GetNSE(); sei++)
3885 outfile << "mesh.AddFace([ ";
3886 Element2d sel = (*ngMesh)[sei];
3887 for (int j = 0; j < sel.GetNP(); j++)
3888 outfile << sel[j] << ( j+1 < sel.GetNP() ? ", " : " ])");
3889 if ( sel.IsDeleted() ) outfile << " ## IsDeleted ";
3890 outfile << std::endl;
3892 if ((*ngMesh)[sei].GetIndex())
3894 if ( int dom1 = ngMesh->GetFaceDescriptor((*ngMesh)[sei].GetIndex ()).DomainIn())
3895 outfile << "grp"<< dom1 <<".Add([ " << (int)sei+1 << " ])" << std::endl;
3896 if ( int dom2 = ngMesh->GetFaceDescriptor((*ngMesh)[sei].GetIndex ()).DomainOut())
3897 outfile << "grp"<< dom2 <<".Add([ " << (int)sei+1 << " ])" << std::endl;
3901 for (ElementIndex ei = 0; ei < ngMesh->GetNE(); ei++)
3903 Element el = (*ngMesh)[ei];
3904 outfile << "mesh.AddVolume([ ";
3905 for (int j = 0; j < el.GetNP(); j++)
3906 outfile << el[j] << ( j+1 < el.GetNP() ? ", " : " ])");
3907 outfile << std::endl;
3910 for (int i = 1; i <= ngMesh->GetNSeg(); i++)
3912 const Segment & seg = ngMesh->LineSegment (i);
3913 outfile << "mesh.AddEdge([ "
3915 << seg[1] << " ])" << std::endl;
3917 std::cout << "Write " << pyFile << std::endl;
3920 //================================================================================
3922 * \brief Constructor of NETGENPlugin_ngMeshInfo
3924 //================================================================================
3926 NETGENPlugin_ngMeshInfo::NETGENPlugin_ngMeshInfo( netgen::Mesh* ngMesh,
3927 bool checkRemovedElems):
3928 _elementsRemoved( false ), _copyOfLocalH(0)
3932 _nbNodes = ngMesh->GetNP();
3933 _nbSegments = ngMesh->GetNSeg();
3934 _nbFaces = ngMesh->GetNSE();
3935 _nbVolumes = ngMesh->GetNE();
3937 if ( checkRemovedElems )
3938 for ( int i = 1; i <= ngMesh->GetNSE() && !_elementsRemoved; ++i )
3939 _elementsRemoved = ngMesh->SurfaceElement(i).IsDeleted();
3943 _nbNodes = _nbSegments = _nbFaces = _nbVolumes = 0;
3947 //================================================================================
3949 * \brief Copy LocalH member from one netgen mesh to another
3951 //================================================================================
3953 void NETGENPlugin_ngMeshInfo::transferLocalH( netgen::Mesh* fromMesh,
3954 netgen::Mesh* toMesh )
3956 if ( !fromMesh->LocalHFunctionGenerated() ) return;
3957 if ( !toMesh->LocalHFunctionGenerated() )
3958 NETGENPlugin_NetgenLibWrapper::CalcLocalH( toMesh );
3960 const size_t size = sizeof( netgen::LocalH );
3961 _copyOfLocalH = new char[ size ];
3962 memcpy( (void*)_copyOfLocalH, (void*)&toMesh->LocalHFunction(), size );
3963 memcpy( (void*)&toMesh->LocalHFunction(), (void*)&fromMesh->LocalHFunction(), size );
3966 //================================================================================
3968 * \brief Restore LocalH member of a netgen mesh
3970 //================================================================================
3972 void NETGENPlugin_ngMeshInfo::restoreLocalH( netgen::Mesh* toMesh )
3974 if ( _copyOfLocalH )
3976 const size_t size = sizeof( netgen::LocalH );
3977 memcpy( (void*)&toMesh->LocalHFunction(), (void*)_copyOfLocalH, size );
3978 delete [] _copyOfLocalH;
3983 //================================================================================
3985 * \brief Find "internal" sub-shapes
3987 //================================================================================
3989 NETGENPlugin_Internals::NETGENPlugin_Internals( SMESH_Mesh& mesh,
3990 const TopoDS_Shape& shape,
3992 : _mesh( mesh ), _is3D( is3D )
3994 SMESHDS_Mesh* meshDS = mesh.GetMeshDS();
3996 TopExp_Explorer f,e;
3997 for ( f.Init( shape, TopAbs_FACE ); f.More(); f.Next() )
3999 int faceID = meshDS->ShapeToIndex( f.Current() );
4001 // find not computed internal edges
4003 for ( e.Init( f.Current().Oriented(TopAbs_FORWARD), TopAbs_EDGE ); e.More(); e.Next() )
4004 if ( e.Current().Orientation() == TopAbs_INTERNAL )
4006 SMESH_subMesh* eSM = mesh.GetSubMesh( e.Current() );
4007 if ( eSM->IsEmpty() )
4009 _e2face.insert( make_pair( eSM->GetId(), faceID ));
4010 for ( TopoDS_Iterator v(e.Current()); v.More(); v.Next() )
4011 _e2face.insert( make_pair( meshDS->ShapeToIndex( v.Value() ), faceID ));
4015 // find internal vertices in a face
4016 set<int> intVV; // issue 0020850 where same vertex is twice in a face
4017 for ( TopoDS_Iterator fSub( f.Current() ); fSub.More(); fSub.Next())
4018 if ( fSub.Value().ShapeType() == TopAbs_VERTEX )
4020 int vID = meshDS->ShapeToIndex( fSub.Value() );
4021 if ( intVV.insert( vID ).second )
4022 _f2v[ faceID ].push_back( vID );
4027 // find internal faces and their subshapes where nodes are to be doubled
4028 // to make a crack with non-sewed borders
4030 if ( f.Current().Orientation() == TopAbs_INTERNAL )
4032 _intShapes.insert( meshDS->ShapeToIndex( f.Current() ));
4035 list< TopoDS_Shape > edges;
4036 for ( e.Init( f.Current(), TopAbs_EDGE ); e.More(); e.Next())
4037 if ( SMESH_MesherHelper::NbAncestors( e.Current(), mesh, TopAbs_FACE ) > 1 )
4039 _intShapes.insert( meshDS->ShapeToIndex( e.Current() ));
4040 edges.push_back( e.Current() );
4041 // find border faces
4042 PShapeIteratorPtr fIt =
4043 SMESH_MesherHelper::GetAncestors( edges.back(),mesh,TopAbs_FACE );
4044 while ( const TopoDS_Shape* pFace = fIt->next() )
4045 if ( !pFace->IsSame( f.Current() ))
4046 _borderFaces.insert( meshDS->ShapeToIndex( *pFace ));
4049 // we consider vertex internal if it is shared by more than one internal edge
4050 list< TopoDS_Shape >::iterator edge = edges.begin();
4051 for ( ; edge != edges.end(); ++edge )
4052 for ( TopoDS_Iterator v( *edge ); v.More(); v.Next() )
4054 set<int> internalEdges;
4055 PShapeIteratorPtr eIt =
4056 SMESH_MesherHelper::GetAncestors( v.Value(),mesh,TopAbs_EDGE );
4057 while ( const TopoDS_Shape* pEdge = eIt->next() )
4059 int edgeID = meshDS->ShapeToIndex( *pEdge );
4060 if ( isInternalShape( edgeID ))
4061 internalEdges.insert( edgeID );
4063 if ( internalEdges.size() > 1 )
4064 _intShapes.insert( meshDS->ShapeToIndex( v.Value() ));
4068 } // loop on geom faces
4070 // find vertices internal in solids
4073 for ( TopExp_Explorer so(shape, TopAbs_SOLID); so.More(); so.Next())
4075 int soID = meshDS->ShapeToIndex( so.Current() );
4076 for ( TopoDS_Iterator soSub( so.Current() ); soSub.More(); soSub.Next())
4077 if ( soSub.Value().ShapeType() == TopAbs_VERTEX )
4078 _s2v[ soID ].push_back( meshDS->ShapeToIndex( soSub.Value() ));
4083 //================================================================================
4085 * \brief Find mesh faces on non-internal geom faces sharing internal edge
4086 * some nodes of which are to be doubled to make the second border of the "crack"
4088 //================================================================================
4090 void NETGENPlugin_Internals::findBorderElements( TIDSortedElemSet & borderElems )
4092 if ( _intShapes.empty() ) return;
4094 SMESH_Mesh& mesh = const_cast<SMESH_Mesh&>(_mesh);
4095 SMESHDS_Mesh* meshDS = mesh.GetMeshDS();
4097 // loop on internal geom edges
4098 set<int>::const_iterator intShapeId = _intShapes.begin();
4099 for ( ; intShapeId != _intShapes.end(); ++intShapeId )
4101 const TopoDS_Shape& s = meshDS->IndexToShape( *intShapeId );
4102 if ( s.ShapeType() != TopAbs_EDGE ) continue;
4104 // get internal and non-internal geom faces sharing the internal edge <s>
4106 set<int>::iterator bordFace = _borderFaces.end();
4107 PShapeIteratorPtr faces = SMESH_MesherHelper::GetAncestors( s, _mesh, TopAbs_FACE );
4108 while ( const TopoDS_Shape* pFace = faces->next() )
4110 int faceID = meshDS->ShapeToIndex( *pFace );
4111 if ( isInternalShape( faceID ))
4114 bordFace = _borderFaces.insert( faceID ).first;
4116 if ( bordFace == _borderFaces.end() || !intFace ) continue;
4118 // get all links of mesh faces on internal geom face sharing nodes on edge <s>
4119 set< SMESH_OrientedLink > links; //!< links of faces on internal geom face
4120 list<const SMDS_MeshElement*> suspectFaces[2]; //!< mesh faces on border geom faces
4121 int nbSuspectFaces = 0;
4122 SMESHDS_SubMesh* intFaceSM = meshDS->MeshElements( intFace );
4123 if ( !intFaceSM || intFaceSM->NbElements() == 0 ) continue;
4124 SMESH_subMeshIteratorPtr smIt = mesh.GetSubMesh( s )->getDependsOnIterator(true,true);
4125 while ( smIt->more() )
4127 SMESHDS_SubMesh* sm = smIt->next()->GetSubMeshDS();
4128 if ( !sm ) continue;
4129 SMDS_NodeIteratorPtr nIt = sm->GetNodes();
4130 while ( nIt->more() )
4132 const SMDS_MeshNode* nOnEdge = nIt->next();
4133 SMDS_ElemIteratorPtr fIt = nOnEdge->GetInverseElementIterator(SMDSAbs_Face);
4134 while ( fIt->more() )
4136 const SMDS_MeshElement* f = fIt->next();
4137 const int nbNodes = f->NbCornerNodes();
4138 if ( intFaceSM->Contains( f ))
4140 for ( int i = 0; i < nbNodes; ++i )
4141 links.insert( SMESH_OrientedLink( f->GetNode(i), f->GetNode((i+1)%nbNodes)));
4146 for ( int i = 0; i < nbNodes; ++i )
4147 nbDblNodes += isInternalShape( f->GetNode(i)->GetShapeID() );
4149 suspectFaces[ nbDblNodes < 2 ].push_back( f );
4155 // suspectFaces[0] having link with same orientation as mesh faces on
4156 // the internal geom face are <borderElems>. suspectFaces[1] have
4157 // only one node on edge <s>, we decide on them later (at the 2nd loop)
4158 // by links of <borderElems> found at the 1st and 2nd loops
4159 set< SMESH_OrientedLink > borderLinks;
4160 for ( int isPostponed = 0; isPostponed < 2; ++isPostponed )
4162 list<const SMDS_MeshElement*>::iterator fIt = suspectFaces[isPostponed].begin();
4163 for ( int nbF = 0; fIt != suspectFaces[isPostponed].end(); ++fIt, ++nbF )
4165 const SMDS_MeshElement* f = *fIt;
4166 bool isBorder = false, linkFound = false, borderLinkFound = false;
4167 list< SMESH_OrientedLink > faceLinks;
4168 int nbNodes = f->NbCornerNodes();
4169 for ( int i = 0; i < nbNodes; ++i )
4171 SMESH_OrientedLink link( f->GetNode(i), f->GetNode((i+1)%nbNodes));
4172 faceLinks.push_back( link );
4175 set< SMESH_OrientedLink >::iterator foundLink = links.find( link );
4176 if ( foundLink != links.end() )
4179 isBorder = ( foundLink->_reversed == link._reversed );
4180 if ( !isBorder && !isPostponed ) break;
4181 faceLinks.pop_back();
4183 else if ( isPostponed && !borderLinkFound )
4185 foundLink = borderLinks.find( link );
4186 if ( foundLink != borderLinks.end() )
4188 borderLinkFound = true;
4189 isBorder = ( foundLink->_reversed != link._reversed );
4196 borderElems.insert( f );
4197 borderLinks.insert( faceLinks.begin(), faceLinks.end() );
4199 else if ( !linkFound && !borderLinkFound )
4201 suspectFaces[1].push_back( f );
4202 if ( nbF > 2 * nbSuspectFaces )
4203 break; // dead loop protection
4210 //================================================================================
4212 * \brief put internal shapes in maps and fill in submeshes to precompute
4214 //================================================================================
4216 void NETGENPlugin_Internals::getInternalEdges( TopTools_IndexedMapOfShape& fmap,
4217 TopTools_IndexedMapOfShape& emap,
4218 TopTools_IndexedMapOfShape& vmap,
4219 list< SMESH_subMesh* > smToPrecompute[])
4221 if ( !hasInternalEdges() ) return;
4222 map<int,int>::const_iterator ev_face = _e2face.begin();
4223 for ( ; ev_face != _e2face.end(); ++ev_face )
4225 const TopoDS_Shape& ev = _mesh.GetMeshDS()->IndexToShape( ev_face->first );
4226 const TopoDS_Shape& face = _mesh.GetMeshDS()->IndexToShape( ev_face->second );
4228 ( ev.ShapeType() == TopAbs_EDGE ? emap : vmap ).Add( ev );
4230 //cout<<"INTERNAL EDGE or VERTEX "<<ev_face->first<<" on face "<<ev_face->second<<endl;
4232 smToPrecompute[ MeshDim_1D ].push_back( _mesh.GetSubMeshContaining( ev_face->first ));
4236 //================================================================================
4238 * \brief return shapes and submeshes to be meshed and already meshed boundary submeshes
4240 //================================================================================
4242 void NETGENPlugin_Internals::getInternalFaces( TopTools_IndexedMapOfShape& fmap,
4243 TopTools_IndexedMapOfShape& emap,
4244 list< SMESH_subMesh* >& intFaceSM,
4245 list< SMESH_subMesh* >& boundarySM)
4247 if ( !hasInternalFaces() ) return;
4249 // <fmap> and <emap> are for not yet meshed shapes
4250 // <intFaceSM> is for submeshes of faces
4251 // <boundarySM> is for meshed edges and vertices
4256 set<int> shapeIDs ( _intShapes );
4257 if ( !_borderFaces.empty() )
4258 shapeIDs.insert( _borderFaces.begin(), _borderFaces.end() );
4260 set<int>::const_iterator intS = shapeIDs.begin();
4261 for ( ; intS != shapeIDs.end(); ++intS )
4263 SMESH_subMesh* sm = _mesh.GetSubMeshContaining( *intS );
4265 if ( sm->GetSubShape().ShapeType() != TopAbs_FACE ) continue;
4267 intFaceSM.push_back( sm );
4269 // add submeshes of not computed internal faces
4270 if ( !sm->IsEmpty() ) continue;
4272 SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(true,true);
4273 while ( smIt->more() )
4276 const TopoDS_Shape& s = sm->GetSubShape();
4278 if ( sm->IsEmpty() )
4281 switch ( s.ShapeType() ) {
4282 case TopAbs_FACE: fmap.Add ( s ); break;
4283 case TopAbs_EDGE: emap.Add ( s ); break;
4289 if ( s.ShapeType() != TopAbs_FACE )
4290 boundarySM.push_back( sm );
4296 //================================================================================
4298 * \brief Return true if given shape is to be precomputed in order to be correctly
4299 * added to netgen mesh
4301 //================================================================================
4303 bool NETGENPlugin_Internals::isShapeToPrecompute(const TopoDS_Shape& s)
4305 int shapeID = _mesh.GetMeshDS()->ShapeToIndex( s );
4306 switch ( s.ShapeType() ) {
4307 case TopAbs_FACE : break; //return isInternalShape( shapeID ) || isBorderFace( shapeID );
4308 case TopAbs_EDGE : return isInternalEdge( shapeID );
4309 case TopAbs_VERTEX: break;
4315 //================================================================================
4317 * \brief Return SMESH
4319 //================================================================================
4321 SMESH_Mesh& NETGENPlugin_Internals::getMesh() const
4323 return const_cast<SMESH_Mesh&>( _mesh );
4326 //================================================================================
4328 * \brief Access to a counter of NETGENPlugin_NetgenLibWrapper instances
4330 //================================================================================
4332 int& NETGENPlugin_NetgenLibWrapper::instanceCounter()
4334 static int theCouner = 0;
4338 //================================================================================
4340 * \brief Initialize netgen library
4342 //================================================================================
4344 NETGENPlugin_NetgenLibWrapper::NETGENPlugin_NetgenLibWrapper():
4347 if ( instanceCounter() == 0 )
4350 if ( !netgen::testout )
4351 netgen::testout = new ofstream( "test.out" );
4354 ++instanceCounter();
4356 _isComputeOk = false;
4360 if ( !getenv( "KEEP_NETGEN_OUTPUT" ))
4362 // redirect all netgen output (mycout,myerr,cout) to _outputFileName
4363 _outputFileName = getOutputFileName();
4364 _ngcout = netgen::mycout;
4365 _ngcerr = netgen::myerr;
4366 netgen::mycout = new ofstream ( _outputFileName.c_str() );
4367 netgen::myerr = netgen::mycout;
4368 _coutBuffer = std::cout.rdbuf();
4370 std::cout << "NOTE: netgen output is redirected to file " << _outputFileName << std::endl;
4372 std::cout.rdbuf( netgen::mycout->rdbuf() );
4376 setMesh( Ng_NewMesh() );
4379 //================================================================================
4381 * \brief Finish using netgen library
4383 //================================================================================
4385 NETGENPlugin_NetgenLibWrapper::~NETGENPlugin_NetgenLibWrapper()
4387 --instanceCounter();
4389 Ng_DeleteMesh( ngMesh() );
4393 std::cout.rdbuf( _coutBuffer );
4400 //================================================================================
4402 * \brief Set netgen mesh to delete at destruction
4404 //================================================================================
4406 void NETGENPlugin_NetgenLibWrapper::setMesh( Ng_Mesh* mesh )
4409 Ng_DeleteMesh( ngMesh() );
4410 _ngMesh = (netgen::Mesh*) mesh;
4413 //================================================================================
4415 * \brief Perform a step of mesh generation
4416 * \param [inout] occgeo - geometry to mesh
4417 * \param [inout] startWith - start step
4418 * \param [inout] endWith - end step
4419 * \param [inout] ngMesh - netgen mesh
4420 * \return int - is error
4422 //================================================================================
4424 int NETGENPlugin_NetgenLibWrapper::GenerateMesh( netgen::OCCGeometry& occgeo,
4425 int startWith, int endWith,
4426 netgen::Mesh* & ngMesh )
4432 ngMesh = new netgen::Mesh;
4433 ngMesh->SetGeometry( shared_ptr<netgen::NetgenGeometry>( &occgeo, &NOOP_Deleter ));
4435 netgen::mparam.perfstepsstart = startWith;
4436 netgen::mparam.perfstepsend = endWith;
4437 std::shared_ptr<netgen::Mesh> meshPtr( ngMesh, &NOOP_Deleter );
4438 err = occgeo.GenerateMesh( meshPtr, netgen::mparam );
4443 err = netgen::OCCGenerateMesh(occgeo, ngMesh, netgen::mparam, startWith, endWith);
4448 err = netgen::OCCGenerateMesh(occgeo, ngMesh, startWith, endWith, optstr);
4455 //================================================================================
4457 * \brief Create a mesh size tree
4459 //================================================================================
4461 void NETGENPlugin_NetgenLibWrapper::CalcLocalH( netgen::Mesh * ngMesh )
4463 #if defined( NETGEN_V5 ) || defined( NETGEN_V6 )
4464 ngMesh->CalcLocalH(netgen::mparam.grading);
4466 ngMesh->CalcLocalH();
4470 //================================================================================
4472 * \brief Return a unique file name
4474 //================================================================================
4476 std::string NETGENPlugin_NetgenLibWrapper::getOutputFileName()
4478 std::string aTmpDir = SALOMEDS_Tool::GetTmpDir();
4480 TCollection_AsciiString aGenericName = aTmpDir.c_str();
4481 aGenericName += "NETGEN_";
4483 aGenericName += getpid();
4485 aGenericName += _getpid();
4487 aGenericName += "_";
4488 aGenericName += Abs((Standard_Integer)(long) aGenericName.ToCString());
4489 aGenericName += ".out";
4491 return aGenericName.ToCString();
4494 //================================================================================
4496 * \brief Remove "test.out" and "problemfaces" files in current directory
4498 //================================================================================
4500 void NETGENPlugin_NetgenLibWrapper::RemoveTmpFiles()
4502 bool rm = SMESH_File("test.out").remove() ;
4504 if ( rm && netgen::testout && instanceCounter() == 0 )
4506 delete netgen::testout;
4507 netgen::testout = 0;
4510 SMESH_File("problemfaces").remove();
4511 SMESH_File("occmesh.rep").remove();
4514 //================================================================================
4516 * \brief Remove file with netgen output
4518 //================================================================================
4520 void NETGENPlugin_NetgenLibWrapper::removeOutputFile()
4522 if ( !_outputFileName.empty() )
4526 delete netgen::mycout;
4527 netgen::mycout = _ngcout;
4528 netgen::myerr = _ngcerr;
4531 string tmpDir = SALOMEDS_Tool::GetDirFromPath ( _outputFileName );
4532 string aFileName = SALOMEDS_Tool::GetNameFromPath( _outputFileName ) + ".out";
4533 SALOMEDS_Tool::ListOfFiles aFiles;
4535 aFiles.push_back(aFileName.c_str());
4537 SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.c_str(), aFiles, true );