1 // Copyright (C) 2007-2008 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
22 // File : NETGENPlugin_NETGEN_2D_ONLY.cxx
23 // Author : Edward AGAPOV (OCC)
26 #include "NETGENPlugin_NETGEN_2D_ONLY.hxx"
28 #include "NETGENPlugin_Mesher.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 "StdMeshers_FaceSide.hxx"
38 #include "StdMeshers_MaxElementArea.hxx"
39 #include "StdMeshers_LengthFromEdges.hxx"
40 #include "StdMeshers_QuadranglePreference.hxx"
42 #include <Precision.hxx>
43 #include <Standard_ErrorHandler.hxx>
44 #include <Standard_Failure.hxx>
46 #include "utilities.h"
58 #include <occgeom.hpp>
59 #include <meshing.hpp>
60 //#include <meshtype.hpp>
62 extern int OCCGenerateMesh (OCCGeometry&, Mesh*&, int, int, char*);
63 /*extern*/ MeshingParameters mparam;
67 using namespace netgen;
68 using namespace nglib;
70 //=============================================================================
74 //=============================================================================
76 NETGENPlugin_NETGEN_2D_ONLY::NETGENPlugin_NETGEN_2D_ONLY(int hypId, int studyId,
78 : SMESH_2D_Algo(hypId, studyId, gen)
80 MESSAGE("NETGENPlugin_NETGEN_2D_ONLY::NETGENPlugin_NETGEN_2D_ONLY");
81 _name = "NETGEN_2D_ONLY";
83 _shapeType = (1 << TopAbs_FACE);// 1 bit /shape type
85 _compatibleHypothesis.push_back("MaxElementArea");
86 _compatibleHypothesis.push_back("LengthFromEdges");
87 _compatibleHypothesis.push_back("QuadranglePreference");
89 _hypMaxElementArea = 0;
90 _hypLengthFromEdges = 0;
91 _hypQuadranglePreference = 0;
94 //=============================================================================
98 //=============================================================================
100 NETGENPlugin_NETGEN_2D_ONLY::~NETGENPlugin_NETGEN_2D_ONLY()
102 MESSAGE("NETGENPlugin_NETGEN_2D_ONLY::~NETGENPlugin_NETGEN_2D_ONLY");
105 //=============================================================================
109 //=============================================================================
111 bool NETGENPlugin_NETGEN_2D_ONLY::CheckHypothesis (SMESH_Mesh& aMesh,
112 const TopoDS_Shape& aShape,
113 Hypothesis_Status& aStatus)
115 _hypMaxElementArea = 0;
116 _hypLengthFromEdges = 0;
117 _hypQuadranglePreference = 0;
119 const list<const SMESHDS_Hypothesis*>& hyps = GetUsedHypothesis(aMesh, aShape, false);
123 aStatus = HYP_OK; //SMESH_Hypothesis::HYP_MISSING;
124 return true; // (PAL13464) can work with no hypothesis, LengthFromEdges is default one
127 aStatus = HYP_MISSING;
129 list<const SMESHDS_Hypothesis*>::const_iterator ith;
130 for (ith = hyps.begin(); ith != hyps.end(); ++ith )
132 const SMESHDS_Hypothesis* hyp = (*ith);
134 string hypName = hyp->GetName();
136 if ( hypName == "MaxElementArea")
137 _hypMaxElementArea = static_cast<const StdMeshers_MaxElementArea*> (hyp);
138 else if ( hypName == "LengthFromEdges" )
139 _hypLengthFromEdges = static_cast<const StdMeshers_LengthFromEdges*> (hyp);
140 else if ( hypName == "QuadranglePreference" )
141 _hypQuadranglePreference = static_cast<const StdMeshers_QuadranglePreference*>(hyp);
143 aStatus = HYP_INCOMPATIBLE;
148 if ( _hypMaxElementArea && _hypLengthFromEdges ) {
149 aStatus = HYP_CONCURENT;
153 if ( _hypMaxElementArea || _hypLengthFromEdges )
156 return aStatus == HYP_OK;
159 //================================================================================
161 * \brief Fill netgen mesh with segments
162 * \retval SMESH_ComputeErrorPtr - error description
164 //================================================================================
166 static TError AddSegmentsToMesh(netgen::Mesh& ngMesh,
168 const TSideVector& wires,
169 SMESH_MesherHelper& helper,
170 vector< const SMDS_MeshNode* > & nodeVec)
172 // ----------------------------
173 // Check wires and count nodes
174 // ----------------------------
176 for ( int iW = 0; iW < wires.size(); ++iW )
178 StdMeshers_FaceSidePtr wire = wires[ iW ];
179 if ( wire->MissVertexNode() )
181 (new SMESH_ComputeError(COMPERR_BAD_INPUT_MESH, "Missing nodes on vertices"));
183 const vector<UVPtStruct>& uvPtVec = wire->GetUVPtStruct();
184 if ( uvPtVec.size() != wire->NbPoints() )
186 (new SMESH_ComputeError(COMPERR_BAD_INPUT_MESH,
187 SMESH_Comment("Unexpected nb of points on wire ") << iW
188 << ": " << uvPtVec.size()<<" != "<<wire->NbPoints()));
189 nbNodes += wire->NbSegments();
191 nodeVec.reserve( nbNodes );
197 // netgen::Box<3> bb = geom.GetBoundingBox();
198 // bb.Increase (bb.Diam()/10);
199 // ngMesh.SetLocalH (bb.PMin(), bb.PMax(), 0.5); // set grading
201 const int faceID = 1, solidID = 0;
202 ngMesh.AddFaceDescriptor (FaceDescriptor(faceID, solidID, solidID, 0));
204 for ( int iW = 0; iW < wires.size(); ++iW )
206 StdMeshers_FaceSidePtr wire = wires[ iW ];
207 const vector<UVPtStruct>& uvPtVec = wire->GetUVPtStruct();
209 bool reverse = // 20526: [CEA] Disk meshing fails
210 ( wire->NbEdges() == 1 &&
211 geom.emap(geom.emap.FindIndex(wire->Edge(0))).Orientation() == TopAbs_REVERSED );
213 int firstPointID = ngMesh.GetNP() + 1;
214 int edgeID = 1, posID = -2;
215 for ( int i = 0; i < wire->NbSegments(); ++i ) // loop on segments
217 // Add the first point of a segment
218 const SMDS_MeshNode * n = uvPtVec[ i ].node;
219 const int posShapeID = n->GetPosition()->GetShapeId();
221 // skip nodes on degenerated edges
222 if ( helper.IsDegenShape( posShapeID ) &&
223 helper.IsDegenShape( uvPtVec[ i+1 ].node->GetPosition()->GetShapeId() ))
226 nodeVec.push_back( n );
228 MeshPoint mp( Point<3> (n->X(), n->Y(), n->Z()) );
229 ngMesh.AddPoint ( mp, 1, EDGEPOINT );
234 seg.p1 = ngMesh.GetNP(); // ng node id
235 seg.p2 = seg.p1 + 1; // ng node id
236 seg.edgenr = ngMesh.GetNSeg() + 1;// segment id
237 seg.si = faceID; // = geom.fmap.FindIndex (face);
239 for ( int iEnd = 0; iEnd < 2; ++iEnd)
241 const UVPtStruct& pnt = uvPtVec[ i + iEnd ];
243 seg.epgeominfo[ iEnd ].dist = pnt.param; // param on curve
244 seg.epgeominfo[ iEnd ].u = pnt.u;
245 seg.epgeominfo[ iEnd ].v = pnt.v;
247 // find out edge id and node parameter on edge
248 bool onVertex = ( pnt.node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX );
249 if ( onVertex || posShapeID != posID )
252 double normParam = pnt.normParam;
254 normParam = 0.5 * ( uvPtVec[ i ].normParam + uvPtVec[ i+1 ].normParam );
255 const TopoDS_Edge& edge = wire->Edge( wire->EdgeIndex( normParam ));
256 edgeID = geom.emap.FindIndex( edge );
258 if ( onVertex ) // param on curve is different on each of two edges
259 seg.epgeominfo[ iEnd ].dist = helper.GetNodeU( edge, pnt.node );
261 seg.epgeominfo[ iEnd ].edgenr = edgeID; // = geom.emap.FindIndex(edge);
263 // 20526: [CEA] Disk meshing fails
266 swap (seg.p1, seg.p2);
267 swap (seg.epgeominfo[0].dist, seg.epgeominfo[1].dist);
268 swap (seg.epgeominfo[0].u, seg.epgeominfo[1].u);
269 swap (seg.epgeominfo[0].v, seg.epgeominfo[1].v);
272 ngMesh.AddSegment (seg);
274 // cout << "Segment: " << seg.edgenr << endl
275 // << "\tp1: " << seg.p1 << endl
276 // << "\tp2: " << seg.p2 << endl
277 // << "\tp0 param: " << seg.epgeominfo[ 0 ].dist << endl
278 // << "\tp0 uv: " << seg.epgeominfo[ 0 ].u <<", "<< seg.epgeominfo[ 0 ].v << endl
279 // << "\tp0 edge: " << seg.epgeominfo[ 0 ].edgenr << endl
280 // << "\tp1 param: " << seg.epgeominfo[ 1 ].dist << endl
281 // << "\tp1 uv: " << seg.epgeominfo[ 1 ].u <<", "<< seg.epgeominfo[ 1 ].v << endl
282 // << "\tp1 edge: " << seg.epgeominfo[ 1 ].edgenr << endl;
284 Segment& seg = ngMesh.LineSegment( ngMesh.GetNSeg() );
285 seg.p2 = firstPointID;
288 ngMesh.CalcSurfacesOfNode();
293 //=============================================================================
295 *Here we are going to use the NETGEN mesher
297 //=============================================================================
299 bool NETGENPlugin_NETGEN_2D_ONLY::Compute(SMESH_Mesh& aMesh,
300 const TopoDS_Shape& aShape)
302 MESSAGE("NETGENPlugin_NETGEN_2D_ONLY::Compute()");
304 SMESHDS_Mesh* meshDS = aMesh.GetMeshDS();
305 int faceID = meshDS->ShapeToIndex( aShape );
307 SMESH_MesherHelper helper(aMesh);
308 _quadraticMesh = helper.IsQuadraticSubMesh(aShape);
309 helper.SetElementsOnShape( true );
310 const bool ignoreMediumNodes = _quadraticMesh;
312 // ------------------------
313 // get all edges of a face
314 // ------------------------
315 const TopoDS_Face F = TopoDS::Face( aShape.Oriented( TopAbs_FORWARD ));
317 TSideVector wires = StdMeshers_FaceSide::GetFaceWires( F, aMesh, ignoreMediumNodes, problem );
318 if ( problem && !problem->IsOK() )
319 return error( problem );
320 int nbWires = wires.size();
322 return error( "Problem in StdMeshers_FaceSide::GetFaceWires()");
323 if ( wires[0]->NbSegments() < 3 ) // ex: a circle with 2 segments
324 return error(COMPERR_BAD_INPUT_MESH,
325 SMESH_Comment("Too few segments: ")<<wires[0]->NbSegments());
327 // -------------------------
328 // Make input netgen mesh
329 // -------------------------
332 netgen::Mesh * ngMesh = new netgen::Mesh ();
334 netgen::OCCGeometry occgeo;
335 NETGENPlugin_Mesher::PrepareOCCgeometry( occgeo, F, aMesh );
336 occgeo.fmap.Clear(); // face can be reversed, which is wrong in this case (issue 19978)
337 occgeo.fmap.Add( F );
339 vector< const SMDS_MeshNode* > nodeVec;
340 problem = AddSegmentsToMesh( *ngMesh, occgeo, wires, helper, nodeVec );
341 if ( problem && !problem->IsOK() ) {
342 delete ngMesh; Ng_Exit();
343 return error( problem );
346 // --------------------
347 // compute edge length
348 // --------------------
350 double edgeLength = 0;
351 if (_hypLengthFromEdges || !_hypLengthFromEdges && !_hypMaxElementArea)
354 for ( int iW = 0; iW < nbWires; ++iW )
356 edgeLength += wires[ iW ]->Length();
357 nbSegments += wires[ iW ]->NbSegments();
360 edgeLength /= nbSegments;
362 if ( _hypMaxElementArea )
364 double maxArea = _hypMaxElementArea->GetMaxArea();
365 edgeLength = sqrt(2. * maxArea/sqrt(3.0));
367 if ( edgeLength < DBL_MIN )
368 edgeLength = occgeo.GetBoundingBox().Diam();
370 //cout << " edgeLength = " << edgeLength << endl;
372 netgen::mparam.maxh = edgeLength;
373 netgen::mparam.quad = _hypQuadranglePreference ? 1 : 0;
374 //ngMesh->SetGlobalH ( edgeLength );
376 // -------------------------
377 // Generate surface mesh
378 // -------------------------
381 int startWith = MESHCONST_MESHSURFACE;
382 int endWith = MESHCONST_OPTSURFACE;
386 #if (OCC_VERSION_MAJOR << 16 | OCC_VERSION_MINOR << 8 | OCC_VERSION_MAINTENANCE) > 0x060100
389 err = netgen::OCCGenerateMesh(occgeo, ngMesh, startWith, endWith, optstr);
391 catch (Standard_Failure& ex) {
392 string comment = ex.DynamicType()->Name();
393 if ( ex.GetMessageString() && strlen( ex.GetMessageString() )) {
395 comment += ex.GetMessageString();
397 error(COMPERR_OCC_EXCEPTION, comment);
399 catch (NgException exc) {
400 error( SMESH_Comment("NgException: ") << exc.What() );
403 error(COMPERR_EXCEPTION,"Exception in netgen::OCCGenerateMesh()");
406 // ----------------------------------------------------
407 // Fill the SMESHDS with the generated nodes and faces
408 // ----------------------------------------------------
410 int nbNodes = ngMesh->GetNP();
411 int nbFaces = ngMesh->GetNSE();
413 int nbInputNodes = nodeVec.size();
414 nodeVec.resize( nbNodes, 0 );
417 for ( int i = nbInputNodes + 1; i <= nbNodes; ++i )
419 const MeshPoint& ngPoint = ngMesh->Point(i);
420 SMDS_MeshNode * node = meshDS->AddNode(ngPoint.X(), ngPoint.Y(), ngPoint.Z());
421 nodeVec[ i-1 ] = node;
425 bool reverse = ( aShape.Orientation() == TopAbs_REVERSED );
426 for ( int i = 1; i <= nbFaces ; ++i )
428 const Element2d& elem = ngMesh->SurfaceElement(i);
429 vector<const SMDS_MeshNode*> nodes( elem.GetNP() );
430 for (int j=1; j <= elem.GetNP(); ++j)
432 int pind = elem.PNum(j);
433 const SMDS_MeshNode* node = nodeVec.at(pind-1);
435 nodes[ nodes.size()-j ] = node;
438 if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_3DSPACE )
440 const PointGeomInfo& pgi = elem.GeomInfoPi(j);
441 meshDS->SetNodeOnFace((SMDS_MeshNode*)node, faceID, pgi.u, pgi.v);
444 SMDS_MeshFace* face = 0;
445 if ( elem.GetType() == TRIG )
446 face = helper.AddFace(nodes[0],nodes[1],nodes[2]);
448 face = helper.AddFace(nodes[0],nodes[1],nodes[2],nodes[3]);
451 Ng_DeleteMesh((nglib::Ng_Mesh*)ngMesh);
454 NETGENPlugin_Mesher::RemoveTmpFiles();
460 //=============================================================================
464 //=============================================================================
466 bool NETGENPlugin_NETGEN_2D_ONLY::Evaluate(SMESH_Mesh& aMesh,
467 const TopoDS_Shape& aShape,
468 MapShapeNbElems& aResMap)
470 TopoDS_Face F = TopoDS::Face(aShape);
474 // collect info from edges
475 int nb0d = 0, nb1d = 0;
476 bool IsQuadratic = false;
478 double fullLen = 0.0;
479 TopTools_MapOfShape tmpMap;
480 for (TopExp_Explorer exp(F, TopAbs_EDGE); exp.More(); exp.Next()) {
481 TopoDS_Edge E = TopoDS::Edge(exp.Current());
482 if( tmpMap.Contains(E) )
485 SMESH_subMesh *aSubMesh = aMesh.GetSubMesh(exp.Current());
486 MapShapeNbElemsItr anIt = aResMap.find(aSubMesh);
487 if( anIt==aResMap.end() ) {
488 SMESH_subMesh *sm = aMesh.GetSubMesh(F);
489 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
490 smError.reset( new SMESH_ComputeError(COMPERR_ALGO_FAILED,"Submesh can not be evaluated",this));
493 std::vector<int> aVec = (*anIt).second;
494 nb0d += aVec[SMDSEntity_Node];
495 nb1d += Max(aVec[SMDSEntity_Edge],aVec[SMDSEntity_Quad_Edge]);
496 double aLen = SMESH_Algo::EdgeLength(E);
499 IsQuadratic = (aVec[SMDSEntity_Quad_Edge] > aVec[SMDSEntity_Edge]);
505 // compute edge length
507 if (_hypLengthFromEdges || !_hypLengthFromEdges && !_hypMaxElementArea) {
509 ELen = fullLen / nb1d;
511 if ( _hypMaxElementArea ) {
512 double maxArea = _hypMaxElementArea->GetMaxArea();
513 ELen = sqrt(2. * maxArea/sqrt(3.0));
515 if ( ELen < Precision::Confusion() ) {
516 SMESH_subMesh *sm = aMesh.GetSubMesh(F);
518 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
519 smError.reset( new SMESH_ComputeError(COMPERR_ALGO_FAILED,"Submesh can not be evaluated.\nToo small element length",this));
525 BRepGProp::SurfaceProperties(F,G);
526 double anArea = G.Mass();
528 if ( ELen > Precision::Confusion() )
529 nbFaces = (int) ( anArea / ( ELen*ELen*sqrt(3.) / 4 ) );
530 int nbNodes = (int) ( ( nbFaces*3 - (nb1d-1)*2 ) / 6 + 1 );
531 std::vector<int> aVec(SMDSEntity_Last);
532 for(int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aVec[i]=0;
534 aVec[SMDSEntity_Node] = nbNodes;
535 aVec[SMDSEntity_Quad_Triangle] = nbFaces;
538 aVec[SMDSEntity_Node] = nbNodes;
539 aVec[SMDSEntity_Triangle] = nbFaces;
541 SMESH_subMesh *sm = aMesh.GetSubMesh(F);
542 aResMap.insert(std::make_pair(sm,aVec));