1 // Copyright (C) 2007-2014 CEA/DEN, EDF R&D, OPEN CASCADE
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 // Lesser General Public License for more details.
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
20 // File : NETGENPlugin_NETGEN_2D_ONLY.cxx
21 // Author : Edward AGAPOV (OCC)
24 #include "NETGENPlugin_NETGEN_2D_ONLY.hxx"
26 #include "NETGENPlugin_Mesher.hxx"
27 #include "NETGENPlugin_Hypothesis_2D.hxx"
29 #include <SMDS_MeshElement.hxx>
30 #include <SMDS_MeshNode.hxx>
31 #include <SMESHDS_Mesh.hxx>
32 #include <SMESH_Comment.hxx>
33 #include <SMESH_Gen.hxx>
34 #include <SMESH_Mesh.hxx>
35 #include <SMESH_MesherHelper.hxx>
36 #include <SMESH_subMesh.hxx>
37 #include <StdMeshers_FaceSide.hxx>
38 #include <StdMeshers_LengthFromEdges.hxx>
39 #include <StdMeshers_MaxElementArea.hxx>
40 #include <StdMeshers_QuadranglePreference.hxx>
41 #include <StdMeshers_ViscousLayers2D.hxx>
43 #include <Precision.hxx>
44 #include <Standard_ErrorHandler.hxx>
45 #include <Standard_Failure.hxx>
47 #include <utilities.h>
62 #include <occgeom.hpp>
63 #include <meshing.hpp>
64 //#include <meshtype.hpp>
67 extern int OCCGenerateMesh (OCCGeometry&, Mesh*&, MeshingParameters&, int, int);
69 extern int OCCGenerateMesh (OCCGeometry&, Mesh*&, int, int, char*);
71 extern MeshingParameters mparam;
75 using namespace netgen;
76 using namespace nglib;
78 //#define DUMP_SEGMENTS
80 //=============================================================================
84 //=============================================================================
86 NETGENPlugin_NETGEN_2D_ONLY::NETGENPlugin_NETGEN_2D_ONLY(int hypId, int studyId,
88 : SMESH_2D_Algo(hypId, studyId, gen)
90 MESSAGE("NETGENPlugin_NETGEN_2D_ONLY::NETGENPlugin_NETGEN_2D_ONLY");
91 _name = "NETGEN_2D_ONLY";
93 _shapeType = (1 << TopAbs_FACE);// 1 bit /shape type
95 _compatibleHypothesis.push_back("MaxElementArea");
96 _compatibleHypothesis.push_back("LengthFromEdges");
97 _compatibleHypothesis.push_back("QuadranglePreference");
98 _compatibleHypothesis.push_back("NETGEN_Parameters_2D");
99 _compatibleHypothesis.push_back("ViscousLayers2D");
101 _hypMaxElementArea = 0;
102 _hypLengthFromEdges = 0;
103 _hypQuadranglePreference = 0;
107 //=============================================================================
111 //=============================================================================
113 NETGENPlugin_NETGEN_2D_ONLY::~NETGENPlugin_NETGEN_2D_ONLY()
115 MESSAGE("NETGENPlugin_NETGEN_2D_ONLY::~NETGENPlugin_NETGEN_2D_ONLY");
118 //=============================================================================
122 //=============================================================================
124 bool NETGENPlugin_NETGEN_2D_ONLY::CheckHypothesis (SMESH_Mesh& aMesh,
125 const TopoDS_Shape& aShape,
126 Hypothesis_Status& aStatus)
128 _hypMaxElementArea = 0;
129 _hypLengthFromEdges = 0;
130 _hypQuadranglePreference = 0;
134 const list<const SMESHDS_Hypothesis*>& hyps = GetUsedHypothesis(aMesh, aShape, false);
138 aStatus = HYP_OK; //SMESH_Hypothesis::HYP_MISSING;
139 return true; // (PAL13464) can work with no hypothesis, LengthFromEdges is default one
142 aStatus = HYP_MISSING;
144 list<const SMESHDS_Hypothesis*>::const_iterator ith;
145 for (ith = hyps.begin(); ith != hyps.end(); ++ith )
147 const SMESHDS_Hypothesis* hyp = (*ith);
149 string hypName = hyp->GetName();
151 if ( hypName == "MaxElementArea")
152 _hypMaxElementArea = static_cast<const StdMeshers_MaxElementArea*> (hyp);
153 else if ( hypName == "LengthFromEdges" )
154 _hypLengthFromEdges = static_cast<const StdMeshers_LengthFromEdges*> (hyp);
155 else if ( hypName == "QuadranglePreference" )
156 _hypQuadranglePreference = static_cast<const StdMeshers_QuadranglePreference*>(hyp);
157 else if ( hypName == "NETGEN_Parameters_2D" )
158 _hypParameters = static_cast<const NETGENPlugin_Hypothesis_2D*>(hyp);
159 else if ( hypName == StdMeshers_ViscousLayers2D::GetHypType() )
162 aStatus = HYP_INCOMPATIBLE;
167 int nbHyps = bool(_hypMaxElementArea) + bool(_hypLengthFromEdges) + bool(_hypParameters );
169 aStatus = HYP_CONCURENT;
173 return ( aStatus == HYP_OK );
176 //=============================================================================
178 *Here we are going to use the NETGEN mesher
180 //=============================================================================
182 bool NETGENPlugin_NETGEN_2D_ONLY::Compute(SMESH_Mesh& aMesh,
183 const TopoDS_Shape& aShape)
185 netgen::multithread.terminate = 0;
186 netgen::multithread.task = "Surface meshing";
188 SMESHDS_Mesh* meshDS = aMesh.GetMeshDS();
189 int faceID = meshDS->ShapeToIndex( aShape );
191 SMESH_MesherHelper helper(aMesh);
192 _quadraticMesh = helper.IsQuadraticSubMesh(aShape);
193 helper.SetElementsOnShape( true );
194 const bool ignoreMediumNodes = _quadraticMesh;
196 // build viscous layers if required
197 TopoDS_Face F = TopoDS::Face( aShape/*.Oriented( TopAbs_FORWARD )*/);
198 if ( F.Orientation() != TopAbs_FORWARD &&
199 F.Orientation() != TopAbs_REVERSED )
200 F.Orientation( TopAbs_FORWARD ); // avoid pb with TopAbs_INTERNAL
201 SMESH_ProxyMesh::Ptr proxyMesh = StdMeshers_ViscousLayers2D::Compute( aMesh, F );
205 // ------------------------
206 // get all edges of a face
207 // ------------------------
210 StdMeshers_FaceSide::GetFaceWires( F, aMesh, ignoreMediumNodes, problem, proxyMesh );
211 if ( problem && !problem->IsOK() )
212 return error( problem );
213 int nbWires = wires.size();
215 return error( "Problem in StdMeshers_FaceSide::GetFaceWires()");
216 if ( wires[0]->NbSegments() < 3 ) // ex: a circle with 2 segments
217 return error(COMPERR_BAD_INPUT_MESH,
218 SMESH_Comment("Too few segments: ")<<wires[0]->NbSegments());
220 // --------------------
221 // compute edge length
222 // --------------------
224 NETGENPlugin_Mesher aMesher( &aMesh, aShape, /*isVolume=*/false);
225 netgen::OCCGeometry occgeo;
226 aMesher.PrepareOCCgeometry( occgeo, F, aMesh );
227 occgeo.fmap.Clear(); // face can be reversed, which is wrong in this case (issue 19978)
228 occgeo.fmap.Add( F );
230 if ( _hypParameters )
232 aMesher.SetParameters(_hypParameters);
236 double edgeLength = 0;
237 if (_hypLengthFromEdges /*|| (!_hypLengthFromEdges && !_hypMaxElementArea)*/)
240 for ( int iW = 0; iW < nbWires; ++iW )
242 edgeLength += wires[ iW ]->Length();
243 nbSegments += wires[ iW ]->NbSegments();
246 edgeLength /= nbSegments;
248 else if ( _hypMaxElementArea )
250 double maxArea = _hypMaxElementArea->GetMaxArea();
251 edgeLength = sqrt(2. * maxArea/sqrt(3.0));
255 // set edgeLength by a longest segment
257 for ( int iW = 0; iW < nbWires; ++iW )
259 const UVPtStructVec& points = wires[ iW ]->GetUVPtStruct();
260 gp_Pnt pPrev = SMESH_TNodeXYZ( points[0].node );
261 for ( size_t i = 1; i < points.size(); ++i )
263 gp_Pnt p = SMESH_TNodeXYZ( points[i].node );
264 maxSeg2 = Max( maxSeg2, p.SquareDistance( pPrev ));
268 edgeLength = sqrt( maxSeg2 ) * 1.05;
270 if ( edgeLength < DBL_MIN )
271 edgeLength = occgeo.GetBoundingBox().Diam();
273 netgen::mparam.maxh = edgeLength;
274 netgen::mparam.minh = aMesher.GetDefaultMinSize( aShape, netgen::mparam.maxh );
275 netgen::mparam.quad = _hypQuadranglePreference ? 1 : 0;
276 netgen::mparam.grading = 0.4; // Moderate fineness by default
278 occgeo.face_maxh = netgen::mparam.maxh;
280 // -------------------------
281 // Make input netgen mesh
282 // -------------------------
284 // MESHCONST_ANALYSE step may lead to a failure, so we make an attempt
285 // w/o MESHCONST_ANALYSE at the second loop
287 int iLoop = netgen::mparam.uselocalh ? 0 : 1; // uselocalh depends on
288 for ( ; iLoop < 2; iLoop++ )
290 bool isMESHCONST_ANALYSE = false;
293 NETGENPlugin_NetgenLibWrapper ngLib;
294 netgen::Mesh * ngMesh = (netgen::Mesh*) ngLib._ngMesh;
295 ngLib._isComputeOk = false;
300 int startWith = MESHCONST_ANALYSE;
301 int endWith = MESHCONST_ANALYSE;
303 if ( !_hypLengthFromEdges && !_hypMaxElementArea && iLoop == 0 )
305 isMESHCONST_ANALYSE = true;
307 err = netgen::OCCGenerateMesh(occgeo, ngMesh, netgen::mparam, startWith, endWith);
309 err = netgen::OCCGenerateMesh(occgeo, ngMesh, startWith, endWith, optstr);
312 ngLib.setMesh(( nglib::Ng_Mesh*) ngMesh );
316 Box<3> bb = occgeo.GetBoundingBox();
317 bb.Increase (bb.Diam()/10);
318 ngMesh->SetLocalH (bb.PMin(), bb.PMax(), netgen::mparam.grading);
319 ngMesh->SetGlobalH (netgen::mparam.maxh);
321 //cerr << "max " << netgen::mparam.maxh << " min " << netgen::mparam.minh << endl;
323 vector< const SMDS_MeshNode* > nodeVec;
324 problem = aMesher.AddSegmentsToMesh( *ngMesh, occgeo, wires, helper, nodeVec );
325 if ( problem && !problem->IsOK() )
326 return error( problem );
330 // limit element size near existing segments
331 TopTools_IndexedMapOfShape edgeMap;
332 PShapeIteratorPtr solidIt = helper.GetAncestors( F, aMesh, TopAbs_SOLID );
333 while ( const TopoDS_Shape* solid = solidIt->next() )
335 TopExp_Explorer eExp( *solid, TopAbs_EDGE );
336 for ( ; eExp.More(); eExp.Next() )
338 const TopoDS_Shape& edge = eExp.Current();
339 if (( SMESH_Algo::isDegenerated( TopoDS::Edge( edge ))) ||
340 ( helper.IsSubShape( edge, aShape )) ||
341 ( !edgeMap.Add( edge )))
343 SMESHDS_SubMesh* smDS = aMesh.GetMeshDS()->MeshElements( edge );
344 if ( !smDS ) continue;
345 SMDS_ElemIteratorPtr segIt = smDS->GetElements();
346 while ( segIt->more() )
348 const SMDS_MeshElement* seg = segIt->next();
349 SMESH_TNodeXYZ n1 = seg->GetNode(0);
350 SMESH_TNodeXYZ n2 = seg->GetNode(1);
351 gp_XYZ p = 0.5 * ( n1 + n2 );
352 netgen::Point3d pi(p.X(), p.Y(), p.Z());
353 ngMesh->RestrictLocalH( pi, Max(( n1 - n2 ).Modulus(), netgen::mparam.minh ));
359 // -------------------------
360 // Generate surface mesh
361 // -------------------------
363 startWith = MESHCONST_MESHSURFACE;
364 endWith = MESHCONST_OPTSURFACE;
370 err = netgen::OCCGenerateMesh(occgeo, ngMesh, netgen::mparam, startWith, endWith);
372 err = netgen::OCCGenerateMesh(occgeo, ngMesh, startWith, endWith, optstr);
374 if(netgen::multithread.terminate)
377 error(SMESH_Comment("Error in netgen::OCCGenerateMesh() at ") << netgen::multithread.task);
379 catch (Standard_Failure& ex)
381 SMESH_Comment str("Exception in netgen::OCCGenerateMesh()");
382 str << " at " << netgen::multithread.task
383 << ": " << ex.DynamicType()->Name();
384 if ( ex.GetMessageString() && strlen( ex.GetMessageString() ))
385 str << ": " << ex.GetMessageString();
390 SMESH_Comment str("Exception in netgen::OCCGenerateMesh()");
391 str << " at " << netgen::multithread.task;
395 if ( err /*&& !isMESHCONST_ANALYSE*/ && iLoop == 0 )
397 netgen::mparam.minh = netgen::mparam.maxh;
398 netgen::mparam.maxh = 0;
399 for ( int iW = 0; iW < wires.size(); ++iW )
401 StdMeshers_FaceSidePtr wire = wires[ iW ];
402 const vector<UVPtStruct>& uvPtVec = wire->GetUVPtStruct();
403 for ( size_t iP = 1; iP < uvPtVec.size(); ++iP )
405 SMESH_TNodeXYZ p( uvPtVec[ iP ].node );
406 netgen::Point3d np( p.X(),p.Y(),p.Z());
407 double segLen = p.Distance( uvPtVec[ iP-1 ].node );
408 double size = ngMesh->GetH( np );
409 netgen::mparam.minh = Min( netgen::mparam.minh, size );
410 netgen::mparam.maxh = Max( netgen::mparam.maxh, segLen );
413 //cerr << "min " << netgen::mparam.minh << " max " << netgen::mparam.maxh << endl;
414 netgen::mparam.minh *= 0.9;
415 netgen::mparam.maxh *= 1.1;
420 // ----------------------------------------------------
421 // Fill the SMESHDS with the generated nodes and faces
422 // ----------------------------------------------------
424 int nbNodes = ngMesh->GetNP();
425 int nbFaces = ngMesh->GetNSE();
427 int nbInputNodes = nodeVec.size()-1;
428 nodeVec.resize( nbNodes+1, 0 );
431 for ( int ngID = nbInputNodes + 1; ngID <= nbNodes; ++ngID )
433 const MeshPoint& ngPoint = ngMesh->Point( ngID );
434 SMDS_MeshNode * node = meshDS->AddNode(ngPoint(0), ngPoint(1), ngPoint(2));
435 nodeVec[ ngID ] = node;
439 const bool reverse = false; //( aShape.Orientation() == TopAbs_REVERSED );
441 for ( i = 1; i <= nbFaces ; ++i )
443 const Element2d& elem = ngMesh->SurfaceElement(i);
444 vector<const SMDS_MeshNode*> nodes( elem.GetNP() );
445 for (j=1; j <= elem.GetNP(); ++j)
447 int pind = elem.PNum(j);
450 const SMDS_MeshNode* node = nodeVec[ pind ];
452 nodes[ nodes.size()-j ] = node;
455 if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_3DSPACE )
457 const PointGeomInfo& pgi = elem.GeomInfoPi(j);
458 meshDS->SetNodeOnFace((SMDS_MeshNode*)node, faceID, pgi.u, pgi.v);
461 if ( j > elem.GetNP() )
463 SMDS_MeshFace* face = 0;
464 if ( elem.GetType() == TRIG )
465 face = helper.AddFace(nodes[0],nodes[1],nodes[2]);
467 face = helper.AddFace(nodes[0],nodes[1],nodes[2],nodes[3]);
471 ngLib._isComputeOk = !err;
479 void NETGENPlugin_NETGEN_2D_ONLY::CancelCompute()
481 SMESH_Algo::CancelCompute();
482 netgen::multithread.terminate = 1;
485 //================================================================================
487 * \brief Return progress of Compute() [0.,1]
489 //================================================================================
491 double NETGENPlugin_NETGEN_2D_ONLY::GetProgress() const
493 const char* task1 = "Surface meshing";
494 //const char* task2 = "Optimizing surface";
495 double& progress = const_cast<NETGENPlugin_NETGEN_2D_ONLY*>( this )->_progress;
496 if ( _progressByTic < 0. &&
497 strncmp( netgen::multithread.task, task1, 3 ) == 0 )
499 progress = Min( 0.25, SMESH_Algo::GetProgressByTic() ); // [0, 0.25]
501 else //if ( strncmp( netgen::multithread.task, task2, 3 ) == 0)
503 if ( _progressByTic < 0 )
505 NETGENPlugin_NETGEN_2D_ONLY* me = (NETGENPlugin_NETGEN_2D_ONLY*) this;
506 me->_progressByTic = 0.25 / (_progressTic+1);
508 const_cast<NETGENPlugin_NETGEN_2D_ONLY*>( this )->_progressTic++;
509 progress = Max( progress, _progressByTic * _progressTic );
511 //cout << netgen::multithread.task << " " << _progressTic << endl;
512 return Min( progress, 0.99 );
515 //=============================================================================
519 //=============================================================================
521 bool NETGENPlugin_NETGEN_2D_ONLY::Evaluate(SMESH_Mesh& aMesh,
522 const TopoDS_Shape& aShape,
523 MapShapeNbElems& aResMap)
525 TopoDS_Face F = TopoDS::Face(aShape);
529 // collect info from edges
530 int nb0d = 0, nb1d = 0;
531 bool IsQuadratic = false;
533 double fullLen = 0.0;
534 TopTools_MapOfShape tmpMap;
535 for (TopExp_Explorer exp(F, TopAbs_EDGE); exp.More(); exp.Next()) {
536 TopoDS_Edge E = TopoDS::Edge(exp.Current());
537 if( tmpMap.Contains(E) )
540 SMESH_subMesh *aSubMesh = aMesh.GetSubMesh(exp.Current());
541 MapShapeNbElemsItr anIt = aResMap.find(aSubMesh);
542 if( anIt==aResMap.end() ) {
543 SMESH_subMesh *sm = aMesh.GetSubMesh(F);
544 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
545 smError.reset( new SMESH_ComputeError(COMPERR_ALGO_FAILED,"Submesh can not be evaluated",this));
548 std::vector<int> aVec = (*anIt).second;
549 nb0d += aVec[SMDSEntity_Node];
550 nb1d += Max(aVec[SMDSEntity_Edge],aVec[SMDSEntity_Quad_Edge]);
551 double aLen = SMESH_Algo::EdgeLength(E);
554 IsQuadratic = (aVec[SMDSEntity_Quad_Edge] > aVec[SMDSEntity_Edge]);
560 // compute edge length
562 if (_hypLengthFromEdges || !_hypLengthFromEdges && !_hypMaxElementArea) {
564 ELen = fullLen / nb1d;
566 if ( _hypMaxElementArea ) {
567 double maxArea = _hypMaxElementArea->GetMaxArea();
568 ELen = sqrt(2. * maxArea/sqrt(3.0));
571 BRepGProp::SurfaceProperties(F,G);
572 double anArea = G.Mass();
574 const int hugeNb = numeric_limits<int>::max()/10;
575 if ( anArea / hugeNb > ELen*ELen )
577 SMESH_subMesh *sm = aMesh.GetSubMesh(F);
578 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
579 smError.reset( new SMESH_ComputeError(COMPERR_ALGO_FAILED,"Submesh can not be evaluated.\nToo small element length",this));
582 int nbFaces = (int) ( anArea / ( ELen*ELen*sqrt(3.) / 4 ) );
583 int nbNodes = (int) ( ( nbFaces*3 - (nb1d-1)*2 ) / 6 + 1 );
584 std::vector<int> aVec(SMDSEntity_Last);
585 for(int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aVec[i]=0;
587 aVec[SMDSEntity_Node] = nbNodes;
588 aVec[SMDSEntity_Quad_Triangle] = nbFaces;
591 aVec[SMDSEntity_Node] = nbNodes;
592 aVec[SMDSEntity_Triangle] = nbFaces;
594 SMESH_subMesh *sm = aMesh.GetSubMesh(F);
595 aResMap.insert(std::make_pair(sm,aVec));