Salome HOME
PAL18696 SMESH : version of MED export
[modules/smesh.git] / src / SMESH_I / SMESH_Mesh_i.cxx
1 //  SMESH SMESH_I : idl implementation based on 'SMESH' unit's calsses
2 //
3 //  Copyright (C) 2003  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 //
24 //  File   : SMESH_Mesh_i.cxx
25 //  Author : Paul RASCLE, EDF
26 //  Module : SMESH
27 //  $Header$
28
29 #include "SMESH_Mesh_i.hxx"
30
31 #include "SMESH_Filter_i.hxx"
32 #include "SMESH_Gen_i.hxx"
33 #include "SMESH_Group_i.hxx"
34 #include "SMESH_MEDMesh_i.hxx"
35 #include "SMESH_MeshEditor_i.hxx"
36 #include "SMESH_PythonDump.hxx"
37 #include "SMESH_subMesh_i.hxx"
38
39 #include "DriverMED_R_SMESHDS_Mesh.h"
40 #include "DriverMED_W_SMESHDS_Mesh.h"
41 #include "SMDS_VolumeTool.hxx"
42 #include "SMESHDS_Command.hxx"
43 #include "SMESHDS_CommandType.hxx"
44 #include "SMESHDS_GroupOnGeom.hxx"
45 #include "SMESH_Group.hxx"
46 #include "SMESH_MeshEditor.hxx"
47 #include "SMESH_MesherHelper.hxx"
48 #include "SMDS_EdgePosition.hxx"
49 #include "SMDS_FacePosition.hxx"
50
51 #include "OpUtil.hxx"
52 #include "SALOME_NamingService.hxx"
53 #include "Utils_CorbaException.hxx"
54 #include "Utils_ExceptHandlers.hxx"
55 #include "Utils_SINGLETON.hxx"
56 #include "utilities.h"
57
58 // OCCT Includes
59 #include <BRep_Builder.hxx>
60 #include <OSD_Directory.hxx>
61 #include <OSD_File.hxx>
62 #include <OSD_Path.hxx>
63 #include <OSD_Protection.hxx>
64 #include <TColStd_MapIteratorOfMapOfInteger.hxx>
65 #include <TColStd_MapOfInteger.hxx>
66 #include <TColStd_SequenceOfInteger.hxx>
67 #include <TCollection_AsciiString.hxx>
68 #include <TopExp_Explorer.hxx>
69 #include <TopoDS_Compound.hxx>
70
71 // STL Includes
72 #include <string>
73 #include <iostream>
74 #include <sstream>
75
76 #ifdef _DEBUG_
77 static int MYDEBUG = 0;
78 #else
79 static int MYDEBUG = 0;
80 #endif
81
82 using namespace std;
83 using SMESH::TPythonDump;
84
85 int SMESH_Mesh_i::myIdGenerator = 0;
86
87
88
89 //=============================================================================
90 /*!
91  *  Constructor
92  */
93 //=============================================================================
94
95 SMESH_Mesh_i::SMESH_Mesh_i( PortableServer::POA_ptr thePOA,
96                             SMESH_Gen_i*            gen_i,
97                             CORBA::Long studyId )
98 : SALOME::GenericObj_i( thePOA )
99 {
100   MESSAGE("SMESH_Mesh_i");
101   _impl = NULL;
102   _gen_i = gen_i;
103   _id = myIdGenerator++;
104   _studyId = studyId;
105   thePOA->activate_object( this );
106 }
107
108 //=============================================================================
109 /*!
110  *  Destructor
111  */
112 //=============================================================================
113
114 SMESH_Mesh_i::~SMESH_Mesh_i()
115 {
116   INFOS("~SMESH_Mesh_i");
117   map<int, SMESH::SMESH_GroupBase_ptr>::iterator it;
118   for ( it = _mapGroups.begin(); it != _mapGroups.end(); it++ ) {
119     SMESH_GroupBase_i* aGroup = dynamic_cast<SMESH_GroupBase_i*>( SMESH_Gen_i::GetServant( it->second ).in() );
120     if ( aGroup ) {
121
122       // this method is colled from destructor of group (PAL6331)
123       //_impl->RemoveGroup( aGroup->GetLocalID() );
124
125       aGroup->Destroy();
126     }
127   }
128   _mapGroups.clear();
129 }
130
131 //=============================================================================
132 /*!
133  *  SetShape
134  *
135  *  Associates <this> mesh with <theShape> and puts a reference
136  *  to <theShape> into the current study;
137  *  the previous shape is substituted by the new one.
138  */
139 //=============================================================================
140
141 void SMESH_Mesh_i::SetShape( GEOM::GEOM_Object_ptr theShapeObject )
142     throw (SALOME::SALOME_Exception)
143 {
144   Unexpect aCatch(SALOME_SalomeException);
145   try {
146     _impl->ShapeToMesh( _gen_i->GeomObjectToShape( theShapeObject ));
147   }
148   catch(SALOME_Exception & S_ex) {
149     THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
150   }
151 }
152
153 //================================================================================
154 /*!
155  * \brief return true if mesh has a shape to build a shape on
156  */
157 //================================================================================
158
159 CORBA::Boolean SMESH_Mesh_i::HasShapeToMesh()
160   throw (SALOME::SALOME_Exception)
161 {
162   Unexpect aCatch(SALOME_SalomeException);
163   bool res = false;
164   try {
165     res = _impl->HasShapeToMesh();
166   }
167   catch(SALOME_Exception & S_ex) {
168     THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
169   }
170   return res;
171 }
172
173 //=======================================================================
174 //function : GetShapeToMesh
175 //purpose  :
176 //=======================================================================
177
178 GEOM::GEOM_Object_ptr SMESH_Mesh_i::GetShapeToMesh()
179     throw (SALOME::SALOME_Exception)
180 {
181   Unexpect aCatch(SALOME_SalomeException);
182   GEOM::GEOM_Object_var aShapeObj;
183   try {
184     TopoDS_Shape S = _impl->GetMeshDS()->ShapeToMesh();
185     if ( !S.IsNull() )
186       aShapeObj = _gen_i->ShapeToGeomObject( S );
187   }
188   catch(SALOME_Exception & S_ex) {
189     THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
190   }
191   return aShapeObj._retn();
192 }
193
194 //=============================================================================
195 /*!
196  *
197  */
198 //=============================================================================
199
200 static SMESH::DriverMED_ReadStatus ConvertDriverMEDReadStatus (int theStatus)
201 {
202   SMESH::DriverMED_ReadStatus res;
203   switch (theStatus)
204   {
205   case DriverMED_R_SMESHDS_Mesh::DRS_OK:
206     res = SMESH::DRS_OK; break;
207   case DriverMED_R_SMESHDS_Mesh::DRS_EMPTY:
208     res = SMESH::DRS_EMPTY; break;
209   case DriverMED_R_SMESHDS_Mesh::DRS_WARN_RENUMBER:
210     res = SMESH::DRS_WARN_RENUMBER; break;
211   case DriverMED_R_SMESHDS_Mesh::DRS_WARN_SKIP_ELEM:
212     res = SMESH::DRS_WARN_SKIP_ELEM; break;
213   case DriverMED_R_SMESHDS_Mesh::DRS_FAIL:
214   default:
215     res = SMESH::DRS_FAIL; break;
216   }
217   return res;
218 }
219
220 //=============================================================================
221 /*!
222  *  ImportMEDFile
223  *
224  *  Imports mesh data from MED file
225  */
226 //=============================================================================
227
228 SMESH::DriverMED_ReadStatus
229 SMESH_Mesh_i::ImportMEDFile( const char* theFileName, const char* theMeshName )
230   throw ( SALOME::SALOME_Exception )
231 {
232   Unexpect aCatch(SALOME_SalomeException);
233   int status;
234   try {
235     status = _impl->MEDToMesh( theFileName, theMeshName );
236   }
237   catch( SALOME_Exception& S_ex ) {
238     THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
239   }
240   catch ( ... ) {
241     THROW_SALOME_CORBA_EXCEPTION("ImportMEDFile(): unknown exception", SALOME::BAD_PARAM);
242   }
243
244   CreateGroupServants();
245
246   return ConvertDriverMEDReadStatus(status);
247 }
248
249 //================================================================================
250 /*!
251  * \brief Return string representation of a MED file version comprising nbDigits
252  */
253 //================================================================================
254
255 char* SMESH_Mesh_i::GetVersionString(SMESH::MED_VERSION version, CORBA::Short nbDigits)
256 {
257   std::string ver = DriverMED_W_SMESHDS_Mesh::GetVersionString(MED::EVersion(version),
258                                                                nbDigits);
259   return CORBA::string_dup( ver.c_str() );
260 }
261
262 //=============================================================================
263 /*!
264  *  ImportUNVFile
265  *
266  *  Imports mesh data from MED file
267  */
268 //=============================================================================
269
270 int SMESH_Mesh_i::ImportUNVFile( const char* theFileName )
271   throw ( SALOME::SALOME_Exception )
272 {
273   // Read mesh with name = <theMeshName> into SMESH_Mesh
274   _impl->UNVToMesh( theFileName );
275
276   CreateGroupServants();
277
278   return 1;
279 }
280
281 //=============================================================================
282 /*!
283  *  ImportSTLFile
284  *
285  *  Imports mesh data from STL file
286  */
287 //=============================================================================
288 int SMESH_Mesh_i::ImportSTLFile( const char* theFileName )
289   throw ( SALOME::SALOME_Exception )
290 {
291   // Read mesh with name = <theMeshName> into SMESH_Mesh
292   _impl->STLToMesh( theFileName );
293
294   return 1;
295 }
296
297 //=============================================================================
298 /*!
299  *  importMEDFile
300  *
301  *  Imports mesh data from MED file
302  */
303 //=============================================================================
304
305 // int SMESH_Mesh_i::importMEDFile( const char* theFileName, const char* theMeshName )
306 // {
307 //   // Read mesh with name = <theMeshName> and all its groups into SMESH_Mesh
308 //   int status = _impl->MEDToMesh( theFileName, theMeshName );
309 //   CreateGroupServants();
310
311 //   return status;
312 // }
313
314 //=============================================================================
315 /*!
316  *
317  */
318 //=============================================================================
319
320 #define RETURNCASE(hyp_stat) case SMESH_Hypothesis::hyp_stat: return SMESH::hyp_stat;
321
322 SMESH::Hypothesis_Status SMESH_Mesh_i::ConvertHypothesisStatus
323                          (SMESH_Hypothesis::Hypothesis_Status theStatus)
324 {
325   switch (theStatus) {
326   RETURNCASE( HYP_OK            );
327   RETURNCASE( HYP_MISSING       );
328   RETURNCASE( HYP_CONCURENT     );
329   RETURNCASE( HYP_BAD_PARAMETER );
330   RETURNCASE( HYP_HIDDEN_ALGO   );
331   RETURNCASE( HYP_HIDING_ALGO   );
332   RETURNCASE( HYP_UNKNOWN_FATAL );
333   RETURNCASE( HYP_INCOMPATIBLE  );
334   RETURNCASE( HYP_NOTCONFORM    );
335   RETURNCASE( HYP_ALREADY_EXIST );
336   RETURNCASE( HYP_BAD_DIM       );
337   RETURNCASE( HYP_BAD_SUBSHAPE  );
338   RETURNCASE( HYP_BAD_GEOMETRY  );
339   default:;
340   }
341   return SMESH::HYP_UNKNOWN_FATAL;
342 }
343
344 //=============================================================================
345 /*!
346  *  AddHypothesis
347  *
348  *  calls internal addHypothesis() and then adds a reference to <anHyp> under
349  *  the SObject actually having a reference to <aSubShape>.
350  *  NB: For this method to work, it is necessary to add a reference to sub-shape first.
351  */
352 //=============================================================================
353
354 SMESH::Hypothesis_Status SMESH_Mesh_i::AddHypothesis(GEOM::GEOM_Object_ptr aSubShapeObject,
355                                                      SMESH::SMESH_Hypothesis_ptr anHyp)
356   throw(SALOME::SALOME_Exception)
357 {
358   Unexpect aCatch(SALOME_SalomeException);
359   SMESH_Hypothesis::Hypothesis_Status status = addHypothesis( aSubShapeObject, anHyp );
360
361   if ( !SMESH_Hypothesis::IsStatusFatal(status) )
362     _gen_i->AddHypothesisToShape(_gen_i->GetCurrentStudy(), _this(),
363                                  aSubShapeObject, anHyp );
364
365   if(MYDEBUG) MESSAGE( " AddHypothesis(): status = " << status );
366
367   // Update Python script
368   TPythonDump() << "status = " << _this() << ".AddHypothesis( "
369                 << aSubShapeObject << ", " << anHyp << " )";
370
371   return ConvertHypothesisStatus(status);
372 }
373
374 //=============================================================================
375 /*!
376  *
377  */
378 //=============================================================================
379
380 SMESH_Hypothesis::Hypothesis_Status
381   SMESH_Mesh_i::addHypothesis(GEOM::GEOM_Object_ptr       aSubShapeObject,
382                               SMESH::SMESH_Hypothesis_ptr anHyp)
383 {
384   if(MYDEBUG) MESSAGE("addHypothesis");
385
386   if (CORBA::is_nil(aSubShapeObject))
387     THROW_SALOME_CORBA_EXCEPTION("bad subShape reference",
388                                  SALOME::BAD_PARAM);
389
390   SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow(anHyp);
391   if (CORBA::is_nil(myHyp))
392     THROW_SALOME_CORBA_EXCEPTION("bad hypothesis reference",
393                                  SALOME::BAD_PARAM);
394
395   SMESH_Hypothesis::Hypothesis_Status status = SMESH_Hypothesis::HYP_OK;
396   try
397   {
398     TopoDS_Shape myLocSubShape = _gen_i->GeomObjectToShape( aSubShapeObject);
399     int hypId = myHyp->GetId();
400     status = _impl->AddHypothesis(myLocSubShape, hypId);
401     if ( !SMESH_Hypothesis::IsStatusFatal(status) ) {
402       _mapHypo[hypId] = SMESH::SMESH_Hypothesis::_duplicate( myHyp );
403       // assure there is a corresponding submesh
404       if ( !_impl->IsMainShape( myLocSubShape )) {
405         int shapeId = _impl->GetMeshDS()->ShapeToIndex( myLocSubShape );
406         if ( _mapSubMesh_i.find( shapeId ) == _mapSubMesh_i.end() )
407           createSubMesh( aSubShapeObject );
408       }
409     }
410   }
411   catch(SALOME_Exception & S_ex)
412   {
413     THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
414   }
415   return status;
416 }
417
418 //=============================================================================
419 /*!
420  *
421  */
422 //=============================================================================
423
424 SMESH::Hypothesis_Status SMESH_Mesh_i::RemoveHypothesis(GEOM::GEOM_Object_ptr aSubShapeObject,
425                                                         SMESH::SMESH_Hypothesis_ptr anHyp)
426      throw(SALOME::SALOME_Exception)
427 {
428   Unexpect aCatch(SALOME_SalomeException);
429   SMESH_Hypothesis::Hypothesis_Status status = removeHypothesis( aSubShapeObject, anHyp );
430
431   if ( !SMESH_Hypothesis::IsStatusFatal(status) )
432     _gen_i->RemoveHypothesisFromShape(_gen_i->GetCurrentStudy(), _this(),
433                                       aSubShapeObject, anHyp );
434
435   // Update Python script
436   TPythonDump() << "status = " << _this() << ".RemoveHypothesis( "
437                 << aSubShapeObject << ", " << anHyp << " )";
438
439   return ConvertHypothesisStatus(status);
440 }
441
442 //=============================================================================
443 /*!
444  *
445  */
446 //=============================================================================
447
448 SMESH_Hypothesis::Hypothesis_Status SMESH_Mesh_i::removeHypothesis(GEOM::GEOM_Object_ptr aSubShapeObject,
449                                  SMESH::SMESH_Hypothesis_ptr anHyp)
450 {
451         if(MYDEBUG) MESSAGE("removeHypothesis()");
452         // **** proposer liste de subShape (selection multiple)
453
454         if (CORBA::is_nil(aSubShapeObject))
455                 THROW_SALOME_CORBA_EXCEPTION("bad subShape reference",
456                         SALOME::BAD_PARAM);
457
458         SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow(anHyp);
459         if (CORBA::is_nil(myHyp))
460           THROW_SALOME_CORBA_EXCEPTION("bad hypothesis reference",
461                         SALOME::BAD_PARAM);
462
463         SMESH_Hypothesis::Hypothesis_Status status = SMESH_Hypothesis::HYP_OK;
464         try
465         {
466                 TopoDS_Shape myLocSubShape = _gen_i->GeomObjectToShape(aSubShapeObject);
467                 int hypId = myHyp->GetId();
468                 status = _impl->RemoveHypothesis(myLocSubShape, hypId);
469                 if ( !SMESH_Hypothesis::IsStatusFatal(status) )
470                   _mapHypo.erase( hypId );
471         }
472         catch(SALOME_Exception & S_ex)
473         {
474                 THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
475         }
476         return status;
477 }
478
479 //=============================================================================
480 /*!
481  *
482  */
483 //=============================================================================
484
485 SMESH::ListOfHypothesis *
486         SMESH_Mesh_i::GetHypothesisList(GEOM::GEOM_Object_ptr aSubShapeObject)
487 throw(SALOME::SALOME_Exception)
488 {
489   Unexpect aCatch(SALOME_SalomeException);
490   if (MYDEBUG) MESSAGE("GetHypothesisList");
491   if (CORBA::is_nil(aSubShapeObject))
492     THROW_SALOME_CORBA_EXCEPTION("bad subShape reference",
493                                  SALOME::BAD_PARAM);
494
495   SMESH::ListOfHypothesis_var aList = new SMESH::ListOfHypothesis();
496
497   try {
498     TopoDS_Shape myLocSubShape = _gen_i->GeomObjectToShape(aSubShapeObject);
499     const list<const SMESHDS_Hypothesis*>& aLocalList = _impl->GetHypothesisList( myLocSubShape );
500     int i = 0, n = aLocalList.size();
501     aList->length( n );
502
503     for ( list<const SMESHDS_Hypothesis*>::const_iterator anIt = aLocalList.begin(); i < n && anIt != aLocalList.end(); anIt++ ) {
504       SMESHDS_Hypothesis* aHyp = (SMESHDS_Hypothesis*)(*anIt);
505       if ( _mapHypo.find( aHyp->GetID() ) != _mapHypo.end() )
506         aList[i++] = SMESH::SMESH_Hypothesis::_narrow( _mapHypo[aHyp->GetID()] );
507     }
508
509     aList->length( i );
510   }
511   catch(SALOME_Exception & S_ex) {
512     THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
513   }
514
515   return aList._retn();
516 }
517
518 //=============================================================================
519 /*!
520  *
521  */
522 //=============================================================================
523 SMESH::SMESH_subMesh_ptr SMESH_Mesh_i::GetSubMesh(GEOM::GEOM_Object_ptr aSubShapeObject,
524                                                   const char*           theName )
525      throw(SALOME::SALOME_Exception)
526 {
527   Unexpect aCatch(SALOME_SalomeException);
528   MESSAGE("SMESH_Mesh_i::GetSubMesh");
529   if (CORBA::is_nil(aSubShapeObject))
530     THROW_SALOME_CORBA_EXCEPTION("bad subShape reference",
531                                  SALOME::BAD_PARAM);
532
533   SMESH::SMESH_subMesh_var subMesh;
534   SMESH::SMESH_Mesh_var    aMesh = SMESH::SMESH_Mesh::_narrow(_this());
535   try {
536     TopoDS_Shape myLocSubShape = _gen_i->GeomObjectToShape(aSubShapeObject);
537
538     //Get or Create the SMESH_subMesh object implementation
539
540     int subMeshId = _impl->GetMeshDS()->ShapeToIndex( myLocSubShape );
541     subMesh = getSubMesh( subMeshId );
542
543     // create a new subMesh object servant if there is none for the shape
544     if ( subMesh->_is_nil() )
545       subMesh = createSubMesh( aSubShapeObject );
546
547     if ( _gen_i->CanPublishInStudy( subMesh )) {
548       SALOMEDS::SObject_var aSO =
549         _gen_i->PublishSubMesh(_gen_i->GetCurrentStudy(), aMesh,
550                                subMesh, aSubShapeObject, theName );
551       if ( !aSO->_is_nil()) {
552         // Update Python script
553         TPythonDump() << aSO << " = " << _this() << ".GetSubMesh( "
554                       << aSubShapeObject << ", '" << theName << "' )";
555       }
556     }
557   }
558   catch(SALOME_Exception & S_ex) {
559     THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
560   }
561   return subMesh._retn();
562 }
563
564 //=============================================================================
565 /*!
566  *
567  */
568 //=============================================================================
569
570 void SMESH_Mesh_i::RemoveSubMesh( SMESH::SMESH_subMesh_ptr theSubMesh )
571      throw (SALOME::SALOME_Exception)
572 {
573   if(MYDEBUG) MESSAGE("SMESH_Mesh_i::RemoveSubMesh");
574   if ( theSubMesh->_is_nil() )
575     return;
576
577   GEOM::GEOM_Object_var aSubShapeObject;
578   SALOMEDS::Study_ptr aStudy = _gen_i->GetCurrentStudy();
579   if ( !aStudy->_is_nil() )  {
580     // Remove submesh's SObject
581     SALOMEDS::SObject_var anSO = _gen_i->ObjectToSObject( aStudy, theSubMesh );
582     if ( !anSO->_is_nil() ) {
583       long aTag = SMESH_Gen_i::GetRefOnShapeTag();
584       SALOMEDS::SObject_var anObj, aRef;
585       if ( anSO->FindSubObject( aTag, anObj ) && anObj->ReferencedObject( aRef ) )
586         aSubShapeObject = GEOM::GEOM_Object::_narrow( aRef->GetObject() );
587
588       aStudy->NewBuilder()->RemoveObjectWithChildren( anSO );
589
590       // Update Python script
591       TPythonDump() << _this() << ".RemoveSubMesh( " << anSO << " )";
592     }
593   }
594
595   removeSubMesh( theSubMesh, aSubShapeObject.in() );
596 }
597
598 //=============================================================================
599 /*!
600  *  ElementTypeString
601  */
602 //=============================================================================
603 #define CASE2STRING(enum) case SMESH::enum: return "SMESH."#enum;
604 inline TCollection_AsciiString ElementTypeString (SMESH::ElementType theElemType)
605 {
606   switch (theElemType) {
607     CASE2STRING( ALL );
608     CASE2STRING( NODE );
609     CASE2STRING( EDGE );
610     CASE2STRING( FACE );
611     CASE2STRING( VOLUME );
612   default:;
613   }
614   return "";
615 }
616
617 //=============================================================================
618 /*!
619  *
620  */
621 //=============================================================================
622
623 SMESH::SMESH_Group_ptr SMESH_Mesh_i::CreateGroup( SMESH::ElementType theElemType,
624                                                  const char*         theName )
625      throw(SALOME::SALOME_Exception)
626 {
627   Unexpect aCatch(SALOME_SalomeException);
628   SMESH::SMESH_Group_var aNewGroup =
629     SMESH::SMESH_Group::_narrow( createGroup( theElemType, theName ));
630
631   if ( _gen_i->CanPublishInStudy( aNewGroup ) ) {
632     SALOMEDS::SObject_var aSO =
633       _gen_i->PublishGroup(_gen_i->GetCurrentStudy(), _this(),
634                            aNewGroup, GEOM::GEOM_Object::_nil(), theName);
635     if ( !aSO->_is_nil()) {
636       // Update Python script
637       TPythonDump() << aSO << " = " << _this() << ".CreateGroup( "
638                     << ElementTypeString(theElemType) << ", '" << theName << "' )";
639     }
640   }
641   return aNewGroup._retn();
642 }
643
644
645 //=============================================================================
646 /*!
647  *
648  */
649 //=============================================================================
650 SMESH::SMESH_GroupOnGeom_ptr SMESH_Mesh_i::CreateGroupFromGEOM (SMESH::ElementType    theElemType,
651                                                                 const char*           theName,
652                                                                 GEOM::GEOM_Object_ptr theGeomObj)
653      throw(SALOME::SALOME_Exception)
654 {
655   Unexpect aCatch(SALOME_SalomeException);
656   SMESH::SMESH_GroupOnGeom_var aNewGroup;
657
658   TopoDS_Shape aShape = _gen_i->GeomObjectToShape( theGeomObj );
659   if ( !aShape.IsNull() ) {
660     aNewGroup = SMESH::SMESH_GroupOnGeom::_narrow
661       ( createGroup( theElemType, theName, aShape ));
662     if ( _gen_i->CanPublishInStudy( aNewGroup ) ) {
663       SALOMEDS::SObject_var aSO =
664         _gen_i->PublishGroup(_gen_i->GetCurrentStudy(), _this(),
665                              aNewGroup, theGeomObj, theName);
666       if ( !aSO->_is_nil()) {
667         // Update Python script
668         TPythonDump() << aSO << " = " << _this() << ".CreateGroupFromGEOM("
669                       << ElementTypeString(theElemType) << ", '" << theName << "', "
670                       << theGeomObj << " )";
671       }
672     }
673   }
674
675   return aNewGroup._retn();
676 }
677
678 //=============================================================================
679 /*!
680  *
681  */
682 //=============================================================================
683
684 void SMESH_Mesh_i::RemoveGroup( SMESH::SMESH_GroupBase_ptr theGroup )
685      throw (SALOME::SALOME_Exception)
686 {
687   if ( theGroup->_is_nil() )
688     return;
689
690   SMESH_GroupBase_i* aGroup =
691     dynamic_cast<SMESH_GroupBase_i*>( SMESH_Gen_i::GetServant( theGroup ).in() );
692   if ( !aGroup )
693     return;
694
695   SALOMEDS::Study_ptr aStudy = _gen_i->GetCurrentStudy();
696   if ( !aStudy->_is_nil() )  {
697     SALOMEDS::SObject_var aGroupSO = _gen_i->ObjectToSObject( aStudy, theGroup );
698
699     if ( !aGroupSO->_is_nil() ) {
700       // Update Python script
701       TPythonDump() << _this() << ".RemoveGroup( " << aGroupSO << " )";
702
703       // Remove group's SObject
704       aStudy->NewBuilder()->RemoveObject( aGroupSO );
705     }
706   }
707
708   // Remove the group from SMESH data structures
709   removeGroup( aGroup->GetLocalID() );
710 }
711
712 //=============================================================================
713 /*! RemoveGroupWithContents
714  *  Remove group with its contents
715  */
716 //=============================================================================
717 void SMESH_Mesh_i::RemoveGroupWithContents( SMESH::SMESH_GroupBase_ptr theGroup )
718   throw (SALOME::SALOME_Exception)
719 {
720   if ( theGroup->_is_nil() )
721     return;
722
723   SMESH_GroupBase_i* aGroup =
724     dynamic_cast<SMESH_GroupBase_i*>( SMESH_Gen_i::GetServant( theGroup ).in() );
725   if ( !aGroup )
726     return;
727
728   SMESH::long_array_var anIds = aGroup->GetListOfID();
729   SMESH::SMESH_MeshEditor_var aMeshEditor = SMESH_Mesh_i::GetMeshEditor();
730
731   // Update Python script
732   TPythonDump() << _this() << ".RemoveGroupWithContents( " << theGroup << " )";
733
734   // Remove contents
735   if ( aGroup->GetType() == SMESH::NODE )
736     aMeshEditor->RemoveNodes( anIds );
737   else
738     aMeshEditor->RemoveElements( anIds );
739
740   // Remove group
741   RemoveGroup( theGroup );
742
743   // Clear python lines, created by RemoveNodes/Elements() and RemoveGroup()
744   _gen_i->RemoveLastFromPythonScript(_gen_i->GetCurrentStudy()->StudyId());
745   _gen_i->RemoveLastFromPythonScript(_gen_i->GetCurrentStudy()->StudyId());
746 }
747
748
749 //================================================================================
750 /*!
751  * \brief Get the list of groups existing in the mesh
752   * \retval SMESH::ListOfGroups * - list of groups
753  */
754 //================================================================================
755
756 SMESH::ListOfGroups * SMESH_Mesh_i::GetGroups() throw(SALOME::SALOME_Exception)
757 {
758   Unexpect aCatch(SALOME_SalomeException);
759   if (MYDEBUG) MESSAGE("GetGroups");
760
761   SMESH::ListOfGroups_var aList = new SMESH::ListOfGroups();
762
763   // Python Dump
764   TPythonDump aPythonDump;
765   if ( !_mapGroups.empty() ) // (IMP13463) avoid "SyntaxError: can't assign to []"
766     aPythonDump << "[ ";
767
768   try {
769     aList->length( _mapGroups.size() );
770     int i = 0;
771     map<int, SMESH::SMESH_GroupBase_ptr>::iterator it = _mapGroups.begin();
772     for ( ; it != _mapGroups.end(); it++ ) {
773       if ( CORBA::is_nil( it->second )) continue;
774       aList[i++] = SMESH::SMESH_GroupBase::_duplicate( it->second );
775       // Python Dump
776       if (i > 1) aPythonDump << ", ";
777       aPythonDump << it->second;
778     }
779     aList->length( i );
780   }
781   catch(SALOME_Exception & S_ex) {
782     THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
783   }
784
785   // Update Python script
786   if ( !_mapGroups.empty() ) // (IMP13463) avoid "SyntaxError: can't assign to []"
787     aPythonDump << " ] = " << _this() << ".GetGroups()";
788
789   return aList._retn();
790 }
791 //=============================================================================
792 /*!
793  *  Get number of groups existing in the mesh
794  */
795 //=============================================================================
796
797 CORBA::Long SMESH_Mesh_i::NbGroups() throw (SALOME::SALOME_Exception)
798 {
799   Unexpect aCatch(SALOME_SalomeException);
800   return _mapGroups.size();
801 }
802
803 //=============================================================================
804 /*! UnionGroups
805  *  New group is created. All mesh elements that are
806  *  present in initial groups are added to the new one
807  */
808 //=============================================================================
809 SMESH::SMESH_Group_ptr SMESH_Mesh_i::UnionGroups( SMESH::SMESH_GroupBase_ptr theGroup1,
810                                                   SMESH::SMESH_GroupBase_ptr theGroup2,
811                                                   const char* theName )
812   throw (SALOME::SALOME_Exception)
813 {
814   try
815   {
816     if ( theGroup1->_is_nil() || theGroup2->_is_nil() ||
817          theGroup1->GetType() != theGroup2->GetType() )
818       return SMESH::SMESH_Group::_nil();
819
820     // Create Union
821     SMESH::SMESH_Group_var aResGrp = CreateGroup( theGroup1->GetType(), theName );
822     if ( aResGrp->_is_nil() )
823       return SMESH::SMESH_Group::_nil();
824
825     SMESH::long_array_var anIds1 = theGroup1->GetListOfID();
826     SMESH::long_array_var anIds2 = theGroup2->GetListOfID();
827
828     TColStd_MapOfInteger aResMap;
829
830     for ( int i1 = 0, n1 = anIds1->length(); i1 < n1; i1++ )
831       aResMap.Add( anIds1[ i1 ] );
832
833     for ( int i2 = 0, n2 = anIds2->length(); i2 < n2; i2++ )
834       aResMap.Add( anIds2[ i2 ] );
835
836     SMESH::long_array_var aResIds = new SMESH::long_array;
837     aResIds->length( aResMap.Extent() );
838
839     int resI = 0;
840     TColStd_MapIteratorOfMapOfInteger anIter( aResMap );
841     for( ; anIter.More(); anIter.Next() )
842       aResIds[ resI++ ] = anIter.Key();
843
844     aResGrp->Add( aResIds );
845
846     // Clear python lines, created by CreateGroup() and Add()
847     SALOMEDS::Study_ptr aStudy = _gen_i->GetCurrentStudy();
848     _gen_i->RemoveLastFromPythonScript(aStudy->StudyId());
849     _gen_i->RemoveLastFromPythonScript(aStudy->StudyId());
850
851     // Update Python script
852     TPythonDump() << aResGrp << " = " << _this() << ".UnionGroups( "
853                   << theGroup1 << ", " << theGroup2 << ", '"
854                   << theName << "' )";
855
856     return aResGrp._retn();
857   }
858   catch( ... )
859   {
860     return SMESH::SMESH_Group::_nil();
861   }
862 }
863
864 //=============================================================================
865 /*! IntersectGroups
866  *  New group is created. All mesh elements that are
867  *  present in both initial groups are added to the new one.
868  */
869 //=============================================================================
870 SMESH::SMESH_Group_ptr SMESH_Mesh_i::IntersectGroups( SMESH::SMESH_GroupBase_ptr theGroup1,
871                                                       SMESH::SMESH_GroupBase_ptr theGroup2,
872                                                       const char* theName )
873   throw (SALOME::SALOME_Exception)
874 {
875   if ( theGroup1->_is_nil() || theGroup2->_is_nil() ||
876        theGroup1->GetType() != theGroup2->GetType() )
877     return SMESH::SMESH_Group::_nil();
878
879   // Create Intersection
880   SMESH::SMESH_Group_var aResGrp = CreateGroup( theGroup1->GetType(), theName );
881   if ( aResGrp->_is_nil() )
882     return aResGrp;
883
884   SMESH::long_array_var anIds1 = theGroup1->GetListOfID();
885   SMESH::long_array_var anIds2 = theGroup2->GetListOfID();
886
887   TColStd_MapOfInteger aMap1;
888
889   for ( int i1 = 0, n1 = anIds1->length(); i1 < n1; i1++ )
890     aMap1.Add( anIds1[ i1 ] );
891
892   TColStd_SequenceOfInteger aSeq;
893
894   for ( int i2 = 0, n2 = anIds2->length(); i2 < n2; i2++ )
895     if ( aMap1.Contains( anIds2[ i2 ] ) )
896       aSeq.Append( anIds2[ i2 ] );
897
898   SMESH::long_array_var aResIds = new SMESH::long_array;
899   aResIds->length( aSeq.Length() );
900
901   for ( int resI = 0, resN = aSeq.Length(); resI < resN; resI++ )
902     aResIds[ resI ] = aSeq( resI + 1 );
903
904   aResGrp->Add( aResIds );
905
906   // Clear python lines, created by CreateGroup() and Add()
907   SALOMEDS::Study_ptr aStudy = _gen_i->GetCurrentStudy();
908   _gen_i->RemoveLastFromPythonScript(aStudy->StudyId());
909   _gen_i->RemoveLastFromPythonScript(aStudy->StudyId());
910
911   // Update Python script
912   TPythonDump() << aResGrp << " = " << _this() << ".IntersectGroups( "
913                 << theGroup1 << ", " << theGroup2 << ", '" << theName << "')";
914
915   return aResGrp._retn();
916 }
917
918 //=============================================================================
919 /*! CutGroups
920  *  New group is created. All mesh elements that are present in
921  *  main group but do not present in tool group are added to the new one
922  */
923 //=============================================================================
924 SMESH::SMESH_Group_ptr SMESH_Mesh_i::CutGroups( SMESH::SMESH_GroupBase_ptr theGroup1,
925                                                 SMESH::SMESH_GroupBase_ptr theGroup2,
926                                                 const char* theName )
927   throw (SALOME::SALOME_Exception)
928 {
929   if ( theGroup1->_is_nil() || theGroup2->_is_nil() ||
930        theGroup1->GetType() != theGroup2->GetType() )
931     return SMESH::SMESH_Group::_nil();
932
933   // Perform Cutting
934   SMESH::SMESH_Group_var aResGrp = CreateGroup( theGroup1->GetType(), theName );
935   if ( aResGrp->_is_nil() )
936     return aResGrp;
937
938   SMESH::long_array_var anIds1 = theGroup1->GetListOfID();
939   SMESH::long_array_var anIds2 = theGroup2->GetListOfID();
940
941   TColStd_MapOfInteger aMap2;
942
943   for ( int i2 = 0, n2 = anIds2->length(); i2 < n2; i2++ )
944     aMap2.Add( anIds2[ i2 ] );
945
946
947   TColStd_SequenceOfInteger aSeq;
948   for ( int i1 = 0, n1 = anIds1->length(); i1 < n1; i1++ )
949     if ( !aMap2.Contains( anIds1[ i1 ] ) )
950       aSeq.Append( anIds1[ i1 ] );
951
952   SMESH::long_array_var aResIds = new SMESH::long_array;
953   aResIds->length( aSeq.Length() );
954
955   for ( int resI = 0, resN = aSeq.Length(); resI < resN; resI++ )
956     aResIds[ resI ] = aSeq( resI + 1 );
957
958   aResGrp->Add( aResIds );
959
960   // Clear python lines, created by CreateGroup() and Add()
961   SALOMEDS::Study_ptr aStudy = _gen_i->GetCurrentStudy();
962   _gen_i->RemoveLastFromPythonScript(aStudy->StudyId());
963   _gen_i->RemoveLastFromPythonScript(aStudy->StudyId());
964
965   // Update Python script
966   TPythonDump() << aResGrp << " = " << _this() << ".CutGroups( "
967                 << theGroup1 << ", " << theGroup2 << ", '"
968                 << theName << "' )";
969
970   return aResGrp._retn();
971 }
972
973 //================================================================================
974 /*!
975  * \brief Return group items of a group present in a study
976  */
977 //================================================================================
978
979 static GEOM::GEOM_Object_ptr getGroupItemsFromStudy(CORBA::Object_ptr    theMesh,
980                                                     SMESH_Gen_i*         theGen,
981                                                     list<TopoDS_Shape> & theItems)
982 {
983   GEOM::GEOM_Object_var groupObj;
984   SALOMEDS::Study_var  study = theGen->GetCurrentStudy();
985   GEOM::GEOM_Gen_var geomGen = theGen->GetGeomEngine();
986   if ( study->_is_nil() || geomGen->_is_nil() )
987     return groupObj._retn();
988   
989   GEOM::GEOM_IGroupOperations_var groupOp =
990     geomGen->GetIGroupOperations( theGen->GetCurrentStudyID() );
991   GEOM::GEOM_IShapesOperations_var shapeOp =
992     geomGen->GetIShapesOperations( theGen->GetCurrentStudyID() );
993
994   SALOMEDS::SObject_var meshOS = theGen->ObjectToSObject(study, theMesh);
995   if ( meshOS->_is_nil() || groupOp->_is_nil() || shapeOp->_is_nil() )
996     return groupObj._retn();
997   SALOMEDS::SObject_var fatherSO = meshOS->GetFather();
998   if ( fatherSO->_is_nil() || fatherSO->Tag() != theGen->GetSubMeshOnCompoundTag() )
999     return groupObj._retn(); // keep only submeshes on groups
1000
1001   SALOMEDS::ChildIterator_var anIter = study->NewChildIterator(meshOS);
1002   if ( anIter->_is_nil() ) return groupObj._retn();
1003   for ( ; anIter->More(); anIter->Next())
1004   {
1005     SALOMEDS::SObject_var aSObject = anIter->Value();
1006     SALOMEDS::SObject_var aRefSO;
1007     if ( !aSObject->_is_nil() && aSObject->ReferencedObject(aRefSO) )
1008     {
1009       groupObj = GEOM::GEOM_Object::_narrow(aRefSO->GetObject());
1010       if ( groupObj->_is_nil() ) break;
1011       GEOM::ListOfLong_var  ids = groupOp->GetObjects( groupObj );
1012       GEOM::GEOM_Object_var mainShape = groupObj->GetMainShape();
1013       for ( int i = 0; i < ids->length(); ++i ) {
1014         GEOM::GEOM_Object_var subShape = shapeOp->GetSubShape( mainShape, ids[i] );
1015         TopoDS_Shape S = theGen->GeomObjectToShape( subShape );
1016         if ( !S.IsNull() )
1017           theItems.push_back( S );
1018       }
1019       break;
1020     }
1021   }
1022   return groupObj._retn();
1023 }
1024
1025 //=============================================================================
1026 /*!
1027  * \brief Update hypotheses assigned to geom groups if the latter change
1028  * 
1029  * NPAL16168: "geometrical group edition from a submesh don't modifiy mesh computation"
1030  */
1031 //=============================================================================
1032
1033 void SMESH_Mesh_i::CheckGeomGroupModif()
1034 {
1035   if ( !_impl->HasShapeToMesh() ) return;
1036
1037   SALOMEDS::Study_var study = _gen_i->GetCurrentStudy();
1038   if ( study->_is_nil() ) return;
1039
1040   // check if items of groups changed
1041   map<int, ::SMESH_subMesh*>::iterator i_sm = _mapSubMesh.begin();
1042   for ( ; i_sm != _mapSubMesh.end(); ++i_sm )
1043   {
1044     const TopoDS_Shape & oldGroupShape = i_sm->second->GetSubShape();
1045     SMESHDS_SubMesh * oldDS = i_sm->second->GetSubMeshDS();
1046     if ( !oldDS /*|| !oldDS->IsComplexSubmesh()*/ )
1047       continue;
1048     int oldID = i_sm->first;
1049     map<int, SMESH::SMESH_subMesh_ptr>::iterator i_smIor = _mapSubMeshIor.find( oldID );
1050     if ( i_smIor == _mapSubMeshIor.end() )
1051       continue;
1052     list< TopoDS_Shape> newItems;
1053     GEOM::GEOM_Object_var groupObj = getGroupItemsFromStudy ( i_smIor->second, _gen_i, newItems );
1054     if ( groupObj->_is_nil() )
1055       continue;
1056
1057     int nbOldItems = oldDS->IsComplexSubmesh() ? oldDS->NbSubMeshes() : 1;
1058     int nbNewItems = newItems.size();
1059     bool groupChanged = ( nbOldItems != nbNewItems);
1060     if ( !groupChanged ) {
1061       if ( !oldDS->IsComplexSubmesh() ) { // old group has one item
1062         groupChanged = ( oldGroupShape != newItems.front() );
1063       }
1064       else {
1065         list<TopoDS_Shape>::iterator item = newItems.begin();
1066         for ( ; item != newItems.end() && !groupChanged; ++item )
1067         {
1068           SMESHDS_SubMesh * itemDS = _impl->GetMeshDS()->MeshElements( *item );
1069           groupChanged = ( !itemDS || !oldDS->ContainsSubMesh( itemDS ));
1070         }
1071       }
1072     }
1073     // update hypotheses and submeshes if necessary
1074     if ( groupChanged )
1075     {
1076       // get a new group shape
1077       GEOM_Client* geomClient = _gen_i->GetShapeReader();
1078       if ( !geomClient ) continue;
1079       TCollection_AsciiString groupIOR = _gen_i->GetGeomEngine()->GetStringFromIOR( groupObj );
1080       geomClient->RemoveShapeFromBuffer( groupIOR );
1081       TopoDS_Shape newGroupShape = _gen_i->GeomObjectToShape( groupObj );
1082       // update hypotheses
1083       list <const SMESHDS_Hypothesis * > hyps = _impl->GetHypothesisList(oldGroupShape);
1084       list <const SMESHDS_Hypothesis * >::iterator hypIt;
1085       for ( hypIt = hyps.begin(); hypIt != hyps.end(); ++hypIt )
1086       {
1087         _impl->RemoveHypothesis( oldGroupShape, (*hypIt)->GetID());
1088         _impl->AddHypothesis   ( newGroupShape, (*hypIt)->GetID());
1089       }
1090       // care of submeshes
1091       SMESH_subMesh* newSubmesh = _impl->GetSubMesh( newGroupShape );
1092       int newID = newSubmesh->GetId();
1093       if ( newID != oldID ) {
1094         _mapSubMesh   [ newID ] = newSubmesh;
1095         _mapSubMesh_i [ newID ] = _mapSubMesh_i [ oldID ];
1096         _mapSubMeshIor[ newID ] = _mapSubMeshIor[ oldID ];
1097         _mapSubMesh.erase   (oldID);
1098         _mapSubMesh_i.erase (oldID);
1099         _mapSubMeshIor.erase(oldID);
1100         _mapSubMesh_i [ newID ]->changeLocalId( newID );
1101       }
1102     }
1103   }
1104 }
1105
1106 //=============================================================================
1107 /*!
1108  *
1109  */
1110 //=============================================================================
1111
1112 SMESH::SMESH_subMesh_ptr SMESH_Mesh_i::createSubMesh( GEOM::GEOM_Object_ptr theSubShapeObject )
1113 {
1114   if(MYDEBUG) MESSAGE( "createSubMesh" );
1115   TopoDS_Shape myLocSubShape = _gen_i->GeomObjectToShape(theSubShapeObject);
1116
1117   ::SMESH_subMesh * mySubMesh = _impl->GetSubMesh(myLocSubShape);
1118   int subMeshId = _impl->GetMeshDS()->ShapeToIndex( myLocSubShape );
1119   SMESH_subMesh_i *subMeshServant = new SMESH_subMesh_i(myPOA, _gen_i, this, subMeshId);
1120   SMESH::SMESH_subMesh_var subMesh
1121     = SMESH::SMESH_subMesh::_narrow(subMeshServant->_this());
1122
1123   _mapSubMesh[subMeshId] = mySubMesh;
1124   _mapSubMesh_i[subMeshId] = subMeshServant;
1125   _mapSubMeshIor[subMeshId] = SMESH::SMESH_subMesh::_duplicate(subMesh);
1126
1127   // register CORBA object for persistence
1128   int nextId = _gen_i->RegisterObject( subMesh );
1129   if(MYDEBUG) MESSAGE( "Add submesh to map with id = "<< nextId);
1130
1131   return subMesh._retn();
1132 }
1133
1134 //=======================================================================
1135 //function : getSubMesh
1136 //purpose  :
1137 //=======================================================================
1138
1139 SMESH::SMESH_subMesh_ptr SMESH_Mesh_i::getSubMesh(int shapeID)
1140 {
1141   map<int, SMESH::SMESH_subMesh_ptr>::iterator it = _mapSubMeshIor.find( shapeID );
1142   if ( it == _mapSubMeshIor.end() )
1143     return SMESH::SMESH_subMesh::_nil();
1144
1145   return SMESH::SMESH_subMesh::_duplicate( (*it).second );
1146 }
1147
1148
1149 //=============================================================================
1150 /*!
1151  *
1152  */
1153 //=============================================================================
1154
1155 void SMESH_Mesh_i::removeSubMesh (SMESH::SMESH_subMesh_ptr theSubMesh,
1156                                   GEOM::GEOM_Object_ptr    theSubShapeObject )
1157 {
1158   MESSAGE("SMESH_Mesh_i::removeSubMesh()");
1159   if ( theSubMesh->_is_nil() || theSubShapeObject->_is_nil() )
1160     return;
1161
1162   try {
1163     SMESH::ListOfHypothesis_var aHypList = GetHypothesisList( theSubShapeObject );
1164     for ( int i = 0, n = aHypList->length(); i < n; i++ ) {
1165       removeHypothesis( theSubShapeObject, aHypList[i] );
1166     }
1167   }
1168   catch( const SALOME::SALOME_Exception& ) {
1169     INFOS("SMESH_Mesh_i::removeSubMesh(): exception caught!");
1170   }
1171
1172   int subMeshId = theSubMesh->GetId();
1173
1174   _mapSubMesh.erase(subMeshId);
1175   _mapSubMesh_i.erase(subMeshId);
1176   _mapSubMeshIor.erase(subMeshId);
1177   if(MYDEBUG) MESSAGE("SMESH_Mesh_i::removeSubMesh() completed");
1178 }
1179
1180 //=============================================================================
1181 /*!
1182  *
1183  */
1184 //=============================================================================
1185
1186 SMESH::SMESH_GroupBase_ptr SMESH_Mesh_i::createGroup (SMESH::ElementType theElemType,
1187                                                       const char*         theName,
1188                                                       const TopoDS_Shape& theShape )
1189 {
1190   int anId;
1191   SMESH::SMESH_GroupBase_var aGroup;
1192   if ( _impl->AddGroup( (SMDSAbs_ElementType)theElemType, theName, anId, theShape )) {
1193     SMESH_GroupBase_i* aGroupImpl;
1194     if ( !theShape.IsNull() )
1195       aGroupImpl = new SMESH_GroupOnGeom_i( SMESH_Gen_i::GetPOA(), this, anId );
1196     else
1197       aGroupImpl = new SMESH_Group_i( SMESH_Gen_i::GetPOA(), this, anId );
1198
1199     // PAL7962: san -- To ensure correct mapping of servant and correct reference counting in GenericObj_i
1200     SMESH_Gen_i::GetPOA()->activate_object( aGroupImpl );
1201     aGroupImpl->Register();
1202     // PAL7962: san -- To ensure correct mapping of servant and correct reference counting in GenericObj_i
1203
1204     aGroup = SMESH::SMESH_GroupBase::_narrow( aGroupImpl->_this() );
1205     _mapGroups[anId] = SMESH::SMESH_GroupBase::_duplicate( aGroup );
1206
1207     // register CORBA object for persistence
1208     int nextId = _gen_i->RegisterObject( aGroup );
1209     if(MYDEBUG) MESSAGE( "Add group to map with id = "<< nextId);
1210   }
1211   return aGroup._retn();
1212 }
1213
1214 //=============================================================================
1215 /*!
1216  * SMESH_Mesh_i::removeGroup
1217  *
1218  * Should be called by ~SMESH_Group_i()
1219  */
1220 //=============================================================================
1221
1222 void SMESH_Mesh_i::removeGroup( const int theId )
1223 {
1224   if(MYDEBUG) MESSAGE("SMESH_Mesh_i::removeGroup()" );
1225   if ( _mapGroups.find( theId ) != _mapGroups.end() ) {
1226     _mapGroups.erase( theId );
1227     _impl->RemoveGroup( theId );
1228   }
1229 }
1230
1231
1232 //=============================================================================
1233 /*!
1234  *
1235  */
1236 //=============================================================================
1237
1238 SMESH::log_array * SMESH_Mesh_i::GetLog(CORBA::Boolean clearAfterGet)
1239 throw(SALOME::SALOME_Exception)
1240 {
1241   if(MYDEBUG) MESSAGE("SMESH_Mesh_i::GetLog");
1242
1243   SMESH::log_array_var aLog;
1244   try{
1245     list < SMESHDS_Command * >logDS = _impl->GetLog();
1246     aLog = new SMESH::log_array;
1247     int indexLog = 0;
1248     int lg = logDS.size();
1249     SCRUTE(lg);
1250     aLog->length(lg);
1251     list < SMESHDS_Command * >::iterator its = logDS.begin();
1252     while(its != logDS.end()){
1253       SMESHDS_Command *com = *its;
1254       int comType = com->GetType();
1255       //SCRUTE(comType);
1256       int lgcom = com->GetNumber();
1257       //SCRUTE(lgcom);
1258       const list < int >&intList = com->GetIndexes();
1259       int inum = intList.size();
1260       //SCRUTE(inum);
1261       list < int >::const_iterator ii = intList.begin();
1262       const list < double >&coordList = com->GetCoords();
1263       int rnum = coordList.size();
1264       //SCRUTE(rnum);
1265       list < double >::const_iterator ir = coordList.begin();
1266       aLog[indexLog].commandType = comType;
1267       aLog[indexLog].number = lgcom;
1268       aLog[indexLog].coords.length(rnum);
1269       aLog[indexLog].indexes.length(inum);
1270       for(int i = 0; i < rnum; i++){
1271         aLog[indexLog].coords[i] = *ir;
1272         //MESSAGE(" "<<i<<" "<<ir.Value());
1273         ir++;
1274       }
1275       for(int i = 0; i < inum; i++){
1276         aLog[indexLog].indexes[i] = *ii;
1277         //MESSAGE(" "<<i<<" "<<ii.Value());
1278         ii++;
1279       }
1280       indexLog++;
1281       its++;
1282     }
1283     if(clearAfterGet)
1284       _impl->ClearLog();
1285   }
1286   catch(SALOME_Exception & S_ex){
1287     THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
1288   }
1289   return aLog._retn();
1290 }
1291
1292
1293 //=============================================================================
1294 /*!
1295  *
1296  */
1297 //=============================================================================
1298
1299 void SMESH_Mesh_i::ClearLog() throw(SALOME::SALOME_Exception)
1300 {
1301   if(MYDEBUG) MESSAGE("SMESH_Mesh_i::ClearLog");
1302   // ****
1303 }
1304
1305 //=============================================================================
1306 /*!
1307  *
1308  */
1309 //=============================================================================
1310
1311 CORBA::Long SMESH_Mesh_i::GetId()throw(SALOME::SALOME_Exception)
1312 {
1313   if(MYDEBUG) MESSAGE("SMESH_Mesh_i::GetId");
1314   return _id;
1315 }
1316
1317 //=============================================================================
1318 /*!
1319  *
1320  */
1321 //=============================================================================
1322
1323 CORBA::Long SMESH_Mesh_i::GetStudyId()throw(SALOME::SALOME_Exception)
1324 {
1325   return _studyId;
1326 }
1327
1328 //=============================================================================
1329 /*!
1330  *
1331  */
1332 //=============================================================================
1333
1334 void SMESH_Mesh_i::SetImpl(::SMESH_Mesh * impl)
1335 {
1336   if(MYDEBUG) MESSAGE("SMESH_Mesh_i::SetImpl");
1337   _impl = impl;
1338 }
1339
1340 //=============================================================================
1341 /*!
1342  *
1343  */
1344 //=============================================================================
1345
1346 ::SMESH_Mesh & SMESH_Mesh_i::GetImpl()
1347 {
1348   if(MYDEBUG) MESSAGE("SMESH_Mesh_i::GetImpl()");
1349   return *_impl;
1350 }
1351
1352 //=============================================================================
1353 /*!
1354  * Return mesh editor
1355  */
1356 //=============================================================================
1357
1358 SMESH::SMESH_MeshEditor_ptr SMESH_Mesh_i::GetMeshEditor()
1359 {
1360   // Create MeshEditor
1361   SMESH_MeshEditor_i *aMeshEditor = new SMESH_MeshEditor_i( this, false );
1362   SMESH::SMESH_MeshEditor_var aMesh = aMeshEditor->_this();
1363
1364   // Update Python script
1365   TPythonDump() << aMeshEditor << " = " << _this() << ".GetMeshEditor()";
1366
1367   return aMesh._retn();
1368 }
1369
1370 //=============================================================================
1371 /*!
1372  * Return mesh edition previewer
1373  */
1374 //=============================================================================
1375
1376 SMESH::SMESH_MeshEditor_ptr SMESH_Mesh_i::GetMeshEditPreviewer()
1377 {
1378   SMESH_MeshEditor_i *aMeshEditor = new SMESH_MeshEditor_i( this, true );
1379   SMESH::SMESH_MeshEditor_var aMesh = aMeshEditor->_this();
1380   return aMesh._retn();
1381 }
1382
1383 //=============================================================================
1384 /*!
1385  *  Export in different formats
1386  */
1387 //=============================================================================
1388
1389 CORBA::Boolean SMESH_Mesh_i::HasDuplicatedGroupNamesMED()
1390 {
1391   return _impl->HasDuplicatedGroupNamesMED();
1392 }
1393
1394 static void PrepareForWriting (const char* file)
1395 {
1396   TCollection_AsciiString aFullName ((char*)file);
1397   OSD_Path aPath (aFullName);
1398   OSD_File aFile (aPath);
1399   if (aFile.Exists()) {
1400     // existing filesystem node
1401     if (aFile.KindOfFile() == OSD_FILE) {
1402       if (aFile.IsWriteable()) {
1403         aFile.Reset();
1404         aFile.Remove();
1405         if (aFile.Failed()) {
1406           TCollection_AsciiString msg ("File ");
1407           msg += aFullName + " cannot be replaced.";
1408           THROW_SALOME_CORBA_EXCEPTION(msg.ToCString(), SALOME::BAD_PARAM);
1409         }
1410       } else {
1411         TCollection_AsciiString msg ("File ");
1412         msg += aFullName + " cannot be overwritten.";
1413         THROW_SALOME_CORBA_EXCEPTION(msg.ToCString(), SALOME::BAD_PARAM);
1414       }
1415     } else {
1416       TCollection_AsciiString msg ("Location ");
1417       msg += aFullName + " is not a file.";
1418       THROW_SALOME_CORBA_EXCEPTION(msg.ToCString(), SALOME::BAD_PARAM);
1419     }
1420   } else {
1421     // nonexisting file; check if it can be created
1422     aFile.Reset();
1423     aFile.Build(OSD_WriteOnly, OSD_Protection());
1424     if (aFile.Failed()) {
1425       TCollection_AsciiString msg ("You cannot create the file ");
1426       msg += aFullName + ". Check the directory existance and access rights.";
1427       THROW_SALOME_CORBA_EXCEPTION(msg.ToCString(), SALOME::BAD_PARAM);
1428     } else {
1429       aFile.Close();
1430       aFile.Remove();
1431     }
1432   }
1433 }
1434
1435 void SMESH_Mesh_i::ExportToMED (const char* file,
1436                                 CORBA::Boolean auto_groups,
1437                                 SMESH::MED_VERSION theVersion)
1438   throw(SALOME::SALOME_Exception)
1439 {
1440   Unexpect aCatch(SALOME_SalomeException);
1441
1442   // Update Python script
1443   TPythonDump() << _this() << ".ExportToMED( '"
1444                 << file << "', " << auto_groups << ", " << theVersion << " )";
1445
1446   // Perform Export
1447   PrepareForWriting(file);
1448   char* aMeshName = "Mesh";
1449   SALOMEDS::Study_ptr aStudy = _gen_i->GetCurrentStudy();
1450   if ( !aStudy->_is_nil() ) {
1451     SALOMEDS::SObject_var aMeshSO = _gen_i->ObjectToSObject( aStudy, _this() );
1452     if ( !aMeshSO->_is_nil() ) {
1453       aMeshName = aMeshSO->GetName();
1454       //SCRUTE(file);
1455       //SCRUTE(aMeshName);
1456       //SCRUTE(aMeshSO->GetID());
1457
1458       // asv : 27.10.04 : fix of 6903: check for StudyLocked before adding attributes
1459       if ( !aStudy->GetProperties()->IsLocked() )
1460         {
1461         SALOMEDS::GenericAttribute_var anAttr;
1462         SALOMEDS::StudyBuilder_var aStudyBuilder = aStudy->NewBuilder();
1463         SALOMEDS::AttributeExternalFileDef_var aFileName;
1464         anAttr=aStudyBuilder->FindOrCreateAttribute(aMeshSO, "AttributeExternalFileDef");
1465         aFileName = SALOMEDS::AttributeExternalFileDef::_narrow(anAttr);
1466         ASSERT(!aFileName->_is_nil());
1467         aFileName->SetValue(file);
1468         SALOMEDS::AttributeFileType_var aFileType;
1469         anAttr=aStudyBuilder->FindOrCreateAttribute(aMeshSO, "AttributeFileType");
1470         aFileType = SALOMEDS::AttributeFileType::_narrow(anAttr);
1471         ASSERT(!aFileType->_is_nil());
1472         aFileType->SetValue("FICHIERMED");
1473         }
1474     }
1475   }
1476   _impl->ExportMED( file, aMeshName, auto_groups, theVersion );
1477 }
1478
1479 void SMESH_Mesh_i::ExportMED (const char* file,
1480                               CORBA::Boolean auto_groups)
1481   throw(SALOME::SALOME_Exception)
1482 {
1483   ExportToMED(file,auto_groups,SMESH::MED_V2_1);
1484 }
1485
1486 void SMESH_Mesh_i::ExportDAT (const char *file)
1487   throw(SALOME::SALOME_Exception)
1488 {
1489   Unexpect aCatch(SALOME_SalomeException);
1490
1491   // Update Python script
1492   TPythonDump() << _this() << ".ExportDAT( '" << file << "' )";
1493
1494   // Perform Export
1495   PrepareForWriting(file);
1496   _impl->ExportDAT(file);
1497 }
1498
1499 void SMESH_Mesh_i::ExportUNV (const char *file)
1500   throw(SALOME::SALOME_Exception)
1501 {
1502   Unexpect aCatch(SALOME_SalomeException);
1503
1504   // Update Python script
1505   TPythonDump() << _this() << ".ExportUNV( '" << file << "' )";
1506
1507   // Perform Export
1508   PrepareForWriting(file);
1509   _impl->ExportUNV(file);
1510 }
1511
1512 void SMESH_Mesh_i::ExportSTL (const char *file, const bool isascii)
1513   throw(SALOME::SALOME_Exception)
1514 {
1515   Unexpect aCatch(SALOME_SalomeException);
1516
1517   // Update Python script
1518   TPythonDump() << _this() << ".ExportSTL( '" << file << "', " << isascii << " )";
1519
1520   // Perform Export
1521   PrepareForWriting(file);
1522   _impl->ExportSTL(file, isascii);
1523 }
1524
1525 //=============================================================================
1526 /*!
1527  *
1528  */
1529 //=============================================================================
1530
1531 SALOME_MED::MESH_ptr SMESH_Mesh_i::GetMEDMesh()throw(SALOME::SALOME_Exception)
1532 {
1533   Unexpect aCatch(SALOME_SalomeException);
1534   SMESH_MEDMesh_i *aMedMesh = new SMESH_MEDMesh_i(this);
1535   SALOME_MED::MESH_var aMesh = aMedMesh->_this();
1536   return aMesh._retn();
1537 }
1538
1539 //=============================================================================
1540 /*!
1541  *
1542  */
1543 //=============================================================================
1544 CORBA::Long SMESH_Mesh_i::NbNodes()throw(SALOME::SALOME_Exception)
1545 {
1546   Unexpect aCatch(SALOME_SalomeException);
1547   return _impl->NbNodes();
1548 }
1549
1550 //=============================================================================
1551 /*!
1552  *
1553  */
1554 //=============================================================================
1555 CORBA::Long SMESH_Mesh_i::NbElements()throw (SALOME::SALOME_Exception)
1556 {
1557   Unexpect aCatch(SALOME_SalomeException);
1558   return NbEdges() + NbFaces() + NbVolumes();
1559 }
1560
1561 //=============================================================================
1562 /*!
1563  *
1564  */
1565 //=============================================================================
1566 CORBA::Long SMESH_Mesh_i::NbEdges()throw(SALOME::SALOME_Exception)
1567 {
1568   Unexpect aCatch(SALOME_SalomeException);
1569   return _impl->NbEdges();
1570 }
1571
1572 CORBA::Long SMESH_Mesh_i::NbEdgesOfOrder(SMESH::ElementOrder order)
1573   throw(SALOME::SALOME_Exception)
1574 {
1575   Unexpect aCatch(SALOME_SalomeException);
1576   return _impl->NbEdges( (SMDSAbs_ElementOrder) order);
1577 }
1578
1579 //=============================================================================
1580 /*!
1581  *
1582  */
1583 //=============================================================================
1584 CORBA::Long SMESH_Mesh_i::NbFaces()throw(SALOME::SALOME_Exception)
1585 {
1586   Unexpect aCatch(SALOME_SalomeException);
1587   return _impl->NbFaces();
1588 }
1589
1590 CORBA::Long SMESH_Mesh_i::NbTriangles()throw(SALOME::SALOME_Exception)
1591 {
1592   Unexpect aCatch(SALOME_SalomeException);
1593   return _impl->NbTriangles();
1594 }
1595
1596 CORBA::Long SMESH_Mesh_i::NbQuadrangles()throw(SALOME::SALOME_Exception)
1597 {
1598   Unexpect aCatch(SALOME_SalomeException);
1599   return _impl->NbQuadrangles();
1600 }
1601
1602 CORBA::Long SMESH_Mesh_i::NbPolygons()throw(SALOME::SALOME_Exception)
1603 {
1604   Unexpect aCatch(SALOME_SalomeException);
1605   return _impl->NbPolygons();
1606 }
1607
1608 CORBA::Long SMESH_Mesh_i::NbFacesOfOrder(SMESH::ElementOrder order)
1609   throw(SALOME::SALOME_Exception)
1610 {
1611   Unexpect aCatch(SALOME_SalomeException);
1612   return _impl->NbFaces( (SMDSAbs_ElementOrder) order);
1613 }
1614
1615 CORBA::Long SMESH_Mesh_i::NbTrianglesOfOrder(SMESH::ElementOrder order)
1616   throw(SALOME::SALOME_Exception)
1617 {
1618   Unexpect aCatch(SALOME_SalomeException);
1619   return _impl->NbTriangles( (SMDSAbs_ElementOrder) order);
1620 }
1621
1622 CORBA::Long SMESH_Mesh_i::NbQuadranglesOfOrder(SMESH::ElementOrder order)
1623   throw(SALOME::SALOME_Exception)
1624 {
1625   Unexpect aCatch(SALOME_SalomeException);
1626   return _impl->NbQuadrangles( (SMDSAbs_ElementOrder) order);
1627 }
1628
1629 //=============================================================================
1630 /*!
1631  *
1632  */
1633 //=============================================================================
1634 CORBA::Long SMESH_Mesh_i::NbVolumes()throw(SALOME::SALOME_Exception)
1635 {
1636   Unexpect aCatch(SALOME_SalomeException);
1637   return _impl->NbVolumes();
1638 }
1639
1640 CORBA::Long SMESH_Mesh_i::NbTetras()throw(SALOME::SALOME_Exception)
1641 {
1642   Unexpect aCatch(SALOME_SalomeException);
1643   return _impl->NbTetras();
1644 }
1645
1646 CORBA::Long SMESH_Mesh_i::NbHexas()throw(SALOME::SALOME_Exception)
1647 {
1648   Unexpect aCatch(SALOME_SalomeException);
1649   return _impl->NbHexas();
1650 }
1651
1652 CORBA::Long SMESH_Mesh_i::NbPyramids()throw(SALOME::SALOME_Exception)
1653 {
1654   Unexpect aCatch(SALOME_SalomeException);
1655   return _impl->NbPyramids();
1656 }
1657
1658 CORBA::Long SMESH_Mesh_i::NbPrisms()throw(SALOME::SALOME_Exception)
1659 {
1660   Unexpect aCatch(SALOME_SalomeException);
1661   return _impl->NbPrisms();
1662 }
1663
1664 CORBA::Long SMESH_Mesh_i::NbPolyhedrons()throw(SALOME::SALOME_Exception)
1665 {
1666   Unexpect aCatch(SALOME_SalomeException);
1667   return _impl->NbPolyhedrons();
1668 }
1669
1670 CORBA::Long SMESH_Mesh_i::NbVolumesOfOrder(SMESH::ElementOrder order)
1671   throw(SALOME::SALOME_Exception)
1672 {
1673   Unexpect aCatch(SALOME_SalomeException);
1674   return _impl->NbVolumes( (SMDSAbs_ElementOrder) order);
1675 }
1676
1677 CORBA::Long SMESH_Mesh_i::NbTetrasOfOrder(SMESH::ElementOrder order)
1678   throw(SALOME::SALOME_Exception)
1679 {
1680   Unexpect aCatch(SALOME_SalomeException);
1681   return _impl->NbTetras( (SMDSAbs_ElementOrder) order);
1682 }
1683
1684 CORBA::Long SMESH_Mesh_i::NbHexasOfOrder(SMESH::ElementOrder order)
1685   throw(SALOME::SALOME_Exception)
1686 {
1687   Unexpect aCatch(SALOME_SalomeException);
1688   return _impl->NbHexas( (SMDSAbs_ElementOrder) order);
1689 }
1690
1691 CORBA::Long SMESH_Mesh_i::NbPyramidsOfOrder(SMESH::ElementOrder order)
1692   throw(SALOME::SALOME_Exception)
1693 {
1694   Unexpect aCatch(SALOME_SalomeException);
1695   return _impl->NbPyramids( (SMDSAbs_ElementOrder) order);
1696 }
1697
1698 CORBA::Long SMESH_Mesh_i::NbPrismsOfOrder(SMESH::ElementOrder order)
1699   throw(SALOME::SALOME_Exception)
1700 {
1701   Unexpect aCatch(SALOME_SalomeException);
1702   return _impl->NbPrisms( (SMDSAbs_ElementOrder) order);
1703 }
1704
1705 //=============================================================================
1706 /*!
1707  *
1708  */
1709 //=============================================================================
1710 CORBA::Long SMESH_Mesh_i::NbSubMesh()throw(SALOME::SALOME_Exception)
1711 {
1712   Unexpect aCatch(SALOME_SalomeException);
1713   return _impl->NbSubMesh();
1714 }
1715
1716 //=============================================================================
1717 /*!
1718  *
1719  */
1720 //=============================================================================
1721 char* SMESH_Mesh_i::Dump()
1722 {
1723   std::ostringstream os;
1724   _impl->Dump( os );
1725   return CORBA::string_dup( os.str().c_str() );
1726 }
1727
1728 //=============================================================================
1729 /*!
1730  *
1731  */
1732 //=============================================================================
1733 SMESH::long_array* SMESH_Mesh_i::GetIDs()
1734 {
1735 //   SMESH::long_array_var aResult = new SMESH::long_array();
1736 //   SMESHDS_Mesh* aSMESHDS_Mesh = _impl->GetMeshDS();
1737 //   int aMinId = aSMESHDS_Mesh->MinElementID();
1738 //   int aMaxId =  aSMESHDS_Mesh->MaxElementID();
1739
1740 //   aResult->length(aMaxId - aMinId + 1);
1741
1742 //   for (int i = 0, id = aMinId; id <= aMaxId; id++  )
1743 //     aResult[i++] = id;
1744
1745 //   return aResult._retn();
1746   // PAL12398
1747   return GetElementsId();
1748 }
1749
1750 //=============================================================================
1751 /*!
1752  *
1753  */
1754 //=============================================================================
1755
1756 SMESH::long_array* SMESH_Mesh_i::GetElementsId()
1757      throw (SALOME::SALOME_Exception)
1758 {
1759   Unexpect aCatch(SALOME_SalomeException);
1760   MESSAGE("SMESH_Mesh_i::GetElementsId");
1761   SMESH::long_array_var aResult = new SMESH::long_array();
1762   SMESHDS_Mesh* aSMESHDS_Mesh = _impl->GetMeshDS();
1763
1764   if ( aSMESHDS_Mesh == NULL )
1765     return aResult._retn();
1766
1767   long nbElements = NbElements();
1768   aResult->length( nbElements );
1769   SMDS_ElemIteratorPtr anIt = aSMESHDS_Mesh->elementsIterator();
1770   for ( int i = 0, n = nbElements; i < n && anIt->more(); i++ )
1771     aResult[i] = anIt->next()->GetID();
1772
1773   return aResult._retn();
1774 }
1775
1776
1777 //=============================================================================
1778 /*!
1779  *
1780  */
1781 //=============================================================================
1782
1783 SMESH::long_array* SMESH_Mesh_i::GetElementsByType( SMESH::ElementType theElemType )
1784     throw (SALOME::SALOME_Exception)
1785 {
1786   Unexpect aCatch(SALOME_SalomeException);
1787   MESSAGE("SMESH_subMesh_i::GetElementsByType");
1788   SMESH::long_array_var aResult = new SMESH::long_array();
1789   SMESHDS_Mesh* aSMESHDS_Mesh = _impl->GetMeshDS();
1790
1791   if ( aSMESHDS_Mesh == NULL )
1792     return aResult._retn();
1793
1794   long nbElements = NbElements();
1795
1796   // No sense in returning ids of elements along with ids of nodes:
1797   // when theElemType == SMESH::ALL, return node ids only if
1798   // there are no elements
1799   if ( theElemType == SMESH::NODE || theElemType == SMESH::ALL && nbElements == 0 )
1800     return GetNodesId();
1801
1802   aResult->length( nbElements );
1803
1804   int i = 0;
1805
1806   SMDS_ElemIteratorPtr anIt = aSMESHDS_Mesh->elementsIterator();
1807   while ( i < nbElements && anIt->more() ) {
1808     const SMDS_MeshElement* anElem = anIt->next();
1809     if ( theElemType == SMESH::ALL || anElem->GetType() == (SMDSAbs_ElementType)theElemType )
1810       aResult[i++] = anElem->GetID();
1811   }
1812
1813   aResult->length( i );
1814
1815   return aResult._retn();
1816 }
1817
1818 //=============================================================================
1819 /*!
1820  *
1821  */
1822 //=============================================================================
1823
1824 SMESH::long_array* SMESH_Mesh_i::GetNodesId()
1825   throw (SALOME::SALOME_Exception)
1826 {
1827   Unexpect aCatch(SALOME_SalomeException);
1828   MESSAGE("SMESH_subMesh_i::GetNodesId");
1829   SMESH::long_array_var aResult = new SMESH::long_array();
1830   SMESHDS_Mesh* aSMESHDS_Mesh = _impl->GetMeshDS();
1831
1832   if ( aSMESHDS_Mesh == NULL )
1833     return aResult._retn();
1834
1835   long nbNodes = NbNodes();
1836   aResult->length( nbNodes );
1837   SMDS_NodeIteratorPtr anIt = aSMESHDS_Mesh->nodesIterator();
1838   for ( int i = 0, n = nbNodes; i < n && anIt->more(); i++ )
1839     aResult[i] = anIt->next()->GetID();
1840
1841   return aResult._retn();
1842 }
1843
1844 //=============================================================================
1845 /*!
1846  *
1847  */
1848 //=============================================================================
1849
1850 SMESH::ElementType SMESH_Mesh_i::GetElementType( const CORBA::Long id, const bool iselem )
1851   throw (SALOME::SALOME_Exception)
1852 {
1853   return ( SMESH::ElementType )_impl->GetElementType( id, iselem );
1854 }
1855
1856
1857 //=============================================================================
1858 /*!
1859  * Returns ID of elements for given submesh
1860  */
1861 //=============================================================================
1862 SMESH::long_array* SMESH_Mesh_i::GetSubMeshElementsId(const CORBA::Long ShapeID)
1863      throw (SALOME::SALOME_Exception)
1864 {
1865   SMESH::long_array_var aResult = new SMESH::long_array();
1866
1867   SMESH_subMesh* SM = _impl->GetSubMeshContaining(ShapeID);
1868   if(!SM) return aResult._retn();
1869
1870   SMESHDS_SubMesh* SDSM = SM->GetSubMeshDS();
1871   if(!SDSM) return aResult._retn();
1872
1873   aResult->length(SDSM->NbElements());
1874
1875   SMDS_ElemIteratorPtr eIt = SDSM->GetElements();
1876   int i = 0;
1877   while ( eIt->more() ) {
1878     aResult[i++] = eIt->next()->GetID();
1879   }
1880
1881   return aResult._retn();
1882 }
1883
1884
1885 //=============================================================================
1886 /*!
1887  * Returns ID of nodes for given submesh
1888  * If param all==true - returns all nodes, else -
1889  * returns only nodes on shapes.
1890  */
1891 //=============================================================================
1892 SMESH::long_array* SMESH_Mesh_i::GetSubMeshNodesId(const CORBA::Long ShapeID, CORBA::Boolean all)
1893      throw (SALOME::SALOME_Exception)
1894 {
1895   SMESH::long_array_var aResult = new SMESH::long_array();
1896
1897   SMESH_subMesh* SM = _impl->GetSubMeshContaining(ShapeID);
1898   if(!SM) return aResult._retn();
1899
1900   SMESHDS_SubMesh* SDSM = SM->GetSubMeshDS();
1901   if(!SDSM) return aResult._retn();
1902
1903   map<int,const SMDS_MeshElement*> theElems;
1904   if( !all || (SDSM->NbElements()==0 && SDSM->NbNodes()==1) ) {
1905     SMDS_NodeIteratorPtr nIt = SDSM->GetNodes();
1906     while ( nIt->more() ) {
1907       const SMDS_MeshNode* elem = nIt->next();
1908       theElems.insert( make_pair(elem->GetID(),elem) );
1909     }
1910   }
1911   else { // all nodes of submesh elements
1912     SMDS_ElemIteratorPtr eIt = SDSM->GetElements();
1913     while ( eIt->more() ) {
1914       const SMDS_MeshElement* anElem = eIt->next();
1915       SMDS_ElemIteratorPtr nIt = anElem->nodesIterator();
1916       while ( nIt->more() ) {
1917         const SMDS_MeshElement* elem = nIt->next();
1918         theElems.insert( make_pair(elem->GetID(),elem) );
1919       }
1920     }
1921   }
1922
1923   aResult->length(theElems.size());
1924   map<int, const SMDS_MeshElement * >::iterator itElem;
1925   int i = 0;
1926   for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ )
1927     aResult[i++] = (*itElem).first;
1928
1929   return aResult._retn();
1930 }
1931   
1932
1933 //=============================================================================
1934 /*!
1935  * Returns type of elements for given submesh
1936  */
1937 //=============================================================================
1938 SMESH::ElementType SMESH_Mesh_i::GetSubMeshElementType(const CORBA::Long ShapeID)
1939      throw (SALOME::SALOME_Exception)
1940 {
1941   SMESH_subMesh* SM = _impl->GetSubMeshContaining(ShapeID);
1942   if(!SM) return SMESH::ALL;
1943
1944   SMESHDS_SubMesh* SDSM = SM->GetSubMeshDS();
1945   if(!SDSM) return SMESH::ALL;
1946
1947   if(SDSM->NbElements()==0)
1948     return (SM->GetSubShape().ShapeType() == TopAbs_VERTEX) ? SMESH::NODE : SMESH::ALL;
1949
1950   SMDS_ElemIteratorPtr eIt = SDSM->GetElements();
1951   const SMDS_MeshElement* anElem = eIt->next();
1952   return ( SMESH::ElementType ) anElem->GetType();
1953 }
1954   
1955
1956 //=============================================================================
1957 /*!
1958  *
1959  */
1960 //=============================================================================
1961
1962 CORBA::LongLong SMESH_Mesh_i::GetMeshPtr()
1963 {
1964   CORBA::LongLong pointeur = CORBA::LongLong(_impl);
1965   cerr << "CORBA::LongLong SMESH_Mesh_i::GetMeshPtr() " << pointeur << endl;
1966   return pointeur;
1967 }
1968
1969
1970 //=============================================================================
1971 /*!
1972  * Get XYZ coordinates of node as list of double
1973  * If there is not node for given ID - returns empty list
1974  */
1975 //=============================================================================
1976
1977 SMESH::double_array* SMESH_Mesh_i::GetNodeXYZ(const CORBA::Long id)
1978 {
1979   SMESH::double_array_var aResult = new SMESH::double_array();
1980   SMESHDS_Mesh* aSMESHDS_Mesh = _impl->GetMeshDS();
1981   if ( aSMESHDS_Mesh == NULL )
1982     return aResult._retn();
1983
1984   // find node
1985   const SMDS_MeshNode* aNode = aSMESHDS_Mesh->FindNode(id);
1986   if(!aNode)
1987     return aResult._retn();
1988
1989   // add coordinates
1990   aResult->length(3);
1991   aResult[0] = aNode->X();
1992   aResult[1] = aNode->Y();
1993   aResult[2] = aNode->Z();
1994   return aResult._retn();
1995 }
1996
1997
1998 //=============================================================================
1999 /*!
2000  * For given node returns list of IDs of inverse elements
2001  * If there is not node for given ID - returns empty list
2002  */
2003 //=============================================================================
2004
2005 SMESH::long_array* SMESH_Mesh_i::GetNodeInverseElements(const CORBA::Long id)
2006 {
2007   SMESH::long_array_var aResult = new SMESH::long_array();
2008   SMESHDS_Mesh* aSMESHDS_Mesh = _impl->GetMeshDS();
2009   if ( aSMESHDS_Mesh == NULL )
2010     return aResult._retn();
2011
2012   // find node
2013   const SMDS_MeshNode* aNode = aSMESHDS_Mesh->FindNode(id);
2014   if(!aNode)
2015     return aResult._retn();
2016
2017   // find inverse elements
2018   SMDS_ElemIteratorPtr eIt = aNode->GetInverseElementIterator();
2019   TColStd_SequenceOfInteger IDs;
2020   while(eIt->more()) {
2021     const SMDS_MeshElement* elem = eIt->next();
2022     IDs.Append(elem->GetID());
2023   }
2024   if(IDs.Length()>0) {
2025     aResult->length(IDs.Length());
2026     int i = 1;
2027     for(; i<=IDs.Length(); i++) {
2028       aResult[i-1] = IDs.Value(i);
2029     }
2030   }
2031   return aResult._retn();
2032 }
2033
2034 //=============================================================================
2035 /*!
2036  * \brief Return position of a node on shape
2037  */
2038 //=============================================================================
2039
2040 SMESH::NodePosition* SMESH_Mesh_i::GetNodePosition(CORBA::Long NodeID)
2041 {
2042   SMESH::NodePosition* aNodePosition = new SMESH::NodePosition();
2043   aNodePosition->shapeID = 0;
2044   aNodePosition->shapeType = GEOM::SHAPE;
2045
2046   SMESHDS_Mesh* mesh = _impl->GetMeshDS();
2047   if ( !mesh ) return aNodePosition;
2048
2049   if ( const SMDS_MeshNode* aNode = mesh->FindNode(NodeID) )
2050   {
2051     if ( SMDS_PositionPtr pos = aNode->GetPosition() )
2052     {
2053       aNodePosition->shapeID = pos->GetShapeId();
2054       switch ( pos->GetTypeOfPosition() ) {
2055       case SMDS_TOP_EDGE:
2056         aNodePosition->shapeType = GEOM::EDGE;
2057         aNodePosition->params.length(1);
2058         aNodePosition->params[0] =
2059           static_cast<SMDS_EdgePosition*>( pos.get() )->GetUParameter();
2060         break;
2061       case SMDS_TOP_FACE:
2062         aNodePosition->shapeType = GEOM::FACE;
2063         aNodePosition->params.length(2);
2064         aNodePosition->params[0] =
2065           static_cast<SMDS_FacePosition*>( pos.get() )->GetUParameter();
2066         aNodePosition->params[1] =
2067           static_cast<SMDS_FacePosition*>( pos.get() )->GetVParameter();
2068         break;
2069       case SMDS_TOP_VERTEX:
2070         aNodePosition->shapeType = GEOM::VERTEX;
2071         break;
2072       case SMDS_TOP_3DSPACE:
2073         if ( TopExp_Explorer(_impl->GetShapeToMesh(), TopAbs_SOLID).More() )
2074           aNodePosition->shapeType = GEOM::SOLID;
2075         else if ( TopExp_Explorer(_impl->GetShapeToMesh(), TopAbs_SHELL).More() )
2076           aNodePosition->shapeType = GEOM::SHELL;
2077         break;
2078       default:;
2079       }
2080     }
2081   }
2082   return aNodePosition;
2083 }
2084
2085 //=============================================================================
2086 /*!
2087  * If given element is node returns IDs of shape from position
2088  * If there is not node for given ID - returns -1
2089  */
2090 //=============================================================================
2091
2092 CORBA::Long SMESH_Mesh_i::GetShapeID(const CORBA::Long id)
2093 {
2094   SMESHDS_Mesh* aSMESHDS_Mesh = _impl->GetMeshDS();
2095   if ( aSMESHDS_Mesh == NULL )
2096     return -1;
2097
2098   // try to find node
2099   const SMDS_MeshNode* aNode = aSMESHDS_Mesh->FindNode(id);
2100   if(aNode) {
2101     SMDS_PositionPtr pos = aNode->GetPosition();
2102     if(!pos)
2103       return -1;
2104     else
2105       return pos->GetShapeId();
2106   }
2107
2108   return -1;
2109 }
2110
2111
2112 //=============================================================================
2113 /*!
2114  * For given element returns ID of result shape after 
2115  * ::FindShape() from SMESH_MeshEditor
2116  * If there is not element for given ID - returns -1
2117  */
2118 //=============================================================================
2119
2120 CORBA::Long SMESH_Mesh_i::GetShapeIDForElem(const CORBA::Long id)
2121 {
2122   SMESHDS_Mesh* aSMESHDS_Mesh = _impl->GetMeshDS();
2123   if ( aSMESHDS_Mesh == NULL )
2124     return -1;
2125
2126   // try to find element
2127   const SMDS_MeshElement* elem = aSMESHDS_Mesh->FindElement(id);
2128   if(!elem)
2129     return -1;
2130
2131   //SMESH::SMESH_MeshEditor_var aMeshEditor = SMESH_Mesh_i::GetMeshEditor();
2132   ::SMESH_MeshEditor aMeshEditor(_impl);
2133   int index = aMeshEditor.FindShape( elem );
2134   if(index>0)
2135     return index;
2136
2137   return -1;
2138 }
2139
2140
2141 //=============================================================================
2142 /*!
2143  * Returns number of nodes for given element
2144  * If there is not element for given ID - returns -1
2145  */
2146 //=============================================================================
2147
2148 CORBA::Long SMESH_Mesh_i::GetElemNbNodes(const CORBA::Long id)
2149 {
2150   SMESHDS_Mesh* aSMESHDS_Mesh = _impl->GetMeshDS();
2151   if ( aSMESHDS_Mesh == NULL ) return -1;
2152   // try to find element
2153   const SMDS_MeshElement* elem = aSMESHDS_Mesh->FindElement(id);
2154   if(!elem) return -1;
2155   return elem->NbNodes();
2156 }
2157
2158
2159 //=============================================================================
2160 /*!
2161  * Returns ID of node by given index for given element
2162  * If there is not element for given ID - returns -1
2163  * If there is not node for given index - returns -2
2164  */
2165 //=============================================================================
2166
2167 CORBA::Long SMESH_Mesh_i::GetElemNode(const CORBA::Long id, const CORBA::Long index)
2168 {
2169   SMESHDS_Mesh* aSMESHDS_Mesh = _impl->GetMeshDS();
2170   if ( aSMESHDS_Mesh == NULL ) return -1;
2171   const SMDS_MeshElement* elem = aSMESHDS_Mesh->FindElement(id);
2172   if(!elem) return -1;
2173   if( index>=elem->NbNodes() || index<0 ) return -1;
2174   return elem->GetNode(index)->GetID();
2175 }
2176
2177 //=============================================================================
2178 /*!
2179  * Returns IDs of nodes of given element
2180  */
2181 //=============================================================================
2182
2183 SMESH::long_array* SMESH_Mesh_i::GetElemNodes(const CORBA::Long id)
2184 {
2185   SMESH::long_array_var aResult = new SMESH::long_array();
2186   if ( SMESHDS_Mesh* aSMESHDS_Mesh = _impl->GetMeshDS() )
2187   {
2188     if ( const SMDS_MeshElement* elem = aSMESHDS_Mesh->FindElement(id) )
2189     {
2190       aResult->length( elem->NbNodes() );
2191       for ( int i = 0; i < elem->NbNodes(); ++i )
2192         aResult[ i ] = elem->GetNode( i )->GetID();
2193     }
2194   }
2195   return aResult._retn();
2196 }
2197
2198 //=============================================================================
2199 /*!
2200  * Returns true if given node is medium node
2201  * in given quadratic element
2202  */
2203 //=============================================================================
2204
2205 CORBA::Boolean SMESH_Mesh_i::IsMediumNode(const CORBA::Long ide, const CORBA::Long idn)
2206 {
2207   SMESHDS_Mesh* aSMESHDS_Mesh = _impl->GetMeshDS();
2208   if ( aSMESHDS_Mesh == NULL ) return false;
2209   // try to find node
2210   const SMDS_MeshNode* aNode = aSMESHDS_Mesh->FindNode(idn);
2211   if(!aNode) return false;
2212   // try to find element
2213   const SMDS_MeshElement* elem = aSMESHDS_Mesh->FindElement(ide);
2214   if(!elem) return false;
2215
2216   return elem->IsMediumNode(aNode);
2217 }
2218
2219
2220 //=============================================================================
2221 /*!
2222  * Returns true if given node is medium node
2223  * in one of quadratic elements
2224  */
2225 //=============================================================================
2226
2227 CORBA::Boolean SMESH_Mesh_i::IsMediumNodeOfAnyElem(const CORBA::Long idn,
2228                                                    SMESH::ElementType theElemType)
2229 {
2230   SMESHDS_Mesh* aSMESHDS_Mesh = _impl->GetMeshDS();
2231   if ( aSMESHDS_Mesh == NULL ) return false;
2232
2233   // try to find node
2234   const SMDS_MeshNode* aNode = aSMESHDS_Mesh->FindNode(idn);
2235   if(!aNode) return false;
2236
2237   SMESH_MesherHelper aHelper( *(_impl) );
2238
2239   SMDSAbs_ElementType aType;
2240   if(theElemType==SMESH::EDGE) aType = SMDSAbs_Edge;
2241   else if(theElemType==SMESH::FACE) aType = SMDSAbs_Face;
2242   else if(theElemType==SMESH::VOLUME) aType = SMDSAbs_Volume;
2243   else aType = SMDSAbs_All;
2244
2245   return aHelper.IsMedium(aNode,aType);
2246 }
2247
2248
2249 //=============================================================================
2250 /*!
2251  * Returns number of edges for given element
2252  */
2253 //=============================================================================
2254
2255 CORBA::Long SMESH_Mesh_i::ElemNbEdges(const CORBA::Long id)
2256 {
2257   SMESHDS_Mesh* aSMESHDS_Mesh = _impl->GetMeshDS();
2258   if ( aSMESHDS_Mesh == NULL ) return -1;
2259   const SMDS_MeshElement* elem = aSMESHDS_Mesh->FindElement(id);
2260   if(!elem) return -1;
2261   return elem->NbEdges();
2262 }
2263
2264
2265 //=============================================================================
2266 /*!
2267  * Returns number of faces for given element
2268  */
2269 //=============================================================================
2270
2271 CORBA::Long SMESH_Mesh_i::ElemNbFaces(const CORBA::Long id)
2272 {
2273   SMESHDS_Mesh* aSMESHDS_Mesh = _impl->GetMeshDS();
2274   if ( aSMESHDS_Mesh == NULL ) return -1;
2275   const SMDS_MeshElement* elem = aSMESHDS_Mesh->FindElement(id);
2276   if(!elem) return -1;
2277   return elem->NbFaces();
2278 }
2279
2280
2281 //=============================================================================
2282 /*!
2283  * Returns true if given element is polygon
2284  */
2285 //=============================================================================
2286
2287 CORBA::Boolean SMESH_Mesh_i::IsPoly(const CORBA::Long id)
2288 {
2289   SMESHDS_Mesh* aSMESHDS_Mesh = _impl->GetMeshDS();
2290   if ( aSMESHDS_Mesh == NULL ) return false;
2291   const SMDS_MeshElement* elem = aSMESHDS_Mesh->FindElement(id);
2292   if(!elem) return false;
2293   return elem->IsPoly();
2294 }
2295
2296
2297 //=============================================================================
2298 /*!
2299  * Returns true if given element is quadratic
2300  */
2301 //=============================================================================
2302
2303 CORBA::Boolean SMESH_Mesh_i::IsQuadratic(const CORBA::Long id)
2304 {
2305   SMESHDS_Mesh* aSMESHDS_Mesh = _impl->GetMeshDS();
2306   if ( aSMESHDS_Mesh == NULL ) return false;
2307   const SMDS_MeshElement* elem = aSMESHDS_Mesh->FindElement(id);
2308   if(!elem) return false;
2309   return elem->IsQuadratic();
2310 }
2311
2312
2313 //=============================================================================
2314 /*!
2315  * Returns bary center for given element
2316  */
2317 //=============================================================================
2318
2319 SMESH::double_array* SMESH_Mesh_i::BaryCenter(const CORBA::Long id)
2320 {
2321   SMESH::double_array_var aResult = new SMESH::double_array();
2322   SMESHDS_Mesh* aSMESHDS_Mesh = _impl->GetMeshDS();
2323   if ( aSMESHDS_Mesh == NULL )
2324     return aResult._retn();
2325
2326   const SMDS_MeshElement* elem = aSMESHDS_Mesh->FindElement(id);
2327   if(!elem)
2328     return aResult._retn();
2329
2330   if(elem->GetType()==SMDSAbs_Volume) {
2331     SMDS_VolumeTool aTool;
2332     if(aTool.Set(elem)) {
2333       aResult->length(3);
2334       if (!aTool.GetBaryCenter( aResult[0], aResult[1], aResult[2]) )
2335         aResult->length(0);
2336     }
2337   }
2338   else {
2339     SMDS_ElemIteratorPtr anIt = elem->nodesIterator();
2340     int nbn = 0;
2341     double x=0., y=0., z=0.;
2342     for(; anIt->more(); ) {
2343       nbn++;
2344       const SMDS_MeshNode* aNode = static_cast<const SMDS_MeshNode*>(anIt->next());
2345       x += aNode->X();
2346       y += aNode->Y();
2347       z += aNode->Z();
2348     }
2349     if(nbn>0) {
2350       // add coordinates
2351       aResult->length(3);
2352       aResult[0] = x/nbn;
2353       aResult[1] = y/nbn;
2354       aResult[2] = z/nbn;
2355     }
2356   }
2357
2358   return aResult._retn();
2359 }
2360
2361
2362 //=============================================================================
2363 /*!
2364  * Create and publish group servants if any groups were imported or created anyhow
2365  */
2366 //=============================================================================
2367
2368 void SMESH_Mesh_i::CreateGroupServants() 
2369 {
2370   SALOMEDS::Study_ptr aStudy = _gen_i->GetCurrentStudy();
2371
2372   ::SMESH_Mesh::GroupIteratorPtr groupIt = _impl->GetGroups();
2373   while ( groupIt->more() )
2374   {
2375     ::SMESH_Group* group = groupIt->next();
2376     int            anId = group->GetGroupDS()->GetID();
2377
2378     map<int, SMESH::SMESH_GroupBase_ptr>::iterator it = _mapGroups.find(anId);
2379     if ( it != _mapGroups.end() && !CORBA::is_nil( it->second ))
2380       continue;
2381
2382     SMESH_GroupBase_i* aGroupImpl;
2383     TopoDS_Shape       shape;
2384     if ( SMESHDS_GroupOnGeom* groupOnGeom =
2385          dynamic_cast<SMESHDS_GroupOnGeom*>( group->GetGroupDS() ))
2386     {
2387       aGroupImpl = new SMESH_GroupOnGeom_i( SMESH_Gen_i::GetPOA(), this, anId );
2388       shape      = groupOnGeom->GetShape();
2389     }
2390     else {
2391       aGroupImpl = new SMESH_Group_i( SMESH_Gen_i::GetPOA(), this, anId );
2392     }
2393
2394     // To ensure correct mapping of servant and correct reference counting in GenericObj_i
2395     SMESH_Gen_i::GetPOA()->activate_object( aGroupImpl );
2396     aGroupImpl->Register();
2397
2398     SMESH::SMESH_GroupBase_var groupVar =
2399       SMESH::SMESH_GroupBase::_narrow( aGroupImpl->_this() );
2400     _mapGroups[anId] = SMESH::SMESH_GroupBase::_duplicate( groupVar );
2401
2402     // register CORBA object for persistence
2403     int nextId = _gen_i->RegisterObject( groupVar );
2404     if(MYDEBUG) MESSAGE( "Add group to map with id = "<< nextId);
2405
2406     // publishing of the groups in the study
2407     if ( !aStudy->_is_nil() ) {
2408       GEOM::GEOM_Object_var shapeVar = _gen_i->ShapeToGeomObject( shape );
2409       _gen_i->PublishGroup( aStudy, _this(), groupVar, shapeVar, groupVar->GetName());
2410     }
2411   }
2412 }
2413
2414 //=============================================================================
2415 /*!
2416  * \brief Return groups cantained in _mapGroups by their IDs
2417  */
2418 //=============================================================================
2419
2420 SMESH::ListOfGroups* SMESH_Mesh_i::GetGroups(const list<int>& groupIDs) const
2421 {
2422   int nbGroups = groupIDs.size();
2423   SMESH::ListOfGroups_var aList = new SMESH::ListOfGroups();
2424   aList->length( nbGroups );
2425
2426   list<int>::const_iterator ids = groupIDs.begin();
2427   for ( nbGroups = 0; ids != groupIDs.end(); ++ids )
2428   {
2429     map<int, SMESH::SMESH_GroupBase_ptr>::const_iterator it = _mapGroups.find( *ids );
2430     if ( it != _mapGroups.end() && !CORBA::is_nil( it->second ))
2431       aList[nbGroups++] = SMESH::SMESH_GroupBase::_duplicate( it->second );
2432   }
2433   aList->length( nbGroups );
2434   return aList._retn();
2435 }