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