1 // Copyright (C) 2007-2022 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"
28 #include "NETGENPlugin_DriverParam.hxx"
30 #include <SMDS_MeshElement.hxx>
31 #include <SMDS_MeshNode.hxx>
32 #include <SMESHDS_Mesh.hxx>
33 #include <SMESH_Comment.hxx>
34 #include <SMESH_Gen.hxx>
35 #include <SMESH_Mesh.hxx>
36 #include <SMESH_MesherHelper.hxx>
37 #include <SMESH_subMesh.hxx>
38 #include <StdMeshers_FaceSide.hxx>
39 #include <StdMeshers_LengthFromEdges.hxx>
40 #include <StdMeshers_MaxElementArea.hxx>
41 #include <StdMeshers_QuadranglePreference.hxx>
42 #include <StdMeshers_ViscousLayers2D.hxx>
43 #include "SMESH_DriverStep.hxx"
44 #include "SMESH_DriverMesh.hxx"
47 #include <Precision.hxx>
48 #include <Standard_ErrorHandler.hxx>
49 #include <Standard_Failure.hxx>
51 #include <utilities.h>
58 #include <boost/filesystem.hpp>
59 namespace fs = boost::filesystem;
69 #include <occgeom.hpp>
70 #include <meshing.hpp>
71 //#include <meshtype.hpp>
73 NETGENPLUGIN_DLL_HEADER
74 extern MeshingParameters mparam;
76 extern void OCCSetLocalMeshSize(OCCGeometry & geom, Mesh & mesh);
81 using namespace netgen;
82 using namespace nglib;
85 //=============================================================================
89 //=============================================================================
91 NETGENPlugin_NETGEN_2D_ONLY::NETGENPlugin_NETGEN_2D_ONLY(int hypId,
93 : SMESH_2D_Algo(hypId, gen)
95 _name = "NETGEN_2D_ONLY";
97 _shapeType = (1 << TopAbs_FACE);// 1 bit /shape type
98 _onlyUnaryInput = false; // treat all FACEs at once
100 _compatibleHypothesis.push_back("MaxElementArea");
101 _compatibleHypothesis.push_back("LengthFromEdges");
102 _compatibleHypothesis.push_back("QuadranglePreference");
103 _compatibleHypothesis.push_back("NETGEN_Parameters_2D");
104 _compatibleHypothesis.push_back("ViscousLayers2D");
106 _hypMaxElementArea = 0;
107 _hypLengthFromEdges = 0;
108 _hypQuadranglePreference = 0;
112 //=============================================================================
116 //=============================================================================
118 NETGENPlugin_NETGEN_2D_ONLY::~NETGENPlugin_NETGEN_2D_ONLY()
120 //MESSAGE("NETGENPlugin_NETGEN_2D_ONLY::~NETGENPlugin_NETGEN_2D_ONLY");
123 //=============================================================================
127 //=============================================================================
129 bool NETGENPlugin_NETGEN_2D_ONLY::CheckHypothesis (SMESH_Mesh& aMesh,
130 const TopoDS_Shape& aShape,
131 Hypothesis_Status& aStatus)
133 _hypMaxElementArea = 0;
134 _hypLengthFromEdges = 0;
135 _hypQuadranglePreference = 0;
140 const list<const SMESHDS_Hypothesis*>& hyps = GetUsedHypothesis(aMesh, aShape, false);
144 aStatus = HYP_OK; //SMESH_Hypothesis::HYP_MISSING;
145 return true; // (PAL13464) can work with no hypothesis, LengthFromEdges is default one
148 aStatus = HYP_MISSING;
151 list<const SMESHDS_Hypothesis*>::const_iterator ith;
152 for (ith = hyps.begin(); ith != hyps.end(); ++ith )
154 const SMESHDS_Hypothesis* hyp = (*ith);
156 string hypName = hyp->GetName();
158 if ( hypName == "MaxElementArea")
159 _hypMaxElementArea = static_cast<const StdMeshers_MaxElementArea*> (hyp);
160 else if ( hypName == "LengthFromEdges" )
161 _hypLengthFromEdges = static_cast<const StdMeshers_LengthFromEdges*> (hyp);
162 else if ( hypName == "QuadranglePreference" )
163 _hypQuadranglePreference = static_cast<const StdMeshers_QuadranglePreference*>(hyp);
164 else if ( hypName == "NETGEN_Parameters_2D" )
165 _hypParameters = static_cast<const NETGENPlugin_Hypothesis_2D*>(hyp);
166 else if ( hypName == StdMeshers_ViscousLayers2D::GetHypType() )
169 aStatus = HYP_INCOMPATIBLE;
174 int nbHyps = bool(_hypMaxElementArea) + bool(_hypLengthFromEdges) + bool(_hypParameters );
176 aStatus = HYP_CONCURRENT;
178 error( StdMeshers_ViscousLayers2D::CheckHypothesis( aMesh, aShape, aStatus ));
182 if ( aStatus == HYP_OK && _hypParameters && _hypQuadranglePreference )
184 aStatus = HYP_INCOMPAT_HYPS;
185 return error(SMESH_Comment("\"") << _hypQuadranglePreference->GetName()
186 << "\" and \"" << _hypParameters->GetName()
187 << "\" are incompatible hypotheses");
190 return ( aStatus == HYP_OK );
195 // void limitSize( netgen::Mesh* ngMesh,
196 // const double maxh )
199 // netgen::Point3d pmin, pmax;
200 // ngMesh->GetBox( pmin, pmax, 0 );
201 // const double dx = pmax.X() - pmin.X();
202 // const double dy = pmax.Y() - pmin.Y();
203 // const double dz = pmax.Z() - pmin.Z();
205 // const int nbX = Max( 2, int( dx / maxh * 3 ));
206 // const int nbY = Max( 2, int( dy / maxh * 3 ));
207 // const int nbZ = Max( 2, int( dz / maxh * 3 ));
209 // if ( ! & ngMesh->LocalHFunction() )
210 // ngMesh->SetLocalH( pmin, pmax, 0.1 );
212 // netgen::Point3d p;
213 // for ( int i = 0; i <= nbX; ++i )
215 // p.X() = pmin.X() + i * dx / nbX;
216 // for ( int j = 0; j <= nbY; ++j )
218 // p.Y() = pmin.Y() + j * dy / nbY;
219 // for ( int k = 0; k <= nbZ; ++k )
221 // p.Z() = pmin.Z() + k * dz / nbZ;
222 // ngMesh->RestrictLocalH( p, maxh );
230 // write in a binary file the orientation for each 2D element of the mesh
231 void NETGENPlugin_NETGEN_2D_ONLY::exportElementOrientation(SMESH_Mesh& aMesh,
232 const TopoDS_Shape& aShape,
233 netgen_params& aParams,
234 const std::string output_file)
236 std::map<vtkIdType, bool> elemOrientation;
238 SMESH_ProxyMesh::Ptr proxyMesh( new SMESH_ProxyMesh( aMesh ));
239 for ( TopExp_Explorer exEd( aShape, TopAbs_EDGE ); exEd.More(); exEd.Next())
241 const TopoDS_Shape& aShapeEdge = exEd.Current();
242 const SMESHDS_SubMesh * aSubMeshDSEdge = proxyMesh->GetSubMesh( aShapeEdge );
243 if ( !aSubMeshDSEdge ) continue;
245 SMDS_ElemIteratorPtr iteratorElem = aSubMeshDSEdge->GetElements();
246 while ( iteratorElem->more() ) // loop on elements on a geom face
248 const SMDS_MeshElement* elem = iteratorElem->next();
249 elemOrientation[elem->GetID()] = aShapeEdge.Orientation() == TopAbs_INTERNAL;
253 std::ofstream df(output_file, ios::out|ios::binary);
254 int size=elemOrientation.size();
256 df.write((char*)&size, sizeof(int));
257 for(auto const& [id, orient]:elemOrientation){
258 df.write((char*)&id, sizeof(vtkIdType));
259 df.write((char*)&orient, sizeof(bool));
264 void NETGENPlugin_NETGEN_2D_ONLY::FillParameters(const NETGENPlugin_Hypothesis* hyp, netgen_params &aParams)
266 //TODO: factorize code with the one from NETGEN3D
267 // Move in netgen_param ?
268 aParams.maxh = hyp->GetMaxSize();
269 aParams.minh = hyp->GetMinSize();
270 aParams.segmentsperedge = hyp->GetNbSegPerEdge();
271 aParams.grading = hyp->GetGrowthRate();
272 aParams.curvaturesafety = hyp->GetNbSegPerRadius();
273 aParams.secondorder = hyp->GetSecondOrder() ? 1 : 0;
274 aParams.quad = hyp->GetQuadAllowed() ? 1 : 0;
275 aParams.optimize = hyp->GetOptimize();
276 aParams.fineness = hyp->GetFineness();
277 aParams.uselocalh = hyp->GetSurfaceCurvature();
278 aParams.merge_solids = hyp->GetFuseEdges();
279 aParams.chordalError = hyp->GetChordalErrorEnabled() ? hyp->GetChordalError() : -1.;
280 aParams.optsteps2d = aParams.optimize ? hyp->GetNbSurfOptSteps() : 0;
281 aParams.optsteps3d = aParams.optimize ? hyp->GetNbVolOptSteps() : 0;
282 aParams.elsizeweight = hyp->GetElemSizeWeight();
283 aParams.opterrpow = hyp->GetWorstElemMeasure();
284 aParams.delaunay = hyp->GetUseDelauney();
285 aParams.checkoverlap = hyp->GetCheckOverlapping();
286 aParams.checkchartboundary = hyp->GetCheckChartBoundary();
289 aParams.meshsizefilename = hyp->GetMeshSizeFile();
292 aParams.meshsizefilename = hyp->GetMeshSizeFile().empty() ? 0 : hyp->GetMeshSizeFile().c_str();
295 aParams.closeedgefac = 2;
297 aParams.closeedgefac = 0;
299 aParams.has_LengthFromEdges_hyp = _hypLengthFromEdges;
301 //=============================================================================
303 *Here we are going to use the NETGEN mesher remotely
305 //=============================================================================
307 bool NETGENPlugin_NETGEN_2D_ONLY::RemoteCompute(SMESH_Mesh& aMesh,
308 const TopoDS_Shape& aShape)
311 SMESH_Hypothesis::Hypothesis_Status hypStatus;
312 CheckHypothesis(aMesh, aShape, hypStatus);
314 // Temporary folder for run
315 fs::path tmp_folder = aMesh.tmp_folder / fs::unique_path(fs::path("Face-%%%%-%%%%"));
316 fs::create_directories(tmp_folder);
317 // Using MESH2D generated after all triangles where created.
318 fs::path mesh_file=aMesh.tmp_folder / fs::path("Mesh1D.med");
319 fs::path element_orientation_file=tmp_folder / fs::path("element_orientation.dat");
320 fs::path new_element_file=tmp_folder / fs::path("new_elements.dat");
321 fs::path tmp_mesh_file=tmp_folder / fs::path("tmp_mesh.med");
322 // TODO: Remove that file we do not use it
323 fs::path output_mesh_file=tmp_folder / fs::path("output_mesh.med");
324 fs::path shape_file=tmp_folder / fs::path("shape.step");
325 fs::path param_file=tmp_folder / fs::path("netgen2d_param.txt");
326 fs::path log_file=tmp_folder / fs::path("run.log");
327 //TODO: Handle variable mesh_name
328 std::string mesh_name = "Maillage_1";
331 exportShape(shape_file.string(), aShape);
333 netgen_params aParams;
334 FillParameters(_hypParameters, aParams);
336 exportNetgenParams(param_file.string(), aParams);
338 // Exporting element orientation
339 exportElementOrientation(aMesh, aShape, aParams, element_orientation_file.string());
342 // Calling run_mesher
343 // TODO: check if we need to handle the .exe for windows
345 fs::path run_mesher_exe =
346 fs::path(std::getenv("NETGENPLUGIN_ROOT_DIR"))/
349 fs::path("NETGENPlugin_Runner");
350 cmd = run_mesher_exe.string() +
351 " NETGEN2D " + mesh_file.string() + " "
352 + shape_file.string() + " "
353 + param_file.string() + " "
354 + element_orientation_file.string() + " "
355 + new_element_file.string() + " "
356 + std::to_string(0) + " "
357 + output_mesh_file.string() +
358 " >> " + log_file.string();
360 std::cout << "Running command: " << std::endl;
361 std::cout << cmd << std::endl;
363 // Writing command in log
364 std::ofstream flog(log_file.string());
368 // TODO: Replace system by something else to handle redirection for windows
369 int ret = system(cmd.c_str());
371 // TODO: better error handling (display log ?)
374 //throw Exception("Meshing failed");
375 std::cerr << "Issue with command: " << std::endl;
376 std::cerr << cmd << std::endl;
381 std::ifstream df(new_element_file.string(), ios::binary);
383 int Netgen_NbOfNodes;
384 int Netgen_NbOfNodesNew;
386 double Netgen_point[3];
387 int Netgen_triangle[3];
390 SMESH_MesherHelper helper(aMesh);
391 // This function is necessary so that SetElementOnShape works
392 int _quadraticMesh = helper.IsQuadraticSubMesh(aShape);
393 helper.SetElementsOnShape( true );
395 // Number of nodes in intial mesh
396 df.read((char*) &Netgen_NbOfNodes, sizeof(int));
397 // Number of nodes added by netgen
398 df.read((char*) &Netgen_NbOfNodesNew, sizeof(int));
400 // Filling nodevec (correspondence netgen numbering mesh numbering)
401 vector< const SMDS_MeshNode* > nodeVec ( Netgen_NbOfNodesNew + 1 );
402 for (int nodeIndex = 1 ; nodeIndex <= Netgen_NbOfNodes; ++nodeIndex )
405 df.read((char*) &nodeID, sizeof(int));
406 nodeVec.at(nodeIndex) = nullptr;
407 SMDS_NodeIteratorPtr iteratorNode = aMesh.GetMeshDS()->nodesIterator();
408 while(iteratorNode->more()){
409 const SMDS_MeshNode* node = iteratorNode->next();
410 if(node->GetID() == nodeID){
411 nodeVec.at(nodeIndex) = node;
415 if(nodeVec.at(nodeIndex) == nullptr){
416 std::cout << "Error could not identify id";
421 // Add new points and update nodeVec
422 for (int nodeIndex = Netgen_NbOfNodes +1 ; nodeIndex <= Netgen_NbOfNodesNew; ++nodeIndex )
424 df.read((char *) &Netgen_point, sizeof(double)*3);
426 nodeVec.at(nodeIndex) = helper.AddNode(Netgen_point[0],
432 df.read((char*) &Netgen_NbOfTria, sizeof(int));
433 for ( int elemIndex = 1; elemIndex <= Netgen_NbOfTria; ++elemIndex )
435 df.read((char*) &Netgen_triangle, sizeof(int)*3);
436 helper.AddFace (nodeVec.at( Netgen_triangle[0] ),
437 nodeVec.at( Netgen_triangle[1] ),
438 nodeVec.at( Netgen_triangle[2] ));
446 //=============================================================================
448 *Here we are going to use the NETGEN mesher
450 //=============================================================================
452 bool NETGENPlugin_NETGEN_2D_ONLY::Compute(SMESH_Mesh& aMesh,
453 const TopoDS_Shape& aShape)
456 if(aMesh.IsParallel())
457 return RemoteCompute(aMesh, aShape);
459 netgen::multithread.terminate = 0;
460 netgen::multithread.task = "Surface meshing";
462 SMESHDS_Mesh* meshDS = aMesh.GetMeshDS();
463 SMESH_MesherHelper helper(aMesh);
464 helper.SetElementsOnShape( true );
466 NETGENPlugin_NetgenLibWrapper ngLib;
467 ngLib._isComputeOk = false;
469 netgen::Mesh ngMeshNoLocSize;
470 netgen::Mesh * ngMeshes[2] = { (netgen::Mesh*) ngLib._ngMesh, & ngMeshNoLocSize };
471 netgen::OCCGeometry occgeoComm;
473 // min / max sizes are set as follows:
474 // if ( _hypParameters )
475 // min and max are defined by the user
476 // else if ( _hypLengthFromEdges )
477 // min = aMesher.GetDefaultMinSize()
478 // max = average segment len of a FACE
479 // else if ( _hypMaxElementArea )
480 // min = aMesher.GetDefaultMinSize()
481 // max = f( _hypMaxElementArea )
483 // min = aMesher.GetDefaultMinSize()
484 // max = max segment len of a FACE
485 NETGENPlugin_Mesher aMesher( &aMesh, aShape, /*isVolume=*/false);
486 aMesher.SetParameters( _hypParameters ); // _hypParameters -> netgen::mparam
487 const bool toOptimize = _hypParameters ? _hypParameters->GetOptimize() : true;
488 if ( _hypMaxElementArea )
490 netgen::mparam.maxh = sqrt( 2. * _hypMaxElementArea->GetMaxArea() / sqrt(3.0) );
492 if ( _hypQuadranglePreference )
493 netgen::mparam.quad = true;
495 // local size is common for all FACEs in aShape?
496 const bool isCommonLocalSize = ( !_hypLengthFromEdges && !_hypMaxElementArea && netgen::mparam.uselocalh );
497 const bool isDefaultHyp = ( !_hypLengthFromEdges && !_hypMaxElementArea && !_hypParameters );
501 if ( isCommonLocalSize ) // compute common local size in ngMeshes[0]
503 //list< SMESH_subMesh* > meshedSM[4]; --> all sub-shapes are added to occgeoComm
504 aMesher.PrepareOCCgeometry( occgeoComm, aShape, aMesh );//, meshedSM );
506 // local size set at MESHCONST_ANALYSE step depends on
507 // minh, face_maxh, grading and curvaturesafety; find minh if not set by the user
508 if ( !_hypParameters || netgen::mparam.minh < DBL_MIN )
510 if ( !_hypParameters )
511 netgen::mparam.maxh = occgeoComm.GetBoundingBox().Diam() / 3.;
512 netgen::mparam.minh = aMesher.GetDefaultMinSize( aShape, netgen::mparam.maxh );
514 // set local size depending on curvature and NOT closeness of EDGEs
516 const double factor = 2; //netgen::occparam.resthcloseedgefac;
518 const double factor = netgen::occparam.resthcloseedgefac;
519 netgen::occparam.resthcloseedgeenable = false;
520 netgen::occparam.resthcloseedgefac = 1.0 + netgen::mparam.grading;
522 occgeoComm.face_maxh = netgen::mparam.maxh;
524 netgen::OCCParameters occparam;
525 netgen::OCCSetLocalMeshSize( occgeoComm, *ngMeshes[0], netgen::mparam, occparam );
528 netgen::OCCSetLocalMeshSize( occgeoComm, *ngMeshes[0] );
531 occgeoComm.emap.Clear();
532 occgeoComm.vmap.Clear();
534 // set local size according to size of existing segments
535 TopTools_IndexedMapOfShape edgeMap;
536 TopExp::MapShapes( aMesh.GetShapeToMesh(), TopAbs_EDGE, edgeMap );
537 for ( int iE = 1; iE <= edgeMap.Extent(); ++iE )
539 const TopoDS_Shape& edge = edgeMap( iE );
540 if ( SMESH_Algo::isDegenerated( TopoDS::Edge( edge )))
542 SMESHDS_SubMesh* smDS = meshDS->MeshElements( edge );
543 if ( !smDS ) continue;
544 SMDS_ElemIteratorPtr segIt = smDS->GetElements();
545 while ( segIt->more() )
547 const SMDS_MeshElement* seg = segIt->next();
548 SMESH_TNodeXYZ n1 = seg->GetNode(0);
549 SMESH_TNodeXYZ n2 = seg->GetNode(1);
550 gp_XYZ p = 0.5 * ( n1 + n2 );
551 netgen::Point3d pi(p.X(), p.Y(), p.Z());
552 ngMeshes[0]->RestrictLocalH( pi, factor * ( n1 - n2 ).Modulus() );
556 // set local size defined on shapes
557 aMesher.SetLocalSize( occgeoComm, *ngMeshes[0] );
558 aMesher.SetLocalSizeForChordalError( occgeoComm, *ngMeshes[0] );
560 ngMeshes[0]->LoadLocalMeshSize( netgen::mparam.meshsizefilename );
561 } catch (NgException & ex) {
562 return error( COMPERR_BAD_PARMETERS, ex.What() );
565 netgen::mparam.uselocalh = toOptimize; // restore as it is used at surface optimization
566 // ==================
568 // ==================
570 vector< const SMDS_MeshNode* > nodeVec;
572 TopExp_Explorer fExp( aShape, TopAbs_FACE );
573 for ( int iF = 0; fExp.More(); fExp.Next(), ++iF )
575 TopoDS_Face F = TopoDS::Face( fExp.Current() /*.Oriented( TopAbs_FORWARD )*/);
576 int faceID = meshDS->ShapeToIndex( F );
577 SMESH_ComputeErrorPtr& faceErr = aMesh.GetSubMesh( F )->GetComputeError();
579 _quadraticMesh = helper.IsQuadraticSubMesh( F );
580 const bool ignoreMediumNodes = _quadraticMesh;
582 // build viscous layers if required
583 if ( F.Orientation() != TopAbs_FORWARD &&
584 F.Orientation() != TopAbs_REVERSED )
585 F.Orientation( TopAbs_FORWARD ); // avoid pb with TopAbs_INTERNAL
586 SMESH_ProxyMesh::Ptr proxyMesh = StdMeshers_ViscousLayers2D::Compute( aMesh, F );
590 // ------------------------
591 // get all EDGEs of a FACE
592 // ------------------------
594 StdMeshers_FaceSide::GetFaceWires( F, aMesh, ignoreMediumNodes, faceErr, &helper, proxyMesh );
595 if ( faceErr && !faceErr->IsOK() )
597 size_t nbWires = wires.size();
601 ( new SMESH_ComputeError
602 ( COMPERR_ALGO_FAILED, "Problem in StdMeshers_FaceSide::GetFaceWires()" ));
605 if ( wires[0]->NbSegments() < 3 ) // ex: a circle with 2 segments
608 ( new SMESH_ComputeError
609 ( COMPERR_BAD_INPUT_MESH, SMESH_Comment("Too few segments: ")<<wires[0]->NbSegments()) );
613 // ----------------------
614 // compute maxh of a FACE
615 // ----------------------
617 if ( !_hypParameters )
619 double edgeLength = 0;
620 if (_hypLengthFromEdges )
622 // compute edgeLength as an average segment length
623 smIdType nbSegments = 0;
624 for ( size_t iW = 0; iW < nbWires; ++iW )
626 edgeLength += wires[ iW ]->Length();
627 nbSegments += wires[ iW ]->NbSegments();
630 edgeLength /= double( nbSegments );
631 netgen::mparam.maxh = edgeLength;
633 else if ( isDefaultHyp )
635 // set edgeLength by a longest segment
637 for ( size_t iW = 0; iW < nbWires; ++iW )
639 const UVPtStructVec& points = wires[ iW ]->GetUVPtStruct();
640 if ( points.empty() )
641 return error( COMPERR_BAD_INPUT_MESH );
642 gp_Pnt pPrev = SMESH_TNodeXYZ( points[0].node );
643 for ( size_t i = 1; i < points.size(); ++i )
645 gp_Pnt p = SMESH_TNodeXYZ( points[i].node );
646 maxSeg2 = Max( maxSeg2, p.SquareDistance( pPrev ));
650 edgeLength = sqrt( maxSeg2 ) * 1.05;
651 netgen::mparam.maxh = edgeLength;
653 if ( netgen::mparam.maxh < DBL_MIN )
654 netgen::mparam.maxh = occgeoComm.GetBoundingBox().Diam();
656 if ( !isCommonLocalSize )
658 netgen::mparam.minh = aMesher.GetDefaultMinSize( F, netgen::mparam.maxh );
663 netgen::OCCGeometry occgeom;
665 occgeom.fmap.Add( F );
666 occgeom.CalcBoundingBox();
667 occgeom.facemeshstatus.SetSize(1);
668 occgeom.facemeshstatus = 0;
669 occgeom.face_maxh_modified.SetSize(1);
670 occgeom.face_maxh_modified = 0;
671 occgeom.face_maxh.SetSize(1);
672 occgeom.face_maxh = netgen::mparam.maxh;
674 // -------------------------
676 // -------------------------
678 // MESHCONST_ANALYSE step may lead to a failure, so we make an attempt
679 // w/o MESHCONST_ANALYSE at the second loop
681 enum { LOC_SIZE, NO_LOC_SIZE };
682 int iLoop = isCommonLocalSize ? 0 : 1;
683 for ( ; iLoop < 2; iLoop++ )
685 //bool isMESHCONST_ANALYSE = false;
688 netgen::Mesh * ngMesh = ngMeshes[ iLoop ];
689 ngMesh->DeleteMesh();
691 if ( iLoop == NO_LOC_SIZE )
693 ngMesh->SetGlobalH ( netgen::mparam.maxh );
694 ngMesh->SetMinimalH( netgen::mparam.minh );
695 Box<3> bb = occgeom.GetBoundingBox();
696 bb.Increase (bb.Diam()/10);
697 ngMesh->SetLocalH (bb.PMin(), bb.PMax(), netgen::mparam.grading);
698 aMesher.SetLocalSize( occgeom, *ngMesh );
699 aMesher.SetLocalSizeForChordalError( occgeoComm, *ngMesh );
701 ngMesh->LoadLocalMeshSize( netgen::mparam.meshsizefilename );
702 } catch (NgException & ex) {
703 return error( COMPERR_BAD_PARMETERS, ex.What() );
708 faceErr = aMesher.AddSegmentsToMesh( *ngMesh, occgeom, wires, helper, nodeVec,
709 /*overrideMinH=*/!_hypParameters);
710 if ( faceErr && !faceErr->IsOK() )
713 //if ( !isCommonLocalSize )
714 //limitSize( ngMesh, netgen::mparam.maxh * 0.8);
716 // -------------------------
717 // Generate surface mesh
718 // -------------------------
720 const int startWith = MESHCONST_MESHSURFACE;
721 const int endWith = toOptimize ? MESHCONST_OPTSURFACE : MESHCONST_MESHSURFACE;
726 err = ngLib.GenerateMesh(occgeom, startWith, endWith, ngMesh);
727 if ( netgen::multithread.terminate )
730 str << "Error in netgen::OCCGenerateMesh() at " << netgen::multithread.task;
732 catch (Standard_Failure& ex)
735 str << "Exception in netgen::OCCGenerateMesh()"
736 << " at " << netgen::multithread.task
737 << ": " << ex.DynamicType()->Name();
738 if ( ex.GetMessageString() && strlen( ex.GetMessageString() ))
739 str << ": " << ex.GetMessageString();
743 str << "Exception in netgen::OCCGenerateMesh()"
744 << " at " << netgen::multithread.task;
748 if ( aMesher.FixFaceMesh( occgeom, *ngMesh, 1 ))
750 if ( iLoop == LOC_SIZE )
752 netgen::mparam.minh = netgen::mparam.maxh;
753 netgen::mparam.maxh = 0;
754 for ( size_t iW = 0; iW < wires.size(); ++iW )
756 StdMeshers_FaceSidePtr wire = wires[ iW ];
757 const vector<UVPtStruct>& uvPtVec = wire->GetUVPtStruct();
758 for ( size_t iP = 1; iP < uvPtVec.size(); ++iP )
760 SMESH_TNodeXYZ p( uvPtVec[ iP ].node );
761 netgen::Point3d np( p.X(),p.Y(),p.Z());
762 double segLen = p.Distance( uvPtVec[ iP-1 ].node );
763 double size = ngMesh->GetH( np );
764 netgen::mparam.minh = Min( netgen::mparam.minh, size );
765 netgen:: mparam.maxh = Max( netgen::mparam.maxh, segLen );
768 //cerr << "min " << mparam.minh << " max " << mparam.maxh << endl;
769 netgen::mparam.minh *= 0.9;
770 netgen::mparam.maxh *= 1.1;
775 faceErr.reset( new SMESH_ComputeError( COMPERR_ALGO_FAILED, str ));
779 // ----------------------------------------------------
780 // Fill the SMESHDS with the generated nodes and faces
781 // ----------------------------------------------------
783 int nbNodes = ngMesh->GetNP();
784 int nbFaces = ngMesh->GetNSE();
786 int nbInputNodes = (int) nodeVec.size()-1;
787 nodeVec.resize( nbNodes+1, 0 );
790 for ( int ngID = nbInputNodes + 1; ngID <= nbNodes; ++ngID )
792 const MeshPoint& ngPoint = ngMesh->Point( ngID );
793 SMDS_MeshNode * node = meshDS->AddNode(ngPoint(0), ngPoint(1), ngPoint(2));
794 nodeVec[ ngID ] = node;
799 vector<const SMDS_MeshNode*> nodes;
800 for ( i = 1; i <= nbFaces ; ++i )
802 const Element2d& elem = ngMesh->SurfaceElement(i);
803 nodes.resize( elem.GetNP() );
804 for (j=1; j <= elem.GetNP(); ++j)
806 int pind = elem.PNum(j);
809 nodes[ j-1 ] = nodeVec[ pind ];
810 if ( nodes[ j-1 ]->GetPosition()->GetTypeOfPosition() == SMDS_TOP_3DSPACE )
812 const PointGeomInfo& pgi = elem.GeomInfoPi(j);
813 meshDS->SetNodeOnFace( nodes[ j-1 ], faceID, pgi.u, pgi.v);
816 if ( j > elem.GetNP() )
818 if ( elem.GetType() == TRIG )
819 helper.AddFace(nodes[0],nodes[1],nodes[2]);
821 helper.AddFace(nodes[0],nodes[1],nodes[2],nodes[3]);
832 void NETGENPlugin_NETGEN_2D_ONLY::CancelCompute()
834 SMESH_Algo::CancelCompute();
835 netgen::multithread.terminate = 1;
838 //================================================================================
840 * \brief Return progress of Compute() [0.,1]
842 //================================================================================
844 double NETGENPlugin_NETGEN_2D_ONLY::GetProgress() const
847 // const char* task1 = "Surface meshing";
848 // //const char* task2 = "Optimizing surface";
849 // double& progress = const_cast<NETGENPlugin_NETGEN_2D_ONLY*>( this )->_progress;
850 // if ( _progressByTic < 0. &&
851 // strncmp( netgen::multithread.task, task1, 3 ) == 0 )
853 // progress = Min( 0.25, SMESH_Algo::GetProgressByTic() ); // [0, 0.25]
855 // else //if ( strncmp( netgen::multithread.task, task2, 3 ) == 0)
857 // if ( _progressByTic < 0 )
859 // NETGENPlugin_NETGEN_2D_ONLY* me = (NETGENPlugin_NETGEN_2D_ONLY*) this;
860 // me->_progressByTic = 0.25 / (_progressTic+1);
862 // const_cast<NETGENPlugin_NETGEN_2D_ONLY*>( this )->_progressTic++;
863 // progress = Max( progress, _progressByTic * _progressTic );
865 // //cout << netgen::multithread.task << " " << _progressTic << endl;
866 // return Min( progress, 0.99 );
869 //=============================================================================
873 //=============================================================================
875 bool NETGENPlugin_NETGEN_2D_ONLY::Evaluate(SMESH_Mesh& aMesh,
876 const TopoDS_Shape& aShape,
877 MapShapeNbElems& aResMap)
879 TopoDS_Face F = TopoDS::Face(aShape);
883 // collect info from edges
884 smIdType nb0d = 0, nb1d = 0;
885 bool IsQuadratic = false;
887 double fullLen = 0.0;
888 TopTools_MapOfShape tmpMap;
889 for (TopExp_Explorer exp(F, TopAbs_EDGE); exp.More(); exp.Next()) {
890 TopoDS_Edge E = TopoDS::Edge(exp.Current());
891 if( tmpMap.Contains(E) )
894 SMESH_subMesh *aSubMesh = aMesh.GetSubMesh(exp.Current());
895 MapShapeNbElemsItr anIt = aResMap.find(aSubMesh);
896 if( anIt==aResMap.end() ) {
897 SMESH_subMesh *sm = aMesh.GetSubMesh(F);
898 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
899 smError.reset( new SMESH_ComputeError(COMPERR_ALGO_FAILED,"Submesh can not be evaluated",this));
902 std::vector<smIdType> aVec = (*anIt).second;
903 nb0d += aVec[SMDSEntity_Node];
904 nb1d += std::max(aVec[SMDSEntity_Edge],aVec[SMDSEntity_Quad_Edge]);
905 double aLen = SMESH_Algo::EdgeLength(E);
908 IsQuadratic = (aVec[SMDSEntity_Quad_Edge] > aVec[SMDSEntity_Edge]);
914 // compute edge length
916 if (( _hypLengthFromEdges ) || ( !_hypLengthFromEdges && !_hypMaxElementArea )) {
918 ELen = fullLen / double( nb1d );
920 if ( _hypMaxElementArea ) {
921 double maxArea = _hypMaxElementArea->GetMaxArea();
922 ELen = sqrt(2. * maxArea/sqrt(3.0));
925 BRepGProp::SurfaceProperties(F,G);
926 double anArea = G.Mass();
928 const int hugeNb = numeric_limits<int>::max()/10;
929 if ( anArea / hugeNb > ELen*ELen )
931 SMESH_subMesh *sm = aMesh.GetSubMesh(F);
932 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
933 smError.reset( new SMESH_ComputeError(COMPERR_ALGO_FAILED,"Submesh can not be evaluated.\nToo small element length",this));
936 smIdType nbFaces = (smIdType) ( anArea / ( ELen*ELen*sqrt(3.) / 4 ) );
937 smIdType nbNodes = (smIdType) ( ( nbFaces*3 - (nb1d-1)*2 ) / 6 + 1 );
938 std::vector<smIdType> aVec(SMDSEntity_Last);
939 for(smIdType i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aVec[i]=0;
941 aVec[SMDSEntity_Node] = nbNodes;
942 aVec[SMDSEntity_Quad_Triangle] = nbFaces;
945 aVec[SMDSEntity_Node] = nbNodes;
946 aVec[SMDSEntity_Triangle] = nbFaces;
948 SMESH_subMesh *sm = aMesh.GetSubMesh(F);
949 aResMap.insert(std::make_pair(sm,aVec));