]> SALOME platform Git repositories - plugins/netgenplugin.git/blob - src/NETGENPlugin/NETGENPlugin_NETGEN_2D_ONLY.cxx
Salome HOME
0022232: [CEA 837] Memory corruption in GEOM/SMESH that leads to segfault on debian64
[plugins/netgenplugin.git] / src / NETGENPlugin / NETGENPlugin_NETGEN_2D_ONLY.cxx
1 // Copyright (C) 2007-2013  CEA/DEN, EDF R&D, OPEN CASCADE
2 //
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 // Lesser General Public License for more details.
12 //
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16 //
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
18 //
19
20 // File      : NETGENPlugin_NETGEN_2D_ONLY.cxx
21 // Author    : Edward AGAPOV (OCC)
22 // Project   : SALOME
23 //
24 #include "NETGENPlugin_NETGEN_2D_ONLY.hxx"
25
26 #include "NETGENPlugin_Mesher.hxx"
27 #include "NETGENPlugin_Hypothesis_2D.hxx"
28
29 #include <SMDS_MeshElement.hxx>
30 #include <SMDS_MeshNode.hxx>
31 #include <SMESHDS_Mesh.hxx>
32 #include <SMESH_Comment.hxx>
33 #include <SMESH_Gen.hxx>
34 #include <SMESH_Mesh.hxx>
35 #include <SMESH_MesherHelper.hxx>
36 #include <SMESH_subMesh.hxx>
37 #include <StdMeshers_FaceSide.hxx>
38 #include <StdMeshers_LengthFromEdges.hxx>
39 #include <StdMeshers_MaxElementArea.hxx>
40 #include <StdMeshers_QuadranglePreference.hxx>
41 #include <StdMeshers_ViscousLayers2D.hxx>
42
43 #include <Precision.hxx>
44 #include <Standard_ErrorHandler.hxx>
45 #include <Standard_Failure.hxx>
46
47 #include <utilities.h>
48
49 #include <list>
50 #include <vector>
51 #include <limits>
52
53 /*
54   Netgen include files
55 */
56 namespace nglib {
57 #include <nglib.h>
58 }
59 #ifndef OCCGEOMETRY
60 #define OCCGEOMETRY
61 #endif
62 #include <occgeom.hpp>
63 #include <meshing.hpp>
64 //#include <meshtype.hpp>
65 namespace netgen {
66 #ifdef NETGEN_V5
67   extern int OCCGenerateMesh (OCCGeometry&, Mesh*&, MeshingParameters&, int, int);
68 #else
69   extern int OCCGenerateMesh (OCCGeometry&, Mesh*&, int, int, char*);
70 #endif
71   extern MeshingParameters mparam;
72 }
73
74 using namespace std;
75 using namespace netgen;
76 using namespace nglib;
77
78 //#define DUMP_SEGMENTS
79
80 //=============================================================================
81 /*!
82  *  
83  */
84 //=============================================================================
85
86 NETGENPlugin_NETGEN_2D_ONLY::NETGENPlugin_NETGEN_2D_ONLY(int hypId, int studyId,
87                                                          SMESH_Gen* gen)
88   : SMESH_2D_Algo(hypId, studyId, gen)
89 {
90   MESSAGE("NETGENPlugin_NETGEN_2D_ONLY::NETGENPlugin_NETGEN_2D_ONLY");
91   _name = "NETGEN_2D_ONLY";
92   
93   _shapeType = (1 << TopAbs_FACE);// 1 bit /shape type
94
95   _compatibleHypothesis.push_back("MaxElementArea");
96   _compatibleHypothesis.push_back("LengthFromEdges");
97   _compatibleHypothesis.push_back("QuadranglePreference");
98   _compatibleHypothesis.push_back("NETGEN_Parameters_2D");
99   _compatibleHypothesis.push_back("ViscousLayers2D");
100
101   _hypMaxElementArea = 0;
102   _hypLengthFromEdges = 0;
103   _hypQuadranglePreference = 0;
104   _hypParameters = 0;
105 }
106
107 //=============================================================================
108 /*!
109  *  
110  */
111 //=============================================================================
112
113 NETGENPlugin_NETGEN_2D_ONLY::~NETGENPlugin_NETGEN_2D_ONLY()
114 {
115   MESSAGE("NETGENPlugin_NETGEN_2D_ONLY::~NETGENPlugin_NETGEN_2D_ONLY");
116 }
117
118 //=============================================================================
119 /*!
120  *  
121  */
122 //=============================================================================
123
124 bool NETGENPlugin_NETGEN_2D_ONLY::CheckHypothesis (SMESH_Mesh&         aMesh,
125                                                    const TopoDS_Shape& aShape,
126                                                    Hypothesis_Status&  aStatus)
127 {
128   _hypMaxElementArea = 0;
129   _hypLengthFromEdges = 0;
130   _hypQuadranglePreference = 0;
131
132   const list<const SMESHDS_Hypothesis*>& hyps = GetUsedHypothesis(aMesh, aShape, false);
133
134   if (hyps.empty())
135   {
136     aStatus = HYP_OK; //SMESH_Hypothesis::HYP_MISSING;
137     return true;  // (PAL13464) can work with no hypothesis, LengthFromEdges is default one
138   }
139
140   aStatus = HYP_MISSING;
141
142   list<const SMESHDS_Hypothesis*>::const_iterator ith;
143   for (ith = hyps.begin(); ith != hyps.end(); ++ith )
144   {
145     const SMESHDS_Hypothesis* hyp = (*ith);
146
147     string hypName = hyp->GetName();
148
149     if      ( hypName == "MaxElementArea")
150       _hypMaxElementArea = static_cast<const StdMeshers_MaxElementArea*> (hyp);
151     else if ( hypName == "LengthFromEdges" )
152       _hypLengthFromEdges = static_cast<const StdMeshers_LengthFromEdges*> (hyp);
153     else if ( hypName == "QuadranglePreference" )
154       _hypQuadranglePreference = static_cast<const StdMeshers_QuadranglePreference*>(hyp);
155     else if ( hypName == "NETGEN_Parameters_2D" )
156       _hypParameters = static_cast<const NETGENPlugin_Hypothesis_2D*>(hyp);
157     else if ( hypName == StdMeshers_ViscousLayers2D::GetHypType() )
158       continue;
159     else {
160       aStatus = HYP_INCOMPATIBLE;
161       return false;
162     }
163   }
164
165   int nbHyps = bool(_hypMaxElementArea) + bool(_hypLengthFromEdges) + bool(_hypParameters );
166   if ( nbHyps > 1 )
167     aStatus = HYP_CONCURENT;
168   else
169     aStatus = HYP_OK;
170
171   return ( aStatus == HYP_OK );
172 }
173
174 //=============================================================================
175 /*!
176  *Here we are going to use the NETGEN mesher
177  */
178 //=============================================================================
179
180 bool NETGENPlugin_NETGEN_2D_ONLY::Compute(SMESH_Mesh&         aMesh,
181                                           const TopoDS_Shape& aShape)
182 {
183   netgen::multithread.terminate = 0;
184
185   SMESHDS_Mesh* meshDS = aMesh.GetMeshDS();
186   int faceID = meshDS->ShapeToIndex( aShape );
187
188   SMESH_MesherHelper helper(aMesh);
189   _quadraticMesh = helper.IsQuadraticSubMesh(aShape);
190   helper.SetElementsOnShape( true );
191   const bool ignoreMediumNodes = _quadraticMesh;
192   
193   // build viscous layers if required
194   const TopoDS_Face F = TopoDS::Face( aShape/*.Oriented( TopAbs_FORWARD )*/);
195   SMESH_ProxyMesh::Ptr proxyMesh = StdMeshers_ViscousLayers2D::Compute( aMesh, F );
196   if ( !proxyMesh )
197     return false;
198
199   // ------------------------
200   // get all edges of a face
201   // ------------------------
202   TError problem;
203   TSideVector wires =
204     StdMeshers_FaceSide::GetFaceWires( F, aMesh, ignoreMediumNodes, problem, proxyMesh );
205   if ( problem && !problem->IsOK() )
206     return error( problem );
207   int nbWires = wires.size();
208   if ( nbWires == 0 )
209     return error( "Problem in StdMeshers_FaceSide::GetFaceWires()");
210   if ( wires[0]->NbSegments() < 3 ) // ex: a circle with 2 segments
211     return error(COMPERR_BAD_INPUT_MESH,
212                  SMESH_Comment("Too few segments: ")<<wires[0]->NbSegments());
213
214   // --------------------
215   // compute edge length
216   // --------------------
217
218   NETGENPlugin_Mesher aMesher( &aMesh, aShape, /*isVolume=*/false);
219   netgen::OCCGeometry occgeo;
220   aMesher.PrepareOCCgeometry( occgeo, F, aMesh );
221   occgeo.fmap.Clear(); // face can be reversed, which is wrong in this case (issue 19978)
222   occgeo.fmap.Add( F );
223
224   if ( _hypParameters )
225   {
226     aMesher.SetParameters(_hypParameters);
227   }
228   else
229   {
230     double edgeLength = 0;
231     if (_hypLengthFromEdges || (!_hypLengthFromEdges && !_hypMaxElementArea))
232     {
233       int nbSegments = 0;
234       for ( int iW = 0; iW < nbWires; ++iW )
235       {
236         edgeLength += wires[ iW ]->Length();
237         nbSegments += wires[ iW ]->NbSegments();
238       }
239       if ( nbSegments )
240         edgeLength /= nbSegments;
241     }
242     if ( _hypMaxElementArea )
243     {
244       double maxArea = _hypMaxElementArea->GetMaxArea();
245       edgeLength = sqrt(2. * maxArea/sqrt(3.0));
246     }
247     if ( edgeLength < DBL_MIN )
248       edgeLength = occgeo.GetBoundingBox().Diam();
249
250     netgen::mparam.maxh = edgeLength;
251     netgen::mparam.minh = aMesher.GetDefaultMinSize( aShape, netgen::mparam.maxh );
252     netgen::mparam.quad = _hypQuadranglePreference ? 1 : 0;
253     netgen::mparam.grading = 0.7; // very coarse mesh by default
254   }
255   occgeo.face_maxh = netgen::mparam.maxh;
256
257   // -------------------------
258   // Make input netgen mesh
259   // -------------------------
260
261   NETGENPlugin_NetgenLibWrapper ngLib;
262   netgen::Mesh * ngMesh = (netgen::Mesh*) ngLib._ngMesh;
263
264   Box<3> bb = occgeo.GetBoundingBox();
265   bb.Increase (bb.Diam()/10);
266   ngMesh->SetLocalH (bb.PMin(), bb.PMax(), netgen::mparam.grading);
267   ngMesh->SetGlobalH (netgen::mparam.maxh);
268
269   vector< const SMDS_MeshNode* > nodeVec;
270   problem = aMesher.AddSegmentsToMesh( *ngMesh, occgeo, wires, helper, nodeVec );
271   if ( problem && !problem->IsOK() )
272     return error( problem );
273
274   // -------------------------
275   // Generate surface mesh
276   // -------------------------
277
278 #ifndef NETGEN_V5
279   char *optstr = 0;
280 #endif
281   int startWith = MESHCONST_MESHSURFACE;
282   int endWith   = MESHCONST_OPTSURFACE;
283   int err = 1;
284
285   try {
286 #if (OCC_VERSION_MAJOR << 16 | OCC_VERSION_MINOR << 8 | OCC_VERSION_MAINTENANCE) > 0x060100
287     OCC_CATCH_SIGNALS;
288 #endif
289 #ifdef NETGEN_V5
290     err = netgen::OCCGenerateMesh(occgeo, ngMesh, netgen::mparam, startWith, endWith);
291 #else
292     err = netgen::OCCGenerateMesh(occgeo, ngMesh, startWith, endWith, optstr);
293 #endif
294     if(netgen::multithread.terminate)
295       return false;
296     if ( err )
297       error(SMESH_Comment("Error in netgen::OCCGenerateMesh() at ") << netgen::multithread.task);
298   }
299   catch (Standard_Failure& ex)
300   {
301     SMESH_Comment str("Exception in  netgen::OCCGenerateMesh()");
302     str << " at " << netgen::multithread.task
303         << ": " << ex.DynamicType()->Name();
304     if ( ex.GetMessageString() && strlen( ex.GetMessageString() ))
305       str << ": " << ex.GetMessageString();
306     error(str);
307   }
308   catch (...) {
309     SMESH_Comment str("Exception in  netgen::OCCGenerateMesh()");
310     str << " at " << netgen::multithread.task;
311     error(str);
312   }
313
314   // ----------------------------------------------------
315   // Fill the SMESHDS with the generated nodes and faces
316   // ----------------------------------------------------
317
318   int nbNodes = ngMesh->GetNP();
319   int nbFaces = ngMesh->GetNSE();
320
321   int nbInputNodes = nodeVec.size()-1;
322   nodeVec.resize( nbNodes+1, 0 );
323
324   // add nodes
325   for ( int ngID = nbInputNodes + 1; ngID <= nbNodes; ++ngID )
326   {
327     const MeshPoint& ngPoint = ngMesh->Point( ngID );
328     SMDS_MeshNode * node = meshDS->AddNode(ngPoint(0), ngPoint(1), ngPoint(2));
329     nodeVec[ ngID ] = node;
330   }
331
332   // create faces
333   const bool reverse = false; //( aShape.Orientation() == TopAbs_REVERSED );
334   int i,j;
335   for ( i = 1; i <= nbFaces ; ++i )
336   {
337     const Element2d& elem = ngMesh->SurfaceElement(i);
338     vector<const SMDS_MeshNode*> nodes( elem.GetNP() );
339     for (j=1; j <= elem.GetNP(); ++j)
340     {
341       int pind = elem.PNum(j);
342       if ( pind < 1 )
343         break;
344       const SMDS_MeshNode* node = nodeVec[ pind ];
345       if ( reverse )
346         nodes[ nodes.size()-j ] = node;
347       else
348         nodes[ j-1 ] = node;
349       if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_3DSPACE )
350       {
351         const PointGeomInfo& pgi = elem.GeomInfoPi(j);
352         meshDS->SetNodeOnFace((SMDS_MeshNode*)node, faceID, pgi.u, pgi.v);
353       }
354     }
355     if ( j > elem.GetNP() )
356     {
357       SMDS_MeshFace* face = 0;
358       if ( elem.GetType() == TRIG )
359         face = helper.AddFace(nodes[0],nodes[1],nodes[2]);
360       else
361         face = helper.AddFace(nodes[0],nodes[1],nodes[2],nodes[3]);
362     }
363   }
364
365   ngLib._isComputeOk = !err;
366   return !err;
367 }
368
369 void NETGENPlugin_NETGEN_2D_ONLY::CancelCompute()
370 {
371   SMESH_Algo::CancelCompute();
372   netgen::multithread.terminate = 1;
373 }
374
375 //=============================================================================
376 /*!
377  *
378  */
379 //=============================================================================
380
381 bool NETGENPlugin_NETGEN_2D_ONLY::Evaluate(SMESH_Mesh& aMesh,
382                                            const TopoDS_Shape& aShape,
383                                            MapShapeNbElems& aResMap)
384 {
385   TopoDS_Face F = TopoDS::Face(aShape);
386   if(F.IsNull())
387     return false;
388
389   // collect info from edges
390   int nb0d = 0, nb1d = 0;
391   bool IsQuadratic = false;
392   bool IsFirst = true;
393   double fullLen = 0.0;
394   TopTools_MapOfShape tmpMap;
395   for (TopExp_Explorer exp(F, TopAbs_EDGE); exp.More(); exp.Next()) {
396     TopoDS_Edge E = TopoDS::Edge(exp.Current());
397     if( tmpMap.Contains(E) )
398       continue;
399     tmpMap.Add(E);
400     SMESH_subMesh *aSubMesh = aMesh.GetSubMesh(exp.Current());
401     MapShapeNbElemsItr anIt = aResMap.find(aSubMesh);
402     if( anIt==aResMap.end() ) {
403       SMESH_subMesh *sm = aMesh.GetSubMesh(F);
404       SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
405       smError.reset( new SMESH_ComputeError(COMPERR_ALGO_FAILED,"Submesh can not be evaluated",this));
406       return false;
407     }
408     std::vector<int> aVec = (*anIt).second;
409     nb0d += aVec[SMDSEntity_Node];
410     nb1d += Max(aVec[SMDSEntity_Edge],aVec[SMDSEntity_Quad_Edge]);
411     double aLen = SMESH_Algo::EdgeLength(E);
412     fullLen += aLen;
413     if(IsFirst) {
414       IsQuadratic = (aVec[SMDSEntity_Quad_Edge] > aVec[SMDSEntity_Edge]);
415       IsFirst = false;
416     }
417   }
418   tmpMap.Clear();
419
420   // compute edge length
421   double ELen = 0;
422   if (_hypLengthFromEdges || !_hypLengthFromEdges && !_hypMaxElementArea) {
423     if ( nb1d > 0 )
424       ELen = fullLen / nb1d;
425   }
426   if ( _hypMaxElementArea ) {
427     double maxArea = _hypMaxElementArea->GetMaxArea();
428     ELen = sqrt(2. * maxArea/sqrt(3.0));
429   }
430   GProp_GProps G;
431   BRepGProp::SurfaceProperties(F,G);
432   double anArea = G.Mass();
433
434   const int hugeNb = numeric_limits<int>::max()/10;
435   if ( anArea / hugeNb > ELen*ELen )
436   {
437     SMESH_subMesh *sm = aMesh.GetSubMesh(F);
438     SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
439     smError.reset( new SMESH_ComputeError(COMPERR_ALGO_FAILED,"Submesh can not be evaluated.\nToo small element length",this));
440     return false;
441   }
442   int nbFaces = (int) ( anArea / ( ELen*ELen*sqrt(3.) / 4 ) );
443   int nbNodes = (int) ( ( nbFaces*3 - (nb1d-1)*2 ) / 6 + 1 );
444   std::vector<int> aVec(SMDSEntity_Last);
445   for(int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aVec[i]=0;
446   if( IsQuadratic ) {
447     aVec[SMDSEntity_Node] = nbNodes;
448     aVec[SMDSEntity_Quad_Triangle] = nbFaces;
449   }
450   else {
451     aVec[SMDSEntity_Node] = nbNodes;
452     aVec[SMDSEntity_Triangle] = nbFaces;
453   }
454   SMESH_subMesh *sm = aMesh.GetSubMesh(F);
455   aResMap.insert(std::make_pair(sm,aVec));
456
457   return true;
458 }