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"
59 #include <occgeom.hpp>
60 #include <meshing.hpp>
61 //#include <meshtype.hpp>
63 extern int OCCGenerateMesh (OCCGeometry&, Mesh*&, int, int, char*);
64 /*extern*/ MeshingParameters mparam;
68 using namespace netgen;
69 using namespace nglib;
71 //=============================================================================
75 //=============================================================================
77 NETGENPlugin_NETGEN_2D_ONLY::NETGENPlugin_NETGEN_2D_ONLY(int hypId, int studyId,
79 : SMESH_2D_Algo(hypId, studyId, gen)
81 MESSAGE("NETGENPlugin_NETGEN_2D_ONLY::NETGENPlugin_NETGEN_2D_ONLY");
82 _name = "NETGEN_2D_ONLY";
84 _shapeType = (1 << TopAbs_FACE);// 1 bit /shape type
86 _compatibleHypothesis.push_back("MaxElementArea");
87 _compatibleHypothesis.push_back("LengthFromEdges");
88 _compatibleHypothesis.push_back("QuadranglePreference");
90 _hypMaxElementArea = 0;
91 _hypLengthFromEdges = 0;
92 _hypQuadranglePreference = 0;
95 //=============================================================================
99 //=============================================================================
101 NETGENPlugin_NETGEN_2D_ONLY::~NETGENPlugin_NETGEN_2D_ONLY()
103 MESSAGE("NETGENPlugin_NETGEN_2D_ONLY::~NETGENPlugin_NETGEN_2D_ONLY");
106 //=============================================================================
110 //=============================================================================
112 bool NETGENPlugin_NETGEN_2D_ONLY::CheckHypothesis (SMESH_Mesh& aMesh,
113 const TopoDS_Shape& aShape,
114 Hypothesis_Status& aStatus)
116 _hypMaxElementArea = 0;
117 _hypLengthFromEdges = 0;
118 _hypQuadranglePreference = 0;
120 const list<const SMESHDS_Hypothesis*>& hyps = GetUsedHypothesis(aMesh, aShape, false);
124 aStatus = HYP_OK; //SMESH_Hypothesis::HYP_MISSING;
125 return true; // (PAL13464) can work with no hypothesis, LengthFromEdges is default one
128 aStatus = HYP_MISSING;
130 list<const SMESHDS_Hypothesis*>::const_iterator ith;
131 for (ith = hyps.begin(); ith != hyps.end(); ++ith )
133 const SMESHDS_Hypothesis* hyp = (*ith);
135 string hypName = hyp->GetName();
137 if ( hypName == "MaxElementArea")
138 _hypMaxElementArea = static_cast<const StdMeshers_MaxElementArea*> (hyp);
139 else if ( hypName == "LengthFromEdges" )
140 _hypLengthFromEdges = static_cast<const StdMeshers_LengthFromEdges*> (hyp);
141 else if ( hypName == "QuadranglePreference" )
142 _hypQuadranglePreference = static_cast<const StdMeshers_QuadranglePreference*>(hyp);
144 aStatus = HYP_INCOMPATIBLE;
149 if ( _hypMaxElementArea && _hypLengthFromEdges ) {
150 aStatus = HYP_CONCURENT;
154 if ( _hypMaxElementArea || _hypLengthFromEdges || _hypQuadranglePreference)
157 return aStatus == HYP_OK;
160 //================================================================================
162 * \brief Fill netgen mesh with segments
163 * \retval SMESH_ComputeErrorPtr - error description
165 //================================================================================
167 static TError AddSegmentsToMesh(netgen::Mesh& ngMesh,
169 const TSideVector& wires,
170 SMESH_MesherHelper& helper,
171 vector< const SMDS_MeshNode* > & nodeVec)
173 // ----------------------------
174 // Check wires and count nodes
175 // ----------------------------
177 for ( int iW = 0; iW < wires.size(); ++iW )
179 StdMeshers_FaceSidePtr wire = wires[ iW ];
180 if ( wire->MissVertexNode() )
182 (new SMESH_ComputeError(COMPERR_BAD_INPUT_MESH, "Missing nodes on vertices"));
184 const vector<UVPtStruct>& uvPtVec = wire->GetUVPtStruct();
185 if ( uvPtVec.size() != wire->NbPoints() )
187 (new SMESH_ComputeError(COMPERR_BAD_INPUT_MESH,
188 SMESH_Comment("Unexpected nb of points on wire ") << iW
189 << ": " << uvPtVec.size()<<" != "<<wire->NbPoints()));
190 nbNodes += wire->NbSegments();
192 nodeVec.reserve( nbNodes );
198 // netgen::Box<3> bb = geom.GetBoundingBox();
199 // bb.Increase (bb.Diam()/10);
200 // ngMesh.SetLocalH (bb.PMin(), bb.PMax(), 0.5); // set grading
202 const int faceID = 1, solidID = 0;
203 ngMesh.AddFaceDescriptor (FaceDescriptor(faceID, solidID, solidID, 0));
205 for ( int iW = 0; iW < wires.size(); ++iW )
207 StdMeshers_FaceSidePtr wire = wires[ iW ];
208 const vector<UVPtStruct>& uvPtVec = wire->GetUVPtStruct();
210 int firstPointID = ngMesh.GetNP() + 1;
211 int edgeID = 1, posID = -2;
212 bool isInternalEdge = false;
213 for ( int i = 0; i < wire->NbSegments(); ++i ) // loop on segments
215 // Add the first point of a segment
216 const SMDS_MeshNode * n = uvPtVec[ i ].node;
217 const int posShapeID = n->GetPosition()->GetShapeId();
219 // skip nodes on degenerated edges
220 if ( helper.IsDegenShape( posShapeID ) &&
221 helper.IsDegenShape( uvPtVec[ i+1 ].node->GetPosition()->GetShapeId() ))
224 nodeVec.push_back( n );
226 MeshPoint mp( Point<3> (n->X(), n->Y(), n->Z()) );
227 ngMesh.AddPoint ( mp, 1, EDGEPOINT );
233 seg.pnums[0] = ngMesh.GetNP(); // ng node id
234 seg.pnums[1] = seg.pnums[0] + 1; // ng node id
236 seg.p1 = ngMesh.GetNP(); // ng node id
237 seg.p2 = seg.p1 + 1; // ng node id
239 seg.edgenr = ngMesh.GetNSeg() + 1;// segment id
240 seg.si = faceID; // = geom.fmap.FindIndex (face);
242 for ( int iEnd = 0; iEnd < 2; ++iEnd)
244 const UVPtStruct& pnt = uvPtVec[ i + iEnd ];
246 seg.epgeominfo[ iEnd ].dist = pnt.param; // param on curve
247 seg.epgeominfo[ iEnd ].u = pnt.u;
248 seg.epgeominfo[ iEnd ].v = pnt.v;
250 // find out edge id and node parameter on edge
251 bool onVertex = ( pnt.node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX );
252 if ( onVertex || posShapeID != posID )
255 double normParam = pnt.normParam;
257 normParam = 0.5 * ( uvPtVec[ i ].normParam + uvPtVec[ i+1 ].normParam );
258 const TopoDS_Edge& edge = wire->Edge( wire->EdgeIndex( normParam ));
259 edgeID = geom.emap.FindIndex( edge );
261 isInternalEdge = ( edge.Orientation() == TopAbs_INTERNAL );
262 if ( onVertex ) // param on curve is different on each of two edges
263 seg.epgeominfo[ iEnd ].dist = helper.GetNodeU( edge, pnt.node );
265 seg.epgeominfo[ iEnd ].edgenr = edgeID; // = geom.emap.FindIndex(edge);
268 ngMesh.AddSegment (seg);
270 // cout << "Segment: " << seg.edgenr << endl
271 // << "\tp1: " << seg.p1 << endl
272 // << "\tp2: " << seg.p2 << endl
273 // << "\tp0 param: " << seg.epgeominfo[ 0 ].dist << endl
274 // << "\tp0 uv: " << seg.epgeominfo[ 0 ].u <<", "<< seg.epgeominfo[ 0 ].v << endl
275 // << "\tp0 edge: " << seg.epgeominfo[ 0 ].edgenr << endl
276 // << "\tp1 param: " << seg.epgeominfo[ 1 ].dist << endl
277 // << "\tp1 uv: " << seg.epgeominfo[ 1 ].u <<", "<< seg.epgeominfo[ 1 ].v << endl
278 // << "\tp1 edge: " << seg.epgeominfo[ 1 ].edgenr << endl;
280 if ( isInternalEdge )
283 swap (seg.pnums[0], seg.pnums[1]);
285 swap (seg.p1, seg.p2);
287 swap( seg.epgeominfo[0], seg.epgeominfo[1] );
288 seg.edgenr = ngMesh.GetNSeg() + 1; // segment id
289 ngMesh.AddSegment (seg);
291 } // loop on segments on a wire
293 // close chain of segments
294 bool isClosedWire = ( wire->FirstVertex().IsSame( wire->LastVertex() ));
297 Segment& seg = ngMesh.LineSegment( ngMesh.GetNSeg() );
299 seg.pnums[1] = firstPointID;
301 seg.p2 = firstPointID;
304 else // INTERNAL wire (Issue 0020676)
306 const SMDS_MeshNode * n = uvPtVec.back().node;
307 nodeVec.push_back( n );
309 MeshPoint mp( Point<3> (n->X(), n->Y(), n->Z()) );
310 ngMesh.AddPoint ( mp, 1, EDGEPOINT );
313 } // loop on wires of a face
315 ngMesh.CalcSurfacesOfNode();
320 //=============================================================================
322 *Here we are going to use the NETGEN mesher
324 //=============================================================================
326 bool NETGENPlugin_NETGEN_2D_ONLY::Compute(SMESH_Mesh& aMesh,
327 const TopoDS_Shape& aShape)
329 MESSAGE("NETGENPlugin_NETGEN_2D_ONLY::Compute()");
331 SMESHDS_Mesh* meshDS = aMesh.GetMeshDS();
332 int faceID = meshDS->ShapeToIndex( aShape );
334 SMESH_MesherHelper helper(aMesh);
335 _quadraticMesh = helper.IsQuadraticSubMesh(aShape);
336 helper.SetElementsOnShape( true );
337 const bool ignoreMediumNodes = _quadraticMesh;
339 // ------------------------
340 // get all edges of a face
341 // ------------------------
342 const TopoDS_Face F = TopoDS::Face( aShape.Oriented( TopAbs_FORWARD ));
344 TSideVector wires = StdMeshers_FaceSide::GetFaceWires( F, aMesh, ignoreMediumNodes, problem );
345 if ( problem && !problem->IsOK() )
346 return error( problem );
347 int nbWires = wires.size();
349 return error( "Problem in StdMeshers_FaceSide::GetFaceWires()");
350 if ( wires[0]->NbSegments() < 3 ) // ex: a circle with 2 segments
351 return error(COMPERR_BAD_INPUT_MESH,
352 SMESH_Comment("Too few segments: ")<<wires[0]->NbSegments());
354 // -------------------------
355 // Make input netgen mesh
356 // -------------------------
359 netgen::Mesh * ngMesh = new netgen::Mesh ();
361 netgen::OCCGeometry occgeo;
362 NETGENPlugin_Mesher::PrepareOCCgeometry( occgeo, F, aMesh );
363 occgeo.fmap.Clear(); // face can be reversed, which is wrong in this case (issue 19978)
364 occgeo.fmap.Add( F );
366 vector< const SMDS_MeshNode* > nodeVec;
367 problem = AddSegmentsToMesh( *ngMesh, occgeo, wires, helper, nodeVec );
368 if ( problem && !problem->IsOK() ) {
369 delete ngMesh; Ng_Exit();
370 return error( problem );
373 // --------------------
374 // compute edge length
375 // --------------------
377 double edgeLength = 0;
378 if (_hypLengthFromEdges || !_hypLengthFromEdges && !_hypMaxElementArea)
381 for ( int iW = 0; iW < nbWires; ++iW )
383 edgeLength += wires[ iW ]->Length();
384 nbSegments += wires[ iW ]->NbSegments();
387 edgeLength /= nbSegments;
389 if ( _hypMaxElementArea )
391 double maxArea = _hypMaxElementArea->GetMaxArea();
392 edgeLength = sqrt(2. * maxArea/sqrt(3.0));
394 if ( edgeLength < DBL_MIN )
395 edgeLength = occgeo.GetBoundingBox().Diam();
397 //cout << " edgeLength = " << edgeLength << endl;
399 netgen::mparam.maxh = edgeLength;
400 netgen::mparam.quad = _hypQuadranglePreference ? 1 : 0;
401 //ngMesh->SetGlobalH ( edgeLength );
403 // -------------------------
404 // Generate surface mesh
405 // -------------------------
408 int startWith = MESHCONST_MESHSURFACE;
409 int endWith = MESHCONST_OPTSURFACE;
413 #if (OCC_VERSION_MAJOR << 16 | OCC_VERSION_MINOR << 8 | OCC_VERSION_MAINTENANCE) > 0x060100
416 err = netgen::OCCGenerateMesh(occgeo, ngMesh, startWith, endWith, optstr);
418 catch (Standard_Failure& ex) {
419 string comment = ex.DynamicType()->Name();
420 if ( ex.GetMessageString() && strlen( ex.GetMessageString() )) {
422 comment += ex.GetMessageString();
424 error(COMPERR_OCC_EXCEPTION, comment);
426 catch (NgException exc) {
427 error( SMESH_Comment("NgException: ") << exc.What() );
430 error(COMPERR_EXCEPTION,"Exception in netgen::OCCGenerateMesh()");
433 // ----------------------------------------------------
434 // Fill the SMESHDS with the generated nodes and faces
435 // ----------------------------------------------------
437 int nbNodes = ngMesh->GetNP();
438 int nbFaces = ngMesh->GetNSE();
440 int nbInputNodes = nodeVec.size();
441 nodeVec.resize( nbNodes, 0 );
444 for ( int i = nbInputNodes + 1; i <= nbNodes; ++i )
446 const MeshPoint& ngPoint = ngMesh->Point(i);
448 SMDS_MeshNode * node = meshDS->AddNode(ngPoint(0), ngPoint(1), ngPoint(2));
450 SMDS_MeshNode * node = meshDS->AddNode(ngPoint.X(), ngPoint.Y(), ngPoint.Z());
452 nodeVec[ i-1 ] = node;
456 bool reverse = ( aShape.Orientation() == TopAbs_REVERSED );
457 for ( int i = 1; i <= nbFaces ; ++i )
459 const Element2d& elem = ngMesh->SurfaceElement(i);
460 vector<const SMDS_MeshNode*> nodes( elem.GetNP() );
461 for (int j=1; j <= elem.GetNP(); ++j)
463 int pind = elem.PNum(j);
464 const SMDS_MeshNode* node = nodeVec.at(pind-1);
466 nodes[ nodes.size()-j ] = node;
469 if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_3DSPACE )
471 const PointGeomInfo& pgi = elem.GeomInfoPi(j);
472 meshDS->SetNodeOnFace((SMDS_MeshNode*)node, faceID, pgi.u, pgi.v);
475 SMDS_MeshFace* face = 0;
476 if ( elem.GetType() == TRIG )
477 face = helper.AddFace(nodes[0],nodes[1],nodes[2]);
479 face = helper.AddFace(nodes[0],nodes[1],nodes[2],nodes[3]);
482 Ng_DeleteMesh((nglib::Ng_Mesh*)ngMesh);
485 NETGENPlugin_Mesher::RemoveTmpFiles();
491 //=============================================================================
495 //=============================================================================
497 bool NETGENPlugin_NETGEN_2D_ONLY::Evaluate(SMESH_Mesh& aMesh,
498 const TopoDS_Shape& aShape,
499 MapShapeNbElems& aResMap)
501 TopoDS_Face F = TopoDS::Face(aShape);
505 // collect info from edges
506 int nb0d = 0, nb1d = 0;
507 bool IsQuadratic = false;
509 double fullLen = 0.0;
510 TopTools_MapOfShape tmpMap;
511 for (TopExp_Explorer exp(F, TopAbs_EDGE); exp.More(); exp.Next()) {
512 TopoDS_Edge E = TopoDS::Edge(exp.Current());
513 if( tmpMap.Contains(E) )
516 SMESH_subMesh *aSubMesh = aMesh.GetSubMesh(exp.Current());
517 MapShapeNbElemsItr anIt = aResMap.find(aSubMesh);
518 if( anIt==aResMap.end() ) {
519 SMESH_subMesh *sm = aMesh.GetSubMesh(F);
520 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
521 smError.reset( new SMESH_ComputeError(COMPERR_ALGO_FAILED,"Submesh can not be evaluated",this));
524 std::vector<int> aVec = (*anIt).second;
525 nb0d += aVec[SMDSEntity_Node];
526 nb1d += Max(aVec[SMDSEntity_Edge],aVec[SMDSEntity_Quad_Edge]);
527 double aLen = SMESH_Algo::EdgeLength(E);
530 IsQuadratic = (aVec[SMDSEntity_Quad_Edge] > aVec[SMDSEntity_Edge]);
536 // compute edge length
538 if (_hypLengthFromEdges || !_hypLengthFromEdges && !_hypMaxElementArea) {
540 ELen = fullLen / nb1d;
542 if ( _hypMaxElementArea ) {
543 double maxArea = _hypMaxElementArea->GetMaxArea();
544 ELen = sqrt(2. * maxArea/sqrt(3.0));
547 BRepGProp::SurfaceProperties(F,G);
548 double anArea = G.Mass();
550 const int hugeNb = numeric_limits<int>::max()/10;
551 if ( anArea / hugeNb > ELen*ELen )
553 SMESH_subMesh *sm = aMesh.GetSubMesh(F);
554 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
555 smError.reset( new SMESH_ComputeError(COMPERR_ALGO_FAILED,"Submesh can not be evaluated.\nToo small element length",this));
558 int nbFaces = (int) ( anArea / ( ELen*ELen*sqrt(3.) / 4 ) );
559 int nbNodes = (int) ( ( nbFaces*3 - (nb1d-1)*2 ) / 6 + 1 );
560 std::vector<int> aVec(SMDSEntity_Last);
561 for(int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aVec[i]=0;
563 aVec[SMDSEntity_Node] = nbNodes;
564 aVec[SMDSEntity_Quad_Triangle] = nbFaces;
567 aVec[SMDSEntity_Node] = nbNodes;
568 aVec[SMDSEntity_Triangle] = nbFaces;
570 SMESH_subMesh *sm = aMesh.GetSubMesh(F);
571 aResMap.insert(std::make_pair(sm,aVec));