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