]> SALOME platform Git repositories - plugins/netgenplugin.git/blob - src/NETGENPlugin/NETGENPlugin_NETGEN_2D_ONLY.cxx
Salome HOME
a735a1fbb9f4f40f198a34ea85fb9edc6c841612
[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
30 #include <SMDS_MeshElement.hxx>
31 #include <SMDS_MeshNode.hxx>
32 #include <SMESHDS_Mesh.hxx>
33 #include <SMESH_Comment.hxx>
34 #include <SMESH_Gen.hxx>
35 #include <SMESH_Mesh.hxx>
36 #include <SMESH_MesherHelper.hxx>
37 #include <SMESH_subMesh.hxx>
38 #include <StdMeshers_FaceSide.hxx>
39 #include <StdMeshers_LengthFromEdges.hxx>
40 #include <StdMeshers_MaxElementArea.hxx>
41 #include <StdMeshers_QuadranglePreference.hxx>
42 #include <StdMeshers_ViscousLayers2D.hxx>
43
44 #include <Precision.hxx>
45 #include <Standard_ErrorHandler.hxx>
46 #include <Standard_Failure.hxx>
47
48 #include <utilities.h>
49
50 #include <list>
51 #include <vector>
52 #include <limits>
53
54 /*
55   Netgen include files
56 */
57 namespace nglib {
58 #include <nglib.h>
59 }
60 #ifndef OCCGEOMETRY
61 #define OCCGEOMETRY
62 #endif
63 #include <occgeom.hpp>
64 #include <meshing.hpp>
65 //#include <meshtype.hpp>
66 namespace netgen {
67   NETGENPLUGIN_DLL_HEADER
68   extern MeshingParameters mparam;
69 #ifdef NETGEN_V5
70   extern void OCCSetLocalMeshSize(OCCGeometry & geom, Mesh & mesh);
71 #endif
72 }
73
74 using namespace std;
75 using namespace netgen;
76 using namespace nglib;
77
78 //=============================================================================
79 /*!
80  *
81  */
82 //=============================================================================
83
84 NETGENPlugin_NETGEN_2D_ONLY::NETGENPlugin_NETGEN_2D_ONLY(int        hypId,
85                                                          SMESH_Gen* gen)
86   : SMESH_2D_Algo(hypId, gen)
87 {
88   _name = "NETGEN_2D_ONLY";
89
90   _shapeType = (1 << TopAbs_FACE);// 1 bit /shape type
91   _onlyUnaryInput = false; // treat all FACEs at once
92
93   _compatibleHypothesis.push_back("MaxElementArea");
94   _compatibleHypothesis.push_back("LengthFromEdges");
95   _compatibleHypothesis.push_back("QuadranglePreference");
96   _compatibleHypothesis.push_back("NETGEN_Parameters_2D");
97   _compatibleHypothesis.push_back("ViscousLayers2D");
98
99   _hypMaxElementArea       = 0;
100   _hypLengthFromEdges      = 0;
101   _hypQuadranglePreference = 0;
102   _hypParameters           = 0;
103 }
104
105 //=============================================================================
106 /*!
107  *
108  */
109 //=============================================================================
110
111 NETGENPlugin_NETGEN_2D_ONLY::~NETGENPlugin_NETGEN_2D_ONLY()
112 {
113   //MESSAGE("NETGENPlugin_NETGEN_2D_ONLY::~NETGENPlugin_NETGEN_2D_ONLY");
114 }
115
116 //=============================================================================
117 /*!
118  *
119  */
120 //=============================================================================
121
122 bool NETGENPlugin_NETGEN_2D_ONLY::CheckHypothesis (SMESH_Mesh&         aMesh,
123                                                    const TopoDS_Shape& aShape,
124                                                    Hypothesis_Status&  aStatus)
125 {
126   _hypMaxElementArea = 0;
127   _hypLengthFromEdges = 0;
128   _hypQuadranglePreference = 0;
129   _hypParameters = 0;
130   _progressByTic = -1;
131
132
133   const list<const SMESHDS_Hypothesis*>& hyps = GetUsedHypothesis(aMesh, aShape, false);
134
135   if (hyps.empty())
136   {
137     aStatus = HYP_OK; //SMESH_Hypothesis::HYP_MISSING;
138     return true;  // (PAL13464) can work with no hypothesis, LengthFromEdges is default one
139   }
140
141   aStatus = HYP_MISSING;
142
143   bool hasVL = false;
144   list<const SMESHDS_Hypothesis*>::const_iterator ith;
145   for (ith = hyps.begin(); ith != hyps.end(); ++ith )
146   {
147     const SMESHDS_Hypothesis* hyp = (*ith);
148
149     string hypName = hyp->GetName();
150
151     if      ( hypName == "MaxElementArea")
152       _hypMaxElementArea = static_cast<const StdMeshers_MaxElementArea*> (hyp);
153     else if ( hypName == "LengthFromEdges" )
154       _hypLengthFromEdges = static_cast<const StdMeshers_LengthFromEdges*> (hyp);
155     else if ( hypName == "QuadranglePreference" )
156       _hypQuadranglePreference = static_cast<const StdMeshers_QuadranglePreference*>(hyp);
157     else if ( hypName == "NETGEN_Parameters_2D" )
158       _hypParameters = static_cast<const NETGENPlugin_Hypothesis_2D*>(hyp);
159     else if ( hypName == StdMeshers_ViscousLayers2D::GetHypType() )
160       hasVL = true;
161     else {
162       aStatus = HYP_INCOMPATIBLE;
163       return false;
164     }
165   }
166
167   int nbHyps = bool(_hypMaxElementArea) + bool(_hypLengthFromEdges) + bool(_hypParameters );
168   if ( nbHyps > 1 )
169     aStatus = HYP_CONCURRENT;
170   else if ( hasVL )
171     error( StdMeshers_ViscousLayers2D::CheckHypothesis( aMesh, aShape, aStatus ));
172   else
173     aStatus = HYP_OK;
174
175   if ( aStatus == HYP_OK && _hypParameters && _hypQuadranglePreference )
176   {
177     aStatus = HYP_INCOMPAT_HYPS;
178     return error(SMESH_Comment("\"") << _hypQuadranglePreference->GetName()
179                  << "\" and \"" << _hypParameters->GetName()
180                  << "\" are incompatible hypotheses");
181   }
182
183   return ( aStatus == HYP_OK );
184 }
185
186 // namespace
187 // {
188 //   void limitSize( netgen::Mesh* ngMesh,
189 //                   const double  maxh )
190 //   {
191 //     // get bnd box
192 //     netgen::Point3d pmin, pmax;
193 //     ngMesh->GetBox( pmin, pmax, 0 );
194 //     const double dx = pmax.X() - pmin.X();
195 //     const double dy = pmax.Y() - pmin.Y();
196 //     const double dz = pmax.Z() - pmin.Z();
197
198 //     const int nbX = Max( 2, int( dx / maxh * 3 ));
199 //     const int nbY = Max( 2, int( dy / maxh * 3 ));
200 //     const int nbZ = Max( 2, int( dz / maxh * 3 ));
201
202 //     if ( ! & ngMesh->LocalHFunction() )
203 //       ngMesh->SetLocalH( pmin, pmax, 0.1 );
204
205 //     netgen::Point3d p;
206 //     for ( int i = 0; i <= nbX; ++i )
207 //     {
208 //       p.X() = pmin.X() +  i * dx / nbX;
209 //       for ( int j = 0; j <= nbY; ++j )
210 //       {
211 //         p.Y() = pmin.Y() +  j * dy / nbY;
212 //         for ( int k = 0; k <= nbZ; ++k )
213 //         {
214 //           p.Z() = pmin.Z() +  k * dz / nbZ;
215 //           ngMesh->RestrictLocalH( p, maxh );
216 //         }
217 //       }
218 //     }
219 //   }
220 // }
221
222 //=============================================================================
223 /*!
224  *Here we are going to use the NETGEN mesher
225  */
226 //=============================================================================
227
228 bool NETGENPlugin_NETGEN_2D_ONLY::Compute(SMESH_Mesh&         aMesh,
229                                           const TopoDS_Shape& aShape)
230 {
231   aMesh.Lock();
232   SMESH_Hypothesis::Hypothesis_Status hypStatus;
233   this->CheckHypothesis(aMesh, aShape, hypStatus);
234   aMesh.Unlock();
235
236   netgen::multithread.terminate = 0;
237   //netgen::multithread.task = "Surface meshing";
238
239   SMESHDS_Mesh* meshDS = aMesh.GetMeshDS();
240   SMESH_MesherHelper helper(aMesh);
241   helper.SetElementsOnShape( true );
242
243   NETGENPlugin_NetgenLibWrapper *ngLib;
244   int id_ngLib = nglib_provider.take(&ngLib);
245   ngLib->_isComputeOk = false;
246
247   netgen::Mesh   ngMeshNoLocSize;
248   netgen::Mesh * ngMeshes[2] = { (netgen::Mesh*) ngLib->_ngMesh,  & ngMeshNoLocSize };
249   netgen::OCCGeometry *occgeoComm;
250   int id_occgeoComm = occgeom_provider.take(&occgeoComm);
251
252   // min / max sizes are set as follows:
253   // if ( _hypParameters )
254   //    min and max are defined by the user
255   // else if ( _hypLengthFromEdges )
256   //    min = aMesher.GetDefaultMinSize()
257   //    max = average segment len of a FACE
258   // else if ( _hypMaxElementArea )
259   //    min = aMesher.GetDefaultMinSize()
260   //    max = f( _hypMaxElementArea )
261   // else
262   //    min = aMesher.GetDefaultMinSize()
263   //    max = max segment len of a FACE
264   NETGENPlugin_Mesher aMesher( &aMesh, aShape, /*isVolume=*/false);
265   aMesher.SetParameters( _hypParameters ); // _hypParameters -> netgen::mparam
266   const bool toOptimize = _hypParameters ? _hypParameters->GetOptimize() : true;
267   if ( _hypMaxElementArea )
268   {
269     netgen::mparam.maxh = sqrt( 2. * _hypMaxElementArea->GetMaxArea() / sqrt(3.0) );
270   }
271   if ( _hypQuadranglePreference )
272     netgen::mparam.quad = true;
273
274   // local size is common for all FACEs in aShape?
275   const bool isCommonLocalSize = ( !_hypLengthFromEdges && !_hypMaxElementArea && netgen::mparam.uselocalh );
276   const bool isDefaultHyp = ( !_hypLengthFromEdges && !_hypMaxElementArea && !_hypParameters );
277
278   if ( isCommonLocalSize ) // compute common local size in ngMeshes[0]
279   {
280     //list< SMESH_subMesh* > meshedSM[4]; --> all sub-shapes are added to occgeoComm
281     aMesher.PrepareOCCgeometry( *occgeoComm, aShape, aMesh );//, meshedSM );
282
283     // local size set at MESHCONST_ANALYSE step depends on
284     // minh, face_maxh, grading and curvaturesafety; find minh if not set by the user
285     if ( !_hypParameters || netgen::mparam.minh < DBL_MIN )
286     {
287       if ( !_hypParameters )
288         netgen::mparam.maxh = occgeoComm->GetBoundingBox().Diam() / 3.;
289       netgen::mparam.minh = aMesher.GetDefaultMinSize( aShape, netgen::mparam.maxh );
290     }
291     // set local size depending on curvature and NOT closeness of EDGEs
292 #ifdef NETGEN_V6
293     const double factor = 2; //netgen::occparam.resthcloseedgefac;
294 #else
295     const double factor = netgen::occparam.resthcloseedgefac;
296     netgen::occparam.resthcloseedgeenable = false;
297     netgen::occparam.resthcloseedgefac = 1.0 + netgen::mparam.grading;
298 #endif
299     occgeoComm->face_maxh = netgen::mparam.maxh;
300 #ifdef NETGEN_V6
301     netgen::OCCParameters occparam;
302     netgen::OCCSetLocalMeshSize( *occgeoComm, *ngMeshes[0], netgen::mparam, occparam );
303 #else
304     netgen::OCCSetLocalMeshSize( *occgeoComm, *ngMeshes[0] );
305 #endif
306     occgeoComm->emap.Clear();
307     occgeoComm->vmap.Clear();
308
309     // set local size according to size of existing segments
310     TopTools_IndexedMapOfShape edgeMap;
311     TopExp::MapShapes( aMesh.GetShapeToMesh(), TopAbs_EDGE, edgeMap );
312     for ( int iE = 1; iE <= edgeMap.Extent(); ++iE )
313     {
314       const TopoDS_Shape& edge = edgeMap( iE );
315       if ( SMESH_Algo::isDegenerated( TopoDS::Edge( edge )))
316         continue;
317       SMESHDS_SubMesh* smDS = meshDS->MeshElements( edge );
318       if ( !smDS ) continue;
319       SMDS_ElemIteratorPtr segIt = smDS->GetElements();
320       while ( segIt->more() )
321       {
322         const SMDS_MeshElement* seg = segIt->next();
323         SMESH_TNodeXYZ n1 = seg->GetNode(0);
324         SMESH_TNodeXYZ n2 = seg->GetNode(1);
325         gp_XYZ p = 0.5 * ( n1 + n2 );
326         netgen::Point3d pi(p.X(), p.Y(), p.Z());
327         ngMeshes[0]->RestrictLocalH( pi, factor * ( n1 - n2 ).Modulus() );
328       }
329     }
330
331     // set local size defined on shapes
332     aMesher.SetLocalSize( *occgeoComm, *ngMeshes[0] );
333     aMesher.SetLocalSizeForChordalError( *occgeoComm, *ngMeshes[0] );
334     try {
335       ngMeshes[0]->LoadLocalMeshSize( mparam.meshsizefilename );
336     } catch (NgException & ex) {
337       return error( COMPERR_BAD_PARMETERS, ex.What() );
338     }
339   }
340   netgen::mparam.uselocalh = toOptimize; // restore as it is used at surface optimization
341   // ==================
342   // Loop on all FACEs
343   // ==================
344
345   vector< const SMDS_MeshNode* > nodeVec;
346
347   TopExp_Explorer fExp( aShape, TopAbs_FACE );
348   for ( int iF = 0; fExp.More(); fExp.Next(), ++iF )
349   {
350     TopoDS_Face F = TopoDS::Face( fExp.Current() /*.Oriented( TopAbs_FORWARD )*/);
351     int    faceID = meshDS->ShapeToIndex( F );
352     SMESH_ComputeErrorPtr& faceErr = aMesh.GetSubMesh( F )->GetComputeError();
353
354     _quadraticMesh = helper.IsQuadraticSubMesh( F );
355     const bool ignoreMediumNodes = _quadraticMesh;
356
357     // build viscous layers if required
358     if ( F.Orientation() != TopAbs_FORWARD &&
359          F.Orientation() != TopAbs_REVERSED )
360       F.Orientation( TopAbs_FORWARD ); // avoid pb with TopAbs_INTERNAL
361     SMESH_ProxyMesh::Ptr proxyMesh = StdMeshers_ViscousLayers2D::Compute( aMesh, F );
362     if ( !proxyMesh )
363       continue;
364
365     // ------------------------
366     // get all EDGEs of a FACE
367     // ------------------------
368     TSideVector wires =
369       StdMeshers_FaceSide::GetFaceWires( F, aMesh, ignoreMediumNodes, faceErr, &helper, proxyMesh );
370     if ( faceErr && !faceErr->IsOK() )
371       continue;
372     size_t nbWires = wires.size();
373     if ( nbWires == 0 )
374     {
375       faceErr.reset
376         ( new SMESH_ComputeError
377           ( COMPERR_ALGO_FAILED, "Problem in StdMeshers_FaceSide::GetFaceWires()" ));
378       continue;
379     }
380     if ( wires[0]->NbSegments() < 3 ) // ex: a circle with 2 segments
381     {
382       faceErr.reset
383         ( new SMESH_ComputeError
384           ( COMPERR_BAD_INPUT_MESH, SMESH_Comment("Too few segments: ")<<wires[0]->NbSegments()) );
385       continue;
386     }
387
388     // ----------------------
389     // compute maxh of a FACE
390     // ----------------------
391
392     if ( !_hypParameters )
393     {
394       double edgeLength = 0;
395       if (_hypLengthFromEdges )
396       {
397         // compute edgeLength as an average segment length
398         smIdType nbSegments = 0;
399         for ( size_t iW = 0; iW < nbWires; ++iW )
400         {
401           edgeLength += wires[ iW ]->Length();
402           nbSegments += wires[ iW ]->NbSegments();
403         }
404         if ( nbSegments )
405           edgeLength /= double( nbSegments );
406         netgen::mparam.maxh = edgeLength;
407       }
408       else if ( isDefaultHyp )
409       {
410         // set edgeLength by a longest segment
411         double maxSeg2 = 0;
412         for ( size_t iW = 0; iW < nbWires; ++iW )
413         {
414           const UVPtStructVec& points = wires[ iW ]->GetUVPtStruct();
415           if ( points.empty() )
416             return error( COMPERR_BAD_INPUT_MESH );
417           gp_Pnt pPrev = SMESH_TNodeXYZ( points[0].node );
418           for ( size_t i = 1; i < points.size(); ++i )
419           {
420             gp_Pnt p = SMESH_TNodeXYZ( points[i].node );
421             maxSeg2 = Max( maxSeg2, p.SquareDistance( pPrev ));
422             pPrev = p;
423           }
424         }
425         edgeLength = sqrt( maxSeg2 ) * 1.05;
426         netgen::mparam.maxh = edgeLength;
427       }
428       if ( netgen::mparam.maxh < DBL_MIN )
429         netgen::mparam.maxh = occgeoComm->GetBoundingBox().Diam();
430
431       if ( !isCommonLocalSize )
432       {
433         netgen::mparam.minh = aMesher.GetDefaultMinSize( F, netgen::mparam.maxh );
434       }
435     }
436
437     // prepare occgeom
438     netgen::OCCGeometry *occgeom;
439     int id_occgeom = occgeom_provider.take(&occgeom);
440     occgeom->shape = F;
441     occgeom->fmap.Add( F );
442     occgeom->CalcBoundingBox();
443     occgeom->facemeshstatus.SetSize(1);
444     occgeom->facemeshstatus = 0;
445     occgeom->face_maxh_modified.SetSize(1);
446     occgeom->face_maxh_modified = 0;
447     occgeom->face_maxh.SetSize(1);
448     occgeom->face_maxh = netgen::mparam.maxh;
449
450     // -------------------------
451     // Fill netgen mesh
452     // -------------------------
453
454     // MESHCONST_ANALYSE step may lead to a failure, so we make an attempt
455     // w/o MESHCONST_ANALYSE at the second loop
456     int err = 0;
457     enum { LOC_SIZE, NO_LOC_SIZE };
458     int iLoop = isCommonLocalSize ? 0 : 1;
459     for ( ; iLoop < 2; iLoop++ )
460     {
461       //bool isMESHCONST_ANALYSE = false;
462       InitComputeError();
463
464       netgen::Mesh * ngMesh = ngMeshes[ iLoop ];
465       ngMesh->DeleteMesh();
466
467       if ( iLoop == NO_LOC_SIZE )
468       {
469         ngMesh->SetGlobalH ( mparam.maxh );
470         ngMesh->SetMinimalH( mparam.minh );
471         Box<3> bb = occgeom->GetBoundingBox();
472         bb.Increase (bb.Diam()/10);
473         ngMesh->SetLocalH (bb.PMin(), bb.PMax(), mparam.grading);
474         aMesher.SetLocalSize( *occgeom, *ngMesh );
475         aMesher.SetLocalSizeForChordalError( *occgeoComm, *ngMesh );
476         try {
477           ngMesh->LoadLocalMeshSize( mparam.meshsizefilename );
478         } catch (NgException & ex) {
479           return error( COMPERR_BAD_PARMETERS, ex.What() );
480         }
481       }
482
483       nodeVec.clear();
484       faceErr = aMesher.AddSegmentsToMesh( *ngMesh, *occgeom, wires, helper, nodeVec,
485                                            /*overrideMinH=*/!_hypParameters);
486       if ( faceErr && !faceErr->IsOK() )
487         break;
488
489       //if ( !isCommonLocalSize )
490       //limitSize( ngMesh, mparam.maxh * 0.8);
491
492       // -------------------------
493       // Generate surface mesh
494       // -------------------------
495
496       const int startWith = MESHCONST_MESHSURFACE;
497       const int endWith   = toOptimize ? MESHCONST_OPTSURFACE : MESHCONST_MESHSURFACE;
498
499       SMESH_Comment str;
500       try {
501         OCC_CATCH_SIGNALS;
502         err = ngLib->GenerateMesh(*occgeom, startWith, endWith, ngMesh);
503         if ( netgen::multithread.terminate )
504           return false;
505         if ( err )
506           str << "Error in netgen::OCCGenerateMesh() at " << netgen::multithread.task;
507       }
508       catch (Standard_Failure& ex)
509       {
510         err = 1;
511         str << "Exception in  netgen::OCCGenerateMesh()"
512             << " at " << netgen::multithread.task
513             << ": " << ex.DynamicType()->Name();
514         if ( ex.GetMessageString() && strlen( ex.GetMessageString() ))
515           str << ": " << ex.GetMessageString();
516       }
517       catch (...) {
518         err = 1;
519         str << "Exception in  netgen::OCCGenerateMesh()"
520             << " at " << netgen::multithread.task;
521       }
522       if ( err )
523       {
524         if ( aMesher.FixFaceMesh( *occgeom, *ngMesh, 1 ))
525           break;
526         if ( iLoop == LOC_SIZE )
527         {
528           netgen::mparam.minh = netgen::mparam.maxh;
529           netgen::mparam.maxh = 0;
530           for ( size_t iW = 0; iW < wires.size(); ++iW )
531           {
532             StdMeshers_FaceSidePtr wire = wires[ iW ];
533             const vector<UVPtStruct>& uvPtVec = wire->GetUVPtStruct();
534             for ( size_t iP = 1; iP < uvPtVec.size(); ++iP )
535             {
536               SMESH_TNodeXYZ   p( uvPtVec[ iP ].node );
537               netgen::Point3d np( p.X(),p.Y(),p.Z());
538               double segLen = p.Distance( uvPtVec[ iP-1 ].node );
539               double   size = ngMesh->GetH( np );
540               netgen::mparam.minh = Min( netgen::mparam.minh, size );
541               netgen::mparam.maxh = Max( netgen::mparam.maxh, segLen );
542             }
543           }
544           //cerr << "min " << netgen::mparam.minh << " max " << netgen::mparam.maxh << endl;
545           netgen::mparam.minh *= 0.9;
546           netgen::mparam.maxh *= 1.1;
547           continue;
548         }
549         else
550         {
551           faceErr.reset( new SMESH_ComputeError( COMPERR_ALGO_FAILED, str ));
552         }
553       }
554
555       occgeom_provider.release(id_occgeoComm, true);
556       occgeom_provider.release(id_occgeom, true);
557       aMesh.Lock();
558       // ----------------------------------------------------
559       // Fill the SMESHDS with the generated nodes and faces
560       // ----------------------------------------------------
561
562       int nbNodes = ngMesh->GetNP();
563       int nbFaces = ngMesh->GetNSE();
564
565       int nbInputNodes = (int) nodeVec.size()-1;
566       nodeVec.resize( nbNodes+1, 0 );
567
568       // add nodes
569       for ( int ngID = nbInputNodes + 1; ngID <= nbNodes; ++ngID )
570       {
571         const MeshPoint& ngPoint = ngMesh->Point( ngID );
572         SMDS_MeshNode * node = meshDS->AddNode(ngPoint(0), ngPoint(1), ngPoint(2));
573         nodeVec[ ngID ] = node;
574       }
575
576       // create faces
577       int i,j;
578       vector<const SMDS_MeshNode*> nodes;
579       for ( i = 1; i <= nbFaces ; ++i )
580       {
581         const Element2d& elem = ngMesh->SurfaceElement(i);
582         nodes.resize( elem.GetNP() );
583         for (j=1; j <= elem.GetNP(); ++j)
584         {
585           int pind = elem.PNum(j);
586           if ( pind < 1 )
587             break;
588           nodes[ j-1 ] = nodeVec[ pind ];
589           if ( nodes[ j-1 ]->GetPosition()->GetTypeOfPosition() == SMDS_TOP_3DSPACE )
590           {
591             const PointGeomInfo& pgi = elem.GeomInfoPi(j);
592             meshDS->SetNodeOnFace( nodes[ j-1 ], faceID, pgi.u, pgi.v);
593           }
594         }
595         if ( j > elem.GetNP() )
596         {
597           if ( elem.GetType() == TRIG )
598             helper.AddFace(nodes[0],nodes[1],nodes[2]);
599           else
600             helper.AddFace(nodes[0],nodes[1],nodes[2],nodes[3]);
601         }
602       }
603
604       break;
605     } // two attempts
606   } // loop on FACEs
607   aMesh.Unlock();
608   nglib_provider.release(id_ngLib, true);
609
610
611   return true;
612 }
613
614 void NETGENPlugin_NETGEN_2D_ONLY::CancelCompute()
615 {
616   SMESH_Algo::CancelCompute();
617   netgen::multithread.terminate = 1;
618 }
619
620 //================================================================================
621 /*!
622  * \brief Return progress of Compute() [0.,1]
623  */
624 //================================================================================
625
626 double NETGENPlugin_NETGEN_2D_ONLY::GetProgress() const
627 {
628   return -1;
629   // const char* task1 = "Surface meshing";
630   // //const char* task2 = "Optimizing surface";
631   // double& progress = const_cast<NETGENPlugin_NETGEN_2D_ONLY*>( this )->_progress;
632   // if ( _progressByTic < 0. &&
633   //      strncmp( netgen::multithread.task, task1, 3 ) == 0 )
634   // {
635   //   progress = Min( 0.25, SMESH_Algo::GetProgressByTic() ); // [0, 0.25]
636   // }
637   // else //if ( strncmp( netgen::multithread.task, task2, 3 ) == 0)
638   // {
639   //   if ( _progressByTic < 0 )
640   //   {
641   //     NETGENPlugin_NETGEN_2D_ONLY* me = (NETGENPlugin_NETGEN_2D_ONLY*) this;
642   //     me->_progressByTic = 0.25 / (_progressTic+1);
643   //   }
644   //   const_cast<NETGENPlugin_NETGEN_2D_ONLY*>( this )->_progressTic++;
645   //   progress = Max( progress, _progressByTic * _progressTic );
646   // }
647   // //cout << netgen::multithread.task << " " << _progressTic << endl;
648   // return Min( progress, 0.99 );
649 }
650
651 //=============================================================================
652 /*!
653  *
654  */
655 //=============================================================================
656
657 bool NETGENPlugin_NETGEN_2D_ONLY::Evaluate(SMESH_Mesh& aMesh,
658                                            const TopoDS_Shape& aShape,
659                                            MapShapeNbElems& aResMap)
660 {
661   TopoDS_Face F = TopoDS::Face(aShape);
662   if(F.IsNull())
663     return false;
664
665   // collect info from edges
666   smIdType nb0d = 0, nb1d = 0;
667   bool IsQuadratic = false;
668   bool IsFirst = true;
669   double fullLen = 0.0;
670   TopTools_MapOfShape tmpMap;
671   for (TopExp_Explorer exp(F, TopAbs_EDGE); exp.More(); exp.Next()) {
672     TopoDS_Edge E = TopoDS::Edge(exp.Current());
673     if( tmpMap.Contains(E) )
674       continue;
675     tmpMap.Add(E);
676     SMESH_subMesh *aSubMesh = aMesh.GetSubMesh(exp.Current());
677     MapShapeNbElemsItr anIt = aResMap.find(aSubMesh);
678     if( anIt==aResMap.end() ) {
679       SMESH_subMesh *sm = aMesh.GetSubMesh(F);
680       SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
681       smError.reset( new SMESH_ComputeError(COMPERR_ALGO_FAILED,"Submesh can not be evaluated",this));
682       return false;
683     }
684     std::vector<smIdType> aVec = (*anIt).second;
685     nb0d += aVec[SMDSEntity_Node];
686     nb1d += std::max(aVec[SMDSEntity_Edge],aVec[SMDSEntity_Quad_Edge]);
687     double aLen = SMESH_Algo::EdgeLength(E);
688     fullLen += aLen;
689     if(IsFirst) {
690       IsQuadratic = (aVec[SMDSEntity_Quad_Edge] > aVec[SMDSEntity_Edge]);
691       IsFirst = false;
692     }
693   }
694   tmpMap.Clear();
695
696   // compute edge length
697   double ELen = 0;
698   if (( _hypLengthFromEdges ) || ( !_hypLengthFromEdges && !_hypMaxElementArea )) {
699     if ( nb1d > 0 )
700       ELen = fullLen / double( nb1d );
701   }
702   if ( _hypMaxElementArea ) {
703     double maxArea = _hypMaxElementArea->GetMaxArea();
704     ELen = sqrt(2. * maxArea/sqrt(3.0));
705   }
706   GProp_GProps G;
707   BRepGProp::SurfaceProperties(F,G);
708   double anArea = G.Mass();
709
710   const int hugeNb = numeric_limits<int>::max()/10;
711   if ( anArea / hugeNb > ELen*ELen )
712   {
713     SMESH_subMesh *sm = aMesh.GetSubMesh(F);
714     SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
715     smError.reset( new SMESH_ComputeError(COMPERR_ALGO_FAILED,"Submesh can not be evaluated.\nToo small element length",this));
716     return false;
717   }
718   smIdType nbFaces = (smIdType) ( anArea / ( ELen*ELen*sqrt(3.) / 4 ) );
719   smIdType nbNodes = (smIdType) ( ( nbFaces*3 - (nb1d-1)*2 ) / 6 + 1 );
720   std::vector<smIdType> aVec(SMDSEntity_Last);
721   for(smIdType i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aVec[i]=0;
722   if( IsQuadratic ) {
723     aVec[SMDSEntity_Node] = nbNodes;
724     aVec[SMDSEntity_Quad_Triangle] = nbFaces;
725   }
726   else {
727     aVec[SMDSEntity_Node] = nbNodes;
728     aVec[SMDSEntity_Triangle] = nbFaces;
729   }
730   SMESH_subMesh *sm = aMesh.GetSubMesh(F);
731   aResMap.insert(std::make_pair(sm,aVec));
732
733   return true;
734 }