]> SALOME platform Git repositories - plugins/netgenplugin.git/blob - src/NETGENPlugin/NETGENPlugin_NETGEN_2D_ONLY.cxx
Salome HOME
0020526: [CEA] Disk meshing fails
[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     bool reverse = // 20526: [CEA] Disk meshing fails
210       ( wire->NbEdges() == 1 && 
211         geom.emap(geom.emap.FindIndex(wire->Edge(0))).Orientation() == TopAbs_REVERSED );
212
213     int firstPointID = ngMesh.GetNP() + 1;
214     int edgeID = 1, posID = -2;
215     for ( int i = 0; i < wire->NbSegments(); ++i ) // loop on segments
216     {
217       // Add the first point of a segment
218       const SMDS_MeshNode * n = uvPtVec[ i ].node;
219       const int posShapeID = n->GetPosition()->GetShapeId();
220
221       // skip nodes on degenerated edges
222       if ( helper.IsDegenShape( posShapeID ) &&
223            helper.IsDegenShape( uvPtVec[ i+1 ].node->GetPosition()->GetShapeId() ))
224         continue;
225
226       nodeVec.push_back( n );
227
228       MeshPoint mp( Point<3> (n->X(), n->Y(), n->Z()) );
229       ngMesh.AddPoint ( mp, 1, EDGEPOINT );
230
231       // Add the segment
232       Segment seg;
233
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);
238
239       for ( int iEnd = 0; iEnd < 2; ++iEnd)
240       {
241         const UVPtStruct& pnt = uvPtVec[ i + iEnd ];
242
243         seg.epgeominfo[ iEnd ].dist = pnt.param; // param on curve
244         seg.epgeominfo[ iEnd ].u    = pnt.u;
245         seg.epgeominfo[ iEnd ].v    = pnt.v;
246
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 )
250         {
251           // get edge id
252           double normParam = pnt.normParam;
253           if ( onVertex )
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 );
257           posID  = posShapeID;
258           if ( onVertex ) // param on curve is different on each of two edges
259             seg.epgeominfo[ iEnd ].dist = helper.GetNodeU( edge, pnt.node );
260         }
261         seg.epgeominfo[ iEnd ].edgenr = edgeID; //  = geom.emap.FindIndex(edge);
262       }
263       // 20526: [CEA] Disk meshing fails
264       if (reverse)
265       {
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);
270       }
271
272       ngMesh.AddSegment (seg);
273
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;
283     }
284     Segment& seg = ngMesh.LineSegment( ngMesh.GetNSeg() );
285     seg.p2 = firstPointID;
286   }
287
288   ngMesh.CalcSurfacesOfNode();  
289
290   return TError();
291 }
292
293 //=============================================================================
294 /*!
295  *Here we are going to use the NETGEN mesher
296  */
297 //=============================================================================
298
299 bool NETGENPlugin_NETGEN_2D_ONLY::Compute(SMESH_Mesh&         aMesh,
300                                           const TopoDS_Shape& aShape)
301 {
302   MESSAGE("NETGENPlugin_NETGEN_2D_ONLY::Compute()");
303
304   SMESHDS_Mesh* meshDS = aMesh.GetMeshDS();
305   int faceID = meshDS->ShapeToIndex( aShape );
306
307   SMESH_MesherHelper helper(aMesh);
308   _quadraticMesh = helper.IsQuadraticSubMesh(aShape);
309   helper.SetElementsOnShape( true );
310   const bool ignoreMediumNodes = _quadraticMesh;
311   
312   // ------------------------
313   // get all edges of a face
314   // ------------------------
315   const TopoDS_Face F = TopoDS::Face( aShape.Oriented( TopAbs_FORWARD ));
316   TError problem;
317   TSideVector wires = StdMeshers_FaceSide::GetFaceWires( F, aMesh, ignoreMediumNodes, problem );
318   if ( problem && !problem->IsOK() )
319     return error( problem );
320   int nbWires = wires.size();
321   if ( nbWires == 0 )
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());
326
327   // -------------------------
328   // Make input netgen mesh
329   // -------------------------
330
331   Ng_Init();
332   netgen::Mesh * ngMesh = new netgen::Mesh ();
333
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 );
338
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 );
344   }
345
346   // --------------------
347   // compute edge length
348   // --------------------
349
350   double edgeLength = 0;
351   if (_hypLengthFromEdges || !_hypLengthFromEdges && !_hypMaxElementArea)
352   {
353     int nbSegments = 0;
354     for ( int iW = 0; iW < nbWires; ++iW )
355     {
356       edgeLength += wires[ iW ]->Length();
357       nbSegments += wires[ iW ]->NbSegments();
358     }
359     if ( nbSegments )
360       edgeLength /= nbSegments;
361   }
362   if ( _hypMaxElementArea )
363   {
364     double maxArea = _hypMaxElementArea->GetMaxArea();
365     edgeLength = sqrt(2. * maxArea/sqrt(3.0));
366   }
367   if ( edgeLength < DBL_MIN )
368     edgeLength = occgeo.GetBoundingBox().Diam();
369
370   //cout << " edgeLength = " << edgeLength << endl;
371
372   netgen::mparam.maxh = edgeLength;
373   netgen::mparam.quad = _hypQuadranglePreference ? 1 : 0;
374   //ngMesh->SetGlobalH ( edgeLength );
375
376   // -------------------------
377   // Generate surface mesh
378   // -------------------------
379
380   char *optstr = 0;
381   int startWith = MESHCONST_MESHSURFACE;
382   int endWith   = MESHCONST_OPTSURFACE;
383   int err = 1;
384
385   try {
386 #if (OCC_VERSION_MAJOR << 16 | OCC_VERSION_MINOR << 8 | OCC_VERSION_MAINTENANCE) > 0x060100
387     OCC_CATCH_SIGNALS;
388 #endif
389     err = netgen::OCCGenerateMesh(occgeo, ngMesh, startWith, endWith, optstr);
390   }
391   catch (Standard_Failure& ex) {
392     string comment = ex.DynamicType()->Name();
393     if ( ex.GetMessageString() && strlen( ex.GetMessageString() )) {
394       comment += ": ";
395       comment += ex.GetMessageString();
396     }
397     error(COMPERR_OCC_EXCEPTION, comment);
398   }
399   catch (NgException exc) {
400     error( SMESH_Comment("NgException: ") << exc.What() );
401   }
402   catch (...) {
403     error(COMPERR_EXCEPTION,"Exception in netgen::OCCGenerateMesh()");
404   }
405
406   // ----------------------------------------------------
407   // Fill the SMESHDS with the generated nodes and faces
408   // ----------------------------------------------------
409
410   int nbNodes = ngMesh->GetNP();
411   int nbFaces = ngMesh->GetNSE();
412
413   int nbInputNodes = nodeVec.size();
414   nodeVec.resize( nbNodes, 0 );
415
416   // add nodes
417   for ( int i = nbInputNodes + 1; i <= nbNodes; ++i )
418   {
419     const MeshPoint& ngPoint = ngMesh->Point(i);
420     SMDS_MeshNode * node = meshDS->AddNode(ngPoint.X(), ngPoint.Y(), ngPoint.Z());
421     nodeVec[ i-1 ] = node;
422   }
423
424   // create faces
425   bool reverse = ( aShape.Orientation() == TopAbs_REVERSED );
426   for ( int i = 1; i <= nbFaces ; ++i )
427   {
428     const Element2d& elem = ngMesh->SurfaceElement(i);
429     vector<const SMDS_MeshNode*> nodes( elem.GetNP() );
430     for (int j=1; j <= elem.GetNP(); ++j)
431     {
432       int pind = elem.PNum(j);
433       const SMDS_MeshNode* node = nodeVec.at(pind-1);
434       if ( reverse )
435         nodes[ nodes.size()-j ] = node;
436       else
437         nodes[ j-1 ] = node;
438       if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_3DSPACE )
439       {
440         const PointGeomInfo& pgi = elem.GeomInfoPi(j);
441         meshDS->SetNodeOnFace((SMDS_MeshNode*)node, faceID, pgi.u, pgi.v);
442       }
443     }
444     SMDS_MeshFace* face = 0;
445     if ( elem.GetType() == TRIG )
446       face = helper.AddFace(nodes[0],nodes[1],nodes[2]);
447     else
448       face = helper.AddFace(nodes[0],nodes[1],nodes[2],nodes[3]);
449   }
450
451   Ng_DeleteMesh((nglib::Ng_Mesh*)ngMesh);
452   Ng_Exit();
453
454   NETGENPlugin_Mesher::RemoveTmpFiles();
455
456   return !err;
457 }
458
459
460 //=============================================================================
461 /*!
462  *
463  */
464 //=============================================================================
465
466 bool NETGENPlugin_NETGEN_2D_ONLY::Evaluate(SMESH_Mesh& aMesh,
467                                            const TopoDS_Shape& aShape,
468                                            MapShapeNbElems& aResMap)
469 {
470   TopoDS_Face F = TopoDS::Face(aShape);
471   if(F.IsNull())
472     return false;
473
474   // collect info from edges
475   int nb0d = 0, nb1d = 0;
476   bool IsQuadratic = false;
477   bool IsFirst = true;
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) )
483       continue;
484     tmpMap.Add(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));
491       return false;
492     }
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);
497     fullLen += aLen;
498     if(IsFirst) {
499       IsQuadratic = (aVec[SMDSEntity_Quad_Edge] > aVec[SMDSEntity_Edge]);
500       IsFirst = false;
501     }
502   }
503   tmpMap.Clear();
504
505   // compute edge length
506   double ELen = 0;
507   if (_hypLengthFromEdges || !_hypLengthFromEdges && !_hypMaxElementArea) {
508     if ( nb1d > 0 )
509       ELen = fullLen / nb1d;
510   }
511   if ( _hypMaxElementArea ) {
512     double maxArea = _hypMaxElementArea->GetMaxArea();
513     ELen = sqrt(2. * maxArea/sqrt(3.0));
514   }
515   if ( ELen < Precision::Confusion() ) {
516     SMESH_subMesh *sm = aMesh.GetSubMesh(F);
517     if ( sm ) {
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));
520     }
521     return false;
522   }
523
524   GProp_GProps G;
525   BRepGProp::SurfaceProperties(F,G);
526   double anArea = G.Mass();
527   int nbFaces = 0;
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;
533   if( IsQuadratic ) {
534     aVec[SMDSEntity_Node] = nbNodes;
535     aVec[SMDSEntity_Quad_Triangle] = nbFaces;
536   }
537   else {
538     aVec[SMDSEntity_Node] = nbNodes;
539     aVec[SMDSEntity_Triangle] = nbFaces;
540   }
541   SMESH_subMesh *sm = aMesh.GetSubMesh(F);
542   aResMap.insert(std::make_pair(sm,aVec));
543
544   return true;
545 }