Salome HOME
Merge from V6_main_20120808 08Aug12
[plugins/netgenplugin.git] / src / NETGENPlugin / NETGENPlugin_NETGEN_3D.cxx
1 // Copyright (C) 2007-2012  CEA/DEN, EDF R&D, 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.
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 //=============================================================================
24 // File      : NETGENPlugin_NETGEN_3D.cxx
25 //             Moved here from SMESH_NETGEN_3D.cxx
26 // Created   : lundi 27 Janvier 2003
27 // Author    : Nadir BOUHAMOU (CEA)
28 // Project   : SALOME
29 //=============================================================================
30 //
31 #include "NETGENPlugin_NETGEN_3D.hxx"
32
33 #include "NETGENPlugin_Hypothesis.hxx"
34
35 #include "SMDS_MeshElement.hxx"
36 #include "SMDS_MeshNode.hxx"
37 #include "SMESHDS_Mesh.hxx"
38 #include "SMESH_Comment.hxx"
39 #include "SMESH_ControlsDef.hxx"
40 #include "SMESH_Gen.hxx"
41 #include "SMESH_Mesh.hxx"
42 #include "SMESH_MesherHelper.hxx"
43 #include "SMESH_MeshEditor.hxx"
44 #include "StdMeshers_QuadToTriaAdaptor.hxx"
45 #include "StdMeshers_MaxElementVolume.hxx"
46 #include "StdMeshers_ViscousLayers.hxx"
47
48 #include <BRepGProp.hxx>
49 #include <BRep_Tool.hxx>
50 #include <GProp_GProps.hxx>
51 #include <TopExp.hxx>
52 #include <TopExp_Explorer.hxx>
53 #include <TopTools_ListIteratorOfListOfShape.hxx>
54 #include <TopoDS.hxx>
55
56 #include <Standard_Failure.hxx>
57 #include <Standard_ErrorHandler.hxx>
58
59 #include "utilities.h"
60
61 #include <list>
62 #include <vector>
63 #include <map>
64
65 /*
66   Netgen include files
67 */
68
69 #ifndef OCCGEOMETRY
70 #define OCCGEOMETRY
71 #endif
72 #include <occgeom.hpp>
73 namespace nglib {
74 #include <nglib.h>
75 }
76 namespace netgen {
77   extern int OCCGenerateMesh (OCCGeometry&, Mesh*&, int, int, char*);
78   extern MeshingParameters mparam;
79   extern volatile multithreadt multithread;
80 }
81 using namespace nglib;
82 using namespace std;
83
84 //=============================================================================
85 /*!
86  *  
87  */
88 //=============================================================================
89
90 NETGENPlugin_NETGEN_3D::NETGENPlugin_NETGEN_3D(int hypId, int studyId,
91                              SMESH_Gen* gen)
92   : SMESH_3D_Algo(hypId, studyId, gen)
93 {
94   MESSAGE("NETGENPlugin_NETGEN_3D::NETGENPlugin_NETGEN_3D");
95   _name = "NETGEN_3D";
96   _shapeType = (1 << TopAbs_SHELL) | (1 << TopAbs_SOLID);// 1 bit /shape type
97   _compatibleHypothesis.push_back("MaxElementVolume");
98   _compatibleHypothesis.push_back("NETGEN_Parameters");
99   _compatibleHypothesis.push_back("ViscousLayers");
100
101   _maxElementVolume = 0.;
102
103   _hypMaxElementVolume = NULL;
104   _hypParameters = NULL;
105   _viscousLayersHyp = NULL;
106
107   _requireShape = false; // can work without shape
108 }
109
110 //=============================================================================
111 /*!
112  *  
113  */
114 //=============================================================================
115
116 NETGENPlugin_NETGEN_3D::~NETGENPlugin_NETGEN_3D()
117 {
118   MESSAGE("NETGENPlugin_NETGEN_3D::~NETGENPlugin_NETGEN_3D");
119 }
120
121 //=============================================================================
122 /*!
123  *  
124  */
125 //=============================================================================
126
127 bool NETGENPlugin_NETGEN_3D::CheckHypothesis (SMESH_Mesh&         aMesh,
128                                               const TopoDS_Shape& aShape,
129                                               Hypothesis_Status&  aStatus)
130 {
131   MESSAGE("NETGENPlugin_NETGEN_3D::CheckHypothesis");
132
133   _hypMaxElementVolume = NULL;
134   _hypParameters = NULL;
135   _viscousLayersHyp = NULL;
136   _maxElementVolume = DBL_MAX;
137
138   list<const SMESHDS_Hypothesis*>::const_iterator itl;
139   const SMESHDS_Hypothesis* theHyp;
140
141   const list<const SMESHDS_Hypothesis*>& hyps =
142     GetUsedHypothesis(aMesh, aShape, /*ignoreAuxiliary=*/false);
143   list <const SMESHDS_Hypothesis* >::const_iterator h = hyps.begin();
144   if ( h == hyps.end())
145   {
146     aStatus = SMESH_Hypothesis::HYP_OK;
147     return true;  // can work with no hypothesis
148   }
149
150   aStatus = HYP_OK;
151   for ( ; h != hyps.end(); ++h )
152   {
153     if ( !_hypMaxElementVolume )
154       _hypMaxElementVolume = dynamic_cast< const StdMeshers_MaxElementVolume*> ( *h );
155     if ( !_viscousLayersHyp )
156       _viscousLayersHyp = dynamic_cast< const StdMeshers_ViscousLayers*> ( *h );
157     if ( ! _hypParameters )
158       _hypParameters = dynamic_cast< const NETGENPlugin_Hypothesis*> ( *h );
159
160     if ( *h != _hypMaxElementVolume &&
161          *h != _viscousLayersHyp &&
162          *h != _hypParameters)
163       aStatus = HYP_INCOMPATIBLE;
164   }
165   if ( _hypMaxElementVolume && _hypParameters )
166     aStatus = HYP_INCOMPATIBLE;
167
168   if ( _hypMaxElementVolume )
169     _maxElementVolume = _hypMaxElementVolume->GetMaxVolume();
170
171   return aStatus == HYP_OK;
172 }
173
174 //=============================================================================
175 /*!
176  *Here we are going to use the NETGEN mesher
177  */
178 //=============================================================================
179
180 bool NETGENPlugin_NETGEN_3D::Compute(SMESH_Mesh&         aMesh,
181                                      const TopoDS_Shape& aShape)
182 {
183 #ifdef WITH_SMESH_CANCEL_COMPUTE
184   netgen::multithread.terminate = 0;
185 #endif
186   MESSAGE("NETGENPlugin_NETGEN_3D::Compute with maxElmentsize = " << _maxElementVolume);
187
188   SMESHDS_Mesh* meshDS = aMesh.GetMeshDS();
189
190   SMESH_MesherHelper helper(aMesh);
191   bool _quadraticMesh = helper.IsQuadraticSubMesh(aShape);
192   helper.SetElementsOnShape( true );
193
194   int Netgen_NbOfNodes     = 0;
195
196   double Netgen_point[3];
197   int Netgen_triangle[3];
198
199   NETGENPlugin_NetgenLibWrapper ngLib;
200   Ng_Mesh * Netgen_mesh = ngLib._ngMesh;
201
202   // vector of nodes in which node index == netgen ID
203   vector< const SMDS_MeshNode* > nodeVec;
204   {
205     const int invalid_ID = -1;
206
207     SMESH::Controls::Area areaControl;
208     SMESH::Controls::TSequenceOfXYZ nodesCoords;
209
210     // maps nodes to ng ID
211     typedef map< const SMDS_MeshNode*, int, TIDCompare > TNodeToIDMap;
212     typedef TNodeToIDMap::value_type                     TN2ID;
213     TNodeToIDMap nodeToNetgenID;
214
215     // find internal shapes
216     NETGENPlugin_Internals internals( aMesh, aShape, /*is3D=*/true );
217
218     // ---------------------------------
219     // Feed the Netgen with surface mesh
220     // ---------------------------------
221
222     TopAbs_ShapeEnum mainType = aMesh.GetShapeToMesh().ShapeType();
223     bool checkReverse = ( mainType == TopAbs_COMPOUND || mainType == TopAbs_COMPSOLID );
224
225     SMESH_ProxyMesh::Ptr proxyMesh( new SMESH_ProxyMesh( aMesh ));
226     if ( _viscousLayersHyp )
227     {
228       proxyMesh = _viscousLayersHyp->Compute( aMesh, aShape );
229       if ( !proxyMesh )
230         return false;
231     }
232     if ( aMesh.NbQuadrangles() > 0 )
233     {
234       StdMeshers_QuadToTriaAdaptor* Adaptor = new StdMeshers_QuadToTriaAdaptor;
235       Adaptor->Compute(aMesh,aShape,proxyMesh.get());
236       proxyMesh.reset( Adaptor );
237     }
238
239     for ( TopExp_Explorer exFa( aShape, TopAbs_FACE ); exFa.More(); exFa.Next())
240     {
241       const TopoDS_Shape& aShapeFace = exFa.Current();
242       int faceID = meshDS->ShapeToIndex( aShapeFace );
243       bool isInternalFace = internals.isInternalShape( faceID );
244       bool isRev = false;
245       if ( checkReverse && !isInternalFace &&
246            helper.NbAncestors(aShapeFace, aMesh, aShape.ShapeType()) > 1 )
247         // IsReversedSubMesh() can work wrong on strongly curved faces,
248         // so we use it as less as possible
249         isRev = SMESH_Algo::IsReversedSubMesh( TopoDS::Face(aShapeFace), meshDS );
250
251       const SMESHDS_SubMesh * aSubMeshDSFace = proxyMesh->GetSubMesh( aShapeFace );
252       if ( !aSubMeshDSFace ) continue;
253       SMDS_ElemIteratorPtr iteratorElem = aSubMeshDSFace->GetElements();
254       while ( iteratorElem->more() ) // loop on elements on a geom face
255       {
256         // check mesh face
257         const SMDS_MeshElement* elem = iteratorElem->next();
258         if ( !elem )
259           return error( COMPERR_BAD_INPUT_MESH, "Null element encounters");
260         if ( elem->NbCornerNodes() != 3 )
261           return error( COMPERR_BAD_INPUT_MESH, "Not triangle element encounters");
262
263         // Add nodes of triangles and triangles them-selves to netgen mesh
264
265         // add three nodes of triangle
266         bool hasDegen = false;
267         for ( int iN = 0; iN < 3; ++iN )
268         {
269           const SMDS_MeshNode* node = elem->GetNode( iN );
270           const int shapeID = node->getshapeId();
271           if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_EDGE &&
272                helper.IsDegenShape( shapeID ))
273           {
274             // ignore all nodes on degeneraged edge and use node on its vertex instead
275             TopoDS_Shape vertex = TopoDS_Iterator( meshDS->IndexToShape( shapeID )).Value();
276             node = SMESH_Algo::VertexNode( TopoDS::Vertex( vertex ), meshDS );
277             hasDegen = true;
278           }
279           int& ngID = nodeToNetgenID.insert(TN2ID( node, invalid_ID )).first->second;
280           if ( ngID == invalid_ID )
281           {
282             ngID = ++Netgen_NbOfNodes;
283             Netgen_point [ 0 ] = node->X();
284             Netgen_point [ 1 ] = node->Y();
285             Netgen_point [ 2 ] = node->Z();
286             Ng_AddPoint(Netgen_mesh, Netgen_point);
287           }
288           Netgen_triangle[ isRev ? 2-iN : iN ] = ngID;
289         }
290         // add triangle
291         if ( hasDegen && (Netgen_triangle[0] == Netgen_triangle[1] ||
292                           Netgen_triangle[0] == Netgen_triangle[2] ||
293                           Netgen_triangle[2] == Netgen_triangle[1] ))
294           continue;
295
296         Ng_AddSurfaceElement(Netgen_mesh, NG_TRIG, Netgen_triangle);
297
298         if ( isInternalFace && !proxyMesh->IsTemporary( elem ))
299         {
300           swap( Netgen_triangle[1], Netgen_triangle[2] );
301           Ng_AddSurfaceElement(Netgen_mesh, NG_TRIG, Netgen_triangle);
302         }
303       } // loop on elements on a face
304     } // loop on faces of a SOLID or SHELL
305
306     // insert old nodes into nodeVec
307     nodeVec.resize( nodeToNetgenID.size() + 1, 0 );
308     TNodeToIDMap::iterator n_id = nodeToNetgenID.begin();
309     for ( ; n_id != nodeToNetgenID.end(); ++n_id )
310       nodeVec[ n_id->second ] = n_id->first;
311     nodeToNetgenID.clear();
312
313     if ( internals.hasInternalVertexInSolid() )
314     {
315       netgen::OCCGeometry occgeo;
316       NETGENPlugin_Mesher::addIntVerticesInSolids( occgeo,
317                                                    (netgen::Mesh&) *Netgen_mesh,
318                                                    nodeVec,
319                                                    internals);
320     }
321   }
322
323   // -------------------------
324   // Generate the volume mesh
325   // -------------------------
326
327   return compute( aMesh, helper, nodeVec, Netgen_mesh);
328 }
329
330 //================================================================================
331 /*!
332  * \brief set parameters and generate the volume mesh
333  */
334 //================================================================================
335
336 bool NETGENPlugin_NETGEN_3D::compute(SMESH_Mesh&                     aMesh,
337                                      SMESH_MesherHelper&             helper,
338                                      vector< const SMDS_MeshNode* >& nodeVec,
339                                      Ng_Mesh *                       Netgen_mesh)
340 {
341 #ifdef WITH_SMESH_CANCEL_COMPUTE
342   netgen::multithread.terminate = 0;
343 #endif
344   netgen::Mesh* ngMesh = (netgen::Mesh*)Netgen_mesh;
345   int Netgen_NbOfNodes = Ng_GetNP(Netgen_mesh);
346
347   char *optstr = 0;
348   int startWith = netgen::MESHCONST_MESHVOLUME;
349   int endWith   = netgen::MESHCONST_OPTVOLUME;
350   int err = 1;
351
352   NETGENPlugin_Mesher aMesher( &aMesh, helper.GetSubShape(), /*isVolume=*/true );
353   netgen::OCCGeometry occgeo;
354   
355   if ( _hypParameters )
356   {
357     aMesher.SetParameters( _hypParameters );
358     if ( !_hypParameters->GetOptimize() )
359       endWith = netgen::MESHCONST_MESHVOLUME;
360   }
361   else if ( _hypMaxElementVolume )
362   {
363     netgen::mparam.maxh = pow( 72, 1/6. ) * pow( _maxElementVolume, 1/3. );
364   }
365   else if ( aMesh.HasShapeToMesh() )
366   {
367     aMesher.PrepareOCCgeometry( occgeo, helper.GetSubShape(), aMesh );
368     netgen::mparam.maxh = occgeo.GetBoundingBox().Diam()/2;
369   }
370   else
371   {
372     netgen::Point3d pmin, pmax;
373     ngMesh->GetBox (pmin, pmax);
374     netgen::mparam.maxh = Dist(pmin, pmax)/2;
375   }
376
377   if ( !_hypParameters && aMesh.HasShapeToMesh() )
378   {
379     netgen::mparam.minh = aMesher.GetDefaultMinSize( helper.GetSubShape(), netgen::mparam.maxh );
380   }
381
382   try
383   {
384 #if (OCC_VERSION_MAJOR << 16 | OCC_VERSION_MINOR << 8 | OCC_VERSION_MAINTENANCE) > 0x060100
385     OCC_CATCH_SIGNALS;
386 #endif
387     ngMesh->CalcLocalH();
388     err = netgen::OCCGenerateMesh(occgeo, ngMesh, startWith, endWith, optstr);
389 #ifdef WITH_SMESH_CANCEL_COMPUTE
390     if(netgen::multithread.terminate)
391       return false;
392 #endif
393     if ( err )
394       error(SMESH_Comment("Error in netgen::OCCGenerateMesh() at ") << netgen::multithread.task);
395   }
396   catch (Standard_Failure& ex)
397   {
398     SMESH_Comment str("Exception in  netgen::OCCGenerateMesh()");
399     str << " at " << netgen::multithread.task
400         << ": " << ex.DynamicType()->Name();
401     if ( ex.GetMessageString() && strlen( ex.GetMessageString() ))
402       str << ": " << ex.GetMessageString();
403     error(str);
404   }
405   catch (...)
406   {
407     SMESH_Comment str("Exception in  netgen::OCCGenerateMesh()");
408     str << " at " << netgen::multithread.task;
409     error(str);
410   }
411
412   int Netgen_NbOfNodesNew = Ng_GetNP(Netgen_mesh);
413   int Netgen_NbOfTetra    = Ng_GetNE(Netgen_mesh);
414
415   MESSAGE("End of Volume Mesh Generation. err=" << err <<
416           ", nb new nodes: " << Netgen_NbOfNodesNew - Netgen_NbOfNodes <<
417           ", nb tetra: " << Netgen_NbOfTetra);
418
419   // -------------------------------------------------------------------
420   // Feed back the SMESHDS with the generated Nodes and Volume Elements
421   // -------------------------------------------------------------------
422
423   if ( err )
424   {
425     SMESH_ComputeErrorPtr ce = NETGENPlugin_Mesher::readErrors(nodeVec);
426     if ( ce && !ce->myBadElements.empty() )
427       error( ce );
428   }
429
430   bool isOK = ( /*status == NG_OK &&*/ Netgen_NbOfTetra > 0 );// get whatever built
431   if ( isOK )
432   {
433     double Netgen_point[3];
434     int    Netgen_tetrahedron[4];
435
436     // create and insert new nodes into nodeVec
437     nodeVec.resize( Netgen_NbOfNodesNew + 1, 0 );
438     int nodeIndex = Netgen_NbOfNodes + 1;
439     for ( ; nodeIndex <= Netgen_NbOfNodesNew; ++nodeIndex )
440     {
441       Ng_GetPoint( Netgen_mesh, nodeIndex, Netgen_point );
442       nodeVec.at(nodeIndex) = helper.AddNode(Netgen_point[0], Netgen_point[1], Netgen_point[2]);
443     }
444
445     // create tetrahedrons
446     for ( int elemIndex = 1; elemIndex <= Netgen_NbOfTetra; ++elemIndex )
447     {
448       Ng_GetVolumeElement(Netgen_mesh, elemIndex, Netgen_tetrahedron);
449       try
450       {
451         helper.AddVolume (nodeVec.at( Netgen_tetrahedron[0] ),
452                           nodeVec.at( Netgen_tetrahedron[1] ),
453                           nodeVec.at( Netgen_tetrahedron[2] ),
454                           nodeVec.at( Netgen_tetrahedron[3] ));
455       }
456       catch (...)
457       {
458       }
459     }
460   }
461
462   return !err;
463 }
464
465 //================================================================================
466 /*!
467  * \brief Compute tetrahedral mesh from 2D mesh without geometry
468  */
469 //================================================================================
470
471 bool NETGENPlugin_NETGEN_3D::Compute(SMESH_Mesh&         aMesh,
472                                      SMESH_MesherHelper* aHelper)
473 {
474   MESSAGE("NETGENPlugin_NETGEN_3D::Compute with maxElmentsize = " << _maxElementVolume);  
475   const int invalid_ID = -1;
476   bool _quadraticMesh = false;
477
478   SMESH_MesherHelper::MType MeshType = aHelper->IsQuadraticMesh();
479
480   if(MeshType == SMESH_MesherHelper::COMP)
481     return error( COMPERR_BAD_INPUT_MESH,
482                   SMESH_Comment("Mesh with linear and quadratic elements given."));
483   else if (MeshType == SMESH_MesherHelper::QUADRATIC)
484     _quadraticMesh = true;
485
486   // ---------------------------------
487   // Feed the Netgen with surface mesh
488   // ---------------------------------
489
490   int Netgen_NbOfNodes = 0;
491   int Netgen_param2ndOrder = 0;
492   double Netgen_paramFine = 1.;
493   double Netgen_paramSize = pow( 72, 1/6. ) * pow( _maxElementVolume, 1/3. );
494   
495   double Netgen_point[3];
496   int Netgen_triangle[3];
497   int Netgen_tetrahedron[4];
498
499   NETGENPlugin_NetgenLibWrapper ngLib;
500   Ng_Mesh * Netgen_mesh = ngLib._ngMesh;
501
502   SMESH_ProxyMesh::Ptr proxyMesh( new SMESH_ProxyMesh( aMesh ));
503   if ( aMesh.NbQuadrangles() > 0 )
504   {
505     StdMeshers_QuadToTriaAdaptor* Adaptor = new StdMeshers_QuadToTriaAdaptor;
506     Adaptor->Compute(aMesh);
507     proxyMesh.reset( Adaptor );
508   }
509
510   // maps nodes to ng ID
511   typedef map< const SMDS_MeshNode*, int, TIDCompare > TNodeToIDMap;
512   typedef TNodeToIDMap::value_type                     TN2ID;
513   TNodeToIDMap nodeToNetgenID;
514
515   SMDS_ElemIteratorPtr fIt = proxyMesh->GetFaces();
516   while( fIt->more())
517   {
518     // check element
519     const SMDS_MeshElement* elem = fIt->next();
520     if ( !elem )
521       return error( COMPERR_BAD_INPUT_MESH, "Null element encounters");
522     if ( elem->NbCornerNodes() != 3 )
523       return error( COMPERR_BAD_INPUT_MESH, "Not triangle element encounters");
524       
525     // add three nodes of triangle
526     for ( int iN = 0; iN < 3; ++iN )
527     {
528       const SMDS_MeshNode* node = elem->GetNode( iN );
529       int& ngID = nodeToNetgenID.insert(TN2ID( node, invalid_ID )).first->second;
530       if ( ngID == invalid_ID )
531       {
532         ngID = ++Netgen_NbOfNodes;
533         Netgen_point [ 0 ] = node->X();
534         Netgen_point [ 1 ] = node->Y();
535         Netgen_point [ 2 ] = node->Z();
536         Ng_AddPoint(Netgen_mesh, Netgen_point);
537       }
538       Netgen_triangle[ iN ] = ngID;
539     }
540     Ng_AddSurfaceElement(Netgen_mesh, NG_TRIG, Netgen_triangle);
541   }
542   proxyMesh.reset(); // delete tmp faces
543
544   // vector of nodes in which node index == netgen ID
545   vector< const SMDS_MeshNode* > nodeVec ( nodeToNetgenID.size() + 1 );
546   // insert old nodes into nodeVec
547   TNodeToIDMap::iterator n_id = nodeToNetgenID.begin();
548   for ( ; n_id != nodeToNetgenID.end(); ++n_id )
549     nodeVec.at( n_id->second ) = n_id->first;
550   nodeToNetgenID.clear();
551
552   // -------------------------
553   // Generate the volume mesh
554   // -------------------------
555
556   return compute( aMesh, *aHelper, nodeVec, Netgen_mesh);
557 }
558
559 #ifdef WITH_SMESH_CANCEL_COMPUTE
560 void NETGENPlugin_NETGEN_3D::CancelCompute()
561 {
562   SMESH_Algo::CancelCompute();
563   netgen::multithread.terminate = 1;
564 }
565 #endif
566
567 //=============================================================================
568 /*!
569  *
570  */
571 //=============================================================================
572
573 bool NETGENPlugin_NETGEN_3D::Evaluate(SMESH_Mesh& aMesh,
574                                       const TopoDS_Shape& aShape,
575                                       MapShapeNbElems& aResMap)
576 {
577   int nbtri = 0, nbqua = 0;
578   double fullArea = 0.0;
579   for (TopExp_Explorer expF(aShape, TopAbs_FACE); expF.More(); expF.Next()) {
580     TopoDS_Face F = TopoDS::Face( expF.Current() );
581     SMESH_subMesh *sm = aMesh.GetSubMesh(F);
582     MapShapeNbElemsItr anIt = aResMap.find(sm);
583     if( anIt==aResMap.end() ) {
584       SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
585       smError.reset( new SMESH_ComputeError(COMPERR_ALGO_FAILED,"Submesh can not be evaluated",this));
586       return false;
587     }
588     std::vector<int> aVec = (*anIt).second;
589     nbtri += Max(aVec[SMDSEntity_Triangle],aVec[SMDSEntity_Quad_Triangle]);
590     nbqua += Max(aVec[SMDSEntity_Quadrangle],aVec[SMDSEntity_Quad_Quadrangle]);
591     GProp_GProps G;
592     BRepGProp::SurfaceProperties(F,G);
593     double anArea = G.Mass();
594     fullArea += anArea;
595   }
596
597   // collect info from edges
598   int nb0d_e = 0, nb1d_e = 0;
599   bool IsQuadratic = false;
600   bool IsFirst = true;
601   TopTools_MapOfShape tmpMap;
602   for (TopExp_Explorer expF(aShape, TopAbs_EDGE); expF.More(); expF.Next()) {
603     TopoDS_Edge E = TopoDS::Edge(expF.Current());
604     if( tmpMap.Contains(E) )
605       continue;
606     tmpMap.Add(E);
607     SMESH_subMesh *aSubMesh = aMesh.GetSubMesh(expF.Current());
608     MapShapeNbElemsItr anIt = aResMap.find(aSubMesh);
609     if( anIt==aResMap.end() ) {
610       SMESH_ComputeErrorPtr& smError = aSubMesh->GetComputeError();
611       smError.reset( new SMESH_ComputeError(COMPERR_ALGO_FAILED,
612                                             "Submesh can not be evaluated",this));
613       return false;
614     }
615     std::vector<int> aVec = (*anIt).second;
616     nb0d_e += aVec[SMDSEntity_Node];
617     nb1d_e += Max(aVec[SMDSEntity_Edge],aVec[SMDSEntity_Quad_Edge]);
618     if(IsFirst) {
619       IsQuadratic = (aVec[SMDSEntity_Quad_Edge] > aVec[SMDSEntity_Edge]);
620       IsFirst = false;
621     }
622   }
623   tmpMap.Clear();
624
625   double ELen_face = sqrt(2.* ( fullArea/(nbtri+nbqua*2) ) / sqrt(3.0) );
626   double ELen_vol = pow( 72, 1/6. ) * pow( _maxElementVolume, 1/3. );
627   double ELen = Min(ELen_vol,ELen_face*2);
628
629   GProp_GProps G;
630   BRepGProp::VolumeProperties(aShape,G);
631   double aVolume = G.Mass();
632   double tetrVol = 0.1179*ELen*ELen*ELen;
633   double CoeffQuality = 0.9;
634   int nbVols = int( aVolume/tetrVol/CoeffQuality );
635   int nb1d_f = (nbtri*3 + nbqua*4 - nb1d_e) / 2;
636   int nb1d_in = (nbVols*6 - nb1d_e - nb1d_f ) / 5;
637   std::vector<int> aVec(SMDSEntity_Last);
638   for(int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aVec[i]=0;
639   if( IsQuadratic ) {
640     aVec[SMDSEntity_Node] = nb1d_in/6 + 1 + nb1d_in;
641     aVec[SMDSEntity_Quad_Tetra] = nbVols - nbqua*2;
642     aVec[SMDSEntity_Quad_Pyramid] = nbqua;
643   }
644   else {
645     aVec[SMDSEntity_Node] = nb1d_in/6 + 1;
646     aVec[SMDSEntity_Tetra] = nbVols - nbqua*2;
647     aVec[SMDSEntity_Pyramid] = nbqua;
648   }
649   SMESH_subMesh *sm = aMesh.GetSubMesh(aShape);
650   aResMap.insert(std::make_pair(sm,aVec));
651   
652   return true;
653 }
654
655