]> SALOME platform Git repositories - plugins/netgenplugin.git/blob - src/NETGENPlugin/NETGENPlugin_NETGEN_2D_ONLY.cxx
Salome HOME
partial work for netgen2d in run_mesher + corrections for netgen3d nodeVec + restorin...
[plugins/netgenplugin.git] / src / NETGENPlugin / NETGENPlugin_NETGEN_2D_ONLY.cxx
1 // Copyright (C) 2007-2022  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, or (at your option) any later version.
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 #include "NETGENPlugin_Provider.hxx"
29 #include "netgen_param.hxx"
30
31 #include <SMDS_MeshElement.hxx>
32 #include <SMDS_MeshNode.hxx>
33 #include <SMESHDS_Mesh.hxx>
34 #include <SMESH_Comment.hxx>
35 #include <SMESH_Gen.hxx>
36 #include <SMESH_Mesh.hxx>
37 #include <SMESH_MesherHelper.hxx>
38 #include <SMESH_subMesh.hxx>
39 #include <StdMeshers_FaceSide.hxx>
40 #include <StdMeshers_LengthFromEdges.hxx>
41 #include <StdMeshers_MaxElementArea.hxx>
42 #include <StdMeshers_QuadranglePreference.hxx>
43 #include <StdMeshers_ViscousLayers2D.hxx>
44 #include "DriverStep.hxx"
45 #include "DriverMesh.hxx"
46
47
48 #include <Precision.hxx>
49 #include <Standard_ErrorHandler.hxx>
50 #include <Standard_Failure.hxx>
51
52 #include <utilities.h>
53
54 #include <list>
55 #include <vector>
56 #include <limits>
57
58 #include <cstdlib>
59 #include <boost/filesystem.hpp>
60 namespace fs = boost::filesystem;
61 /*
62   Netgen include files
63 */
64 namespace nglib {
65 #include <nglib.h>
66 }
67 #ifndef OCCGEOMETRY
68 #define OCCGEOMETRY
69 #endif
70 #include <occgeom.hpp>
71 #include <meshing.hpp>
72 //#include <meshtype.hpp>
73 namespace netgen {
74   NETGENPLUGIN_DLL_HEADER
75   extern MeshingParameters mparam;
76 #ifdef NETGEN_V5
77   extern void OCCSetLocalMeshSize(OCCGeometry & geom, Mesh & mesh);
78 #endif
79 }
80
81 using namespace std;
82 using namespace netgen;
83 using namespace nglib;
84
85
86 //=============================================================================
87 /*!
88  *
89  */
90 //=============================================================================
91
92 NETGENPlugin_NETGEN_2D_ONLY::NETGENPlugin_NETGEN_2D_ONLY(int        hypId,
93                                                          SMESH_Gen* gen)
94   : SMESH_2D_Algo(hypId, gen)
95 {
96   _name = "NETGEN_2D_ONLY";
97
98   _shapeType = (1 << TopAbs_FACE);// 1 bit /shape type
99   _onlyUnaryInput = false; // treat all FACEs at once
100
101   _compatibleHypothesis.push_back("MaxElementArea");
102   _compatibleHypothesis.push_back("LengthFromEdges");
103   _compatibleHypothesis.push_back("QuadranglePreference");
104   _compatibleHypothesis.push_back("NETGEN_Parameters_2D");
105   _compatibleHypothesis.push_back("ViscousLayers2D");
106
107   _hypMaxElementArea       = 0;
108   _hypLengthFromEdges      = 0;
109   _hypQuadranglePreference = 0;
110   _hypParameters           = 0;
111 }
112
113 //=============================================================================
114 /*!
115  *
116  */
117 //=============================================================================
118
119 NETGENPlugin_NETGEN_2D_ONLY::~NETGENPlugin_NETGEN_2D_ONLY()
120 {
121   //MESSAGE("NETGENPlugin_NETGEN_2D_ONLY::~NETGENPlugin_NETGEN_2D_ONLY");
122 }
123
124 //=============================================================================
125 /*!
126  *
127  */
128 //=============================================================================
129
130 bool NETGENPlugin_NETGEN_2D_ONLY::CheckHypothesis (SMESH_Mesh&         aMesh,
131                                                    const TopoDS_Shape& aShape,
132                                                    Hypothesis_Status&  aStatus)
133 {
134   _hypMaxElementArea = 0;
135   _hypLengthFromEdges = 0;
136   _hypQuadranglePreference = 0;
137   _hypParameters = 0;
138   _progressByTic = -1;
139
140
141   const list<const SMESHDS_Hypothesis*>& hyps = GetUsedHypothesis(aMesh, aShape, false);
142
143   if (hyps.empty())
144   {
145     aStatus = HYP_OK; //SMESH_Hypothesis::HYP_MISSING;
146     return true;  // (PAL13464) can work with no hypothesis, LengthFromEdges is default one
147   }
148
149   aStatus = HYP_MISSING;
150
151   bool hasVL = false;
152   list<const SMESHDS_Hypothesis*>::const_iterator ith;
153   for (ith = hyps.begin(); ith != hyps.end(); ++ith )
154   {
155     const SMESHDS_Hypothesis* hyp = (*ith);
156
157     string hypName = hyp->GetName();
158
159     if      ( hypName == "MaxElementArea")
160       _hypMaxElementArea = static_cast<const StdMeshers_MaxElementArea*> (hyp);
161     else if ( hypName == "LengthFromEdges" )
162       _hypLengthFromEdges = static_cast<const StdMeshers_LengthFromEdges*> (hyp);
163     else if ( hypName == "QuadranglePreference" )
164       _hypQuadranglePreference = static_cast<const StdMeshers_QuadranglePreference*>(hyp);
165     else if ( hypName == "NETGEN_Parameters_2D" )
166       _hypParameters = static_cast<const NETGENPlugin_Hypothesis_2D*>(hyp);
167     else if ( hypName == StdMeshers_ViscousLayers2D::GetHypType() )
168       hasVL = true;
169     else {
170       aStatus = HYP_INCOMPATIBLE;
171       return false;
172     }
173   }
174
175   int nbHyps = bool(_hypMaxElementArea) + bool(_hypLengthFromEdges) + bool(_hypParameters );
176   if ( nbHyps > 1 )
177     aStatus = HYP_CONCURRENT;
178   else if ( hasVL )
179     error( StdMeshers_ViscousLayers2D::CheckHypothesis( aMesh, aShape, aStatus ));
180   else
181     aStatus = HYP_OK;
182
183   if ( aStatus == HYP_OK && _hypParameters && _hypQuadranglePreference )
184   {
185     aStatus = HYP_INCOMPAT_HYPS;
186     return error(SMESH_Comment("\"") << _hypQuadranglePreference->GetName()
187                  << "\" and \"" << _hypParameters->GetName()
188                  << "\" are incompatible hypotheses");
189   }
190
191   return ( aStatus == HYP_OK );
192 }
193
194 // namespace
195 // {
196 //   void limitSize( netgen::Mesh* ngMesh,
197 //                   const double  maxh )
198 //   {
199 //     // get bnd box
200 //     netgen::Point3d pmin, pmax;
201 //     ngMesh->GetBox( pmin, pmax, 0 );
202 //     const double dx = pmax.X() - pmin.X();
203 //     const double dy = pmax.Y() - pmin.Y();
204 //     const double dz = pmax.Z() - pmin.Z();
205
206 //     const int nbX = Max( 2, int( dx / maxh * 3 ));
207 //     const int nbY = Max( 2, int( dy / maxh * 3 ));
208 //     const int nbZ = Max( 2, int( dz / maxh * 3 ));
209
210 //     if ( ! & ngMesh->LocalHFunction() )
211 //       ngMesh->SetLocalH( pmin, pmax, 0.1 );
212
213 //     netgen::Point3d p;
214 //     for ( int i = 0; i <= nbX; ++i )
215 //     {
216 //       p.X() = pmin.X() +  i * dx / nbX;
217 //       for ( int j = 0; j <= nbY; ++j )
218 //       {
219 //         p.Y() = pmin.Y() +  j * dy / nbY;
220 //         for ( int k = 0; k <= nbZ; ++k )
221 //         {
222 //           p.Z() = pmin.Z() +  k * dz / nbZ;
223 //           ngMesh->RestrictLocalH( p, maxh );
224 //         }
225 //       }
226 //     }
227 //   }
228 // }
229
230
231 // write in a binary file the orientation for each 2D element of the mesh
232 void NETGENPlugin_NETGEN_2D_ONLY::exportElementOrientation(SMESH_Mesh& aMesh,
233                                                            const TopoDS_Shape& aShape,
234                                                            netgen_params& aParams,
235                                                            const std::string output_file)
236 {
237   std::map<vtkIdType, bool> elemOrientation;
238
239   SMESH_ProxyMesh::Ptr proxyMesh( new SMESH_ProxyMesh( aMesh ));
240   for ( TopExp_Explorer exEd( aShape, TopAbs_EDGE ); exEd.More(); exEd.Next())
241   {
242     const TopoDS_Shape& aShapeEdge = exEd.Current();
243     const SMESHDS_SubMesh * aSubMeshDSEdge = proxyMesh->GetSubMesh( aShapeEdge );
244     if ( !aSubMeshDSEdge ) continue;
245
246     SMDS_ElemIteratorPtr iteratorElem = aSubMeshDSEdge->GetElements();
247     while ( iteratorElem->more() ) // loop on elements on a geom face
248     {
249       const SMDS_MeshElement* elem = iteratorElem->next();
250       elemOrientation[elem->GetID()] = aShapeEdge.Orientation() == TopAbs_INTERNAL;
251     }
252   }
253
254   std::ofstream df(output_file, ios::out|ios::binary);
255   int size=elemOrientation.size();
256
257   df.write((char*)&size, sizeof(int));
258   for(auto const& [id, orient]:elemOrientation){
259     df.write((char*)&id, sizeof(vtkIdType));
260     df.write((char*)&orient, sizeof(bool));
261   }
262   df.close();
263 }
264
265 void NETGENPlugin_NETGEN_2D_ONLY::FillParameters(const NETGENPlugin_Hypothesis* hyp, netgen_params &aParams)
266 {
267   //TODO: factorize code with the one from NETGEN3D
268   // Move in netgen_param ?
269   aParams.maxh               = hyp->GetMaxSize();
270   aParams.minh               = hyp->GetMinSize();
271   aParams.segmentsperedge    = hyp->GetNbSegPerEdge();
272   aParams.grading            = hyp->GetGrowthRate();
273   aParams.curvaturesafety    = hyp->GetNbSegPerRadius();
274   aParams.secondorder        = hyp->GetSecondOrder() ? 1 : 0;
275   aParams.quad               = hyp->GetQuadAllowed() ? 1 : 0;
276   aParams.optimize           = hyp->GetOptimize();
277   aParams.fineness           = hyp->GetFineness();
278   aParams.uselocalh          = hyp->GetSurfaceCurvature();
279   aParams.merge_solids       = hyp->GetFuseEdges();
280   aParams.chordalError       = hyp->GetChordalErrorEnabled() ? hyp->GetChordalError() : -1.;
281   aParams.optsteps2d         = aParams.optimize ? hyp->GetNbSurfOptSteps() : 0;
282   aParams.optsteps3d         = aParams.optimize ? hyp->GetNbVolOptSteps()  : 0;
283   aParams.elsizeweight       = hyp->GetElemSizeWeight();
284   aParams.opterrpow          = hyp->GetWorstElemMeasure();
285   aParams.delaunay           = hyp->GetUseDelauney();
286   aParams.checkoverlap       = hyp->GetCheckOverlapping();
287   aParams.checkchartboundary = hyp->GetCheckChartBoundary();
288 #ifdef NETGEN_V6
289   // std::string
290   aParams.meshsizefilename = hyp->GetMeshSizeFile();
291 #else
292   // const char*
293   aParams.meshsizefilename = hyp->GetMeshSizeFile().empty() ? 0 : hyp->GetMeshSizeFile().c_str();
294 #endif
295 #ifdef NETGEN_V6
296   aParams.closeedgefac = 2;
297 #else
298   aParams.closeedgefac = 0;
299 #endif
300   aParams.has_LengthFromEdges_hyp = _hypLengthFromEdges;
301 }
302 //=============================================================================
303 /*!
304  *Here we are going to use the NETGEN mesher remotely
305  */
306 //=============================================================================
307
308 bool NETGENPlugin_NETGEN_2D_ONLY::RemoteCompute(SMESH_Mesh&         aMesh,
309                                                 const TopoDS_Shape& aShape)
310 {
311     aMesh.Lock();
312   SMESH_Hypothesis::Hypothesis_Status hypStatus;
313   CheckHypothesis(aMesh, aShape, hypStatus);
314
315   // Temporary folder for run
316   fs::path tmp_folder = aMesh.tmp_folder / fs::unique_path(fs::path("Face-%%%%-%%%%"));
317   fs::create_directories(tmp_folder);
318   // Using MESH2D generated after all triangles where created.
319   fs::path mesh_file=aMesh.tmp_folder / fs::path("Mesh1D.med");
320   fs::path element_orientation_file=tmp_folder / fs::path("element_orientation.dat");
321   fs::path new_element_file=tmp_folder / fs::path("new_elements.dat");
322   fs::path tmp_mesh_file=tmp_folder / fs::path("tmp_mesh.med");
323   // TODO: Remove that file we do not use it
324   fs::path output_mesh_file=tmp_folder / fs::path("output_mesh.med");
325   fs::path shape_file=tmp_folder / fs::path("shape.step");
326   fs::path param_file=tmp_folder / fs::path("netgen2d_param.txt");
327   fs::path log_file=tmp_folder / fs::path("run_mesher.log");
328   //TODO: Handle variable mesh_name
329   std::string mesh_name = "Maillage_1";
330
331   //Writing Shape
332   export_shape(shape_file.string(), aShape);
333   //Writing hypo
334   netgen_params aParams;
335   FillParameters(_hypParameters, aParams);
336
337   export_netgen_params(param_file.string(), aParams);
338
339   // Exporting element orientation
340   exportElementOrientation(aMesh, aShape, aParams, element_orientation_file.string());
341
342   aMesh.Unlock();
343   // Calling run_mesher
344   // TODO: check if we need to handle the .exe for windows
345   std::string cmd;
346   fs::path run_mesher_exe =
347     fs::path(std::getenv("NETGENPLUGIN_ROOT_DIR"))/
348     fs::path("bin")/
349     fs::path("salome")/
350     fs::path("run_mesher");
351   cmd = run_mesher_exe.string() +
352                   " NETGEN2D " + mesh_file.string() + " "
353                                + shape_file.string() + " "
354                                + param_file.string() + " "
355                                + element_orientation_file.string() + " "
356                                + new_element_file.string() + " "
357                                + std::to_string(0) + " "
358                                + output_mesh_file.string() +
359                                " >> " + log_file.string();
360
361   std::cout << "Running command: " << std::endl;
362   std::cout << cmd << std::endl;
363
364   // Writing command in log
365   std::ofstream flog(log_file.string());
366   flog << cmd << endl;
367   flog.close();
368
369   // TODO: Replace system by something else to handle redirection for windows
370   int ret = system(cmd.c_str());
371
372   // TODO: better error handling (display log ?)
373   if(ret != 0){
374     // Run crahed
375     //throw Exception("Meshing failed");
376     std::cerr << "Issue with command: " << std::endl;
377     std::cerr << cmd << std::endl;
378     return false;
379   }
380
381     aMesh.Lock();
382   std::ifstream df(new_element_file.string(), ios::binary);
383
384   int Netgen_NbOfNodes;
385   int Netgen_NbOfNodesNew;
386   int Netgen_NbOfTria;
387   double Netgen_point[3];
388   int    Netgen_triangle[3];
389   int nodeID;
390
391   SMESH_MesherHelper helper(aMesh);
392   // This function is necessary so that SetElementOnShape works
393   int _quadraticMesh = helper.IsQuadraticSubMesh(aShape);
394   helper.SetElementsOnShape( true );
395
396   // Number of nodes in intial mesh
397   df.read((char*) &Netgen_NbOfNodes, sizeof(int));
398   // Number of nodes added by netgen
399   df.read((char*) &Netgen_NbOfNodesNew, sizeof(int));
400
401   // Filling nodevec (correspondence netgen numbering mesh numbering)
402   vector< const SMDS_MeshNode* > nodeVec ( Netgen_NbOfNodesNew + 1 );
403   for (int nodeIndex = 1 ; nodeIndex <= Netgen_NbOfNodes; ++nodeIndex )
404   {
405     //Id of the point
406     df.read((char*) &nodeID, sizeof(int));
407     nodeVec.at(nodeIndex) = nullptr;
408     SMDS_NodeIteratorPtr iteratorNode = aMesh.GetMeshDS()->nodesIterator();
409     while(iteratorNode->more()){
410       const SMDS_MeshNode* node = iteratorNode->next();
411       if(node->GetID() == nodeID){
412         nodeVec.at(nodeIndex) = node;
413         break;
414       }
415     }
416     if(nodeVec.at(nodeIndex) == nullptr){
417       std::cout << "Error could not identify id";
418       return false;
419     }
420   }
421
422   // Add new points and update nodeVec
423   for (int nodeIndex = Netgen_NbOfNodes +1 ; nodeIndex <= Netgen_NbOfNodesNew; ++nodeIndex )
424   {
425     df.read((char *) &Netgen_point, sizeof(double)*3);
426
427     nodeVec.at(nodeIndex) = helper.AddNode(Netgen_point[0],
428                                            Netgen_point[1],
429                                            Netgen_point[2]);
430   }
431
432   // Add tetrahedrons
433   df.read((char*) &Netgen_NbOfTria, sizeof(int));
434   for ( int elemIndex = 1; elemIndex <= Netgen_NbOfTria; ++elemIndex )
435   {
436     df.read((char*) &Netgen_triangle, sizeof(int)*3);
437     helper.AddFace (nodeVec.at( Netgen_triangle[0] ),
438                     nodeVec.at( Netgen_triangle[1] ),
439                     nodeVec.at( Netgen_triangle[2] ));
440   }
441   df.close();
442
443   aMesh.Unlock();
444
445   return true;
446 }
447 //=============================================================================
448 /*!
449  *Here we are going to use the NETGEN mesher
450  */
451 //=============================================================================
452
453 bool NETGENPlugin_NETGEN_2D_ONLY::Compute(SMESH_Mesh&         aMesh,
454                                           const TopoDS_Shape& aShape)
455 {
456
457   if(aMesh.IsParallel())
458     return RemoteCompute(aMesh, aShape);
459
460   netgen::multithread.terminate = 0;
461   netgen::multithread.task = "Surface meshing";
462
463   SMESHDS_Mesh* meshDS = aMesh.GetMeshDS();
464   SMESH_MesherHelper helper(aMesh);
465   helper.SetElementsOnShape( true );
466
467   NETGENPlugin_NetgenLibWrapper ngLib;
468   ngLib._isComputeOk = false;
469
470   netgen::Mesh   ngMeshNoLocSize;
471   netgen::Mesh * ngMeshes[2] = { (netgen::Mesh*) ngLib._ngMesh,  & ngMeshNoLocSize };
472   netgen::OCCGeometry occgeoComm;
473
474   // min / max sizes are set as follows:
475   // if ( _hypParameters )
476   //    min and max are defined by the user
477   // else if ( _hypLengthFromEdges )
478   //    min = aMesher.GetDefaultMinSize()
479   //    max = average segment len of a FACE
480   // else if ( _hypMaxElementArea )
481   //    min = aMesher.GetDefaultMinSize()
482   //    max = f( _hypMaxElementArea )
483   // else
484   //    min = aMesher.GetDefaultMinSize()
485   //    max = max segment len of a FACE
486   NETGENPlugin_Mesher aMesher( &aMesh, aShape, /*isVolume=*/false);
487   aMesher.SetParameters( _hypParameters ); // _hypParameters -> netgen::mparam
488   const bool toOptimize = _hypParameters ? _hypParameters->GetOptimize() : true;
489   if ( _hypMaxElementArea )
490   {
491     netgen::mparam.maxh = sqrt( 2. * _hypMaxElementArea->GetMaxArea() / sqrt(3.0) );
492   }
493   if ( _hypQuadranglePreference )
494     netgen::mparam.quad = true;
495
496   // local size is common for all FACEs in aShape?
497   const bool isCommonLocalSize = ( !_hypLengthFromEdges && !_hypMaxElementArea && netgen::mparam.uselocalh );
498   const bool isDefaultHyp = ( !_hypLengthFromEdges && !_hypMaxElementArea && !_hypParameters );
499   aMesh.Unlock();
500
501
502   if ( isCommonLocalSize ) // compute common local size in ngMeshes[0]
503   {
504     //list< SMESH_subMesh* > meshedSM[4]; --> all sub-shapes are added to occgeoComm
505     aMesher.PrepareOCCgeometry( occgeoComm, aShape, aMesh );//, meshedSM );
506
507     // local size set at MESHCONST_ANALYSE step depends on
508     // minh, face_maxh, grading and curvaturesafety; find minh if not set by the user
509     if ( !_hypParameters || netgen::mparam.minh < DBL_MIN )
510     {
511       if ( !_hypParameters )
512         netgen::mparam.maxh = occgeoComm.GetBoundingBox().Diam() / 3.;
513       netgen::mparam.minh = aMesher.GetDefaultMinSize( aShape, netgen::mparam.maxh );
514     }
515     // set local size depending on curvature and NOT closeness of EDGEs
516 #ifdef NETGEN_V6
517     const double factor = 2; //netgen::occparam.resthcloseedgefac;
518 #else
519     const double factor = netgen::occparam.resthcloseedgefac;
520     netgen::occparam.resthcloseedgeenable = false;
521     netgen::occparam.resthcloseedgefac = 1.0 + netgen::mparam.grading;
522 #endif
523     occgeoComm.face_maxh = netgen::mparam.maxh;
524 #ifdef NETGEN_V6
525     netgen::OCCParameters occparam;
526     netgen::OCCSetLocalMeshSize( occgeoComm, *ngMeshes[0], netgen::mparam, occparam );
527 #else
528     aMesh.Lock();
529     netgen::OCCSetLocalMeshSize( occgeoComm, *ngMeshes[0] );
530     aMesh.Unlock();
531 #endif
532     occgeoComm.emap.Clear();
533     occgeoComm.vmap.Clear();
534
535     // set local size according to size of existing segments
536     TopTools_IndexedMapOfShape edgeMap;
537     TopExp::MapShapes( aMesh.GetShapeToMesh(), TopAbs_EDGE, edgeMap );
538     for ( int iE = 1; iE <= edgeMap.Extent(); ++iE )
539     {
540       const TopoDS_Shape& edge = edgeMap( iE );
541       if ( SMESH_Algo::isDegenerated( TopoDS::Edge( edge )))
542         continue;
543       SMESHDS_SubMesh* smDS = meshDS->MeshElements( edge );
544       if ( !smDS ) continue;
545       SMDS_ElemIteratorPtr segIt = smDS->GetElements();
546       while ( segIt->more() )
547       {
548         const SMDS_MeshElement* seg = segIt->next();
549         SMESH_TNodeXYZ n1 = seg->GetNode(0);
550         SMESH_TNodeXYZ n2 = seg->GetNode(1);
551         gp_XYZ p = 0.5 * ( n1 + n2 );
552         netgen::Point3d pi(p.X(), p.Y(), p.Z());
553         ngMeshes[0]->RestrictLocalH( pi, factor * ( n1 - n2 ).Modulus() );
554       }
555     }
556
557     // set local size defined on shapes
558     aMesher.SetLocalSize( occgeoComm, *ngMeshes[0] );
559     aMesher.SetLocalSizeForChordalError( occgeoComm, *ngMeshes[0] );
560     try {
561       ngMeshes[0]->LoadLocalMeshSize( netgen::mparam.meshsizefilename );
562     } catch (NgException & ex) {
563       return error( COMPERR_BAD_PARMETERS, ex.What() );
564     }
565   }
566   netgen::mparam.uselocalh = toOptimize; // restore as it is used at surface optimization
567   // ==================
568   // Loop on all FACEs
569   // ==================
570
571   vector< const SMDS_MeshNode* > nodeVec;
572
573   TopExp_Explorer fExp( aShape, TopAbs_FACE );
574   for ( int iF = 0; fExp.More(); fExp.Next(), ++iF )
575   {
576     TopoDS_Face F = TopoDS::Face( fExp.Current() /*.Oriented( TopAbs_FORWARD )*/);
577     int    faceID = meshDS->ShapeToIndex( F );
578     SMESH_ComputeErrorPtr& faceErr = aMesh.GetSubMesh( F )->GetComputeError();
579
580     _quadraticMesh = helper.IsQuadraticSubMesh( F );
581     const bool ignoreMediumNodes = _quadraticMesh;
582
583     // build viscous layers if required
584     if ( F.Orientation() != TopAbs_FORWARD &&
585          F.Orientation() != TopAbs_REVERSED )
586       F.Orientation( TopAbs_FORWARD ); // avoid pb with TopAbs_INTERNAL
587     SMESH_ProxyMesh::Ptr proxyMesh = StdMeshers_ViscousLayers2D::Compute( aMesh, F );
588     if ( !proxyMesh )
589       continue;
590
591     // ------------------------
592     // get all EDGEs of a FACE
593     // ------------------------
594     TSideVector wires =
595       StdMeshers_FaceSide::GetFaceWires( F, aMesh, ignoreMediumNodes, faceErr, &helper, proxyMesh );
596     if ( faceErr && !faceErr->IsOK() )
597       continue;
598     size_t nbWires = wires.size();
599     if ( nbWires == 0 )
600     {
601       faceErr.reset
602         ( new SMESH_ComputeError
603           ( COMPERR_ALGO_FAILED, "Problem in StdMeshers_FaceSide::GetFaceWires()" ));
604       continue;
605     }
606     if ( wires[0]->NbSegments() < 3 ) // ex: a circle with 2 segments
607     {
608       faceErr.reset
609         ( new SMESH_ComputeError
610           ( COMPERR_BAD_INPUT_MESH, SMESH_Comment("Too few segments: ")<<wires[0]->NbSegments()) );
611       continue;
612     }
613
614     // ----------------------
615     // compute maxh of a FACE
616     // ----------------------
617
618     if ( !_hypParameters )
619     {
620       double edgeLength = 0;
621       if (_hypLengthFromEdges )
622       {
623         // compute edgeLength as an average segment length
624         smIdType nbSegments = 0;
625         for ( size_t iW = 0; iW < nbWires; ++iW )
626         {
627           edgeLength += wires[ iW ]->Length();
628           nbSegments += wires[ iW ]->NbSegments();
629         }
630         if ( nbSegments )
631           edgeLength /= double( nbSegments );
632         netgen::mparam.maxh = edgeLength;
633       }
634       else if ( isDefaultHyp )
635       {
636         // set edgeLength by a longest segment
637         double maxSeg2 = 0;
638         for ( size_t iW = 0; iW < nbWires; ++iW )
639         {
640           const UVPtStructVec& points = wires[ iW ]->GetUVPtStruct();
641           if ( points.empty() )
642             return error( COMPERR_BAD_INPUT_MESH );
643           gp_Pnt pPrev = SMESH_TNodeXYZ( points[0].node );
644           for ( size_t i = 1; i < points.size(); ++i )
645           {
646             gp_Pnt p = SMESH_TNodeXYZ( points[i].node );
647             maxSeg2 = Max( maxSeg2, p.SquareDistance( pPrev ));
648             pPrev = p;
649           }
650         }
651         edgeLength = sqrt( maxSeg2 ) * 1.05;
652         netgen::mparam.maxh = edgeLength;
653       }
654       if ( netgen::mparam.maxh < DBL_MIN )
655         netgen::mparam.maxh = occgeoComm.GetBoundingBox().Diam();
656
657       if ( !isCommonLocalSize )
658       {
659         netgen::mparam.minh = aMesher.GetDefaultMinSize( F, netgen::mparam.maxh );
660       }
661     }
662
663     // prepare occgeom
664     netgen::OCCGeometry occgeom;
665     occgeom.shape = F;
666     occgeom.fmap.Add( F );
667     occgeom.CalcBoundingBox();
668     occgeom.facemeshstatus.SetSize(1);
669     occgeom.facemeshstatus = 0;
670     occgeom.face_maxh_modified.SetSize(1);
671     occgeom.face_maxh_modified = 0;
672     occgeom.face_maxh.SetSize(1);
673     occgeom.face_maxh = netgen::mparam.maxh;
674
675     // -------------------------
676     // Fill netgen mesh
677     // -------------------------
678
679     // MESHCONST_ANALYSE step may lead to a failure, so we make an attempt
680     // w/o MESHCONST_ANALYSE at the second loop
681     int err = 0;
682     enum { LOC_SIZE, NO_LOC_SIZE };
683     int iLoop = isCommonLocalSize ? 0 : 1;
684     for ( ; iLoop < 2; iLoop++ )
685     {
686       //bool isMESHCONST_ANALYSE = false;
687       InitComputeError();
688
689       netgen::Mesh * ngMesh = ngMeshes[ iLoop ];
690       ngMesh->DeleteMesh();
691
692       if ( iLoop == NO_LOC_SIZE )
693       {
694         ngMesh->SetGlobalH ( netgen::mparam.maxh );
695         ngMesh->SetMinimalH( netgen::mparam.minh );
696         Box<3> bb = occgeom.GetBoundingBox();
697         bb.Increase (bb.Diam()/10);
698         ngMesh->SetLocalH (bb.PMin(), bb.PMax(), netgen::mparam.grading);
699         aMesher.SetLocalSize( occgeom, *ngMesh );
700         aMesher.SetLocalSizeForChordalError( occgeoComm, *ngMesh );
701         try {
702           ngMesh->LoadLocalMeshSize( netgen::mparam.meshsizefilename );
703         } catch (NgException & ex) {
704           return error( COMPERR_BAD_PARMETERS, ex.What() );
705         }
706       }
707
708       nodeVec.clear();
709       faceErr = aMesher.AddSegmentsToMesh( *ngMesh, occgeom, wires, helper, nodeVec,
710                                            /*overrideMinH=*/!_hypParameters);
711       if ( faceErr && !faceErr->IsOK() )
712         break;
713
714       //if ( !isCommonLocalSize )
715       //limitSize( ngMesh, netgen::mparam.maxh * 0.8);
716
717       // -------------------------
718       // Generate surface mesh
719       // -------------------------
720
721       const int startWith = MESHCONST_MESHSURFACE;
722       const int endWith   = toOptimize ? MESHCONST_OPTSURFACE : MESHCONST_MESHSURFACE;
723
724       SMESH_Comment str;
725       try {
726         OCC_CATCH_SIGNALS;
727         err = ngLib.GenerateMesh(occgeom, startWith, endWith, ngMesh);
728         if ( netgen::multithread.terminate )
729           return false;
730         if ( err )
731           str << "Error in netgen::OCCGenerateMesh() at " << netgen::multithread.task;
732       }
733       catch (Standard_Failure& ex)
734       {
735         err = 1;
736         str << "Exception in  netgen::OCCGenerateMesh()"
737             << " at " << netgen::multithread.task
738             << ": " << ex.DynamicType()->Name();
739         if ( ex.GetMessageString() && strlen( ex.GetMessageString() ))
740           str << ": " << ex.GetMessageString();
741       }
742       catch (...) {
743         err = 1;
744         str << "Exception in  netgen::OCCGenerateMesh()"
745             << " at " << netgen::multithread.task;
746       }
747       if ( err )
748       {
749         if ( aMesher.FixFaceMesh( occgeom, *ngMesh, 1 ))
750           break;
751         if ( iLoop == LOC_SIZE )
752         {
753           netgen::mparam.minh = netgen::mparam.maxh;
754           netgen::mparam.maxh = 0;
755           for ( size_t iW = 0; iW < wires.size(); ++iW )
756           {
757             StdMeshers_FaceSidePtr wire = wires[ iW ];
758             const vector<UVPtStruct>& uvPtVec = wire->GetUVPtStruct();
759             for ( size_t iP = 1; iP < uvPtVec.size(); ++iP )
760             {
761               SMESH_TNodeXYZ   p( uvPtVec[ iP ].node );
762               netgen::Point3d np( p.X(),p.Y(),p.Z());
763               double segLen = p.Distance( uvPtVec[ iP-1 ].node );
764               double   size = ngMesh->GetH( np );
765               netgen::mparam.minh = Min( netgen::mparam.minh, size );
766              netgen:: mparam.maxh = Max( netgen::mparam.maxh, segLen );
767             }
768           }
769           //cerr << "min " << mparam.minh << " max " << mparam.maxh << endl;
770           netgen::mparam.minh *= 0.9;
771           netgen::mparam.maxh *= 1.1;
772           continue;
773         }
774         else
775         {
776           faceErr.reset( new SMESH_ComputeError( COMPERR_ALGO_FAILED, str ));
777         }
778       }
779
780       // ----------------------------------------------------
781       // Fill the SMESHDS with the generated nodes and faces
782       // ----------------------------------------------------
783
784       int nbNodes = ngMesh->GetNP();
785       int nbFaces = ngMesh->GetNSE();
786
787       int nbInputNodes = (int) nodeVec.size()-1;
788       nodeVec.resize( nbNodes+1, 0 );
789
790       // add nodes
791       for ( int ngID = nbInputNodes + 1; ngID <= nbNodes; ++ngID )
792       {
793         const MeshPoint& ngPoint = ngMesh->Point( ngID );
794         SMDS_MeshNode * node = meshDS->AddNode(ngPoint(0), ngPoint(1), ngPoint(2));
795         nodeVec[ ngID ] = node;
796       }
797
798       // create faces
799       int i,j;
800       vector<const SMDS_MeshNode*> nodes;
801       for ( i = 1; i <= nbFaces ; ++i )
802       {
803         const Element2d& elem = ngMesh->SurfaceElement(i);
804         nodes.resize( elem.GetNP() );
805         for (j=1; j <= elem.GetNP(); ++j)
806         {
807           int pind = elem.PNum(j);
808           if ( pind < 1 )
809             break;
810           nodes[ j-1 ] = nodeVec[ pind ];
811           if ( nodes[ j-1 ]->GetPosition()->GetTypeOfPosition() == SMDS_TOP_3DSPACE )
812           {
813             const PointGeomInfo& pgi = elem.GeomInfoPi(j);
814             meshDS->SetNodeOnFace( nodes[ j-1 ], faceID, pgi.u, pgi.v);
815           }
816         }
817         if ( j > elem.GetNP() )
818         {
819           if ( elem.GetType() == TRIG )
820             helper.AddFace(nodes[0],nodes[1],nodes[2]);
821           else
822             helper.AddFace(nodes[0],nodes[1],nodes[2],nodes[3]);
823         }
824       }
825
826       break;
827     } // two attempts
828   } // loop on FACEs
829
830   return true;
831 }
832
833 void NETGENPlugin_NETGEN_2D_ONLY::CancelCompute()
834 {
835   SMESH_Algo::CancelCompute();
836   netgen::multithread.terminate = 1;
837 }
838
839 //================================================================================
840 /*!
841  * \brief Return progress of Compute() [0.,1]
842  */
843 //================================================================================
844
845 double NETGENPlugin_NETGEN_2D_ONLY::GetProgress() const
846 {
847   return -1;
848   // const char* task1 = "Surface meshing";
849   // //const char* task2 = "Optimizing surface";
850   // double& progress = const_cast<NETGENPlugin_NETGEN_2D_ONLY*>( this )->_progress;
851   // if ( _progressByTic < 0. &&
852   //      strncmp( netgen::multithread.task, task1, 3 ) == 0 )
853   // {
854   //   progress = Min( 0.25, SMESH_Algo::GetProgressByTic() ); // [0, 0.25]
855   // }
856   // else //if ( strncmp( netgen::multithread.task, task2, 3 ) == 0)
857   // {
858   //   if ( _progressByTic < 0 )
859   //   {
860   //     NETGENPlugin_NETGEN_2D_ONLY* me = (NETGENPlugin_NETGEN_2D_ONLY*) this;
861   //     me->_progressByTic = 0.25 / (_progressTic+1);
862   //   }
863   //   const_cast<NETGENPlugin_NETGEN_2D_ONLY*>( this )->_progressTic++;
864   //   progress = Max( progress, _progressByTic * _progressTic );
865   // }
866   // //cout << netgen::multithread.task << " " << _progressTic << endl;
867   // return Min( progress, 0.99 );
868 }
869
870 //=============================================================================
871 /*!
872  *
873  */
874 //=============================================================================
875
876 bool NETGENPlugin_NETGEN_2D_ONLY::Evaluate(SMESH_Mesh& aMesh,
877                                            const TopoDS_Shape& aShape,
878                                            MapShapeNbElems& aResMap)
879 {
880   TopoDS_Face F = TopoDS::Face(aShape);
881   if(F.IsNull())
882     return false;
883
884   // collect info from edges
885   smIdType nb0d = 0, nb1d = 0;
886   bool IsQuadratic = false;
887   bool IsFirst = true;
888   double fullLen = 0.0;
889   TopTools_MapOfShape tmpMap;
890   for (TopExp_Explorer exp(F, TopAbs_EDGE); exp.More(); exp.Next()) {
891     TopoDS_Edge E = TopoDS::Edge(exp.Current());
892     if( tmpMap.Contains(E) )
893       continue;
894     tmpMap.Add(E);
895     SMESH_subMesh *aSubMesh = aMesh.GetSubMesh(exp.Current());
896     MapShapeNbElemsItr anIt = aResMap.find(aSubMesh);
897     if( anIt==aResMap.end() ) {
898       SMESH_subMesh *sm = aMesh.GetSubMesh(F);
899       SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
900       smError.reset( new SMESH_ComputeError(COMPERR_ALGO_FAILED,"Submesh can not be evaluated",this));
901       return false;
902     }
903     std::vector<smIdType> aVec = (*anIt).second;
904     nb0d += aVec[SMDSEntity_Node];
905     nb1d += std::max(aVec[SMDSEntity_Edge],aVec[SMDSEntity_Quad_Edge]);
906     double aLen = SMESH_Algo::EdgeLength(E);
907     fullLen += aLen;
908     if(IsFirst) {
909       IsQuadratic = (aVec[SMDSEntity_Quad_Edge] > aVec[SMDSEntity_Edge]);
910       IsFirst = false;
911     }
912   }
913   tmpMap.Clear();
914
915   // compute edge length
916   double ELen = 0;
917   if (( _hypLengthFromEdges ) || ( !_hypLengthFromEdges && !_hypMaxElementArea )) {
918     if ( nb1d > 0 )
919       ELen = fullLen / double( nb1d );
920   }
921   if ( _hypMaxElementArea ) {
922     double maxArea = _hypMaxElementArea->GetMaxArea();
923     ELen = sqrt(2. * maxArea/sqrt(3.0));
924   }
925   GProp_GProps G;
926   BRepGProp::SurfaceProperties(F,G);
927   double anArea = G.Mass();
928
929   const int hugeNb = numeric_limits<int>::max()/10;
930   if ( anArea / hugeNb > ELen*ELen )
931   {
932     SMESH_subMesh *sm = aMesh.GetSubMesh(F);
933     SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
934     smError.reset( new SMESH_ComputeError(COMPERR_ALGO_FAILED,"Submesh can not be evaluated.\nToo small element length",this));
935     return false;
936   }
937   smIdType nbFaces = (smIdType) ( anArea / ( ELen*ELen*sqrt(3.) / 4 ) );
938   smIdType nbNodes = (smIdType) ( ( nbFaces*3 - (nb1d-1)*2 ) / 6 + 1 );
939   std::vector<smIdType> aVec(SMDSEntity_Last);
940   for(smIdType i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aVec[i]=0;
941   if( IsQuadratic ) {
942     aVec[SMDSEntity_Node] = nbNodes;
943     aVec[SMDSEntity_Quad_Triangle] = nbFaces;
944   }
945   else {
946     aVec[SMDSEntity_Node] = nbNodes;
947     aVec[SMDSEntity_Triangle] = nbFaces;
948   }
949   SMESH_subMesh *sm = aMesh.GetSubMesh(F);
950   aResMap.insert(std::make_pair(sm,aVec));
951
952   return true;
953 }