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