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