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