Salome HOME
0020557: EDF 1151 SMESH: Netgen 2D fail to mesh a ring
[plugins/netgenplugin.git] / src / NETGENPlugin / NETGENPlugin_NETGEN_2D_ONLY.cxx
1 //  Copyright (C) 2007-2008  CEA/DEN, EDF R&D, OPEN CASCADE
2 //
3 //  Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 //  CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
5 //
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.
10 //
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.
15 //
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
19 //
20 //  See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 //
22 // File      : NETGENPlugin_NETGEN_2D_ONLY.cxx
23 // Author    : Edward AGAPOV (OCC)
24 // Project   : SALOME
25 //
26 #include "NETGENPlugin_NETGEN_2D_ONLY.hxx"
27
28 #include "NETGENPlugin_Mesher.hxx"
29
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"
41
42 #include <Precision.hxx>
43 #include <Standard_ErrorHandler.hxx>
44 #include <Standard_Failure.hxx>
45
46 #include "utilities.h"
47
48 #include <list>
49 #include <vector>
50
51 /*
52   Netgen include files
53 */
54 namespace nglib {
55 #include <nglib.h>
56 }
57 #define OCCGEOMETRY
58 #include <occgeom.hpp>
59 #include <meshing.hpp>
60 //#include <meshtype.hpp>
61 namespace netgen {
62   extern int OCCGenerateMesh (OCCGeometry&, Mesh*&, int, int, char*);
63   /*extern*/ MeshingParameters mparam;
64 }
65
66 using namespace std;
67 using namespace netgen;
68 using namespace nglib;
69
70 //=============================================================================
71 /*!
72  *  
73  */
74 //=============================================================================
75
76 NETGENPlugin_NETGEN_2D_ONLY::NETGENPlugin_NETGEN_2D_ONLY(int hypId, int studyId,
77                                                          SMESH_Gen* gen)
78   : SMESH_2D_Algo(hypId, studyId, gen)
79 {
80   MESSAGE("NETGENPlugin_NETGEN_2D_ONLY::NETGENPlugin_NETGEN_2D_ONLY");
81   _name = "NETGEN_2D_ONLY";
82   
83   _shapeType = (1 << TopAbs_FACE);// 1 bit /shape type
84
85   _compatibleHypothesis.push_back("MaxElementArea");
86   _compatibleHypothesis.push_back("LengthFromEdges");
87   _compatibleHypothesis.push_back("QuadranglePreference");
88
89   _hypMaxElementArea = 0;
90   _hypLengthFromEdges = 0;
91   _hypQuadranglePreference = 0;
92 }
93
94 //=============================================================================
95 /*!
96  *  
97  */
98 //=============================================================================
99
100 NETGENPlugin_NETGEN_2D_ONLY::~NETGENPlugin_NETGEN_2D_ONLY()
101 {
102   MESSAGE("NETGENPlugin_NETGEN_2D_ONLY::~NETGENPlugin_NETGEN_2D_ONLY");
103 }
104
105 //=============================================================================
106 /*!
107  *  
108  */
109 //=============================================================================
110
111 bool NETGENPlugin_NETGEN_2D_ONLY::CheckHypothesis (SMESH_Mesh&         aMesh,
112                                                    const TopoDS_Shape& aShape,
113                                                    Hypothesis_Status&  aStatus)
114 {
115   _hypMaxElementArea = 0;
116   _hypLengthFromEdges = 0;
117   _hypQuadranglePreference = 0;
118
119   const list<const SMESHDS_Hypothesis*>& hyps = GetUsedHypothesis(aMesh, aShape, false);
120
121   if (hyps.empty())
122   {
123     aStatus = HYP_OK; //SMESH_Hypothesis::HYP_MISSING;
124     return true;  // (PAL13464) can work with no hypothesis, LengthFromEdges is default one
125   }
126
127   aStatus = HYP_MISSING;
128
129   list<const SMESHDS_Hypothesis*>::const_iterator ith;
130   for (ith = hyps.begin(); ith != hyps.end(); ++ith )
131   {
132     const SMESHDS_Hypothesis* hyp = (*ith);
133
134     string hypName = hyp->GetName();
135
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);
142     else {
143       aStatus = HYP_INCOMPATIBLE;
144       return false;
145     }
146   }
147
148   if ( _hypMaxElementArea && _hypLengthFromEdges ) {
149     aStatus = HYP_CONCURENT;
150     return false;
151   }
152
153   if ( _hypMaxElementArea || _hypLengthFromEdges )
154     aStatus = HYP_OK;
155
156   return aStatus == HYP_OK;
157 }
158
159 //================================================================================
160 /*!
161  * \brief Fill netgen mesh with segments
162   * \retval SMESH_ComputeErrorPtr - error description
163  */
164 //================================================================================
165
166 static TError AddSegmentsToMesh(netgen::Mesh&                    ngMesh,
167                                 OCCGeometry&                     geom,
168                                 const TSideVector&               wires,
169                                 SMESH_MesherHelper&              helper,
170                                 vector< const SMDS_MeshNode* > & nodeVec)
171 {
172   // ----------------------------
173   // Check wires and count nodes
174   // ----------------------------
175   int nbNodes = 0;
176   for ( int iW = 0; iW < wires.size(); ++iW )
177   {
178     StdMeshers_FaceSidePtr wire = wires[ iW ];
179     if ( wire->MissVertexNode() )
180       return TError
181         (new SMESH_ComputeError(COMPERR_BAD_INPUT_MESH, "Missing nodes on vertices"));
182       
183     const vector<UVPtStruct>& uvPtVec = wire->GetUVPtStruct();
184     if ( uvPtVec.size() != wire->NbPoints() )
185       return TError
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();
190   }
191   nodeVec.reserve( nbNodes );
192
193   // -----------------
194   // Fill netgen mesh
195   // -----------------
196
197 //   netgen::Box<3> bb = geom.GetBoundingBox();
198 //   bb.Increase (bb.Diam()/10);
199 //   ngMesh.SetLocalH (bb.PMin(), bb.PMax(), 0.5); // set grading
200
201   const int faceID = 1, solidID = 0;
202   ngMesh.AddFaceDescriptor (FaceDescriptor(faceID, solidID, solidID, 0));
203
204   for ( int iW = 0; iW < wires.size(); ++iW )
205   {
206     StdMeshers_FaceSidePtr wire = wires[ iW ];
207     const vector<UVPtStruct>& uvPtVec = wire->GetUVPtStruct();
208
209     int firstPointID = ngMesh.GetNP() + 1;
210     int edgeID = 1, posID = -2;
211     for ( int i = 0; i < wire->NbSegments(); ++i ) // loop on segments
212     {
213       // Add the first point of a segment
214       const SMDS_MeshNode * n = uvPtVec[ i ].node;
215       const int posShapeID = n->GetPosition()->GetShapeId();
216
217       // skip nodes on degenerated edges
218       if ( helper.IsDegenShape( posShapeID ) &&
219            helper.IsDegenShape( uvPtVec[ i+1 ].node->GetPosition()->GetShapeId() ))
220         continue;
221
222       nodeVec.push_back( n );
223
224       MeshPoint mp( Point<3> (n->X(), n->Y(), n->Z()) );
225       ngMesh.AddPoint ( mp, 1, EDGEPOINT );
226
227       // Add the segment
228       Segment seg;
229
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);
234
235       for ( int iEnd = 0; iEnd < 2; ++iEnd)
236       {
237         const UVPtStruct& pnt = uvPtVec[ i + iEnd ];
238
239         seg.epgeominfo[ iEnd ].dist = pnt.param; // param on curve
240         seg.epgeominfo[ iEnd ].u    = pnt.u;
241         seg.epgeominfo[ iEnd ].v    = pnt.v;
242
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 )
246         {
247           // get edge id
248           double normParam = pnt.normParam;
249           if ( onVertex )
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 );
253           posID  = posShapeID;
254           if ( onVertex ) // param on curve is different on each of two edges
255             seg.epgeominfo[ iEnd ].dist = helper.GetNodeU( edge, pnt.node );
256         }
257         seg.epgeominfo[ iEnd ].edgenr = edgeID; //  = geom.emap.FindIndex(edge);
258       }
259
260       ngMesh.AddSegment (seg);
261
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;
271     }
272     Segment& seg = ngMesh.LineSegment( ngMesh.GetNSeg() );
273     seg.p2 = firstPointID;
274   }
275
276   ngMesh.CalcSurfacesOfNode();  
277
278   return TError();
279 }
280
281 //=============================================================================
282 /*!
283  *Here we are going to use the NETGEN mesher
284  */
285 //=============================================================================
286
287 bool NETGENPlugin_NETGEN_2D_ONLY::Compute(SMESH_Mesh&         aMesh,
288                                           const TopoDS_Shape& aShape)
289 {
290   MESSAGE("NETGENPlugin_NETGEN_2D_ONLY::Compute()");
291
292   SMESHDS_Mesh* meshDS = aMesh.GetMeshDS();
293   int faceID = meshDS->ShapeToIndex( aShape );
294
295   SMESH_MesherHelper helper(aMesh);
296   _quadraticMesh = helper.IsQuadraticSubMesh(aShape);
297   helper.SetElementsOnShape( true );
298   const bool ignoreMediumNodes = _quadraticMesh;
299   
300   // ------------------------
301   // get all edges of a face
302   // ------------------------
303   const TopoDS_Face F = TopoDS::Face( aShape.Oriented( TopAbs_FORWARD ));
304   TError problem;
305   TSideVector wires = StdMeshers_FaceSide::GetFaceWires( F, aMesh, ignoreMediumNodes, problem );
306   if ( problem && !problem->IsOK() )
307     return error( problem );
308   int nbWires = wires.size();
309   if ( nbWires == 0 )
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());
314
315   // -------------------------
316   // Make input netgen mesh
317   // -------------------------
318
319   Ng_Init();
320   netgen::Mesh * ngMesh = new netgen::Mesh ();
321
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 );
326
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 );
332   }
333
334   // --------------------
335   // compute edge length
336   // --------------------
337
338   double edgeLength = 0;
339   if (_hypLengthFromEdges || !_hypLengthFromEdges && !_hypMaxElementArea)
340   {
341     int nbSegments = 0;
342     for ( int iW = 0; iW < nbWires; ++iW )
343     {
344       edgeLength += wires[ iW ]->Length();
345       nbSegments += wires[ iW ]->NbSegments();
346     }
347     if ( nbSegments )
348       edgeLength /= nbSegments;
349   }
350   if ( _hypMaxElementArea )
351   {
352     double maxArea = _hypMaxElementArea->GetMaxArea();
353     edgeLength = sqrt(2. * maxArea/sqrt(3.0));
354   }
355   if ( edgeLength < DBL_MIN )
356     edgeLength = occgeo.GetBoundingBox().Diam();
357
358   //cout << " edgeLength = " << edgeLength << endl;
359
360   netgen::mparam.maxh = edgeLength;
361   netgen::mparam.quad = _hypQuadranglePreference ? 1 : 0;
362   //ngMesh->SetGlobalH ( edgeLength );
363
364   // -------------------------
365   // Generate surface mesh
366   // -------------------------
367
368   char *optstr = 0;
369   int startWith = MESHCONST_MESHSURFACE;
370   int endWith   = MESHCONST_OPTSURFACE;
371   int err = 1;
372
373   try {
374 #if (OCC_VERSION_MAJOR << 16 | OCC_VERSION_MINOR << 8 | OCC_VERSION_MAINTENANCE) > 0x060100
375     OCC_CATCH_SIGNALS;
376 #endif
377     err = netgen::OCCGenerateMesh(occgeo, ngMesh, startWith, endWith, optstr);
378   }
379   catch (Standard_Failure& ex) {
380     string comment = ex.DynamicType()->Name();
381     if ( ex.GetMessageString() && strlen( ex.GetMessageString() )) {
382       comment += ": ";
383       comment += ex.GetMessageString();
384     }
385     error(COMPERR_OCC_EXCEPTION, comment);
386   }
387   catch (NgException exc) {
388     error( SMESH_Comment("NgException: ") << exc.What() );
389   }
390   catch (...) {
391     error(COMPERR_EXCEPTION,"Exception in netgen::OCCGenerateMesh()");
392   }
393
394   // ----------------------------------------------------
395   // Fill the SMESHDS with the generated nodes and faces
396   // ----------------------------------------------------
397
398   int nbNodes = ngMesh->GetNP();
399   int nbFaces = ngMesh->GetNSE();
400
401   int nbInputNodes = nodeVec.size();
402   nodeVec.resize( nbNodes, 0 );
403
404   // add nodes
405   for ( int i = nbInputNodes + 1; i <= nbNodes; ++i )
406   {
407     const MeshPoint& ngPoint = ngMesh->Point(i);
408     SMDS_MeshNode * node = meshDS->AddNode(ngPoint.X(), ngPoint.Y(), ngPoint.Z());
409     nodeVec[ i-1 ] = node;
410   }
411
412   // create faces
413   bool reverse = ( aShape.Orientation() == TopAbs_REVERSED );
414   for ( int i = 1; i <= nbFaces ; ++i )
415   {
416     const Element2d& elem = ngMesh->SurfaceElement(i);
417     vector<const SMDS_MeshNode*> nodes( elem.GetNP() );
418     for (int j=1; j <= elem.GetNP(); ++j)
419     {
420       int pind = elem.PNum(j);
421       const SMDS_MeshNode* node = nodeVec.at(pind-1);
422       if ( reverse )
423         nodes[ nodes.size()-j ] = node;
424       else
425         nodes[ j-1 ] = node;
426       if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_3DSPACE )
427       {
428         const PointGeomInfo& pgi = elem.GeomInfoPi(j);
429         meshDS->SetNodeOnFace((SMDS_MeshNode*)node, faceID, pgi.u, pgi.v);
430       }
431     }
432     SMDS_MeshFace* face = 0;
433     if ( elem.GetType() == TRIG )
434       face = helper.AddFace(nodes[0],nodes[1],nodes[2]);
435     else
436       face = helper.AddFace(nodes[0],nodes[1],nodes[2],nodes[3]);
437   }
438
439   Ng_DeleteMesh((nglib::Ng_Mesh*)ngMesh);
440   Ng_Exit();
441
442   NETGENPlugin_Mesher::RemoveTmpFiles();
443
444   return !err;
445 }
446
447
448 //=============================================================================
449 /*!
450  *
451  */
452 //=============================================================================
453
454 bool NETGENPlugin_NETGEN_2D_ONLY::Evaluate(SMESH_Mesh& aMesh,
455                                            const TopoDS_Shape& aShape,
456                                            MapShapeNbElems& aResMap)
457 {
458   TopoDS_Face F = TopoDS::Face(aShape);
459   if(F.IsNull())
460     return false;
461
462   // collect info from edges
463   int nb0d = 0, nb1d = 0;
464   bool IsQuadratic = false;
465   bool IsFirst = true;
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) )
471       continue;
472     tmpMap.Add(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));
479       return false;
480     }
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);
485     fullLen += aLen;
486     if(IsFirst) {
487       IsQuadratic = (aVec[SMDSEntity_Quad_Edge] > aVec[SMDSEntity_Edge]);
488       IsFirst = false;
489     }
490   }
491   tmpMap.Clear();
492
493   // compute edge length
494   double ELen = 0;
495   if (_hypLengthFromEdges || !_hypLengthFromEdges && !_hypMaxElementArea) {
496     if ( nb1d > 0 )
497       ELen = fullLen / nb1d;
498   }
499   if ( _hypMaxElementArea ) {
500     double maxArea = _hypMaxElementArea->GetMaxArea();
501     ELen = sqrt(2. * maxArea/sqrt(3.0));
502   }
503   if ( ELen < Precision::Confusion() ) {
504     SMESH_subMesh *sm = aMesh.GetSubMesh(F);
505     if ( sm ) {
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));
508     }
509     return false;
510   }
511
512   GProp_GProps G;
513   BRepGProp::SurfaceProperties(F,G);
514   double anArea = G.Mass();
515   int nbFaces = 0;
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;
521   if( IsQuadratic ) {
522     aVec[SMDSEntity_Node] = nbNodes;
523     aVec[SMDSEntity_Quad_Triangle] = nbFaces;
524   }
525   else {
526     aVec[SMDSEntity_Node] = nbNodes;
527     aVec[SMDSEntity_Triangle] = nbFaces;
528   }
529   SMESH_subMesh *sm = aMesh.GetSubMesh(F);
530   aResMap.insert(std::make_pair(sm,aVec));
531
532   return true;
533 }