1 // Copyright (C) 2007-2016 CEA/DEN, EDF R&D, OPEN CASCADE
3 // Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License, or (at your option) any later version.
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 // Lesser General Public License for more details.
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
23 // NETGENPlugin : C++ implementation
24 // File : NETGENPlugin_Mesher.cxx
25 // Author : Michael Sazonov (OCN)
28 //=============================================================================
30 #include "NETGENPlugin_Mesher.hxx"
31 #include "NETGENPlugin_Hypothesis_2D.hxx"
32 #include "NETGENPlugin_SimpleHypothesis_3D.hxx"
34 #include <SMDS_FaceOfNodes.hxx>
35 #include <SMDS_MeshElement.hxx>
36 #include <SMDS_MeshNode.hxx>
37 #include <SMESHDS_Mesh.hxx>
38 #include <SMESH_Block.hxx>
39 #include <SMESH_Comment.hxx>
40 #include <SMESH_ComputeError.hxx>
41 #include <SMESH_File.hxx>
42 #include <SMESH_Gen_i.hxx>
43 #include <SMESH_Mesh.hxx>
44 #include <SMESH_MesherHelper.hxx>
45 #include <SMESH_subMesh.hxx>
46 #include <StdMeshers_QuadToTriaAdaptor.hxx>
47 #include <StdMeshers_ViscousLayers2D.hxx>
49 #include <SALOMEDS_Tool.hxx>
51 #include <utilities.h>
53 #include <BRepBuilderAPI_Copy.hxx>
54 #include <BRep_Tool.hxx>
55 #include <Bnd_B3d.hxx>
56 #include <NCollection_Map.hxx>
57 #include <Standard_ErrorHandler.hxx>
58 #include <Standard_ProgramError.hxx>
59 #include <TColStd_MapOfInteger.hxx>
61 #include <TopExp_Explorer.hxx>
62 #include <TopTools_DataMapIteratorOfDataMapOfShapeInteger.hxx>
63 #include <TopTools_DataMapIteratorOfDataMapOfShapeShape.hxx>
64 #include <TopTools_DataMapOfShapeInteger.hxx>
65 #include <TopTools_DataMapOfShapeShape.hxx>
66 #include <TopTools_MapOfShape.hxx>
69 // Netgen include files
73 #include <occgeom.hpp>
74 #include <meshing.hpp>
75 //#include <ngexception.hpp>
78 extern int OCCGenerateMesh (OCCGeometry&, Mesh*&, MeshingParameters&, int, int);
80 extern int OCCGenerateMesh (OCCGeometry&, Mesh*&, int, int, char*);
82 //extern void OCCSetLocalMeshSize(OCCGeometry & geom, Mesh & mesh);
83 extern MeshingParameters mparam;
84 extern volatile multithreadt multithread;
85 extern bool merge_solids;
87 // values used for occgeo.facemeshstatus
88 enum EFaceMeshStatus { FACE_NOT_TREATED = 0,
100 using namespace nglib;
104 #define nodeVec_ACCESS(index) ((SMDS_MeshNode*) nodeVec.at((index)))
106 #define nodeVec_ACCESS(index) ((SMDS_MeshNode*) nodeVec[index])
109 #define NGPOINT_COORDS(p) p(0),p(1),p(2)
112 // dump elements added to ng mesh
113 //#define DUMP_SEGMENTS
114 //#define DUMP_TRIANGLES
115 //#define DUMP_TRIANGLES_SCRIPT "/tmp/trias.py" //!< debug AddIntVerticesInSolids()
118 TopTools_IndexedMapOfShape ShapesWithLocalSize;
119 std::map<int,double> VertexId2LocalSize;
120 std::map<int,double> EdgeId2LocalSize;
121 std::map<int,double> FaceId2LocalSize;
123 //=============================================================================
127 //=============================================================================
129 NETGENPlugin_Mesher::NETGENPlugin_Mesher (SMESH_Mesh* mesh,
130 const TopoDS_Shape& aShape,
136 _fineness(NETGENPlugin_Hypothesis::GetDefaultFineness()),
137 _isViscousLayers2D(false),
146 SetDefaultParameters();
147 ShapesWithLocalSize.Clear();
148 VertexId2LocalSize.clear();
149 EdgeId2LocalSize.clear();
150 FaceId2LocalSize.clear();
153 //================================================================================
157 //================================================================================
159 NETGENPlugin_Mesher::~NETGENPlugin_Mesher()
167 //================================================================================
169 * Set pointer to NETGENPlugin_Mesher* field of the holder, that will be
170 * nullified at destruction of this
172 //================================================================================
174 void NETGENPlugin_Mesher::SetSelfPointer( NETGENPlugin_Mesher ** ptr )
185 //================================================================================
187 * \brief Initialize global NETGEN parameters with default values
189 //================================================================================
191 void NETGENPlugin_Mesher::SetDefaultParameters()
193 netgen::MeshingParameters& mparams = netgen::mparam;
194 // maximal mesh edge size
195 mparams.maxh = 0;//NETGENPlugin_Hypothesis::GetDefaultMaxSize();
197 // minimal number of segments per edge
198 mparams.segmentsperedge = NETGENPlugin_Hypothesis::GetDefaultNbSegPerEdge();
199 // rate of growth of size between elements
200 mparams.grading = NETGENPlugin_Hypothesis::GetDefaultGrowthRate();
201 // safety factor for curvatures (elements per radius)
202 mparams.curvaturesafety = NETGENPlugin_Hypothesis::GetDefaultNbSegPerRadius();
203 // create elements of second order
204 mparams.secondorder = NETGENPlugin_Hypothesis::GetDefaultSecondOrder();
205 // quad-dominated surface meshing
209 mparams.quad = NETGENPlugin_Hypothesis_2D::GetDefaultQuadAllowed();
210 _fineness = NETGENPlugin_Hypothesis::GetDefaultFineness();
211 mparams.uselocalh = NETGENPlugin_Hypothesis::GetDefaultSurfaceCurvature();
212 netgen::merge_solids = NETGENPlugin_Hypothesis::GetDefaultFuseEdges();
215 //=============================================================================
219 //=============================================================================
221 void SetLocalSize(TopoDS_Shape GeomShape, double LocalSize)
223 if ( GeomShape.IsNull() ) return;
224 TopAbs_ShapeEnum GeomType = GeomShape.ShapeType();
225 if (GeomType == TopAbs_COMPOUND) {
226 for (TopoDS_Iterator it (GeomShape); it.More(); it.Next()) {
227 SetLocalSize(it.Value(), LocalSize);
232 if (! ShapesWithLocalSize.Contains(GeomShape))
233 key = ShapesWithLocalSize.Add(GeomShape);
235 key = ShapesWithLocalSize.FindIndex(GeomShape);
236 if (GeomType == TopAbs_VERTEX) {
237 VertexId2LocalSize[key] = LocalSize;
238 } else if (GeomType == TopAbs_EDGE) {
239 EdgeId2LocalSize[key] = LocalSize;
240 } else if (GeomType == TopAbs_FACE) {
241 FaceId2LocalSize[key] = LocalSize;
245 //=============================================================================
247 * Pass parameters to NETGEN
249 //=============================================================================
250 void NETGENPlugin_Mesher::SetParameters(const NETGENPlugin_Hypothesis* hyp)
254 netgen::MeshingParameters& mparams = netgen::mparam;
255 // Initialize global NETGEN parameters:
256 // maximal mesh segment size
257 mparams.maxh = hyp->GetMaxSize();
258 // maximal mesh element linear size
259 mparams.minh = hyp->GetMinSize();
260 // minimal number of segments per edge
261 mparams.segmentsperedge = hyp->GetNbSegPerEdge();
262 // rate of growth of size between elements
263 mparams.grading = hyp->GetGrowthRate();
264 // safety factor for curvatures (elements per radius)
265 mparams.curvaturesafety = hyp->GetNbSegPerRadius();
266 // create elements of second order
267 mparams.secondorder = hyp->GetSecondOrder() ? 1 : 0;
268 // quad-dominated surface meshing
269 mparams.quad = hyp->GetQuadAllowed() ? 1 : 0;
270 _optimize = hyp->GetOptimize();
271 _fineness = hyp->GetFineness();
272 mparams.uselocalh = hyp->GetSurfaceCurvature();
273 netgen::merge_solids = hyp->GetFuseEdges();
276 SMESH_Gen_i* smeshGen_i = SMESH_Gen_i::GetSMESHGen();
277 CORBA::Object_var anObject = smeshGen_i->GetNS()->Resolve("/myStudyManager");
278 SALOMEDS::StudyManager_var aStudyMgr = SALOMEDS::StudyManager::_narrow(anObject);
279 SALOMEDS::Study_var myStudy = aStudyMgr->GetStudyByID(hyp->GetStudyId());
281 const NETGENPlugin_Hypothesis::TLocalSize localSizes = hyp->GetLocalSizesAndEntries();
282 NETGENPlugin_Hypothesis::TLocalSize::const_iterator it = localSizes.begin();
283 for ( ; it != localSizes.end() ; it++)
285 std::string entry = (*it).first;
286 double val = (*it).second;
288 GEOM::GEOM_Object_var aGeomObj;
289 SALOMEDS::SObject_var aSObj = myStudy->FindObjectID( entry.c_str() );
290 if ( !aSObj->_is_nil() ) {
291 CORBA::Object_var obj = aSObj->GetObject();
292 aGeomObj = GEOM::GEOM_Object::_narrow(obj);
295 TopoDS_Shape S = smeshGen_i->GeomObjectToShape( aGeomObj.in() );
296 SetLocalSize(S, val);
301 //=============================================================================
303 * Pass simple parameters to NETGEN
305 //=============================================================================
307 void NETGENPlugin_Mesher::SetParameters(const NETGENPlugin_SimpleHypothesis_2D* hyp)
311 SetDefaultParameters();
314 //=============================================================================
316 * Link - a pair of integer numbers
318 //=============================================================================
322 Link(int _n1, int _n2) : n1(_n1), n2(_n2) {}
323 Link() : n1(0), n2(0) {}
324 bool Contains( int n ) const { return n == n1 || n == n2; }
325 bool IsConnected( const Link& other ) const
327 return (( Contains( other.n1 ) || Contains( other.n2 )) && ( this != &other ));
331 int HashCode(const Link& aLink, int aLimit)
333 return HashCode(aLink.n1 + aLink.n2, aLimit);
336 Standard_Boolean IsEqual(const Link& aLink1, const Link& aLink2)
338 return (( aLink1.n1 == aLink2.n1 && aLink1.n2 == aLink2.n2 ) ||
339 ( aLink1.n1 == aLink2.n2 && aLink1.n2 == aLink2.n1 ));
344 //================================================================================
346 * \brief return id of netgen point corresponding to SMDS node
348 //================================================================================
349 typedef map< const SMDS_MeshNode*, int > TNode2IdMap;
351 int ngNodeId( const SMDS_MeshNode* node,
352 netgen::Mesh& ngMesh,
353 TNode2IdMap& nodeNgIdMap)
355 int newNgId = ngMesh.GetNP() + 1;
357 TNode2IdMap::iterator node_id = nodeNgIdMap.insert( make_pair( node, newNgId )).first;
359 if ( node_id->second == newNgId)
361 #if defined(DUMP_SEGMENTS) || defined(DUMP_TRIANGLES)
362 cout << "Ng " << newNgId << " - " << node;
364 netgen::MeshPoint p( netgen::Point<3> (node->X(), node->Y(), node->Z()) );
365 ngMesh.AddPoint( p );
367 return node_id->second;
370 //================================================================================
372 * \brief Return computed EDGEs connected to the given one
374 //================================================================================
376 list< TopoDS_Edge > getConnectedEdges( const TopoDS_Edge& edge,
377 const TopoDS_Face& face,
378 const set< SMESH_subMesh* > & computedSM,
379 const SMESH_MesherHelper& helper,
380 map< SMESH_subMesh*, set< int > >& addedEdgeSM2Faces)
383 list< TopoDS_Edge > edges;
384 list< int > nbEdgesInWire;
385 /*int nbWires =*/ SMESH_Block::GetOrderedEdges( face, edges, nbEdgesInWire);
387 // find <edge> within <edges>
388 list< TopoDS_Edge >::iterator eItFwd = edges.begin();
389 for ( ; eItFwd != edges.end(); ++eItFwd )
390 if ( edge.IsSame( *eItFwd ))
392 if ( eItFwd == edges.end()) return list< TopoDS_Edge>();
394 if ( eItFwd->Orientation() >= TopAbs_INTERNAL )
396 // connected INTERNAL edges returned from GetOrderedEdges() are wrongly oriented
397 // so treat each INTERNAL edge separately
398 TopoDS_Edge e = *eItFwd;
400 edges.push_back( e );
404 // get all computed EDGEs connected to <edge>
406 list< TopoDS_Edge >::iterator eItBack = eItFwd, ePrev;
407 TopoDS_Vertex vCommon;
408 TopTools_MapOfShape eAdded; // map used not to add a seam edge twice to <edges>
411 // put edges before <edge> to <edges> back
412 while ( edges.begin() != eItFwd )
413 edges.splice( edges.end(), edges, edges.begin() );
417 while ( ++eItFwd != edges.end() )
419 SMESH_subMesh* sm = helper.GetMesh()->GetSubMesh( *eItFwd );
421 bool connected = TopExp::CommonVertex( *ePrev, *eItFwd, vCommon );
422 bool computed = sm->IsMeshComputed();
423 bool added = addedEdgeSM2Faces[ sm ].count( helper.GetSubShapeID() );
424 bool doubled = !eAdded.Add( *eItFwd );
425 bool orientOK = (( ePrev ->Orientation() < TopAbs_INTERNAL ) ==
426 ( eItFwd->Orientation() < TopAbs_INTERNAL ) );
427 if ( !connected || !computed || !orientOK || added || doubled )
429 // stop advancement; move edges from tail to head
430 while ( edges.back() != *ePrev )
431 edges.splice( edges.begin(), edges, --edges.end() );
437 while ( eItBack != edges.begin() )
441 SMESH_subMesh* sm = helper.GetMesh()->GetSubMesh( *eItBack );
443 bool connected = TopExp::CommonVertex( *ePrev, *eItBack, vCommon );
444 bool computed = sm->IsMeshComputed();
445 bool added = addedEdgeSM2Faces[ sm ].count( helper.GetSubShapeID() );
446 bool doubled = !eAdded.Add( *eItBack );
447 bool orientOK = (( ePrev ->Orientation() < TopAbs_INTERNAL ) ==
448 ( eItBack->Orientation() < TopAbs_INTERNAL ) );
449 if ( !connected || !computed || !orientOK || added || doubled)
452 edges.erase( edges.begin(), ePrev );
456 if ( edges.front() != edges.back() )
458 // assure that the 1st vertex is meshed
459 TopoDS_Edge eLast = edges.back();
460 while ( !SMESH_Algo::VertexNode( SMESH_MesherHelper::IthVertex( 0, edges.front()), helper.GetMeshDS())
462 edges.front() != eLast )
463 edges.splice( edges.end(), edges, edges.begin() );
468 //================================================================================
470 * \brief Make triangulation of a shape precise enough
472 //================================================================================
474 void updateTriangulation( const TopoDS_Shape& shape )
476 // static set< Poly_Triangulation* > updated;
478 // TopLoc_Location loc;
479 // TopExp_Explorer fExp( shape, TopAbs_FACE );
480 // for ( ; fExp.More(); fExp.Next() )
482 // Handle(Poly_Triangulation) triangulation =
483 // BRep_Tool::Triangulation ( TopoDS::Face( fExp.Current() ), loc);
484 // if ( triangulation.IsNull() ||
485 // updated.insert( triangulation.operator->() ).second )
487 // BRepTools::Clean (shape);
490 BRepMesh_IncrementalMesh e(shape, 0.01, true);
492 catch (Standard_Failure)
495 // updated.erase( triangulation.operator->() );
496 // triangulation = BRep_Tool::Triangulation ( TopoDS::Face( fExp.Current() ), loc);
497 // updated.insert( triangulation.operator->() );
501 //================================================================================
503 * \brief Returns a medium node either existing in SMESH of created by NETGEN
504 * \param [in] corner1 - corner node 1
505 * \param [in] corner2 - corner node 2
506 * \param [in] defaultMedium - the node created by NETGEN
507 * \param [in] helper - holder of medium nodes existing in SMESH
508 * \return const SMDS_MeshNode* - the result node
510 //================================================================================
512 const SMDS_MeshNode* mediumNode( const SMDS_MeshNode* corner1,
513 const SMDS_MeshNode* corner2,
514 const SMDS_MeshNode* defaultMedium,
515 const SMESH_MesherHelper* helper)
519 TLinkNodeMap::const_iterator l2n =
520 helper->GetTLinkNodeMap().find( SMESH_TLink( corner1, corner2 ));
521 if ( l2n != helper->GetTLinkNodeMap().end() )
522 defaultMedium = l2n->second;
524 return defaultMedium;
527 //================================================================================
529 * \brief Assure that mesh on given shapes is quadratic
531 //================================================================================
533 void makeQuadratic( const TopTools_IndexedMapOfShape& shapes,
536 for ( int i = 1; i <= shapes.Extent(); ++i )
538 SMESHDS_SubMesh* smDS = mesh->GetMeshDS()->MeshElements( shapes(i) );
539 if ( !smDS ) continue;
540 SMDS_ElemIteratorPtr elemIt = smDS->GetElements();
541 if ( !elemIt->more() ) continue;
542 const SMDS_MeshElement* e = elemIt->next();
543 if ( !e || e->IsQuadratic() )
546 TIDSortedElemSet elems;
548 while ( elemIt->more() )
549 elems.insert( elems.end(), elemIt->next() );
551 SMESH_MeshEditor( mesh ).ConvertToQuadratic( /*3d=*/false, elems, /*biQuad=*/false );
557 //================================================================================
559 * \brief Initialize netgen::OCCGeometry with OCCT shape
561 //================================================================================
563 void NETGENPlugin_Mesher::PrepareOCCgeometry(netgen::OCCGeometry& occgeo,
564 const TopoDS_Shape& shape,
566 list< SMESH_subMesh* > * meshedSM,
567 NETGENPlugin_Internals* intern)
569 updateTriangulation( shape );
572 BRepBndLib::Add (shape, bb);
573 double x1,y1,z1,x2,y2,z2;
574 bb.Get (x1,y1,z1,x2,y2,z2);
575 MESSAGE("shape bounding box:\n" <<
576 "(" << x1 << " " << y1 << " " << z1 << ") " <<
577 "(" << x2 << " " << y2 << " " << z2 << ")");
578 netgen::Point<3> p1 = netgen::Point<3> (x1,y1,z1);
579 netgen::Point<3> p2 = netgen::Point<3> (x2,y2,z2);
580 occgeo.boundingbox = netgen::Box<3> (p1,p2);
582 occgeo.shape = shape;
585 // fill maps of shapes of occgeo with not yet meshed subshapes
587 // get root submeshes
588 list< SMESH_subMesh* > rootSM;
589 const int shapeID = mesh.GetMeshDS()->ShapeToIndex( shape );
590 if ( shapeID > 0 ) { // SMESH_subMesh with ID 0 may exist, don't use it!
591 rootSM.push_back( mesh.GetSubMesh( shape ));
594 for ( TopoDS_Iterator it( shape ); it.More(); it.Next() )
595 rootSM.push_back( mesh.GetSubMesh( it.Value() ));
600 // add subshapes of empty submeshes
601 list< SMESH_subMesh* >::iterator rootIt = rootSM.begin(), rootEnd = rootSM.end();
602 for ( ; rootIt != rootEnd; ++rootIt ) {
603 SMESH_subMesh * root = *rootIt;
604 SMESH_subMeshIteratorPtr smIt = root->getDependsOnIterator(/*includeSelf=*/true,
605 /*complexShapeFirst=*/true);
606 // to find a right orientation of subshapes (PAL20462)
607 TopTools_IndexedMapOfShape subShapes;
608 TopExp::MapShapes(root->GetSubShape(), subShapes);
609 while ( smIt->more() )
611 SMESH_subMesh* sm = smIt->next();
612 TopoDS_Shape shape = sm->GetSubShape();
613 totNbFaces += ( shape.ShapeType() == TopAbs_FACE );
614 if ( intern && intern->isShapeToPrecompute( shape ))
616 if ( !meshedSM || sm->IsEmpty() )
618 if ( shape.ShapeType() != TopAbs_VERTEX )
619 shape = subShapes( subShapes.FindIndex( shape ));// shape -> index -> oriented shape
620 if ( shape.Orientation() >= TopAbs_INTERNAL )
621 shape.Orientation( TopAbs_FORWARD ); // isuue 0020676
622 switch ( shape.ShapeType() ) {
623 case TopAbs_FACE : occgeo.fmap.Add( shape ); break;
624 case TopAbs_EDGE : occgeo.emap.Add( shape ); break;
625 case TopAbs_VERTEX: occgeo.vmap.Add( shape ); break;
626 case TopAbs_SOLID :occgeo.somap.Add( shape ); break;
630 // collect submeshes of meshed shapes
633 const int dim = SMESH_Gen::GetShapeDim( shape );
634 meshedSM[ dim ].push_back( sm );
638 occgeo.facemeshstatus.SetSize (totNbFaces);
639 occgeo.facemeshstatus = 0;
640 occgeo.face_maxh_modified.SetSize(totNbFaces);
641 occgeo.face_maxh_modified = 0;
642 occgeo.face_maxh.SetSize(totNbFaces);
643 occgeo.face_maxh = netgen::mparam.maxh;
646 //================================================================================
648 * \brief Return a default min size value suitable for the given geometry.
650 //================================================================================
652 double NETGENPlugin_Mesher::GetDefaultMinSize(const TopoDS_Shape& geom,
653 const double maxSize)
655 updateTriangulation( geom );
659 const int* pi[4] = { &i1, &i2, &i3, &i1 };
662 TopExp_Explorer fExp( geom, TopAbs_FACE );
663 for ( ; fExp.More(); fExp.Next() )
665 Handle(Poly_Triangulation) triangulation =
666 BRep_Tool::Triangulation ( TopoDS::Face( fExp.Current() ), loc);
667 if ( triangulation.IsNull() ) continue;
668 const double fTol = BRep_Tool::Tolerance( TopoDS::Face( fExp.Current() ));
669 const TColgp_Array1OfPnt& points = triangulation->Nodes();
670 const Poly_Array1OfTriangle& trias = triangulation->Triangles();
671 for ( int iT = trias.Lower(); iT <= trias.Upper(); ++iT )
673 trias(iT).Get( i1, i2, i3 );
674 for ( int j = 0; j < 3; ++j )
676 double dist2 = points(*pi[j]).SquareDistance( points( *pi[j+1] ));
677 if ( dist2 < minh && fTol*fTol < dist2 )
679 bb.Add( points(*pi[j]));
683 if ( minh > 0.25 * bb.SquareExtent() ) // simple geometry, rough triangulation
685 minh = 1e-3 * sqrt( bb.SquareExtent());
686 //cout << "BND BOX minh = " <<minh << endl;
690 minh = 3 * sqrt( minh ); // triangulation for visualization is rather fine
691 //cout << "TRIANGULATION minh = " <<minh << endl;
693 if ( minh > 0.5 * maxSize )
699 //================================================================================
701 * \brief Restrict size of elements at a given point
703 //================================================================================
705 void NETGENPlugin_Mesher::RestrictLocalSize(netgen::Mesh& ngMesh,
708 const bool overrideMinH)
710 if ( size <= std::numeric_limits<double>::min() )
712 if ( netgen::mparam.minh > size )
716 ngMesh.SetMinimalH( size );
717 netgen::mparam.minh = size;
721 size = netgen::mparam.minh;
724 netgen::Point3d pi(p.X(), p.Y(), p.Z());
725 ngMesh.RestrictLocalH( pi, size );
728 //================================================================================
730 * \brief fill ngMesh with nodes and elements of computed submeshes
732 //================================================================================
734 bool NETGENPlugin_Mesher::FillNgMesh(netgen::OCCGeometry& occgeom,
735 netgen::Mesh& ngMesh,
736 vector<const SMDS_MeshNode*>& nodeVec,
737 const list< SMESH_subMesh* > & meshedSM,
738 SMESH_MesherHelper* quadHelper,
739 SMESH_ProxyMesh::Ptr proxyMesh)
741 TNode2IdMap nodeNgIdMap;
742 for ( size_t i = 1; i < nodeVec.size(); ++i )
743 nodeNgIdMap.insert( make_pair( nodeVec[i], i ));
745 TopTools_MapOfShape visitedShapes;
746 map< SMESH_subMesh*, set< int > > visitedEdgeSM2Faces;
747 set< SMESH_subMesh* > computedSM( meshedSM.begin(), meshedSM.end() );
749 SMESH_MesherHelper helper (*_mesh);
751 int faceNgID = ngMesh.GetNFD();
753 list< SMESH_subMesh* >::const_iterator smIt, smEnd = meshedSM.end();
754 for ( smIt = meshedSM.begin(); smIt != smEnd; ++smIt )
756 SMESH_subMesh* sm = *smIt;
757 if ( !visitedShapes.Add( sm->GetSubShape() ))
760 const SMESHDS_SubMesh * smDS = sm->GetSubMeshDS();
761 if ( !smDS ) continue;
763 switch ( sm->GetSubShape().ShapeType() )
765 case TopAbs_EDGE: { // EDGE
766 // ----------------------
767 TopoDS_Edge geomEdge = TopoDS::Edge( sm->GetSubShape() );
768 if ( geomEdge.Orientation() >= TopAbs_INTERNAL )
769 geomEdge.Orientation( TopAbs_FORWARD ); // issue 0020676
771 // Add ng segments for each not meshed FACE the EDGE bounds
772 PShapeIteratorPtr fIt = helper.GetAncestors( geomEdge, *sm->GetFather(), TopAbs_FACE );
773 while ( const TopoDS_Shape * anc = fIt->next() )
775 faceNgID = occgeom.fmap.FindIndex( *anc );
777 continue; // meshed face
779 int faceSMDSId = helper.GetMeshDS()->ShapeToIndex( *anc );
780 if ( visitedEdgeSM2Faces[ sm ].count( faceSMDSId ))
781 continue; // already treated EDGE
783 TopoDS_Face face = TopoDS::Face( occgeom.fmap( faceNgID ));
784 if ( face.Orientation() >= TopAbs_INTERNAL )
785 face.Orientation( TopAbs_FORWARD ); // issue 0020676
787 // get all meshed EDGEs of the FACE connected to geomEdge (issue 0021140)
788 helper.SetSubShape( face );
789 list< TopoDS_Edge > edges = getConnectedEdges( geomEdge, face, computedSM, helper,
790 visitedEdgeSM2Faces );
792 continue; // wrong ancestor?
794 // find out orientation of <edges> within <face>
795 TopoDS_Edge eNotSeam = edges.front();
796 if ( helper.HasSeam() )
798 list< TopoDS_Edge >::iterator eIt = edges.begin();
799 while ( helper.IsRealSeam( *eIt )) ++eIt;
800 if ( eIt != edges.end() )
803 TopAbs_Orientation fOri = helper.GetSubShapeOri( face, eNotSeam );
804 bool isForwad = ( fOri == eNotSeam.Orientation() || fOri >= TopAbs_INTERNAL );
806 // get all nodes from connected <edges>
807 const bool isQuad = smDS->IsQuadratic();
808 StdMeshers_FaceSide fSide( face, edges, _mesh, isForwad, isQuad );
809 const vector<UVPtStruct>& points = fSide.GetUVPtStruct();
810 if ( points.empty() )
811 return false; // invalid node params?
812 int i, nbSeg = fSide.NbSegments();
814 // remember EDGEs of fSide to treat only once
815 for ( int iE = 0; iE < fSide.NbEdges(); ++iE )
816 visitedEdgeSM2Faces[ helper.GetMesh()->GetSubMesh( fSide.Edge(iE )) ].insert(faceSMDSId);
818 double otherSeamParam = 0;
823 int prevNgId = ngNodeId( points[0].node, ngMesh, nodeNgIdMap );
825 for ( i = 0; i < nbSeg; ++i )
827 const UVPtStruct& p1 = points[ i ];
828 const UVPtStruct& p2 = points[ i+1 ];
830 if ( p1.node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX ) //an EDGE begins
833 if ( helper.IsRealSeam( p1.node->getshapeId() ))
835 TopoDS_Edge e = fSide.Edge( fSide.EdgeIndex( 0.5 * ( p1.normParam + p2.normParam )));
836 isSeam = helper.IsRealSeam( e );
839 otherSeamParam = helper.GetOtherParam( helper.GetPeriodicIndex() & 1 ? p2.u : p2.v );
846 seg[1] = prevNgId = ngNodeId( p2.node, ngMesh, nodeNgIdMap );
847 // node param on curve
848 seg.epgeominfo[ 0 ].dist = p1.param;
849 seg.epgeominfo[ 1 ].dist = p2.param;
851 seg.epgeominfo[ 0 ].u = p1.u;
852 seg.epgeominfo[ 0 ].v = p1.v;
853 seg.epgeominfo[ 1 ].u = p2.u;
854 seg.epgeominfo[ 1 ].v = p2.v;
856 //geomEdge = fSide.Edge( fSide.EdgeIndex( 0.5 * ( p1.normParam + p2.normParam )));
857 //seg.epgeominfo[ 0 ].edgenr = seg.epgeominfo[ 1 ].edgenr = occgeom.emap.FindIndex( geomEdge );
859 //seg.epgeominfo[ iEnd ].edgenr = edgeID; // = geom.emap.FindIndex(edge);
860 seg.si = faceNgID; // = geom.fmap.FindIndex (face);
861 seg.edgenr = ngMesh.GetNSeg() + 1; // segment id
862 ngMesh.AddSegment (seg);
864 SMESH_TNodeXYZ np1( p1.node ), np2( p2.node );
865 RestrictLocalSize( ngMesh, 0.5*(np1+np2), (np1-np2).Modulus() );
868 cout << "Segment: " << seg.edgenr << " on SMESH face " << helper.GetMeshDS()->ShapeToIndex( face ) << endl
869 << "\tface index: " << seg.si << endl
870 << "\tp1: " << seg[0] << endl
871 << "\tp2: " << seg[1] << endl
872 << "\tp0 param: " << seg.epgeominfo[ 0 ].dist << endl
873 << "\tp0 uv: " << seg.epgeominfo[ 0 ].u <<", "<< seg.epgeominfo[ 0 ].v << endl
874 //<< "\tp0 edge: " << seg.epgeominfo[ 0 ].edgenr << endl
875 << "\tp1 param: " << seg.epgeominfo[ 1 ].dist << endl
876 << "\tp1 uv: " << seg.epgeominfo[ 1 ].u <<", "<< seg.epgeominfo[ 1 ].v << endl;
877 //<< "\tp1 edge: " << seg.epgeominfo[ 1 ].edgenr << endl;
881 if ( helper.GetPeriodicIndex() && 1 ) {
882 seg.epgeominfo[ 0 ].u = otherSeamParam;
883 seg.epgeominfo[ 1 ].u = otherSeamParam;
884 swap (seg.epgeominfo[0].v, seg.epgeominfo[1].v);
886 seg.epgeominfo[ 0 ].v = otherSeamParam;
887 seg.epgeominfo[ 1 ].v = otherSeamParam;
888 swap (seg.epgeominfo[0].u, seg.epgeominfo[1].u);
890 swap( seg[0], seg[1] );
891 swap( seg.epgeominfo[0].dist, seg.epgeominfo[1].dist );
892 seg.edgenr = ngMesh.GetNSeg() + 1; // segment id
893 ngMesh.AddSegment( seg );
895 cout << "Segment: " << seg.edgenr << endl
896 << "\t is SEAM (reverse) of the previous. "
897 << " Other " << (helper.GetPeriodicIndex() && 1 ? "U" : "V")
898 << " = " << otherSeamParam << endl;
901 else if ( fOri == TopAbs_INTERNAL )
903 swap( seg[0], seg[1] );
904 swap( seg.epgeominfo[0], seg.epgeominfo[1] );
905 seg.edgenr = ngMesh.GetNSeg() + 1; // segment id
906 ngMesh.AddSegment( seg );
908 cout << "Segment: " << seg.edgenr << endl << "\t is REVERSE of the previous" << endl;
912 } // loop on geomEdge ancestors
914 if ( quadHelper ) // remember medium nodes of sub-meshes
916 SMDS_ElemIteratorPtr edges = smDS->GetElements();
917 while ( edges->more() )
919 const SMDS_MeshElement* e = edges->next();
920 if ( !quadHelper->AddTLinks( static_cast< const SMDS_MeshEdge*>( e )))
926 } // case TopAbs_EDGE
928 case TopAbs_FACE: { // FACE
929 // ----------------------
930 const TopoDS_Face& geomFace = TopoDS::Face( sm->GetSubShape() );
931 helper.SetSubShape( geomFace );
932 bool isInternalFace = ( geomFace.Orientation() == TopAbs_INTERNAL );
934 // Find solids the geomFace bounds
935 int solidID1 = 0, solidID2 = 0;
936 StdMeshers_QuadToTriaAdaptor* quadAdaptor =
937 dynamic_cast<StdMeshers_QuadToTriaAdaptor*>( proxyMesh.get() );
940 solidID1 = occgeom.somap.FindIndex( quadAdaptor->GetShape() );
944 PShapeIteratorPtr solidIt = helper.GetAncestors( geomFace, *sm->GetFather(), TopAbs_SOLID);
945 while ( const TopoDS_Shape * solid = solidIt->next() )
947 int id = occgeom.somap.FindIndex ( *solid );
948 if ( solidID1 && id != solidID1 ) solidID2 = id;
952 // Add ng face descriptors of meshed faces
954 ngMesh.AddFaceDescriptor( netgen::FaceDescriptor( faceNgID, solidID1, solidID2, 0 ));
956 // if second oreder is required, even already meshed faces must be passed to NETGEN
957 int fID = occgeom.fmap.Add( geomFace );
958 occgeom.facemeshstatus[ fID-1 ] = netgen::FACE_MESHED_OK;
959 while ( fID < faceNgID ) // geomFace is already in occgeom.fmap, add a copy
961 fID = occgeom.fmap.Add( BRepBuilderAPI_Copy( geomFace, /*copyGeom=*/false ));
962 if ( occgeom.facemeshstatus.Size() < fID ) occgeom.facemeshstatus.SetSize( fID );
963 occgeom.facemeshstatus[ fID-1 ] = netgen::FACE_MESHED_OK;
965 // Problem with the second order in a quadrangular mesh remains.
966 // 1) All quadrangles generated by NETGEN are moved to an inexistent face
967 // by FillSMesh() (find "AddFaceDescriptor")
968 // 2) Temporary triangles generated by StdMeshers_QuadToTriaAdaptor
969 // are on faces where quadrangles were.
970 // Due to these 2 points, wrong geom faces are used while conversion to quadratic
971 // of the mentioned above quadrangles and triangles
973 // Orient the face correctly in solidID1 (issue 0020206)
974 bool reverse = false;
976 TopoDS_Shape solid = occgeom.somap( solidID1 );
977 TopAbs_Orientation faceOriInSolid = helper.GetSubShapeOri( solid, geomFace );
978 if ( faceOriInSolid >= 0 )
980 helper.IsReversedSubMesh( TopoDS::Face( geomFace.Oriented( faceOriInSolid )));
983 // Add surface elements
985 netgen::Element2d tri(3);
986 tri.SetIndex( faceNgID );
987 SMESH_TNodeXYZ xyz[3];
989 #ifdef DUMP_TRIANGLES
990 cout << "SMESH face " << helper.GetMeshDS()->ShapeToIndex( geomFace )
991 << " internal="<<isInternalFace << endl;
994 smDS = proxyMesh->GetSubMesh( geomFace );
996 SMDS_ElemIteratorPtr faces = smDS->GetElements();
997 while ( faces->more() )
999 const SMDS_MeshElement* f = faces->next();
1000 if ( f->NbNodes() % 3 != 0 ) // not triangle
1002 PShapeIteratorPtr solidIt=helper.GetAncestors(geomFace,*sm->GetFather(),TopAbs_SOLID);
1003 if ( const TopoDS_Shape * solid = solidIt->next() )
1004 sm = _mesh->GetSubMesh( *solid );
1005 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1006 smError.reset( new SMESH_ComputeError(COMPERR_BAD_INPUT_MESH,"Not triangle sub-mesh"));
1007 smError->myBadElements.push_back( f );
1011 for ( int i = 0; i < 3; ++i )
1013 const SMDS_MeshNode* node = f->GetNode( i ), * inFaceNode=0;
1016 // get node UV on face
1017 int shapeID = node->getshapeId();
1018 if ( helper.IsSeamShape( shapeID ))
1020 if ( helper.IsSeamShape( f->GetNodeWrap( i+1 )->getshapeId() ))
1021 inFaceNode = f->GetNodeWrap( i-1 );
1023 inFaceNode = f->GetNodeWrap( i+1 );
1025 gp_XY uv = helper.GetNodeUV( geomFace, node, inFaceNode );
1027 int ind = reverse ? 3-i : i+1;
1028 tri.GeomInfoPi(ind).u = uv.X();
1029 tri.GeomInfoPi(ind).v = uv.Y();
1030 tri.PNum (ind) = ngNodeId( node, ngMesh, nodeNgIdMap );
1033 // pass a triangle size to NG size-map
1034 double size = ( ( xyz[0] - xyz[1] ).Modulus() +
1035 ( xyz[1] - xyz[2] ).Modulus() +
1036 ( xyz[2] - xyz[0] ).Modulus() ) / 3;
1037 gp_XYZ gc = ( xyz[0] + xyz[1] + xyz[2] ) / 3;
1038 RestrictLocalSize( ngMesh, gc, size, /*overrideMinH=*/false );
1040 ngMesh.AddSurfaceElement (tri);
1041 #ifdef DUMP_TRIANGLES
1042 cout << tri << endl;
1045 if ( isInternalFace )
1047 swap( tri[1], tri[2] );
1048 ngMesh.AddSurfaceElement (tri);
1049 #ifdef DUMP_TRIANGLES
1050 cout << tri << endl;
1055 if ( quadHelper ) // remember medium nodes of sub-meshes
1057 SMDS_ElemIteratorPtr faces = smDS->GetElements();
1058 while ( faces->more() )
1060 const SMDS_MeshElement* f = faces->next();
1061 if ( !quadHelper->AddTLinks( static_cast< const SMDS_MeshFace*>( f )))
1067 } // case TopAbs_FACE
1069 case TopAbs_VERTEX: { // VERTEX
1070 // --------------------------
1071 // issue 0021405. Add node only if a VERTEX is shared by a not meshed EDGE,
1072 // else netgen removes a free node and nodeVector becomes invalid
1073 PShapeIteratorPtr ansIt = helper.GetAncestors( sm->GetSubShape(),
1077 while ( const TopoDS_Shape* e = ansIt->next() )
1079 SMESH_subMesh* eSub = helper.GetMesh()->GetSubMesh( *e );
1080 if (( toAdd = ( eSub->IsEmpty() && !SMESH_Algo::isDegenerated( TopoDS::Edge( *e )))))
1085 SMDS_NodeIteratorPtr nodeIt = smDS->GetNodes();
1086 if ( nodeIt->more() )
1087 ngNodeId( nodeIt->next(), ngMesh, nodeNgIdMap );
1093 } // loop on submeshes
1096 nodeVec.resize( ngMesh.GetNP() + 1 );
1097 TNode2IdMap::iterator node_NgId, nodeNgIdEnd = nodeNgIdMap.end();
1098 for ( node_NgId = nodeNgIdMap.begin(); node_NgId != nodeNgIdEnd; ++node_NgId)
1099 nodeVec[ node_NgId->second ] = node_NgId->first;
1104 //================================================================================
1106 * \brief Duplicate mesh faces on internal geom faces
1108 //================================================================================
1110 void NETGENPlugin_Mesher::FixIntFaces(const netgen::OCCGeometry& occgeom,
1111 netgen::Mesh& ngMesh,
1112 NETGENPlugin_Internals& internalShapes)
1114 SMESHDS_Mesh* meshDS = internalShapes.getMesh().GetMeshDS();
1116 // find ng indices of internal faces
1118 for ( int ngFaceID = 1; ngFaceID <= occgeom.fmap.Extent(); ++ngFaceID )
1120 int smeshID = meshDS->ShapeToIndex( occgeom.fmap( ngFaceID ));
1121 if ( internalShapes.isInternalShape( smeshID ))
1122 ngFaceIds.insert( ngFaceID );
1124 if ( !ngFaceIds.empty() )
1127 int i, nbFaces = ngMesh.GetNSE();
1128 for ( i = 1; i <= nbFaces; ++i)
1130 netgen::Element2d elem = ngMesh.SurfaceElement(i);
1131 if ( ngFaceIds.count( elem.GetIndex() ))
1133 swap( elem[1], elem[2] );
1134 ngMesh.AddSurfaceElement (elem);
1140 //================================================================================
1142 * \brief Tries to heal the mesh on a FACE. The FACE is supposed to be partially
1143 * meshed due to NETGEN failure
1144 * \param [in] occgeom - geometry
1145 * \param [in,out] ngMesh - the mesh to fix
1146 * \param [inout] faceID - ID of the FACE to fix the mesh on
1147 * \return bool - is mesh is or becomes OK
1149 //================================================================================
1151 bool NETGENPlugin_Mesher::FixFaceMesh(const netgen::OCCGeometry& occgeom,
1152 netgen::Mesh& ngMesh,
1155 // we address a case where the FACE is almost fully meshed except small holes
1156 // of usually triangular shape at FACE boundary (IPAL52861)
1158 // The case appeared to be not simple: holes only look triangular but
1159 // indeed are a self intersecting polygon. A reason of the bug was in coincident
1160 // NG points on a seam edge. But the code below is very nice, leave it for
1165 if ( occgeom.fmap.Extent() < faceID )
1167 //const TopoDS_Face& face = TopoDS::Face( occgeom.fmap( faceID ));
1169 // find free links on the FACE
1170 NCollection_Map<Link> linkMap;
1171 for ( int iF = 1; iF <= ngMesh.GetNSE(); ++iF )
1173 const netgen::Element2d& elem = ngMesh.SurfaceElement(iF);
1174 if ( faceID != elem.GetIndex() )
1176 int n0 = elem[ elem.GetNP() - 1 ];
1177 for ( int i = 0; i < elem.GetNP(); ++i )
1180 Link link( n0, n1 );
1181 if ( !linkMap.Add( link ))
1182 linkMap.Remove( link );
1186 // add/remove boundary links
1187 for ( int iSeg = 1; iSeg <= ngMesh.GetNSeg(); ++iSeg )
1189 const netgen::Segment& seg = ngMesh.LineSegment( iSeg );
1190 if ( seg.si != faceID ) // !edgeIDs.Contains( seg.edgenr ))
1192 Link link( seg[1], seg[0] ); // reverse!!!
1193 if ( !linkMap.Add( link ))
1194 linkMap.Remove( link );
1196 if ( linkMap.IsEmpty() )
1198 if ( linkMap.Extent() < 3 )
1201 // make triangles of the links
1203 netgen::Element2d tri(3);
1204 tri.SetIndex ( faceID );
1206 NCollection_Map<Link>::Iterator linkIt( linkMap );
1207 Link link1 = linkIt.Value();
1208 // look for a link connected to link1
1209 NCollection_Map<Link>::Iterator linkIt2 = linkIt;
1210 for ( linkIt2.Next(); linkIt2.More(); linkIt2.Next() )
1212 const Link& link2 = linkIt2.Value();
1213 if ( link2.IsConnected( link1 ))
1215 // look for a link connected to both link1 and link2
1216 NCollection_Map<Link>::Iterator linkIt3 = linkIt2;
1217 for ( linkIt3.Next(); linkIt3.More(); linkIt3.Next() )
1219 const Link& link3 = linkIt3.Value();
1220 if ( link3.IsConnected( link1 ) &&
1221 link3.IsConnected( link2 ) )
1226 tri[2] = ( link2.Contains( link1.n1 ) ? link2.n1 : link3.n1 );
1227 if ( tri[0] == tri[2] || tri[1] == tri[2] )
1229 ngMesh.AddSurfaceElement( tri );
1231 // prepare for the next tria search
1232 if ( linkMap.Extent() == 3 )
1234 linkMap.Remove( link3 );
1235 linkMap.Remove( link2 );
1237 linkMap.Remove( link1 );
1238 link1 = linkIt.Value();
1251 //================================================================================
1252 // define gp_XY_Subtracted pointer to function calling gp_XY::Subtracted(gp_XY)
1253 gp_XY_FunPtr(Subtracted);
1254 //gp_XY_FunPtr(Added);
1256 //================================================================================
1258 * \brief Evaluate distance between two 2d points along the surface
1260 //================================================================================
1262 double evalDist( const gp_XY& uv1,
1264 const Handle(Geom_Surface)& surf,
1265 const int stopHandler=-1)
1267 if ( stopHandler > 0 ) // continue recursion
1269 gp_XY mid = SMESH_MesherHelper::GetMiddleUV( surf, uv1, uv2 );
1270 return evalDist( uv1,mid, surf, stopHandler-1 ) + evalDist( mid,uv2, surf, stopHandler-1 );
1272 double dist3D = surf->Value( uv1.X(), uv1.Y() ).Distance( surf->Value( uv2.X(), uv2.Y() ));
1273 if ( stopHandler == 0 ) // stop recursion
1276 // start recursion if necessary
1277 double dist2D = SMESH_MesherHelper::ApplyIn2D(surf, uv1, uv2, gp_XY_Subtracted, 0).Modulus();
1278 if ( fabs( dist3D - dist2D ) < dist2D * 1e-10 )
1279 return dist3D; // equal parametrization of a planar surface
1281 return evalDist( uv1, uv2, surf, 3 ); // start recursion
1284 //================================================================================
1286 * \brief Data of vertex internal in geom face
1288 //================================================================================
1292 gp_XY uv; //!< UV in face parametric space
1293 int ngId; //!< ng id of corrsponding node
1294 gp_XY uvClose; //!< UV of closest boundary node
1295 int ngIdClose; //!< ng id of closest boundary node
1298 //================================================================================
1300 * \brief Data of vertex internal in solid
1302 //================================================================================
1306 int ngId; //!< ng id of corresponding node
1307 int ngIdClose; //!< ng id of closest 2d mesh element
1308 int ngIdCloseN; //!< ng id of closest node of the closest 2d mesh element
1311 inline double dist2(const netgen::MeshPoint& p1, const netgen::MeshPoint& p2)
1313 return gp_Pnt( NGPOINT_COORDS(p1)).SquareDistance( gp_Pnt( NGPOINT_COORDS(p2)));
1317 //================================================================================
1319 * \brief Make netgen take internal vertices in faces into account by adding
1320 * segments including internal vertices
1322 * This function works in supposition that 1D mesh is already computed in ngMesh
1324 //================================================================================
1326 void NETGENPlugin_Mesher::AddIntVerticesInFaces(const netgen::OCCGeometry& occgeom,
1327 netgen::Mesh& ngMesh,
1328 vector<const SMDS_MeshNode*>& nodeVec,
1329 NETGENPlugin_Internals& internalShapes)
1331 if ((int) nodeVec.size() < ngMesh.GetNP() )
1332 nodeVec.resize( ngMesh.GetNP(), 0 );
1334 SMESHDS_Mesh* meshDS = internalShapes.getMesh().GetMeshDS();
1335 SMESH_MesherHelper helper( internalShapes.getMesh() );
1337 const map<int,list<int> >& face2Vert = internalShapes.getFacesWithVertices();
1338 map<int,list<int> >::const_iterator f2v = face2Vert.begin();
1339 for ( ; f2v != face2Vert.end(); ++f2v )
1341 const TopoDS_Face& face = TopoDS::Face( meshDS->IndexToShape( f2v->first ));
1342 if ( face.IsNull() ) continue;
1343 int faceNgID = occgeom.fmap.FindIndex (face);
1344 if ( faceNgID < 0 ) continue;
1346 TopLoc_Location loc;
1347 Handle(Geom_Surface) surf = BRep_Tool::Surface(face,loc);
1349 helper.SetSubShape( face );
1350 helper.SetElementsOnShape( true );
1352 // Get data of internal vertices and add them to ngMesh
1354 multimap< double, TIntVData > dist2VData; // sort vertices by distance from boundary nodes
1356 int i, nbSegInit = ngMesh.GetNSeg();
1358 // boundary characteristics
1359 double totSegLen2D = 0;
1362 const list<int>& iVertices = f2v->second;
1363 list<int>::const_iterator iv = iVertices.begin();
1364 for ( int nbV = 0; iv != iVertices.end(); ++iv, nbV++ )
1367 // get node on vertex
1368 const TopoDS_Vertex V = TopoDS::Vertex( meshDS->IndexToShape( *iv ));
1369 const SMDS_MeshNode * nV = SMESH_Algo::VertexNode( V, meshDS );
1372 SMESH_subMesh* sm = helper.GetMesh()->GetSubMesh( V );
1373 sm->ComputeStateEngine( SMESH_subMesh::COMPUTE );
1374 nV = SMESH_Algo::VertexNode( V, meshDS );
1375 if ( !nV ) continue;
1378 netgen::MeshPoint mp( netgen::Point<3> (nV->X(), nV->Y(), nV->Z()) );
1379 ngMesh.AddPoint ( mp, 1, netgen::EDGEPOINT );
1380 vData.ngId = ngMesh.GetNP();
1381 nodeVec.push_back( nV );
1385 vData.uv = helper.GetNodeUV( face, nV, 0, &uvOK );
1386 if ( !uvOK ) helper.CheckNodeUV( face, nV, vData.uv, BRep_Tool::Tolerance(V),/*force=*/1);
1388 // loop on all segments of the face to find the node closest to vertex and to count
1389 // average segment 2d length
1390 double closeDist2 = numeric_limits<double>::max(), dist2;
1392 for (i = 1; i <= ngMesh.GetNSeg(); ++i)
1394 netgen::Segment & seg = ngMesh.LineSegment(i);
1395 if ( seg.si != faceNgID ) continue;
1397 for ( int iEnd = 0; iEnd < 2; ++iEnd)
1399 uv[iEnd].SetCoord( seg.epgeominfo[iEnd].u, seg.epgeominfo[iEnd].v );
1400 if ( ngIdLast == seg[ iEnd ] ) continue;
1401 dist2 = helper.ApplyIn2D(surf, uv[iEnd], vData.uv, gp_XY_Subtracted,0).SquareModulus();
1402 if ( dist2 < closeDist2 )
1403 vData.ngIdClose = seg[ iEnd ], vData.uvClose = uv[iEnd], closeDist2 = dist2;
1404 ngIdLast = seg[ iEnd ];
1408 totSegLen2D += helper.ApplyIn2D(surf, uv[0], uv[1], gp_XY_Subtracted, false).Modulus();
1412 dist2VData.insert( make_pair( closeDist2, vData ));
1415 if ( totNbSeg == 0 ) break;
1416 double avgSegLen2d = totSegLen2D / totNbSeg;
1418 // Loop on vertices to add segments
1420 multimap< double, TIntVData >::iterator dist_vData = dist2VData.begin();
1421 for ( ; dist_vData != dist2VData.end(); ++dist_vData )
1423 double closeDist2 = dist_vData->first, dist2;
1424 TIntVData & vData = dist_vData->second;
1426 // try to find more close node among segments added for internal vertices
1427 for (i = nbSegInit+1; i <= ngMesh.GetNSeg(); ++i)
1429 netgen::Segment & seg = ngMesh.LineSegment(i);
1430 if ( seg.si != faceNgID ) continue;
1432 for ( int iEnd = 0; iEnd < 2; ++iEnd)
1434 uv[iEnd].SetCoord( seg.epgeominfo[iEnd].u, seg.epgeominfo[iEnd].v );
1435 dist2 = helper.ApplyIn2D(surf, uv[iEnd], vData.uv, gp_XY_Subtracted,0).SquareModulus();
1436 if ( dist2 < closeDist2 )
1437 vData.ngIdClose = seg[ iEnd ], vData.uvClose = uv[iEnd], closeDist2 = dist2;
1440 // decide whether to use the closest node as the second end of segment or to
1441 // create a new point
1442 int segEnd1 = vData.ngId;
1443 int segEnd2 = vData.ngIdClose; // to use closest node
1444 gp_XY uvV = vData.uv, uvP = vData.uvClose;
1445 double segLenHint = ngMesh.GetH( ngMesh.Point( vData.ngId ));
1446 double nodeDist2D = sqrt( closeDist2 );
1447 double nodeDist3D = evalDist( vData.uv, vData.uvClose, surf );
1448 bool avgLenOK = ( avgSegLen2d < 0.75 * nodeDist2D );
1449 bool hintLenOK = ( segLenHint < 0.75 * nodeDist3D );
1450 //cout << "uvV " << uvV.X() <<","<<uvV.Y() << " ";
1451 if ( hintLenOK || avgLenOK )
1453 // create a point between the closest node and V
1456 double r = min( 0.5, ( hintLenOK ? segLenHint/nodeDist3D : avgSegLen2d/nodeDist2D ));
1457 // direction from V to closet node in 2D
1458 gp_Dir2d v2n( helper.ApplyIn2D(surf, uvP, uvV, gp_XY_Subtracted, false ));
1460 uvP = vData.uv + r * nodeDist2D * v2n.XY();
1461 gp_Pnt P = surf->Value( uvP.X(), uvP.Y() ).Transformed( loc );
1463 netgen::MeshPoint mp( netgen::Point<3> (P.X(), P.Y(), P.Z()));
1464 ngMesh.AddPoint ( mp, 1, netgen::EDGEPOINT );
1465 segEnd2 = ngMesh.GetNP();
1466 //cout << "Middle " << r << " uv " << uvP.X() << "," << uvP.Y() << "( " << ngMesh.Point(segEnd2).X()<<","<<ngMesh.Point(segEnd2).Y()<<","<<ngMesh.Point(segEnd2).Z()<<" )"<< endl;
1467 SMDS_MeshNode * nP = helper.AddNode(P.X(), P.Y(), P.Z());
1468 nodeVec.push_back( nP );
1470 //else cout << "at Node " << " uv " << uvP.X() << "," << uvP.Y() << endl;
1473 netgen::Segment seg;
1475 if ( segEnd1 > segEnd2 ) swap( segEnd1, segEnd2 ), swap( uvV, uvP );
1476 seg[0] = segEnd1; // ng node id
1477 seg[1] = segEnd2; // ng node id
1478 seg.edgenr = ngMesh.GetNSeg() + 1;// segment id
1481 seg.epgeominfo[ 0 ].dist = 0; // param on curve
1482 seg.epgeominfo[ 0 ].u = uvV.X();
1483 seg.epgeominfo[ 0 ].v = uvV.Y();
1484 seg.epgeominfo[ 1 ].dist = 1; // param on curve
1485 seg.epgeominfo[ 1 ].u = uvP.X();
1486 seg.epgeominfo[ 1 ].v = uvP.Y();
1488 // seg.epgeominfo[ 0 ].edgenr = 10; // = geom.emap.FindIndex(edge);
1489 // seg.epgeominfo[ 1 ].edgenr = 10; // = geom.emap.FindIndex(edge);
1491 ngMesh.AddSegment (seg);
1493 // add reverse segment
1494 swap( seg[0], seg[1] );
1495 swap( seg.epgeominfo[0], seg.epgeominfo[1] );
1496 seg.edgenr = ngMesh.GetNSeg() + 1; // segment id
1497 ngMesh.AddSegment (seg);
1503 //================================================================================
1505 * \brief Make netgen take internal vertices in solids into account by adding
1506 * faces including internal vertices
1508 * This function works in supposition that 2D mesh is already computed in ngMesh
1510 //================================================================================
1512 void NETGENPlugin_Mesher::AddIntVerticesInSolids(const netgen::OCCGeometry& occgeom,
1513 netgen::Mesh& ngMesh,
1514 vector<const SMDS_MeshNode*>& nodeVec,
1515 NETGENPlugin_Internals& internalShapes)
1517 #ifdef DUMP_TRIANGLES_SCRIPT
1518 // create a python script making a mesh containing triangles added for internal vertices
1519 ofstream py(DUMP_TRIANGLES_SCRIPT);
1520 py << "import SMESH"<< endl
1521 << "from salome.smesh import smeshBuilder"<<endl
1522 << "smesh = smeshBuilder.New(salome.myStudy)"<<endl
1523 << "m = smesh.Mesh(name='triangles')" << endl;
1525 if ((int) nodeVec.size() < ngMesh.GetNP() )
1526 nodeVec.resize( ngMesh.GetNP(), 0 );
1528 SMESHDS_Mesh* meshDS = internalShapes.getMesh().GetMeshDS();
1529 SMESH_MesherHelper helper( internalShapes.getMesh() );
1531 const map<int,list<int> >& so2Vert = internalShapes.getSolidsWithVertices();
1532 map<int,list<int> >::const_iterator s2v = so2Vert.begin();
1533 for ( ; s2v != so2Vert.end(); ++s2v )
1535 const TopoDS_Shape& solid = meshDS->IndexToShape( s2v->first );
1536 if ( solid.IsNull() ) continue;
1537 int solidNgID = occgeom.somap.FindIndex (solid);
1538 if ( solidNgID < 0 && !occgeom.somap.IsEmpty() ) continue;
1540 helper.SetSubShape( solid );
1541 helper.SetElementsOnShape( true );
1543 // find ng indices of faces within the solid
1545 for (TopExp_Explorer fExp(solid, TopAbs_FACE); fExp.More(); fExp.Next() )
1546 ngFaceIds.insert( occgeom.fmap.FindIndex( fExp.Current() ));
1547 if ( ngFaceIds.size() == 1 && *ngFaceIds.begin() == 0 )
1548 ngFaceIds.insert( 1 );
1550 // Get data of internal vertices and add them to ngMesh
1552 multimap< double, TIntVSoData > dist2VData; // sort vertices by distance from ng faces
1554 int i, nbFaceInit = ngMesh.GetNSE();
1556 // boundary characteristics
1557 double totSegLen = 0;
1560 const list<int>& iVertices = s2v->second;
1561 list<int>::const_iterator iv = iVertices.begin();
1562 for ( int nbV = 0; iv != iVertices.end(); ++iv, nbV++ )
1565 const TopoDS_Vertex V = TopoDS::Vertex( meshDS->IndexToShape( *iv ));
1567 // get node on vertex
1568 const SMDS_MeshNode * nV = SMESH_Algo::VertexNode( V, meshDS );
1571 SMESH_subMesh* sm = helper.GetMesh()->GetSubMesh( V );
1572 sm->ComputeStateEngine( SMESH_subMesh::COMPUTE );
1573 nV = SMESH_Algo::VertexNode( V, meshDS );
1574 if ( !nV ) continue;
1577 netgen::MeshPoint mpV( netgen::Point<3> (nV->X(), nV->Y(), nV->Z()) );
1578 ngMesh.AddPoint ( mpV, 1, netgen::FIXEDPOINT );
1579 vData.ngId = ngMesh.GetNP();
1580 nodeVec.push_back( nV );
1582 // loop on all 2d elements to find the one closest to vertex and to count
1583 // average segment length
1584 double closeDist2 = numeric_limits<double>::max(), avgDist2;
1585 for (i = 1; i <= ngMesh.GetNSE(); ++i)
1587 const netgen::Element2d& elem = ngMesh.SurfaceElement(i);
1588 if ( !ngFaceIds.count( elem.GetIndex() )) continue;
1590 multimap< double, int> dist2nID; // sort nodes of element by distance from V
1591 for ( int j = 0; j < elem.GetNP(); ++j)
1593 netgen::MeshPoint mp = ngMesh.Point( elem[j] );
1594 double d2 = dist2( mpV, mp );
1595 dist2nID.insert( make_pair( d2, elem[j] ));
1596 avgDist2 += d2 / elem.GetNP();
1598 totNbSeg++, totSegLen+= sqrt( dist2( mp, ngMesh.Point( elem[(j+1)%elem.GetNP()])));
1600 double dist = dist2nID.begin()->first; //avgDist2;
1601 if ( dist < closeDist2 )
1602 vData.ngIdClose= i, vData.ngIdCloseN= dist2nID.begin()->second, closeDist2= dist;
1604 dist2VData.insert( make_pair( closeDist2, vData ));
1607 if ( totNbSeg == 0 ) break;
1608 double avgSegLen = totSegLen / totNbSeg;
1610 // Loop on vertices to add triangles
1612 multimap< double, TIntVSoData >::iterator dist_vData = dist2VData.begin();
1613 for ( ; dist_vData != dist2VData.end(); ++dist_vData )
1615 double closeDist2 = dist_vData->first;
1616 TIntVSoData & vData = dist_vData->second;
1618 const netgen::MeshPoint& mpV = ngMesh.Point( vData.ngId );
1620 // try to find more close face among ones added for internal vertices
1621 for (i = nbFaceInit+1; i <= ngMesh.GetNSE(); ++i)
1623 double avgDist2 = 0;
1624 multimap< double, int> dist2nID;
1625 const netgen::Element2d& elem = ngMesh.SurfaceElement(i);
1626 for ( int j = 0; j < elem.GetNP(); ++j)
1628 double d = dist2( mpV, ngMesh.Point( elem[j] ));
1629 dist2nID.insert( make_pair( d, elem[j] ));
1630 avgDist2 += d / elem.GetNP();
1631 if ( avgDist2 < closeDist2 )
1632 vData.ngIdClose= i, vData.ngIdCloseN= dist2nID.begin()->second, closeDist2= avgDist2;
1635 // sort nodes of the closest face by angle with vector from V to the closest node
1636 const double tol = numeric_limits<double>::min();
1637 map< double, int > angle2ID;
1638 const netgen::Element2d& closeFace = ngMesh.SurfaceElement( vData.ngIdClose );
1639 netgen::MeshPoint mp[2];
1640 mp[0] = ngMesh.Point( vData.ngIdCloseN );
1641 gp_XYZ p1( NGPOINT_COORDS( mp[0] ));
1642 gp_XYZ pV( NGPOINT_COORDS( mpV ));
1643 gp_Vec v2p1( pV, p1 );
1644 double distN1 = v2p1.Magnitude();
1645 if ( distN1 <= tol ) continue;
1647 for ( int j = 0; j < closeFace.GetNP(); ++j)
1649 mp[1] = ngMesh.Point( closeFace[j] );
1650 gp_Vec v2p( pV, gp_Pnt( NGPOINT_COORDS( mp[1] )) );
1651 angle2ID.insert( make_pair( v2p1.Angle( v2p ), closeFace[j]));
1653 // get node with angle of 60 degrees or greater
1654 map< double, int >::iterator angle_id = angle2ID.lower_bound( 60. * M_PI / 180. );
1655 if ( angle_id == angle2ID.end() ) angle_id = --angle2ID.end();
1656 const double minAngle = 30. * M_PI / 180.;
1657 const double angle = angle_id->first;
1658 bool angleOK = ( angle > minAngle );
1660 // find points to create a triangle
1661 netgen::Element2d tri(3);
1663 tri[0] = vData.ngId;
1664 tri[1] = vData.ngIdCloseN; // to use the closest nodes
1665 tri[2] = angle_id->second; // to use the node with best angle
1667 // decide whether to use the closest node and the node with best angle or to create new ones
1668 for ( int isBestAngleN = 0; isBestAngleN < 2; ++isBestAngleN )
1670 bool createNew = !angleOK; //, distOK = true;
1672 int triInd = isBestAngleN ? 2 : 1;
1673 mp[isBestAngleN] = ngMesh.Point( tri[triInd] );
1678 double distN2 = sqrt( dist2( mpV, mp[isBestAngleN]));
1679 createNew = ( fabs( distN2 - distN1 ) > 0.25 * distN1 );
1681 else if ( angle < tol )
1683 v2p1.SetX( v2p1.X() + 1e-3 );
1689 double segLenHint = ngMesh.GetH( ngMesh.Point( vData.ngId ));
1690 bool avgLenOK = ( avgSegLen < 0.75 * distN1 );
1691 bool hintLenOK = ( segLenHint < 0.75 * distN1 );
1692 createNew = (createNew || avgLenOK || hintLenOK );
1693 // we create a new node not closer than 0.5 to the closest face
1694 // in order not to clash with other close face
1695 double r = min( 0.5, ( hintLenOK ? segLenHint : avgSegLen ) / distN1 );
1696 distFromV = r * distN1;
1700 // create a new point, between the node and the vertex if angleOK
1701 gp_XYZ p( NGPOINT_COORDS( mp[isBestAngleN] ));
1702 gp_Vec v2p( pV, p ); v2p.Normalize();
1703 if ( isBestAngleN && !angleOK )
1704 p = p1 + gp_Dir( v2p.XYZ() - v2p1.XYZ()).XYZ() * distN1 * 0.95;
1706 p = pV + v2p.XYZ() * distFromV;
1708 if ( !isBestAngleN ) p1 = p, distN1 = distFromV;
1710 mp[isBestAngleN].SetPoint( netgen::Point<3> (p.X(), p.Y(), p.Z()));
1711 ngMesh.AddPoint ( mp[isBestAngleN], 1, netgen::SURFACEPOINT );
1712 tri[triInd] = ngMesh.GetNP();
1713 nodeVec.push_back( helper.AddNode( p.X(), p.Y(), p.Z()) );
1716 ngMesh.AddSurfaceElement (tri);
1717 swap( tri[1], tri[2] );
1718 ngMesh.AddSurfaceElement (tri);
1720 #ifdef DUMP_TRIANGLES_SCRIPT
1721 py << "n1 = m.AddNode( "<< mpV(0)<<", "<< mpV(1)<<", "<< mpV(2)<<") "<< endl
1722 << "n2 = m.AddNode( "<< mp[0](0)<<", "<< mp[0](1)<<", "<< mp[0](2)<<") "<< endl
1723 << "n3 = m.AddNode( "<< mp[1](0)<<", "<< mp[1](1)<<", "<< mp[1](2)<<" )" << endl
1724 << "m.AddFace([n1,n2,n3])" << endl;
1726 } // loop on internal vertices of a solid
1728 } // loop on solids with internal vertices
1731 //================================================================================
1733 * \brief Fill netgen mesh with segments of a FACE
1734 * \param ngMesh - netgen mesh
1735 * \param geom - container of OCCT geometry to mesh
1736 * \param wires - data of nodes on FACE boundary
1737 * \param helper - mesher helper holding the FACE
1738 * \param nodeVec - vector of nodes in which node index == netgen ID
1739 * \retval SMESH_ComputeErrorPtr - error description
1741 //================================================================================
1743 SMESH_ComputeErrorPtr
1744 NETGENPlugin_Mesher::AddSegmentsToMesh(netgen::Mesh& ngMesh,
1745 netgen::OCCGeometry& geom,
1746 const TSideVector& wires,
1747 SMESH_MesherHelper& helper,
1748 vector< const SMDS_MeshNode* > & nodeVec,
1749 const bool overrideMinH)
1751 // ----------------------------
1752 // Check wires and count nodes
1753 // ----------------------------
1755 for ( size_t iW = 0; iW < wires.size(); ++iW )
1757 StdMeshers_FaceSidePtr wire = wires[ iW ];
1758 if ( wire->MissVertexNode() )
1760 // Commented for issue 0020960. It worked for the case, let's wait for case where it doesn't.
1761 // It seems that there is no reason for this limitation
1763 // (new SMESH_ComputeError(COMPERR_BAD_INPUT_MESH, "Missing nodes on vertices"));
1765 const vector<UVPtStruct>& uvPtVec = wire->GetUVPtStruct();
1766 if ((int) uvPtVec.size() != wire->NbPoints() )
1767 return SMESH_ComputeError::New(COMPERR_BAD_INPUT_MESH,
1768 SMESH_Comment("Unexpected nb of points on wire ") << iW
1769 << ": " << uvPtVec.size()<<" != "<<wire->NbPoints());
1770 nbNodes += wire->NbPoints();
1772 nodeVec.reserve( nodeVec.size() + nbNodes + 1 );
1773 if ( nodeVec.empty() )
1774 nodeVec.push_back( 0 );
1776 // -----------------
1778 // -----------------
1780 const bool wasNgMeshEmpty = ( ngMesh.GetNP() < 1 ); /* true => this method is called by
1781 NETGENPlugin_NETGEN_2D_ONLY */
1783 // map for nodes on vertices since they can be shared between wires
1784 // ( issue 0020676, face_int_box.brep) and nodes built by NETGEN
1785 map<const SMDS_MeshNode*, int > node2ngID;
1786 if ( !wasNgMeshEmpty ) // fill node2ngID with nodes built by NETGEN
1788 set< int > subIDs; // ids of sub-shapes of the FACE
1789 for ( size_t iW = 0; iW < wires.size(); ++iW )
1791 StdMeshers_FaceSidePtr wire = wires[ iW ];
1792 for ( int iE = 0, nbE = wire->NbEdges(); iE < nbE; ++iE )
1794 subIDs.insert( wire->EdgeID( iE ));
1795 subIDs.insert( helper.GetMeshDS()->ShapeToIndex( wire->FirstVertex( iE )));
1798 for ( size_t ngID = 1; ngID < nodeVec.size(); ++ngID )
1799 if ( subIDs.count( nodeVec[ngID]->getshapeId() ))
1800 node2ngID.insert( make_pair( nodeVec[ngID], ngID ));
1803 const int solidID = 0, faceID = geom.fmap.FindIndex( helper.GetSubShape() );
1804 if ( ngMesh.GetNFD() < 1 )
1805 ngMesh.AddFaceDescriptor( netgen::FaceDescriptor( faceID, solidID, solidID, 0 ));
1807 for ( size_t iW = 0; iW < wires.size(); ++iW )
1809 StdMeshers_FaceSidePtr wire = wires[ iW ];
1810 const vector<UVPtStruct>& uvPtVec = wire->GetUVPtStruct();
1811 const int nbSegments = wire->NbPoints() - 1;
1813 // assure the 1st node to be in node2ngID, which is needed to correctly
1814 // "close chain of segments" (see below) in case if the 1st node is not
1815 // onVertex because it is on a Viscous layer
1816 node2ngID.insert( make_pair( uvPtVec[ 0 ].node, ngMesh.GetNP() + 1 ));
1818 // compute length of every segment
1819 vector<double> segLen( nbSegments );
1820 for ( int i = 0; i < nbSegments; ++i )
1821 segLen[i] = SMESH_TNodeXYZ( uvPtVec[ i ].node ).Distance( uvPtVec[ i+1 ].node );
1823 int edgeID = 1, posID = -2;
1824 bool isInternalWire = false;
1825 double vertexNormPar = 0;
1826 //const int prevNbNGSeg = ngMesh.GetNSeg();
1827 for ( int i = 0; i < nbSegments; ++i ) // loop on segments
1829 // Add the first point of a segment
1831 const SMDS_MeshNode * n = uvPtVec[ i ].node;
1832 const int posShapeID = n->getshapeId();
1833 bool onVertex = ( n->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX );
1834 bool onEdge = ( n->GetPosition()->GetTypeOfPosition() == SMDS_TOP_EDGE );
1836 // skip nodes on degenerated edges
1837 if ( helper.IsDegenShape( posShapeID ) &&
1838 helper.IsDegenShape( uvPtVec[ i+1 ].node->getshapeId() ))
1841 int ngID1 = ngMesh.GetNP() + 1, ngID2 = ngID1+1;
1842 if ( onVertex || ( !wasNgMeshEmpty && onEdge ) || helper.IsRealSeam( posShapeID ))
1843 ngID1 = node2ngID.insert( make_pair( n, ngID1 )).first->second;
1844 if ( ngID1 > ngMesh.GetNP() )
1846 netgen::MeshPoint mp( netgen::Point<3> (n->X(), n->Y(), n->Z()) );
1847 ngMesh.AddPoint ( mp, 1, netgen::EDGEPOINT );
1848 nodeVec.push_back( n );
1850 else // n is in ngMesh already, and ngID2 in prev segment is wrong
1852 ngID2 = ngMesh.GetNP() + 1;
1853 if ( i > 0 ) // prev segment belongs to same wire
1855 netgen::Segment& prevSeg = ngMesh.LineSegment( ngMesh.GetNSeg() );
1862 netgen::Segment seg;
1864 seg[0] = ngID1; // ng node id
1865 seg[1] = ngID2; // ng node id
1866 seg.edgenr = ngMesh.GetNSeg() + 1; // ng segment id
1867 seg.si = faceID; // = geom.fmap.FindIndex (face);
1869 for ( int iEnd = 0; iEnd < 2; ++iEnd)
1871 const UVPtStruct& pnt = uvPtVec[ i + iEnd ];
1873 seg.epgeominfo[ iEnd ].dist = pnt.param; // param on curve
1874 seg.epgeominfo[ iEnd ].u = pnt.u;
1875 seg.epgeominfo[ iEnd ].v = pnt.v;
1877 // find out edge id and node parameter on edge
1878 onVertex = ( pnt.normParam + 1e-10 > vertexNormPar );
1879 if ( onVertex || posShapeID != posID )
1882 double normParam = pnt.normParam;
1884 normParam = 0.5 * ( uvPtVec[ i ].normParam + uvPtVec[ i+1 ].normParam );
1885 int edgeIndexInWire = wire->EdgeIndex( normParam );
1886 vertexNormPar = wire->LastParameter( edgeIndexInWire );
1887 const TopoDS_Edge& edge = wire->Edge( edgeIndexInWire );
1888 edgeID = geom.emap.FindIndex( edge );
1890 isInternalWire = ( edge.Orientation() == TopAbs_INTERNAL );
1891 // if ( onVertex ) // param on curve is different on each of two edges
1892 // seg.epgeominfo[ iEnd ].dist = helper.GetNodeU( edge, pnt.node );
1894 seg.epgeominfo[ iEnd ].edgenr = edgeID; // = geom.emap.FindIndex(edge);
1897 ngMesh.AddSegment (seg);
1899 // restrict size of elements near the segment
1900 SMESH_TNodeXYZ np1( n ), np2( uvPtVec[ i+1 ].node );
1901 // get an average size of adjacent segments to avoid sharp change of
1902 // element size (regression on issue 0020452, note 0010898)
1903 int iPrev = SMESH_MesherHelper::WrapIndex( i-1, nbSegments );
1904 int iNext = SMESH_MesherHelper::WrapIndex( i+1, nbSegments );
1905 double sumH = segLen[ iPrev ] + segLen[ i ] + segLen[ iNext ];
1906 int nbSeg = ( int( segLen[ iPrev ] > sumH / 100.) +
1907 int( segLen[ i ] > sumH / 100.) +
1908 int( segLen[ iNext ] > sumH / 100.));
1910 RestrictLocalSize( ngMesh, 0.5*(np1+np2), sumH / nbSeg, overrideMinH );
1912 if ( isInternalWire )
1914 swap (seg[0], seg[1]);
1915 swap( seg.epgeominfo[0], seg.epgeominfo[1] );
1916 seg.edgenr = ngMesh.GetNSeg() + 1; // segment id
1917 ngMesh.AddSegment (seg);
1919 } // loop on segments on a wire
1921 // close chain of segments
1922 if ( nbSegments > 0 )
1924 netgen::Segment& lastSeg = ngMesh.LineSegment( ngMesh.GetNSeg() - int( isInternalWire ));
1925 const SMDS_MeshNode * lastNode = uvPtVec.back().node;
1926 lastSeg[1] = node2ngID.insert( make_pair( lastNode, lastSeg[1] )).first->second;
1927 if ( lastSeg[1] > ngMesh.GetNP() )
1929 netgen::MeshPoint mp( netgen::Point<3> (lastNode->X(), lastNode->Y(), lastNode->Z()) );
1930 ngMesh.AddPoint ( mp, 1, netgen::EDGEPOINT );
1931 nodeVec.push_back( lastNode );
1933 if ( isInternalWire )
1935 netgen::Segment& realLastSeg = ngMesh.LineSegment( ngMesh.GetNSeg() );
1936 realLastSeg[0] = lastSeg[1];
1940 #ifdef DUMP_SEGMENTS
1941 cout << "BEGIN WIRE " << iW << endl;
1942 for ( int i = prevNbNGSeg+1; i <= ngMesh.GetNSeg(); ++i )
1944 netgen::Segment& seg = ngMesh.LineSegment( i );
1946 netgen::Segment& prevSeg = ngMesh.LineSegment( i-1 );
1947 if ( seg[0] == prevSeg[1] && seg[1] == prevSeg[0] )
1949 cout << "Segment: " << seg.edgenr << endl << "\tis REVRESE of the previous one" << endl;
1953 cout << "Segment: " << seg.edgenr << endl
1954 << "\tp1: " << seg[0] << " n" << nodeVec[ seg[0]]->GetID() << endl
1955 << "\tp2: " << seg[1] << " n" << nodeVec[ seg[1]]->GetID() << endl
1956 << "\tp0 param: " << seg.epgeominfo[ 0 ].dist << endl
1957 << "\tp0 uv: " << seg.epgeominfo[ 0 ].u <<", "<< seg.epgeominfo[ 0 ].v << endl
1958 << "\tp0 edge: " << seg.epgeominfo[ 0 ].edgenr << endl
1959 << "\tp1 param: " << seg.epgeominfo[ 1 ].dist << endl
1960 << "\tp1 uv: " << seg.epgeominfo[ 1 ].u <<", "<< seg.epgeominfo[ 1 ].v << endl
1961 << "\tp1 edge: " << seg.epgeominfo[ 1 ].edgenr << endl;
1963 cout << "--END WIRE " << iW << endl;
1966 } // loop on WIREs of a FACE
1968 // add a segment instead of an internal vertex
1969 if ( wasNgMeshEmpty )
1971 NETGENPlugin_Internals intShapes( *helper.GetMesh(), helper.GetSubShape(), /*is3D=*/false );
1972 AddIntVerticesInFaces( geom, ngMesh, nodeVec, intShapes );
1974 ngMesh.CalcSurfacesOfNode();
1979 //================================================================================
1981 * \brief Fill SMESH mesh according to contents of netgen mesh
1982 * \param occgeo - container of OCCT geometry to mesh
1983 * \param ngMesh - netgen mesh
1984 * \param initState - bn of entities in netgen mesh before computing
1985 * \param sMesh - SMESH mesh to fill in
1986 * \param nodeVec - vector of nodes in which node index == netgen ID
1987 * \param comment - returns problem description
1988 * \param quadHelper - holder of medium nodes of sub-meshes
1989 * \retval int - error
1991 //================================================================================
1993 int NETGENPlugin_Mesher::FillSMesh(const netgen::OCCGeometry& occgeo,
1994 netgen::Mesh& ngMesh,
1995 const NETGENPlugin_ngMeshInfo& initState,
1997 std::vector<const SMDS_MeshNode*>& nodeVec,
1998 SMESH_Comment& comment,
1999 SMESH_MesherHelper* quadHelper)
2001 int nbNod = ngMesh.GetNP();
2002 int nbSeg = ngMesh.GetNSeg();
2003 int nbFac = ngMesh.GetNSE();
2004 int nbVol = ngMesh.GetNE();
2006 SMESHDS_Mesh* meshDS = sMesh.GetMeshDS();
2008 // quadHelper is used for either
2009 // 1) making quadratic elements when a lower dimention mesh is loaded
2010 // to SMESH before convertion to quadratic by NETGEN
2011 // 2) sewing of quadratic elements with quadratic elements of sub-meshes
2012 if ( quadHelper && !quadHelper->GetIsQuadratic() && quadHelper->GetTLinkNodeMap().empty() )
2015 // -------------------------------------
2016 // Create and insert nodes into nodeVec
2017 // -------------------------------------
2019 nodeVec.resize( nbNod + 1 );
2020 int i, nbInitNod = initState._nbNodes;
2021 for (i = nbInitNod+1; i <= nbNod; ++i )
2023 const netgen::MeshPoint& ngPoint = ngMesh.Point(i);
2024 SMDS_MeshNode* node = NULL;
2025 TopoDS_Vertex aVert;
2026 // First, netgen creates nodes on vertices in occgeo.vmap,
2027 // so node index corresponds to vertex index
2028 // but (issue 0020776) netgen does not create nodes with equal coordinates
2029 if ( i-nbInitNod <= occgeo.vmap.Extent() )
2031 gp_Pnt p ( NGPOINT_COORDS(ngPoint) );
2032 for (int iV = i-nbInitNod; aVert.IsNull() && iV <= occgeo.vmap.Extent(); ++iV)
2034 aVert = TopoDS::Vertex( occgeo.vmap( iV ));
2035 gp_Pnt pV = BRep_Tool::Pnt( aVert );
2036 if ( p.SquareDistance( pV ) > 1e-20 )
2039 node = const_cast<SMDS_MeshNode*>( SMESH_Algo::VertexNode( aVert, meshDS ));
2042 if (!node) // node not found on vertex
2044 node = meshDS->AddNode( NGPOINT_COORDS( ngPoint ));
2045 if (!aVert.IsNull())
2046 meshDS->SetNodeOnVertex(node, aVert);
2051 // -------------------------------------------
2052 // Create mesh segments along geometric edges
2053 // -------------------------------------------
2055 int nbInitSeg = initState._nbSegments;
2056 for (i = nbInitSeg+1; i <= nbSeg; ++i )
2058 const netgen::Segment& seg = ngMesh.LineSegment(i);
2060 int pinds[3] = { seg.pnums[0], seg.pnums[1], seg.pnums[2] };
2063 for (int j=0; j < 3; ++j)
2065 int pind = pinds[j];
2066 if (pind <= 0 || !nodeVec_ACCESS(pind))
2074 int aGeomEdgeInd = seg.epgeominfo[j].edgenr;
2075 if (aGeomEdgeInd > 0 && aGeomEdgeInd <= occgeo.emap.Extent())
2076 aEdge = TopoDS::Edge(occgeo.emap(aGeomEdgeInd));
2078 param = seg.epgeominfo[j].dist;
2081 else // middle point
2083 param = param2 * 0.5;
2085 if (!aEdge.IsNull() && nodeVec_ACCESS(pind)->getshapeId() < 1)
2087 meshDS->SetNodeOnEdge(nodeVec_ACCESS(pind), aEdge, param);
2092 SMDS_MeshEdge* edge = 0;
2093 if (nbp == 2) // second order ?
2095 if ( meshDS->FindEdge( nodeVec_ACCESS(pinds[0]), nodeVec_ACCESS(pinds[1])))
2097 if ( quadHelper ) // final mesh must be quadratic
2098 edge = quadHelper->AddEdge(nodeVec_ACCESS(pinds[0]), nodeVec_ACCESS(pinds[1]));
2100 edge = meshDS->AddEdge(nodeVec_ACCESS(pinds[0]), nodeVec_ACCESS(pinds[1]));
2104 if ( meshDS->FindEdge( nodeVec_ACCESS(pinds[0]), nodeVec_ACCESS(pinds[1]),
2105 nodeVec_ACCESS(pinds[2])))
2107 edge = meshDS->AddEdge(nodeVec_ACCESS(pinds[0]), nodeVec_ACCESS(pinds[1]),
2108 nodeVec_ACCESS(pinds[2]));
2112 if ( comment.empty() ) comment << "Cannot create a mesh edge";
2113 MESSAGE("Cannot create a mesh edge");
2114 nbSeg = nbFac = nbVol = 0;
2117 if ( !aEdge.IsNull() && edge->getshapeId() < 1 )
2118 meshDS->SetMeshElementOnShape(edge, aEdge);
2120 else if ( comment.empty() )
2122 comment << "Invalid netgen segment #" << i;
2126 // ----------------------------------------
2127 // Create mesh faces along geometric faces
2128 // ----------------------------------------
2130 int nbInitFac = initState._nbFaces;
2131 int quadFaceID = ngMesh.GetNFD() + 1;
2132 if ( nbInitFac < nbFac )
2133 // add a faces descriptor to exclude qudrangle elements generated by NETGEN
2134 // from computation of 3D mesh
2135 ngMesh.AddFaceDescriptor (netgen::FaceDescriptor(quadFaceID, /*solid1=*/0, /*solid2=*/0, 0));
2137 vector<const SMDS_MeshNode*> nodes;
2138 for (i = nbInitFac+1; i <= nbFac; ++i )
2140 const netgen::Element2d& elem = ngMesh.SurfaceElement(i);
2141 const int aGeomFaceInd = elem.GetIndex();
2143 if (aGeomFaceInd > 0 && aGeomFaceInd <= occgeo.fmap.Extent())
2144 aFace = TopoDS::Face(occgeo.fmap(aGeomFaceInd));
2146 for ( int j = 1; j <= elem.GetNP(); ++j )
2148 int pind = elem.PNum(j);
2149 if ( pind < 1 || pind >= (int) nodeVec.size() )
2151 if ( SMDS_MeshNode* node = nodeVec_ACCESS(pind))
2153 nodes.push_back( node );
2154 if (!aFace.IsNull() && node->getshapeId() < 1)
2156 const netgen::PointGeomInfo& pgi = elem.GeomInfoPi(j);
2157 meshDS->SetNodeOnFace(node, aFace, pgi.u, pgi.v);
2161 if ((int) nodes.size() != elem.GetNP() )
2163 if ( comment.empty() )
2164 comment << "Invalid netgen 2d element #" << i;
2165 continue; // bad node ids
2167 SMDS_MeshFace* face = NULL;
2168 switch (elem.GetType())
2171 if ( quadHelper ) // final mesh must be quadratic
2172 face = quadHelper->AddFace(nodes[0],nodes[1],nodes[2]);
2174 face = meshDS->AddFace(nodes[0],nodes[1],nodes[2]);
2177 if ( quadHelper ) // final mesh must be quadratic
2178 face = quadHelper->AddFace(nodes[0],nodes[1],nodes[2],nodes[3]);
2180 face = meshDS->AddFace(nodes[0],nodes[1],nodes[2],nodes[3]);
2181 // exclude qudrangle elements from computation of 3D mesh
2182 const_cast< netgen::Element2d& >( elem ).SetIndex( quadFaceID );
2185 nodes[5] = mediumNode( nodes[0],nodes[1],nodes[5], quadHelper );
2186 nodes[3] = mediumNode( nodes[1],nodes[2],nodes[3], quadHelper );
2187 nodes[4] = mediumNode( nodes[2],nodes[0],nodes[4], quadHelper );
2188 face = meshDS->AddFace(nodes[0],nodes[1],nodes[2],nodes[5],nodes[3],nodes[4]);
2191 nodes[4] = mediumNode( nodes[0],nodes[1],nodes[4], quadHelper );
2192 nodes[7] = mediumNode( nodes[1],nodes[2],nodes[7], quadHelper );
2193 nodes[5] = mediumNode( nodes[2],nodes[3],nodes[5], quadHelper );
2194 nodes[6] = mediumNode( nodes[3],nodes[0],nodes[6], quadHelper );
2195 face = meshDS->AddFace(nodes[0],nodes[1],nodes[2],nodes[3],
2196 nodes[4],nodes[7],nodes[5],nodes[6]);
2197 // exclude qudrangle elements from computation of 3D mesh
2198 const_cast< netgen::Element2d& >( elem ).SetIndex( quadFaceID );
2201 MESSAGE("NETGEN created a face of unexpected type, ignoring");
2206 if ( comment.empty() ) comment << "Cannot create a mesh face";
2207 MESSAGE("Cannot create a mesh face");
2208 nbSeg = nbFac = nbVol = 0;
2211 if ( !aFace.IsNull() )
2212 meshDS->SetMeshElementOnShape( face, aFace );
2215 // ------------------
2216 // Create tetrahedra
2217 // ------------------
2219 for ( i = 1; i <= nbVol; ++i )
2221 const netgen::Element& elem = ngMesh.VolumeElement(i);
2222 int aSolidInd = elem.GetIndex();
2223 TopoDS_Solid aSolid;
2224 if ( aSolidInd > 0 && aSolidInd <= occgeo.somap.Extent() )
2225 aSolid = TopoDS::Solid(occgeo.somap(aSolidInd));
2227 for ( int j = 1; j <= elem.GetNP(); ++j )
2229 int pind = elem.PNum(j);
2230 if ( pind < 1 || pind >= (int)nodeVec.size() )
2232 if ( SMDS_MeshNode* node = nodeVec_ACCESS(pind) )
2234 nodes.push_back(node);
2235 if ( !aSolid.IsNull() && node->getshapeId() < 1 )
2236 meshDS->SetNodeInVolume(node, aSolid);
2239 if ((int) nodes.size() != elem.GetNP() )
2241 if ( comment.empty() )
2242 comment << "Invalid netgen 3d element #" << i;
2245 SMDS_MeshVolume* vol = NULL;
2246 switch ( elem.GetType() )
2249 vol = meshDS->AddVolume(nodes[0],nodes[1],nodes[2],nodes[3]);
2252 nodes[4] = mediumNode( nodes[0],nodes[1],nodes[4], quadHelper );
2253 nodes[7] = mediumNode( nodes[1],nodes[2],nodes[7], quadHelper );
2254 nodes[5] = mediumNode( nodes[2],nodes[0],nodes[5], quadHelper );
2255 nodes[6] = mediumNode( nodes[0],nodes[3],nodes[6], quadHelper );
2256 nodes[8] = mediumNode( nodes[1],nodes[3],nodes[8], quadHelper );
2257 nodes[9] = mediumNode( nodes[2],nodes[3],nodes[9], quadHelper );
2258 vol = meshDS->AddVolume(nodes[0],nodes[1],nodes[2],nodes[3],
2259 nodes[4],nodes[7],nodes[5],nodes[6],nodes[8],nodes[9]);
2262 MESSAGE("NETGEN created a volume of unexpected type, ignoring");
2267 if ( comment.empty() ) comment << "Cannot create a mesh volume";
2268 MESSAGE("Cannot create a mesh volume");
2269 nbSeg = nbFac = nbVol = 0;
2272 if (!aSolid.IsNull())
2273 meshDS->SetMeshElementOnShape(vol, aSolid);
2275 return comment.empty() ? 0 : 1;
2280 //================================================================================
2282 * \brief Restrict size of elements on the given edge
2284 //================================================================================
2286 void setLocalSize(const TopoDS_Edge& edge,
2290 if ( size <= std::numeric_limits<double>::min() )
2292 Standard_Real u1, u2;
2293 Handle(Geom_Curve) curve = BRep_Tool::Curve(edge, u1, u2);
2294 if ( curve.IsNull() )
2296 TopoDS_Iterator vIt( edge );
2297 if ( !vIt.More() ) return;
2298 gp_Pnt p = BRep_Tool::Pnt( TopoDS::Vertex( vIt.Value() ));
2299 NETGENPlugin_Mesher::RestrictLocalSize( mesh, p.XYZ(), size );
2303 const int nb = (int)( 1.5 * SMESH_Algo::EdgeLength( edge ) / size );
2304 Standard_Real delta = (u2-u1)/nb;
2305 for(int i=0; i<nb; i++)
2307 Standard_Real u = u1 + delta*i;
2308 gp_Pnt p = curve->Value(u);
2309 NETGENPlugin_Mesher::RestrictLocalSize( mesh, p.XYZ(), size );
2310 netgen::Point3d pi(p.X(), p.Y(), p.Z());
2311 double resultSize = mesh.GetH(pi);
2312 if ( resultSize - size > 0.1*size )
2313 // netgen does restriction iff oldH/newH > 1.2 (localh.cpp:136)
2314 NETGENPlugin_Mesher::RestrictLocalSize( mesh, p.XYZ(), resultSize/1.201 );
2319 //================================================================================
2321 * \brief Convert error into text
2323 //================================================================================
2325 std::string text(int err)
2330 SMESH_Comment("Error in netgen::OCCGenerateMesh() at ") << netgen::multithread.task;
2333 //================================================================================
2335 * \brief Convert exception into text
2337 //================================================================================
2339 std::string text(Standard_Failure& ex)
2341 SMESH_Comment str("Exception in netgen::OCCGenerateMesh()");
2342 str << " at " << netgen::multithread.task
2343 << ": " << ex.DynamicType()->Name();
2344 if ( ex.GetMessageString() && strlen( ex.GetMessageString() ))
2345 str << ": " << ex.GetMessageString();
2348 //================================================================================
2350 * \brief Convert exception into text
2352 //================================================================================
2354 std::string text(netgen::NgException& ex)
2356 SMESH_Comment str("NgException");
2357 if ( strlen( netgen::multithread.task ) > 0 )
2358 str << " at " << netgen::multithread.task;
2359 str << ": " << ex.What();
2363 //================================================================================
2365 * \brief Looks for triangles lying on a SOLID
2367 //================================================================================
2369 bool hasBadElemOnSolid( const list<const SMDS_MeshElement*>& elems,
2370 SMESH_subMesh* solidSM )
2372 TopTools_IndexedMapOfShape solidSubs;
2373 TopExp::MapShapes( solidSM->GetSubShape(), solidSubs );
2374 SMESHDS_Mesh* mesh = solidSM->GetFather()->GetMeshDS();
2376 list<const SMDS_MeshElement*>::const_iterator e = elems.begin();
2377 for ( ; e != elems.end(); ++e )
2379 const SMDS_MeshElement* elem = *e;
2380 // if ( elem->GetType() != SMDSAbs_Face ) -- 23047
2382 int nbNodesOnSolid = 0, nbNodes = elem->NbNodes();
2383 SMDS_NodeIteratorPtr nIt = elem->nodeIterator();
2384 while ( nIt->more() )
2386 const SMDS_MeshNode* n = nIt->next();
2387 const TopoDS_Shape& s = mesh->IndexToShape( n->getshapeId() );
2388 nbNodesOnSolid += ( !s.IsNull() && solidSubs.Contains( s ));
2389 if ( nbNodesOnSolid > 2 ||
2390 nbNodesOnSolid == nbNodes)
2397 const double edgeMeshingTime = 0.001;
2398 const double faceMeshingTime = 0.019;
2399 const double edgeFaceMeshingTime = edgeMeshingTime + faceMeshingTime;
2400 const double faceOptimizTime = 0.06;
2401 const double voluMeshingTime = 0.15;
2402 const double volOptimizeTime = 0.77;
2405 //=============================================================================
2407 * Here we are going to use the NETGEN mesher
2409 //=============================================================================
2411 bool NETGENPlugin_Mesher::Compute()
2413 NETGENPlugin_NetgenLibWrapper ngLib;
2415 netgen::MeshingParameters& mparams = netgen::mparam;
2416 MESSAGE("Compute with:\n"
2417 " max size = " << mparams.maxh << "\n"
2418 " segments per edge = " << mparams.segmentsperedge);
2420 " growth rate = " << mparams.grading << "\n"
2421 " elements per radius = " << mparams.curvaturesafety << "\n"
2422 " second order = " << mparams.secondorder << "\n"
2423 " quad allowed = " << mparams.quad << "\n"
2424 " surface curvature = " << mparams.uselocalh << "\n"
2425 " fuse edges = " << netgen::merge_solids);
2427 SMESH_ComputeErrorPtr error = SMESH_ComputeError::New();
2428 SMESH_MesherHelper quadHelper( *_mesh );
2429 quadHelper.SetIsQuadratic( mparams.secondorder );
2431 static string debugFile = "/tmp/ngMesh.py"; /* to call toPython( _ngMesh, debugFile )
2432 while debugging netgen */
2433 // -------------------------
2434 // Prepare OCC geometry
2435 // -------------------------
2437 netgen::OCCGeometry occgeo;
2438 list< SMESH_subMesh* > meshedSM[3]; // for 0-2 dimensions
2439 NETGENPlugin_Internals internals( *_mesh, _shape, _isVolume );
2440 PrepareOCCgeometry( occgeo, _shape, *_mesh, meshedSM, &internals );
2443 _totalTime = edgeFaceMeshingTime;
2445 _totalTime += faceOptimizTime;
2447 _totalTime += voluMeshingTime + ( _optimize ? volOptimizeTime : 0 );
2448 double doneTime = 0;
2451 _curShapeIndex = -1;
2453 // -------------------------
2454 // Generate the mesh
2455 // -------------------------
2458 NETGENPlugin_ngMeshInfo initState; // it remembers size of ng mesh equal to size of Smesh
2460 SMESH_Comment comment;
2463 // vector of nodes in which node index == netgen ID
2464 vector< const SMDS_MeshNode* > nodeVec;
2472 // not to RestrictLocalH() according to curvature during MESHCONST_ANALYSE
2473 mparams.uselocalh = false;
2474 mparams.grading = 0.8; // not limitited size growth
2476 if ( _simpleHyp->GetNumberOfSegments() )
2478 mparams.maxh = occgeo.boundingbox.Diam();
2481 mparams.maxh = _simpleHyp->GetLocalLength();
2484 if ( mparams.maxh == 0.0 )
2485 mparams.maxh = occgeo.boundingbox.Diam();
2486 if ( _simpleHyp || ( mparams.minh == 0.0 && _fineness != NETGENPlugin_Hypothesis::UserDefined))
2487 mparams.minh = GetDefaultMinSize( _shape, mparams.maxh );
2489 // Local size on faces
2490 occgeo.face_maxh = mparams.maxh;
2492 // Let netgen create _ngMesh and calculate element size on not meshed shapes
2496 int startWith = netgen::MESHCONST_ANALYSE;
2497 int endWith = netgen::MESHCONST_ANALYSE;
2502 err = netgen::OCCGenerateMesh(occgeo, _ngMesh, mparams, startWith, endWith);
2504 err = netgen::OCCGenerateMesh(occgeo, _ngMesh, startWith, endWith, optstr);
2506 if(netgen::multithread.terminate)
2509 comment << text(err);
2511 catch (Standard_Failure& ex)
2513 comment << text(ex);
2515 err = 0; //- MESHCONST_ANALYSE isn't so important step
2518 ngLib.setMesh(( Ng_Mesh*) _ngMesh );
2520 _ngMesh->ClearFaceDescriptors(); // we make descriptors our-self
2524 // Pass 1D simple parameters to NETGEN
2525 // --------------------------------
2526 int nbSeg = _simpleHyp->GetNumberOfSegments();
2527 double segSize = _simpleHyp->GetLocalLength();
2528 for ( int iE = 1; iE <= occgeo.emap.Extent(); ++iE )
2530 const TopoDS_Edge& e = TopoDS::Edge( occgeo.emap(iE));
2532 segSize = SMESH_Algo::EdgeLength( e ) / ( nbSeg - 0.4 );
2533 setLocalSize( e, segSize, *_ngMesh );
2536 else // if ( ! _simpleHyp )
2538 // Local size on vertices and edges
2539 // --------------------------------
2540 for(std::map<int,double>::const_iterator it=EdgeId2LocalSize.begin(); it!=EdgeId2LocalSize.end(); it++)
2542 int key = (*it).first;
2543 double hi = (*it).second;
2544 const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
2545 const TopoDS_Edge& e = TopoDS::Edge(shape);
2546 setLocalSize( e, hi, *_ngMesh );
2548 for(std::map<int,double>::const_iterator it=VertexId2LocalSize.begin(); it!=VertexId2LocalSize.end(); it++)
2550 int key = (*it).first;
2551 double hi = (*it).second;
2552 const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
2553 const TopoDS_Vertex& v = TopoDS::Vertex(shape);
2554 gp_Pnt p = BRep_Tool::Pnt(v);
2555 NETGENPlugin_Mesher::RestrictLocalSize( *_ngMesh, p.XYZ(), hi );
2557 for(map<int,double>::const_iterator it=FaceId2LocalSize.begin();
2558 it!=FaceId2LocalSize.end(); it++)
2560 int key = (*it).first;
2561 double val = (*it).second;
2562 const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
2563 int faceNgID = occgeo.fmap.FindIndex(shape);
2564 occgeo.SetFaceMaxH(faceNgID, val);
2565 for ( TopExp_Explorer edgeExp( shape, TopAbs_EDGE ); edgeExp.More(); edgeExp.Next() )
2566 setLocalSize( TopoDS::Edge( edgeExp.Current() ), val, *_ngMesh );
2570 // Precompute internal edges (issue 0020676) in order to
2571 // add mesh on them correctly (twice) to netgen mesh
2572 if ( !err && internals.hasInternalEdges() )
2574 // load internal shapes into OCCGeometry
2575 netgen::OCCGeometry intOccgeo;
2576 internals.getInternalEdges( intOccgeo.fmap, intOccgeo.emap, intOccgeo.vmap, meshedSM );
2577 intOccgeo.boundingbox = occgeo.boundingbox;
2578 intOccgeo.shape = occgeo.shape;
2579 intOccgeo.face_maxh.SetSize(intOccgeo.fmap.Extent());
2580 intOccgeo.face_maxh = netgen::mparam.maxh;
2581 netgen::Mesh *tmpNgMesh = NULL;
2585 // compute local H on internal shapes in the main mesh
2586 //OCCSetLocalMeshSize(intOccgeo, *_ngMesh); it deletes _ngMesh->localH
2588 // let netgen create a temporary mesh
2590 netgen::OCCGenerateMesh(intOccgeo, tmpNgMesh, mparams, startWith, endWith);
2592 netgen::OCCGenerateMesh(intOccgeo, tmpNgMesh, startWith, endWith, optstr);
2594 if(netgen::multithread.terminate)
2597 // copy LocalH from the main to temporary mesh
2598 initState.transferLocalH( _ngMesh, tmpNgMesh );
2600 // compute mesh on internal edges
2601 startWith = endWith = netgen::MESHCONST_MESHEDGES;
2603 err = netgen::OCCGenerateMesh(intOccgeo, tmpNgMesh, mparams, startWith, endWith);
2605 err = netgen::OCCGenerateMesh(intOccgeo, tmpNgMesh, startWith, endWith, optstr);
2607 comment << text(err);
2609 catch (Standard_Failure& ex)
2611 comment << text(ex);
2614 initState.restoreLocalH( tmpNgMesh );
2616 // fill SMESH by netgen mesh
2617 vector< const SMDS_MeshNode* > tmpNodeVec;
2618 FillSMesh( intOccgeo, *tmpNgMesh, initState, *_mesh, tmpNodeVec, comment );
2619 err = ( err || !comment.empty() );
2621 nglib::Ng_DeleteMesh((nglib::Ng_Mesh*)tmpNgMesh);
2624 // Fill _ngMesh with nodes and segments of computed submeshes
2627 err = ! ( FillNgMesh(occgeo, *_ngMesh, nodeVec, meshedSM[ MeshDim_0D ]) &&
2628 FillNgMesh(occgeo, *_ngMesh, nodeVec, meshedSM[ MeshDim_1D ], &quadHelper));
2630 initState = NETGENPlugin_ngMeshInfo(_ngMesh);
2635 startWith = endWith = netgen::MESHCONST_MESHEDGES;
2640 err = netgen::OCCGenerateMesh(occgeo, _ngMesh, mparams, startWith, endWith);
2642 err = netgen::OCCGenerateMesh(occgeo, _ngMesh, startWith, endWith, optstr);
2644 if(netgen::multithread.terminate)
2647 comment << text(err);
2649 catch (Standard_Failure& ex)
2651 comment << text(ex);
2656 _ticTime = ( doneTime += edgeMeshingTime ) / _totalTime / _progressTic;
2658 mparams.uselocalh = true; // restore as it is used at surface optimization
2660 // ---------------------
2661 // compute surface mesh
2662 // ---------------------
2665 // Pass 2D simple parameters to NETGEN
2667 if ( double area = _simpleHyp->GetMaxElementArea() ) {
2669 mparams.maxh = sqrt(2. * area/sqrt(3.0));
2670 mparams.grading = 0.4; // moderate size growth
2673 // length from edges
2674 if ( _ngMesh->GetNSeg() ) {
2675 double edgeLength = 0;
2676 TopTools_MapOfShape visitedEdges;
2677 for ( TopExp_Explorer exp( _shape, TopAbs_EDGE ); exp.More(); exp.Next() )
2678 if( visitedEdges.Add(exp.Current()) )
2679 edgeLength += SMESH_Algo::EdgeLength( TopoDS::Edge( exp.Current() ));
2680 // we have to multiply length by 2 since for each TopoDS_Edge there
2681 // are double set of NETGEN edges, in other words, we have to
2682 // divide _ngMesh->GetNSeg() by 2.
2683 mparams.maxh = 2*edgeLength / _ngMesh->GetNSeg();
2686 mparams.maxh = 1000;
2688 mparams.grading = 0.2; // slow size growth
2690 mparams.quad = _simpleHyp->GetAllowQuadrangles();
2691 mparams.maxh = min( mparams.maxh, occgeo.boundingbox.Diam()/2 );
2692 _ngMesh->SetGlobalH (mparams.maxh);
2693 netgen::Box<3> bb = occgeo.GetBoundingBox();
2694 bb.Increase (bb.Diam()/20);
2695 _ngMesh->SetLocalH (bb.PMin(), bb.PMax(), mparams.grading);
2698 // Care of vertices internal in faces (issue 0020676)
2699 if ( internals.hasInternalVertexInFace() )
2701 // store computed segments in SMESH in order not to create SMESH
2702 // edges for ng segments added by AddIntVerticesInFaces()
2703 FillSMesh( occgeo, *_ngMesh, initState, *_mesh, nodeVec, comment );
2704 // add segments to faces with internal vertices
2705 AddIntVerticesInFaces( occgeo, *_ngMesh, nodeVec, internals );
2706 initState = NETGENPlugin_ngMeshInfo(_ngMesh);
2709 // Build viscous layers
2710 if ( _isViscousLayers2D )
2712 if ( !internals.hasInternalVertexInFace() ) {
2713 FillSMesh( occgeo, *_ngMesh, initState, *_mesh, nodeVec, comment );
2714 initState = NETGENPlugin_ngMeshInfo(_ngMesh);
2716 SMESH_ProxyMesh::Ptr viscousMesh;
2717 SMESH_MesherHelper helper( *_mesh );
2718 for ( int faceID = 1; faceID <= occgeo.fmap.Extent(); ++faceID )
2720 const TopoDS_Face& F = TopoDS::Face( occgeo.fmap( faceID ));
2721 viscousMesh = StdMeshers_ViscousLayers2D::Compute( *_mesh, F );
2724 // exclude from computation ng segments built on EDGEs of F
2725 for (int i = 1; i <= _ngMesh->GetNSeg(); i++)
2727 netgen::Segment & seg = _ngMesh->LineSegment(i);
2728 if (seg.si == faceID)
2731 // add new segments to _ngMesh instead of excluded ones
2732 helper.SetSubShape( F );
2734 StdMeshers_FaceSide::GetFaceWires( F, *_mesh, /*skipMediumNodes=*/true,
2735 error, viscousMesh );
2736 error = AddSegmentsToMesh( *_ngMesh, occgeo, wires, helper, nodeVec );
2738 if ( !error ) error = SMESH_ComputeError::New();
2740 initState = NETGENPlugin_ngMeshInfo(_ngMesh);
2743 // Let netgen compute 2D mesh
2744 startWith = netgen::MESHCONST_MESHSURFACE;
2745 endWith = _optimize ? netgen::MESHCONST_OPTSURFACE : netgen::MESHCONST_MESHSURFACE;
2750 err = netgen::OCCGenerateMesh(occgeo, _ngMesh, mparams, startWith, endWith);
2752 err = netgen::OCCGenerateMesh(occgeo, _ngMesh, startWith, endWith, optstr);
2754 if(netgen::multithread.terminate)
2757 comment << text (err);
2759 catch (Standard_Failure& ex)
2761 comment << text(ex);
2762 //err = 1; -- try to make volumes anyway
2764 catch (netgen::NgException exc)
2766 comment << text(exc);
2767 //err = 1; -- try to make volumes anyway
2772 doneTime += faceMeshingTime + ( _optimize ? faceOptimizTime : 0 );
2773 _ticTime = doneTime / _totalTime / _progressTic;
2775 // ---------------------
2776 // generate volume mesh
2777 // ---------------------
2778 // Fill _ngMesh with nodes and faces of computed 2D submeshes
2779 if ( !err && _isVolume && ( !meshedSM[ MeshDim_2D ].empty() || mparams.quad ))
2781 // load SMESH with computed segments and faces
2782 FillSMesh( occgeo, *_ngMesh, initState, *_mesh, nodeVec, comment, &quadHelper );
2784 // compute pyramids on quadrangles
2785 SMESH_ProxyMesh::Ptr proxyMesh;
2786 if ( _mesh->NbQuadrangles() > 0 )
2787 for ( int iS = 1; iS <= occgeo.somap.Extent(); ++iS )
2789 StdMeshers_QuadToTriaAdaptor* Adaptor = new StdMeshers_QuadToTriaAdaptor;
2790 proxyMesh.reset( Adaptor );
2792 int nbPyrams = _mesh->NbPyramids();
2793 Adaptor->Compute( *_mesh, occgeo.somap(iS) );
2794 if ( nbPyrams != _mesh->NbPyramids() )
2796 list< SMESH_subMesh* > quadFaceSM;
2797 for (TopExp_Explorer face(occgeo.somap(iS), TopAbs_FACE); face.More(); face.Next())
2798 if ( Adaptor->GetProxySubMesh( face.Current() ))
2800 quadFaceSM.push_back( _mesh->GetSubMesh( face.Current() ));
2801 meshedSM[ MeshDim_2D ].remove( quadFaceSM.back() );
2803 FillNgMesh(occgeo, *_ngMesh, nodeVec, quadFaceSM, &quadHelper, proxyMesh);
2806 // fill _ngMesh with faces of sub-meshes
2807 err = ! ( FillNgMesh(occgeo, *_ngMesh, nodeVec, meshedSM[ MeshDim_2D ], &quadHelper));
2808 initState = NETGENPlugin_ngMeshInfo(_ngMesh);
2809 //toPython( _ngMesh, "/tmp/ngPython.py");
2811 if (!err && _isVolume)
2813 // Pass 3D simple parameters to NETGEN
2814 const NETGENPlugin_SimpleHypothesis_3D* simple3d =
2815 dynamic_cast< const NETGENPlugin_SimpleHypothesis_3D* > ( _simpleHyp );
2817 if ( double vol = simple3d->GetMaxElementVolume() ) {
2819 mparams.maxh = pow( 72, 1/6. ) * pow( vol, 1/3. );
2820 mparams.maxh = min( mparams.maxh, occgeo.boundingbox.Diam()/2 );
2823 // length from faces
2824 mparams.maxh = _ngMesh->AverageH();
2826 _ngMesh->SetGlobalH (mparams.maxh);
2827 mparams.grading = 0.4;
2829 _ngMesh->CalcLocalH(mparams.grading);
2831 _ngMesh->CalcLocalH();
2834 // Care of vertices internal in solids and internal faces (issue 0020676)
2835 if ( internals.hasInternalVertexInSolid() || internals.hasInternalFaces() )
2837 // store computed faces in SMESH in order not to create SMESH
2838 // faces for ng faces added here
2839 FillSMesh( occgeo, *_ngMesh, initState, *_mesh, nodeVec, comment, &quadHelper );
2840 // add ng faces to solids with internal vertices
2841 AddIntVerticesInSolids( occgeo, *_ngMesh, nodeVec, internals );
2842 // duplicate mesh faces on internal faces
2843 FixIntFaces( occgeo, *_ngMesh, internals );
2844 initState = NETGENPlugin_ngMeshInfo(_ngMesh);
2846 // Let netgen compute 3D mesh
2847 startWith = endWith = netgen::MESHCONST_MESHVOLUME;
2852 err = netgen::OCCGenerateMesh(occgeo, _ngMesh, mparams, startWith, endWith);
2854 err = netgen::OCCGenerateMesh(occgeo, _ngMesh, startWith, endWith, optstr);
2856 if(netgen::multithread.terminate)
2859 if ( comment.empty() ) // do not overwrite a previos error
2860 comment << text(err);
2862 catch (Standard_Failure& ex)
2864 if ( comment.empty() ) // do not overwrite a previos error
2865 comment << text(ex);
2868 catch (netgen::NgException exc)
2870 if ( comment.empty() ) // do not overwrite a previos error
2871 comment << text(exc);
2874 _ticTime = ( doneTime += voluMeshingTime ) / _totalTime / _progressTic;
2876 // Let netgen optimize 3D mesh
2877 if ( !err && _optimize )
2879 startWith = endWith = netgen::MESHCONST_OPTVOLUME;
2884 err = netgen::OCCGenerateMesh(occgeo, _ngMesh, mparams, startWith, endWith);
2886 err = netgen::OCCGenerateMesh(occgeo, _ngMesh, startWith, endWith, optstr);
2888 if(netgen::multithread.terminate)
2891 if ( comment.empty() ) // do not overwrite a previos error
2892 comment << text(err);
2894 catch (Standard_Failure& ex)
2896 if ( comment.empty() ) // do not overwrite a previos error
2897 comment << text(ex);
2899 catch (netgen::NgException exc)
2901 if ( comment.empty() ) // do not overwrite a previos error
2902 comment << text(exc);
2906 if (!err && mparams.secondorder > 0)
2911 if ( !meshedSM[ MeshDim_1D ].empty() )
2913 // remove segments not attached to geometry (IPAL0052479)
2914 for (int i = 1; i <= _ngMesh->GetNSeg(); ++i)
2916 const netgen::Segment & seg = _ngMesh->LineSegment (i);
2917 if ( seg.epgeominfo[ 0 ].edgenr == 0 )
2918 _ngMesh->DeleteSegment( i );
2920 _ngMesh->Compress();
2922 // convert to quadratic
2923 netgen::OCCRefinementSurfaces ref (occgeo);
2924 ref.MakeSecondOrder (*_ngMesh);
2926 // care of elements already loaded to SMESH
2927 // if ( initState._nbSegments > 0 )
2928 // makeQuadratic( occgeo.emap, _mesh );
2929 // if ( initState._nbFaces > 0 )
2930 // makeQuadratic( occgeo.fmap, _mesh );
2932 catch (Standard_Failure& ex)
2934 if ( comment.empty() ) // do not overwrite a previos error
2935 comment << "Exception in netgen at passing to 2nd order ";
2937 catch (netgen::NgException exc)
2939 if ( comment.empty() ) // do not overwrite a previos error
2940 comment << exc.What();
2945 _ticTime = 0.98 / _progressTic;
2947 int nbNod = _ngMesh->GetNP();
2948 int nbSeg = _ngMesh->GetNSeg();
2949 int nbFac = _ngMesh->GetNSE();
2950 int nbVol = _ngMesh->GetNE();
2951 bool isOK = ( !err && (_isVolume ? (nbVol > 0) : (nbFac > 0)) );
2953 MESSAGE((err ? "Mesh Generation failure" : "End of Mesh Generation") <<
2954 ", nb nodes: " << nbNod <<
2955 ", nb segments: " << nbSeg <<
2956 ", nb faces: " << nbFac <<
2957 ", nb volumes: " << nbVol);
2959 // Feed back the SMESHDS with the generated Nodes and Elements
2960 if ( true /*isOK*/ ) // get whatever built
2962 FillSMesh( occgeo, *_ngMesh, initState, *_mesh, nodeVec, comment, &quadHelper );
2964 if ( quadHelper.GetIsQuadratic() ) // remove free nodes
2965 for ( size_t i = 0; i < nodeVec.size(); ++i )
2966 if ( nodeVec[i] && nodeVec[i]->NbInverseElements() == 0 )
2967 _mesh->GetMeshDS()->RemoveFreeNode( nodeVec[i], 0, /*fromGroups=*/false );
2969 SMESH_ComputeErrorPtr readErr = ReadErrors(nodeVec);
2970 if ( readErr && !readErr->myBadElements.empty() )
2973 if ( !comment.empty() && !readErr->myComment.empty() ) comment += "\n";
2974 comment += readErr->myComment;
2976 if ( error->IsOK() && ( !isOK || comment.size() > 0 ))
2977 error->myName = COMPERR_ALGO_FAILED;
2978 if ( !comment.empty() )
2979 error->myComment = comment;
2981 // SetIsAlwaysComputed( true ) to empty sub-meshes, which
2982 // appear if the geometry contains coincident sub-shape due
2983 // to bool merge_solids = 1; in netgen/libsrc/occ/occgenmesh.cpp
2984 const int nbMaps = 2;
2985 const TopTools_IndexedMapOfShape* geoMaps[nbMaps] =
2986 { & occgeo.vmap, & occgeo.emap/*, & occgeo.fmap*/ };
2987 for ( int iMap = 0; iMap < nbMaps; ++iMap )
2988 for (int i = 1; i <= geoMaps[iMap]->Extent(); i++)
2989 if ( SMESH_subMesh* sm = _mesh->GetSubMeshContaining( geoMaps[iMap]->FindKey(i)))
2990 if ( !sm->IsMeshComputed() )
2991 sm->SetIsAlwaysComputed( true );
2993 // set bad compute error to subshapes of all failed sub-shapes
2994 if ( !error->IsOK() )
2996 bool pb2D = false, pb3D = false;
2997 for (int i = 1; i <= occgeo.fmap.Extent(); i++) {
2998 int status = occgeo.facemeshstatus[i-1];
2999 if (status == netgen::FACE_MESHED_OK ) continue;
3000 if ( SMESH_subMesh* sm = _mesh->GetSubMeshContaining( occgeo.fmap( i ))) {
3001 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
3002 if ( !smError || smError->IsOK() ) {
3003 if ( status == netgen::FACE_FAILED )
3004 smError.reset( new SMESH_ComputeError( *error ));
3006 smError.reset( new SMESH_ComputeError( COMPERR_ALGO_FAILED, "Ignored" ));
3007 if ( SMESH_Algo::GetMeshError( sm ) == SMESH_Algo::MEr_OK )
3008 smError->myName = COMPERR_WARNING;
3010 pb2D = pb2D || smError->IsKO();
3013 if ( !pb2D ) // all faces are OK
3014 for (int i = 1; i <= occgeo.somap.Extent(); i++)
3015 if ( SMESH_subMesh* sm = _mesh->GetSubMeshContaining( occgeo.somap( i )))
3017 bool smComputed = nbVol && !sm->IsEmpty();
3018 if ( smComputed && internals.hasInternalVertexInSolid( sm->GetId() ))
3020 int nbIntV = internals.getSolidsWithVertices().find( sm->GetId() )->second.size();
3021 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
3022 smComputed = ( smDS->NbElements() > 0 || smDS->NbNodes() > nbIntV );
3024 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
3025 if ( !smComputed && ( !smError || smError->IsOK() ))
3027 smError.reset( new SMESH_ComputeError( *error ));
3028 if ( nbVol && SMESH_Algo::GetMeshError( sm ) == SMESH_Algo::MEr_OK )
3030 smError->myName = COMPERR_WARNING;
3032 else if ( !smError->myBadElements.empty() ) // bad surface mesh
3034 if ( !hasBadElemOnSolid( smError->myBadElements, sm ))
3038 pb3D = pb3D || ( smError && smError->IsKO() );
3040 if ( !pb2D && !pb3D )
3041 err = 0; // no fatal errors, only warnings
3044 ngLib._isComputeOk = !err;
3049 //=============================================================================
3053 //=============================================================================
3054 bool NETGENPlugin_Mesher::Evaluate(MapShapeNbElems& aResMap)
3056 netgen::MeshingParameters& mparams = netgen::mparam;
3059 // -------------------------
3060 // Prepare OCC geometry
3061 // -------------------------
3062 netgen::OCCGeometry occgeo;
3063 list< SMESH_subMesh* > meshedSM[4]; // for 0-3 dimensions
3064 NETGENPlugin_Internals internals( *_mesh, _shape, _isVolume );
3065 PrepareOCCgeometry( occgeo, _shape, *_mesh, meshedSM, &internals );
3067 bool tooManyElems = false;
3068 const int hugeNb = std::numeric_limits<int>::max() / 100;
3073 // pass 1D simple parameters to NETGEN
3076 // not to RestrictLocalH() according to curvature during MESHCONST_ANALYSE
3077 mparams.uselocalh = false;
3078 mparams.grading = 0.8; // not limitited size growth
3080 if ( _simpleHyp->GetNumberOfSegments() )
3082 mparams.maxh = occgeo.boundingbox.Diam();
3085 mparams.maxh = _simpleHyp->GetLocalLength();
3088 if ( mparams.maxh == 0.0 )
3089 mparams.maxh = occgeo.boundingbox.Diam();
3090 if ( _simpleHyp || ( mparams.minh == 0.0 && _fineness != NETGENPlugin_Hypothesis::UserDefined))
3091 mparams.minh = GetDefaultMinSize( _shape, mparams.maxh );
3093 // let netgen create _ngMesh and calculate element size on not meshed shapes
3094 NETGENPlugin_NetgenLibWrapper ngLib;
3095 netgen::Mesh *ngMesh = NULL;
3099 int startWith = netgen::MESHCONST_ANALYSE;
3100 int endWith = netgen::MESHCONST_MESHEDGES;
3102 int err = netgen::OCCGenerateMesh(occgeo, ngMesh, mparams, startWith, endWith);
3104 int err = netgen::OCCGenerateMesh(occgeo, ngMesh, startWith, endWith, optstr);
3107 if(netgen::multithread.terminate)
3110 ngLib.setMesh(( Ng_Mesh*) ngMesh );
3112 if ( SMESH_subMesh* sm = _mesh->GetSubMeshContaining( _shape ))
3113 sm->GetComputeError().reset( new SMESH_ComputeError( COMPERR_ALGO_FAILED ));
3118 // Pass 1D simple parameters to NETGEN
3119 // --------------------------------
3120 int nbSeg = _simpleHyp->GetNumberOfSegments();
3121 double segSize = _simpleHyp->GetLocalLength();
3122 for ( int iE = 1; iE <= occgeo.emap.Extent(); ++iE )
3124 const TopoDS_Edge& e = TopoDS::Edge( occgeo.emap(iE));
3126 segSize = SMESH_Algo::EdgeLength( e ) / ( nbSeg - 0.4 );
3127 setLocalSize( e, segSize, *ngMesh );
3130 else // if ( ! _simpleHyp )
3132 // Local size on vertices and edges
3133 // --------------------------------
3134 for(std::map<int,double>::const_iterator it=EdgeId2LocalSize.begin(); it!=EdgeId2LocalSize.end(); it++)
3136 int key = (*it).first;
3137 double hi = (*it).second;
3138 const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
3139 const TopoDS_Edge& e = TopoDS::Edge(shape);
3140 setLocalSize( e, hi, *ngMesh );
3142 for(std::map<int,double>::const_iterator it=VertexId2LocalSize.begin(); it!=VertexId2LocalSize.end(); it++)
3144 int key = (*it).first;
3145 double hi = (*it).second;
3146 const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
3147 const TopoDS_Vertex& v = TopoDS::Vertex(shape);
3148 gp_Pnt p = BRep_Tool::Pnt(v);
3149 NETGENPlugin_Mesher::RestrictLocalSize( *ngMesh, p.XYZ(), hi );
3151 for(map<int,double>::const_iterator it=FaceId2LocalSize.begin();
3152 it!=FaceId2LocalSize.end(); it++)
3154 int key = (*it).first;
3155 double val = (*it).second;
3156 const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
3157 int faceNgID = occgeo.fmap.FindIndex(shape);
3158 occgeo.SetFaceMaxH(faceNgID, val);
3159 for ( TopExp_Explorer edgeExp( shape, TopAbs_EDGE ); edgeExp.More(); edgeExp.Next() )
3160 setLocalSize( TopoDS::Edge( edgeExp.Current() ), val, *ngMesh );
3163 // calculate total nb of segments and length of edges
3164 double fullLen = 0.0;
3166 int entity = mparams.secondorder > 0 ? SMDSEntity_Quad_Edge : SMDSEntity_Edge;
3167 TopTools_DataMapOfShapeInteger Edge2NbSeg;
3168 for (TopExp_Explorer exp(_shape, TopAbs_EDGE); exp.More(); exp.Next())
3170 TopoDS_Edge E = TopoDS::Edge( exp.Current() );
3171 if( !Edge2NbSeg.Bind(E,0) )
3174 double aLen = SMESH_Algo::EdgeLength(E);
3177 vector<int>& aVec = aResMap[_mesh->GetSubMesh(E)];
3179 aVec.resize( SMDSEntity_Last, 0);
3181 fullNbSeg += aVec[ entity ];
3184 // store nb of segments computed by Netgen
3185 NCollection_Map<Link> linkMap;
3186 for (int i = 1; i <= ngMesh->GetNSeg(); ++i )
3188 const netgen::Segment& seg = ngMesh->LineSegment(i);
3189 Link link(seg[0], seg[1]);
3190 if ( !linkMap.Add( link )) continue;
3191 int aGeomEdgeInd = seg.epgeominfo[0].edgenr;
3192 if (aGeomEdgeInd > 0 && aGeomEdgeInd <= occgeo.emap.Extent())
3194 vector<int>& aVec = aResMap[_mesh->GetSubMesh(occgeo.emap(aGeomEdgeInd))];
3198 // store nb of nodes on edges computed by Netgen
3199 TopTools_DataMapIteratorOfDataMapOfShapeInteger Edge2NbSegIt(Edge2NbSeg);
3200 for (; Edge2NbSegIt.More(); Edge2NbSegIt.Next())
3202 vector<int>& aVec = aResMap[_mesh->GetSubMesh(Edge2NbSegIt.Key())];
3203 if ( aVec[ entity ] > 1 && aVec[ SMDSEntity_Node ] == 0 )
3204 aVec[SMDSEntity_Node] = mparams.secondorder > 0 ? 2*aVec[ entity ]-1 : aVec[ entity ]-1;
3206 fullNbSeg += aVec[ entity ];
3207 Edge2NbSeg( Edge2NbSegIt.Key() ) = aVec[ entity ];
3209 if ( fullNbSeg == 0 )
3216 if ( double area = _simpleHyp->GetMaxElementArea() ) {
3218 mparams.maxh = sqrt(2. * area/sqrt(3.0));
3219 mparams.grading = 0.4; // moderate size growth
3222 // length from edges
3223 mparams.maxh = fullLen/fullNbSeg;
3224 mparams.grading = 0.2; // slow size growth
3227 mparams.maxh = min( mparams.maxh, occgeo.boundingbox.Diam()/2 );
3228 mparams.maxh = min( mparams.maxh, fullLen/fullNbSeg * (1. + mparams.grading));
3230 for (TopExp_Explorer exp(_shape, TopAbs_FACE); exp.More(); exp.Next())
3232 TopoDS_Face F = TopoDS::Face( exp.Current() );
3233 SMESH_subMesh *sm = _mesh->GetSubMesh(F);
3235 BRepGProp::SurfaceProperties(F,G);
3236 double anArea = G.Mass();
3237 tooManyElems = tooManyElems || ( anArea/hugeNb > mparams.maxh*mparams.maxh );
3239 if ( !tooManyElems )
3241 TopTools_MapOfShape egdes;
3242 for (TopExp_Explorer exp1(F,TopAbs_EDGE); exp1.More(); exp1.Next())
3243 if ( egdes.Add( exp1.Current() ))
3244 nb1d += Edge2NbSeg.Find(exp1.Current());
3246 int nbFaces = tooManyElems ? hugeNb : int( 4*anArea / (mparams.maxh*mparams.maxh*sqrt(3.)));
3247 int nbNodes = tooManyElems ? hugeNb : (( nbFaces*3 - (nb1d-1)*2 ) / 6 + 1 );
3249 vector<int> aVec(SMDSEntity_Last, 0);
3250 if( mparams.secondorder > 0 ) {
3251 int nb1d_in = (nbFaces*3 - nb1d) / 2;
3252 aVec[SMDSEntity_Node] = nbNodes + nb1d_in;
3253 aVec[SMDSEntity_Quad_Triangle] = nbFaces;
3256 aVec[SMDSEntity_Node] = Max ( nbNodes, 0 );
3257 aVec[SMDSEntity_Triangle] = nbFaces;
3259 aResMap[sm].swap(aVec);
3266 // pass 3D simple parameters to NETGEN
3267 const NETGENPlugin_SimpleHypothesis_3D* simple3d =
3268 dynamic_cast< const NETGENPlugin_SimpleHypothesis_3D* > ( _simpleHyp );
3270 if ( double vol = simple3d->GetMaxElementVolume() ) {
3272 mparams.maxh = pow( 72, 1/6. ) * pow( vol, 1/3. );
3273 mparams.maxh = min( mparams.maxh, occgeo.boundingbox.Diam()/2 );
3276 // using previous length from faces
3278 mparams.grading = 0.4;
3279 mparams.maxh = min( mparams.maxh, fullLen/fullNbSeg * (1. + mparams.grading));
3282 BRepGProp::VolumeProperties(_shape,G);
3283 double aVolume = G.Mass();
3284 double tetrVol = 0.1179*mparams.maxh*mparams.maxh*mparams.maxh;
3285 tooManyElems = tooManyElems || ( aVolume/hugeNb > tetrVol );
3286 int nbVols = tooManyElems ? hugeNb : int(aVolume/tetrVol);
3287 int nb1d_in = int(( nbVols*6 - fullNbSeg ) / 6 );
3288 vector<int> aVec(SMDSEntity_Last, 0 );
3289 if ( tooManyElems ) // avoid FPE
3291 aVec[SMDSEntity_Node] = hugeNb;
3292 aVec[ mparams.secondorder > 0 ? SMDSEntity_Quad_Tetra : SMDSEntity_Tetra] = hugeNb;
3296 if( mparams.secondorder > 0 ) {
3297 aVec[SMDSEntity_Node] = nb1d_in/3 + 1 + nb1d_in;
3298 aVec[SMDSEntity_Quad_Tetra] = nbVols;
3301 aVec[SMDSEntity_Node] = nb1d_in/3 + 1;
3302 aVec[SMDSEntity_Tetra] = nbVols;
3305 SMESH_subMesh *sm = _mesh->GetSubMesh(_shape);
3306 aResMap[sm].swap(aVec);
3312 double NETGENPlugin_Mesher::GetProgress(const SMESH_Algo* holder,
3313 const int * algoProgressTic,
3314 const double * algoProgress) const
3316 ((int&) _progressTic ) = *algoProgressTic + 1;
3318 if ( !_occgeom ) return 0;
3320 double progress = -1;
3323 if ( _ticTime < 0 && netgen::multithread.task[0] == 'O'/*Optimizing surface*/ )
3325 ((double&) _ticTime ) = edgeFaceMeshingTime / _totalTime / _progressTic;
3327 else if ( !_optimize /*&& _occgeom->fmap.Extent() > 1*/ )
3329 int doneShapeIndex = -1;
3330 while ( doneShapeIndex+1 < _occgeom->facemeshstatus.Size() &&
3331 _occgeom->facemeshstatus[ doneShapeIndex+1 ])
3333 if ( doneShapeIndex+1 != _curShapeIndex )
3335 ((int&) _curShapeIndex) = doneShapeIndex+1;
3336 double doneShapeRate = _curShapeIndex / double( _occgeom->fmap.Extent() );
3337 double doneTime = edgeMeshingTime + doneShapeRate * faceMeshingTime;
3338 ((double&) _ticTime) = doneTime / _totalTime / _progressTic;
3339 // cout << "shape " << _curShapeIndex << " _ticTime " << _ticTime
3340 // << " " << doneTime / _totalTime / _progressTic << endl;
3344 else if ( !_optimize && _occgeom->somap.Extent() > 1 )
3346 int curShapeIndex = _curShapeIndex;
3347 if ( _ngMesh->GetNE() > 0 )
3349 netgen::Element el = (*_ngMesh)[netgen::ElementIndex( _ngMesh->GetNE()-1 )];
3350 curShapeIndex = el.GetIndex();
3352 if ( curShapeIndex != _curShapeIndex )
3354 ((int&) _curShapeIndex) = curShapeIndex;
3355 double doneShapeRate = _curShapeIndex / double( _occgeom->somap.Extent() );
3356 double doneTime = edgeFaceMeshingTime + doneShapeRate * voluMeshingTime;
3357 ((double&) _ticTime) = doneTime / _totalTime / _progressTic;
3358 // cout << "shape " << _curShapeIndex << " _ticTime " << _ticTime
3359 // << " " << doneTime / _totalTime / _progressTic << endl;
3363 progress = Max( *algoProgressTic * _ticTime, *algoProgress );
3366 ((int&) *algoProgressTic )++;
3367 ((double&) *algoProgress) = progress;
3369 //cout << progress << " " << *algoProgressTic << " " << netgen::multithread.task << " "<< _ticTime << endl;
3371 return Min( progress, 0.99 );
3374 //================================================================================
3376 * \brief Remove "test.out" and "problemfaces" files in current directory
3378 //================================================================================
3380 void NETGENPlugin_Mesher::RemoveTmpFiles()
3382 bool rm = SMESH_File("test.out").remove() ;
3384 if (rm && netgen::testout)
3386 delete netgen::testout;
3387 netgen::testout = 0;
3390 SMESH_File("problemfaces").remove();
3391 SMESH_File("occmesh.rep").remove();
3394 //================================================================================
3396 * \brief Read mesh entities preventing successful computation from "test.out" file
3398 //================================================================================
3400 SMESH_ComputeErrorPtr
3401 NETGENPlugin_Mesher::ReadErrors(const vector<const SMDS_MeshNode* >& nodeVec)
3403 SMESH_ComputeErrorPtr err = SMESH_ComputeError::New
3404 (COMPERR_BAD_INPUT_MESH, "Some edges multiple times in surface mesh");
3405 SMESH_File file("test.out");
3407 vector<int> three1(3), three2(3);
3408 const char* badEdgeStr = " multiple times in surface mesh";
3409 const int badEdgeStrLen = strlen( badEdgeStr );
3410 const int nbNodes = nodeVec.size();
3412 while( !file.eof() )
3414 if ( strncmp( file, "Edge ", 5 ) == 0 &&
3415 file.getInts( two ) &&
3416 strncmp( file, badEdgeStr, badEdgeStrLen ) == 0 &&
3417 two[0] < nbNodes && two[1] < nbNodes )
3419 err->myBadElements.push_back( new SMDS_LinearEdge( nodeVec[ two[0]], nodeVec[ two[1]] ));
3420 file += badEdgeStrLen;
3422 else if ( strncmp( file, "Intersecting: ", 14 ) == 0 )
3425 // openelement 18 with open element 126
3429 const char* pos = file;
3430 bool ok = ( strncmp( file, "openelement ", 12 ) == 0 );
3431 ok = ok && file.getInts( two );
3432 ok = ok && file.getInts( three1 );
3433 ok = ok && file.getInts( three2 );
3434 for ( int i = 0; ok && i < 3; ++i )
3435 ok = ( three1[i] < nbNodes && nodeVec[ three1[i]]);
3436 for ( int i = 0; ok && i < 3; ++i )
3437 ok = ( three2[i] < nbNodes && nodeVec[ three2[i]]);
3440 err->myBadElements.push_back( new SMDS_FaceOfNodes( nodeVec[ three1[0]],
3441 nodeVec[ three1[1]],
3442 nodeVec[ three1[2]]));
3443 err->myBadElements.push_back( new SMDS_FaceOfNodes( nodeVec[ three2[0]],
3444 nodeVec[ three2[1]],
3445 nodeVec[ three2[2]]));
3446 err->myComment = "Intersecting triangles";
3460 size_t nbBadElems = err->myBadElements.size();
3467 //================================================================================
3469 * \brief Write a python script creating an equivalent SALOME mesh.
3470 * This is useful to see what mesh is passed as input for the next step of mesh
3471 * generation (of mesh of higher dimension)
3473 //================================================================================
3475 void NETGENPlugin_Mesher::toPython( const netgen::Mesh* ngMesh,
3476 const std::string& pyFile)
3478 ofstream outfile(pyFile.c_str(), ios::out);
3479 if ( !outfile ) return;
3481 outfile << "import SMESH" << endl
3482 << "from salome.smesh import smeshBuilder" << endl
3483 << "smesh = smeshBuilder.New(salome.myStudy)" << endl
3484 << "mesh = smesh.Mesh()" << endl << endl;
3486 using namespace netgen;
3488 for (pi = PointIndex::BASE;
3489 pi < ngMesh->GetNP()+PointIndex::BASE; pi++)
3491 outfile << "mesh.AddNode( ";
3492 outfile << (*ngMesh)[pi](0) << ", ";
3493 outfile << (*ngMesh)[pi](1) << ", ";
3494 outfile << (*ngMesh)[pi](2) << ") ## "<< pi << endl;
3497 int nbDom = ngMesh->GetNDomains();
3498 for ( int i = 0; i < nbDom; ++i )
3499 outfile<< "grp" << i+1 << " = mesh.CreateEmptyGroup( SMESH.FACE, 'domain"<< i+1 << "')"<< endl;
3501 SurfaceElementIndex sei;
3502 for (sei = 0; sei < ngMesh->GetNSE(); sei++)
3504 outfile << "mesh.AddFace([ ";
3505 Element2d sel = (*ngMesh)[sei];
3506 for (int j = 0; j < sel.GetNP(); j++)
3507 outfile << sel[j] << ( j+1 < sel.GetNP() ? ", " : " ])");
3508 if ( sel.IsDeleted() ) outfile << " ## IsDeleted ";
3511 if ((*ngMesh)[sei].GetIndex())
3513 if ( int dom1 = ngMesh->GetFaceDescriptor((*ngMesh)[sei].GetIndex ()).DomainIn())
3514 outfile << "grp"<< dom1 <<".Add([ " << (int)sei+1 << " ])" << endl;
3515 if ( int dom2 = ngMesh->GetFaceDescriptor((*ngMesh)[sei].GetIndex ()).DomainOut())
3516 outfile << "grp"<< dom2 <<".Add([ " << (int)sei+1 << " ])" << endl;
3520 for (ElementIndex ei = 0; ei < ngMesh->GetNE(); ei++)
3522 Element el = (*ngMesh)[ei];
3523 outfile << "mesh.AddVolume([ ";
3524 for (int j = 0; j < el.GetNP(); j++)
3525 outfile << el[j] << ( j+1 < el.GetNP() ? ", " : " ])");
3529 for (int i = 1; i <= ngMesh->GetNSeg(); i++)
3531 const Segment & seg = ngMesh->LineSegment (i);
3532 outfile << "mesh.AddEdge([ "
3534 << seg[1] << " ])" << endl;
3536 cout << "Write " << pyFile << endl;
3539 //================================================================================
3541 * \brief Constructor of NETGENPlugin_ngMeshInfo
3543 //================================================================================
3545 NETGENPlugin_ngMeshInfo::NETGENPlugin_ngMeshInfo( netgen::Mesh* ngMesh):
3550 _nbNodes = ngMesh->GetNP();
3551 _nbSegments = ngMesh->GetNSeg();
3552 _nbFaces = ngMesh->GetNSE();
3553 _nbVolumes = ngMesh->GetNE();
3557 _nbNodes = _nbSegments = _nbFaces = _nbVolumes = 0;
3561 //================================================================================
3563 * \brief Copy LocalH member from one netgen mesh to another
3565 //================================================================================
3567 void NETGENPlugin_ngMeshInfo::transferLocalH( netgen::Mesh* fromMesh,
3568 netgen::Mesh* toMesh )
3570 if ( !fromMesh->LocalHFunctionGenerated() ) return;
3571 if ( !toMesh->LocalHFunctionGenerated() )
3573 toMesh->CalcLocalH(netgen::mparam.grading);
3575 toMesh->CalcLocalH();
3578 const size_t size = sizeof( netgen::LocalH );
3579 _copyOfLocalH = new char[ size ];
3580 memcpy( (void*)_copyOfLocalH, (void*)&toMesh->LocalHFunction(), size );
3581 memcpy( (void*)&toMesh->LocalHFunction(), (void*)&fromMesh->LocalHFunction(), size );
3584 //================================================================================
3586 * \brief Restore LocalH member of a netgen mesh
3588 //================================================================================
3590 void NETGENPlugin_ngMeshInfo::restoreLocalH( netgen::Mesh* toMesh )
3592 if ( _copyOfLocalH )
3594 const size_t size = sizeof( netgen::LocalH );
3595 memcpy( (void*)&toMesh->LocalHFunction(), (void*)_copyOfLocalH, size );
3596 delete [] _copyOfLocalH;
3601 //================================================================================
3603 * \brief Find "internal" sub-shapes
3605 //================================================================================
3607 NETGENPlugin_Internals::NETGENPlugin_Internals( SMESH_Mesh& mesh,
3608 const TopoDS_Shape& shape,
3610 : _mesh( mesh ), _is3D( is3D )
3612 SMESHDS_Mesh* meshDS = mesh.GetMeshDS();
3614 TopExp_Explorer f,e;
3615 for ( f.Init( shape, TopAbs_FACE ); f.More(); f.Next() )
3617 int faceID = meshDS->ShapeToIndex( f.Current() );
3619 // find not computed internal edges
3621 for ( e.Init( f.Current().Oriented(TopAbs_FORWARD), TopAbs_EDGE ); e.More(); e.Next() )
3622 if ( e.Current().Orientation() == TopAbs_INTERNAL )
3624 SMESH_subMesh* eSM = mesh.GetSubMesh( e.Current() );
3625 if ( eSM->IsEmpty() )
3627 _e2face.insert( make_pair( eSM->GetId(), faceID ));
3628 for ( TopoDS_Iterator v(e.Current()); v.More(); v.Next() )
3629 _e2face.insert( make_pair( meshDS->ShapeToIndex( v.Value() ), faceID ));
3633 // find internal vertices in a face
3634 set<int> intVV; // issue 0020850 where same vertex is twice in a face
3635 for ( TopoDS_Iterator fSub( f.Current() ); fSub.More(); fSub.Next())
3636 if ( fSub.Value().ShapeType() == TopAbs_VERTEX )
3638 int vID = meshDS->ShapeToIndex( fSub.Value() );
3639 if ( intVV.insert( vID ).second )
3640 _f2v[ faceID ].push_back( vID );
3645 // find internal faces and their subshapes where nodes are to be doubled
3646 // to make a crack with non-sewed borders
3648 if ( f.Current().Orientation() == TopAbs_INTERNAL )
3650 _intShapes.insert( meshDS->ShapeToIndex( f.Current() ));
3653 list< TopoDS_Shape > edges;
3654 for ( e.Init( f.Current(), TopAbs_EDGE ); e.More(); e.Next())
3655 if ( SMESH_MesherHelper::NbAncestors( e.Current(), mesh, TopAbs_FACE ) > 1 )
3657 _intShapes.insert( meshDS->ShapeToIndex( e.Current() ));
3658 edges.push_back( e.Current() );
3659 // find border faces
3660 PShapeIteratorPtr fIt =
3661 SMESH_MesherHelper::GetAncestors( edges.back(),mesh,TopAbs_FACE );
3662 while ( const TopoDS_Shape* pFace = fIt->next() )
3663 if ( !pFace->IsSame( f.Current() ))
3664 _borderFaces.insert( meshDS->ShapeToIndex( *pFace ));
3667 // we consider vertex internal if it is shared by more than one internal edge
3668 list< TopoDS_Shape >::iterator edge = edges.begin();
3669 for ( ; edge != edges.end(); ++edge )
3670 for ( TopoDS_Iterator v( *edge ); v.More(); v.Next() )
3672 set<int> internalEdges;
3673 PShapeIteratorPtr eIt =
3674 SMESH_MesherHelper::GetAncestors( v.Value(),mesh,TopAbs_EDGE );
3675 while ( const TopoDS_Shape* pEdge = eIt->next() )
3677 int edgeID = meshDS->ShapeToIndex( *pEdge );
3678 if ( isInternalShape( edgeID ))
3679 internalEdges.insert( edgeID );
3681 if ( internalEdges.size() > 1 )
3682 _intShapes.insert( meshDS->ShapeToIndex( v.Value() ));
3686 } // loop on geom faces
3688 // find vertices internal in solids
3691 for ( TopExp_Explorer so(shape, TopAbs_SOLID); so.More(); so.Next())
3693 int soID = meshDS->ShapeToIndex( so.Current() );
3694 for ( TopoDS_Iterator soSub( so.Current() ); soSub.More(); soSub.Next())
3695 if ( soSub.Value().ShapeType() == TopAbs_VERTEX )
3696 _s2v[ soID ].push_back( meshDS->ShapeToIndex( soSub.Value() ));
3701 //================================================================================
3703 * \brief Find mesh faces on non-internal geom faces sharing internal edge
3704 * some nodes of which are to be doubled to make the second border of the "crack"
3706 //================================================================================
3708 void NETGENPlugin_Internals::findBorderElements( TIDSortedElemSet & borderElems )
3710 if ( _intShapes.empty() ) return;
3712 SMESH_Mesh& mesh = const_cast<SMESH_Mesh&>(_mesh);
3713 SMESHDS_Mesh* meshDS = mesh.GetMeshDS();
3715 // loop on internal geom edges
3716 set<int>::const_iterator intShapeId = _intShapes.begin();
3717 for ( ; intShapeId != _intShapes.end(); ++intShapeId )
3719 const TopoDS_Shape& s = meshDS->IndexToShape( *intShapeId );
3720 if ( s.ShapeType() != TopAbs_EDGE ) continue;
3722 // get internal and non-internal geom faces sharing the internal edge <s>
3724 set<int>::iterator bordFace = _borderFaces.end();
3725 PShapeIteratorPtr faces = SMESH_MesherHelper::GetAncestors( s, _mesh, TopAbs_FACE );
3726 while ( const TopoDS_Shape* pFace = faces->next() )
3728 int faceID = meshDS->ShapeToIndex( *pFace );
3729 if ( isInternalShape( faceID ))
3732 bordFace = _borderFaces.insert( faceID ).first;
3734 if ( bordFace == _borderFaces.end() || !intFace ) continue;
3736 // get all links of mesh faces on internal geom face sharing nodes on edge <s>
3737 set< SMESH_OrientedLink > links; //!< links of faces on internal geom face
3738 list<const SMDS_MeshElement*> suspectFaces[2]; //!< mesh faces on border geom faces
3739 int nbSuspectFaces = 0;
3740 SMESHDS_SubMesh* intFaceSM = meshDS->MeshElements( intFace );
3741 if ( !intFaceSM || intFaceSM->NbElements() == 0 ) continue;
3742 SMESH_subMeshIteratorPtr smIt = mesh.GetSubMesh( s )->getDependsOnIterator(true,true);
3743 while ( smIt->more() )
3745 SMESHDS_SubMesh* sm = smIt->next()->GetSubMeshDS();
3746 if ( !sm ) continue;
3747 SMDS_NodeIteratorPtr nIt = sm->GetNodes();
3748 while ( nIt->more() )
3750 const SMDS_MeshNode* nOnEdge = nIt->next();
3751 SMDS_ElemIteratorPtr fIt = nOnEdge->GetInverseElementIterator(SMDSAbs_Face);
3752 while ( fIt->more() )
3754 const SMDS_MeshElement* f = fIt->next();
3755 const int nbNodes = f->NbCornerNodes();
3756 if ( intFaceSM->Contains( f ))
3758 for ( int i = 0; i < nbNodes; ++i )
3759 links.insert( SMESH_OrientedLink( f->GetNode(i), f->GetNode((i+1)%nbNodes)));
3764 for ( int i = 0; i < nbNodes; ++i )
3765 nbDblNodes += isInternalShape( f->GetNode(i)->getshapeId() );
3767 suspectFaces[ nbDblNodes < 2 ].push_back( f );
3773 // suspectFaces[0] having link with same orientation as mesh faces on
3774 // the internal geom face are <borderElems>. suspectFaces[1] have
3775 // only one node on edge <s>, we decide on them later (at the 2nd loop)
3776 // by links of <borderElems> found at the 1st and 2nd loops
3777 set< SMESH_OrientedLink > borderLinks;
3778 for ( int isPostponed = 0; isPostponed < 2; ++isPostponed )
3780 list<const SMDS_MeshElement*>::iterator fIt = suspectFaces[isPostponed].begin();
3781 for ( int nbF = 0; fIt != suspectFaces[isPostponed].end(); ++fIt, ++nbF )
3783 const SMDS_MeshElement* f = *fIt;
3784 bool isBorder = false, linkFound = false, borderLinkFound = false;
3785 list< SMESH_OrientedLink > faceLinks;
3786 int nbNodes = f->NbCornerNodes();
3787 for ( int i = 0; i < nbNodes; ++i )
3789 SMESH_OrientedLink link( f->GetNode(i), f->GetNode((i+1)%nbNodes));
3790 faceLinks.push_back( link );
3793 set< SMESH_OrientedLink >::iterator foundLink = links.find( link );
3794 if ( foundLink != links.end() )
3797 isBorder = ( foundLink->_reversed == link._reversed );
3798 if ( !isBorder && !isPostponed ) break;
3799 faceLinks.pop_back();
3801 else if ( isPostponed && !borderLinkFound )
3803 foundLink = borderLinks.find( link );
3804 if ( foundLink != borderLinks.end() )
3806 borderLinkFound = true;
3807 isBorder = ( foundLink->_reversed != link._reversed );
3814 borderElems.insert( f );
3815 borderLinks.insert( faceLinks.begin(), faceLinks.end() );
3817 else if ( !linkFound && !borderLinkFound )
3819 suspectFaces[1].push_back( f );
3820 if ( nbF > 2 * nbSuspectFaces )
3821 break; // dead loop protection
3828 //================================================================================
3830 * \brief put internal shapes in maps and fill in submeshes to precompute
3832 //================================================================================
3834 void NETGENPlugin_Internals::getInternalEdges( TopTools_IndexedMapOfShape& fmap,
3835 TopTools_IndexedMapOfShape& emap,
3836 TopTools_IndexedMapOfShape& vmap,
3837 list< SMESH_subMesh* > smToPrecompute[])
3839 if ( !hasInternalEdges() ) return;
3840 map<int,int>::const_iterator ev_face = _e2face.begin();
3841 for ( ; ev_face != _e2face.end(); ++ev_face )
3843 const TopoDS_Shape& ev = _mesh.GetMeshDS()->IndexToShape( ev_face->first );
3844 const TopoDS_Shape& face = _mesh.GetMeshDS()->IndexToShape( ev_face->second );
3846 ( ev.ShapeType() == TopAbs_EDGE ? emap : vmap ).Add( ev );
3848 //cout<<"INTERNAL EDGE or VERTEX "<<ev_face->first<<" on face "<<ev_face->second<<endl;
3850 smToPrecompute[ MeshDim_1D ].push_back( _mesh.GetSubMeshContaining( ev_face->first ));
3854 //================================================================================
3856 * \brief return shapes and submeshes to be meshed and already meshed boundary submeshes
3858 //================================================================================
3860 void NETGENPlugin_Internals::getInternalFaces( TopTools_IndexedMapOfShape& fmap,
3861 TopTools_IndexedMapOfShape& emap,
3862 list< SMESH_subMesh* >& intFaceSM,
3863 list< SMESH_subMesh* >& boundarySM)
3865 if ( !hasInternalFaces() ) return;
3867 // <fmap> and <emap> are for not yet meshed shapes
3868 // <intFaceSM> is for submeshes of faces
3869 // <boundarySM> is for meshed edges and vertices
3874 set<int> shapeIDs ( _intShapes );
3875 if ( !_borderFaces.empty() )
3876 shapeIDs.insert( _borderFaces.begin(), _borderFaces.end() );
3878 set<int>::const_iterator intS = shapeIDs.begin();
3879 for ( ; intS != shapeIDs.end(); ++intS )
3881 SMESH_subMesh* sm = _mesh.GetSubMeshContaining( *intS );
3883 if ( sm->GetSubShape().ShapeType() != TopAbs_FACE ) continue;
3885 intFaceSM.push_back( sm );
3887 // add submeshes of not computed internal faces
3888 if ( !sm->IsEmpty() ) continue;
3890 SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(true,true);
3891 while ( smIt->more() )
3894 const TopoDS_Shape& s = sm->GetSubShape();
3896 if ( sm->IsEmpty() )
3899 switch ( s.ShapeType() ) {
3900 case TopAbs_FACE: fmap.Add ( s ); break;
3901 case TopAbs_EDGE: emap.Add ( s ); break;
3907 if ( s.ShapeType() != TopAbs_FACE )
3908 boundarySM.push_back( sm );
3914 //================================================================================
3916 * \brief Return true if given shape is to be precomputed in order to be correctly
3917 * added to netgen mesh
3919 //================================================================================
3921 bool NETGENPlugin_Internals::isShapeToPrecompute(const TopoDS_Shape& s)
3923 int shapeID = _mesh.GetMeshDS()->ShapeToIndex( s );
3924 switch ( s.ShapeType() ) {
3925 case TopAbs_FACE : break; //return isInternalShape( shapeID ) || isBorderFace( shapeID );
3926 case TopAbs_EDGE : return isInternalEdge( shapeID );
3927 case TopAbs_VERTEX: break;
3933 //================================================================================
3935 * \brief Return SMESH
3937 //================================================================================
3939 SMESH_Mesh& NETGENPlugin_Internals::getMesh() const
3941 return const_cast<SMESH_Mesh&>( _mesh );
3944 //================================================================================
3946 * \brief Initialize netgen library
3948 //================================================================================
3950 NETGENPlugin_NetgenLibWrapper::NETGENPlugin_NetgenLibWrapper()
3954 _isComputeOk = false;
3956 if ( !getenv( "KEEP_NETGEN_OUTPUT" ))
3958 // redirect all netgen output (mycout,myerr,cout) to _outputFileName
3959 _outputFileName = getOutputFileName();
3960 netgen::mycout = new ofstream ( _outputFileName.c_str() );
3961 netgen::myerr = netgen::mycout;
3962 _coutBuffer = std::cout.rdbuf();
3964 cout << "NOTE: netgen output is redirected to file " << _outputFileName << endl;
3966 std::cout.rdbuf( netgen::mycout->rdbuf() );
3970 _ngMesh = Ng_NewMesh();
3973 //================================================================================
3975 * \brief Finish using netgen library
3977 //================================================================================
3979 NETGENPlugin_NetgenLibWrapper::~NETGENPlugin_NetgenLibWrapper()
3981 Ng_DeleteMesh( _ngMesh );
3983 NETGENPlugin_Mesher::RemoveTmpFiles();
3985 std::cout.rdbuf( _coutBuffer );
3992 //================================================================================
3994 * \brief Set netgen mesh to delete at destruction
3996 //================================================================================
3998 void NETGENPlugin_NetgenLibWrapper::setMesh( Ng_Mesh* mesh )
4001 Ng_DeleteMesh( _ngMesh );
4005 //================================================================================
4007 * \brief Return a unique file name
4009 //================================================================================
4011 std::string NETGENPlugin_NetgenLibWrapper::getOutputFileName()
4013 std::string aTmpDir = SALOMEDS_Tool::GetTmpDir();
4015 TCollection_AsciiString aGenericName = (char*)aTmpDir.c_str();
4016 aGenericName += "NETGEN_";
4018 aGenericName += getpid();
4020 aGenericName += _getpid();
4022 aGenericName += "_";
4023 aGenericName += Abs((Standard_Integer)(long) aGenericName.ToCString());
4024 aGenericName += ".out";
4026 return aGenericName.ToCString();
4029 //================================================================================
4031 * \brief Remove file with netgen output
4033 //================================================================================
4035 void NETGENPlugin_NetgenLibWrapper::removeOutputFile()
4037 if ( !_outputFileName.empty() )
4039 if ( netgen::mycout )
4041 delete netgen::mycout;
4045 string tmpDir = SALOMEDS_Tool::GetDirFromPath ( _outputFileName );
4046 string aFileName = SALOMEDS_Tool::GetNameFromPath( _outputFileName ) + ".out";
4047 SALOMEDS::ListOfFileNames_var aFiles = new SALOMEDS::ListOfFileNames;
4049 aFiles[0] = aFileName.c_str();
4051 SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.c_str(), aFiles.in(), true );