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