1 // Copyright (C) 2007-2012 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.
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>
48 #include <utilities.h>
50 #include <BRepBuilderAPI_Copy.hxx>
51 #include <BRep_Tool.hxx>
52 #include <Bnd_B3d.hxx>
53 #include <NCollection_Map.hxx>
54 #include <Standard_ErrorHandler.hxx>
56 #include <TopExp_Explorer.hxx>
57 #include <TopTools_DataMapIteratorOfDataMapOfShapeInteger.hxx>
58 #include <TopTools_DataMapIteratorOfDataMapOfShapeShape.hxx>
59 #include <TopTools_DataMapOfShapeInteger.hxx>
60 #include <TopTools_DataMapOfShapeShape.hxx>
61 #include <TopTools_MapOfShape.hxx>
64 // Netgen include files
68 #include <occgeom.hpp>
69 #include <meshing.hpp>
70 //#include <ngexception.hpp>
72 extern int OCCGenerateMesh (OCCGeometry&, Mesh*&, int, int, char*);
73 //extern void OCCSetLocalMeshSize(OCCGeometry & geom, Mesh & mesh);
74 extern MeshingParameters mparam;
75 extern volatile multithreadt multithread;
81 using namespace nglib;
85 #define nodeVec_ACCESS(index) ((SMDS_MeshNode*) nodeVec.at((index)))
87 #define nodeVec_ACCESS(index) ((SMDS_MeshNode*) nodeVec[index])
91 #define NGPOINT_COORDS(p) p(0),p(1),p(2)
93 #define NGPOINT_COORDS(p) p.X(),p.Y(),p.Z()
96 // dump elements added to ng mesh
97 //#define DUMP_SEGMENTS
98 //#define DUMP_TRIANGLES
99 //#define DUMP_TRIANGLES_SCRIPT "/tmp/trias.py" //!< debug addIntVerticesInSolids()
101 TopTools_IndexedMapOfShape ShapesWithLocalSize;
102 std::map<int,double> VertexId2LocalSize;
103 std::map<int,double> EdgeId2LocalSize;
104 std::map<int,double> FaceId2LocalSize;
106 //=============================================================================
110 //=============================================================================
112 NETGENPlugin_Mesher::NETGENPlugin_Mesher (SMESH_Mesh* mesh,
113 const TopoDS_Shape& aShape,
119 _fineness(NETGENPlugin_Hypothesis::GetDefaultFineness()),
123 ShapesWithLocalSize.Clear();
124 VertexId2LocalSize.clear();
125 EdgeId2LocalSize.clear();
126 FaceId2LocalSize.clear();
129 //================================================================================
131 * \brief Initialize global NETGEN parameters with default values
133 //================================================================================
135 void NETGENPlugin_Mesher::defaultParameters()
137 netgen::MeshingParameters& mparams = netgen::mparam;
138 // maximal mesh edge size
139 mparams.maxh = 0;//NETGENPlugin_Hypothesis::GetDefaultMaxSize();
141 // minimal number of segments per edge
142 mparams.segmentsperedge = NETGENPlugin_Hypothesis::GetDefaultNbSegPerEdge();
143 // rate of growth of size between elements
144 mparams.grading = NETGENPlugin_Hypothesis::GetDefaultGrowthRate();
145 // safety factor for curvatures (elements per radius)
146 mparams.curvaturesafety = NETGENPlugin_Hypothesis::GetDefaultNbSegPerRadius();
147 // create elements of second order
148 mparams.secondorder = NETGENPlugin_Hypothesis::GetDefaultSecondOrder() ? 1 : 0;
149 // quad-dominated surface meshing
153 mparams.quad = NETGENPlugin_Hypothesis_2D::GetDefaultQuadAllowed() ? 1 : 0;
154 _fineness = NETGENPlugin_Hypothesis::GetDefaultFineness();
157 //=============================================================================
161 //=============================================================================
162 void SetLocalSize(TopoDS_Shape GeomShape, double LocalSize)
164 TopAbs_ShapeEnum GeomType = GeomShape.ShapeType();
165 if (GeomType == TopAbs_COMPOUND) {
166 for (TopoDS_Iterator it (GeomShape); it.More(); it.Next()) {
167 SetLocalSize(it.Value(), LocalSize);
172 if (! ShapesWithLocalSize.Contains(GeomShape))
173 key = ShapesWithLocalSize.Add(GeomShape);
175 key = ShapesWithLocalSize.FindIndex(GeomShape);
176 if (GeomType == TopAbs_VERTEX) {
177 VertexId2LocalSize[key] = LocalSize;
178 } else if (GeomType == TopAbs_EDGE) {
179 EdgeId2LocalSize[key] = LocalSize;
180 } else if (GeomType == TopAbs_FACE) {
181 FaceId2LocalSize[key] = LocalSize;
185 //=============================================================================
187 * Pass parameters to NETGEN
189 //=============================================================================
190 void NETGENPlugin_Mesher::SetParameters(const NETGENPlugin_Hypothesis* hyp)
194 netgen::MeshingParameters& mparams = netgen::mparam;
195 // Initialize global NETGEN parameters:
196 // maximal mesh segment size
197 mparams.maxh = hyp->GetMaxSize();
198 // maximal mesh element linear size
199 mparams.minh = hyp->GetMinSize();
200 // minimal number of segments per edge
201 mparams.segmentsperedge = hyp->GetNbSegPerEdge();
202 // rate of growth of size between elements
203 mparams.grading = hyp->GetGrowthRate();
204 // safety factor for curvatures (elements per radius)
205 mparams.curvaturesafety = hyp->GetNbSegPerRadius();
206 // create elements of second order
207 mparams.secondorder = hyp->GetSecondOrder() ? 1 : 0;
208 // quad-dominated surface meshing
209 // only triangles are allowed for volumic mesh (before realizing IMP 0021676)
211 mparams.quad = hyp->GetQuadAllowed() ? 1 : 0;
212 _optimize = hyp->GetOptimize();
213 _fineness = hyp->GetFineness();
216 SMESH_Gen_i* smeshGen_i = SMESH_Gen_i::GetSMESHGen();
217 CORBA::Object_var anObject = smeshGen_i->GetNS()->Resolve("/myStudyManager");
218 SALOMEDS::StudyManager_var aStudyMgr = SALOMEDS::StudyManager::_narrow(anObject);
219 SALOMEDS::Study_var myStudy = aStudyMgr->GetStudyByID(hyp->GetStudyId());
221 const NETGENPlugin_Hypothesis::TLocalSize localSizes = hyp->GetLocalSizesAndEntries();
222 NETGENPlugin_Hypothesis::TLocalSize::const_iterator it = localSizes.begin();
223 for (it ; it != localSizes.end() ; it++)
225 std::string entry = (*it).first;
226 double val = (*it).second;
228 GEOM::GEOM_Object_var aGeomObj;
229 TopoDS_Shape S = TopoDS_Shape();
230 SALOMEDS::SObject_var aSObj = myStudy->FindObjectID( entry.c_str() );
231 SALOMEDS::GenericAttribute_var anAttr;
232 if (!aSObj->_is_nil() && aSObj->FindAttribute(anAttr, "AttributeIOR")) {
233 SALOMEDS::AttributeIOR_var anIOR = SALOMEDS::AttributeIOR::_narrow(anAttr);
234 CORBA::String_var aVal = anIOR->Value();
235 CORBA::Object_var obj = myStudy->ConvertIORToObject(aVal);
236 aGeomObj = GEOM::GEOM_Object::_narrow(obj);
238 if ( !aGeomObj->_is_nil() )
239 S = smeshGen_i->GeomObjectToShape( aGeomObj.in() );
241 SetLocalSize(S, val);
246 //=============================================================================
248 * Pass simple parameters to NETGEN
250 //=============================================================================
252 void NETGENPlugin_Mesher::SetParameters(const NETGENPlugin_SimpleHypothesis_2D* hyp)
259 //=============================================================================
261 * Link - a pair of integer numbers
263 //=============================================================================
267 Link(int _n1, int _n2) : n1(_n1), n2(_n2) {}
268 Link() : n1(0), n2(0) {}
271 int HashCode(const Link& aLink, int aLimit)
273 return HashCode(aLink.n1 + aLink.n2, aLimit);
276 Standard_Boolean IsEqual(const Link& aLink1, const Link& aLink2)
278 return (aLink1.n1 == aLink2.n1 && aLink1.n2 == aLink2.n2 ||
279 aLink1.n1 == aLink2.n2 && aLink1.n2 == aLink2.n1);
284 //================================================================================
286 * \brief return id of netgen point corresponding to SMDS node
288 //================================================================================
289 typedef map< const SMDS_MeshNode*, int > TNode2IdMap;
291 int ngNodeId( const SMDS_MeshNode* node,
292 netgen::Mesh& ngMesh,
293 TNode2IdMap& nodeNgIdMap)
295 int newNgId = ngMesh.GetNP() + 1;
297 TNode2IdMap::iterator node_id = nodeNgIdMap.insert( make_pair( node, newNgId )).first;
299 if ( node_id->second == newNgId)
301 #if defined(DUMP_SEGMENTS) || defined(DUMP_TRIANGLES)
302 cout << "Ng " << newNgId << " - " << node;
304 netgen::MeshPoint p( netgen::Point<3> (node->X(), node->Y(), node->Z()) );
305 ngMesh.AddPoint( p );
307 return node_id->second;
310 //================================================================================
312 * \brief Return computed EDGEs connected to the given one
314 //================================================================================
316 list< TopoDS_Edge > getConnectedEdges( const TopoDS_Edge& edge,
317 const TopoDS_Face& face,
318 const set< SMESH_subMesh* > & computedSM,
319 const SMESH_MesherHelper& helper,
320 map< SMESH_subMesh*, set< int > >& addedEdgeSM2Faces)
324 list< TopoDS_Edge > edges;
325 list< int > nbEdgesInWire;
326 int nbWires = SMESH_Block::GetOrderedEdges( face, v1, edges, nbEdgesInWire);
328 // find <edge> within <edges>
329 list< TopoDS_Edge >::iterator eItFwd = edges.begin();
330 for ( ; eItFwd != edges.end(); ++eItFwd )
331 if ( edge.IsSame( *eItFwd ))
333 if ( eItFwd == edges.end()) return list< TopoDS_Edge>();
335 if ( eItFwd->Orientation() >= TopAbs_INTERNAL )
337 // connected INTERNAL edges returned from GetOrderedEdges() are wrongly oriented
338 // so treat each INTERNAL edge separately
339 TopoDS_Edge e = *eItFwd;
341 edges.push_back( e );
345 // get all computed EDGEs connected to <edge>
347 list< TopoDS_Edge >::iterator eItBack = eItFwd, ePrev;
348 TopoDS_Vertex vCommon;
349 TopTools_MapOfShape eAdded; // map used not to add a seam edge twice to <edges>
352 // put edges before <edge> to <edges> back
353 while ( edges.begin() != eItFwd )
354 edges.splice( edges.end(), edges, edges.begin() );
358 while ( ++eItFwd != edges.end() )
360 SMESH_subMesh* sm = helper.GetMesh()->GetSubMesh( *eItFwd );
362 bool connected = TopExp::CommonVertex( *ePrev, *eItFwd, vCommon );
363 bool computed = sm->IsMeshComputed();
364 bool added = addedEdgeSM2Faces[ sm ].count( helper.GetSubShapeID() );
365 bool doubled = !eAdded.Add( *eItFwd );
366 bool orientOK = (( ePrev ->Orientation() < TopAbs_INTERNAL ) ==
367 ( eItFwd->Orientation() < TopAbs_INTERNAL ) );
368 if ( !connected || !computed || !orientOK || added || doubled )
370 // stop advancement; move edges from tail to head
371 while ( edges.back() != *ePrev )
372 edges.splice( edges.begin(), edges, --edges.end() );
378 while ( eItBack != edges.begin() )
382 SMESH_subMesh* sm = helper.GetMesh()->GetSubMesh( *eItBack );
384 bool connected = TopExp::CommonVertex( *ePrev, *eItBack, vCommon );
385 bool computed = sm->IsMeshComputed();
386 bool added = addedEdgeSM2Faces[ sm ].count( helper.GetSubShapeID() );
387 bool doubled = !eAdded.Add( *eItBack );
388 bool orientOK = (( ePrev ->Orientation() < TopAbs_INTERNAL ) ==
389 ( eItBack->Orientation() < TopAbs_INTERNAL ) );
390 if ( !connected || !computed || !orientOK || added || doubled)
393 edges.erase( edges.begin(), ePrev );
397 if ( edges.front() != edges.back() )
399 // assure that the 1st vertex is meshed
400 TopoDS_Edge eLast = edges.back();
401 while ( !SMESH_Algo::VertexNode( SMESH_MesherHelper::IthVertex( 0, edges.front()), helper.GetMeshDS())
403 edges.front() != eLast )
404 edges.splice( edges.end(), edges, edges.begin() );
409 //================================================================================
411 * \brief Make triangulation of a shape precise enough
413 //================================================================================
415 void updateTriangulation( const TopoDS_Shape& shape )
417 // static set< Poly_Triangulation* > updated;
419 // TopLoc_Location loc;
420 // TopExp_Explorer fExp( shape, TopAbs_FACE );
421 // for ( ; fExp.More(); fExp.Next() )
423 // Handle(Poly_Triangulation) triangulation =
424 // BRep_Tool::Triangulation ( TopoDS::Face( fExp.Current() ), loc);
425 // if ( triangulation.IsNull() ||
426 // updated.insert( triangulation.operator->() ).second )
428 // BRepTools::Clean (shape);
430 #if (OCC_VERSION_MAJOR << 16 | OCC_VERSION_MINOR << 8 | OCC_VERSION_MAINTENANCE) > 0x060100
433 BRepMesh_IncrementalMesh e(shape, 0.01, true);
436 catch (Standard_Failure)
439 // updated.erase( triangulation.operator->() );
440 // triangulation = BRep_Tool::Triangulation ( TopoDS::Face( fExp.Current() ), loc);
441 // updated.insert( triangulation.operator->() );
447 //================================================================================
449 * \brief Initialize netgen::OCCGeometry with OCCT shape
451 //================================================================================
453 void NETGENPlugin_Mesher::PrepareOCCgeometry(netgen::OCCGeometry& occgeo,
454 const TopoDS_Shape& shape,
456 list< SMESH_subMesh* > * meshedSM,
457 NETGENPlugin_Internals* intern)
459 updateTriangulation( shape );
462 BRepBndLib::Add (shape, bb);
463 double x1,y1,z1,x2,y2,z2;
464 bb.Get (x1,y1,z1,x2,y2,z2);
465 MESSAGE("shape bounding box:\n" <<
466 "(" << x1 << " " << y1 << " " << z1 << ") " <<
467 "(" << x2 << " " << y2 << " " << z2 << ")");
468 netgen::Point<3> p1 = netgen::Point<3> (x1,y1,z1);
469 netgen::Point<3> p2 = netgen::Point<3> (x2,y2,z2);
470 occgeo.boundingbox = netgen::Box<3> (p1,p2);
472 occgeo.shape = shape;
475 // fill maps of shapes of occgeo with not yet meshed subshapes
477 // get root submeshes
478 list< SMESH_subMesh* > rootSM;
479 if ( SMESH_subMesh* sm = mesh.GetSubMeshContaining( shape )) {
480 rootSM.push_back( sm );
483 for ( TopoDS_Iterator it( shape ); it.More(); it.Next() )
484 rootSM.push_back( mesh.GetSubMesh( it.Value() ));
487 // add subshapes of empty submeshes
488 list< SMESH_subMesh* >::iterator rootIt = rootSM.begin(), rootEnd = rootSM.end();
489 for ( ; rootIt != rootEnd; ++rootIt ) {
490 SMESH_subMesh * root = *rootIt;
491 SMESH_subMeshIteratorPtr smIt = root->getDependsOnIterator(/*includeSelf=*/true,
492 /*complexShapeFirst=*/true);
493 // to find a right orientation of subshapes (PAL20462)
494 TopTools_IndexedMapOfShape subShapes;
495 TopExp::MapShapes(root->GetSubShape(), subShapes);
496 while ( smIt->more() )
498 SMESH_subMesh* sm = smIt->next();
499 TopoDS_Shape shape = sm->GetSubShape();
500 if ( intern && intern->isShapeToPrecompute( shape ))
502 if ( !meshedSM || sm->IsEmpty() )
504 if ( shape.ShapeType() != TopAbs_VERTEX )
505 shape = subShapes( subShapes.FindIndex( shape ));// shape -> index -> oriented shape
506 if ( shape.Orientation() >= TopAbs_INTERNAL )
507 shape.Orientation( TopAbs_FORWARD ); // isuue 0020676
508 switch ( shape.ShapeType() ) {
509 case TopAbs_FACE : occgeo.fmap.Add( shape ); break;
510 case TopAbs_EDGE : occgeo.emap.Add( shape ); break;
511 case TopAbs_VERTEX: occgeo.vmap.Add( shape ); break;
512 case TopAbs_SOLID :occgeo.somap.Add( shape ); break;
516 // collect submeshes of meshed shapes
519 const int dim = SMESH_Gen::GetShapeDim( shape );
520 meshedSM[ dim ].push_back( sm );
524 occgeo.facemeshstatus.SetSize (occgeo.fmap.Extent());
525 occgeo.facemeshstatus = 0;
527 occgeo.face_maxh_modified.SetSize(occgeo.fmap.Extent());
528 occgeo.face_maxh_modified = 0;
529 occgeo.face_maxh.SetSize(occgeo.fmap.Extent());
530 occgeo.face_maxh = netgen::mparam.maxh;
534 //================================================================================
536 * \brief Return a default min size value suitable for the given geometry.
538 //================================================================================
540 double NETGENPlugin_Mesher::GetDefaultMinSize(const TopoDS_Shape& geom,
541 const double maxSize)
543 updateTriangulation( geom );
547 const int* pi[4] = { &i1, &i2, &i3, &i1 };
550 TopExp_Explorer fExp( geom, TopAbs_FACE );
551 for ( ; fExp.More(); fExp.Next() )
553 Handle(Poly_Triangulation) triangulation =
554 BRep_Tool::Triangulation ( TopoDS::Face( fExp.Current() ), loc);
555 if ( triangulation.IsNull() ) continue;
556 const double fTol = BRep_Tool::Tolerance( TopoDS::Face( fExp.Current() ));
557 const TColgp_Array1OfPnt& points = triangulation->Nodes();
558 const Poly_Array1OfTriangle& trias = triangulation->Triangles();
559 for ( int iT = trias.Lower(); iT <= trias.Upper(); ++iT )
561 trias(iT).Get( i1, i2, i3 );
562 for ( int j = 0; j < 3; ++j )
564 double dist2 = points(*pi[j]).SquareDistance( points( *pi[j+1] ));
565 if ( dist2 < minh && fTol*fTol < dist2 )
567 bb.Add( points(*pi[j]));
571 if ( minh > 0.25 * bb.SquareExtent() ) // simple geometry, rough triangulation
573 minh = 1e-3 * sqrt( bb.SquareExtent());
574 //cout << "BND BOX minh = " <<minh << endl;
578 minh = 3 * sqrt( minh ); // triangulation for visualization is rather fine
579 //cout << "TRIANGULATION minh = " <<minh << endl;
581 if ( minh > 0.5 * maxSize )
587 //================================================================================
589 * \brief Restrict size of elements at a given point
591 //================================================================================
593 void NETGENPlugin_Mesher::RestrictLocalSize(netgen::Mesh& ngMesh, const gp_XYZ& p, const double size)
595 if ( netgen::mparam.minh > size )
597 ngMesh.SetMinimalH( size );
598 netgen::mparam.minh = size;
600 netgen::Point3d pi(p.X(), p.Y(), p.Z());
601 ngMesh.RestrictLocalH( pi, size );
604 //================================================================================
606 * \brief fill ngMesh with nodes and elements of computed submeshes
608 //================================================================================
610 bool NETGENPlugin_Mesher::fillNgMesh(netgen::OCCGeometry& occgeom,
611 netgen::Mesh& ngMesh,
612 vector<const SMDS_MeshNode*>& nodeVec,
613 const list< SMESH_subMesh* > & meshedSM,
614 SMESH_ProxyMesh::Ptr proxyMesh)
616 TNode2IdMap nodeNgIdMap;
617 for ( int i = 1; i < nodeVec.size(); ++i )
618 nodeNgIdMap.insert( make_pair( nodeVec[i], i ));
620 TopTools_MapOfShape visitedShapes;
621 map< SMESH_subMesh*, set< int > > visitedEdgeSM2Faces;
622 set< SMESH_subMesh* > computedSM( meshedSM.begin(), meshedSM.end() );
624 SMESH_MesherHelper helper (*_mesh);
626 int faceNgID = ngMesh.GetNFD();
628 list< SMESH_subMesh* >::const_iterator smIt, smEnd = meshedSM.end();
629 for ( smIt = meshedSM.begin(); smIt != smEnd; ++smIt )
631 SMESH_subMesh* sm = *smIt;
632 if ( !visitedShapes.Add( sm->GetSubShape() ))
635 const SMESHDS_SubMesh * smDS = sm->GetSubMeshDS();
636 if ( !smDS ) continue;
638 switch ( sm->GetSubShape().ShapeType() )
640 case TopAbs_EDGE: { // EDGE
641 // ----------------------
642 TopoDS_Edge geomEdge = TopoDS::Edge( sm->GetSubShape() );
643 if ( geomEdge.Orientation() >= TopAbs_INTERNAL )
644 geomEdge.Orientation( TopAbs_FORWARD ); // issue 0020676
646 // Add ng segments for each not meshed FACE the EDGE bounds
647 PShapeIteratorPtr fIt = helper.GetAncestors( geomEdge, *sm->GetFather(), TopAbs_FACE );
648 while ( const TopoDS_Shape * anc = fIt->next() )
650 faceNgID = occgeom.fmap.FindIndex( *anc );
652 continue; // meshed face
654 int faceSMDSId = helper.GetMeshDS()->ShapeToIndex( *anc );
655 if ( visitedEdgeSM2Faces[ sm ].count( faceSMDSId ))
656 continue; // already treated EDGE
658 TopoDS_Face face = TopoDS::Face( occgeom.fmap( faceNgID ));
659 if ( face.Orientation() >= TopAbs_INTERNAL )
660 face.Orientation( TopAbs_FORWARD ); // issue 0020676
662 // get all meshed EDGEs of the FACE connected to geomEdge (issue 0021140)
663 helper.SetSubShape( face );
664 list< TopoDS_Edge > edges = getConnectedEdges( geomEdge, face, computedSM, helper,
665 visitedEdgeSM2Faces );
667 continue; // wrong ancestor?
669 // find out orientation of <edges> within <face>
670 TopoDS_Edge eNotSeam = edges.front();
671 if ( helper.HasSeam() )
673 list< TopoDS_Edge >::iterator eIt = edges.begin();
674 while ( helper.IsRealSeam( *eIt )) ++eIt;
675 if ( eIt != edges.end() )
678 TopAbs_Orientation fOri = helper.GetSubShapeOri( face, eNotSeam );
679 bool isForwad = ( fOri == eNotSeam.Orientation() || fOri >= TopAbs_INTERNAL );
681 // get all nodes from connected <edges>
682 bool isQuad = smDS->NbElements() ? smDS->GetElements()->next()->IsQuadratic() : false;
683 StdMeshers_FaceSide fSide( face, edges, _mesh, isForwad, isQuad );
684 const vector<UVPtStruct>& points = fSide.GetUVPtStruct();
685 int i, nbSeg = fSide.NbSegments();
687 // remember EDGEs of fSide to treat only once
688 for ( int iE = 0; iE < fSide.NbEdges(); ++iE )
689 visitedEdgeSM2Faces[ helper.GetMesh()->GetSubMesh( fSide.Edge(iE )) ].insert(faceSMDSId);
691 double otherSeamParam = 0;
696 int prevNgId = ngNodeId( points[0].node, ngMesh, nodeNgIdMap );
698 for ( i = 0; i < nbSeg; ++i )
700 const UVPtStruct& p1 = points[ i ];
701 const UVPtStruct& p2 = points[ i+1 ];
703 if ( p1.node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX ) //an EDGE begins
706 if ( helper.IsRealSeam( p1.node->getshapeId() ))
708 TopoDS_Edge e = fSide.Edge( fSide.EdgeIndex( 0.5 * ( p1.normParam + p2.normParam )));
709 isSeam = helper.IsRealSeam( e );
712 otherSeamParam = helper.GetOtherParam( helper.GetPeriodicIndex() & 1 ? p2.u : p2.v );
719 seg[1] = prevNgId = ngNodeId( p2.node, ngMesh, nodeNgIdMap );
720 // node param on curve
721 seg.epgeominfo[ 0 ].dist = p1.param;
722 seg.epgeominfo[ 1 ].dist = p2.param;
724 seg.epgeominfo[ 0 ].u = p1.u;
725 seg.epgeominfo[ 0 ].v = p1.v;
726 seg.epgeominfo[ 1 ].u = p2.u;
727 seg.epgeominfo[ 1 ].v = p2.v;
729 //geomEdge = fSide.Edge( fSide.EdgeIndex( 0.5 * ( p1.normParam + p2.normParam )));
730 //seg.epgeominfo[ 0 ].edgenr = seg.epgeominfo[ 1 ].edgenr = occgeom.emap.FindIndex( geomEdge );
732 //seg.epgeominfo[ iEnd ].edgenr = edgeID; // = geom.emap.FindIndex(edge);
733 seg.si = faceNgID; // = geom.fmap.FindIndex (face);
734 seg.edgenr = ngMesh.GetNSeg() + 1; // segment id
735 ngMesh.AddSegment (seg);
737 SMESH_TNodeXYZ np1( p1.node ), np2( p2.node );
738 RestrictLocalSize( ngMesh, 0.5*(np1+np2), (np1-np2).Modulus() );
741 cout << "Segment: " << seg.edgenr << " on SMESH face " << helper.GetMeshDS()->ShapeToIndex( face ) << endl
742 << "\tface index: " << seg.si << endl
743 << "\tp1: " << seg[0] << endl
744 << "\tp2: " << seg[1] << endl
745 << "\tp0 param: " << seg.epgeominfo[ 0 ].dist << endl
746 << "\tp0 uv: " << seg.epgeominfo[ 0 ].u <<", "<< seg.epgeominfo[ 0 ].v << endl
747 //<< "\tp0 edge: " << seg.epgeominfo[ 0 ].edgenr << endl
748 << "\tp1 param: " << seg.epgeominfo[ 1 ].dist << endl
749 << "\tp1 uv: " << seg.epgeominfo[ 1 ].u <<", "<< seg.epgeominfo[ 1 ].v << endl;
750 //<< "\tp1 edge: " << seg.epgeominfo[ 1 ].edgenr << endl;
754 if ( helper.GetPeriodicIndex() && 1 ) {
755 seg.epgeominfo[ 0 ].u = otherSeamParam;
756 seg.epgeominfo[ 1 ].u = otherSeamParam;
757 swap (seg.epgeominfo[0].v, seg.epgeominfo[1].v);
759 seg.epgeominfo[ 0 ].v = otherSeamParam;
760 seg.epgeominfo[ 1 ].v = otherSeamParam;
761 swap (seg.epgeominfo[0].u, seg.epgeominfo[1].u);
763 swap (seg[0], seg[1]);
764 swap (seg.epgeominfo[0].dist, seg.epgeominfo[1].dist);
765 seg.edgenr = ngMesh.GetNSeg() + 1; // segment id
766 ngMesh.AddSegment (seg);
768 cout << "Segment: " << seg.edgenr << endl
769 << "\t is SEAM (reverse) of the previous. "
770 << " Other " << (helper.GetPeriodicIndex() && 1 ? "U" : "V")
771 << " = " << otherSeamParam << endl;
774 else if ( fOri == TopAbs_INTERNAL )
776 swap (seg[0], seg[1]);
777 swap( seg.epgeominfo[0], seg.epgeominfo[1] );
778 seg.edgenr = ngMesh.GetNSeg() + 1; // segment id
779 ngMesh.AddSegment (seg);
781 cout << "Segment: " << seg.edgenr << endl << "\t is REVERSE of the previous" << endl;
785 } // loop on geomEdge ancestors
788 } // case TopAbs_EDGE
790 case TopAbs_FACE: { // FACE
791 // ----------------------
792 const TopoDS_Face& geomFace = TopoDS::Face( sm->GetSubShape() );
793 helper.SetSubShape( geomFace );
794 bool isInternalFace = ( geomFace.Orientation() == TopAbs_INTERNAL );
796 // Find solids the geomFace bounds
797 int solidID1 = 0, solidID2 = 0;
798 StdMeshers_QuadToTriaAdaptor* quadAdaptor =
799 dynamic_cast<StdMeshers_QuadToTriaAdaptor*>( proxyMesh.get() );
802 solidID1 = occgeom.somap.FindIndex( quadAdaptor->GetShape() );
806 PShapeIteratorPtr solidIt = helper.GetAncestors( geomFace, *sm->GetFather(), TopAbs_SOLID);
807 while ( const TopoDS_Shape * solid = solidIt->next() )
809 int id = occgeom.somap.FindIndex ( *solid );
810 if ( solidID1 && id != solidID1 ) solidID2 = id;
814 // Add ng face descriptors of meshed faces
816 ngMesh.AddFaceDescriptor (netgen::FaceDescriptor(faceNgID, solidID1, solidID2, 0));
818 // if second oreder is required, even already meshed faces must be passed to NETGEN
819 int fID = occgeom.fmap.Add( geomFace );
820 while ( fID < faceNgID ) // geomFace is already in occgeom.fmap, add a copy
821 fID = occgeom.fmap.Add( BRepBuilderAPI_Copy( geomFace, /*copyGeom=*/false ));
822 // Problem with the second order in a quadrangular mesh remains.
823 // 1) All quadrangles geberated by NETGEN are moved to an inexistent face
824 // by FillSMesh() (find AddFaceDescriptor)
825 // 2) Temporary triangles generated by StdMeshers_QuadToTriaAdaptor
826 // are on faces where quadrangles were.
827 // Due to these 2 points, wrong geom faces are used while conversion to qudratic
828 // of the mentioned above quadrangles and triangles
830 // Orient the face correctly in solidID1 (issue 0020206)
831 bool reverse = false;
833 TopoDS_Shape solid = occgeom.somap( solidID1 );
834 TopAbs_Orientation faceOriInSolid = helper.GetSubShapeOri( solid, geomFace );
835 if ( faceOriInSolid >= 0 )
836 reverse = SMESH_Algo::IsReversedSubMesh
837 ( TopoDS::Face( geomFace.Oriented( faceOriInSolid )), helper.GetMeshDS() );
840 // Add surface elements
842 netgen::Element2d tri(3);
843 tri.SetIndex ( faceNgID );
846 #ifdef DUMP_TRIANGLES
847 cout << "SMESH face " << helper.GetMeshDS()->ShapeToIndex( geomFace )
848 << " internal="<<isInternalFace << endl;
851 smDS = proxyMesh->GetSubMesh( geomFace );
853 SMDS_ElemIteratorPtr faces = smDS->GetElements();
854 while ( faces->more() )
856 const SMDS_MeshElement* f = faces->next();
857 if ( f->NbNodes() % 3 != 0 ) // not triangle
859 PShapeIteratorPtr solidIt=helper.GetAncestors(geomFace,*sm->GetFather(),TopAbs_SOLID);
860 if ( const TopoDS_Shape * solid = solidIt->next() )
861 sm = _mesh->GetSubMesh( *solid );
862 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
863 smError.reset( new SMESH_ComputeError(COMPERR_BAD_INPUT_MESH,"Not triangle submesh"));
864 smError->myBadElements.push_back( f );
868 for ( int i = 0; i < 3; ++i )
870 const SMDS_MeshNode* node = f->GetNode( i ), * inFaceNode=0;
872 // get node UV on face
873 int shapeID = node->getshapeId();
874 if ( helper.IsSeamShape( shapeID ))
875 if ( helper.IsSeamShape( f->GetNodeWrap( i+1 )->getshapeId() ))
876 inFaceNode = f->GetNodeWrap( i-1 );
878 inFaceNode = f->GetNodeWrap( i+1 );
879 gp_XY uv = helper.GetNodeUV( geomFace, node, inFaceNode );
881 int ind = reverse ? 3-i : i+1;
882 tri.GeomInfoPi(ind).u = uv.X();
883 tri.GeomInfoPi(ind).v = uv.Y();
884 tri.PNum (ind) = ngNodeId( node, ngMesh, nodeNgIdMap );
887 ngMesh.AddSurfaceElement (tri);
888 #ifdef DUMP_TRIANGLES
892 if ( isInternalFace )
894 swap( tri[1], tri[2] );
895 ngMesh.AddSurfaceElement (tri);
896 #ifdef DUMP_TRIANGLES
902 } // case TopAbs_FACE
904 case TopAbs_VERTEX: { // VERTEX
905 // --------------------------
906 // issue 0021405. Add node only if a VERTEX is shared by a not meshed EDGE,
907 // else netgen removes a free node and nodeVector becomes invalid
908 PShapeIteratorPtr ansIt = helper.GetAncestors( sm->GetSubShape(),
912 while ( const TopoDS_Shape* e = ansIt->next() )
914 SMESH_subMesh* eSub = helper.GetMesh()->GetSubMesh( *e );
915 if (( toAdd = eSub->IsEmpty() )) break;
919 SMDS_NodeIteratorPtr nodeIt = smDS->GetNodes();
920 if ( nodeIt->more() )
921 ngNodeId( nodeIt->next(), ngMesh, nodeNgIdMap );
927 } // loop on submeshes
930 nodeVec.resize( ngMesh.GetNP() + 1 );
931 TNode2IdMap::iterator node_NgId, nodeNgIdEnd = nodeNgIdMap.end();
932 for ( node_NgId = nodeNgIdMap.begin(); node_NgId != nodeNgIdEnd; ++node_NgId)
933 nodeVec[ node_NgId->second ] = node_NgId->first;
938 //================================================================================
940 * \brief Duplicate mesh faces on internal geom faces
942 //================================================================================
944 void NETGENPlugin_Mesher::fixIntFaces(const netgen::OCCGeometry& occgeom,
945 netgen::Mesh& ngMesh,
946 NETGENPlugin_Internals& internalShapes)
948 SMESHDS_Mesh* meshDS = internalShapes.getMesh().GetMeshDS();
950 // find ng indices of internal faces
952 for ( int ngFaceID = 1; ngFaceID <= occgeom.fmap.Extent(); ++ngFaceID )
954 int smeshID = meshDS->ShapeToIndex( occgeom.fmap( ngFaceID ));
955 if ( internalShapes.isInternalShape( smeshID ))
956 ngFaceIds.insert( ngFaceID );
958 if ( !ngFaceIds.empty() )
961 int i, nbFaces = ngMesh.GetNSE();
962 for (int i = 1; i <= nbFaces; ++i)
964 netgen::Element2d elem = ngMesh.SurfaceElement(i);
965 if ( ngFaceIds.count( elem.GetIndex() ))
967 swap( elem[1], elem[2] );
968 ngMesh.AddSurfaceElement (elem);
976 //================================================================================
977 // define gp_XY_Subtracted pointer to function calling gp_XY::Subtracted(gp_XY)
978 gp_XY_FunPtr(Subtracted);
979 //gp_XY_FunPtr(Added);
981 //================================================================================
983 * \brief Evaluate distance between two 2d points along the surface
985 //================================================================================
987 double evalDist( const gp_XY& uv1,
989 const Handle(Geom_Surface)& surf,
990 const int stopHandler=-1)
992 if ( stopHandler > 0 ) // continue recursion
994 gp_XY mid = SMESH_MesherHelper::GetMiddleUV( surf, uv1, uv2 );
995 return evalDist( uv1,mid, surf, stopHandler-1 ) + evalDist( mid,uv2, surf, stopHandler-1 );
997 double dist3D = surf->Value( uv1.X(), uv1.Y() ).Distance( surf->Value( uv2.X(), uv2.Y() ));
998 if ( stopHandler == 0 ) // stop recursion
1001 // start recursion if necessary
1002 double dist2D = SMESH_MesherHelper::applyIn2D(surf, uv1, uv2, gp_XY_Subtracted, 0).Modulus();
1003 if ( fabs( dist3D - dist2D ) < dist2D * 1e-10 )
1004 return dist3D; // equal parametrization of a planar surface
1006 return evalDist( uv1, uv2, surf, 3 ); // start recursion
1009 //================================================================================
1011 * \brief Data of vertex internal in geom face
1013 //================================================================================
1017 gp_XY uv; //!< UV in face parametric space
1018 int ngId; //!< ng id of corrsponding node
1019 gp_XY uvClose; //!< UV of closest boundary node
1020 int ngIdClose; //!< ng id of closest boundary node
1023 //================================================================================
1025 * \brief Data of vertex internal in solid
1027 //================================================================================
1031 int ngId; //!< ng id of corresponding node
1032 int ngIdClose; //!< ng id of closest 2d mesh element
1033 int ngIdCloseN; //!< ng id of closest node of the closest 2d mesh element
1036 inline double dist2(const netgen::MeshPoint& p1, const netgen::MeshPoint& p2)
1038 return gp_Pnt( NGPOINT_COORDS(p1)).SquareDistance( gp_Pnt( NGPOINT_COORDS(p2)));
1042 //================================================================================
1044 * \brief Make netgen take internal vertices in faces into account by adding
1045 * segments including internal vertices
1047 * This function works in supposition that 1D mesh is already computed in ngMesh
1049 //================================================================================
1051 void NETGENPlugin_Mesher::addIntVerticesInFaces(const netgen::OCCGeometry& occgeom,
1052 netgen::Mesh& ngMesh,
1053 vector<const SMDS_MeshNode*>& nodeVec,
1054 NETGENPlugin_Internals& internalShapes)
1056 if ( nodeVec.size() < ngMesh.GetNP() )
1057 nodeVec.resize( ngMesh.GetNP(), 0 );
1059 SMESHDS_Mesh* meshDS = internalShapes.getMesh().GetMeshDS();
1060 SMESH_MesherHelper helper( internalShapes.getMesh() );
1062 const map<int,list<int> >& face2Vert = internalShapes.getFacesWithVertices();
1063 map<int,list<int> >::const_iterator f2v = face2Vert.begin();
1064 for ( ; f2v != face2Vert.end(); ++f2v )
1066 const TopoDS_Face& face = TopoDS::Face( meshDS->IndexToShape( f2v->first ));
1067 if ( face.IsNull() ) continue;
1068 int faceNgID = occgeom.fmap.FindIndex (face);
1069 if ( faceNgID < 0 ) continue;
1071 TopLoc_Location loc;
1072 Handle(Geom_Surface) surf = BRep_Tool::Surface(face,loc);
1074 helper.SetSubShape( face );
1075 helper.SetElementsOnShape( true );
1077 // Get data of internal vertices and add them to ngMesh
1079 multimap< double, TIntVData > dist2VData; // sort vertices by distance from boundary nodes
1081 int i, nbSegInit = ngMesh.GetNSeg();
1083 // boundary characteristics
1084 double totSegLen2D = 0;
1087 const list<int>& iVertices = f2v->second;
1088 list<int>::const_iterator iv = iVertices.begin();
1089 for ( int nbV = 0; iv != iVertices.end(); ++iv, nbV++ )
1092 // get node on vertex
1093 const TopoDS_Vertex V = TopoDS::Vertex( meshDS->IndexToShape( *iv ));
1094 const SMDS_MeshNode * nV = SMESH_Algo::VertexNode( V, meshDS );
1097 SMESH_subMesh* sm = helper.GetMesh()->GetSubMesh( V );
1098 sm->ComputeStateEngine( SMESH_subMesh::COMPUTE );
1099 nV = SMESH_Algo::VertexNode( V, meshDS );
1100 if ( !nV ) continue;
1103 netgen::MeshPoint mp( netgen::Point<3> (nV->X(), nV->Y(), nV->Z()) );
1104 ngMesh.AddPoint ( mp, 1, netgen::EDGEPOINT );
1105 vData.ngId = ngMesh.GetNP();
1106 nodeVec.push_back( nV );
1110 vData.uv = helper.GetNodeUV( face, nV, 0, &uvOK );
1111 if ( !uvOK ) helper.CheckNodeUV( face, nV, vData.uv, BRep_Tool::Tolerance(V),/*force=*/1);
1113 // loop on all segments of the face to find the node closest to vertex and to count
1114 // average segment 2d length
1115 double closeDist2 = numeric_limits<double>::max(), dist2;
1117 for (i = 1; i <= ngMesh.GetNSeg(); ++i)
1119 netgen::Segment & seg = ngMesh.LineSegment(i);
1120 if ( seg.si != faceNgID ) continue;
1122 for ( int iEnd = 0; iEnd < 2; ++iEnd)
1124 uv[iEnd].SetCoord( seg.epgeominfo[iEnd].u, seg.epgeominfo[iEnd].v );
1125 if ( ngIdLast == seg[ iEnd ] ) continue;
1126 dist2 = helper.applyIn2D(surf, uv[iEnd], vData.uv, gp_XY_Subtracted,0).SquareModulus();
1127 if ( dist2 < closeDist2 )
1128 vData.ngIdClose = seg[ iEnd ], vData.uvClose = uv[iEnd], closeDist2 = dist2;
1129 ngIdLast = seg[ iEnd ];
1133 totSegLen2D += helper.applyIn2D(surf, uv[0], uv[1], gp_XY_Subtracted, false).Modulus();
1137 dist2VData.insert( make_pair( closeDist2, vData ));
1140 if ( totNbSeg == 0 ) break;
1141 double avgSegLen2d = totSegLen2D / totNbSeg;
1143 // Loop on vertices to add segments
1145 multimap< double, TIntVData >::iterator dist_vData = dist2VData.begin();
1146 for ( ; dist_vData != dist2VData.end(); ++dist_vData )
1148 double closeDist2 = dist_vData->first, dist2;
1149 TIntVData & vData = dist_vData->second;
1151 // try to find more close node among segments added for internal vertices
1152 for (i = nbSegInit+1; i <= ngMesh.GetNSeg(); ++i)
1154 netgen::Segment & seg = ngMesh.LineSegment(i);
1155 if ( seg.si != faceNgID ) continue;
1157 for ( int iEnd = 0; iEnd < 2; ++iEnd)
1159 uv[iEnd].SetCoord( seg.epgeominfo[iEnd].u, seg.epgeominfo[iEnd].v );
1160 dist2 = helper.applyIn2D(surf, uv[iEnd], vData.uv, gp_XY_Subtracted,0).SquareModulus();
1161 if ( dist2 < closeDist2 )
1162 vData.ngIdClose = seg[ iEnd ], vData.uvClose = uv[iEnd], closeDist2 = dist2;
1165 // decide whether to use the closest node as the second end of segment or to
1166 // create a new point
1167 int segEnd1 = vData.ngId;
1168 int segEnd2 = vData.ngIdClose; // to use closest node
1169 gp_XY uvV = vData.uv, uvP = vData.uvClose;
1170 double segLenHint = ngMesh.GetH( ngMesh.Point( vData.ngId ));
1171 double nodeDist2D = sqrt( closeDist2 );
1172 double nodeDist3D = evalDist( vData.uv, vData.uvClose, surf );
1173 bool avgLenOK = ( avgSegLen2d < 0.75 * nodeDist2D );
1174 bool hintLenOK = ( segLenHint < 0.75 * nodeDist3D );
1175 //cout << "uvV " << uvV.X() <<","<<uvV.Y() << " ";
1176 if ( hintLenOK || avgLenOK )
1178 // create a point between the closest node and V
1181 double r = min( 0.5, ( hintLenOK ? segLenHint/nodeDist3D : avgSegLen2d/nodeDist2D ));
1182 // direction from V to closet node in 2D
1183 gp_Dir2d v2n( helper.applyIn2D(surf, uvP, uvV, gp_XY_Subtracted, false ));
1185 uvP = vData.uv + r * nodeDist2D * v2n.XY();
1186 gp_Pnt P = surf->Value( uvP.X(), uvP.Y() ).Transformed( loc );
1188 netgen::MeshPoint mp( netgen::Point<3> (P.X(), P.Y(), P.Z()));
1189 ngMesh.AddPoint ( mp, 1, netgen::EDGEPOINT );
1190 segEnd2 = ngMesh.GetNP();
1191 //cout << "Middle " << r << " uv " << uvP.X() << "," << uvP.Y() << "( " << ngMesh.Point(segEnd2).X()<<","<<ngMesh.Point(segEnd2).Y()<<","<<ngMesh.Point(segEnd2).Z()<<" )"<< endl;
1192 SMDS_MeshNode * nP = helper.AddNode(P.X(), P.Y(), P.Z());
1193 nodeVec.push_back( nP );
1195 //else cout << "at Node " << " uv " << uvP.X() << "," << uvP.Y() << endl;
1198 netgen::Segment seg;
1200 if ( segEnd1 > segEnd2 ) swap( segEnd1, segEnd2 ), swap( uvV, uvP );
1201 seg[0] = segEnd1; // ng node id
1202 seg[1] = segEnd2; // ng node id
1203 seg.edgenr = ngMesh.GetNSeg() + 1;// segment id
1206 seg.epgeominfo[ 0 ].dist = 0; // param on curve
1207 seg.epgeominfo[ 0 ].u = uvV.X();
1208 seg.epgeominfo[ 0 ].v = uvV.Y();
1209 seg.epgeominfo[ 1 ].dist = 1; // param on curve
1210 seg.epgeominfo[ 1 ].u = uvP.X();
1211 seg.epgeominfo[ 1 ].v = uvP.Y();
1213 // seg.epgeominfo[ 0 ].edgenr = 10; // = geom.emap.FindIndex(edge);
1214 // seg.epgeominfo[ 1 ].edgenr = 10; // = geom.emap.FindIndex(edge);
1216 ngMesh.AddSegment (seg);
1218 // add reverse segment
1219 swap (seg[0], seg[1]);
1220 swap( seg.epgeominfo[0], seg.epgeominfo[1] );
1221 seg.edgenr = ngMesh.GetNSeg() + 1; // segment id
1222 ngMesh.AddSegment (seg);
1228 //================================================================================
1230 * \brief Make netgen take internal vertices in solids into account by adding
1231 * faces including internal vertices
1233 * This function works in supposition that 2D mesh is already computed in ngMesh
1235 //================================================================================
1237 void NETGENPlugin_Mesher::addIntVerticesInSolids(const netgen::OCCGeometry& occgeom,
1238 netgen::Mesh& ngMesh,
1239 vector<const SMDS_MeshNode*>& nodeVec,
1240 NETGENPlugin_Internals& internalShapes)
1242 #ifdef DUMP_TRIANGLES_SCRIPT
1243 // create a python script making a mesh containing triangles added for internal vertices
1244 ofstream py(DUMP_TRIANGLES_SCRIPT);
1245 py << "from smesh import * "<< endl
1246 << "m = Mesh(name='triangles')" << endl;
1248 if ( nodeVec.size() < ngMesh.GetNP() )
1249 nodeVec.resize( ngMesh.GetNP(), 0 );
1251 SMESHDS_Mesh* meshDS = internalShapes.getMesh().GetMeshDS();
1252 SMESH_MesherHelper helper( internalShapes.getMesh() );
1254 const map<int,list<int> >& so2Vert = internalShapes.getSolidsWithVertices();
1255 map<int,list<int> >::const_iterator s2v = so2Vert.begin();
1256 for ( ; s2v != so2Vert.end(); ++s2v )
1258 const TopoDS_Shape& solid = meshDS->IndexToShape( s2v->first );
1259 if ( solid.IsNull() ) continue;
1260 int solidNgID = occgeom.somap.FindIndex (solid);
1261 if ( solidNgID < 0 && !occgeom.somap.IsEmpty() ) continue;
1263 helper.SetSubShape( solid );
1264 helper.SetElementsOnShape( true );
1266 // find ng indices of faces within the solid
1268 for (TopExp_Explorer fExp(solid, TopAbs_FACE); fExp.More(); fExp.Next() )
1269 ngFaceIds.insert( occgeom.fmap.FindIndex( fExp.Current() ));
1270 if ( ngFaceIds.size() == 1 && *ngFaceIds.begin() == 0 )
1271 ngFaceIds.insert( 1 );
1273 // Get data of internal vertices and add them to ngMesh
1275 multimap< double, TIntVSoData > dist2VData; // sort vertices by distance from ng faces
1277 int i, nbFaceInit = ngMesh.GetNSE();
1279 // boundary characteristics
1280 double totSegLen = 0;
1283 const list<int>& iVertices = s2v->second;
1284 list<int>::const_iterator iv = iVertices.begin();
1285 for ( int nbV = 0; iv != iVertices.end(); ++iv, nbV++ )
1288 const TopoDS_Vertex V = TopoDS::Vertex( meshDS->IndexToShape( *iv ));
1290 // get node on vertex
1291 const SMDS_MeshNode * nV = SMESH_Algo::VertexNode( V, meshDS );
1294 SMESH_subMesh* sm = helper.GetMesh()->GetSubMesh( V );
1295 sm->ComputeStateEngine( SMESH_subMesh::COMPUTE );
1296 nV = SMESH_Algo::VertexNode( V, meshDS );
1297 if ( !nV ) continue;
1300 netgen::MeshPoint mpV( netgen::Point<3> (nV->X(), nV->Y(), nV->Z()) );
1301 ngMesh.AddPoint ( mpV, 1, netgen::FIXEDPOINT );
1302 vData.ngId = ngMesh.GetNP();
1303 nodeVec.push_back( nV );
1305 // loop on all 2d elements to find the one closest to vertex and to count
1306 // average segment length
1307 double closeDist2 = numeric_limits<double>::max(), avgDist2;
1308 for (i = 1; i <= ngMesh.GetNSE(); ++i)
1310 const netgen::Element2d& elem = ngMesh.SurfaceElement(i);
1311 if ( !ngFaceIds.count( elem.GetIndex() )) continue;
1313 multimap< double, int> dist2nID; // sort nodes of element by distance from V
1314 for ( int j = 0; j < elem.GetNP(); ++j)
1316 netgen::MeshPoint mp = ngMesh.Point( elem[j] );
1317 double d2 = dist2( mpV, mp );
1318 dist2nID.insert( make_pair( d2, elem[j] ));
1319 avgDist2 += d2 / elem.GetNP();
1321 totNbSeg++, totSegLen+= sqrt( dist2( mp, ngMesh.Point( elem[(j+1)%elem.GetNP()])));
1323 double dist = dist2nID.begin()->first; //avgDist2;
1324 if ( dist < closeDist2 )
1325 vData.ngIdClose= i, vData.ngIdCloseN= dist2nID.begin()->second, closeDist2= dist;
1327 dist2VData.insert( make_pair( closeDist2, vData ));
1330 if ( totNbSeg == 0 ) break;
1331 double avgSegLen = totSegLen / totNbSeg;
1333 // Loop on vertices to add triangles
1335 multimap< double, TIntVSoData >::iterator dist_vData = dist2VData.begin();
1336 for ( ; dist_vData != dist2VData.end(); ++dist_vData )
1338 double closeDist2 = dist_vData->first;
1339 TIntVSoData & vData = dist_vData->second;
1341 const netgen::MeshPoint& mpV = ngMesh.Point( vData.ngId );
1343 // try to find more close face among ones added for internal vertices
1344 for (i = nbFaceInit+1; i <= ngMesh.GetNSE(); ++i)
1346 double avgDist2 = 0;
1347 multimap< double, int> dist2nID;
1348 const netgen::Element2d& elem = ngMesh.SurfaceElement(i);
1349 for ( int j = 0; j < elem.GetNP(); ++j)
1351 double d = dist2( mpV, ngMesh.Point( elem[j] ));
1352 dist2nID.insert( make_pair( d, elem[j] ));
1353 avgDist2 += d / elem.GetNP();
1354 if ( avgDist2 < closeDist2 )
1355 vData.ngIdClose= i, vData.ngIdCloseN= dist2nID.begin()->second, closeDist2= avgDist2;
1358 // sort nodes of the closest face by angle with vector from V to the closest node
1359 const double tol = numeric_limits<double>::min();
1360 map< double, int > angle2ID;
1361 const netgen::Element2d& closeFace = ngMesh.SurfaceElement( vData.ngIdClose );
1362 netgen::MeshPoint mp[2];
1363 mp[0] = ngMesh.Point( vData.ngIdCloseN );
1364 gp_XYZ p1( NGPOINT_COORDS( mp[0] ));
1365 gp_XYZ pV( NGPOINT_COORDS( mpV ));
1366 gp_Vec v2p1( pV, p1 );
1367 double distN1 = v2p1.Magnitude();
1368 if ( distN1 <= tol ) continue;
1370 for ( int j = 0; j < closeFace.GetNP(); ++j)
1372 mp[1] = ngMesh.Point( closeFace[j] );
1373 gp_Vec v2p( pV, gp_Pnt( NGPOINT_COORDS( mp[1] )) );
1374 angle2ID.insert( make_pair( v2p1.Angle( v2p ), closeFace[j]));
1376 // get node with angle of 60 degrees or greater
1377 map< double, int >::iterator angle_id = angle2ID.lower_bound( 60. * M_PI / 180. );
1378 if ( angle_id == angle2ID.end() ) angle_id = --angle2ID.end();
1379 const double minAngle = 30. * M_PI / 180.;
1380 const double angle = angle_id->first;
1381 bool angleOK = ( angle > minAngle );
1383 // find points to create a triangle
1384 netgen::Element2d tri(3);
1386 tri[0] = vData.ngId;
1387 tri[1] = vData.ngIdCloseN; // to use the closest nodes
1388 tri[2] = angle_id->second; // to use the node with best angle
1390 // decide whether to use the closest node and the node with best angle or to create new ones
1391 for ( int isBestAngleN = 0; isBestAngleN < 2; ++isBestAngleN )
1393 bool createNew = !angleOK, distOK = true;
1395 int triInd = isBestAngleN ? 2 : 1;
1396 mp[isBestAngleN] = ngMesh.Point( tri[triInd] );
1401 double distN2 = sqrt( dist2( mpV, mp[isBestAngleN]));
1402 createNew = ( fabs( distN2 - distN1 ) > 0.25 * distN1 );
1404 else if ( angle < tol )
1406 v2p1.SetX( v2p1.X() + 1e-3 );
1412 double segLenHint = ngMesh.GetH( ngMesh.Point( vData.ngId ));
1413 bool avgLenOK = ( avgSegLen < 0.75 * distN1 );
1414 bool hintLenOK = ( segLenHint < 0.75 * distN1 );
1415 createNew = (createNew || avgLenOK || hintLenOK );
1416 // we create a new node not closer than 0.5 to the closest face
1417 // in order not to clash with other close face
1418 double r = min( 0.5, ( hintLenOK ? segLenHint : avgSegLen ) / distN1 );
1419 distFromV = r * distN1;
1423 // create a new point, between the node and the vertex if angleOK
1424 gp_XYZ p( NGPOINT_COORDS( mp[isBestAngleN] ));
1425 gp_Vec v2p( pV, p ); v2p.Normalize();
1426 if ( isBestAngleN && !angleOK )
1427 p = p1 + gp_Dir( v2p.XYZ() - v2p1.XYZ()).XYZ() * distN1 * 0.95;
1429 p = pV + v2p.XYZ() * distFromV;
1431 if ( !isBestAngleN ) p1 = p, distN1 = distFromV;
1433 mp[isBestAngleN].SetPoint( netgen::Point<3> (p.X(), p.Y(), p.Z()));
1434 ngMesh.AddPoint ( mp[isBestAngleN], 1, netgen::SURFACEPOINT );
1435 tri[triInd] = ngMesh.GetNP();
1436 nodeVec.push_back( helper.AddNode( p.X(), p.Y(), p.Z()) );
1439 ngMesh.AddSurfaceElement (tri);
1440 swap( tri[1], tri[2] );
1441 ngMesh.AddSurfaceElement (tri);
1443 #ifdef DUMP_TRIANGLES_SCRIPT
1444 py << "n1 = m.AddNode( "<< mpV.X()<<", "<< mpV.Y()<<", "<< mpV.Z()<<") "<< endl
1445 << "n2 = m.AddNode( "<< mp[0].X()<<", "<< mp[0].Y()<<", "<< mp[0].Z()<<") "<< endl
1446 << "n3 = m.AddNode( "<< mp[1].X()<<", "<< mp[1].Y()<<", "<< mp[1].Z()<<" )" << endl
1447 << "m.AddFace([n1,n2,n3])" << endl;
1449 } // loop on internal vertices of a solid
1451 } // loop on solids with internal vertices
1454 //================================================================================
1456 * \brief Fill SMESH mesh according to contents of netgen mesh
1457 * \param occgeo - container of OCCT geometry to mesh
1458 * \param ngMesh - netgen mesh
1459 * \param initState - bn of entities in netgen mesh before computing
1460 * \param sMesh - SMESH mesh to fill in
1461 * \param nodeVec - vector of nodes in which node index == netgen ID
1462 * \retval int - error
1464 //================================================================================
1466 int NETGENPlugin_Mesher::FillSMesh(const netgen::OCCGeometry& occgeo,
1467 netgen::Mesh& ngMesh,
1468 const NETGENPlugin_ngMeshInfo& initState,
1470 std::vector<const SMDS_MeshNode*>& nodeVec,
1471 SMESH_Comment& comment)
1473 int nbNod = ngMesh.GetNP();
1474 int nbSeg = ngMesh.GetNSeg();
1475 int nbFac = ngMesh.GetNSE();
1476 int nbVol = ngMesh.GetNE();
1478 SMESHDS_Mesh* meshDS = sMesh.GetMeshDS();
1480 // -------------------------------------
1481 // Create and insert nodes into nodeVec
1482 // -------------------------------------
1484 nodeVec.resize( nbNod + 1 );
1485 int i, nbInitNod = initState._nbNodes;
1486 for (i = nbInitNod+1; i <= nbNod; ++i )
1488 const netgen::MeshPoint& ngPoint = ngMesh.Point(i);
1489 SMDS_MeshNode* node = NULL;
1490 TopoDS_Vertex aVert;
1491 // First, netgen creates nodes on vertices in occgeo.vmap,
1492 // so node index corresponds to vertex index
1493 // but (issue 0020776) netgen does not create nodes with equal coordinates
1494 if ( i-nbInitNod <= occgeo.vmap.Extent() )
1496 gp_Pnt p ( NGPOINT_COORDS(ngPoint) );
1497 for (int iV = i-nbInitNod; aVert.IsNull() && iV <= occgeo.vmap.Extent(); ++iV)
1499 aVert = TopoDS::Vertex( occgeo.vmap( iV ) );
1500 gp_Pnt pV = BRep_Tool::Pnt( aVert );
1501 if ( p.SquareDistance( pV ) > 1e-20 )
1504 node = const_cast<SMDS_MeshNode*>( SMESH_Algo::VertexNode( aVert, meshDS ));
1507 if (!node) // node not found on vertex
1509 node = meshDS->AddNode( NGPOINT_COORDS( ngPoint ));
1510 if (!aVert.IsNull())
1511 meshDS->SetNodeOnVertex(node, aVert);
1516 // -------------------------------------------
1517 // Create mesh segments along geometric edges
1518 // -------------------------------------------
1520 int nbInitSeg = initState._nbSegments;
1521 for (i = nbInitSeg+1; i <= nbSeg; ++i )
1523 const netgen::Segment& seg = ngMesh.LineSegment(i);
1526 int pinds[3] = { seg.pnums[0], seg.pnums[1], seg.pnums[2] };
1528 int pinds[3] = { seg.p1, seg.p2, seg.pmid };
1532 for (int j=0; j < 3; ++j)
1534 int pind = pinds[j];
1535 if (pind <= 0 || !nodeVec_ACCESS(pind))
1543 int aGeomEdgeInd = seg.epgeominfo[j].edgenr;
1544 if (aGeomEdgeInd > 0 && aGeomEdgeInd <= occgeo.emap.Extent())
1545 aEdge = TopoDS::Edge(occgeo.emap(aGeomEdgeInd));
1547 param = seg.epgeominfo[j].dist;
1550 else // middle point
1552 param = param2 * 0.5;
1554 if (!aEdge.IsNull() && nodeVec_ACCESS(pind)->getshapeId() < 1)
1556 meshDS->SetNodeOnEdge(nodeVec_ACCESS(pind), aEdge, param);
1561 SMDS_MeshEdge* edge = 0;
1562 if (nbp == 2) // second order ?
1564 if ( meshDS->FindEdge( nodeVec_ACCESS(pinds[0]), nodeVec_ACCESS(pinds[1])))
1566 edge = meshDS->AddEdge(nodeVec_ACCESS(pinds[0]), nodeVec_ACCESS(pinds[1]));
1570 if ( meshDS->FindEdge( nodeVec_ACCESS(pinds[0]), nodeVec_ACCESS(pinds[1]),
1571 nodeVec_ACCESS(pinds[2])))
1573 edge = meshDS->AddEdge(nodeVec_ACCESS(pinds[0]), nodeVec_ACCESS(pinds[1]),
1574 nodeVec_ACCESS(pinds[2]));
1578 if ( comment.empty() ) comment << "Cannot create a mesh edge";
1579 MESSAGE("Cannot create a mesh edge");
1580 nbSeg = nbFac = nbVol = 0;
1583 if ( !aEdge.IsNull() && edge->getshapeId() < 1 )
1584 meshDS->SetMeshElementOnShape(edge, aEdge);
1586 else if ( comment.empty() )
1588 comment << "Invalid netgen segment #" << i;
1592 // ----------------------------------------
1593 // Create mesh faces along geometric faces
1594 // ----------------------------------------
1596 int nbInitFac = initState._nbFaces;
1597 int quadFaceID = ngMesh.GetNFD() + 1;
1598 if ( nbInitFac < nbFac )
1599 // add a faces descriptor to exclude qudrangle elements generated by NETGEN
1600 // from computation of 3D mesh
1601 ngMesh.AddFaceDescriptor (netgen::FaceDescriptor(quadFaceID, /*solid1=*/0, /*solid2=*/0, 0));
1603 for (i = nbInitFac+1; i <= nbFac; ++i )
1605 const netgen::Element2d& elem = ngMesh.SurfaceElement(i);
1606 int aGeomFaceInd = elem.GetIndex();
1608 if (aGeomFaceInd > 0 && aGeomFaceInd <= occgeo.fmap.Extent())
1609 aFace = TopoDS::Face(occgeo.fmap(aGeomFaceInd));
1610 vector<SMDS_MeshNode*> nodes;
1611 for (int j=1; j <= elem.GetNP(); ++j)
1613 int pind = elem.PNum(j);
1614 if ( pind < 1 || pind >= nodeVec.size() )
1616 if ( SMDS_MeshNode* node = nodeVec_ACCESS(pind))
1618 nodes.push_back(node);
1619 if (!aFace.IsNull() && node->getshapeId() < 1)
1621 const netgen::PointGeomInfo& pgi = elem.GeomInfoPi(j);
1622 meshDS->SetNodeOnFace(node, aFace, pgi.u, pgi.v);
1626 if ( nodes.size() != elem.GetNP() )
1628 if ( comment.empty() )
1629 comment << "Invalid netgen 2d element #" << i;
1630 continue; // bad node ids
1632 SMDS_MeshFace* face = NULL;
1633 switch (elem.GetType())
1636 face = meshDS->AddFace(nodes[0],nodes[1],nodes[2]);
1639 face = meshDS->AddFace(nodes[0],nodes[1],nodes[2],nodes[3]);
1640 // exclude qudrangle elements from computation of 3D mesh
1641 const_cast< netgen::Element2d& >( elem ).SetIndex( quadFaceID );
1644 face = meshDS->AddFace(nodes[0],nodes[1],nodes[2],nodes[5],nodes[3],nodes[4]);
1647 face = meshDS->AddFace(nodes[0],nodes[1],nodes[2],nodes[3],
1648 nodes[4],nodes[7],nodes[5],nodes[6]);
1649 // exclude qudrangle elements from computation of 3D mesh
1650 const_cast< netgen::Element2d& >( elem ).SetIndex( quadFaceID );
1653 MESSAGE("NETGEN created a face of unexpected type, ignoring");
1658 if ( comment.empty() ) comment << "Cannot create a mesh face";
1659 MESSAGE("Cannot create a mesh face");
1660 nbSeg = nbFac = nbVol = 0;
1663 if (!aFace.IsNull())
1664 meshDS->SetMeshElementOnShape(face, aFace);
1667 // ------------------
1668 // Create tetrahedra
1669 // ------------------
1671 for (i = 1; i <= nbVol; ++i)
1673 const netgen::Element& elem = ngMesh.VolumeElement(i);
1674 int aSolidInd = elem.GetIndex();
1675 TopoDS_Solid aSolid;
1676 if (aSolidInd > 0 && aSolidInd <= occgeo.somap.Extent())
1677 aSolid = TopoDS::Solid(occgeo.somap(aSolidInd));
1678 vector<SMDS_MeshNode*> nodes;
1679 for (int j=1; j <= elem.GetNP(); ++j)
1681 int pind = elem.PNum(j);
1682 if ( pind < 1 || pind >= nodeVec.size() )
1684 if ( SMDS_MeshNode* node = nodeVec_ACCESS(pind) )
1686 nodes.push_back(node);
1687 if ( !aSolid.IsNull() && node->getshapeId() < 1 )
1688 meshDS->SetNodeInVolume(node, aSolid);
1691 if ( nodes.size() != elem.GetNP() )
1693 if ( comment.empty() )
1694 comment << "Invalid netgen 3d element #" << i;
1697 SMDS_MeshVolume* vol = NULL;
1698 switch (elem.GetType())
1701 vol = meshDS->AddVolume(nodes[0],nodes[1],nodes[2],nodes[3]);
1704 vol = meshDS->AddVolume(nodes[0],nodes[1],nodes[2],nodes[3],
1705 nodes[4],nodes[7],nodes[5],nodes[6],nodes[8],nodes[9]);
1708 MESSAGE("NETGEN created a volume of unexpected type, ignoring");
1713 if ( comment.empty() ) comment << "Cannot create a mesh volume";
1714 MESSAGE("Cannot create a mesh volume");
1715 nbSeg = nbFac = nbVol = 0;
1718 if (!aSolid.IsNull())
1719 meshDS->SetMeshElementOnShape(vol, aSolid);
1721 return comment.empty() ? 0 : 1;
1726 //================================================================================
1728 * \brief Restrict size of elements on the given edge
1730 //================================================================================
1732 void setLocalSize(const TopoDS_Edge& edge,
1736 const int nb = 1000;
1737 Standard_Real u1, u2;
1738 Handle(Geom_Curve) curve = BRep_Tool::Curve(edge, u1, u2);
1739 if ( curve.IsNull() )
1741 TopoDS_Iterator vIt( edge );
1742 if ( !vIt.More() ) return;
1743 gp_Pnt p = BRep_Tool::Pnt( TopoDS::Vertex( vIt.Value() ));
1744 NETGENPlugin_Mesher::RestrictLocalSize( mesh, p.XYZ(), size );
1748 Standard_Real delta = (u2-u1)/nb;
1749 for(int i=0; i<nb; i++)
1751 Standard_Real u = u1 + delta*i;
1752 gp_Pnt p = curve->Value(u);
1753 NETGENPlugin_Mesher::RestrictLocalSize( mesh, p.XYZ(), size );
1754 netgen::Point3d pi(p.X(), p.Y(), p.Z());
1755 double resultSize = mesh.GetH(pi);
1756 if ( resultSize - size > 0.1*size )
1757 // netgen does restriction iff oldH/newH > 1.2 (localh.cpp:136)
1758 NETGENPlugin_Mesher::RestrictLocalSize( mesh, p.XYZ(), resultSize/1.201 );
1763 //================================================================================
1765 * \brief Convert error into text
1767 //================================================================================
1769 std::string text(int err)
1774 SMESH_Comment("Error in netgen::OCCGenerateMesh() at ") << netgen::multithread.task;
1777 //================================================================================
1779 * \brief Convert exception into text
1781 //================================================================================
1783 std::string text(Standard_Failure& ex)
1785 SMESH_Comment str("Exception in netgen::OCCGenerateMesh()");
1786 str << " at " << netgen::multithread.task
1787 << ": " << ex.DynamicType()->Name();
1788 if ( ex.GetMessageString() && strlen( ex.GetMessageString() ))
1789 str << ": " << ex.GetMessageString();
1792 //================================================================================
1794 * \brief Convert exception into text
1796 //================================================================================
1798 std::string text(netgen::NgException& ex)
1800 SMESH_Comment str("NgException");
1801 str << " at " << netgen::multithread.task << ": " << ex.What();
1806 //=============================================================================
1808 * Here we are going to use the NETGEN mesher
1810 //=============================================================================
1812 bool NETGENPlugin_Mesher::Compute()
1814 NETGENPlugin_NetgenLibWrapper ngLib;
1816 netgen::MeshingParameters& mparams = netgen::mparam;
1817 MESSAGE("Compute with:\n"
1818 " max size = " << mparams.maxh << "\n"
1819 " segments per edge = " << mparams.segmentsperedge);
1821 " growth rate = " << mparams.grading << "\n"
1822 " elements per radius = " << mparams.curvaturesafety << "\n"
1823 " second order = " << mparams.secondorder << "\n"
1824 " quad allowed = " << mparams.quad);
1825 cout << " quad allowed = " << mparams.quad<<endl;
1827 SMESH_ComputeErrorPtr error = SMESH_ComputeError::New();
1830 // -------------------------
1831 // Prepare OCC geometry
1832 // -------------------------
1834 netgen::OCCGeometry occgeo;
1835 list< SMESH_subMesh* > meshedSM[3]; // for 0-2 dimensions
1836 NETGENPlugin_Internals internals( *_mesh, _shape, _isVolume );
1837 PrepareOCCgeometry( occgeo, _shape, *_mesh, meshedSM, &internals );
1839 // -------------------------
1840 // Generate the mesh
1841 // -------------------------
1843 netgen::Mesh *ngMesh = NULL;
1844 NETGENPlugin_ngMeshInfo initState; // it remembers size of ng mesh equal to size of Smesh
1846 SMESH_Comment comment;
1849 // vector of nodes in which node index == netgen ID
1850 vector< const SMDS_MeshNode* > nodeVec;
1858 // not to RestrictLocalH() according to curvature during MESHCONST_ANALYSE
1859 mparams.uselocalh = false;
1860 mparams.grading = 0.8; // not limitited size growth
1862 if ( _simpleHyp->GetNumberOfSegments() )
1864 mparams.maxh = occgeo.boundingbox.Diam();
1867 mparams.maxh = _simpleHyp->GetLocalLength();
1870 if ( mparams.maxh == 0.0 )
1871 mparams.maxh = occgeo.boundingbox.Diam();
1872 if ( _simpleHyp || ( mparams.minh == 0.0 && _fineness != NETGENPlugin_Hypothesis::UserDefined))
1873 mparams.minh = GetDefaultMinSize( _shape, mparams.maxh );
1876 // Local size on faces
1877 occgeo.face_maxh = mparams.maxh;
1880 // Let netgen create ngMesh and calculate element size on not meshed shapes
1882 int startWith = netgen::MESHCONST_ANALYSE;
1883 int endWith = netgen::MESHCONST_ANALYSE;
1887 err = netgen::OCCGenerateMesh(occgeo, ngMesh, startWith, endWith, optstr);
1888 #ifdef WITH_SMESH_CANCEL_COMPUTE
1889 if(netgen::multithread.terminate)
1892 comment << text(err);
1894 catch (Standard_Failure& ex)
1896 comment << text(ex);
1898 err = 0; //- MESHCONST_ANALYSE isn't so important step
1901 ngLib.setMesh(( Ng_Mesh*) ngMesh );
1903 ngMesh->ClearFaceDescriptors(); // we make descriptors our-self
1907 // Pass 1D simple parameters to NETGEN
1908 // --------------------------------
1909 int nbSeg = _simpleHyp->GetNumberOfSegments();
1910 double segSize = _simpleHyp->GetLocalLength();
1911 for ( int iE = 1; iE <= occgeo.emap.Extent(); ++iE )
1913 const TopoDS_Edge& e = TopoDS::Edge( occgeo.emap(iE));
1915 segSize = SMESH_Algo::EdgeLength( e ) / ( nbSeg - 0.4 );
1916 setLocalSize( e, segSize, *ngMesh );
1919 else // if ( ! _simpleHyp )
1921 // Local size on vertices and edges
1922 // --------------------------------
1923 for(std::map<int,double>::const_iterator it=EdgeId2LocalSize.begin(); it!=EdgeId2LocalSize.end(); it++)
1925 int key = (*it).first;
1926 double hi = (*it).second;
1927 const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
1928 const TopoDS_Edge& e = TopoDS::Edge(shape);
1929 setLocalSize( e, hi, *ngMesh );
1931 for(std::map<int,double>::const_iterator it=VertexId2LocalSize.begin(); it!=VertexId2LocalSize.end(); it++)
1933 int key = (*it).first;
1934 double hi = (*it).second;
1935 const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
1936 const TopoDS_Vertex& v = TopoDS::Vertex(shape);
1937 gp_Pnt p = BRep_Tool::Pnt(v);
1938 NETGENPlugin_Mesher::RestrictLocalSize( *ngMesh, p.XYZ(), hi );
1940 for(map<int,double>::const_iterator it=FaceId2LocalSize.begin();
1941 it!=FaceId2LocalSize.end(); it++)
1943 int key = (*it).first;
1944 double val = (*it).second;
1945 const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
1946 int faceNgID = occgeo.fmap.FindIndex(shape);
1947 occgeo.SetFaceMaxH(faceNgID, val);
1948 for ( TopExp_Explorer edgeExp( shape, TopAbs_EDGE ); edgeExp.More(); edgeExp.Next() )
1949 setLocalSize( TopoDS::Edge( edgeExp.Current() ), val, *ngMesh );
1953 // Precompute internal edges (issue 0020676) in order to
1954 // add mesh on them correctly (twice) to netgen mesh
1955 if ( !err && internals.hasInternalEdges() )
1957 // load internal shapes into OCCGeometry
1958 netgen::OCCGeometry intOccgeo;
1959 internals.getInternalEdges( intOccgeo.fmap, intOccgeo.emap, intOccgeo.vmap, meshedSM );
1960 intOccgeo.boundingbox = occgeo.boundingbox;
1961 intOccgeo.shape = occgeo.shape;
1963 intOccgeo.face_maxh.SetSize(intOccgeo.fmap.Extent());
1964 intOccgeo.face_maxh = netgen::mparam.maxh;
1966 netgen::Mesh *tmpNgMesh = NULL;
1970 // compute local H on internal shapes in the main mesh
1971 //OCCSetLocalMeshSize(intOccgeo, *ngMesh); it deletes ngMesh->localH
1973 // let netgen create a temporary mesh
1974 netgen::OCCGenerateMesh(intOccgeo, tmpNgMesh, startWith, endWith, optstr);
1975 #ifdef WITH_SMESH_CANCEL_COMPUTE
1976 if(netgen::multithread.terminate)
1979 // copy LocalH from the main to temporary mesh
1980 initState.transferLocalH( ngMesh, tmpNgMesh );
1982 // compute mesh on internal edges
1983 startWith = endWith = netgen::MESHCONST_MESHEDGES;
1984 err = netgen::OCCGenerateMesh(intOccgeo, tmpNgMesh, startWith, endWith, optstr);
1985 comment << text(err);
1987 catch (Standard_Failure& ex)
1989 comment << text(ex);
1992 initState.restoreLocalH( tmpNgMesh );
1994 // fill SMESH by netgen mesh
1995 vector< const SMDS_MeshNode* > tmpNodeVec;
1996 FillSMesh( intOccgeo, *tmpNgMesh, initState, *_mesh, tmpNodeVec, comment );
1997 err = ( err || !comment.empty() );
1999 nglib::Ng_DeleteMesh((nglib::Ng_Mesh*)tmpNgMesh);
2002 // Fill ngMesh with nodes and segments of computed submeshes
2005 _faceDescriptors.clear();
2006 err = ! ( fillNgMesh(occgeo, *ngMesh, nodeVec, meshedSM[ MeshDim_0D ]) &&
2007 fillNgMesh(occgeo, *ngMesh, nodeVec, meshedSM[ MeshDim_1D ]));
2009 initState = NETGENPlugin_ngMeshInfo(ngMesh);
2014 startWith = endWith = netgen::MESHCONST_MESHEDGES;
2018 err = netgen::OCCGenerateMesh(occgeo, ngMesh, startWith, endWith, optstr);
2019 #ifdef WITH_SMESH_CANCEL_COMPUTE
2020 if(netgen::multithread.terminate)
2023 comment << text(err);
2025 catch (Standard_Failure& ex)
2027 comment << text(ex);
2031 mparams.uselocalh = true; // restore as it is used at surface optimization
2033 // ---------------------
2034 // compute surface mesh
2035 // ---------------------
2038 // Pass 2D simple parameters to NETGEN
2040 if ( double area = _simpleHyp->GetMaxElementArea() ) {
2042 mparams.maxh = sqrt(2. * area/sqrt(3.0));
2043 mparams.grading = 0.4; // moderate size growth
2046 // length from edges
2047 if ( ngMesh->GetNSeg() ) {
2048 double edgeLength = 0;
2049 TopTools_MapOfShape visitedEdges;
2050 for ( TopExp_Explorer exp( _shape, TopAbs_EDGE ); exp.More(); exp.Next() )
2051 if( visitedEdges.Add(exp.Current()) )
2052 edgeLength += SMESH_Algo::EdgeLength( TopoDS::Edge( exp.Current() ));
2053 // we have to multiply length by 2 since for each TopoDS_Edge there
2054 // are double set of NETGEN edges, in other words, we have to
2055 // divide ngMesh->GetNSeg() by 2.
2056 mparams.maxh = 2*edgeLength / ngMesh->GetNSeg();
2059 mparams.maxh = 1000;
2061 mparams.grading = 0.2; // slow size growth
2063 mparams.quad = _simpleHyp->GetAllowQuadrangles();
2064 mparams.maxh = min( mparams.maxh, occgeo.boundingbox.Diam()/2 );
2065 ngMesh->SetGlobalH (mparams.maxh);
2066 netgen::Box<3> bb = occgeo.GetBoundingBox();
2067 bb.Increase (bb.Diam()/20);
2068 ngMesh->SetLocalH (bb.PMin(), bb.PMax(), mparams.grading);
2071 // Care of vertices internal in faces (issue 0020676)
2072 if ( internals.hasInternalVertexInFace() )
2074 // store computed segments in SMESH in order not to create SMESH
2075 // edges for ng segments added by addIntVerticesInFaces()
2076 FillSMesh( occgeo, *ngMesh, initState, *_mesh, nodeVec, comment );
2077 // add segments to faces with internal vertices
2078 addIntVerticesInFaces( occgeo, *ngMesh, nodeVec, internals );
2079 initState = NETGENPlugin_ngMeshInfo(ngMesh);
2082 // Let netgen compute 2D mesh
2083 startWith = netgen::MESHCONST_MESHSURFACE;
2084 endWith = _optimize ? netgen::MESHCONST_OPTSURFACE : netgen::MESHCONST_MESHSURFACE;
2088 err = netgen::OCCGenerateMesh(occgeo, ngMesh, startWith, endWith, optstr);
2089 #ifdef WITH_SMESH_CANCEL_COMPUTE
2090 if(netgen::multithread.terminate)
2093 comment << text (err);
2095 catch (Standard_Failure& ex)
2097 comment << text(ex);
2098 //err = 1; -- try to make volumes anyway
2100 catch (netgen::NgException exc)
2102 comment << text(exc);
2103 //err = 1; -- try to make volumes anyway
2106 // ---------------------
2107 // generate volume mesh
2108 // ---------------------
2109 // Fill ngMesh with nodes and faces of computed 2D submeshes
2110 if ( !err && _isVolume && ( !meshedSM[ MeshDim_2D ].empty() || mparams.quad ))
2112 // load SMESH with computed segments and faces
2113 FillSMesh( occgeo, *ngMesh, initState, *_mesh, nodeVec, comment );
2115 // compute pyramids on quadrangles
2116 SMESH_ProxyMesh::Ptr proxyMesh;
2117 if ( _mesh->NbQuadrangles() > 0 )
2118 for ( int iS = 1; iS <= occgeo.somap.Extent(); ++iS )
2120 StdMeshers_QuadToTriaAdaptor* Adaptor = new StdMeshers_QuadToTriaAdaptor;
2121 proxyMesh.reset( Adaptor );
2123 int nbPyrams = _mesh->NbPyramids();
2124 Adaptor->Compute( *_mesh, occgeo.somap(iS) );
2125 if ( nbPyrams != _mesh->NbPyramids() )
2127 list< SMESH_subMesh* > quadFaceSM;
2128 for (TopExp_Explorer face(occgeo.somap(iS), TopAbs_FACE); face.More(); face.Next())
2129 if ( Adaptor->GetProxySubMesh( face.Current() ))
2131 quadFaceSM.push_back( _mesh->GetSubMesh( face.Current() ));
2132 meshedSM[ MeshDim_2D ].remove( quadFaceSM.back() );
2134 fillNgMesh(occgeo, *ngMesh, nodeVec, quadFaceSM, proxyMesh);
2137 // fill ngMesh with faces of sub-meshes
2138 err = ! ( fillNgMesh(occgeo, *ngMesh, nodeVec, meshedSM[ MeshDim_2D ]));
2139 initState = NETGENPlugin_ngMeshInfo(ngMesh);
2140 //toPython( ngMesh, "/tmp/ngPython.py");
2142 if (!err && _isVolume)
2144 // Pass 3D simple parameters to NETGEN
2145 const NETGENPlugin_SimpleHypothesis_3D* simple3d =
2146 dynamic_cast< const NETGENPlugin_SimpleHypothesis_3D* > ( _simpleHyp );
2148 if ( double vol = simple3d->GetMaxElementVolume() ) {
2150 mparams.maxh = pow( 72, 1/6. ) * pow( vol, 1/3. );
2151 mparams.maxh = min( mparams.maxh, occgeo.boundingbox.Diam()/2 );
2154 // length from faces
2155 mparams.maxh = ngMesh->AverageH();
2157 ngMesh->SetGlobalH (mparams.maxh);
2158 mparams.grading = 0.4;
2159 ngMesh->CalcLocalH();
2161 // Care of vertices internal in solids and internal faces (issue 0020676)
2162 if ( internals.hasInternalVertexInSolid() || internals.hasInternalFaces() )
2164 // store computed faces in SMESH in order not to create SMESH
2165 // faces for ng faces added here
2166 FillSMesh( occgeo, *ngMesh, initState, *_mesh, nodeVec, comment );
2167 // add ng faces to solids with internal vertices
2168 addIntVerticesInSolids( occgeo, *ngMesh, nodeVec, internals );
2169 // duplicate mesh faces on internal faces
2170 fixIntFaces( occgeo, *ngMesh, internals );
2171 initState = NETGENPlugin_ngMeshInfo(ngMesh);
2173 // Let netgen compute 3D mesh
2174 startWith = endWith = netgen::MESHCONST_MESHVOLUME;
2178 err = netgen::OCCGenerateMesh(occgeo, ngMesh, startWith, endWith, optstr);
2179 #ifdef WITH_SMESH_CANCEL_COMPUTE
2180 if(netgen::multithread.terminate)
2183 if ( comment.empty() ) // do not overwrite a previos error
2184 comment << text(err);
2186 catch (Standard_Failure& ex)
2188 if ( comment.empty() ) // do not overwrite a previos error
2189 comment << text(ex);
2192 catch (netgen::NgException exc)
2194 if ( comment.empty() ) // do not overwrite a previos error
2195 comment << text(exc);
2198 // Let netgen optimize 3D mesh
2199 if ( !err && _optimize )
2201 startWith = endWith = netgen::MESHCONST_OPTVOLUME;
2205 err = netgen::OCCGenerateMesh(occgeo, ngMesh, startWith, endWith, optstr);
2206 #ifdef WITH_SMESH_CANCEL_COMPUTE
2207 if(netgen::multithread.terminate)
2210 if ( comment.empty() ) // do not overwrite a previos error
2211 comment << text(err);
2213 catch (Standard_Failure& ex)
2215 if ( comment.empty() ) // do not overwrite a previos error
2216 comment << text(ex);
2218 catch (netgen::NgException exc)
2220 if ( comment.empty() ) // do not overwrite a previos error
2221 comment << text(exc);
2225 if (!err && mparams.secondorder > 0)
2230 netgen::OCCRefinementSurfaces ref (occgeo);
2231 ref.MakeSecondOrder (*ngMesh);
2233 catch (Standard_Failure& ex)
2235 if ( comment.empty() ) // do not overwrite a previos error
2236 comment << "Exception in netgen at passing to 2nd order ";
2238 catch (netgen::NgException exc)
2240 if ( comment.empty() ) // do not overwrite a previos error
2241 comment << exc.What();
2245 int nbNod = ngMesh->GetNP();
2246 int nbSeg = ngMesh->GetNSeg();
2247 int nbFac = ngMesh->GetNSE();
2248 int nbVol = ngMesh->GetNE();
2249 bool isOK = ( !err && (_isVolume ? (nbVol > 0) : (nbFac > 0)) );
2251 MESSAGE((err ? "Mesh Generation failure" : "End of Mesh Generation") <<
2252 ", nb nodes: " << nbNod <<
2253 ", nb segments: " << nbSeg <<
2254 ", nb faces: " << nbFac <<
2255 ", nb volumes: " << nbVol);
2257 // Feed back the SMESHDS with the generated Nodes and Elements
2258 if ( true /*isOK*/ ) // get whatever built
2259 FillSMesh( occgeo, *ngMesh, initState, *_mesh, nodeVec, comment ); //!<
2261 SMESH_ComputeErrorPtr readErr = readErrors(nodeVec);
2262 if ( readErr && !readErr->myBadElements.empty() )
2265 if ( error->IsOK() && ( !isOK || comment.size() > 0 ))
2266 error->myName = COMPERR_ALGO_FAILED;
2267 if ( !comment.empty() )
2268 error->myComment = comment;
2270 // SetIsAlwaysComputed( true ) to empty sub-meshes, which
2271 // appear if the geometry contains coincident sub-shape due
2272 // to bool merge_solids = 1; in netgen/libsrc/occ/occgenmesh.cpp
2273 const int nbMaps = 2;
2274 const TopTools_IndexedMapOfShape* geoMaps[nbMaps] =
2275 { & occgeo.vmap, & occgeo.emap/*, & occgeo.fmap*/ };
2276 for ( int iMap = 0; iMap < nbMaps; ++iMap )
2277 for (int i = 1; i <= geoMaps[iMap]->Extent(); i++)
2278 if ( SMESH_subMesh* sm = _mesh->GetSubMeshContaining( geoMaps[iMap]->FindKey(i)))
2279 if ( !sm->IsMeshComputed() )
2280 sm->SetIsAlwaysComputed( true );
2282 // set bad compute error to subshapes of all failed sub-shapes
2283 if ( !error->IsOK() )
2285 bool pb2D = false, pb3D = false;
2286 for (int i = 1; i <= occgeo.fmap.Extent(); i++) {
2287 int status = occgeo.facemeshstatus[i-1];
2288 if (status == 1 ) continue;
2289 if ( SMESH_subMesh* sm = _mesh->GetSubMeshContaining( occgeo.fmap( i ))) {
2290 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
2291 if ( !smError || smError->IsOK() ) {
2293 smError.reset( new SMESH_ComputeError( *error ));
2295 smError.reset( new SMESH_ComputeError( COMPERR_ALGO_FAILED, "Ignored" ));
2296 if ( SMESH_Algo::GetMeshError( sm ) == SMESH_Algo::MEr_OK )
2297 smError->myName = COMPERR_WARNING;
2299 pb2D = pb2D || smError->IsKO();
2302 if ( !pb2D ) // all faces are OK
2303 for (int i = 1; i <= occgeo.somap.Extent(); i++)
2304 if ( SMESH_subMesh* sm = _mesh->GetSubMeshContaining( occgeo.somap( i )))
2306 bool smComputed = nbVol && !sm->IsEmpty();
2307 if ( smComputed && internals.hasInternalVertexInSolid( sm->GetId() ))
2309 int nbIntV = internals.getSolidsWithVertices().find( sm->GetId() )->second.size();
2310 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
2311 smComputed = ( smDS->NbElements() > 0 || smDS->NbNodes() > nbIntV );
2313 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
2314 if ( !smComputed && ( !smError || smError->IsOK() ))
2316 smError.reset( new SMESH_ComputeError( *error ));
2317 if ( nbVol && SMESH_Algo::GetMeshError( sm ) == SMESH_Algo::MEr_OK )
2318 smError->myName = COMPERR_WARNING;
2320 pb3D = pb3D || ( smError && smError->IsKO() );
2322 if ( !pb2D && !pb3D )
2323 err = 0; // no fatal errors, only warnings
2329 //=============================================================================
2333 //=============================================================================
2334 bool NETGENPlugin_Mesher::Evaluate(MapShapeNbElems& aResMap)
2336 netgen::MeshingParameters& mparams = netgen::mparam;
2339 // -------------------------
2340 // Prepare OCC geometry
2341 // -------------------------
2342 netgen::OCCGeometry occgeo;
2343 PrepareOCCgeometry( occgeo, _shape, *_mesh );
2345 bool tooManyElems = false;
2346 const int hugeNb = std::numeric_limits<int>::max() / 100;
2351 // pass 1D simple parameters to NETGEN
2353 if ( int nbSeg = _simpleHyp->GetNumberOfSegments() ) {
2355 mparams.segmentsperedge = nbSeg + 0.1;
2356 mparams.maxh = occgeo.boundingbox.Diam();
2357 mparams.minh = GetDefaultMinSize( _shape, mparams.maxh );
2358 mparams.grading = 0.01;
2362 mparams.segmentsperedge = 1;
2363 mparams.maxh = _simpleHyp->GetLocalLength();
2366 // let netgen create ngMesh and calculate element size on not meshed shapes
2367 NETGENPlugin_NetgenLibWrapper ngLib;
2368 netgen::Mesh *ngMesh = NULL;
2370 int startWith = netgen::MESHCONST_ANALYSE;
2371 int endWith = netgen::MESHCONST_MESHEDGES;
2372 int err = netgen::OCCGenerateMesh(occgeo, ngMesh, startWith, endWith, optstr);
2373 #ifdef WITH_SMESH_CANCEL_COMPUTE
2374 if(netgen::multithread.terminate)
2377 ngLib.setMesh(( Ng_Mesh*) ngMesh );
2379 if ( SMESH_subMesh* sm = _mesh->GetSubMeshContaining( _shape ))
2380 sm->GetComputeError().reset( new SMESH_ComputeError( COMPERR_ALGO_FAILED ));
2384 // calculate total nb of segments and length of edges
2385 double fullLen = 0.0;
2387 int entity = mparams.secondorder > 0 ? SMDSEntity_Quad_Edge : SMDSEntity_Edge;
2388 TopTools_DataMapOfShapeInteger Edge2NbSeg;
2389 for (TopExp_Explorer exp(_shape, TopAbs_EDGE); exp.More(); exp.Next())
2391 TopoDS_Edge E = TopoDS::Edge( exp.Current() );
2392 if( !Edge2NbSeg.Bind(E,0) )
2395 double aLen = SMESH_Algo::EdgeLength(E);
2398 vector<int>& aVec = aResMap[_mesh->GetSubMesh(E)];
2400 aVec.resize( SMDSEntity_Last, 0);
2402 fullNbSeg += aVec[ entity ];
2405 // store nb of segments computed by Netgen
2406 NCollection_Map<Link> linkMap;
2407 for (int i = 1; i <= ngMesh->GetNSeg(); ++i )
2409 const netgen::Segment& seg = ngMesh->LineSegment(i);
2410 Link link(seg[0], seg[1]);
2411 if ( !linkMap.Add( link )) continue;
2412 int aGeomEdgeInd = seg.epgeominfo[0].edgenr;
2413 if (aGeomEdgeInd > 0 && aGeomEdgeInd <= occgeo.emap.Extent())
2415 vector<int>& aVec = aResMap[_mesh->GetSubMesh(occgeo.emap(aGeomEdgeInd))];
2419 // store nb of nodes on edges computed by Netgen
2420 TopTools_DataMapIteratorOfDataMapOfShapeInteger Edge2NbSegIt(Edge2NbSeg);
2421 for (; Edge2NbSegIt.More(); Edge2NbSegIt.Next())
2423 vector<int>& aVec = aResMap[_mesh->GetSubMesh(Edge2NbSegIt.Key())];
2424 if ( aVec[ entity ] > 1 && aVec[ SMDSEntity_Node ] == 0 )
2425 aVec[SMDSEntity_Node] = mparams.secondorder > 0 ? 2*aVec[ entity ]-1 : aVec[ entity ]-1;
2427 fullNbSeg += aVec[ entity ];
2428 Edge2NbSeg( Edge2NbSegIt.Key() ) = aVec[ entity ];
2435 if ( double area = _simpleHyp->GetMaxElementArea() ) {
2437 mparams.maxh = sqrt(2. * area/sqrt(3.0));
2438 mparams.grading = 0.4; // moderate size growth
2441 // length from edges
2442 mparams.maxh = fullLen/fullNbSeg;
2443 mparams.grading = 0.2; // slow size growth
2446 mparams.maxh = min( mparams.maxh, occgeo.boundingbox.Diam()/2 );
2447 mparams.maxh = min( mparams.maxh, fullLen/fullNbSeg * (1. + mparams.grading));
2449 for (TopExp_Explorer exp(_shape, TopAbs_FACE); exp.More(); exp.Next())
2451 TopoDS_Face F = TopoDS::Face( exp.Current() );
2452 SMESH_subMesh *sm = _mesh->GetSubMesh(F);
2454 BRepGProp::SurfaceProperties(F,G);
2455 double anArea = G.Mass();
2456 tooManyElems = tooManyElems || ( anArea/hugeNb > mparams.maxh*mparams.maxh );
2458 if ( !tooManyElems )
2460 TopTools_MapOfShape egdes;
2461 for (TopExp_Explorer exp1(F,TopAbs_EDGE); exp1.More(); exp1.Next())
2462 if ( egdes.Add( exp1.Current() ))
2463 nb1d += Edge2NbSeg.Find(exp1.Current());
2465 int nbFaces = tooManyElems ? hugeNb : int( 4*anArea / (mparams.maxh*mparams.maxh*sqrt(3.)));
2466 int nbNodes = tooManyElems ? hugeNb : (( nbFaces*3 - (nb1d-1)*2 ) / 6 + 1 );
2468 vector<int> aVec(SMDSEntity_Last, 0);
2469 if( mparams.secondorder > 0 ) {
2470 int nb1d_in = (nbFaces*3 - nb1d) / 2;
2471 aVec[SMDSEntity_Node] = nbNodes + nb1d_in;
2472 aVec[SMDSEntity_Quad_Triangle] = nbFaces;
2475 aVec[SMDSEntity_Node] = Max ( nbNodes, 0 );
2476 aVec[SMDSEntity_Triangle] = nbFaces;
2478 aResMap[sm].swap(aVec);
2485 // pass 3D simple parameters to NETGEN
2486 const NETGENPlugin_SimpleHypothesis_3D* simple3d =
2487 dynamic_cast< const NETGENPlugin_SimpleHypothesis_3D* > ( _simpleHyp );
2489 if ( double vol = simple3d->GetMaxElementVolume() ) {
2491 mparams.maxh = pow( 72, 1/6. ) * pow( vol, 1/3. );
2492 mparams.maxh = min( mparams.maxh, occgeo.boundingbox.Diam()/2 );
2495 // using previous length from faces
2497 mparams.grading = 0.4;
2498 mparams.maxh = min( mparams.maxh, fullLen/fullNbSeg * (1. + mparams.grading));
2501 BRepGProp::VolumeProperties(_shape,G);
2502 double aVolume = G.Mass();
2503 double tetrVol = 0.1179*mparams.maxh*mparams.maxh*mparams.maxh;
2504 tooManyElems = tooManyElems || ( aVolume/hugeNb > tetrVol );
2505 int nbVols = tooManyElems ? hugeNb : int(aVolume/tetrVol);
2506 int nb1d_in = int(( nbVols*6 - fullNbSeg ) / 6 );
2507 vector<int> aVec(SMDSEntity_Last, 0 );
2508 if ( tooManyElems ) // avoid FPE
2510 aVec[SMDSEntity_Node] = hugeNb;
2511 aVec[ mparams.secondorder > 0 ? SMDSEntity_Quad_Tetra : SMDSEntity_Tetra] = hugeNb;
2515 if( mparams.secondorder > 0 ) {
2516 aVec[SMDSEntity_Node] = nb1d_in/3 + 1 + nb1d_in;
2517 aVec[SMDSEntity_Quad_Tetra] = nbVols;
2520 aVec[SMDSEntity_Node] = nb1d_in/3 + 1;
2521 aVec[SMDSEntity_Tetra] = nbVols;
2524 SMESH_subMesh *sm = _mesh->GetSubMesh(_shape);
2525 aResMap[sm].swap(aVec);
2531 //================================================================================
2533 * \brief Remove "test.out" and "problemfaces" files in current directory
2535 //================================================================================
2537 void NETGENPlugin_Mesher::RemoveTmpFiles()
2539 if ( SMESH_File("test.out").remove() && netgen::testout)
2541 delete netgen::testout;
2542 netgen::testout = 0;
2544 SMESH_File("problemfaces").remove();
2545 SMESH_File("occmesh.rep").remove();
2548 //================================================================================
2550 * \brief Read mesh entities preventing successful computation from "test.out" file
2552 //================================================================================
2554 SMESH_ComputeErrorPtr
2555 NETGENPlugin_Mesher::readErrors(const vector<const SMDS_MeshNode* >& nodeVec)
2557 SMESH_ComputeErrorPtr err = SMESH_ComputeError::New
2558 (COMPERR_BAD_INPUT_MESH, "Some edges multiple times in surface mesh");
2559 SMESH_File file("test.out");
2561 const char* badEdgeStr = " multiple times in surface mesh";
2562 const int badEdgeStrLen = strlen( badEdgeStr );
2563 while( !file.eof() )
2565 if ( strncmp( file, "Edge ", 5 ) == 0 &&
2566 file.getInts( two ) &&
2567 strncmp( file, badEdgeStr, badEdgeStrLen ) == 0 &&
2568 two[0] < nodeVec.size() && two[1] < nodeVec.size())
2570 err->myBadElements.push_back( new SMDS_LinearEdge( nodeVec[ two[0]], nodeVec[ two[1]] ));
2571 file += badEdgeStrLen;
2573 else if ( strncmp( file, "Intersecting: ", 14 ) == 0 )
2576 // openelement 18 with open element 126
2579 vector<int> three1(3), three2(3);
2581 const char* pos = file;
2582 bool ok = ( strncmp( file, "openelement ", 12 ) == 0 );
2583 ok = ok && file.getInts( two );
2584 ok = ok && file.getInts( three1 );
2585 ok = ok && file.getInts( three2 );
2586 for ( int i = 0; ok && i < 3; ++i )
2587 ok = ( three1[i] < nodeVec.size() && nodeVec[ three1[i]]);
2588 for ( int i = 0; ok && i < 3; ++i )
2589 ok = ( three2[i] < nodeVec.size() && nodeVec[ three2[i]]);
2592 err->myBadElements.push_back( new SMDS_FaceOfNodes( nodeVec[ three1[0]],
2593 nodeVec[ three1[1]],
2594 nodeVec[ three1[2]]));
2595 err->myBadElements.push_back( new SMDS_FaceOfNodes( nodeVec[ three2[0]],
2596 nodeVec[ three2[1]],
2597 nodeVec[ three2[2]]));
2598 err->myComment = "Intersecting triangles";
2613 //================================================================================
2615 * \brief Write a python script creating an equivalent SALOME mesh.
2616 * This is useful to see what mesh is passed as input for the next step of mesh
2617 * generation (of mesh of higher dimension)
2619 //================================================================================
2621 void NETGENPlugin_Mesher::toPython( const netgen::Mesh* ngMesh,
2622 const std::string& pyFile)
2624 ofstream outfile(pyFile.c_str(), ios::out);
2625 if ( !outfile ) return;
2627 outfile << "import smesh, SMESH" << endl
2628 << "mesh = smesh.Mesh()" << endl << endl;
2630 using namespace netgen;
2632 for (pi = PointIndex::BASE;
2633 pi < ngMesh->GetNP()+PointIndex::BASE; pi++)
2635 outfile << "mesh.AddNode( ";
2636 outfile << (*ngMesh)[pi](0) << ", ";
2637 outfile << (*ngMesh)[pi](1) << ", ";
2638 outfile << (*ngMesh)[pi](2) << ")" << endl;
2641 int nbDom = ngMesh->GetNDomains();
2642 for ( int i = 0; i < nbDom; ++i )
2643 outfile<< "grp" << i+1 << " = mesh.CreateEmptyGroup( SMESH.FACE, 'domain"<< i+1 << "')"<< endl;
2645 SurfaceElementIndex sei;
2646 for (sei = 0; sei < ngMesh->GetNSE(); sei++)
2648 outfile << "mesh.AddFace([ ";
2649 Element2d sel = (*ngMesh)[sei];
2650 for (int j = 0; j < sel.GetNP(); j++)
2651 outfile << sel[j] << ( j+1 < sel.GetNP() ? ", " : " ])");
2654 if ((*ngMesh)[sei].GetIndex())
2656 if ( int dom1 = ngMesh->GetFaceDescriptor((*ngMesh)[sei].GetIndex ()).DomainIn())
2657 outfile << "grp"<< dom1 <<".Add([ " << (int)sei+1 << " ])" << endl;
2658 if ( int dom2 = ngMesh->GetFaceDescriptor((*ngMesh)[sei].GetIndex ()).DomainOut())
2659 outfile << "grp"<< dom2 <<".Add([ " << (int)sei+1 << " ])" << endl;
2663 for (ElementIndex ei = 0; ei < ngMesh->GetNE(); ei++)
2665 Element el = (*ngMesh)[ei];
2666 outfile << "mesh.AddVolume([ ";
2667 for (int j = 0; j < el.GetNP(); j++)
2668 outfile << el[j] << ( j+1 < el.GetNP() ? ", " : " ])");
2672 for (int i = 1; i <= ngMesh->GetNSeg(); i++)
2674 const Segment & seg = ngMesh->LineSegment (i);
2675 outfile << "mesh.AddEdge([ "
2677 << seg[1] << " ])" << endl;
2679 cout << "Write " << pyFile << endl;
2682 //================================================================================
2684 * \brief Constructor of NETGENPlugin_ngMeshInfo
2686 //================================================================================
2688 NETGENPlugin_ngMeshInfo::NETGENPlugin_ngMeshInfo( netgen::Mesh* ngMesh):
2693 _nbNodes = ngMesh->GetNP();
2694 _nbSegments = ngMesh->GetNSeg();
2695 _nbFaces = ngMesh->GetNSE();
2696 _nbVolumes = ngMesh->GetNE();
2700 _nbNodes = _nbSegments = _nbFaces = _nbVolumes = 0;
2704 //================================================================================
2706 * \brief Copy LocalH member from one netgen mesh to another
2708 //================================================================================
2710 void NETGENPlugin_ngMeshInfo::transferLocalH( netgen::Mesh* fromMesh,
2711 netgen::Mesh* toMesh )
2713 if ( !fromMesh->LocalHFunctionGenerated() ) return;
2714 if ( !toMesh->LocalHFunctionGenerated() )
2715 toMesh->CalcLocalH();
2717 const size_t size = sizeof( netgen::LocalH );
2718 _copyOfLocalH = new char[ size ];
2719 memcpy( (void*)_copyOfLocalH, (void*)&toMesh->LocalHFunction(), size );
2720 memcpy( (void*)&toMesh->LocalHFunction(), (void*)&fromMesh->LocalHFunction(), size );
2723 //================================================================================
2725 * \brief Restore LocalH member of a netgen mesh
2727 //================================================================================
2729 void NETGENPlugin_ngMeshInfo::restoreLocalH( netgen::Mesh* toMesh )
2731 if ( _copyOfLocalH )
2733 const size_t size = sizeof( netgen::LocalH );
2734 memcpy( (void*)&toMesh->LocalHFunction(), (void*)_copyOfLocalH, size );
2735 delete [] _copyOfLocalH;
2740 //================================================================================
2742 * \brief Find "internal" sub-shapes
2744 //================================================================================
2746 NETGENPlugin_Internals::NETGENPlugin_Internals( SMESH_Mesh& mesh,
2747 const TopoDS_Shape& shape,
2749 : _mesh( mesh ), _is3D( is3D )
2751 SMESHDS_Mesh* meshDS = mesh.GetMeshDS();
2753 TopExp_Explorer f,e;
2754 for ( f.Init( shape, TopAbs_FACE ); f.More(); f.Next() )
2756 int faceID = meshDS->ShapeToIndex( f.Current() );
2758 // find not computed internal edges
2760 for ( e.Init( f.Current().Oriented(TopAbs_FORWARD), TopAbs_EDGE ); e.More(); e.Next() )
2761 if ( e.Current().Orientation() == TopAbs_INTERNAL )
2763 SMESH_subMesh* eSM = mesh.GetSubMesh( e.Current() );
2764 if ( eSM->IsEmpty() )
2766 _e2face.insert( make_pair( eSM->GetId(), faceID ));
2767 for ( TopoDS_Iterator v(e.Current()); v.More(); v.Next() )
2768 _e2face.insert( make_pair( meshDS->ShapeToIndex( v.Value() ), faceID ));
2772 // find internal vertices in a face
2773 set<int> intVV; // issue 0020850 where same vertex is twice in a face
2774 for ( TopoDS_Iterator fSub( f.Current() ); fSub.More(); fSub.Next())
2775 if ( fSub.Value().ShapeType() == TopAbs_VERTEX )
2777 int vID = meshDS->ShapeToIndex( fSub.Value() );
2778 if ( intVV.insert( vID ).second )
2779 _f2v[ faceID ].push_back( vID );
2784 // find internal faces and their subshapes where nodes are to be doubled
2785 // to make a crack with non-sewed borders
2787 if ( f.Current().Orientation() == TopAbs_INTERNAL )
2789 _intShapes.insert( meshDS->ShapeToIndex( f.Current() ));
2792 list< TopoDS_Shape > edges;
2793 for ( e.Init( f.Current(), TopAbs_EDGE ); e.More(); e.Next())
2794 if ( SMESH_MesherHelper::NbAncestors( e.Current(), mesh, TopAbs_FACE ) > 1 )
2796 _intShapes.insert( meshDS->ShapeToIndex( e.Current() ));
2797 edges.push_back( e.Current() );
2798 // find border faces
2799 PShapeIteratorPtr fIt =
2800 SMESH_MesherHelper::GetAncestors( edges.back(),mesh,TopAbs_FACE );
2801 while ( const TopoDS_Shape* pFace = fIt->next() )
2802 if ( !pFace->IsSame( f.Current() ))
2803 _borderFaces.insert( meshDS->ShapeToIndex( *pFace ));
2806 // we consider vertex internal if it is shared by more than one internal edge
2807 list< TopoDS_Shape >::iterator edge = edges.begin();
2808 for ( ; edge != edges.end(); ++edge )
2809 for ( TopoDS_Iterator v( *edge ); v.More(); v.Next() )
2811 set<int> internalEdges;
2812 PShapeIteratorPtr eIt =
2813 SMESH_MesherHelper::GetAncestors( v.Value(),mesh,TopAbs_EDGE );
2814 while ( const TopoDS_Shape* pEdge = eIt->next() )
2816 int edgeID = meshDS->ShapeToIndex( *pEdge );
2817 if ( isInternalShape( edgeID ))
2818 internalEdges.insert( edgeID );
2820 if ( internalEdges.size() > 1 )
2821 _intShapes.insert( meshDS->ShapeToIndex( v.Value() ));
2825 } // loop on geom faces
2827 // find vertices internal in solids
2830 for ( TopExp_Explorer so(shape, TopAbs_SOLID); so.More(); so.Next())
2832 int soID = meshDS->ShapeToIndex( so.Current() );
2833 for ( TopoDS_Iterator soSub( so.Current() ); soSub.More(); soSub.Next())
2834 if ( soSub.Value().ShapeType() == TopAbs_VERTEX )
2835 _s2v[ soID ].push_back( meshDS->ShapeToIndex( soSub.Value() ));
2840 //================================================================================
2842 * \brief Find mesh faces on non-internal geom faces sharing internal edge
2843 * some nodes of which are to be doubled to make the second border of the "crack"
2845 //================================================================================
2847 void NETGENPlugin_Internals::findBorderElements( TIDSortedElemSet & borderElems )
2849 if ( _intShapes.empty() ) return;
2851 SMESH_Mesh& mesh = const_cast<SMESH_Mesh&>(_mesh);
2852 SMESHDS_Mesh* meshDS = mesh.GetMeshDS();
2854 // loop on internal geom edges
2855 set<int>::const_iterator intShapeId = _intShapes.begin();
2856 for ( ; intShapeId != _intShapes.end(); ++intShapeId )
2858 const TopoDS_Shape& s = meshDS->IndexToShape( *intShapeId );
2859 if ( s.ShapeType() != TopAbs_EDGE ) continue;
2861 // get internal and non-internal geom faces sharing the internal edge <s>
2863 set<int>::iterator bordFace = _borderFaces.end();
2864 PShapeIteratorPtr faces = SMESH_MesherHelper::GetAncestors( s, _mesh, TopAbs_FACE );
2865 while ( const TopoDS_Shape* pFace = faces->next() )
2867 int faceID = meshDS->ShapeToIndex( *pFace );
2868 if ( isInternalShape( faceID ))
2871 bordFace = _borderFaces.insert( faceID ).first;
2873 if ( bordFace == _borderFaces.end() || !intFace ) continue;
2875 // get all links of mesh faces on internal geom face sharing nodes on edge <s>
2876 set< SMESH_OrientedLink > links; //!< links of faces on internal geom face
2877 list<const SMDS_MeshElement*> suspectFaces[2]; //!< mesh faces on border geom faces
2878 int nbSuspectFaces = 0;
2879 SMESHDS_SubMesh* intFaceSM = meshDS->MeshElements( intFace );
2880 if ( !intFaceSM || intFaceSM->NbElements() == 0 ) continue;
2881 SMESH_subMeshIteratorPtr smIt = mesh.GetSubMesh( s )->getDependsOnIterator(true,true);
2882 while ( smIt->more() )
2884 SMESHDS_SubMesh* sm = smIt->next()->GetSubMeshDS();
2885 if ( !sm ) continue;
2886 SMDS_NodeIteratorPtr nIt = sm->GetNodes();
2887 while ( nIt->more() )
2889 const SMDS_MeshNode* nOnEdge = nIt->next();
2890 SMDS_ElemIteratorPtr fIt = nOnEdge->GetInverseElementIterator(SMDSAbs_Face);
2891 while ( fIt->more() )
2893 const SMDS_MeshElement* f = fIt->next();
2894 int nbNodes = f->NbNodes() / ( f->IsQuadratic() ? 2 : 1 );
2895 if ( intFaceSM->Contains( f ))
2897 for ( int i = 0; i < nbNodes; ++i )
2898 links.insert( SMESH_OrientedLink( f->GetNode(i), f->GetNode((i+1)%nbNodes)));
2903 for ( int i = 0; i < nbNodes; ++i )
2904 nbDblNodes += isInternalShape( f->GetNode(i)->getshapeId() );
2906 suspectFaces[ nbDblNodes < 2 ].push_back( f );
2912 // suspectFaces[0] having link with same orientation as mesh faces on
2913 // the internal geom face are <borderElems>. suspectFaces[1] have
2914 // only one node on edge <s>, we decide on them later (at the 2nd loop)
2915 // by links of <borderElems> found at the 1st and 2nd loops
2916 set< SMESH_OrientedLink > borderLinks;
2917 for ( int isPostponed = 0; isPostponed < 2; ++isPostponed )
2919 list<const SMDS_MeshElement*>::iterator fIt = suspectFaces[isPostponed].begin();
2920 for ( int nbF = 0; fIt != suspectFaces[isPostponed].end(); ++fIt, ++nbF )
2922 const SMDS_MeshElement* f = *fIt;
2923 bool isBorder = false, linkFound = false, borderLinkFound = false;
2924 list< SMESH_OrientedLink > faceLinks;
2925 int nbNodes = f->NbNodes() / ( f->IsQuadratic() ? 2 : 1 );
2926 for ( int i = 0; i < nbNodes; ++i )
2928 SMESH_OrientedLink link( f->GetNode(i), f->GetNode((i+1)%nbNodes));
2929 faceLinks.push_back( link );
2932 set< SMESH_OrientedLink >::iterator foundLink = links.find( link );
2933 if ( foundLink != links.end() )
2936 isBorder = ( foundLink->_reversed == link._reversed );
2937 if ( !isBorder && !isPostponed ) break;
2938 faceLinks.pop_back();
2940 else if ( isPostponed && !borderLinkFound )
2942 foundLink = borderLinks.find( link );
2943 if ( foundLink != borderLinks.end() )
2945 borderLinkFound = true;
2946 isBorder = ( foundLink->_reversed != link._reversed );
2953 borderElems.insert( f );
2954 borderLinks.insert( faceLinks.begin(), faceLinks.end() );
2956 else if ( !linkFound && !borderLinkFound )
2958 suspectFaces[1].push_back( f );
2959 if ( nbF > 2 * nbSuspectFaces )
2960 break; // dead loop protection
2967 //================================================================================
2969 * \brief put internal shapes in maps and fill in submeshes to precompute
2971 //================================================================================
2973 void NETGENPlugin_Internals::getInternalEdges( TopTools_IndexedMapOfShape& fmap,
2974 TopTools_IndexedMapOfShape& emap,
2975 TopTools_IndexedMapOfShape& vmap,
2976 list< SMESH_subMesh* > smToPrecompute[])
2978 if ( !hasInternalEdges() ) return;
2979 map<int,int>::const_iterator ev_face = _e2face.begin();
2980 for ( ; ev_face != _e2face.end(); ++ev_face )
2982 const TopoDS_Shape& ev = _mesh.GetMeshDS()->IndexToShape( ev_face->first );
2983 const TopoDS_Shape& face = _mesh.GetMeshDS()->IndexToShape( ev_face->second );
2985 ( ev.ShapeType() == TopAbs_EDGE ? emap : vmap ).Add( ev );
2987 //cout<<"INTERNAL EDGE or VERTEX "<<ev_face->first<<" on face "<<ev_face->second<<endl;
2989 smToPrecompute[ MeshDim_1D ].push_back( _mesh.GetSubMeshContaining( ev_face->first ));
2993 //================================================================================
2995 * \brief return shapes and submeshes to be meshed and already meshed boundary submeshes
2997 //================================================================================
2999 void NETGENPlugin_Internals::getInternalFaces( TopTools_IndexedMapOfShape& fmap,
3000 TopTools_IndexedMapOfShape& emap,
3001 list< SMESH_subMesh* >& intFaceSM,
3002 list< SMESH_subMesh* >& boundarySM)
3004 if ( !hasInternalFaces() ) return;
3006 // <fmap> and <emap> are for not yet meshed shapes
3007 // <intFaceSM> is for submeshes of faces
3008 // <boundarySM> is for meshed edges and vertices
3013 set<int> shapeIDs ( _intShapes );
3014 if ( !_borderFaces.empty() )
3015 shapeIDs.insert( _borderFaces.begin(), _borderFaces.end() );
3017 set<int>::const_iterator intS = shapeIDs.begin();
3018 for ( ; intS != shapeIDs.end(); ++intS )
3020 SMESH_subMesh* sm = _mesh.GetSubMeshContaining( *intS );
3022 if ( sm->GetSubShape().ShapeType() != TopAbs_FACE ) continue;
3024 intFaceSM.push_back( sm );
3026 // add submeshes of not computed internal faces
3027 if ( !sm->IsEmpty() ) continue;
3029 SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(true,true);
3030 while ( smIt->more() )
3033 const TopoDS_Shape& s = sm->GetSubShape();
3035 if ( sm->IsEmpty() )
3038 switch ( s.ShapeType() ) {
3039 case TopAbs_FACE: fmap.Add ( s ); break;
3040 case TopAbs_EDGE: emap.Add ( s ); break;
3046 if ( s.ShapeType() != TopAbs_FACE )
3047 boundarySM.push_back( sm );
3053 //================================================================================
3055 * \brief Return true if given shape is to be precomputed in order to be correctly
3056 * added to netgen mesh
3058 //================================================================================
3060 bool NETGENPlugin_Internals::isShapeToPrecompute(const TopoDS_Shape& s)
3062 int shapeID = _mesh.GetMeshDS()->ShapeToIndex( s );
3063 switch ( s.ShapeType() ) {
3064 case TopAbs_FACE : break; //return isInternalShape( shapeID ) || isBorderFace( shapeID );
3065 case TopAbs_EDGE : return isInternalEdge( shapeID );
3066 case TopAbs_VERTEX: break;
3072 //================================================================================
3074 * \brief Return SMESH
3076 //================================================================================
3078 SMESH_Mesh& NETGENPlugin_Internals::getMesh() const
3080 return const_cast<SMESH_Mesh&>( _mesh );
3083 //================================================================================
3085 * \brief Initialize netgen library
3087 //================================================================================
3089 NETGENPlugin_NetgenLibWrapper::NETGENPlugin_NetgenLibWrapper()
3092 _ngMesh = Ng_NewMesh();
3095 //================================================================================
3097 * \brief Finish using netgen library
3099 //================================================================================
3101 NETGENPlugin_NetgenLibWrapper::~NETGENPlugin_NetgenLibWrapper()
3103 Ng_DeleteMesh( _ngMesh );
3105 NETGENPlugin_Mesher::RemoveTmpFiles();
3108 //================================================================================
3110 * \brief Set netgen mesh to delete at destruction
3112 //================================================================================
3114 void NETGENPlugin_NetgenLibWrapper::setMesh( Ng_Mesh* mesh )
3117 Ng_DeleteMesh( _ngMesh );