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_DriverShape.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");
329 exportShape(shape_file.string(), aShape);
331 netgen_params aParams;
332 FillParameters(_hypParameters, aParams);
334 exportNetgenParams(param_file.string(), aParams);
336 // Exporting element orientation
337 exportElementOrientation(aMesh, aShape, aParams, element_orientation_file.string());
340 // Calling run_mesher
341 // TODO: check if we need to handle the .exe for windows
343 fs::path run_mesher_exe =
344 fs::path(std::getenv("NETGENPLUGIN_ROOT_DIR"))/
347 fs::path("NETGENPlugin_Runner");
348 cmd = run_mesher_exe.string() +
349 " NETGEN2D " + mesh_file.string() + " "
350 + shape_file.string() + " "
351 + param_file.string() + " "
352 + element_orientation_file.string() + " "
353 + new_element_file.string() + " "
354 + std::to_string(0) + " "
355 + output_mesh_file.string() +
356 " >> " + log_file.string();
358 std::cout << "Running command: " << std::endl;
359 std::cout << cmd << std::endl;
361 // Writing command in log
362 std::ofstream flog(log_file.string());
366 // TODO: Replace system by something else to handle redirection for windows
367 int ret = system(cmd.c_str());
369 // TODO: better error handling (display log ?)
372 //throw Exception("Meshing failed");
373 std::cerr << "Issue with command: " << std::endl;
374 std::cerr << cmd << std::endl;
379 std::ifstream df(new_element_file.string(), ios::binary);
381 int Netgen_NbOfNodes;
382 int Netgen_NbOfNodesNew;
384 double Netgen_point[3];
385 int Netgen_triangle[3];
388 SMESH_MesherHelper helper(aMesh);
389 // This function is necessary so that SetElementOnShape works
390 int _quadraticMesh = helper.IsQuadraticSubMesh(aShape);
391 helper.SetElementsOnShape( true );
393 // Number of nodes in intial mesh
394 df.read((char*) &Netgen_NbOfNodes, sizeof(int));
395 // Number of nodes added by netgen
396 df.read((char*) &Netgen_NbOfNodesNew, sizeof(int));
398 // Filling nodevec (correspondence netgen numbering mesh numbering)
399 vector< const SMDS_MeshNode* > nodeVec ( Netgen_NbOfNodesNew + 1 );
400 for (int nodeIndex = 1 ; nodeIndex <= Netgen_NbOfNodes; ++nodeIndex )
403 df.read((char*) &nodeID, sizeof(int));
404 nodeVec.at(nodeIndex) = nullptr;
405 SMDS_NodeIteratorPtr iteratorNode = aMesh.GetMeshDS()->nodesIterator();
406 while(iteratorNode->more()){
407 const SMDS_MeshNode* node = iteratorNode->next();
408 if(node->GetID() == nodeID){
409 nodeVec.at(nodeIndex) = node;
413 if(nodeVec.at(nodeIndex) == nullptr){
414 std::cout << "Error could not identify id";
419 // Add new points and update nodeVec
420 for (int nodeIndex = Netgen_NbOfNodes +1 ; nodeIndex <= Netgen_NbOfNodesNew; ++nodeIndex )
422 df.read((char *) &Netgen_point, sizeof(double)*3);
424 nodeVec.at(nodeIndex) = helper.AddNode(Netgen_point[0],
430 df.read((char*) &Netgen_NbOfTria, sizeof(int));
431 for ( int elemIndex = 1; elemIndex <= Netgen_NbOfTria; ++elemIndex )
433 df.read((char*) &Netgen_triangle, sizeof(int)*3);
434 helper.AddFace (nodeVec.at( Netgen_triangle[0] ),
435 nodeVec.at( Netgen_triangle[1] ),
436 nodeVec.at( Netgen_triangle[2] ));
444 //=============================================================================
446 *Here we are going to use the NETGEN mesher
448 //=============================================================================
450 bool NETGENPlugin_NETGEN_2D_ONLY::Compute(SMESH_Mesh& aMesh,
451 const TopoDS_Shape& aShape)
454 if(aMesh.IsParallel())
455 return RemoteCompute(aMesh, aShape);
457 netgen::multithread.terminate = 0;
458 netgen::multithread.task = "Surface meshing";
460 SMESHDS_Mesh* meshDS = aMesh.GetMeshDS();
461 SMESH_MesherHelper helper(aMesh);
462 helper.SetElementsOnShape( true );
464 NETGENPlugin_NetgenLibWrapper ngLib;
465 ngLib._isComputeOk = false;
467 netgen::Mesh ngMeshNoLocSize;
468 netgen::Mesh * ngMeshes[2] = { (netgen::Mesh*) ngLib._ngMesh, & ngMeshNoLocSize };
469 netgen::OCCGeometry occgeoComm;
471 // min / max sizes are set as follows:
472 // if ( _hypParameters )
473 // min and max are defined by the user
474 // else if ( _hypLengthFromEdges )
475 // min = aMesher.GetDefaultMinSize()
476 // max = average segment len of a FACE
477 // else if ( _hypMaxElementArea )
478 // min = aMesher.GetDefaultMinSize()
479 // max = f( _hypMaxElementArea )
481 // min = aMesher.GetDefaultMinSize()
482 // max = max segment len of a FACE
483 NETGENPlugin_Mesher aMesher( &aMesh, aShape, /*isVolume=*/false);
484 aMesher.SetParameters( _hypParameters ); // _hypParameters -> netgen::mparam
485 const bool toOptimize = _hypParameters ? _hypParameters->GetOptimize() : true;
486 if ( _hypMaxElementArea )
488 netgen::mparam.maxh = sqrt( 2. * _hypMaxElementArea->GetMaxArea() / sqrt(3.0) );
490 if ( _hypQuadranglePreference )
491 netgen::mparam.quad = true;
493 // local size is common for all FACEs in aShape?
494 const bool isCommonLocalSize = ( !_hypLengthFromEdges && !_hypMaxElementArea && netgen::mparam.uselocalh );
495 const bool isDefaultHyp = ( !_hypLengthFromEdges && !_hypMaxElementArea && !_hypParameters );
499 if ( isCommonLocalSize ) // compute common local size in ngMeshes[0]
501 //list< SMESH_subMesh* > meshedSM[4]; --> all sub-shapes are added to occgeoComm
502 aMesher.PrepareOCCgeometry( occgeoComm, aShape, aMesh );//, meshedSM );
504 // local size set at MESHCONST_ANALYSE step depends on
505 // minh, face_maxh, grading and curvaturesafety; find minh if not set by the user
506 if ( !_hypParameters || netgen::mparam.minh < DBL_MIN )
508 if ( !_hypParameters )
509 netgen::mparam.maxh = occgeoComm.GetBoundingBox().Diam() / 3.;
510 netgen::mparam.minh = aMesher.GetDefaultMinSize( aShape, netgen::mparam.maxh );
512 // set local size depending on curvature and NOT closeness of EDGEs
514 const double factor = 2; //netgen::occparam.resthcloseedgefac;
516 const double factor = netgen::occparam.resthcloseedgefac;
517 netgen::occparam.resthcloseedgeenable = false;
518 netgen::occparam.resthcloseedgefac = 1.0 + netgen::mparam.grading;
520 occgeoComm.face_maxh = netgen::mparam.maxh;
522 netgen::OCCParameters occparam;
523 netgen::OCCSetLocalMeshSize( occgeoComm, *ngMeshes[0], netgen::mparam, occparam );
526 netgen::OCCSetLocalMeshSize( occgeoComm, *ngMeshes[0] );
529 occgeoComm.emap.Clear();
530 occgeoComm.vmap.Clear();
532 // set local size according to size of existing segments
533 TopTools_IndexedMapOfShape edgeMap;
534 TopExp::MapShapes( aMesh.GetShapeToMesh(), TopAbs_EDGE, edgeMap );
535 for ( int iE = 1; iE <= edgeMap.Extent(); ++iE )
537 const TopoDS_Shape& edge = edgeMap( iE );
538 if ( SMESH_Algo::isDegenerated( TopoDS::Edge( edge )))
540 SMESHDS_SubMesh* smDS = meshDS->MeshElements( edge );
541 if ( !smDS ) continue;
542 SMDS_ElemIteratorPtr segIt = smDS->GetElements();
543 while ( segIt->more() )
545 const SMDS_MeshElement* seg = segIt->next();
546 SMESH_TNodeXYZ n1 = seg->GetNode(0);
547 SMESH_TNodeXYZ n2 = seg->GetNode(1);
548 gp_XYZ p = 0.5 * ( n1 + n2 );
549 netgen::Point3d pi(p.X(), p.Y(), p.Z());
550 ngMeshes[0]->RestrictLocalH( pi, factor * ( n1 - n2 ).Modulus() );
554 // set local size defined on shapes
555 aMesher.SetLocalSize( occgeoComm, *ngMeshes[0] );
556 aMesher.SetLocalSizeForChordalError( occgeoComm, *ngMeshes[0] );
558 ngMeshes[0]->LoadLocalMeshSize( netgen::mparam.meshsizefilename );
559 } catch (NgException & ex) {
560 return error( COMPERR_BAD_PARMETERS, ex.What() );
563 netgen::mparam.uselocalh = toOptimize; // restore as it is used at surface optimization
564 // ==================
566 // ==================
568 vector< const SMDS_MeshNode* > nodeVec;
570 TopExp_Explorer fExp( aShape, TopAbs_FACE );
571 for ( int iF = 0; fExp.More(); fExp.Next(), ++iF )
573 TopoDS_Face F = TopoDS::Face( fExp.Current() /*.Oriented( TopAbs_FORWARD )*/);
574 int faceID = meshDS->ShapeToIndex( F );
575 SMESH_ComputeErrorPtr& faceErr = aMesh.GetSubMesh( F )->GetComputeError();
577 _quadraticMesh = helper.IsQuadraticSubMesh( F );
578 const bool ignoreMediumNodes = _quadraticMesh;
580 // build viscous layers if required
581 if ( F.Orientation() != TopAbs_FORWARD &&
582 F.Orientation() != TopAbs_REVERSED )
583 F.Orientation( TopAbs_FORWARD ); // avoid pb with TopAbs_INTERNAL
584 SMESH_ProxyMesh::Ptr proxyMesh = StdMeshers_ViscousLayers2D::Compute( aMesh, F );
588 // ------------------------
589 // get all EDGEs of a FACE
590 // ------------------------
592 StdMeshers_FaceSide::GetFaceWires( F, aMesh, ignoreMediumNodes, faceErr, &helper, proxyMesh );
593 if ( faceErr && !faceErr->IsOK() )
595 size_t nbWires = wires.size();
599 ( new SMESH_ComputeError
600 ( COMPERR_ALGO_FAILED, "Problem in StdMeshers_FaceSide::GetFaceWires()" ));
603 if ( wires[0]->NbSegments() < 3 ) // ex: a circle with 2 segments
606 ( new SMESH_ComputeError
607 ( COMPERR_BAD_INPUT_MESH, SMESH_Comment("Too few segments: ")<<wires[0]->NbSegments()) );
611 // ----------------------
612 // compute maxh of a FACE
613 // ----------------------
615 if ( !_hypParameters )
617 double edgeLength = 0;
618 if (_hypLengthFromEdges )
620 // compute edgeLength as an average segment length
621 smIdType nbSegments = 0;
622 for ( size_t iW = 0; iW < nbWires; ++iW )
624 edgeLength += wires[ iW ]->Length();
625 nbSegments += wires[ iW ]->NbSegments();
628 edgeLength /= double( nbSegments );
629 netgen::mparam.maxh = edgeLength;
631 else if ( isDefaultHyp )
633 // set edgeLength by a longest segment
635 for ( size_t iW = 0; iW < nbWires; ++iW )
637 const UVPtStructVec& points = wires[ iW ]->GetUVPtStruct();
638 if ( points.empty() )
639 return error( COMPERR_BAD_INPUT_MESH );
640 gp_Pnt pPrev = SMESH_TNodeXYZ( points[0].node );
641 for ( size_t i = 1; i < points.size(); ++i )
643 gp_Pnt p = SMESH_TNodeXYZ( points[i].node );
644 maxSeg2 = Max( maxSeg2, p.SquareDistance( pPrev ));
648 edgeLength = sqrt( maxSeg2 ) * 1.05;
649 netgen::mparam.maxh = edgeLength;
651 if ( netgen::mparam.maxh < DBL_MIN )
652 netgen::mparam.maxh = occgeoComm.GetBoundingBox().Diam();
654 if ( !isCommonLocalSize )
656 netgen::mparam.minh = aMesher.GetDefaultMinSize( F, netgen::mparam.maxh );
661 netgen::OCCGeometry occgeom;
663 occgeom.fmap.Add( F );
664 occgeom.CalcBoundingBox();
665 occgeom.facemeshstatus.SetSize(1);
666 occgeom.facemeshstatus = 0;
667 occgeom.face_maxh_modified.SetSize(1);
668 occgeom.face_maxh_modified = 0;
669 occgeom.face_maxh.SetSize(1);
670 occgeom.face_maxh = netgen::mparam.maxh;
672 // -------------------------
674 // -------------------------
676 // MESHCONST_ANALYSE step may lead to a failure, so we make an attempt
677 // w/o MESHCONST_ANALYSE at the second loop
679 enum { LOC_SIZE, NO_LOC_SIZE };
680 int iLoop = isCommonLocalSize ? 0 : 1;
681 for ( ; iLoop < 2; iLoop++ )
683 //bool isMESHCONST_ANALYSE = false;
686 netgen::Mesh * ngMesh = ngMeshes[ iLoop ];
687 ngMesh->DeleteMesh();
689 if ( iLoop == NO_LOC_SIZE )
691 ngMesh->SetGlobalH ( netgen::mparam.maxh );
692 ngMesh->SetMinimalH( netgen::mparam.minh );
693 Box<3> bb = occgeom.GetBoundingBox();
694 bb.Increase (bb.Diam()/10);
695 ngMesh->SetLocalH (bb.PMin(), bb.PMax(), netgen::mparam.grading);
696 aMesher.SetLocalSize( occgeom, *ngMesh );
697 aMesher.SetLocalSizeForChordalError( occgeoComm, *ngMesh );
699 ngMesh->LoadLocalMeshSize( netgen::mparam.meshsizefilename );
700 } catch (NgException & ex) {
701 return error( COMPERR_BAD_PARMETERS, ex.What() );
706 faceErr = aMesher.AddSegmentsToMesh( *ngMesh, occgeom, wires, helper, nodeVec,
707 /*overrideMinH=*/!_hypParameters);
708 if ( faceErr && !faceErr->IsOK() )
711 //if ( !isCommonLocalSize )
712 //limitSize( ngMesh, netgen::mparam.maxh * 0.8);
714 // -------------------------
715 // Generate surface mesh
716 // -------------------------
718 const int startWith = MESHCONST_MESHSURFACE;
719 const int endWith = toOptimize ? MESHCONST_OPTSURFACE : MESHCONST_MESHSURFACE;
724 err = ngLib.GenerateMesh(occgeom, startWith, endWith, ngMesh);
725 if ( netgen::multithread.terminate )
728 str << "Error in netgen::OCCGenerateMesh() at " << netgen::multithread.task;
730 catch (Standard_Failure& ex)
733 str << "Exception in netgen::OCCGenerateMesh()"
734 << " at " << netgen::multithread.task
735 << ": " << ex.DynamicType()->Name();
736 if ( ex.GetMessageString() && strlen( ex.GetMessageString() ))
737 str << ": " << ex.GetMessageString();
741 str << "Exception in netgen::OCCGenerateMesh()"
742 << " at " << netgen::multithread.task;
746 if ( aMesher.FixFaceMesh( occgeom, *ngMesh, 1 ))
748 if ( iLoop == LOC_SIZE )
750 netgen::mparam.minh = netgen::mparam.maxh;
751 netgen::mparam.maxh = 0;
752 for ( size_t iW = 0; iW < wires.size(); ++iW )
754 StdMeshers_FaceSidePtr wire = wires[ iW ];
755 const vector<UVPtStruct>& uvPtVec = wire->GetUVPtStruct();
756 for ( size_t iP = 1; iP < uvPtVec.size(); ++iP )
758 SMESH_TNodeXYZ p( uvPtVec[ iP ].node );
759 netgen::Point3d np( p.X(),p.Y(),p.Z());
760 double segLen = p.Distance( uvPtVec[ iP-1 ].node );
761 double size = ngMesh->GetH( np );
762 netgen::mparam.minh = Min( netgen::mparam.minh, size );
763 netgen:: mparam.maxh = Max( netgen::mparam.maxh, segLen );
766 //cerr << "min " << mparam.minh << " max " << mparam.maxh << endl;
767 netgen::mparam.minh *= 0.9;
768 netgen::mparam.maxh *= 1.1;
773 faceErr.reset( new SMESH_ComputeError( COMPERR_ALGO_FAILED, str ));
777 // ----------------------------------------------------
778 // Fill the SMESHDS with the generated nodes and faces
779 // ----------------------------------------------------
781 int nbNodes = ngMesh->GetNP();
782 int nbFaces = ngMesh->GetNSE();
784 int nbInputNodes = (int) nodeVec.size()-1;
785 nodeVec.resize( nbNodes+1, 0 );
788 for ( int ngID = nbInputNodes + 1; ngID <= nbNodes; ++ngID )
790 const MeshPoint& ngPoint = ngMesh->Point( ngID );
791 SMDS_MeshNode * node = meshDS->AddNode(ngPoint(0), ngPoint(1), ngPoint(2));
792 nodeVec[ ngID ] = node;
797 vector<const SMDS_MeshNode*> nodes;
798 for ( i = 1; i <= nbFaces ; ++i )
800 const Element2d& elem = ngMesh->SurfaceElement(i);
801 nodes.resize( elem.GetNP() );
802 for (j=1; j <= elem.GetNP(); ++j)
804 int pind = elem.PNum(j);
807 nodes[ j-1 ] = nodeVec[ pind ];
808 if ( nodes[ j-1 ]->GetPosition()->GetTypeOfPosition() == SMDS_TOP_3DSPACE )
810 const PointGeomInfo& pgi = elem.GeomInfoPi(j);
811 meshDS->SetNodeOnFace( nodes[ j-1 ], faceID, pgi.u, pgi.v);
814 if ( j > elem.GetNP() )
816 if ( elem.GetType() == TRIG )
817 helper.AddFace(nodes[0],nodes[1],nodes[2]);
819 helper.AddFace(nodes[0],nodes[1],nodes[2],nodes[3]);
830 void NETGENPlugin_NETGEN_2D_ONLY::CancelCompute()
832 SMESH_Algo::CancelCompute();
833 netgen::multithread.terminate = 1;
836 //================================================================================
838 * \brief Return progress of Compute() [0.,1]
840 //================================================================================
842 double NETGENPlugin_NETGEN_2D_ONLY::GetProgress() const
845 // const char* task1 = "Surface meshing";
846 // //const char* task2 = "Optimizing surface";
847 // double& progress = const_cast<NETGENPlugin_NETGEN_2D_ONLY*>( this )->_progress;
848 // if ( _progressByTic < 0. &&
849 // strncmp( netgen::multithread.task, task1, 3 ) == 0 )
851 // progress = Min( 0.25, SMESH_Algo::GetProgressByTic() ); // [0, 0.25]
853 // else //if ( strncmp( netgen::multithread.task, task2, 3 ) == 0)
855 // if ( _progressByTic < 0 )
857 // NETGENPlugin_NETGEN_2D_ONLY* me = (NETGENPlugin_NETGEN_2D_ONLY*) this;
858 // me->_progressByTic = 0.25 / (_progressTic+1);
860 // const_cast<NETGENPlugin_NETGEN_2D_ONLY*>( this )->_progressTic++;
861 // progress = Max( progress, _progressByTic * _progressTic );
863 // //cout << netgen::multithread.task << " " << _progressTic << endl;
864 // return Min( progress, 0.99 );
867 //=============================================================================
871 //=============================================================================
873 bool NETGENPlugin_NETGEN_2D_ONLY::Evaluate(SMESH_Mesh& aMesh,
874 const TopoDS_Shape& aShape,
875 MapShapeNbElems& aResMap)
877 TopoDS_Face F = TopoDS::Face(aShape);
881 // collect info from edges
882 smIdType nb0d = 0, nb1d = 0;
883 bool IsQuadratic = false;
885 double fullLen = 0.0;
886 TopTools_MapOfShape tmpMap;
887 for (TopExp_Explorer exp(F, TopAbs_EDGE); exp.More(); exp.Next()) {
888 TopoDS_Edge E = TopoDS::Edge(exp.Current());
889 if( tmpMap.Contains(E) )
892 SMESH_subMesh *aSubMesh = aMesh.GetSubMesh(exp.Current());
893 MapShapeNbElemsItr anIt = aResMap.find(aSubMesh);
894 if( anIt==aResMap.end() ) {
895 SMESH_subMesh *sm = aMesh.GetSubMesh(F);
896 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
897 smError.reset( new SMESH_ComputeError(COMPERR_ALGO_FAILED,"Submesh can not be evaluated",this));
900 std::vector<smIdType> aVec = (*anIt).second;
901 nb0d += aVec[SMDSEntity_Node];
902 nb1d += std::max(aVec[SMDSEntity_Edge],aVec[SMDSEntity_Quad_Edge]);
903 double aLen = SMESH_Algo::EdgeLength(E);
906 IsQuadratic = (aVec[SMDSEntity_Quad_Edge] > aVec[SMDSEntity_Edge]);
912 // compute edge length
914 if (( _hypLengthFromEdges ) || ( !_hypLengthFromEdges && !_hypMaxElementArea )) {
916 ELen = fullLen / double( nb1d );
918 if ( _hypMaxElementArea ) {
919 double maxArea = _hypMaxElementArea->GetMaxArea();
920 ELen = sqrt(2. * maxArea/sqrt(3.0));
923 BRepGProp::SurfaceProperties(F,G);
924 double anArea = G.Mass();
926 const int hugeNb = numeric_limits<int>::max()/10;
927 if ( anArea / hugeNb > ELen*ELen )
929 SMESH_subMesh *sm = aMesh.GetSubMesh(F);
930 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
931 smError.reset( new SMESH_ComputeError(COMPERR_ALGO_FAILED,"Submesh can not be evaluated.\nToo small element length",this));
934 smIdType nbFaces = (smIdType) ( anArea / ( ELen*ELen*sqrt(3.) / 4 ) );
935 smIdType nbNodes = (smIdType) ( ( nbFaces*3 - (nb1d-1)*2 ) / 6 + 1 );
936 std::vector<smIdType> aVec(SMDSEntity_Last);
937 for(smIdType i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aVec[i]=0;
939 aVec[SMDSEntity_Node] = nbNodes;
940 aVec[SMDSEntity_Quad_Triangle] = nbFaces;
943 aVec[SMDSEntity_Node] = nbNodes;
944 aVec[SMDSEntity_Triangle] = nbFaces;
946 SMESH_subMesh *sm = aMesh.GetSubMesh(F);
947 aResMap.insert(std::make_pair(sm,aVec));