Salome HOME
Correction for random error with NETGEN when multiple computation run at the same...
[plugins/netgenplugin.git] / src / NETGENPlugin / NETGENPlugin_Mesher.hxx
1 // Copyright (C) 2007-2022  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, or (at your option) any later version.
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
23 //  NETGENPlugin : C++ implementation
24 // File      : NETGENPlugin_Mesher.hxx
25 // Author    : Michael Sazonov (OCN)
26 // Date      : 31/03/2006
27 // Project   : SALOME
28 //
29 #ifndef _NETGENPlugin_Mesher_HXX_
30 #define _NETGENPlugin_Mesher_HXX_
31
32 #include "NETGENPlugin_Defs.hxx"
33
34 #include <StdMeshers_FaceSide.hxx>
35 #include <SMDS_MeshElement.hxx>
36 #include <SMESH_Algo.hxx>
37 #include <SMESH_ProxyMesh.hxx>
38 #include <SALOMEDS_Tool.hxx>
39
40 #include <TopTools_IndexedMapOfShape.hxx>
41
42 namespace nglib {
43 #include <nglib.h>
44 }
45
46 #include <map>
47 #include <vector>
48 #include <set>
49
50 class NETGENPlugin_Hypothesis;
51 class NETGENPlugin_Internals;
52 class NETGENPlugin_SimpleHypothesis_2D;
53 class SMESHDS_Mesh;
54 class SMESH_Comment;
55 class SMESH_Mesh;
56 class SMESH_MesherHelper;
57 class StdMeshers_ViscousLayers;
58 class TopoDS_Shape;
59 namespace netgen {
60   class OCCGeometry;
61   class Mesh;
62 }
63
64 // Class for temporary folder switching
65 class ChdirRAII
66 {
67   public:
68 #ifndef WIN32
69     ChdirRAII(const std::string& wd):_wd(wd) { if(_wd.empty()) return ; char *pwd(get_current_dir_name()); _od = pwd; free(pwd); chdir(_wd.c_str()); }
70     ~ChdirRAII() { if(_od.empty()) return ; chdir(_od.c_str()); }
71 #else
72     ChdirRAII(const std::string& wd) : _wd(wd) {
73       if (_wd.empty())
74         return;
75       TCHAR pwd[MAX_PATH];
76       GetCurrentDirectory(sizeof(pwd), pwd);
77       _od = Kernel_Utils::utf8_encode_s(pwd);
78       SetCurrentDirectory(Kernel_Utils::utf8_decode_s(_wd).c_str());
79     }
80     ~ChdirRAII() {
81       if (_od.empty()) return;
82       SetCurrentDirectory(Kernel_Utils::utf8_decode_s(_od).c_str());
83     }
84 #endif
85   private:
86     std::string _wd;
87     std::string _od;
88 };
89 //=============================================================================
90 /*!
91  * \brief Struct storing nb of entities in netgen mesh
92  */
93 //=============================================================================
94
95 struct NETGENPlugin_ngMeshInfo
96 {
97   int   _nbNodes, _nbSegments, _nbFaces, _nbVolumes;
98   bool  _elementsRemoved; // case where netgen can remove free nodes
99   char* _copyOfLocalH;
100   NETGENPlugin_ngMeshInfo( netgen::Mesh* ngMesh=0, bool checkRemovedElems=false );
101   void transferLocalH( netgen::Mesh* fromMesh, netgen::Mesh* toMesh );
102   void restoreLocalH ( netgen::Mesh* ngMesh);
103 };
104
105 //================================================================================
106 /*!
107  * \brief It correctly initializes netgen library at constructor and
108  *        correctly finishes using netgen library at destructor
109  */
110 //================================================================================
111
112 struct NETGENPLUGIN_EXPORT NETGENPlugin_NetgenLibWrapper
113 {
114   bool           _isComputeOk;
115   netgen::Mesh * _ngMesh;
116
117   NETGENPlugin_NetgenLibWrapper();
118   ~NETGENPlugin_NetgenLibWrapper();
119   void setMesh( nglib::Ng_Mesh* mesh );
120   nglib::Ng_Mesh* ngMesh() { return (nglib::Ng_Mesh*)(void*)_ngMesh; }
121
122
123
124   static int GenerateMesh(netgen::OCCGeometry& occgeo, int startWith, int endWith,
125                           netgen::Mesh* & ngMesh);
126   int GenerateMesh(netgen::OCCGeometry& occgeo, int startWith, int endWith )
127   {
128     return GenerateMesh( occgeo, startWith, endWith, _ngMesh );
129   }
130
131   static void CalcLocalH( netgen::Mesh * ngMesh );
132
133   static void RemoveTmpFiles();
134   static int& instanceCounter();
135   void setOutputFile(std::string);
136
137  private:
138   std::string getOutputFileName();
139   void        removeOutputFile();
140   std::string _outputFileName;
141   // This will change current directory when the class is instanciated and switch
142   ChdirRAII _tmpDir;
143
144
145   ostream *       _ngcout;
146   ostream *       _ngcerr;
147   std::streambuf* _coutBuffer;   // to re-/store cout.rdbuf()
148 };
149
150 //=============================================================================
151 /*!
152  * \brief This class calls the NETGEN mesher of OCC geometry
153  */
154 //=============================================================================
155
156 class NETGENPLUGIN_EXPORT NETGENPlugin_Mesher
157 {
158  public:
159   // ---------- PUBLIC METHODS ----------
160
161   NETGENPlugin_Mesher (SMESH_Mesh* mesh, const TopoDS_Shape& aShape,
162                        const bool isVolume);
163   ~NETGENPlugin_Mesher();
164   void SetSelfPointer( NETGENPlugin_Mesher ** ptr );
165
166   void SetParameters(const NETGENPlugin_Hypothesis*          hyp);
167   void SetParameters(const NETGENPlugin_SimpleHypothesis_2D* hyp);
168   void SetParameters(const StdMeshers_ViscousLayers*         hyp );
169   void SetViscousLayers2DAssigned(bool isAssigned) { _isViscousLayers2D = isAssigned; }
170
171   void SetLocalSizeForChordalError( netgen::OCCGeometry& occgeo, netgen::Mesh& ngMesh );
172   static void SetLocalSize( netgen::OCCGeometry& occgeo, netgen::Mesh& ngMesh );
173
174   bool Compute();
175
176   bool Evaluate(MapShapeNbElems& aResMap);
177
178   double GetProgress(const SMESH_Algo* holder,
179                      const int *       algoProgressTic,
180                      const double *    algoProgress) const;
181
182   static void PrepareOCCgeometry(netgen::OCCGeometry&          occgeom,
183                                  const TopoDS_Shape&           shape,
184                                  SMESH_Mesh&                   mesh,
185                                  std::list< SMESH_subMesh* > * meshedSM=0,
186                                  NETGENPlugin_Internals*       internalShapes=0);
187
188   static double GetDefaultMinSize(const TopoDS_Shape& shape,
189                                   const double        maxSize);
190
191   static void RestrictLocalSize(netgen::Mesh& ngMesh,
192                                 const gp_XYZ& p,
193                                 double        size,
194                                 const bool    overrideMinH=true);
195
196   static int FillSMesh(const netgen::OCCGeometry&          occgeom,
197                        netgen::Mesh&                       ngMesh,
198                        const NETGENPlugin_ngMeshInfo&      initState,
199                        SMESH_Mesh&                         sMesh,
200                        std::vector<const SMDS_MeshNode*>&  nodeVec,
201                        SMESH_Comment&                      comment,
202                        SMESH_MesherHelper*                 quadHelper=0);
203
204   bool FillNgMesh(netgen::OCCGeometry&                occgeom,
205                   netgen::Mesh&                       ngMesh,
206                   std::vector<const SMDS_MeshNode*>&  nodeVec,
207                   const std::list< SMESH_subMesh* > & meshedSM,
208                   SMESH_MesherHelper*                 quadHelper=0,
209                   SMESH_ProxyMesh::Ptr                proxyMesh=SMESH_ProxyMesh::Ptr());
210
211   static void FixIntFaces(const netgen::OCCGeometry& occgeom,
212                           netgen::Mesh&              ngMesh,
213                           NETGENPlugin_Internals&    internalShapes);
214
215   static bool FixFaceMesh(const netgen::OCCGeometry& occgeom,
216                           netgen::Mesh&              ngMesh,
217                           const int                  faceID);
218
219   static void AddIntVerticesInFaces(const netgen::OCCGeometry&          occgeom,
220                                     netgen::Mesh&                       ngMesh,
221                                     std::vector<const SMDS_MeshNode*>&  nodeVec,
222                                     NETGENPlugin_Internals&             internalShapes);
223
224   static void AddIntVerticesInSolids(const netgen::OCCGeometry&         occgeom,
225                                     netgen::Mesh&                       ngMesh,
226                                     std::vector<const SMDS_MeshNode*>&  nodeVec,
227                                     NETGENPlugin_Internals&             internalShapes);
228
229   static SMESH_ComputeErrorPtr
230     AddSegmentsToMesh(netgen::Mesh&                         ngMesh,
231                       netgen::OCCGeometry&                  geom,
232                       const TSideVector&                    wires,
233                       SMESH_MesherHelper&                   helper,
234                       std::vector< const SMDS_MeshNode* > & nodeVec,
235                       const bool                            overrideMinH=true);
236
237   void SetDefaultParameters();
238
239   static SMESH_ComputeErrorPtr ReadErrors(const std::vector< const SMDS_MeshNode* >& nodeVec);
240
241
242   static void toPython( const netgen::Mesh* ngMesh ); // debug
243
244  private:
245
246   SMESH_Mesh*          _mesh;
247   const TopoDS_Shape&  _shape;
248   bool                 _isVolume;
249   bool                 _optimize;
250   int                  _fineness;
251   bool                 _isViscousLayers2D;
252   double               _chordalError;
253   netgen::Mesh*        _ngMesh;
254   netgen::OCCGeometry* _occgeom;
255
256   int                  _curShapeIndex;
257   volatile int         _progressTic;
258   volatile double      _ticTime; // normalized [0,1] compute time per a SMESH_Algo::_progressTic
259   volatile double      _totalTime;
260
261   const NETGENPlugin_SimpleHypothesis_2D * _simpleHyp;
262   const StdMeshers_ViscousLayers*   _viscousLayersHyp;
263
264   // a pointer to NETGENPlugin_Mesher* field of the holder, that will be
265   // nullified at destruction of this
266   NETGENPlugin_Mesher ** _ptrToMe;
267 };
268
269 //=============================================================================
270 /*!
271  * \brief Container of info needed to solve problems with internal shapes.
272  *
273  * Issue 0020676. It is made up as a class to be ready to extract from NETGEN
274  * and put in SMESH as soon as the same solution is needed somewhere else.
275  * The approach is to precompute internal edges in 2D and internal faces in 3D
276  * and put their mesh correctly (twice) into netgen mesh.
277  * In 2D, this class finds internal edges in faces and their vertices.
278  * In 3D, it additionally finds internal faces, their edges shared with other faces,
279  * and their vertices shared by several internal edges. Nodes built on the found
280  * shapes and mesh faces built on the found internal faces are to be doubled in
281  * netgen mesh to emulate a "crack"
282  *
283  * For internal faces a more simple solution is found, which is just to duplicate
284  * mesh faces on internal geom faces without modeling a "real crack". For this
285  * reason findBorderElements() is no more used anywhere.
286  */
287 //=============================================================================
288
289 class NETGENPLUGIN_EXPORT NETGENPlugin_Internals
290 {
291   SMESH_Mesh&       _mesh;
292   bool              _is3D;
293   //2D
294   std::map<int,int> _e2face;//!<edges and their vertices in faces where they are TopAbs_INTERNAL
295   std::map<int,std::list<int> > _f2v;//!<faces with internal vertices
296   // 3D
297   std::set<int>     _intShapes;
298   std::set<int>     _borderFaces; //!< non-internal faces sharing the internal edge
299   std::map<int,std::list<int> > _s2v;//!<solids with internal vertices
300
301 public:
302   NETGENPlugin_Internals( SMESH_Mesh& mesh, const TopoDS_Shape& shape, bool is3D );
303
304   SMESH_Mesh& getMesh() const;
305
306   bool isShapeToPrecompute(const TopoDS_Shape& s);
307
308   // 2D meshing
309   // edges
310   bool hasInternalEdges() const { return !_e2face.empty(); }
311   bool isInternalEdge( int id ) const { return _e2face.count( id ); }
312   const std::map<int,int>& getEdgesAndVerticesWithFaces() const { return _e2face; }
313   void getInternalEdges( TopTools_IndexedMapOfShape&  fmap,
314                          TopTools_IndexedMapOfShape&  emap,
315                          TopTools_IndexedMapOfShape&  vmap,
316                          std::list< SMESH_subMesh* > smToPrecompute[]);
317   // vertices
318   bool hasInternalVertexInFace() const { return !_f2v.empty(); }
319   const std::map<int,std::list<int> >& getFacesWithVertices() const { return _f2v; }
320
321   // 3D meshing
322   // faces
323   bool hasInternalFaces() const { return !_intShapes.empty(); }
324   bool isInternalShape( int id ) const { return _intShapes.count( id ); }
325   void findBorderElements( std::set< const SMDS_MeshElement*, TIDCompare > & borderElems );
326   bool isBorderFace( int faceID ) const { return _borderFaces.count( faceID ); }
327   void getInternalFaces( TopTools_IndexedMapOfShape&  fmap,
328                          TopTools_IndexedMapOfShape&  emap,
329                          std::list< SMESH_subMesh* >& facesSM,
330                          std::list< SMESH_subMesh* >& boundarySM);
331   // vertices
332   bool hasInternalVertexInSolid() const { return !_s2v.empty(); }
333   bool hasInternalVertexInSolid(int soID ) const { return _s2v.count(soID); }
334   const std::map<int,std::list<int> >& getSolidsWithVertices() const { return _s2v; }
335
336
337 };
338
339 #endif