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