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 int firstPointID = ngMesh.GetNP() + 1;
210 int edgeID = 1, posID = -2;
211 for ( int i = 0; i < wire->NbSegments(); ++i ) // loop on segments
213 // Add the first point of a segment
214 const SMDS_MeshNode * n = uvPtVec[ i ].node;
215 const int posShapeID = n->GetPosition()->GetShapeId();
217 // skip nodes on degenerated edges
218 if ( helper.IsDegenShape( posShapeID ) &&
219 helper.IsDegenShape( uvPtVec[ i+1 ].node->GetPosition()->GetShapeId() ))
222 nodeVec.push_back( n );
224 MeshPoint mp( Point<3> (n->X(), n->Y(), n->Z()) );
225 ngMesh.AddPoint ( mp, 1, EDGEPOINT );
230 seg.p1 = ngMesh.GetNP(); // ng node id
231 seg.p2 = seg.p1 + 1; // ng node id
232 seg.edgenr = ngMesh.GetNSeg() + 1;// segment id
233 seg.si = faceID; // = geom.fmap.FindIndex (face);
235 for ( int iEnd = 0; iEnd < 2; ++iEnd)
237 const UVPtStruct& pnt = uvPtVec[ i + iEnd ];
239 seg.epgeominfo[ iEnd ].dist = pnt.param; // param on curve
240 seg.epgeominfo[ iEnd ].u = pnt.u;
241 seg.epgeominfo[ iEnd ].v = pnt.v;
243 // find out edge id and node parameter on edge
244 bool onVertex = ( pnt.node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX );
245 if ( onVertex || posShapeID != posID )
248 double normParam = pnt.normParam;
250 normParam = 0.5 * ( uvPtVec[ i ].normParam + uvPtVec[ i+1 ].normParam );
251 const TopoDS_Edge& edge = wire->Edge( wire->EdgeIndex( normParam ));
252 edgeID = geom.emap.FindIndex( edge );
254 if ( onVertex ) // param on curve is different on each of two edges
255 seg.epgeominfo[ iEnd ].dist = helper.GetNodeU( edge, pnt.node );
257 seg.epgeominfo[ iEnd ].edgenr = edgeID; // = geom.emap.FindIndex(edge);
260 ngMesh.AddSegment (seg);
262 // cout << "Segment: " << seg.edgenr << endl
263 // << "\tp1: " << seg.p1 << endl
264 // << "\tp2: " << seg.p2 << endl
265 // << "\tp0 param: " << seg.epgeominfo[ 0 ].dist << endl
266 // << "\tp0 uv: " << seg.epgeominfo[ 0 ].u <<", "<< seg.epgeominfo[ 0 ].v << endl
267 // << "\tp0 edge: " << seg.epgeominfo[ 0 ].edgenr << endl
268 // << "\tp1 param: " << seg.epgeominfo[ 1 ].dist << endl
269 // << "\tp1 uv: " << seg.epgeominfo[ 1 ].u <<", "<< seg.epgeominfo[ 1 ].v << endl
270 // << "\tp1 edge: " << seg.epgeominfo[ 1 ].edgenr << endl;
272 Segment& seg = ngMesh.LineSegment( ngMesh.GetNSeg() );
273 seg.p2 = firstPointID;
276 ngMesh.CalcSurfacesOfNode();
281 //=============================================================================
283 *Here we are going to use the NETGEN mesher
285 //=============================================================================
287 bool NETGENPlugin_NETGEN_2D_ONLY::Compute(SMESH_Mesh& aMesh,
288 const TopoDS_Shape& aShape)
290 MESSAGE("NETGENPlugin_NETGEN_2D_ONLY::Compute()");
292 SMESHDS_Mesh* meshDS = aMesh.GetMeshDS();
293 int faceID = meshDS->ShapeToIndex( aShape );
295 SMESH_MesherHelper helper(aMesh);
296 _quadraticMesh = helper.IsQuadraticSubMesh(aShape);
297 helper.SetElementsOnShape( true );
298 const bool ignoreMediumNodes = _quadraticMesh;
300 // ------------------------
301 // get all edges of a face
302 // ------------------------
303 const TopoDS_Face F = TopoDS::Face( aShape.Oriented( TopAbs_FORWARD ));
305 TSideVector wires = StdMeshers_FaceSide::GetFaceWires( F, aMesh, ignoreMediumNodes, problem );
306 if ( problem && !problem->IsOK() )
307 return error( problem );
308 int nbWires = wires.size();
310 return error( "Problem in StdMeshers_FaceSide::GetFaceWires()");
311 if ( wires[0]->NbSegments() < 3 ) // ex: a circle with 2 segments
312 return error(COMPERR_BAD_INPUT_MESH,
313 SMESH_Comment("Too few segments: ")<<wires[0]->NbSegments());
315 // -------------------------
316 // Make input netgen mesh
317 // -------------------------
320 netgen::Mesh * ngMesh = new netgen::Mesh ();
322 netgen::OCCGeometry occgeo;
323 NETGENPlugin_Mesher::PrepareOCCgeometry( occgeo, F, aMesh );
324 occgeo.fmap.Clear(); // face can be reversed, which is wrong in this case (issue 19978)
325 occgeo.fmap.Add( F );
327 vector< const SMDS_MeshNode* > nodeVec;
328 problem = AddSegmentsToMesh( *ngMesh, occgeo, wires, helper, nodeVec );
329 if ( problem && !problem->IsOK() ) {
330 delete ngMesh; Ng_Exit();
331 return error( problem );
334 // --------------------
335 // compute edge length
336 // --------------------
338 double edgeLength = 0;
339 if (_hypLengthFromEdges || !_hypLengthFromEdges && !_hypMaxElementArea)
342 for ( int iW = 0; iW < nbWires; ++iW )
344 edgeLength += wires[ iW ]->Length();
345 nbSegments += wires[ iW ]->NbSegments();
348 edgeLength /= nbSegments;
350 if ( _hypMaxElementArea )
352 double maxArea = _hypMaxElementArea->GetMaxArea();
353 edgeLength = sqrt(2. * maxArea/sqrt(3.0));
355 if ( edgeLength < DBL_MIN )
356 edgeLength = occgeo.GetBoundingBox().Diam();
358 //cout << " edgeLength = " << edgeLength << endl;
360 netgen::mparam.maxh = edgeLength;
361 netgen::mparam.quad = _hypQuadranglePreference ? 1 : 0;
362 //ngMesh->SetGlobalH ( edgeLength );
364 // -------------------------
365 // Generate surface mesh
366 // -------------------------
369 int startWith = MESHCONST_MESHSURFACE;
370 int endWith = MESHCONST_OPTSURFACE;
374 #if (OCC_VERSION_MAJOR << 16 | OCC_VERSION_MINOR << 8 | OCC_VERSION_MAINTENANCE) > 0x060100
377 err = netgen::OCCGenerateMesh(occgeo, ngMesh, startWith, endWith, optstr);
379 catch (Standard_Failure& ex) {
380 string comment = ex.DynamicType()->Name();
381 if ( ex.GetMessageString() && strlen( ex.GetMessageString() )) {
383 comment += ex.GetMessageString();
385 error(COMPERR_OCC_EXCEPTION, comment);
387 catch (NgException exc) {
388 error( SMESH_Comment("NgException: ") << exc.What() );
391 error(COMPERR_EXCEPTION,"Exception in netgen::OCCGenerateMesh()");
394 // ----------------------------------------------------
395 // Fill the SMESHDS with the generated nodes and faces
396 // ----------------------------------------------------
398 int nbNodes = ngMesh->GetNP();
399 int nbFaces = ngMesh->GetNSE();
401 int nbInputNodes = nodeVec.size();
402 nodeVec.resize( nbNodes, 0 );
405 for ( int i = nbInputNodes + 1; i <= nbNodes; ++i )
407 const MeshPoint& ngPoint = ngMesh->Point(i);
408 SMDS_MeshNode * node = meshDS->AddNode(ngPoint.X(), ngPoint.Y(), ngPoint.Z());
409 nodeVec[ i-1 ] = node;
413 bool reverse = ( aShape.Orientation() == TopAbs_REVERSED );
414 for ( int i = 1; i <= nbFaces ; ++i )
416 const Element2d& elem = ngMesh->SurfaceElement(i);
417 vector<const SMDS_MeshNode*> nodes( elem.GetNP() );
418 for (int j=1; j <= elem.GetNP(); ++j)
420 int pind = elem.PNum(j);
421 const SMDS_MeshNode* node = nodeVec.at(pind-1);
423 nodes[ nodes.size()-j ] = node;
426 if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_3DSPACE )
428 const PointGeomInfo& pgi = elem.GeomInfoPi(j);
429 meshDS->SetNodeOnFace((SMDS_MeshNode*)node, faceID, pgi.u, pgi.v);
432 SMDS_MeshFace* face = 0;
433 if ( elem.GetType() == TRIG )
434 face = helper.AddFace(nodes[0],nodes[1],nodes[2]);
436 face = helper.AddFace(nodes[0],nodes[1],nodes[2],nodes[3]);
439 Ng_DeleteMesh((nglib::Ng_Mesh*)ngMesh);
442 NETGENPlugin_Mesher::RemoveTmpFiles();
448 //=============================================================================
452 //=============================================================================
454 bool NETGENPlugin_NETGEN_2D_ONLY::Evaluate(SMESH_Mesh& aMesh,
455 const TopoDS_Shape& aShape,
456 MapShapeNbElems& aResMap)
458 TopoDS_Face F = TopoDS::Face(aShape);
462 // collect info from edges
463 int nb0d = 0, nb1d = 0;
464 bool IsQuadratic = false;
466 double fullLen = 0.0;
467 TopTools_MapOfShape tmpMap;
468 for (TopExp_Explorer exp(F, TopAbs_EDGE); exp.More(); exp.Next()) {
469 TopoDS_Edge E = TopoDS::Edge(exp.Current());
470 if( tmpMap.Contains(E) )
473 SMESH_subMesh *aSubMesh = aMesh.GetSubMesh(exp.Current());
474 MapShapeNbElemsItr anIt = aResMap.find(aSubMesh);
475 if( anIt==aResMap.end() ) {
476 SMESH_subMesh *sm = aMesh.GetSubMesh(F);
477 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
478 smError.reset( new SMESH_ComputeError(COMPERR_ALGO_FAILED,"Submesh can not be evaluated",this));
481 std::vector<int> aVec = (*anIt).second;
482 nb0d += aVec[SMDSEntity_Node];
483 nb1d += Max(aVec[SMDSEntity_Edge],aVec[SMDSEntity_Quad_Edge]);
484 double aLen = SMESH_Algo::EdgeLength(E);
487 IsQuadratic = (aVec[SMDSEntity_Quad_Edge] > aVec[SMDSEntity_Edge]);
493 // compute edge length
495 if (_hypLengthFromEdges || !_hypLengthFromEdges && !_hypMaxElementArea) {
497 ELen = fullLen / nb1d;
499 if ( _hypMaxElementArea ) {
500 double maxArea = _hypMaxElementArea->GetMaxArea();
501 ELen = sqrt(2. * maxArea/sqrt(3.0));
503 if ( ELen < Precision::Confusion() ) {
504 SMESH_subMesh *sm = aMesh.GetSubMesh(F);
506 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
507 smError.reset( new SMESH_ComputeError(COMPERR_ALGO_FAILED,"Submesh can not be evaluated.\nToo small element length",this));
513 BRepGProp::SurfaceProperties(F,G);
514 double anArea = G.Mass();
516 if ( ELen > Precision::Confusion() )
517 nbFaces = (int) ( anArea / ( ELen*ELen*sqrt(3.) / 4 ) );
518 int nbNodes = (int) ( ( nbFaces*3 - (nb1d-1)*2 ) / 6 + 1 );
519 std::vector<int> aVec(SMDSEntity_Last);
520 for(int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aVec[i]=0;
522 aVec[SMDSEntity_Node] = nbNodes;
523 aVec[SMDSEntity_Quad_Triangle] = nbFaces;
526 aVec[SMDSEntity_Node] = nbNodes;
527 aVec[SMDSEntity_Triangle] = nbFaces;
529 SMESH_subMesh *sm = aMesh.GetSubMesh(F);
530 aResMap.insert(std::make_pair(sm,aVec));