Salome HOME
[bos #38045] [EDF] (2023-T3) Stand alone version for Netgen meshers.
[plugins/netgenplugin.git] / src / NETGENPlugin / NETGENPlugin_Mesher.hxx
1 // Copyright (C) 2007-2023  CEA, EDF, 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 #include "Basics_Utils.hxx"
40 #include "SALOME_Basics.hxx"
41 #include <TopTools_IndexedMapOfShape.hxx>
42
43 // Netgen include files
44 #ifndef OCCGEOMETRY
45 #define OCCGEOMETRY
46 #endif
47 #include <occgeom.hpp>
48 #include <meshing.hpp>
49
50 namespace nglib {
51 #include <nglib.h>
52 }
53
54 #include <map>
55 #include <vector>
56 #include <set>
57
58 class NETGENPlugin_Hypothesis;
59 class NETGENPlugin_Internals;
60 class NETGENPlugin_SimpleHypothesis_2D;
61 class SMESHDS_Mesh;
62 class SMESH_Comment;
63 class SMESH_Mesh;
64 class SMESH_MesherHelper;
65 class StdMeshers_ViscousLayers;
66 class TopoDS_Shape;
67 namespace netgen {
68   class OCCGeometry;
69   class Mesh;
70   NETGENPLUGIN_DLL_HEADER
71   extern MeshingParameters mparam;
72 }
73
74 // Class for temporary folder switching
75 class ChdirRAII
76 {
77   public:
78 #ifndef WIN32
79     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()); }
80     ~ChdirRAII() { if(_od.empty()) return ; chdir(_od.c_str()); }
81 #else
82     ChdirRAII(const std::string& wd) : _wd(wd) {
83       if (_wd.empty())
84         return;
85       TCHAR pwd[MAX_PATH];
86       GetCurrentDirectory(sizeof(pwd), pwd);
87       _od = Kernel_Utils::utf8_encode_s(pwd);
88       SetCurrentDirectory(Kernel_Utils::utf8_decode_s(_wd).c_str());
89     }
90     ~ChdirRAII() {
91       if (_od.empty()) return;
92       SetCurrentDirectory(Kernel_Utils::utf8_decode_s(_od).c_str());
93     }
94 #endif
95   private:
96     std::string _wd;
97     std::string _od;
98 };
99 //=============================================================================
100 /*!
101  * \brief Struct storing nb of entities in netgen mesh
102  */
103 //=============================================================================
104
105 struct NETGENPlugin_ngMeshInfo
106 {
107   int   _nbNodes, _nbSegments, _nbFaces, _nbVolumes;
108   bool  _elementsRemoved; // case where netgen can remove free nodes
109   char* _copyOfLocalH;
110   NETGENPlugin_ngMeshInfo( netgen::Mesh* ngMesh=0, bool checkRemovedElems=false );
111   void transferLocalH( netgen::Mesh* fromMesh, netgen::Mesh* toMesh );
112   void restoreLocalH ( netgen::Mesh* ngMesh);
113 };
114
115 //================================================================================
116 /*!
117  * \brief It correctly initializes netgen library at constructor and
118  *        correctly finishes using netgen library at destructor
119  */
120 //================================================================================
121
122 struct NETGENPLUGIN_EXPORT NETGENPlugin_NetgenLibWrapper
123 {
124   bool           _isComputeOk;
125   netgen::Mesh * _ngMesh;
126
127   NETGENPlugin_NetgenLibWrapper();
128   ~NETGENPlugin_NetgenLibWrapper();
129   void setMesh( nglib::Ng_Mesh* mesh );
130   nglib::Ng_Mesh* ngMesh() { return (nglib::Ng_Mesh*)(void*)_ngMesh; }
131
132
133
134   static int GenerateMesh(netgen::OCCGeometry& occgeo, int startWith, int endWith,
135                           netgen::Mesh* & ngMesh);
136   int GenerateMesh(netgen::OCCGeometry& occgeo, int startWith, int endWith )
137   {
138     return GenerateMesh( occgeo, startWith, endWith, _ngMesh );
139   }
140
141   static void CalcLocalH( netgen::Mesh * ngMesh );
142
143   static void RemoveTmpFiles();
144   static int& instanceCounter();
145   void setOutputFile(std::string);
146
147  private:
148   std::string getOutputFileName();
149   void        removeOutputFile();
150   std::string _outputFileName;
151   // This will change current directory when the class is instanciated and switch
152   ChdirRAII _tmpDir;
153
154
155   ostream *       _ngcout;
156   ostream *       _ngcerr;
157   std::streambuf* _coutBuffer;   // to re-/store cout.rdbuf()
158 };
159
160 //=============================================================================
161 /*!
162  * \brief This class calls the NETGEN mesher of OCC geometry
163  */
164 //=============================================================================
165
166 class NETGENPLUGIN_EXPORT NETGENPlugin_Mesher
167 {
168  public:
169   // ---------- PUBLIC METHODS ----------
170
171   NETGENPlugin_Mesher (SMESH_Mesh* mesh, const TopoDS_Shape& aShape,
172                        const bool isVolume);
173   ~NETGENPlugin_Mesher();
174   void SetSelfPointer( NETGENPlugin_Mesher ** ptr );
175
176   void SetParameters(const NETGENPlugin_Hypothesis*          hyp);
177   void SetParameters(const NETGENPlugin_SimpleHypothesis_2D* hyp);
178   void SetParameters(const StdMeshers_ViscousLayers*         hyp );
179   void SetViscousLayers2DAssigned(bool isAssigned) { _isViscousLayers2D = isAssigned; }
180
181   void SetLocalSizeForChordalError( netgen::OCCGeometry& occgeo, netgen::Mesh& ngMesh );
182   static void SetLocalSize( netgen::OCCGeometry& occgeo, netgen::Mesh& ngMesh );
183
184   
185 /**
186  * @brief InitialSetup. Fill occgeo map with geometrical objects not meshed. Fill meshdSM with the already computed
187  *        submeshes, and mesh the internal edges so faces with internal are eventurally properly meshed.
188  *        Define the class members _ngMesh and _occgeom
189  */
190   void InitialSetup( NETGENPlugin_NetgenLibWrapper& ngLib, netgen::OCCGeometry& occgeo, 
191                       list< SMESH_subMesh* >* meshedSM, NETGENPlugin_Internals* internals, 
192                       SMESH_MesherHelper &quadHelper, NETGENPlugin_ngMeshInfo& initState, netgen::MeshingParameters &mparams );
193
194   void InitialSetupSA( NETGENPlugin_NetgenLibWrapper& ngLib, netgen::OCCGeometry& occgeo, 
195                       list< SMESH_subMesh* >* meshedSM, NETGENPlugin_Internals* internals, 
196                       SMESH_MesherHelper &quadHelper, NETGENPlugin_ngMeshInfo& initState, 
197                       netgen::MeshingParameters &mparams, bool useFMapFunction = false );
198
199   void SetBasicMeshParameters( NETGENPlugin_NetgenLibWrapper& ngLib, netgen::MeshingParameters &mparams, netgen::OCCGeometry& occgeo );
200   void SetBasicMeshParametersFor2D( netgen::OCCGeometry& occgeo, vector< const SMDS_MeshNode* >& nodeVec, 
201                                       netgen::MeshingParameters &mparams, NETGENPlugin_Internals* internals, 
202                                         NETGENPlugin_ngMeshInfo& initState );
203   void SetBasicMeshParametersFor3D( NETGENPlugin_NetgenLibWrapper& ngLib, netgen::OCCGeometry& occgeo, 
204                                       vector< const SMDS_MeshNode* >& nodeVec, netgen::MeshingParameters &mparams, 
205                                         NETGENPlugin_Internals* internals, NETGENPlugin_ngMeshInfo& initState, SMESH_MesherHelper &quadHelper, 
206                                           SMESH_Comment& comment );
207   void CallNetgenConstAnalysis( NETGENPlugin_NetgenLibWrapper& ngLib, netgen::MeshingParameters &mparams, netgen::OCCGeometry& occgeo );
208   int CallNetgenMeshEdges( NETGENPlugin_NetgenLibWrapper& ngLib, netgen::OCCGeometry& occgeo );
209   int CallNetgenMeshFaces( NETGENPlugin_NetgenLibWrapper& ngLib, netgen::OCCGeometry& occgeo, SMESH_Comment& comment );
210   int CallNetgenMeshVolumens( NETGENPlugin_NetgenLibWrapper& ngLib, netgen::OCCGeometry& occgeo, SMESH_Comment& comment );
211   void MakeSecondOrder( NETGENPlugin_NetgenLibWrapper& ngLib, netgen::MeshingParameters &mparams, netgen::OCCGeometry& occgeo, 
212                           list< SMESH_subMesh* >* meshedSM, NETGENPlugin_ngMeshInfo& initState, SMESH_Comment& comment );
213   int FillInternalElements( NETGENPlugin_NetgenLibWrapper& ngLib, NETGENPlugin_Internals& internals, netgen::OCCGeometry& occgeo,
214                               NETGENPlugin_ngMeshInfo& initState, SMESH_MesherHelper &quadHelper, list< SMESH_subMesh* >* meshedSM );
215   bool Fill2DViscousLayer( netgen::OCCGeometry& occgeo, vector< const SMDS_MeshNode* >& nodeVec, 
216                             NETGENPlugin_Internals* internals, NETGENPlugin_ngMeshInfo& initState );
217
218   bool Fill3DViscousLayerAndQuadAdaptor( netgen::OCCGeometry& occgeo, vector< const SMDS_MeshNode* >& nodeVec, 
219                                           netgen::MeshingParameters &mparams, NETGENPlugin_ngMeshInfo& initState,
220                                           list< SMESH_subMesh* >* meshedSM, SMESH_MesherHelper &quadHelper, int & err );
221
222   int Fill0D1DElements( netgen::OCCGeometry& occgeo, vector< const SMDS_MeshNode* >& nodeVec, list< SMESH_subMesh* >* meshedSM, SMESH_MesherHelper &quadHelper );
223   void FillSMESH( netgen::OCCGeometry& occgeo, NETGENPlugin_ngMeshInfo& initState, vector< const SMDS_MeshNode* >& nodeVec, SMESH_MesherHelper &quadHelper, SMESH_Comment& comment );
224   ///// End definition methods to rewrite function
225   
226   enum DIM {
227     D1 = 1,
228     D2,
229     D3
230   };       
231   
232   bool Compute();
233   bool Compute( NETGENPlugin_NetgenLibWrapper& ngLib, vector< const SMDS_MeshNode* >& nodeVec, bool write2SMESH, DIM dim );
234
235   bool Evaluate(MapShapeNbElems& aResMap);
236
237   double GetProgress(const SMESH_Algo* holder,
238                      const int *       algoProgressTic,
239                      const double *    algoProgress) const;
240
241   static void PrepareOCCgeometry(netgen::OCCGeometry&          occgeom,
242                                  const TopoDS_Shape&           shape,
243                                  SMESH_Mesh&                   mesh,
244                                  std::list< SMESH_subMesh* > * meshedSM=0,
245                                  NETGENPlugin_Internals*       internalShapes=0);
246
247   static double GetDefaultMinSize(const TopoDS_Shape& shape,
248                                   const double        maxSize);
249
250   static void RestrictLocalSize(netgen::Mesh& ngMesh,
251                                 const gp_XYZ& p,
252                                 double        size,
253                                 const bool    overrideMinH=true);
254
255   static int FillSMesh(const netgen::OCCGeometry&          occgeom,
256                        netgen::Mesh&                       ngMesh,
257                        const NETGENPlugin_ngMeshInfo&      initState,
258                        SMESH_Mesh&                         sMesh,
259                        std::vector<const SMDS_MeshNode*>&  nodeVec,
260                        SMESH_Comment&                      comment,
261                        SMESH_MesherHelper*                 quadHelper=0);
262
263   bool FillNgMesh(netgen::OCCGeometry&                occgeom,
264                   netgen::Mesh&                       ngMesh,
265                   std::vector<const SMDS_MeshNode*>&  nodeVec,
266                   const std::list< SMESH_subMesh* > & meshedSM,
267                   SMESH_MesherHelper*                 quadHelper=0,
268                   SMESH_ProxyMesh::Ptr                proxyMesh=SMESH_ProxyMesh::Ptr());
269
270   static void FixIntFaces(const netgen::OCCGeometry& occgeom,
271                           netgen::Mesh&              ngMesh,
272                           NETGENPlugin_Internals&    internalShapes);
273
274   static bool FixFaceMesh(const netgen::OCCGeometry& occgeom,
275                           netgen::Mesh&              ngMesh,
276                           const int                  faceID);
277
278   static void AddIntVerticesInFaces(const netgen::OCCGeometry&          occgeom,
279                                     netgen::Mesh&                       ngMesh,
280                                     std::vector<const SMDS_MeshNode*>&  nodeVec,
281                                     NETGENPlugin_Internals&             internalShapes);
282
283   static void AddIntVerticesInSolids(const netgen::OCCGeometry&         occgeom,
284                                     netgen::Mesh&                       ngMesh,
285                                     std::vector<const SMDS_MeshNode*>&  nodeVec,
286                                     NETGENPlugin_Internals&             internalShapes);
287
288   static SMESH_ComputeErrorPtr
289     AddSegmentsToMesh(netgen::Mesh&                         ngMesh,
290                       netgen::OCCGeometry&                  geom,
291                       const TSideVector&                    wires,
292                       SMESH_MesherHelper&                   helper,
293                       std::vector< const SMDS_MeshNode* > & nodeVec,
294                       const bool                            overrideMinH=true);
295
296   void SetDefaultParameters();
297
298   static SMESH_ComputeErrorPtr ReadErrors(const std::vector< const SMDS_MeshNode* >& nodeVec);
299
300
301   static void toPython( const netgen::Mesh* ngMesh ); // debug
302
303  private:
304
305   bool Compute1D( NETGENPlugin_NetgenLibWrapper& ngLib, netgen::OCCGeometry& occgeo );
306
307   bool Compute2D( NETGENPlugin_NetgenLibWrapper& ngLib, netgen::OCCGeometry& occgeo,
308                   netgen::MeshingParameters &mparams, list< SMESH_subMesh* >* meshedSM, 
309                   NETGENPlugin_ngMeshInfo& initState, NETGENPlugin_Internals* internals, 
310                   vector< const SMDS_MeshNode* >& nodeVec, SMESH_Comment& comment, DIM dim );
311                   
312   bool Compute3D( NETGENPlugin_NetgenLibWrapper& ngLib, netgen::OCCGeometry& occgeo,
313                   netgen::MeshingParameters &mparams, list< SMESH_subMesh* >* meshedSM, 
314                   NETGENPlugin_ngMeshInfo& initState, NETGENPlugin_Internals* internals, 
315                   vector< const SMDS_MeshNode* >& nodeVec, SMESH_MesherHelper &quadHelper, 
316                   SMESH_Comment& comment);
317
318   SMESH_Mesh*          _mesh;
319   const TopoDS_Shape&  _shape;
320   bool                 _isVolume;
321   bool                 _optimize;
322   int                  _fineness;
323   bool                 _isViscousLayers2D;
324   double               _chordalError;
325   netgen::Mesh*        _ngMesh;
326   netgen::OCCGeometry* _occgeom;
327
328   int                  _curShapeIndex;
329   volatile int         _progressTic;
330   volatile double      _ticTime; // normalized [0,1] compute time per a SMESH_Algo::_progressTic
331   volatile double      _totalTime;
332
333   const NETGENPlugin_SimpleHypothesis_2D * _simpleHyp;
334   const StdMeshers_ViscousLayers*   _viscousLayersHyp;
335
336   // a pointer to NETGENPlugin_Mesher* field of the holder, that will be
337   // nullified at destruction of this
338   NETGENPlugin_Mesher ** _ptrToMe;
339 };
340
341 //=============================================================================
342 /*!
343  * \brief Container of info needed to solve problems with internal shapes.
344  *
345  * Issue 0020676. It is made up as a class to be ready to extract from NETGEN
346  * and put in SMESH as soon as the same solution is needed somewhere else.
347  * The approach is to precompute internal edges in 2D and internal faces in 3D
348  * and put their mesh correctly (twice) into netgen mesh.
349  * In 2D, this class finds internal edges in faces and their vertices.
350  * In 3D, it additionally finds internal faces, their edges shared with other faces,
351  * and their vertices shared by several internal edges. Nodes built on the found
352  * shapes and mesh faces built on the found internal faces are to be doubled in
353  * netgen mesh to emulate a "crack"
354  *
355  * For internal faces a more simple solution is found, which is just to duplicate
356  * mesh faces on internal geom faces without modeling a "real crack". For this
357  * reason findBorderElements() is no more used anywhere.
358  */
359 //=============================================================================
360
361 class NETGENPLUGIN_EXPORT NETGENPlugin_Internals
362 {
363   SMESH_Mesh&       _mesh;
364   bool              _is3D;
365   //2D
366   std::map<int,int> _e2face;//!<edges and their vertices in faces where they are TopAbs_INTERNAL
367   std::map<int,std::list<int> > _f2v;//!<faces with internal vertices
368   // 3D
369   std::set<int>     _intShapes;
370   std::set<int>     _borderFaces; //!< non-internal faces sharing the internal edge
371   std::map<int,std::list<int> > _s2v;//!<solids with internal vertices
372
373 public:
374   NETGENPlugin_Internals( SMESH_Mesh& mesh, const TopoDS_Shape& shape, bool is3D );
375
376   SMESH_Mesh& getMesh() const;
377
378   bool isShapeToPrecompute(const TopoDS_Shape& s);
379
380   // 2D meshing
381   // edges
382   bool hasInternalEdges() const { return !_e2face.empty(); }
383   bool isInternalEdge( int id ) const { return _e2face.count( id ); }
384   const std::map<int,int>& getEdgesAndVerticesWithFaces() const { return _e2face; }
385   void getInternalEdges( TopTools_IndexedMapOfShape&  fmap,
386                          TopTools_IndexedMapOfShape&  emap,
387                          TopTools_IndexedMapOfShape&  vmap,
388                          std::list< SMESH_subMesh* > smToPrecompute[]);
389   // vertices
390   bool hasInternalVertexInFace() const { return !_f2v.empty(); }
391   const std::map<int,std::list<int> >& getFacesWithVertices() const { return _f2v; }
392
393   // 3D meshing
394   // faces
395   bool hasInternalFaces() const { return !_intShapes.empty(); }
396   bool isInternalShape( int id ) const { return _intShapes.count( id ); }
397   void findBorderElements( std::set< const SMDS_MeshElement*, TIDCompare > & borderElems );
398   bool isBorderFace( int faceID ) const { return _borderFaces.count( faceID ); }
399   void getInternalFaces( TopTools_IndexedMapOfShape&  fmap,
400                          TopTools_IndexedMapOfShape&  emap,
401                          std::list< SMESH_subMesh* >& facesSM,
402                          std::list< SMESH_subMesh* >& boundarySM);
403   // vertices
404   bool hasInternalVertexInSolid() const { return !_s2v.empty(); }
405   bool hasInternalVertexInSolid(int soID ) const { return _s2v.count(soID); }
406   const std::map<int,std::list<int> >& getSolidsWithVertices() const { return _s2v; }
407
408
409 };
410
411 #endif