1 // Copyright (C) 2007-2013 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.
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;
133 const list<const SMESHDS_Hypothesis*>& hyps = GetUsedHypothesis(aMesh, aShape, false);
137 aStatus = HYP_OK; //SMESH_Hypothesis::HYP_MISSING;
138 return true; // (PAL13464) can work with no hypothesis, LengthFromEdges is default one
141 aStatus = HYP_MISSING;
143 list<const SMESHDS_Hypothesis*>::const_iterator ith;
144 for (ith = hyps.begin(); ith != hyps.end(); ++ith )
146 const SMESHDS_Hypothesis* hyp = (*ith);
148 string hypName = hyp->GetName();
150 if ( hypName == "MaxElementArea")
151 _hypMaxElementArea = static_cast<const StdMeshers_MaxElementArea*> (hyp);
152 else if ( hypName == "LengthFromEdges" )
153 _hypLengthFromEdges = static_cast<const StdMeshers_LengthFromEdges*> (hyp);
154 else if ( hypName == "QuadranglePreference" )
155 _hypQuadranglePreference = static_cast<const StdMeshers_QuadranglePreference*>(hyp);
156 else if ( hypName == "NETGEN_Parameters_2D" )
157 _hypParameters = static_cast<const NETGENPlugin_Hypothesis_2D*>(hyp);
158 else if ( hypName == StdMeshers_ViscousLayers2D::GetHypType() )
161 aStatus = HYP_INCOMPATIBLE;
166 int nbHyps = bool(_hypMaxElementArea) + bool(_hypLengthFromEdges) + bool(_hypParameters );
168 aStatus = HYP_CONCURENT;
172 return ( aStatus == HYP_OK );
175 //=============================================================================
177 *Here we are going to use the NETGEN mesher
179 //=============================================================================
181 bool NETGENPlugin_NETGEN_2D_ONLY::Compute(SMESH_Mesh& aMesh,
182 const TopoDS_Shape& aShape)
184 netgen::multithread.terminate = 0;
185 netgen::multithread.task = "Surface meshing";
187 SMESHDS_Mesh* meshDS = aMesh.GetMeshDS();
188 int faceID = meshDS->ShapeToIndex( aShape );
190 SMESH_MesherHelper helper(aMesh);
191 _quadraticMesh = helper.IsQuadraticSubMesh(aShape);
192 helper.SetElementsOnShape( true );
193 const bool ignoreMediumNodes = _quadraticMesh;
195 // build viscous layers if required
196 TopoDS_Face F = TopoDS::Face( aShape/*.Oriented( TopAbs_FORWARD )*/);
197 if ( F.Orientation() != TopAbs_FORWARD &&
198 F.Orientation() != TopAbs_REVERSED )
199 F.Orientation( TopAbs_FORWARD ); // avoid pb with TopAbs_INTERNAL
200 SMESH_ProxyMesh::Ptr proxyMesh = StdMeshers_ViscousLayers2D::Compute( aMesh, F );
204 // ------------------------
205 // get all edges of a face
206 // ------------------------
209 StdMeshers_FaceSide::GetFaceWires( F, aMesh, ignoreMediumNodes, problem, proxyMesh );
210 if ( problem && !problem->IsOK() )
211 return error( problem );
212 int nbWires = wires.size();
214 return error( "Problem in StdMeshers_FaceSide::GetFaceWires()");
215 if ( wires[0]->NbSegments() < 3 ) // ex: a circle with 2 segments
216 return error(COMPERR_BAD_INPUT_MESH,
217 SMESH_Comment("Too few segments: ")<<wires[0]->NbSegments());
219 // --------------------
220 // compute edge length
221 // --------------------
223 NETGENPlugin_Mesher aMesher( &aMesh, aShape, /*isVolume=*/false);
224 netgen::OCCGeometry occgeo;
225 aMesher.PrepareOCCgeometry( occgeo, F, aMesh );
226 occgeo.fmap.Clear(); // face can be reversed, which is wrong in this case (issue 19978)
227 occgeo.fmap.Add( F );
229 if ( _hypParameters )
231 aMesher.SetParameters(_hypParameters);
235 double edgeLength = 0;
236 if (_hypLengthFromEdges /*|| (!_hypLengthFromEdges && !_hypMaxElementArea)*/)
239 for ( int iW = 0; iW < nbWires; ++iW )
241 edgeLength += wires[ iW ]->Length();
242 nbSegments += wires[ iW ]->NbSegments();
245 edgeLength /= nbSegments;
247 else if ( _hypMaxElementArea )
249 double maxArea = _hypMaxElementArea->GetMaxArea();
250 edgeLength = sqrt(2. * maxArea/sqrt(3.0));
254 // set edgeLength by a longest segment
255 double maxSeg2 = occgeo.GetBoundingBox().Diam();
256 for ( int iW = 0; iW < nbWires; ++iW )
258 const UVPtStructVec& points = wires[ iW ]->GetUVPtStruct();
259 gp_Pnt pPrev = SMESH_TNodeXYZ( points[0].node );
260 for ( size_t i = 1; i < points.size(); ++i )
262 gp_Pnt p = SMESH_TNodeXYZ( points[i].node );
263 maxSeg2 = Max( maxSeg2, p.SquareDistance( pPrev ));
267 edgeLength = sqrt( maxSeg2 ) * 1.05;
269 if ( edgeLength < DBL_MIN )
270 edgeLength = occgeo.GetBoundingBox().Diam();
272 netgen::mparam.maxh = edgeLength;
273 netgen::mparam.minh = aMesher.GetDefaultMinSize( aShape, netgen::mparam.maxh );
274 netgen::mparam.quad = _hypQuadranglePreference ? 1 : 0;
275 netgen::mparam.grading = 0.4; // Moderate fineness by default
277 occgeo.face_maxh = netgen::mparam.maxh;
279 // -------------------------
280 // Make input netgen mesh
281 // -------------------------
283 // MESHCONST_ANALYSE step may lead to a failure, so we make an attempt
284 // w/o MESHCONST_ANALYSE at the second loop
286 for ( int iLoop = 0; iLoop < 2; iLoop++ )
288 bool isMESHCONST_ANALYSE = false;
291 NETGENPlugin_NetgenLibWrapper ngLib;
292 netgen::Mesh * ngMesh = (netgen::Mesh*) ngLib._ngMesh;
293 ngLib._isComputeOk = false;
298 int startWith = MESHCONST_ANALYSE;
299 int endWith = MESHCONST_ANALYSE;
301 if ( !_hypLengthFromEdges && !_hypMaxElementArea && iLoop == 0 )
303 isMESHCONST_ANALYSE = true;
305 err = netgen::OCCGenerateMesh(occgeo, ngMesh, netgen::mparam, startWith, endWith);
307 err = netgen::OCCGenerateMesh(occgeo, ngMesh, startWith, endWith, optstr);
310 ngLib.setMesh(( nglib::Ng_Mesh*) ngMesh );
314 Box<3> bb = occgeo.GetBoundingBox();
315 bb.Increase (bb.Diam()/10);
316 ngMesh->SetLocalH (bb.PMin(), bb.PMax(), netgen::mparam.grading);
317 ngMesh->SetGlobalH (netgen::mparam.maxh);
319 //cerr << "max " << netgen::mparam.maxh << " min " << netgen::mparam.minh << endl;
321 vector< const SMDS_MeshNode* > nodeVec;
322 problem = aMesher.AddSegmentsToMesh( *ngMesh, occgeo, wires, helper, nodeVec );
323 if ( problem && !problem->IsOK() )
324 return error( problem );
326 // limit element size near existing segments
327 TopTools_IndexedMapOfShape edgeMap, faceMap;
328 TopExp::MapShapes( aMesh.GetShapeToMesh(), TopAbs_EDGE, edgeMap );
329 for ( int iE = 1; iE <= edgeMap.Extent(); ++iE )
331 const TopoDS_Shape& edge = edgeMap( iE );
332 if ( SMESH_Algo::isDegenerated( TopoDS::Edge( edge )) ||
333 helper.IsSubShape( edge, aShape ))
335 SMESHDS_SubMesh* smDS = aMesh.GetMeshDS()->MeshElements( edge );
336 if ( !smDS ) continue;
337 SMDS_ElemIteratorPtr segIt = smDS->GetElements();
338 while ( segIt->more() )
340 const SMDS_MeshElement* seg = segIt->next();
341 SMESH_TNodeXYZ n1 = seg->GetNode(0);
342 SMESH_TNodeXYZ n2 = seg->GetNode(1);
343 gp_XYZ p = 0.5 * ( n1 + n2 );
344 netgen::Point3d pi(p.X(), p.Y(), p.Z());
345 ngMesh->RestrictLocalH( pi, Max(( n1 - n2 ).Modulus(), netgen::mparam.minh ));
349 // -------------------------
350 // Generate surface mesh
351 // -------------------------
353 startWith = MESHCONST_MESHSURFACE;
354 endWith = MESHCONST_OPTSURFACE;
360 err = netgen::OCCGenerateMesh(occgeo, ngMesh, netgen::mparam, startWith, endWith);
362 err = netgen::OCCGenerateMesh(occgeo, ngMesh, startWith, endWith, optstr);
364 if(netgen::multithread.terminate)
367 error(SMESH_Comment("Error in netgen::OCCGenerateMesh() at ") << netgen::multithread.task);
369 catch (Standard_Failure& ex)
371 SMESH_Comment str("Exception in netgen::OCCGenerateMesh()");
372 str << " at " << netgen::multithread.task
373 << ": " << ex.DynamicType()->Name();
374 if ( ex.GetMessageString() && strlen( ex.GetMessageString() ))
375 str << ": " << ex.GetMessageString();
380 SMESH_Comment str("Exception in netgen::OCCGenerateMesh()");
381 str << " at " << netgen::multithread.task;
385 if ( err /*&& isMESHCONST_ANALYSE*/ && iLoop == 0 )
387 netgen::mparam.minh = netgen::mparam.maxh;
388 netgen::mparam.maxh = 0;
389 for ( int iW = 0; iW < wires.size(); ++iW )
391 StdMeshers_FaceSidePtr wire = wires[ iW ];
392 const vector<UVPtStruct>& uvPtVec = wire->GetUVPtStruct();
393 for ( size_t iP = 0; iP < uvPtVec.size(); ++iP )
395 netgen::Point3d p( uvPtVec[iP].node->X(),
396 uvPtVec[iP].node->Y(),
397 uvPtVec[iP].node->Z());
398 double size = ngMesh->GetH( p );
399 netgen::mparam.minh = Min( netgen::mparam.minh, size );
400 netgen::mparam.maxh = Max( netgen::mparam.maxh, size );
403 //cerr << "min " << netgen::mparam.minh << " max " << netgen::mparam.maxh << endl;
404 netgen::mparam.minh *= 0.9;
405 netgen::mparam.maxh *= 1.1;
410 // ----------------------------------------------------
411 // Fill the SMESHDS with the generated nodes and faces
412 // ----------------------------------------------------
414 int nbNodes = ngMesh->GetNP();
415 int nbFaces = ngMesh->GetNSE();
417 int nbInputNodes = nodeVec.size()-1;
418 nodeVec.resize( nbNodes+1, 0 );
421 for ( int ngID = nbInputNodes + 1; ngID <= nbNodes; ++ngID )
423 const MeshPoint& ngPoint = ngMesh->Point( ngID );
424 SMDS_MeshNode * node = meshDS->AddNode(ngPoint(0), ngPoint(1), ngPoint(2));
425 nodeVec[ ngID ] = node;
429 const bool reverse = false; //( aShape.Orientation() == TopAbs_REVERSED );
431 for ( i = 1; i <= nbFaces ; ++i )
433 const Element2d& elem = ngMesh->SurfaceElement(i);
434 vector<const SMDS_MeshNode*> nodes( elem.GetNP() );
435 for (j=1; j <= elem.GetNP(); ++j)
437 int pind = elem.PNum(j);
440 const SMDS_MeshNode* node = nodeVec[ pind ];
442 nodes[ nodes.size()-j ] = node;
445 if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_3DSPACE )
447 const PointGeomInfo& pgi = elem.GeomInfoPi(j);
448 meshDS->SetNodeOnFace((SMDS_MeshNode*)node, faceID, pgi.u, pgi.v);
451 if ( j > elem.GetNP() )
453 SMDS_MeshFace* face = 0;
454 if ( elem.GetType() == TRIG )
455 face = helper.AddFace(nodes[0],nodes[1],nodes[2]);
457 face = helper.AddFace(nodes[0],nodes[1],nodes[2],nodes[3]);
461 ngLib._isComputeOk = !err;
469 void NETGENPlugin_NETGEN_2D_ONLY::CancelCompute()
471 SMESH_Algo::CancelCompute();
472 netgen::multithread.terminate = 1;
475 //================================================================================
477 * \brief Return progress of Compute() [0.,1]
479 //================================================================================
481 double NETGENPlugin_NETGEN_2D_ONLY::GetProgress() const
483 const char* task1 = "Surface meshing";
484 //const char* task2 = "Optimizing surface";
485 double& progress = const_cast<NETGENPlugin_NETGEN_2D_ONLY*>( this )->_progress;
486 if ( _progressByTic < 0. &&
487 strncmp( netgen::multithread.task, task1, 3 ) == 0 )
489 progress = Min( 0.25, SMESH_Algo::GetProgressByTic() ); // [0, 0.25]
491 else //if ( strncmp( netgen::multithread.task, task2, 3 ) == 0)
493 if ( _progressByTic < 0 )
495 NETGENPlugin_NETGEN_2D_ONLY* me = (NETGENPlugin_NETGEN_2D_ONLY*) this;
496 me->_progressByTic = 0.25 / (_progressTic+1);
498 const_cast<NETGENPlugin_NETGEN_2D_ONLY*>( this )->_progressTic++;
499 progress = Max( progress, _progressByTic * _progressTic );
501 //cout << netgen::multithread.task << " " << _progressTic << endl;
502 return Min( progress, 0.99 );
505 //=============================================================================
509 //=============================================================================
511 bool NETGENPlugin_NETGEN_2D_ONLY::Evaluate(SMESH_Mesh& aMesh,
512 const TopoDS_Shape& aShape,
513 MapShapeNbElems& aResMap)
515 TopoDS_Face F = TopoDS::Face(aShape);
519 // collect info from edges
520 int nb0d = 0, nb1d = 0;
521 bool IsQuadratic = false;
523 double fullLen = 0.0;
524 TopTools_MapOfShape tmpMap;
525 for (TopExp_Explorer exp(F, TopAbs_EDGE); exp.More(); exp.Next()) {
526 TopoDS_Edge E = TopoDS::Edge(exp.Current());
527 if( tmpMap.Contains(E) )
530 SMESH_subMesh *aSubMesh = aMesh.GetSubMesh(exp.Current());
531 MapShapeNbElemsItr anIt = aResMap.find(aSubMesh);
532 if( anIt==aResMap.end() ) {
533 SMESH_subMesh *sm = aMesh.GetSubMesh(F);
534 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
535 smError.reset( new SMESH_ComputeError(COMPERR_ALGO_FAILED,"Submesh can not be evaluated",this));
538 std::vector<int> aVec = (*anIt).second;
539 nb0d += aVec[SMDSEntity_Node];
540 nb1d += Max(aVec[SMDSEntity_Edge],aVec[SMDSEntity_Quad_Edge]);
541 double aLen = SMESH_Algo::EdgeLength(E);
544 IsQuadratic = (aVec[SMDSEntity_Quad_Edge] > aVec[SMDSEntity_Edge]);
550 // compute edge length
552 if (_hypLengthFromEdges || !_hypLengthFromEdges && !_hypMaxElementArea) {
554 ELen = fullLen / nb1d;
556 if ( _hypMaxElementArea ) {
557 double maxArea = _hypMaxElementArea->GetMaxArea();
558 ELen = sqrt(2. * maxArea/sqrt(3.0));
561 BRepGProp::SurfaceProperties(F,G);
562 double anArea = G.Mass();
564 const int hugeNb = numeric_limits<int>::max()/10;
565 if ( anArea / hugeNb > ELen*ELen )
567 SMESH_subMesh *sm = aMesh.GetSubMesh(F);
568 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
569 smError.reset( new SMESH_ComputeError(COMPERR_ALGO_FAILED,"Submesh can not be evaluated.\nToo small element length",this));
572 int nbFaces = (int) ( anArea / ( ELen*ELen*sqrt(3.) / 4 ) );
573 int nbNodes = (int) ( ( nbFaces*3 - (nb1d-1)*2 ) / 6 + 1 );
574 std::vector<int> aVec(SMDSEntity_Last);
575 for(int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aVec[i]=0;
577 aVec[SMDSEntity_Node] = nbNodes;
578 aVec[SMDSEntity_Quad_Triangle] = nbFaces;
581 aVec[SMDSEntity_Node] = nbNodes;
582 aVec[SMDSEntity_Triangle] = nbFaces;
584 SMESH_subMesh *sm = aMesh.GetSubMesh(F);
585 aResMap.insert(std::make_pair(sm,aVec));