Salome HOME
fix indentation
[modules/smesh.git] / src / SMESH / SMESH_Mesh.cxx
1 // Copyright (C) 2007-2013  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 //  File   : SMESH_Mesh.cxx
24 //  Author : Paul RASCLE, EDF
25 //  Module : SMESH
26 //
27 #include "SMESH_Mesh.hxx"
28 #include "SMESH_MesherHelper.hxx"
29 #include "SMESH_subMesh.hxx"
30 #include "SMESH_Gen.hxx"
31 #include "SMESH_Hypothesis.hxx"
32 #include "SMESH_Group.hxx"
33 #include "SMESH_HypoFilter.hxx"
34 #include "SMESHDS_Group.hxx"
35 #include "SMESHDS_Script.hxx"
36 #include "SMESHDS_GroupOnGeom.hxx"
37 #include "SMESHDS_Document.hxx"
38 #include "SMDS_MeshVolume.hxx"
39 #include "SMDS_SetIterator.hxx"
40
41 #include "utilities.h"
42
43 #include "DriverDAT_W_SMDS_Mesh.h"
44 #include "DriverGMF_Read.hxx"
45 #include "DriverGMF_Write.hxx"
46 #include "DriverMED_R_SMESHDS_Mesh.h"
47 #include "DriverMED_W_SMESHDS_Mesh.h"
48 #include "DriverSTL_R_SMDS_Mesh.h"
49 #include "DriverSTL_W_SMDS_Mesh.h"
50 #include "DriverUNV_R_SMDS_Mesh.h"
51 #include "DriverUNV_W_SMDS_Mesh.h"
52 #ifdef WITH_CGNS
53 #include "DriverCGNS_Read.hxx"
54 #include "DriverCGNS_Write.hxx"
55 #endif
56
57 #undef _Precision_HeaderFile
58 #include <BRepBndLib.hxx>
59 #include <BRepPrimAPI_MakeBox.hxx>
60 #include <Bnd_Box.hxx>
61 #include <TColStd_MapOfInteger.hxx>
62 #include <TopExp.hxx>
63 #include <TopExp_Explorer.hxx>
64 #include <TopTools_ListIteratorOfListOfShape.hxx>
65 #include <TopTools_ListOfShape.hxx>
66 #include <TopTools_MapOfShape.hxx>
67 #include <TopoDS_Iterator.hxx>
68
69 #include "SMESH_TryCatch.hxx" // include after OCCT headers!
70
71 #include "Utils_ExceptHandlers.hxx"
72 #ifndef WIN32
73 #include <boost/thread/thread.hpp>
74 #include <boost/bind.hpp>
75 #else 
76 #include <pthread.h> 
77 #endif
78
79 using namespace std;
80
81 // maximum stored group name length in MED file
82 #define MAX_MED_GROUP_NAME_LENGTH 80
83
84 #ifdef _DEBUG_
85 static int MYDEBUG = 0;
86 #else
87 static int MYDEBUG = 0;
88 #endif
89
90 #define cSMESH_Hyp(h) static_cast<const SMESH_Hypothesis*>(h)
91
92 typedef SMESH_HypoFilter THypType;
93
94 //=============================================================================
95 /*!
96  * 
97  */
98 //=============================================================================
99
100 SMESH_Mesh::SMESH_Mesh(int               theLocalId, 
101                        int               theStudyId, 
102                        SMESH_Gen*        theGen,
103                        bool              theIsEmbeddedMode,
104                        SMESHDS_Document* theDocument):
105   _groupId( 0 ), _nbSubShapes( 0 )
106 {
107   MESSAGE("SMESH_Mesh::SMESH_Mesh(int localId)");
108   _id            = theLocalId;
109   _studyId       = theStudyId;
110   _gen           = theGen;
111   _myDocument    = theDocument;
112   _myMeshDS      = theDocument->NewMesh(theIsEmbeddedMode,theLocalId);
113   _isShapeToMesh = false;
114   _isAutoColor   = false;
115   _isModified    = false;
116   _shapeDiagonal = 0.0;
117   _callUp        = NULL;
118   _myMeshDS->ShapeToMesh( PseudoShape() );
119 }
120
121 //================================================================================
122 /*!
123  * \brief Constructor of SMESH_Mesh being a base of some descendant class
124  */
125 //================================================================================
126
127 SMESH_Mesh::SMESH_Mesh():
128   _id(-1),
129   _studyId(-1),
130   _groupId( 0 ),
131   _nbSubShapes( 0 ),
132   _isShapeToMesh( false ),
133   _myDocument( 0 ),
134   _myMeshDS( 0 ),
135   _gen( 0 ),
136   _isAutoColor( false ),
137   _isModified( false ),
138   _shapeDiagonal( 0.0 ),
139   _callUp( 0 )
140 {
141 }
142
143 namespace
144 {
145 #ifndef WIN32
146   void deleteMeshDS(SMESHDS_Mesh* meshDS)
147   {
148     //cout << "deleteMeshDS( " << meshDS << endl;
149     delete meshDS;
150   }
151 #else
152   static void* deleteMeshDS(void* meshDS)
153   {
154     //cout << "deleteMeshDS( " << meshDS << endl;
155     SMESHDS_Mesh* m = (SMESHDS_Mesh*)meshDS;
156     if(m) {
157       delete m;
158     }
159     return 0;
160   }
161 #endif
162 }
163
164 //=============================================================================
165 /*!
166  *
167  */
168 //=============================================================================
169
170 SMESH_Mesh::~SMESH_Mesh()
171 {
172   MESSAGE("SMESH_Mesh::~SMESH_Mesh");
173
174   // issue 0020340: EDF 1022 SMESH : Crash with FindNodeClosestTo in a second new study
175   //   Notify event listeners at least that something happens
176   if ( SMESH_subMesh * sm = GetSubMeshContaining(1))
177     sm->ComputeStateEngine( SMESH_subMesh::MESH_ENTITY_REMOVED );
178
179   // delete groups
180   map < int, SMESH_Group * >::iterator itg;
181   for (itg = _mapGroup.begin(); itg != _mapGroup.end(); itg++) {
182     SMESH_Group *aGroup = (*itg).second;
183     delete aGroup;
184   }
185   _mapGroup.clear();
186
187   // delete sub-meshes
188   map <int, SMESH_subMesh*>::iterator sm = _mapSubMesh.begin();
189   for ( ; sm != _mapSubMesh.end(); ++sm )
190   {
191     delete sm->second;
192     sm->second = 0;
193   }
194   _mapSubMesh.clear();
195
196   if ( _callUp) delete _callUp;
197   _callUp = 0;
198
199   // remove self from studyContext
200   if ( _gen )
201   {
202     StudyContextStruct * studyContext = _gen->GetStudyContext( _studyId );
203     studyContext->mapMesh.erase( _id );
204   }
205   if ( _myDocument )
206     _myDocument->RemoveMesh( _id );
207   _myDocument = 0;
208
209   if ( _myMeshDS ) {
210     // delete _myMeshDS, in a thread in order not to block closing a study with large meshes
211 #ifndef WIN32
212     boost::thread aThread(boost::bind( & deleteMeshDS, _myMeshDS ));
213 #else
214     pthread_t thread;
215     int result=pthread_create(&thread, NULL, deleteMeshDS, (void*)_myMeshDS);
216 #endif
217   }
218 }
219
220 //================================================================================
221 /*!
222  * \brief Return true if a mesh with given id exists
223  */
224 //================================================================================
225
226 bool SMESH_Mesh::MeshExists( int meshId ) const
227 {
228   return _myDocument ? _myDocument->GetMesh( meshId ) : false;
229 }
230
231 //=============================================================================
232 /*!
233  * \brief Set geometry to be meshed
234  */
235 //=============================================================================
236
237 void SMESH_Mesh::ShapeToMesh(const TopoDS_Shape & aShape)
238 {
239   if(MYDEBUG) MESSAGE("SMESH_Mesh::ShapeToMesh");
240
241   if ( !aShape.IsNull() && _isShapeToMesh ) {
242     if ( aShape.ShapeType() != TopAbs_COMPOUND && // group contents is allowed to change
243          _myMeshDS->ShapeToMesh().ShapeType() != TopAbs_COMPOUND )
244       throw SALOME_Exception(LOCALIZED ("a shape to mesh has already been defined"));
245   }
246   // clear current data
247   if ( !_myMeshDS->ShapeToMesh().IsNull() )
248   {
249     // removal of a shape to mesh, delete objects referring to sub-shapes:
250     // - sub-meshes
251     map <int, SMESH_subMesh *>::iterator i_sm = _mapSubMesh.begin();
252     for ( ; i_sm != _mapSubMesh.end(); ++i_sm )
253       delete i_sm->second;
254     _mapSubMesh.clear();
255     //  - groups on geometry
256     map <int, SMESH_Group *>::iterator i_gr = _mapGroup.begin();
257     while ( i_gr != _mapGroup.end() ) {
258       if ( dynamic_cast<SMESHDS_GroupOnGeom*>( i_gr->second->GetGroupDS() )) {
259         _myMeshDS->RemoveGroup( i_gr->second->GetGroupDS() );
260         delete i_gr->second;
261         _mapGroup.erase( i_gr++ );
262       }
263       else
264         i_gr++;
265     }
266     _mapAncestors.Clear();
267
268     // clear SMESHDS
269     TopoDS_Shape aNullShape;
270     _myMeshDS->ShapeToMesh( aNullShape );
271
272     _shapeDiagonal = 0.0;
273   }
274
275   // set a new geometry
276   if ( !aShape.IsNull() )
277   {
278     _myMeshDS->ShapeToMesh(aShape);
279     _isShapeToMesh = true;
280     _nbSubShapes = _myMeshDS->MaxShapeIndex();
281
282     // fill map of ancestors
283     fillAncestorsMap(aShape);
284   }
285   else
286   {
287     _isShapeToMesh = false;
288     _shapeDiagonal = 0.0;
289     _myMeshDS->ShapeToMesh( PseudoShape() );
290   }
291   _isModified = false;
292 }
293
294 //=======================================================================
295 /*!
296  * \brief Return geometry to be meshed. (It may be a PseudoShape()!)
297  */
298 //=======================================================================
299
300 TopoDS_Shape SMESH_Mesh::GetShapeToMesh() const
301 {
302   return _myMeshDS->ShapeToMesh();
303 }
304
305 //=======================================================================
306 /*!
307  * \brief Return a solid which is returned by GetShapeToMesh() if
308  *        a real geometry to be meshed was not set
309  */
310 //=======================================================================
311
312 const TopoDS_Solid& SMESH_Mesh::PseudoShape()
313 {
314   static TopoDS_Solid aSolid;
315   if ( aSolid.IsNull() )
316   {
317     aSolid = BRepPrimAPI_MakeBox(1,1,1);
318   }
319   return aSolid;
320 }
321
322 //=======================================================================
323 /*!
324  * \brief Return diagonal size of bounding box of a shape
325  */
326 //=======================================================================
327
328 double SMESH_Mesh::GetShapeDiagonalSize(const TopoDS_Shape & aShape)
329 {
330   if ( !aShape.IsNull() ) {
331     Bnd_Box Box;
332     BRepBndLib::Add(aShape, Box);
333     return sqrt( Box.SquareExtent() );
334   }
335   return 0;
336 }
337
338 //=======================================================================
339 /*!
340  * \brief Return diagonal size of bounding box of shape to mesh
341  */
342 //=======================================================================
343
344 double SMESH_Mesh::GetShapeDiagonalSize() const
345 {
346   if ( _shapeDiagonal == 0. && _isShapeToMesh )
347     const_cast<SMESH_Mesh*>(this)->_shapeDiagonal = GetShapeDiagonalSize( GetShapeToMesh() );
348
349   return _shapeDiagonal;
350 }
351
352 //================================================================================
353 /*!
354  * \brief Load mesh from study file
355  */
356 //================================================================================
357
358 void SMESH_Mesh::Load()
359 {
360   if (_callUp)
361     _callUp->Load();
362 }
363
364 //=======================================================================
365 /*!
366  * \brief Remove all nodes and elements
367  */
368 //=======================================================================
369
370 void SMESH_Mesh::Clear()
371 {
372   if ( HasShapeToMesh() ) // remove all nodes and elements
373   {
374     // clear mesh data
375     _myMeshDS->ClearMesh();
376
377     // update compute state of submeshes
378     if ( SMESH_subMesh *sm = GetSubMeshContaining( GetShapeToMesh() ) )
379     {
380       sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
381       sm->ComputeSubMeshStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
382       sm->ComputeStateEngine( SMESH_subMesh::CLEAN ); // for event listeners (issue 0020918)
383       sm->ComputeSubMeshStateEngine( SMESH_subMesh::CLEAN );
384     }
385   }
386   else // remove only nodes/elements computed by algorithms
387   {
388     if ( SMESH_subMesh *sm = GetSubMeshContaining( GetShapeToMesh() ) )
389     {
390       sm->ComputeStateEngine( SMESH_subMesh::CLEAN );
391       sm->ComputeSubMeshStateEngine( SMESH_subMesh::CLEAN );
392       sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
393       sm->ComputeSubMeshStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
394     }
395   }
396   _isModified = false;
397 }
398
399 //=======================================================================
400 /*!
401  * \brief Remove all nodes and elements of indicated shape
402  */
403 //=======================================================================
404
405 void SMESH_Mesh::ClearSubMesh(const int theShapeId)
406 {
407   // clear sub-meshes; get ready to re-compute as a side-effect 
408   if ( SMESH_subMesh *sm = GetSubMeshContaining( theShapeId ) )
409   {
410     SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/true,
411                                                              /*complexShapeFirst=*/false);
412     while ( smIt->more() )
413     {
414       sm = smIt->next();
415       TopAbs_ShapeEnum shapeType = sm->GetSubShape().ShapeType();      
416       if ( shapeType == TopAbs_VERTEX || shapeType < TopAbs_SOLID )
417         // all other shapes depends on vertices so they are already cleaned
418         sm->ComputeStateEngine( SMESH_subMesh::CLEAN );
419       // to recompute even if failed
420       sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
421     }
422   }
423 }
424
425 //=======================================================================
426 //function : UNVToMesh
427 //purpose  : 
428 //=======================================================================
429
430 int SMESH_Mesh::UNVToMesh(const char* theFileName)
431 {
432   if(MYDEBUG) MESSAGE("UNVToMesh - theFileName = "<<theFileName);
433   if(_isShapeToMesh)
434     throw SALOME_Exception(LOCALIZED("a shape to mesh has already been defined"));
435   _isShapeToMesh = false;
436   DriverUNV_R_SMDS_Mesh myReader;
437   myReader.SetMesh(_myMeshDS);
438   myReader.SetFile(theFileName);
439   myReader.SetMeshId(-1);
440   myReader.Perform();
441   if(MYDEBUG){
442     MESSAGE("UNVToMesh - _myMeshDS->NbNodes() = "<<_myMeshDS->NbNodes());
443     MESSAGE("UNVToMesh - _myMeshDS->NbEdges() = "<<_myMeshDS->NbEdges());
444     MESSAGE("UNVToMesh - _myMeshDS->NbFaces() = "<<_myMeshDS->NbFaces());
445     MESSAGE("UNVToMesh - _myMeshDS->NbVolumes() = "<<_myMeshDS->NbVolumes());
446   }
447   SMDS_MeshGroup* aGroup = (SMDS_MeshGroup*) myReader.GetGroup();
448   if (aGroup != 0) {
449     TGroupNamesMap aGroupNames = myReader.GetGroupNamesMap();
450     //const TGroupIdMap& aGroupId = myReader.GetGroupIdMap();
451     aGroup->InitSubGroupsIterator();
452     while (aGroup->MoreSubGroups()) {
453       SMDS_MeshGroup* aSubGroup = (SMDS_MeshGroup*) aGroup->NextSubGroup();
454       string aName = aGroupNames[aSubGroup];
455       int aId;
456
457       SMESH_Group* aSMESHGroup = AddGroup( aSubGroup->GetType(), aName.c_str(), aId );
458       if ( aSMESHGroup ) {
459         if(MYDEBUG) MESSAGE("UNVToMesh - group added: "<<aName);      
460         SMESHDS_Group* aGroupDS = dynamic_cast<SMESHDS_Group*>( aSMESHGroup->GetGroupDS() );
461         if ( aGroupDS ) {
462           aGroupDS->SetStoreName(aName.c_str());
463           aSubGroup->InitIterator();
464           const SMDS_MeshElement* aElement = 0;
465           while (aSubGroup->More()) {
466             aElement = aSubGroup->Next();
467             if (aElement) {
468               aGroupDS->SMDSGroup().Add(aElement);
469             }
470           }
471           if (aElement)
472             aGroupDS->SetType(aElement->GetType());
473         }
474       }
475     }
476   }
477   return 1;
478 }
479
480 //=======================================================================
481 //function : MEDToMesh
482 //purpose  : 
483 //=======================================================================
484
485 int SMESH_Mesh::MEDToMesh(const char* theFileName, const char* theMeshName)
486 {
487   if(MYDEBUG) MESSAGE("MEDToMesh - theFileName = "<<theFileName<<", mesh name = "<<theMeshName);
488   if(_isShapeToMesh)
489     throw SALOME_Exception(LOCALIZED("a shape to mesh has already been defined"));
490   _isShapeToMesh = false;
491   DriverMED_R_SMESHDS_Mesh myReader;
492   myReader.SetMesh(_myMeshDS);
493   myReader.SetMeshId(-1);
494   myReader.SetFile(theFileName);
495   myReader.SetMeshName(theMeshName);
496   Driver_Mesh::Status status = myReader.Perform();
497   if(MYDEBUG){
498     MESSAGE("MEDToMesh - _myMeshDS->NbNodes() = "<<_myMeshDS->NbNodes());
499     MESSAGE("MEDToMesh - _myMeshDS->NbEdges() = "<<_myMeshDS->NbEdges());
500     MESSAGE("MEDToMesh - _myMeshDS->NbFaces() = "<<_myMeshDS->NbFaces());
501     MESSAGE("MEDToMesh - _myMeshDS->NbVolumes() = "<<_myMeshDS->NbVolumes());
502   }
503
504   // Reading groups (sub-meshes are out of scope of MED import functionality)
505   list<TNameAndType> aGroupNames = myReader.GetGroupNamesAndTypes();
506   if(MYDEBUG) MESSAGE("MEDToMesh - Nb groups = "<<aGroupNames.size()); 
507   int anId;
508   list<TNameAndType>::iterator name_type = aGroupNames.begin();
509   for ( ; name_type != aGroupNames.end(); name_type++ ) {
510     SMESH_Group* aGroup = AddGroup( name_type->second, name_type->first.c_str(), anId );
511     if ( aGroup ) {
512       if(MYDEBUG) MESSAGE("MEDToMesh - group added: "<<name_type->first.c_str());      
513       SMESHDS_Group* aGroupDS = dynamic_cast<SMESHDS_Group*>( aGroup->GetGroupDS() );
514       if ( aGroupDS ) {
515         aGroupDS->SetStoreName( name_type->first.c_str() );
516         myReader.GetGroup( aGroupDS );
517       }
518     }
519   }
520   return (int) status;
521 }
522
523 //=======================================================================
524 //function : STLToMesh
525 //purpose  : 
526 //=======================================================================
527
528 int SMESH_Mesh::STLToMesh(const char* theFileName)
529 {
530   if(MYDEBUG) MESSAGE("STLToMesh - theFileName = "<<theFileName);
531   if(_isShapeToMesh)
532     throw SALOME_Exception(LOCALIZED("a shape to mesh has already been defined"));
533   _isShapeToMesh = false;
534   DriverSTL_R_SMDS_Mesh myReader;
535   myReader.SetMesh(_myMeshDS);
536   myReader.SetFile(theFileName);
537   myReader.SetMeshId(-1);
538   myReader.Perform();
539   if(MYDEBUG){
540     MESSAGE("STLToMesh - _myMeshDS->NbNodes() = "<<_myMeshDS->NbNodes());
541     MESSAGE("STLToMesh - _myMeshDS->NbEdges() = "<<_myMeshDS->NbEdges());
542     MESSAGE("STLToMesh - _myMeshDS->NbFaces() = "<<_myMeshDS->NbFaces());
543     MESSAGE("STLToMesh - _myMeshDS->NbVolumes() = "<<_myMeshDS->NbVolumes());
544   }
545   return 1;
546 }
547
548 //================================================================================
549 /*!
550  * \brief Reads the given mesh from the CGNS file
551  *  \param theFileName - name of the file
552  *  \retval int - Driver_Mesh::Status
553  */
554 //================================================================================
555
556 int SMESH_Mesh::CGNSToMesh(const char*  theFileName,
557                            const int    theMeshIndex,
558                            std::string& theMeshName)
559 {
560   int res = Driver_Mesh::DRS_FAIL;
561 #ifdef WITH_CGNS
562
563   DriverCGNS_Read myReader;
564   myReader.SetMesh(_myMeshDS);
565   myReader.SetFile(theFileName);
566   myReader.SetMeshId(theMeshIndex);
567   res = myReader.Perform();
568   theMeshName = myReader.GetMeshName();
569
570   // create groups
571   SynchronizeGroups();
572
573 #endif
574   return res;
575 }
576
577 //================================================================================
578 /*!
579  * \brief Fill its data by reading a GMF file
580  */
581 //================================================================================
582
583 SMESH_ComputeErrorPtr SMESH_Mesh::GMFToMesh(const char* theFileName,
584                                             bool        theMakeRequiredGroups)
585 {
586   DriverGMF_Read myReader;
587   myReader.SetMesh(_myMeshDS);
588   myReader.SetFile(theFileName);
589   myReader.SetMakeRequiredGroups( theMakeRequiredGroups );
590   myReader.Perform();
591   //theMeshName = myReader.GetMeshName();
592
593   // create groups
594   SynchronizeGroups();
595
596   return myReader.GetError();
597 }
598
599 //=============================================================================
600 /*!
601  * 
602  */
603 //=============================================================================
604
605 SMESH_Hypothesis::Hypothesis_Status
606   SMESH_Mesh::AddHypothesis(const TopoDS_Shape & aSubShape,
607                             int                  anHypId  ) throw(SALOME_Exception)
608 {
609   Unexpect aCatch(SalomeException);
610   if(MYDEBUG) MESSAGE("SMESH_Mesh::AddHypothesis");
611
612   SMESH_subMesh *subMesh = GetSubMesh(aSubShape);
613   if ( !subMesh || !subMesh->GetId())
614     return SMESH_Hypothesis::HYP_BAD_SUBSHAPE;
615
616   SMESH_Hypothesis *anHyp = GetHypothesis( anHypId );
617   if ( !anHyp )
618     throw SALOME_Exception(LOCALIZED("hypothesis does not exist"));
619
620   bool isGlobalHyp = IsMainShape( aSubShape );
621
622   // NotConformAllowed can be only global
623   if ( !isGlobalHyp )
624   {
625     // NOTE: this is not a correct way to check a name of hypothesis,
626     // there should be an attribute of hypothesis saying that it can/can't
627     // be global/local
628     string hypName = anHyp->GetName();
629     if ( hypName == "NotConformAllowed" )
630     {
631       if(MYDEBUG) MESSAGE( "Hypotesis <NotConformAllowed> can be only global" );
632       return SMESH_Hypothesis::HYP_INCOMPATIBLE;
633     }
634   }
635
636   // shape 
637
638   bool isAlgo = ( !anHyp->GetType() == SMESHDS_Hypothesis::PARAM_ALGO );
639   int event = isAlgo ? SMESH_subMesh::ADD_ALGO : SMESH_subMesh::ADD_HYP;
640
641   SMESH_Hypothesis::Hypothesis_Status ret = subMesh->AlgoStateEngine(event, anHyp);
642
643   // sub-shapes
644   if (!SMESH_Hypothesis::IsStatusFatal(ret) &&
645       anHyp->GetDim() <= SMESH_Gen::GetShapeDim(aSubShape)) // is added on father
646   {
647     event = isAlgo ? SMESH_subMesh::ADD_FATHER_ALGO : SMESH_subMesh::ADD_FATHER_HYP;
648
649     SMESH_Hypothesis::Hypothesis_Status ret2 =
650       subMesh->SubMeshesAlgoStateEngine(event, anHyp);
651     if (ret2 > ret)
652       ret = ret2;
653
654     // check concurent hypotheses on ancestors
655     if (ret < SMESH_Hypothesis::HYP_CONCURENT && !isGlobalHyp )
656     {
657       SMESH_subMeshIteratorPtr smIt = subMesh->getDependsOnIterator(false,false);
658       while ( smIt->more() ) {
659         SMESH_subMesh* sm = smIt->next();
660         if ( sm->IsApplicableHypotesis( anHyp )) {
661           ret2 = sm->CheckConcurentHypothesis( anHyp->GetType() );
662           if (ret2 > ret) {
663             ret = ret2;
664             break;
665           }
666         }
667       }
668     }
669   }
670   HasModificationsToDiscard(); // to reset _isModified flag if a mesh becomes empty
671
672   if(MYDEBUG) subMesh->DumpAlgoState(true);
673   if(MYDEBUG) SCRUTE(ret);
674   return ret;
675 }
676
677 //=============================================================================
678 /*!
679  * 
680  */
681 //=============================================================================
682
683 SMESH_Hypothesis::Hypothesis_Status
684   SMESH_Mesh::RemoveHypothesis(const TopoDS_Shape & aSubShape,
685                                int anHypId)throw(SALOME_Exception)
686 {
687   Unexpect aCatch(SalomeException);
688   if(MYDEBUG) MESSAGE("SMESH_Mesh::RemoveHypothesis");
689   
690   StudyContextStruct *sc = _gen->GetStudyContext(_studyId);
691   if (sc->mapHypothesis.find(anHypId) == sc->mapHypothesis.end())
692     throw SALOME_Exception(LOCALIZED("hypothesis does not exist"));
693   
694   SMESH_Hypothesis *anHyp = sc->mapHypothesis[anHypId];
695   if(MYDEBUG) {
696     SCRUTE(anHyp->GetType());
697   }
698   
699   // shape 
700   
701   bool isAlgo = ( !anHyp->GetType() == SMESHDS_Hypothesis::PARAM_ALGO );
702   int event = isAlgo ? SMESH_subMesh::REMOVE_ALGO : SMESH_subMesh::REMOVE_HYP;
703
704   SMESH_subMesh *subMesh = GetSubMesh(aSubShape);
705
706   SMESH_Hypothesis::Hypothesis_Status ret = subMesh->AlgoStateEngine(event, anHyp);
707
708   // there may appear concurrent hyps that were covered by the removed hyp
709   if (ret < SMESH_Hypothesis::HYP_CONCURENT &&
710       subMesh->IsApplicableHypotesis( anHyp ) &&
711       subMesh->CheckConcurentHypothesis( anHyp->GetType() ) != SMESH_Hypothesis::HYP_OK)
712     ret = SMESH_Hypothesis::HYP_CONCURENT;
713
714   // sub-shapes
715   if (!SMESH_Hypothesis::IsStatusFatal(ret) &&
716       anHyp->GetDim() <= SMESH_Gen::GetShapeDim(aSubShape)) // is removed from father
717   {
718     event = isAlgo ? SMESH_subMesh::REMOVE_FATHER_ALGO : SMESH_subMesh::REMOVE_FATHER_HYP;
719
720     SMESH_Hypothesis::Hypothesis_Status ret2 =
721       subMesh->SubMeshesAlgoStateEngine(event, anHyp);
722     if (ret2 > ret) // more severe
723       ret = ret2;
724
725     // check concurent hypotheses on ancestors
726     if (ret < SMESH_Hypothesis::HYP_CONCURENT && !IsMainShape( aSubShape ) )
727     {
728       SMESH_subMeshIteratorPtr smIt = subMesh->getDependsOnIterator(false,false);
729       while ( smIt->more() ) {
730         SMESH_subMesh* sm = smIt->next();
731         if ( sm->IsApplicableHypotesis( anHyp )) {
732           ret2 = sm->CheckConcurentHypothesis( anHyp->GetType() );
733           if (ret2 > ret) {
734             ret = ret2;
735             break;
736           }
737         }
738       }
739     }
740   }
741
742   HasModificationsToDiscard(); // to reset _isModified flag if mesh become empty
743
744   if(MYDEBUG) subMesh->DumpAlgoState(true);
745   if(MYDEBUG) SCRUTE(ret);
746   return ret;
747 }
748
749 //=============================================================================
750 /*!
751  * 
752  */
753 //=============================================================================
754
755 const list<const SMESHDS_Hypothesis*>&
756 SMESH_Mesh::GetHypothesisList(const TopoDS_Shape & aSubShape) const
757   throw(SALOME_Exception)
758 {
759   Unexpect aCatch(SalomeException);
760   return _myMeshDS->GetHypothesis(aSubShape);
761 }
762
763 //=======================================================================
764 /*!
765  * \brief Return the hypothesis assigned to the shape
766  *  \param aSubShape    - the shape to check
767  *  \param aFilter      - the hypothesis filter
768  *  \param andAncestors - flag to check hypos assigned to ancestors of the shape
769  *  \param assignedTo   - to return the shape the found hypo is assigned to
770  *  \retval SMESH_Hypothesis* - the first hypo passed through aFilter
771  */
772 //=======================================================================
773
774 const SMESH_Hypothesis * SMESH_Mesh::GetHypothesis(const TopoDS_Shape &    aSubShape,
775                                                    const SMESH_HypoFilter& aFilter,
776                                                    const bool              andAncestors,
777                                                    TopoDS_Shape*           assignedTo) const
778 {
779   {
780     const list<const SMESHDS_Hypothesis*>& hypList = _myMeshDS->GetHypothesis(aSubShape);
781     list<const SMESHDS_Hypothesis*>::const_iterator hyp = hypList.begin();
782     for ( ; hyp != hypList.end(); hyp++ ) {
783       const SMESH_Hypothesis * h = cSMESH_Hyp( *hyp );
784       if ( aFilter.IsOk( h, aSubShape)) {
785         if ( assignedTo ) *assignedTo = aSubShape;
786         return h;
787       }
788     }
789   }
790   if ( andAncestors )
791   {
792     // user sorted submeshes of ancestors, according to stored submesh priority
793     const list<SMESH_subMesh*> smList = getAncestorsSubMeshes( aSubShape );
794     list<SMESH_subMesh*>::const_iterator smIt = smList.begin(); 
795     for ( ; smIt != smList.end(); smIt++ )
796     {
797       const TopoDS_Shape& curSh = (*smIt)->GetSubShape();
798       const list<const SMESHDS_Hypothesis*>& hypList = _myMeshDS->GetHypothesis(curSh);
799       list<const SMESHDS_Hypothesis*>::const_iterator hyp = hypList.begin();
800       for ( ; hyp != hypList.end(); hyp++ ) {
801         const SMESH_Hypothesis * h = cSMESH_Hyp( *hyp );
802         if (aFilter.IsOk( h, curSh )) {
803           if ( assignedTo ) *assignedTo = curSh;
804           return h;
805         }
806       }
807     }
808   }
809   return 0;
810 }
811
812 //================================================================================
813 /*!
814  * \brief Return hypothesis assigned to the shape
815   * \param aSubShape - the shape to check
816   * \param aFilter - the hypothesis filter
817   * \param aHypList - the list of the found hypotheses
818   * \param andAncestors - flag to check hypos assigned to ancestors of the shape
819   * \retval int - number of unique hypos in aHypList
820  */
821 //================================================================================
822
823 int SMESH_Mesh::GetHypotheses(const TopoDS_Shape &                aSubShape,
824                               const SMESH_HypoFilter&             aFilter,
825                               list <const SMESHDS_Hypothesis * >& aHypList,
826                               const bool                          andAncestors,
827                               list< TopoDS_Shape > *              assignedTo/*=0*/) const
828 {
829   set<string> hypTypes; // to exclude same type hypos from the result list
830   int nbHyps = 0;
831
832   // only one main hypothesis is allowed
833   bool mainHypFound = false;
834
835   // fill in hypTypes
836   list<const SMESHDS_Hypothesis*>::const_iterator hyp;
837   for ( hyp = aHypList.begin(); hyp != aHypList.end(); hyp++ ) {
838     if ( hypTypes.insert( (*hyp)->GetName() ).second )
839       nbHyps++;
840     if ( !cSMESH_Hyp(*hyp)->IsAuxiliary() )
841       mainHypFound = true;
842   }
843
844   // get hypos from aSubShape
845   {
846     const list<const SMESHDS_Hypothesis*>& hypList = _myMeshDS->GetHypothesis(aSubShape);
847     for ( hyp = hypList.begin(); hyp != hypList.end(); hyp++ )
848       if ( aFilter.IsOk (cSMESH_Hyp( *hyp ), aSubShape) &&
849            ( cSMESH_Hyp(*hyp)->IsAuxiliary() || !mainHypFound ) &&
850            hypTypes.insert( (*hyp)->GetName() ).second )
851       {
852         aHypList.push_back( *hyp );
853         nbHyps++;
854         if ( !cSMESH_Hyp(*hyp)->IsAuxiliary() )
855           mainHypFound = true;
856         if ( assignedTo ) assignedTo->push_back( aSubShape );
857       }
858   }
859
860   // get hypos from ancestors of aSubShape
861   if ( andAncestors )
862   {
863     TopTools_MapOfShape map;
864
865     // user sorted submeshes of ancestors, according to stored submesh priority
866     const list<SMESH_subMesh*> smList = getAncestorsSubMeshes( aSubShape );
867     list<SMESH_subMesh*>::const_iterator smIt = smList.begin(); 
868     for ( ; smIt != smList.end(); smIt++ )
869     {
870       const TopoDS_Shape& curSh = (*smIt)->GetSubShape();
871      if ( !map.Add( curSh ))
872         continue;
873       const list<const SMESHDS_Hypothesis*>& hypList = _myMeshDS->GetHypothesis(curSh);
874       for ( hyp = hypList.begin(); hyp != hypList.end(); hyp++ )
875         if (aFilter.IsOk( cSMESH_Hyp( *hyp ), curSh ) &&
876             ( cSMESH_Hyp(*hyp)->IsAuxiliary() || !mainHypFound ) &&
877             hypTypes.insert( (*hyp)->GetName() ).second )
878         {
879           aHypList.push_back( *hyp );
880           nbHyps++;
881           if ( !cSMESH_Hyp(*hyp)->IsAuxiliary() )
882             mainHypFound = true;
883           if ( assignedTo ) assignedTo->push_back( curSh );
884         }
885     }
886   }
887   return nbHyps;
888 }
889
890 //================================================================================
891 /*!
892  * \brief Return a hypothesis by its ID
893  */
894 //================================================================================
895
896 SMESH_Hypothesis * SMESH_Mesh::GetHypothesis(const int anHypId) const
897 {
898   StudyContextStruct *sc = _gen->GetStudyContext(_studyId);
899   if (sc->mapHypothesis.find(anHypId) == sc->mapHypothesis.end())
900     return NULL;
901
902   SMESH_Hypothesis *anHyp = sc->mapHypothesis[anHypId];
903   return anHyp;
904 }
905
906 //=============================================================================
907 /*!
908  * 
909  */
910 //=============================================================================
911
912 const list<SMESHDS_Command*> & SMESH_Mesh::GetLog() throw(SALOME_Exception)
913 {
914   Unexpect aCatch(SalomeException);
915   if(MYDEBUG) MESSAGE("SMESH_Mesh::GetLog");
916   return _myMeshDS->GetScript()->GetCommands();
917 }
918
919 //=============================================================================
920 /*!
921  * 
922  */
923 //=============================================================================
924 void SMESH_Mesh::ClearLog() throw(SALOME_Exception)
925 {
926   Unexpect aCatch(SalomeException);
927   if(MYDEBUG) MESSAGE("SMESH_Mesh::ClearLog");
928   _myMeshDS->GetScript()->Clear();
929 }
930
931 //=============================================================================
932 /*!
933  * Get or Create the SMESH_subMesh object implementation
934  */
935 //=============================================================================
936
937 SMESH_subMesh *SMESH_Mesh::GetSubMesh(const TopoDS_Shape & aSubShape)
938   throw(SALOME_Exception)
939 {
940   Unexpect aCatch(SalomeException);
941   SMESH_subMesh *aSubMesh;
942   int index = _myMeshDS->ShapeToIndex(aSubShape);
943
944   // for submeshes on GEOM Group
945   if (( !index || index > _nbSubShapes ) && aSubShape.ShapeType() == TopAbs_COMPOUND ) {
946     TopoDS_Iterator it( aSubShape );
947     if ( it.More() )
948     {
949       index = _myMeshDS->AddCompoundSubmesh( aSubShape, it.Value().ShapeType() );
950       // fill map of Ancestors
951       while ( _nbSubShapes < index )
952         fillAncestorsMap( _myMeshDS->IndexToShape( ++_nbSubShapes ));
953     }
954   }
955 //   if ( !index )
956 //     return NULL; // neither sub-shape nor a group
957
958   map <int, SMESH_subMesh *>::iterator i_sm = _mapSubMesh.find(index);
959   if ( i_sm != _mapSubMesh.end())
960   {
961     aSubMesh = i_sm->second;
962   }
963   else
964   {
965     aSubMesh = new SMESH_subMesh(index, this, _myMeshDS, aSubShape);
966     _mapSubMesh[index] = aSubMesh;
967   }
968   return aSubMesh;
969 }
970
971 //=============================================================================
972 /*!
973  * Get the SMESH_subMesh object implementation. Dont create it, return null
974  * if it does not exist.
975  */
976 //=============================================================================
977
978 SMESH_subMesh *SMESH_Mesh::GetSubMeshContaining(const TopoDS_Shape & aSubShape) const
979   throw(SALOME_Exception)
980 {
981   Unexpect aCatch(SalomeException);
982   SMESH_subMesh *aSubMesh = NULL;
983   
984   int index = _myMeshDS->ShapeToIndex(aSubShape);
985
986   map <int, SMESH_subMesh *>::const_iterator i_sm = _mapSubMesh.find(index);
987   if ( i_sm != _mapSubMesh.end())
988     aSubMesh = i_sm->second;
989
990   return aSubMesh;
991 }
992 //=============================================================================
993 /*!
994  * Get the SMESH_subMesh object implementation. Dont create it, return null
995  * if it does not exist.
996  */
997 //=============================================================================
998
999 SMESH_subMesh *SMESH_Mesh::GetSubMeshContaining(const int aShapeID) const
1000 throw(SALOME_Exception)
1001 {
1002   Unexpect aCatch(SalomeException);
1003   
1004   map <int, SMESH_subMesh *>::const_iterator i_sm = _mapSubMesh.find(aShapeID);
1005   if (i_sm == _mapSubMesh.end())
1006     return NULL;
1007   return i_sm->second;
1008 }
1009 //================================================================================
1010 /*!
1011  * \brief Return submeshes of groups containing the given sub-shape
1012  */
1013 //================================================================================
1014
1015 list<SMESH_subMesh*>
1016 SMESH_Mesh::GetGroupSubMeshesContaining(const TopoDS_Shape & aSubShape) const
1017   throw(SALOME_Exception)
1018 {
1019   Unexpect aCatch(SalomeException);
1020   list<SMESH_subMesh*> found;
1021
1022   SMESH_subMesh * subMesh = GetSubMeshContaining(aSubShape);
1023   if ( !subMesh )
1024     return found;
1025
1026   // submeshes of groups have max IDs, so search from the map end
1027   map<int, SMESH_subMesh *>::const_reverse_iterator i_sm;
1028   for ( i_sm = _mapSubMesh.rbegin(); i_sm != _mapSubMesh.rend(); ++i_sm) {
1029     SMESHDS_SubMesh * ds = i_sm->second->GetSubMeshDS();
1030     if ( ds && ds->IsComplexSubmesh() ) {
1031       if ( SMESH_MesherHelper::IsSubShape( aSubShape, i_sm->second->GetSubShape() ))
1032       {
1033         found.push_back( i_sm->second );
1034         //break;
1035       }
1036     } else {
1037       break; // the rest sub-meshes are not those of groups
1038     }
1039   }
1040
1041   if ( found.empty() ) // maybe the main shape is a COMPOUND (issue 0021530)
1042   {
1043     if ( SMESH_subMesh * mainSM = GetSubMeshContaining(1))
1044       if ( mainSM->GetSubShape().ShapeType() == TopAbs_COMPOUND )
1045       {
1046         TopoDS_Iterator it( mainSM->GetSubShape() );
1047         if ( it.Value().ShapeType() == aSubShape.ShapeType() &&
1048              SMESH_MesherHelper::IsSubShape( aSubShape, mainSM->GetSubShape() ))
1049           found.push_back( mainSM );
1050       }
1051   }
1052   return found;
1053 }
1054 //=======================================================================
1055 //function : IsUsedHypothesis
1056 //purpose  : Return True if anHyp is used to mesh aSubShape
1057 //=======================================================================
1058
1059 bool SMESH_Mesh::IsUsedHypothesis(SMESHDS_Hypothesis * anHyp,
1060                                   const SMESH_subMesh* aSubMesh)
1061 {
1062   SMESH_Hypothesis* hyp = static_cast<SMESH_Hypothesis*>(anHyp);
1063
1064   // check if anHyp can be used to mesh aSubMesh
1065   if ( !aSubMesh || !aSubMesh->IsApplicableHypotesis( hyp ))
1066     return false;
1067
1068   const TopoDS_Shape & aSubShape = const_cast<SMESH_subMesh*>( aSubMesh )->GetSubShape();
1069
1070   SMESH_Algo *algo = _gen->GetAlgo(*this, aSubShape );
1071
1072   // algorithm
1073   if (anHyp->GetType() > SMESHDS_Hypothesis::PARAM_ALGO)
1074     return ( anHyp == algo );
1075
1076   // algorithm parameter
1077   if (algo)
1078   {
1079     // look trough hypotheses used by algo
1080     SMESH_HypoFilter hypoKind;
1081     if ( algo->InitCompatibleHypoFilter( hypoKind, !hyp->IsAuxiliary() )) {
1082       list <const SMESHDS_Hypothesis * > usedHyps;
1083       if ( GetHypotheses( aSubShape, hypoKind, usedHyps, true ))
1084         return ( find( usedHyps.begin(), usedHyps.end(), anHyp ) != usedHyps.end() );
1085     }
1086   }
1087
1088   // look through all assigned hypotheses
1089   //SMESH_HypoFilter filter( SMESH_HypoFilter::Is( hyp ));
1090   return false; //GetHypothesis( aSubShape, filter, true );
1091 }
1092
1093 //=============================================================================
1094 /*!
1095  *
1096  */
1097 //=============================================================================
1098
1099 const list < SMESH_subMesh * >&
1100 SMESH_Mesh::GetSubMeshUsingHypothesis(SMESHDS_Hypothesis * anHyp)
1101   throw(SALOME_Exception)
1102 {
1103   Unexpect aCatch(SalomeException);
1104   if(MYDEBUG) MESSAGE("SMESH_Mesh::GetSubMeshUsingHypothesis");
1105   map < int, SMESH_subMesh * >::iterator itsm;
1106   _subMeshesUsingHypothesisList.clear();
1107   for (itsm = _mapSubMesh.begin(); itsm != _mapSubMesh.end(); itsm++)
1108   {
1109     SMESH_subMesh *aSubMesh = (*itsm).second;
1110     if ( IsUsedHypothesis ( anHyp, aSubMesh ))
1111       _subMeshesUsingHypothesisList.push_back(aSubMesh);
1112   }
1113   return _subMeshesUsingHypothesisList;
1114 }
1115
1116 //=======================================================================
1117 //function : NotifySubMeshesHypothesisModification
1118 //purpose  : Say all submeshes using theChangedHyp that it has been modified
1119 //=======================================================================
1120
1121 void SMESH_Mesh::NotifySubMeshesHypothesisModification(const SMESH_Hypothesis* hyp)
1122 {
1123   Unexpect aCatch(SalomeException);
1124
1125   if ( !GetMeshDS()->IsUsedHypothesis( hyp ))
1126     return;
1127
1128   if (_callUp)
1129     _callUp->HypothesisModified();
1130
1131   const SMESH_Algo *foundAlgo = 0;
1132   SMESH_HypoFilter algoKind, compatibleHypoKind;
1133   list <const SMESHDS_Hypothesis * > usedHyps;
1134
1135
1136   map < int, SMESH_subMesh * >::iterator itsm;
1137   for (itsm = _mapSubMesh.begin(); itsm != _mapSubMesh.end(); itsm++)
1138   {
1139     SMESH_subMesh *aSubMesh = (*itsm).second;
1140     if ( aSubMesh->IsApplicableHypotesis( hyp ))
1141     {
1142       const TopoDS_Shape & aSubShape = aSubMesh->GetSubShape();
1143
1144       if ( !foundAlgo ) // init filter for algo search
1145         algoKind.Init( THypType::IsAlgo() ).And( THypType::IsApplicableTo( aSubShape ));
1146       
1147       const SMESH_Algo *algo = static_cast<const SMESH_Algo*>
1148         ( GetHypothesis( aSubShape, algoKind, true ));
1149
1150       if ( algo )
1151       {
1152         bool sameAlgo = ( algo == foundAlgo );
1153         if ( !sameAlgo && foundAlgo )
1154           sameAlgo = ( strcmp( algo->GetName(), foundAlgo->GetName() ) == 0);
1155
1156         if ( !sameAlgo ) { // init filter for used hypos search
1157           if ( !algo->InitCompatibleHypoFilter( compatibleHypoKind, !hyp->IsAuxiliary() ))
1158             continue; // algo does not use any hypothesis
1159           foundAlgo = algo;
1160         }
1161
1162         // check if hyp is used by algo
1163         usedHyps.clear();
1164         if ( GetHypotheses( aSubShape, compatibleHypoKind, usedHyps, true ) &&
1165              find( usedHyps.begin(), usedHyps.end(), hyp ) != usedHyps.end() )
1166         {
1167           aSubMesh->AlgoStateEngine(SMESH_subMesh::MODIF_HYP,
1168                                     const_cast< SMESH_Hypothesis*>( hyp ));
1169         }
1170       }
1171     }
1172   }
1173   HasModificationsToDiscard(); // to reset _isModified flag if mesh becomes empty
1174   GetMeshDS()->Modified();
1175 }
1176
1177 //=============================================================================
1178 /*!
1179  *  Auto color functionality
1180  */
1181 //=============================================================================
1182 void SMESH_Mesh::SetAutoColor(bool theAutoColor) throw(SALOME_Exception)
1183 {
1184   Unexpect aCatch(SalomeException);
1185   _isAutoColor = theAutoColor;
1186 }
1187
1188 bool SMESH_Mesh::GetAutoColor() throw(SALOME_Exception)
1189 {
1190   Unexpect aCatch(SalomeException);
1191   return _isAutoColor;
1192 }
1193
1194 //=======================================================================
1195 //function : SetIsModified
1196 //purpose  : Set the flag meaning that the mesh has been edited "manually"
1197 //=======================================================================
1198
1199 void SMESH_Mesh::SetIsModified(bool isModified)
1200 {
1201   _isModified = isModified;
1202
1203   if ( _isModified )
1204     // check if mesh becomes empty as result of modification
1205     HasModificationsToDiscard();
1206 }
1207
1208 //=======================================================================
1209 //function : HasModificationsToDiscard
1210 //purpose  : Return true if the mesh has been edited since a total re-compute
1211 //           and those modifications may prevent successful partial re-compute.
1212 //           As a side effect reset _isModified flag if mesh is empty
1213 //issue    : 0020693
1214 //=======================================================================
1215
1216 bool SMESH_Mesh::HasModificationsToDiscard() const
1217 {
1218   if ( ! _isModified )
1219     return false;
1220
1221   // return true if the next Compute() will be partial and
1222   // existing but changed elements may prevent successful re-compute
1223   bool hasComputed = false, hasNotComputed = false;
1224   map <int, SMESH_subMesh*>::const_iterator i_sm = _mapSubMesh.begin();
1225   for ( ; i_sm != _mapSubMesh.end() ; ++i_sm )
1226     switch ( i_sm->second->GetSubShape().ShapeType() )
1227     {
1228     case TopAbs_EDGE:
1229     case TopAbs_FACE:
1230     case TopAbs_SOLID:
1231       if ( i_sm->second->IsMeshComputed() )
1232         hasComputed = true;
1233       else
1234         hasNotComputed = true;
1235       if ( hasComputed && hasNotComputed)
1236         return true;
1237     }
1238
1239   if ( NbNodes() < 1 )
1240     const_cast<SMESH_Mesh*>(this)->_isModified = false;
1241
1242   return false;
1243 }
1244
1245 //================================================================================
1246 /*!
1247  * \brief Check if any groups of the same type have equal names
1248  */
1249 //================================================================================
1250
1251 bool SMESH_Mesh::HasDuplicatedGroupNamesMED()
1252 {
1253   //set<string> aGroupNames; // Corrected for Mantis issue 0020028
1254   map< SMDSAbs_ElementType, set<string> > aGroupNames;
1255   for ( map<int, SMESH_Group*>::iterator it = _mapGroup.begin(); it != _mapGroup.end(); it++ )
1256   {
1257     SMESH_Group* aGroup = it->second;
1258     SMDSAbs_ElementType aType = aGroup->GetGroupDS()->GetType();
1259     string aGroupName = aGroup->GetName();
1260     aGroupName.resize(MAX_MED_GROUP_NAME_LENGTH);
1261     if (!aGroupNames[aType].insert(aGroupName).second)
1262       return true;
1263   }
1264
1265   return false;
1266 }
1267
1268 //================================================================================
1269 /*!
1270  * \brief Export the mesh to a med file
1271  */
1272 //================================================================================
1273
1274 void SMESH_Mesh::ExportMED(const char *        file, 
1275                            const char*         theMeshName, 
1276                            bool                theAutoGroups,
1277                            int                 theVersion,
1278                            const SMESHDS_Mesh* meshPart,
1279                            bool                theAutoDimension)
1280   throw(SALOME_Exception)
1281 {
1282   SMESH_TRY;
1283
1284   DriverMED_W_SMESHDS_Mesh myWriter;
1285   myWriter.SetFile         ( file, MED::EVersion(theVersion) );
1286   myWriter.SetMesh         ( meshPart ? (SMESHDS_Mesh*) meshPart : _myMeshDS   );
1287   myWriter.SetAutoDimension( theAutoDimension );
1288   if ( !theMeshName ) 
1289     myWriter.SetMeshId     ( _id         );
1290   else {
1291     myWriter.SetMeshId     ( -1          );
1292     myWriter.SetMeshName   ( theMeshName );
1293   }
1294
1295   if ( theAutoGroups ) {
1296     myWriter.AddGroupOfNodes();
1297     myWriter.AddGroupOfEdges();
1298     myWriter.AddGroupOfFaces();
1299     myWriter.AddGroupOfVolumes();
1300   }
1301
1302   // Pass groups to writer. Provide unique group names.
1303   //set<string> aGroupNames; // Corrected for Mantis issue 0020028
1304   if ( !meshPart )
1305   {
1306     map< SMDSAbs_ElementType, set<string> > aGroupNames;
1307     char aString [256];
1308     int maxNbIter = 10000; // to guarantee cycle finish
1309     for ( map<int, SMESH_Group*>::iterator it = _mapGroup.begin(); it != _mapGroup.end(); it++ ) {
1310       SMESH_Group*       aGroup   = it->second;
1311       SMESHDS_GroupBase* aGroupDS = aGroup->GetGroupDS();
1312       if ( aGroupDS ) {
1313         SMDSAbs_ElementType aType = aGroupDS->GetType();
1314         string aGroupName0 = aGroup->GetName();
1315         aGroupName0.resize(MAX_MED_GROUP_NAME_LENGTH);
1316         string aGroupName = aGroupName0;
1317         for (int i = 1; !aGroupNames[aType].insert(aGroupName).second && i < maxNbIter; i++) {
1318           sprintf(&aString[0], "GR_%d_%s", i, aGroupName0.c_str());
1319           aGroupName = aString;
1320           aGroupName.resize(MAX_MED_GROUP_NAME_LENGTH);
1321         }
1322         aGroupDS->SetStoreName( aGroupName.c_str() );
1323         myWriter.AddGroup( aGroupDS );
1324       }
1325     }
1326   }
1327   // Perform export
1328   myWriter.Perform();
1329
1330   SMESH_CATCH( SMESH::throwSalomeEx );
1331 }
1332
1333 //================================================================================
1334 /*!
1335  * \brief Export the mesh to a SAUV file
1336  */
1337 //================================================================================
1338
1339 void SMESH_Mesh::ExportSAUV(const char *file, 
1340                             const char* theMeshName, 
1341                             bool theAutoGroups)
1342   throw(SALOME_Exception)
1343 {
1344   std::string medfilename(file);
1345   medfilename += ".med";
1346   std::string cmd;
1347 #ifdef WIN32
1348   cmd = "%PYTHONBIN% ";
1349 #else
1350   cmd = "python ";
1351 #endif
1352   cmd += "-c \"";
1353   cmd += "from medutilities import my_remove ; my_remove(r'" + medfilename + "')";
1354   cmd += "\"";
1355   system(cmd.c_str());
1356   ExportMED(medfilename.c_str(), theMeshName, theAutoGroups, 1);
1357 #ifdef WIN32
1358   cmd = "%PYTHONBIN% ";
1359 #else
1360   cmd = "python ";
1361 #endif
1362   cmd += "-c \"";
1363   cmd += "from medutilities import convert ; convert(r'" + medfilename + "', 'MED', 'GIBI', 1, r'" + file + "')";
1364   cmd += "\"";
1365   system(cmd.c_str());
1366 #ifdef WIN32
1367   cmd = "%PYTHONBIN% ";
1368 #else
1369   cmd = "python ";
1370 #endif
1371   cmd += "-c \"";
1372   cmd += "from medutilities import my_remove ; my_remove(r'" + medfilename + "')";
1373   cmd += "\"";
1374   system(cmd.c_str());
1375 }
1376
1377 //================================================================================
1378 /*!
1379  * \brief Export the mesh to a DAT file
1380  */
1381 //================================================================================
1382
1383 void SMESH_Mesh::ExportDAT(const char *        file,
1384                            const SMESHDS_Mesh* meshPart) throw(SALOME_Exception)
1385 {
1386   Unexpect aCatch(SalomeException);
1387   DriverDAT_W_SMDS_Mesh myWriter;
1388   myWriter.SetFile( file );
1389   myWriter.SetMesh( meshPart ? (SMESHDS_Mesh*) meshPart : _myMeshDS );
1390   myWriter.SetMeshId(_id);
1391   myWriter.Perform();
1392 }
1393
1394 //================================================================================
1395 /*!
1396  * \brief Export the mesh to an UNV file
1397  */
1398 //================================================================================
1399
1400 void SMESH_Mesh::ExportUNV(const char *        file,
1401                            const SMESHDS_Mesh* meshPart) throw(SALOME_Exception)
1402 {
1403   Unexpect aCatch(SalomeException);
1404   DriverUNV_W_SMDS_Mesh myWriter;
1405   myWriter.SetFile( file );
1406   myWriter.SetMesh( meshPart ? (SMESHDS_Mesh*) meshPart : _myMeshDS );
1407   myWriter.SetMeshId(_id);
1408   //  myWriter.SetGroups(_mapGroup);
1409
1410   if ( !meshPart )
1411   {
1412     for ( map<int, SMESH_Group*>::iterator it = _mapGroup.begin(); it != _mapGroup.end(); it++ ) {
1413       SMESH_Group*       aGroup   = it->second;
1414       SMESHDS_GroupBase* aGroupDS = aGroup->GetGroupDS();
1415       if ( aGroupDS ) {
1416         string aGroupName = aGroup->GetName();
1417         aGroupDS->SetStoreName( aGroupName.c_str() );
1418         myWriter.AddGroup( aGroupDS );
1419       }
1420     }
1421   }
1422   myWriter.Perform();
1423 }
1424
1425 //================================================================================
1426 /*!
1427  * \brief Export the mesh to an STL file
1428  */
1429 //================================================================================
1430
1431 void SMESH_Mesh::ExportSTL(const char *        file,
1432                            const bool          isascii,
1433                            const SMESHDS_Mesh* meshPart) throw(SALOME_Exception)
1434 {
1435   Unexpect aCatch(SalomeException);
1436   DriverSTL_W_SMDS_Mesh myWriter;
1437   myWriter.SetFile( file );
1438   myWriter.SetIsAscii( isascii );
1439   myWriter.SetMesh( meshPart ? (SMESHDS_Mesh*) meshPart : _myMeshDS);
1440   myWriter.SetMeshId(_id);
1441   myWriter.Perform();
1442 }
1443
1444 //================================================================================
1445 /*!
1446  * \brief Export the mesh to the CGNS file
1447  */
1448 //================================================================================
1449
1450 void SMESH_Mesh::ExportCGNS(const char *        file,
1451                             const SMESHDS_Mesh* meshDS)
1452 {
1453   int res = Driver_Mesh::DRS_FAIL;
1454 #ifdef WITH_CGNS
1455   DriverCGNS_Write myWriter;
1456   myWriter.SetFile( file );
1457   myWriter.SetMesh( const_cast<SMESHDS_Mesh*>( meshDS ));
1458   myWriter.SetMeshName( SMESH_Comment("Mesh_") << meshDS->GetPersistentId());
1459   res = myWriter.Perform();
1460 #endif
1461   if ( res != Driver_Mesh::DRS_OK )
1462     throw SALOME_Exception("Export failed");
1463 }
1464
1465 //================================================================================
1466 /*!
1467  * \brief Export the mesh to a GMF file
1468  */
1469 //================================================================================
1470
1471 void SMESH_Mesh::ExportGMF(const char *        file,
1472                            const SMESHDS_Mesh* meshDS,
1473                            bool                withRequiredGroups)
1474 {
1475   DriverGMF_Write myWriter;
1476   myWriter.SetFile( file );
1477   myWriter.SetMesh( const_cast<SMESHDS_Mesh*>( meshDS ));
1478   myWriter.SetExportRequiredGroups( withRequiredGroups );
1479
1480   myWriter.Perform();
1481 }
1482
1483 //================================================================================
1484 /*!
1485  * \brief Return a ratio of "compute cost" of computed sub-meshes to the whole
1486  *        "compute cost".
1487  */
1488 //================================================================================
1489
1490 double SMESH_Mesh::GetComputeProgress() const
1491 {
1492   double totalCost = 1e-100, computedCost = 0;
1493   const SMESH_subMesh* curSM = _gen->GetCurrentSubMesh();
1494
1495   // get progress of a current algo
1496   TColStd_MapOfInteger currentSubIds; 
1497   if ( curSM )
1498     if ( SMESH_Algo* algo = curSM->GetAlgo() )
1499     {
1500       int algoNotDoneCost = 0, algoDoneCost = 0;
1501       const std::vector<SMESH_subMesh*>& smToCompute = algo->SubMeshesToCompute();
1502       for ( size_t i = 0; i < smToCompute.size(); ++i )
1503       {
1504         if ( smToCompute[i]->IsEmpty() )
1505           algoNotDoneCost += smToCompute[i]->GetComputeCost();
1506         else
1507           algoDoneCost += smToCompute[i]->GetComputeCost();
1508         currentSubIds.Add( smToCompute[i]->GetId() );
1509       }
1510       double rate = 0;
1511       try
1512       {
1513         OCC_CATCH_SIGNALS;
1514         rate = algo->GetProgress();
1515       }
1516       catch (...) {
1517 #ifdef _DEBUG_
1518         cerr << "Exception in " << algo->GetName() << "::GetProgress()" << endl;
1519 #endif
1520       }
1521       if ( 0. < rate && rate < 1.001 )
1522       {
1523         computedCost += rate * ( algoDoneCost + algoNotDoneCost );
1524       }
1525       else
1526       {
1527         rate = algo->GetProgressByTic();
1528         computedCost += algoDoneCost + rate * algoNotDoneCost;
1529       }
1530       // cout << "rate: "<<rate << " algoNotDoneCost: " << algoNotDoneCost << endl;
1531     }
1532
1533   // get cost of already treated sub-meshes
1534   if ( SMESH_subMesh* mainSM = GetSubMeshContaining( 1 ))
1535   {
1536     SMESH_subMeshIteratorPtr smIt = mainSM->getDependsOnIterator(/*includeSelf=*/true);
1537     while ( smIt->more() )
1538     {
1539       const SMESH_subMesh* sm = smIt->next();
1540       const int smCost = sm->GetComputeCost();
1541       totalCost += smCost;
1542       if ( !currentSubIds.Contains( sm->GetId() ) )
1543       {
1544         if (( !sm->IsEmpty() ) ||
1545             ( sm->GetComputeState() == SMESH_subMesh::FAILED_TO_COMPUTE &&
1546               !sm->DependsOn( curSM ) ))
1547           computedCost += smCost;
1548       }
1549     }
1550   }
1551   // cout << "Total: " << totalCost
1552   //      << " computed: " << computedCost << " progress: " << computedCost / totalCost
1553   //      << " nbElems: " << GetMeshDS()->GetMeshInfo().NbElements() << endl;
1554   return computedCost / totalCost;
1555 }
1556
1557 //================================================================================
1558 /*!
1559  * \brief Return number of nodes in the mesh
1560  */
1561 //================================================================================
1562
1563 int SMESH_Mesh::NbNodes() const throw(SALOME_Exception)
1564 {
1565   Unexpect aCatch(SalomeException);
1566   return _myMeshDS->NbNodes();
1567 }
1568
1569 //================================================================================
1570 /*!
1571  * \brief  Return number of edges of given order in the mesh
1572  */
1573 //================================================================================
1574
1575 int SMESH_Mesh::Nb0DElements() const throw(SALOME_Exception)
1576 {
1577   Unexpect aCatch(SalomeException);
1578   return _myMeshDS->GetMeshInfo().Nb0DElements();
1579 }
1580
1581 //================================================================================
1582 /*!
1583  * \brief  Return number of edges of given order in the mesh
1584  */
1585 //================================================================================
1586
1587 int SMESH_Mesh::NbEdges(SMDSAbs_ElementOrder order) const throw(SALOME_Exception)
1588 {
1589   Unexpect aCatch(SalomeException);
1590   return _myMeshDS->GetMeshInfo().NbEdges(order);
1591 }
1592
1593 //================================================================================
1594 /*!
1595  * \brief Return number of faces of given order in the mesh
1596  */
1597 //================================================================================
1598
1599 int SMESH_Mesh::NbFaces(SMDSAbs_ElementOrder order) const throw(SALOME_Exception)
1600 {
1601   Unexpect aCatch(SalomeException);
1602   return _myMeshDS->GetMeshInfo().NbFaces(order);
1603 }
1604
1605 //================================================================================
1606 /*!
1607  * \brief Return the number of faces in the mesh
1608  */
1609 //================================================================================
1610
1611 int SMESH_Mesh::NbTriangles(SMDSAbs_ElementOrder order) const throw(SALOME_Exception)
1612 {
1613   Unexpect aCatch(SalomeException);
1614   return _myMeshDS->GetMeshInfo().NbTriangles(order);
1615 }
1616
1617 //================================================================================
1618 /*!
1619  * \brief Return number of biquadratic triangles in the mesh
1620  */
1621 //================================================================================
1622
1623 int SMESH_Mesh::NbBiQuadTriangles() const throw(SALOME_Exception)
1624 {
1625   Unexpect aCatch(SalomeException);
1626   return _myMeshDS->GetMeshInfo().NbBiQuadTriangles();
1627 }
1628
1629 //================================================================================
1630 /*!
1631  * \brief Return the number nodes faces in the mesh
1632  */
1633 //================================================================================
1634
1635 int SMESH_Mesh::NbQuadrangles(SMDSAbs_ElementOrder order) const throw(SALOME_Exception)
1636 {
1637   Unexpect aCatch(SalomeException);
1638   return _myMeshDS->GetMeshInfo().NbQuadrangles(order);
1639 }
1640
1641 //================================================================================
1642 /*!
1643  * \brief Return number of biquadratic quadrangles in the mesh
1644  */
1645 //================================================================================
1646
1647 int SMESH_Mesh::NbBiQuadQuadrangles() const throw(SALOME_Exception)
1648 {
1649   Unexpect aCatch(SalomeException);
1650   return _myMeshDS->GetMeshInfo().NbBiQuadQuadrangles();
1651 }
1652
1653 //================================================================================
1654 /*!
1655  * \brief Return the number of polygonal faces in the mesh
1656  */
1657 //================================================================================
1658
1659 int SMESH_Mesh::NbPolygons() const throw(SALOME_Exception)
1660 {
1661   Unexpect aCatch(SalomeException);
1662   return _myMeshDS->GetMeshInfo().NbPolygons();
1663 }
1664
1665 //================================================================================
1666 /*!
1667  * \brief Return number of volumes of given order in the mesh
1668  */
1669 //================================================================================
1670
1671 int SMESH_Mesh::NbVolumes(SMDSAbs_ElementOrder order) const throw(SALOME_Exception)
1672 {
1673   Unexpect aCatch(SalomeException);
1674   return _myMeshDS->GetMeshInfo().NbVolumes(order);
1675 }
1676
1677 //================================================================================
1678 /*!
1679  * \brief  Return number of tetrahedrons of given order in the mesh
1680  */
1681 //================================================================================
1682
1683 int SMESH_Mesh::NbTetras(SMDSAbs_ElementOrder order) const throw(SALOME_Exception)
1684 {
1685   Unexpect aCatch(SalomeException);
1686   return _myMeshDS->GetMeshInfo().NbTetras(order);
1687 }
1688
1689 //================================================================================
1690 /*!
1691  * \brief  Return number of hexahedrons of given order in the mesh
1692  */
1693 //================================================================================
1694
1695 int SMESH_Mesh::NbHexas(SMDSAbs_ElementOrder order) const throw(SALOME_Exception)
1696 {
1697   Unexpect aCatch(SalomeException);
1698   return _myMeshDS->GetMeshInfo().NbHexas(order);
1699 }
1700
1701 //================================================================================
1702 /*!
1703  * \brief  Return number of triquadratic hexahedrons in the mesh
1704  */
1705 //================================================================================
1706
1707 int SMESH_Mesh::NbTriQuadraticHexas() const throw(SALOME_Exception)
1708 {
1709   Unexpect aCatch(SalomeException);
1710   return _myMeshDS->GetMeshInfo().NbTriQuadHexas();
1711 }
1712
1713 //================================================================================
1714 /*!
1715  * \brief  Return number of pyramids of given order in the mesh
1716  */
1717 //================================================================================
1718
1719 int SMESH_Mesh::NbPyramids(SMDSAbs_ElementOrder order) const throw(SALOME_Exception)
1720 {
1721   Unexpect aCatch(SalomeException);
1722   return _myMeshDS->GetMeshInfo().NbPyramids(order);
1723 }
1724
1725 //================================================================================
1726 /*!
1727  * \brief  Return number of prisms (penthahedrons) of given order in the mesh
1728  */
1729 //================================================================================
1730
1731 int SMESH_Mesh::NbPrisms(SMDSAbs_ElementOrder order) const throw(SALOME_Exception)
1732 {
1733   Unexpect aCatch(SalomeException);
1734   return _myMeshDS->GetMeshInfo().NbPrisms(order);
1735 }
1736
1737 //================================================================================
1738 /*!
1739  * \brief  Return number of hexagonal prisms in the mesh
1740  */
1741 //================================================================================
1742
1743 int SMESH_Mesh::NbHexagonalPrisms() const throw(SALOME_Exception)
1744 {
1745   Unexpect aCatch(SalomeException);
1746   return _myMeshDS->GetMeshInfo().NbHexPrisms();
1747 }
1748
1749 //================================================================================
1750 /*!
1751  * \brief  Return number of polyhedrons in the mesh
1752  */
1753 //================================================================================
1754
1755 int SMESH_Mesh::NbPolyhedrons() const throw(SALOME_Exception)
1756 {
1757   Unexpect aCatch(SalomeException);
1758   return _myMeshDS->GetMeshInfo().NbPolyhedrons();
1759 }
1760
1761 //================================================================================
1762 /*!
1763  * \brief  Return number of ball elements in the mesh
1764  */
1765 //================================================================================
1766
1767 int SMESH_Mesh::NbBalls() const throw(SALOME_Exception)
1768 {
1769   Unexpect aCatch(SalomeException);
1770   return _myMeshDS->GetMeshInfo().NbBalls();
1771 }
1772
1773 //================================================================================
1774 /*!
1775  * \brief  Return number of submeshes in the mesh
1776  */
1777 //================================================================================
1778
1779 int SMESH_Mesh::NbSubMesh() const throw(SALOME_Exception)
1780 {
1781   Unexpect aCatch(SalomeException);
1782   return _myMeshDS->NbSubMesh();
1783 }
1784
1785 //=======================================================================
1786 //function : IsNotConformAllowed
1787 //purpose  : check if a hypothesis alowing notconform mesh is present
1788 //=======================================================================
1789
1790 bool SMESH_Mesh::IsNotConformAllowed() const
1791 {
1792   if(MYDEBUG) MESSAGE("SMESH_Mesh::IsNotConformAllowed");
1793
1794   static SMESH_HypoFilter filter( SMESH_HypoFilter::HasName( "NotConformAllowed" ));
1795   return GetHypothesis( _myMeshDS->ShapeToMesh(), filter, false );
1796 }
1797
1798 //=======================================================================
1799 //function : IsMainShape
1800 //purpose  : 
1801 //=======================================================================
1802
1803 bool SMESH_Mesh::IsMainShape(const TopoDS_Shape& theShape) const
1804 {
1805   return theShape.IsSame(_myMeshDS->ShapeToMesh() );
1806 }
1807
1808 //=============================================================================
1809 /*!
1810  *  
1811  */
1812 //=============================================================================
1813
1814 SMESH_Group* SMESH_Mesh::AddGroup (const SMDSAbs_ElementType theType,
1815                                    const char*               theName,
1816                                    int&                      theId,
1817                                    const TopoDS_Shape&       theShape,
1818                                    const SMESH_PredicatePtr& thePredicate)
1819 {
1820   if (_mapGroup.count(_groupId))
1821     return NULL;
1822   theId = _groupId;
1823   SMESH_Group* aGroup = new SMESH_Group (theId, this, theType, theName, theShape, thePredicate);
1824   GetMeshDS()->AddGroup( aGroup->GetGroupDS() );
1825   _mapGroup[_groupId++] = aGroup;
1826   return aGroup;
1827 }
1828
1829 //================================================================================
1830 /*!
1831  * \brief Creates a group based on an existing SMESHDS group. Group ID should be unique
1832  */
1833 //================================================================================
1834
1835 SMESH_Group* SMESH_Mesh::AddGroup (SMESHDS_GroupBase* groupDS) throw(SALOME_Exception)
1836 {
1837   if ( !groupDS ) 
1838     throw SALOME_Exception(LOCALIZED ("SMESH_Mesh::AddGroup(): NULL SMESHDS_GroupBase"));
1839
1840   map <int, SMESH_Group*>::iterator i_g = _mapGroup.find( groupDS->GetID() );
1841   if ( i_g != _mapGroup.end() && i_g->second )
1842   {
1843     if ( i_g->second->GetGroupDS() == groupDS )
1844       return i_g->second;
1845     else
1846       throw SALOME_Exception(LOCALIZED ("SMESH_Mesh::AddGroup() wrong ID of SMESHDS_GroupBase"));
1847   }
1848   SMESH_Group* aGroup = new SMESH_Group (groupDS);
1849   _mapGroup[ groupDS->GetID() ] = aGroup;
1850   GetMeshDS()->AddGroup( aGroup->GetGroupDS() );
1851
1852   _groupId = 1 + _mapGroup.rbegin()->first;
1853
1854   return aGroup;
1855 }
1856
1857
1858 //================================================================================
1859 /*!
1860  * \brief Creates SMESH_Groups for not wrapped SMESHDS_Groups
1861  *  \retval bool - true if new SMESH_Groups have been created
1862  * 
1863  */
1864 //================================================================================
1865
1866 bool SMESH_Mesh::SynchronizeGroups()
1867 {
1868   int nbGroups = _mapGroup.size();
1869   const set<SMESHDS_GroupBase*>& groups = _myMeshDS->GetGroups();
1870   set<SMESHDS_GroupBase*>::const_iterator gIt = groups.begin();
1871   for ( ; gIt != groups.end(); ++gIt )
1872   {
1873     SMESHDS_GroupBase* groupDS = (SMESHDS_GroupBase*) *gIt;
1874     _groupId = groupDS->GetID();
1875     if ( !_mapGroup.count( _groupId ))
1876       _mapGroup[_groupId] = new SMESH_Group( groupDS );
1877   }
1878   if ( !_mapGroup.empty() )
1879     _groupId = _mapGroup.rbegin()->first + 1;
1880
1881   return nbGroups < _mapGroup.size();
1882 }
1883
1884 //================================================================================
1885 /*!
1886  * \brief Return iterator on all existing groups
1887  */
1888 //================================================================================
1889
1890 SMESH_Mesh::GroupIteratorPtr SMESH_Mesh::GetGroups() const
1891 {
1892   typedef map <int, SMESH_Group *> TMap;
1893   return GroupIteratorPtr( new SMDS_mapIterator<TMap>( _mapGroup ));
1894 }
1895
1896 //=============================================================================
1897 /*!
1898  * \brief Return a group by ID
1899  */
1900 //=============================================================================
1901
1902 SMESH_Group* SMESH_Mesh::GetGroup (const int theGroupID)
1903 {
1904   if (_mapGroup.find(theGroupID) == _mapGroup.end())
1905     return NULL;
1906   return _mapGroup[theGroupID];
1907 }
1908
1909
1910 //=============================================================================
1911 /*!
1912  * \brief Return IDs of all groups
1913  */
1914 //=============================================================================
1915
1916 list<int> SMESH_Mesh::GetGroupIds() const
1917 {
1918   list<int> anIds;
1919   for ( map<int, SMESH_Group*>::const_iterator it = _mapGroup.begin(); it != _mapGroup.end(); it++ )
1920     anIds.push_back( it->first );
1921   
1922   return anIds;
1923 }
1924
1925 //================================================================================
1926 /*!
1927  * \brief Set a caller of methods at level of CORBA API implementation.
1928  * The set upCaller will be deleted by SMESH_Mesh
1929  */
1930 //================================================================================
1931
1932 void SMESH_Mesh::SetCallUp( TCallUp* upCaller )
1933 {
1934   if ( _callUp ) delete _callUp;
1935   _callUp = upCaller;
1936 }
1937
1938 //=============================================================================
1939 /*!
1940  *  
1941  */
1942 //=============================================================================
1943
1944 bool SMESH_Mesh::RemoveGroup (const int theGroupID)
1945 {
1946   if (_mapGroup.find(theGroupID) == _mapGroup.end())
1947     return false;
1948   GetMeshDS()->RemoveGroup( _mapGroup[theGroupID]->GetGroupDS() );
1949   delete _mapGroup[theGroupID];
1950   _mapGroup.erase (theGroupID);
1951   if (_callUp)
1952     _callUp->RemoveGroup( theGroupID );
1953   return true;
1954 }
1955
1956 //=======================================================================
1957 //function : GetAncestors
1958 //purpose  : return list of ancestors of theSubShape in the order
1959 //           that lower dimention shapes come first.
1960 //=======================================================================
1961
1962 const TopTools_ListOfShape& SMESH_Mesh::GetAncestors(const TopoDS_Shape& theS) const
1963 {
1964   if ( _mapAncestors.Contains( theS ) )
1965     return _mapAncestors.FindFromKey( theS );
1966
1967   static TopTools_ListOfShape emptyList;
1968   return emptyList;
1969 }
1970
1971 //=======================================================================
1972 //function : Dump
1973 //purpose  : dumps contents of mesh to stream [ debug purposes ]
1974 //=======================================================================
1975
1976 ostream& SMESH_Mesh::Dump(ostream& save)
1977 {
1978   int clause = 0;
1979   save << "========================== Dump contents of mesh ==========================" << endl << endl;
1980   save << ++clause << ") Total number of nodes:   \t"    << NbNodes() << endl;
1981   save << ++clause << ") Total number of edges:   \t"    << NbEdges() << endl;
1982   save << ++clause << ") Total number of faces:   \t"    << NbFaces() << endl;
1983   save << ++clause << ") Total number of polygons:\t"    << NbPolygons() << endl;
1984   save << ++clause << ") Total number of volumes:\t"     << NbVolumes() << endl;
1985   save << ++clause << ") Total number of polyhedrons:\t" << NbPolyhedrons() << endl << endl;
1986   for ( int isQuadratic = 0; isQuadratic < 2; ++isQuadratic )
1987   {
1988     string orderStr = isQuadratic ? "quadratic" : "linear";
1989     SMDSAbs_ElementOrder order  = isQuadratic ? ORDER_QUADRATIC : ORDER_LINEAR;
1990
1991     save << ++clause << ") Total number of " << orderStr << " edges:\t" << NbEdges(order) << endl;
1992     save << ++clause << ") Total number of " << orderStr << " faces:\t" << NbFaces(order) << endl;
1993     if ( NbFaces(order) > 0 ) {
1994       int nb3 = NbTriangles(order);
1995       int nb4 = NbQuadrangles(order);
1996       save << clause << ".1) Number of " << orderStr << " triangles:  \t" << nb3 << endl;
1997       save << clause << ".2) Number of " << orderStr << " quadrangles:\t" << nb4 << endl;
1998       if ( nb3 + nb4 !=  NbFaces(order) ) {
1999         map<int,int> myFaceMap;
2000         SMDS_FaceIteratorPtr itFaces=_myMeshDS->facesIterator();
2001         while( itFaces->more( ) ) {
2002           int nbNodes = itFaces->next()->NbNodes();
2003           if ( myFaceMap.find( nbNodes ) == myFaceMap.end() )
2004             myFaceMap[ nbNodes ] = 0;
2005           myFaceMap[ nbNodes ] = myFaceMap[ nbNodes ] + 1;
2006         }
2007         save << clause << ".3) Faces in detail: " << endl;
2008         map <int,int>::iterator itF;
2009         for (itF = myFaceMap.begin(); itF != myFaceMap.end(); itF++)
2010           save << "--> nb nodes: " << itF->first << " - nb elemens:\t" << itF->second << endl;
2011       }
2012     }
2013     save << ++clause << ") Total number of " << orderStr << " volumes:\t" << NbVolumes(order) << endl;
2014     if ( NbVolumes(order) > 0 ) {
2015       int nb8 = NbHexas(order);
2016       int nb4 = NbTetras(order);
2017       int nb5 = NbPyramids(order);
2018       int nb6 = NbPrisms(order);
2019       save << clause << ".1) Number of " << orderStr << " hexahedrons:\t" << nb8 << endl;
2020       save << clause << ".2) Number of " << orderStr << " tetrahedrons:\t" << nb4 << endl;
2021       save << clause << ".3) Number of " << orderStr << " prisms:      \t" << nb6 << endl;
2022       save << clause << ".4) Number of " << orderStr << " pyramids:\t" << nb5 << endl;
2023       if ( nb8 + nb4 + nb5 + nb6 != NbVolumes(order) ) {
2024         map<int,int> myVolumesMap;
2025         SMDS_VolumeIteratorPtr itVolumes=_myMeshDS->volumesIterator();
2026         while( itVolumes->more( ) ) {
2027           int nbNodes = itVolumes->next()->NbNodes();
2028           if ( myVolumesMap.find( nbNodes ) == myVolumesMap.end() )
2029             myVolumesMap[ nbNodes ] = 0;
2030           myVolumesMap[ nbNodes ] = myVolumesMap[ nbNodes ] + 1;
2031         }
2032         save << clause << ".5) Volumes in detail: " << endl;
2033         map <int,int>::iterator itV;
2034         for (itV = myVolumesMap.begin(); itV != myVolumesMap.end(); itV++)
2035           save << "--> nb nodes: " << itV->first << " - nb elemens:\t" << itV->second << endl;
2036       }
2037     }
2038     save << endl;
2039   }
2040   save << "===========================================================================" << endl;
2041   return save;
2042 }
2043
2044 //=======================================================================
2045 //function : GetElementType
2046 //purpose  : Returns type of mesh element with certain id
2047 //=======================================================================
2048
2049 SMDSAbs_ElementType SMESH_Mesh::GetElementType( const int id, const bool iselem )
2050 {
2051   return _myMeshDS->GetElementType( id, iselem );
2052 }
2053
2054 //=============================================================================
2055 /*!
2056  *  \brief Convert group on geometry into standalone group
2057  */
2058 //=============================================================================
2059
2060 SMESH_Group* SMESH_Mesh::ConvertToStandalone ( int theGroupID )
2061 {
2062   SMESH_Group* aGroup = 0;
2063   map < int, SMESH_Group * >::iterator itg = _mapGroup.find( theGroupID );
2064   if ( itg == _mapGroup.end() )
2065     return aGroup;
2066
2067   SMESH_Group* anOldGrp = (*itg).second;
2068   SMESHDS_GroupBase* anOldGrpDS = anOldGrp->GetGroupDS();
2069   if ( !anOldGrp || !anOldGrpDS )
2070     return aGroup;
2071
2072   // create new standalone group
2073   aGroup = new SMESH_Group (theGroupID, this, anOldGrpDS->GetType(), anOldGrp->GetName() );
2074   _mapGroup[theGroupID] = aGroup;
2075
2076   SMESHDS_Group* aNewGrpDS = dynamic_cast<SMESHDS_Group*>( aGroup->GetGroupDS() );
2077   GetMeshDS()->RemoveGroup( anOldGrpDS );
2078   GetMeshDS()->AddGroup( aNewGrpDS );
2079
2080   // add elements (or nodes) into new created group
2081   SMDS_ElemIteratorPtr anItr = anOldGrpDS->GetElements();
2082   while ( anItr->more() )
2083     aNewGrpDS->Add( (anItr->next())->GetID() );
2084
2085   // set color
2086   aNewGrpDS->SetColor( anOldGrpDS->GetColor() );
2087
2088   // remove old group
2089   delete anOldGrp;
2090
2091   return aGroup;
2092 }
2093
2094 //=============================================================================
2095 /*!
2096  *  \brief remove submesh order  from Mesh
2097  */
2098 //=============================================================================
2099
2100 void SMESH_Mesh::ClearMeshOrder()
2101 {
2102   _mySubMeshOrder.clear();
2103 }
2104
2105 //=============================================================================
2106 /*!
2107  *  \brief remove submesh order  from Mesh
2108  */
2109 //=============================================================================
2110
2111 void SMESH_Mesh::SetMeshOrder(const TListOfListOfInt& theOrder )
2112 {
2113   _mySubMeshOrder = theOrder;
2114 }
2115
2116 //=============================================================================
2117 /*!
2118  *  \brief return submesh order if any
2119  */
2120 //=============================================================================
2121
2122 const TListOfListOfInt& SMESH_Mesh::GetMeshOrder() const
2123 {
2124   return _mySubMeshOrder;
2125 }
2126
2127 //=============================================================================
2128 /*!
2129  *  \brief fill _mapAncestors
2130  */
2131 //=============================================================================
2132
2133 void SMESH_Mesh::fillAncestorsMap(const TopoDS_Shape& theShape)
2134 {
2135
2136   int desType, ancType;
2137   if ( !theShape.IsSame( GetShapeToMesh()) && theShape.ShapeType() == TopAbs_COMPOUND )
2138   {
2139     // a geom group is added. Insert it into lists of ancestors before
2140     // the first ancestor more complex than group members
2141     TopoDS_Iterator subIt( theShape );
2142     if ( !subIt.More() ) return;
2143     int memberType = subIt.Value().ShapeType();
2144     for ( desType = TopAbs_VERTEX; desType >= memberType; desType-- )
2145       for (TopExp_Explorer des( theShape, TopAbs_ShapeEnum( desType )); des.More(); des.Next())
2146       {
2147         if ( !_mapAncestors.Contains( des.Current() )) continue;// issue 0020982
2148         TopTools_ListOfShape& ancList = _mapAncestors.ChangeFromKey( des.Current() );
2149         TopTools_ListIteratorOfListOfShape ancIt (ancList);
2150         while ( ancIt.More() && ancIt.Value().ShapeType() >= memberType )
2151           ancIt.Next();
2152         if ( ancIt.More() )
2153           ancList.InsertBefore( theShape, ancIt );
2154       }
2155   }
2156   {
2157     for ( desType = TopAbs_VERTEX; desType > TopAbs_COMPOUND; desType-- )
2158       for ( ancType = desType - 1; ancType >= TopAbs_COMPOUND; ancType-- )
2159         TopExp::MapShapesAndAncestors ( theShape,
2160                                         (TopAbs_ShapeEnum) desType,
2161                                         (TopAbs_ShapeEnum) ancType,
2162                                         _mapAncestors );
2163   }
2164   // visit COMPOUNDs inside a COMPOUND that are not reachable by TopExp_Explorer
2165   if ( theShape.ShapeType() == TopAbs_COMPOUND )
2166   {
2167     for ( TopoDS_Iterator sIt(theShape); sIt.More(); sIt.Next() )
2168       if ( sIt.Value().ShapeType() == TopAbs_COMPOUND )
2169         fillAncestorsMap( sIt.Value() );
2170   }
2171 }
2172
2173 //=============================================================================
2174 /*!
2175  * \brief sort submeshes according to stored mesh order
2176  * \param theListToSort in out list to be sorted
2177  * \return FALSE if nothing sorted
2178  */
2179 //=============================================================================
2180
2181 bool SMESH_Mesh::SortByMeshOrder(list<SMESH_subMesh*>& theListToSort) const
2182 {
2183   if ( !_mySubMeshOrder.size() || theListToSort.size() < 2)
2184     return true;
2185   
2186   bool res = false;
2187   list<SMESH_subMesh*> onlyOrderedList;
2188   // collect all ordered submeshes in one list as pointers
2189   // and get their positions within theListToSort
2190   typedef list<SMESH_subMesh*>::iterator TPosInList;
2191   map< int, TPosInList > sortedPos;
2192   TPosInList smBeg = theListToSort.begin(), smEnd = theListToSort.end();
2193   TListOfListOfInt::const_iterator listIdsIt = _mySubMeshOrder.begin();
2194   for( ; listIdsIt != _mySubMeshOrder.end(); listIdsIt++) {
2195     const TListOfInt& listOfId = *listIdsIt;
2196     TListOfInt::const_iterator idIt = listOfId.begin();
2197     for ( ; idIt != listOfId.end(); idIt++ ) {
2198       if ( SMESH_subMesh * sm = GetSubMeshContaining( *idIt )) {
2199         TPosInList smPos = find( smBeg, smEnd, sm );
2200         if ( smPos != smEnd ) {
2201           onlyOrderedList.push_back( sm );
2202           sortedPos[ distance( smBeg, smPos )] = smPos;
2203         }
2204       }
2205     }
2206   }
2207   if (onlyOrderedList.size() < 2)
2208     return res;
2209   res = true;
2210
2211   list<SMESH_subMesh*>::iterator onlyBIt = onlyOrderedList.begin();
2212   list<SMESH_subMesh*>::iterator onlyEIt = onlyOrderedList.end();
2213
2214   // iterate on ordered submeshes and insert them in detected positions
2215   map< int, TPosInList >::iterator i_pos = sortedPos.begin();
2216   for ( ; onlyBIt != onlyEIt; ++onlyBIt, ++i_pos )
2217     *(i_pos->second) = *onlyBIt;
2218
2219   return res;
2220 }
2221
2222 //================================================================================
2223 /*!
2224  * \brief Return true if given order of sub-meshes is OK
2225  */
2226 //================================================================================
2227
2228 bool SMESH_Mesh::IsOrderOK( const SMESH_subMesh* smBefore,
2229                             const SMESH_subMesh* smAfter ) const
2230 {
2231   TListOfListOfInt::const_iterator listIdsIt = _mySubMeshOrder.begin();
2232   TListOfInt::const_iterator idBef, idAft;
2233   for( ; listIdsIt != _mySubMeshOrder.end(); listIdsIt++)
2234   {
2235     const TListOfInt& listOfId = *listIdsIt;
2236     idBef = std::find( listOfId.begin(), listOfId.end(), smBefore->GetId() );
2237     if ( idBef != listOfId.end() )
2238       idAft = std::find( listOfId.begin(), listOfId.end(), smAfter->GetId() );
2239     if ( idAft != listOfId.end () )
2240       return ( std::distance( listOfId.begin(), idBef ) <
2241                std::distance( listOfId.begin(), idAft )   );
2242   }
2243   return true; // no order imposed to given submeshes
2244
2245
2246 //=============================================================================
2247 /*!
2248  * \brief sort submeshes according to stored mesh order
2249  * \param theListToSort in out list to be sorted
2250  * \return FALSE if nothing sorted
2251  */
2252 //=============================================================================
2253
2254 list<SMESH_subMesh*>
2255 SMESH_Mesh::getAncestorsSubMeshes (const TopoDS_Shape& theSubShape) const
2256 {
2257   list<SMESH_subMesh*> listOfSubMesh;
2258   TopTools_ListIteratorOfListOfShape it( GetAncestors( theSubShape ));
2259   for (; it.More(); it.Next() )
2260     if ( SMESH_subMesh* sm = GetSubMeshContaining( it.Value() ))
2261       listOfSubMesh.push_back(sm);
2262
2263   // sort submeshes according to stored mesh order
2264   SortByMeshOrder( listOfSubMesh );
2265
2266   return listOfSubMesh;
2267 }