Back to index

salome-smesh  6.5.0
SMESH_Gen_i.cxx
Go to the documentation of this file.
00001 // Copyright (C) 2007-2012  CEA/DEN, EDF R&D, OPEN CASCADE
00002 //
00003 // Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
00004 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
00005 //
00006 // This library is free software; you can redistribute it and/or
00007 // modify it under the terms of the GNU Lesser General Public
00008 // License as published by the Free Software Foundation; either
00009 // version 2.1 of the License.
00010 //
00011 // This library is distributed in the hope that it will be useful,
00012 // but WITHOUT ANY WARRANTY; without even the implied warranty of
00013 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00014 // Lesser General Public License for more details.
00015 //
00016 // You should have received a copy of the GNU Lesser General Public
00017 // License along with this library; if not, write to the Free Software
00018 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
00019 //
00020 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
00021 //
00022 //  File   : SMESH_Gen_i.cxx
00023 //  Author : Paul RASCLE, EDF
00024 //  Module : SMESH
00025 
00026 #include <TopExp.hxx>
00027 #include <TopExp_Explorer.hxx>
00028 #include <TopoDS.hxx>
00029 #include <TopoDS_Iterator.hxx>
00030 #include <TopoDS_Compound.hxx>
00031 #include <TopoDS_CompSolid.hxx>
00032 #include <TopoDS_Solid.hxx>
00033 #include <TopoDS_Shell.hxx>
00034 #include <TopoDS_Face.hxx>
00035 #include <TopoDS_Wire.hxx>
00036 #include <TopoDS_Edge.hxx>
00037 #include <TopoDS_Vertex.hxx>
00038 #include <TopoDS_Shape.hxx>
00039 #include <TopTools_MapOfShape.hxx>
00040 #include <TopTools_IndexedMapOfShape.hxx>
00041 #include <TopTools_ListOfShape.hxx>
00042 #include <TopTools_ListIteratorOfListOfShape.hxx>
00043 #include <gp_Pnt.hxx>
00044 #include <BRep_Tool.hxx>
00045 #include <TCollection_AsciiString.hxx>
00046 #include <OSD.hxx>
00047 
00048 #ifdef WNT
00049  #include <windows.h>
00050  #include <process.h>
00051 #else
00052  #include <dlfcn.h>
00053 #endif
00054 
00055 #ifdef WNT
00056  #define LibHandle HMODULE
00057  #define LoadLib( name ) LoadLibrary( name )
00058  #define GetProc GetProcAddress
00059  #define UnLoadLib( handle ) FreeLibrary( handle );
00060 #else
00061  #define LibHandle void*
00062  #define LoadLib( name ) dlopen( name, RTLD_LAZY )
00063  #define GetProc dlsym
00064  #define UnLoadLib( handle ) dlclose( handle );
00065 #endif
00066 
00067 #include "SMESH_Gen_i.hxx"
00068 
00069 #include "SMDS_EdgePosition.hxx"
00070 #include "SMDS_FacePosition.hxx"
00071 #include "SMDS_PolyhedralVolumeOfNodes.hxx"
00072 #include "SMDS_SetIterator.hxx"
00073 #include "SMDS_SpacePosition.hxx"
00074 #include "SMDS_VertexPosition.hxx"
00075 #include "SMESHDS_Document.hxx"
00076 #include "SMESHDS_Group.hxx"
00077 #include "SMESHDS_GroupOnGeom.hxx"
00078 #include "SMESH_Algo_i.hxx"
00079 #include "SMESH_File.hxx"
00080 #include "SMESH_Group.hxx"
00081 #include "SMESH_Group_i.hxx"
00082 #include "SMESH_Hypothesis.hxx"
00083 #include "SMESH_Hypothesis_i.hxx"
00084 #include "SMESH_Mesh.hxx"
00085 #include "SMESH_MeshEditor.hxx"
00086 #include "SMESH_Mesh_i.hxx"
00087 #include "SMESH_PreMeshInfo.hxx"
00088 #include "SMESH_PythonDump.hxx"
00089 
00090 #include CORBA_SERVER_HEADER(SMESH_Group)
00091 #include CORBA_SERVER_HEADER(SMESH_Filter)
00092 #include CORBA_SERVER_HEADER(SMESH_MeshEditor)
00093 
00094 #include "DriverMED_W_SMESHDS_Mesh.h"
00095 #include "DriverMED_R_SMESHDS_Mesh.h"
00096 #ifdef WITH_CGNS
00097 #include "DriverCGNS_Read.hxx"
00098 #endif
00099 #include "memoire.h"
00100 
00101 #include <GEOM_Client.hxx>
00102 
00103 #include <Basics_Utils.hxx>
00104 #include <HDFOI.hxx>
00105 #include <OpUtil.hxx>
00106 #include <SALOMEDS_Tool.hxx>
00107 #include <SALOME_Container_i.hxx>
00108 #include <SALOME_LifeCycleCORBA.hxx>
00109 #include <SALOME_NamingService.hxx>
00110 #include <Utils_CorbaException.hxx>
00111 #include <Utils_ExceptHandlers.hxx>
00112 #include <Utils_SINGLETON.hxx>
00113 #include <utilities.h>
00114 
00115 #include CORBA_CLIENT_HEADER(SALOME_ModuleCatalog)
00116 #include CORBA_CLIENT_HEADER(SALOME_Session)
00117 
00118 #include <map>
00119 #include <fstream>
00120 #include <cstdio>
00121 
00122 using namespace std;
00123 using SMESH::TPythonDump;
00124 using SMESH::TVar;
00125 
00126 #define NUM_TMP_FILES 2
00127 
00128 #ifdef _DEBUG_
00129 static int MYDEBUG = 0;
00130 #else
00131 static int MYDEBUG = 0;
00132 #endif
00133 
00134 // Static variables definition
00135 GEOM::GEOM_Gen_var      SMESH_Gen_i::myGeomGen = GEOM::GEOM_Gen::_nil();
00136 CORBA::ORB_var          SMESH_Gen_i::myOrb;
00137 PortableServer::POA_var SMESH_Gen_i::myPoa;
00138 SALOME_NamingService*   SMESH_Gen_i::myNS  = NULL;
00139 SALOME_LifeCycleCORBA*  SMESH_Gen_i::myLCC = NULL;
00140 SMESH_Gen_i*            SMESH_Gen_i::mySMESHGen = NULL;
00141 
00142 
00143 const int nbElemPerDiagonal = 10;
00144 
00145 //=============================================================================
00151 //=============================================================================
00152 
00153 PortableServer::ServantBase_var SMESH_Gen_i::GetServant( CORBA::Object_ptr theObject )
00154 {
00155   if( CORBA::is_nil( theObject ) || CORBA::is_nil( GetPOA() ) )
00156     return NULL;
00157   try {
00158     PortableServer::Servant aServant = GetPOA()->reference_to_servant( theObject );
00159     return aServant;
00160   }
00161   catch (...) {
00162     INFOS( "GetServant - Unknown exception was caught!!!" );
00163     return NULL;
00164   }
00165 }
00166 
00167 //=============================================================================
00173 //=============================================================================
00174 
00175 CORBA::Object_var SMESH_Gen_i::SObjectToObject( SALOMEDS::SObject_ptr theSObject )
00176 {
00177   SALOMEDS::GenericAttribute_var anAttr;
00178   CORBA::Object_var anObj;
00179   if ( !theSObject->_is_nil() ) {
00180     try {
00181       if( theSObject->FindAttribute( anAttr, "AttributeIOR" ) ) {
00182         SALOMEDS::AttributeIOR_var anIOR  = SALOMEDS::AttributeIOR::_narrow( anAttr );
00183         CORBA::String_var aValue = anIOR->Value();
00184         if( strcmp( aValue, "" ) != 0 )
00185           anObj = GetORB()->string_to_object( aValue );
00186         }
00187     }
00188     catch( ... ) {
00189       INFOS( "SObjectToObject - Unknown exception was caught!!!" );
00190     }
00191   }
00192   return anObj;
00193 }
00194 
00195 //=============================================================================
00201 //=============================================================================
00202 
00203 SALOME_NamingService* SMESH_Gen_i::GetNS()
00204 {
00205   if ( myNS == NULL ) {
00206     myNS = SINGLETON_<SALOME_NamingService>::Instance();
00207     ASSERT(SINGLETON_<SALOME_NamingService>::IsAlreadyExisting());
00208     myNS->init_orb( GetORB() );
00209   }
00210   return myNS;
00211 }
00212 
00213 //=============================================================================
00219 //=============================================================================
00220 SALOME_LifeCycleCORBA*  SMESH_Gen_i::GetLCC() {
00221   if ( myLCC == NULL ) {
00222     myLCC = new SALOME_LifeCycleCORBA( GetNS() );
00223   }
00224   return myLCC;
00225 }
00226 
00227 
00228 //=============================================================================
00234 //=============================================================================
00235 GEOM::GEOM_Gen_ptr SMESH_Gen_i::GetGeomEngine() {
00236   //CCRT GEOM::GEOM_Gen_var aGeomEngine =
00237   //CCRT   GEOM::GEOM_Gen::_narrow( GetLCC()->FindOrLoad_Component("FactoryServer","GEOM") );
00238   //CCRT return aGeomEngine._retn();
00239   if(CORBA::is_nil(myGeomGen))
00240   {
00241     Engines::EngineComponent_ptr temp=GetLCC()->FindOrLoad_Component("FactoryServer","GEOM");
00242     myGeomGen=GEOM::GEOM_Gen::_narrow(temp);
00243   }
00244   return myGeomGen;
00245 }
00246 
00247 //=============================================================================
00253 //=============================================================================
00254 
00255 SMESH_Gen_i::SMESH_Gen_i()
00256 {
00257   INFOS( "SMESH_Gen_i::SMESH_Gen_i : default constructor" );
00258 }
00259 
00260 //=============================================================================
00266 //=============================================================================
00267 
00268 SMESH_Gen_i::SMESH_Gen_i( CORBA::ORB_ptr            orb,
00269                           PortableServer::POA_ptr   poa,
00270                           PortableServer::ObjectId* contId,
00271                           const char*               instanceName,
00272                           const char*               interfaceName )
00273      : Engines_Component_i( orb, poa, contId, instanceName, interfaceName )
00274 {
00275   MESSAGE( "SMESH_Gen_i::SMESH_Gen_i : standard constructor" );
00276 
00277   myOrb = CORBA::ORB::_duplicate(orb);
00278   myPoa = PortableServer::POA::_duplicate(poa);
00279 
00280   _thisObj = this ;
00281   _id = myPoa->activate_object( _thisObj );
00282 
00283   myIsEmbeddedMode = false;
00284   myShapeReader = NULL;  // shape reader
00285   mySMESHGen = this;
00286   myIsHistoricalPythonDump = true;
00287   myToForgetMeshDataOnHypModif = false;
00288 
00289   // set it in standalone mode only
00290   //OSD::SetSignal( true );
00291 
00292   // 0020605: EDF 1190 SMESH: Display performance. 80 seconds for 52000 cells.
00293   // find out mode (embedded or standalone) here else
00294   // meshes created before calling SMESH_Client::GetSMESHGen(), which calls
00295   // SMESH_Gen_i::SetEmbeddedMode(), have wrong IsEmbeddedMode flag
00296   if ( SALOME_NamingService* ns = GetNS() )
00297   {
00298     CORBA::Object_var obj = ns->Resolve( "/Kernel/Session" );
00299     SALOME::Session_var session = SALOME::Session::_narrow( obj ) ;
00300     if ( !session->_is_nil() )
00301     {
00302       CORBA::String_var str_host = session->getHostname();
00303       CORBA::Long        s_pid = session->getPID();
00304       string my_host = Kernel_Utils::GetHostname();
00305 #ifdef WNT
00306       long    my_pid = (long)_getpid();
00307 #else
00308       long    my_pid = (long) getpid();
00309 #endif
00310       SetEmbeddedMode( s_pid == my_pid && my_host == str_host.in() );
00311     }
00312   }
00313 }
00314 
00315 //=============================================================================
00321 //=============================================================================
00322 
00323 SMESH_Gen_i::~SMESH_Gen_i()
00324 {
00325   MESSAGE( "SMESH_Gen_i::~SMESH_Gen_i" );
00326 
00327   // delete hypothesis creators
00328   map<string, GenericHypothesisCreator_i*>::iterator itHyp;
00329   for (itHyp = myHypCreatorMap.begin(); itHyp != myHypCreatorMap.end(); itHyp++)
00330   {
00331     delete (*itHyp).second;
00332   }
00333   myHypCreatorMap.clear();
00334 
00335   // Clear study contexts data
00336   map<int, StudyContext*>::iterator it;
00337   for ( it = myStudyContextMap.begin(); it != myStudyContextMap.end(); ++it ) {
00338     delete it->second;
00339   }
00340   myStudyContextMap.clear();
00341   // delete shape reader
00342   if ( !myShapeReader )
00343     delete myShapeReader;
00344 }
00345 
00346 //=============================================================================
00352 //=============================================================================
00353 SMESH::SMESH_Hypothesis_ptr SMESH_Gen_i::createHypothesis(const char* theHypName,
00354                                                           const char* theLibName)
00355      throw (SALOME::SALOME_Exception)
00356 {
00357   /* It's Need to tranlate lib name for WIN32 or X platform */
00358   char* aPlatformLibName = 0;
00359   if ( theLibName && theLibName[0] != '\0'  )
00360   {
00361     int libNameLen = strlen(theLibName);
00362     //check for old format "libXXXXXXX.so"
00363     if (libNameLen > 7 &&
00364         !strncmp( theLibName, "lib", 3 ) &&
00365         !strcmp( theLibName+libNameLen-3, ".so" ))
00366     {
00367       //the old format
00368 #ifdef WNT
00369       aPlatformLibName = new char[libNameLen - 1];
00370       aPlatformLibName[0] = '\0';
00371       aPlatformLibName = strncat( aPlatformLibName, theLibName+3, libNameLen-6  );
00372       aPlatformLibName = strcat( aPlatformLibName, ".dll" );
00373       aPlatformLibName[libNameLen - 2] = '\0';
00374 #else
00375       aPlatformLibName = new char[ libNameLen + 1];
00376       aPlatformLibName[0] = '\0';
00377       aPlatformLibName = strcat( aPlatformLibName, theLibName );
00378       aPlatformLibName[libNameLen] = '\0';
00379 #endif
00380     }
00381     else
00382     {
00383       //try to use new format
00384 #ifdef WNT
00385       aPlatformLibName = new char[ libNameLen + 5 ];
00386       aPlatformLibName[0] = '\0';
00387       aPlatformLibName = strcat( aPlatformLibName, theLibName );
00388       aPlatformLibName = strcat( aPlatformLibName, ".dll" );
00389 #else
00390       aPlatformLibName = new char[ libNameLen + 7 ];
00391       aPlatformLibName[0] = '\0';
00392       aPlatformLibName = strcat( aPlatformLibName, "lib" );
00393       aPlatformLibName = strcat( aPlatformLibName, theLibName );
00394       aPlatformLibName = strcat( aPlatformLibName, ".so" );
00395 #endif
00396     }
00397   }
00398 
00399 
00400   Unexpect aCatch(SALOME_SalomeException);
00401   if(MYDEBUG) MESSAGE( "Create Hypothesis <" << theHypName << "> from " << aPlatformLibName/*theLibName*/);
00402 
00403   // create a new hypothesis object servant
00404   SMESH_Hypothesis_i* myHypothesis_i = 0;
00405   SMESH::SMESH_Hypothesis_var hypothesis_i;
00406 
00407   try
00408   {
00409     // check, if creator for this hypothesis type already exists
00410     if (myHypCreatorMap.find(string(theHypName)) == myHypCreatorMap.end())
00411     {
00412       // load plugin library
00413       if(MYDEBUG) MESSAGE("Loading server meshers plugin library ...");
00414       LibHandle libHandle = LoadLib( aPlatformLibName/*theLibName*/ );
00415       if (!libHandle)
00416       {
00417         // report any error, if occured
00418 #ifndef WNT
00419         const char* anError = dlerror();
00420         throw(SALOME_Exception(anError));
00421 #else
00422         throw(SALOME_Exception(LOCALIZED( "Can't load server meshers plugin library" )));
00423 #endif
00424       }
00425 
00426       // get method, returning hypothesis creator
00427       if(MYDEBUG) MESSAGE("Find GetHypothesisCreator() method ...");
00428       typedef GenericHypothesisCreator_i* (*GetHypothesisCreator)(const char* theHypName);
00429       GetHypothesisCreator procHandle =
00430         (GetHypothesisCreator)GetProc( libHandle, "GetHypothesisCreator" );
00431       if (!procHandle)
00432       {
00433         throw(SALOME_Exception(LOCALIZED("bad hypothesis plugin library")));
00434         UnLoadLib(libHandle);
00435       }
00436 
00437       // get hypothesis creator
00438       if(MYDEBUG) MESSAGE("Get Hypothesis Creator for " << theHypName);
00439       GenericHypothesisCreator_i* aCreator = procHandle(theHypName);
00440       if (!aCreator)
00441       {
00442         throw(SALOME_Exception(LOCALIZED("no such a hypothesis in this plugin")));
00443       }
00444 
00445       // map hypothesis creator to a hypothesis name
00446       myHypCreatorMap[string(theHypName)] = aCreator;
00447     }
00448 
00449     // create a new hypothesis object, store its ref. in studyContext
00450     if(MYDEBUG) MESSAGE("Create Hypothesis " << theHypName);
00451     myHypothesis_i =
00452       myHypCreatorMap[string(theHypName)]->Create(myPoa, GetCurrentStudyID(), &myGen);
00453     myHypothesis_i->SetLibName(aPlatformLibName/*theLibName*/); // for persistency assurance
00454   }
00455   catch (SALOME_Exception& S_ex)
00456   {
00457     THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
00458   }
00459 
00460   if ( aPlatformLibName )
00461     delete[] aPlatformLibName;
00462 
00463   if (!myHypothesis_i)
00464     return hypothesis_i._retn();
00465 
00466   // activate the CORBA servant of hypothesis
00467   hypothesis_i = SMESH::SMESH_Hypothesis::_narrow( myHypothesis_i->_this() );
00468   int nextId = RegisterObject( hypothesis_i );
00469   if(MYDEBUG) MESSAGE( "Add hypo to map with id = "<< nextId );
00470 
00471   return hypothesis_i._retn();
00472 }
00473 
00474 //=============================================================================
00480 //=============================================================================
00481 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::createMesh()
00482      throw ( SALOME::SALOME_Exception )
00483 {
00484   Unexpect aCatch(SALOME_SalomeException);
00485   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::createMesh" );
00486 
00487   // Get or create the GEOM_Client instance
00488   try {
00489     // create a new mesh object servant, store it in a map in study context
00490     SMESH_Mesh_i* meshServant = new SMESH_Mesh_i( GetPOA(), this, GetCurrentStudyID() );
00491     // create a new mesh object
00492     MESSAGE("myIsEmbeddedMode " << myIsEmbeddedMode);
00493     meshServant->SetImpl( myGen.CreateMesh( GetCurrentStudyID(), myIsEmbeddedMode ));
00494 
00495     // activate the CORBA servant of Mesh
00496     SMESH::SMESH_Mesh_var mesh = SMESH::SMESH_Mesh::_narrow( meshServant->_this() );
00497     int nextId = RegisterObject( mesh );
00498     if(MYDEBUG) MESSAGE( "Add mesh to map with id = "<< nextId);
00499     return mesh._retn();
00500   }
00501   catch (SALOME_Exception& S_ex) {
00502     THROW_SALOME_CORBA_EXCEPTION( S_ex.what(), SALOME::BAD_PARAM );
00503   }
00504   return SMESH::SMESH_Mesh::_nil();
00505 }
00506 
00507 //=============================================================================
00513 //=============================================================================
00514 GEOM_Client* SMESH_Gen_i::GetShapeReader()
00515 {
00516   // create shape reader if necessary
00517   if ( !myShapeReader )
00518     myShapeReader = new GEOM_Client(GetContainerRef());
00519   ASSERT( myShapeReader );
00520   return myShapeReader;
00521 }
00522 
00523 //=============================================================================
00529 //=============================================================================
00530 //GEOM::GEOM_Gen_ptr SMESH_Gen_i::SetGeomEngine( const char* containerLoc )
00531 void SMESH_Gen_i::SetGeomEngine( GEOM::GEOM_Gen_ptr geomcompo )
00532 {
00533   //Engines::Component_ptr temp=GetLCC()->FindOrLoad_Component(containerLoc,"GEOM");
00534   //myGeomGen=GEOM::GEOM_Gen::_narrow(temp);
00535   myGeomGen=GEOM::GEOM_Gen::_duplicate(geomcompo);
00536   //return myGeomGen;
00537 }
00538 
00539 //=============================================================================
00545 //=============================================================================
00546 
00547 void SMESH_Gen_i::SetEmbeddedMode( CORBA::Boolean theMode )
00548 {
00549   myIsEmbeddedMode = theMode;
00550   MESSAGE("myIsEmbeddedMode " << myIsEmbeddedMode);
00551 
00552   if ( !myIsEmbeddedMode ) {
00553     //PAL10867: disable signals catching with "noexcepthandler" option
00554     char* envNoCatchSignals = getenv("NOT_INTERCEPT_SIGNALS");
00555     if (!envNoCatchSignals || !atoi(envNoCatchSignals))
00556     {
00557       bool raiseFPE;
00558 #ifdef _DEBUG_
00559       raiseFPE = true;
00560       char* envDisableFPE = getenv("DISABLE_FPE");
00561       if (envDisableFPE && atoi(envDisableFPE))
00562         raiseFPE = false;
00563 #else
00564       raiseFPE = false;
00565 #endif
00566       OSD::SetSignal( raiseFPE );
00567     }
00568     // else OSD::SetSignal() is called in GUI
00569   }
00570 }
00571 
00572 //=============================================================================
00578 //=============================================================================
00579 
00580 CORBA::Boolean SMESH_Gen_i::IsEmbeddedMode()
00581 {
00582   return myIsEmbeddedMode;
00583 }
00584 
00585 //=============================================================================
00591 //=============================================================================
00592 
00593 void SMESH_Gen_i::SetCurrentStudy( SALOMEDS::Study_ptr theStudy )
00594 {
00595   int curStudyId = GetCurrentStudyID();
00596   myCurrentStudy = SALOMEDS::Study::_duplicate( theStudy );
00597   // create study context, if it doesn't exist and set current study
00598   int studyId = GetCurrentStudyID();
00599   if ( myStudyContextMap.find( studyId ) == myStudyContextMap.end() ) {
00600     myStudyContextMap[ studyId ] = new StudyContext;
00601   }
00602 
00603   // myCurrentStudy may be nil
00604   if ( !CORBA::is_nil( myCurrentStudy ) ) {
00605     SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder();
00606     if( !myCurrentStudy->FindComponent( "GEOM" )->_is_nil() )
00607       aStudyBuilder->LoadWith( myCurrentStudy->FindComponent( "GEOM" ), GetGeomEngine() );
00608 
00609     // NPAL16168, issue 0020210
00610     // Let meshes update their data depending on GEOM groups that could change
00611     if ( curStudyId != studyId )
00612     {
00613       //SALOMEDS::SComponent_var me =  PublishComponent( myCurrentStudy );
00614       SALOMEDS::SComponent_var me = SALOMEDS::SComponent::_narrow
00615         ( myCurrentStudy->FindComponent( ComponentDataType() ) );
00616       if ( !me->_is_nil() ) {
00617         SALOMEDS::ChildIterator_var anIter = myCurrentStudy->NewChildIterator( me );
00618         for ( ; anIter->More(); anIter->Next() ) {
00619           SALOMEDS::SObject_var so = anIter->Value();
00620           CORBA::Object_var    ior = SObjectToObject( so );
00621           if ( SMESH_Mesh_i*  mesh = SMESH::DownCast<SMESH_Mesh_i*>( ior ))
00622             mesh->CheckGeomGroupModif();
00623         }
00624       }
00625     }
00626   }
00627 }
00628 
00629 //=============================================================================
00635 //=============================================================================
00636 
00637 SALOMEDS::Study_ptr SMESH_Gen_i::GetCurrentStudy()
00638 {
00639   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetCurrentStudy: study Id = " << GetCurrentStudyID() );
00640   return SALOMEDS::Study::_duplicate( myCurrentStudy );
00641 }
00642 
00643 //=============================================================================
00649 //=============================================================================
00650 StudyContext* SMESH_Gen_i::GetCurrentStudyContext()
00651 {
00652   if ( !CORBA::is_nil( myCurrentStudy ) &&
00653       myStudyContextMap.find( GetCurrentStudyID() ) != myStudyContextMap.end() )
00654     return myStudyContextMap[ myCurrentStudy->StudyId() ];
00655   else
00656     return 0;
00657 }
00658 
00659 //=============================================================================
00665 //=============================================================================
00666 
00667 SMESH::SMESH_Hypothesis_ptr SMESH_Gen_i::CreateHypothesis( const char* theHypName,
00668                                                            const char* theLibName )
00669      throw ( SALOME::SALOME_Exception )
00670 {
00671   Unexpect aCatch(SALOME_SalomeException);
00672   // Create hypothesis/algorithm
00673   SMESH::SMESH_Hypothesis_var hyp = this->createHypothesis( theHypName, theLibName );
00674 
00675   // Publish hypothesis/algorithm in the study
00676   if ( CanPublishInStudy( hyp ) ) {
00677     SALOMEDS::SObject_var aSO = PublishHypothesis( myCurrentStudy, hyp );
00678     if ( !aSO->_is_nil() ) {
00679       // Update Python script
00680       TPythonDump() << aSO << " = " << this << ".CreateHypothesis('"
00681                     << theHypName << "', '" << theLibName << "')";
00682     }
00683   }
00684 
00685   return hyp._retn();
00686 }
00687 
00688 //================================================================================
00700 //================================================================================
00701 
00702 SMESH::SMESH_Hypothesis_ptr
00703 SMESH_Gen_i::GetHypothesisParameterValues (const char*           theHypType,
00704                                            const char*           theLibName,
00705                                            SMESH::SMESH_Mesh_ptr theMesh,
00706                                            GEOM::GEOM_Object_ptr theGeom,
00707                                            CORBA::Boolean        byMesh)
00708   throw ( SALOME::SALOME_Exception )
00709 {
00710   Unexpect aCatch(SALOME_SalomeException);
00711   if ( byMesh && CORBA::is_nil( theMesh ) )
00712     return SMESH::SMESH_Hypothesis::_nil();
00713   if ( byMesh && CORBA::is_nil( theGeom ) )
00714     return SMESH::SMESH_Hypothesis::_nil();
00715 
00716   // -----------------------------------------------
00717   // find hypothesis used to mesh theGeom
00718   // -----------------------------------------------
00719 
00720   // get mesh and shape
00721   SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
00722   TopoDS_Shape shape = GeomObjectToShape( theGeom );
00723   if ( byMesh && ( !meshServant || meshServant->NbNodes()==0 || shape.IsNull() ))
00724     return SMESH::SMESH_Hypothesis::_nil();
00725   ::SMESH_Mesh* mesh = meshServant ? &meshServant->GetImpl() : (::SMESH_Mesh*)0;
00726 
00727   // create a temporary hypothesis to know its dimention
00728   SMESH::SMESH_Hypothesis_var tmpHyp = this->createHypothesis( theHypType, theLibName );
00729   SMESH_Hypothesis_i* hypServant = SMESH::DownCast<SMESH_Hypothesis_i*>( tmpHyp );
00730   if ( !hypServant )
00731     return SMESH::SMESH_Hypothesis::_nil();
00732   ::SMESH_Hypothesis* hyp = hypServant->GetImpl();
00733 
00734   if ( byMesh ) {
00735     // look for a hypothesis of theHypType used to mesh the shape
00736     if ( myGen.GetShapeDim( shape ) == hyp->GetDim() )
00737     {
00738       // check local shape
00739       SMESH::ListOfHypothesis_var aHypList = theMesh->GetHypothesisList( theGeom );
00740       int nbLocalHyps = aHypList->length();
00741       for ( int i = 0; i < nbLocalHyps; i++ )
00742         if ( strcmp( theHypType, aHypList[i]->GetName() ) == 0 ) // FOUND local!
00743           return SMESH::SMESH_Hypothesis::_duplicate( aHypList[i] );
00744       // check super shapes
00745       TopTools_ListIteratorOfListOfShape itShape( mesh->GetAncestors( shape ));
00746       while ( nbLocalHyps == 0 && itShape.More() ) {
00747         GEOM::GEOM_Object_ptr geomObj = ShapeToGeomObject( itShape.Value() );
00748         if ( ! CORBA::is_nil( geomObj )) {
00749           SMESH::ListOfHypothesis_var aHypList = theMesh->GetHypothesisList( geomObj );
00750           nbLocalHyps = aHypList->length();
00751           for ( int i = 0; i < nbLocalHyps; i++ )
00752             if ( strcmp( theHypType, aHypList[i]->GetName() ) == 0 ) // FOUND global!
00753               return SMESH::SMESH_Hypothesis::_duplicate( aHypList[i] );
00754         }
00755         itShape.Next();
00756       }
00757     }
00758 
00759     // let the temporary hypothesis find out somehow parameter values by mesh
00760     if ( hyp->SetParametersByMesh( mesh, shape ))
00761       return SMESH::SMESH_Hypothesis::_duplicate( tmpHyp );
00762   }
00763   else {
00764     double diagonal = 0;
00765     if ( mesh )
00766       diagonal = mesh->GetShapeDiagonalSize();
00767     else
00768       diagonal = ::SMESH_Mesh::GetShapeDiagonalSize( shape );
00769     ::SMESH_Hypothesis::TDefaults dflts;
00770     dflts._elemLength = diagonal / myGen.GetBoundaryBoxSegmentation();
00771     dflts._nbSegments = myGen.GetDefaultNbSegments();
00772     dflts._shape      = &shape;
00773     // let the temporary hypothesis initialize it's values
00774     if ( hyp->SetParametersByDefaults( dflts, mesh ))
00775       return SMESH::SMESH_Hypothesis::_duplicate( tmpHyp );
00776   }
00777 
00778   return SMESH::SMESH_Hypothesis::_nil();
00779 }
00780 
00781 //=============================================================================
00786 //=============================================================================
00787 
00788 void SMESH_Gen_i::SetBoundaryBoxSegmentation( CORBA::Long theNbSegments )
00789   throw ( SALOME::SALOME_Exception )
00790 {
00791   if ( theNbSegments > 0 )
00792     myGen.SetBoundaryBoxSegmentation( int( theNbSegments ));
00793   else
00794     THROW_SALOME_CORBA_EXCEPTION( "non-positive number of segments", SALOME::BAD_PARAM );
00795 }
00796 //=============================================================================
00800 //=============================================================================
00801 void SMESH_Gen_i::SetDefaultNbSegments(CORBA::Long theNbSegments)
00802   throw ( SALOME::SALOME_Exception )
00803 {
00804   if ( theNbSegments > 0 )
00805     myGen.SetDefaultNbSegments( int(theNbSegments) );
00806   else
00807     THROW_SALOME_CORBA_EXCEPTION( "non-positive number of segments", SALOME::BAD_PARAM );
00808 }
00809 
00810 //=============================================================================
00814 //=============================================================================
00815 
00816 void SMESH_Gen_i::SetOption(const char* name, const char* value)
00817 {
00818   if ( name && value && strlen( value ) > 0 )
00819   {
00820     string msgToGUI; 
00821     if ( strcmp(name, "historical_python_dump") == 0 )
00822     {
00823       myIsHistoricalPythonDump = ( value[0] == '1' || toupper(value[0]) == 'T' ); // 1 || true
00824       msgToGUI = "preferences/SMESH/historical_python_dump/";
00825       msgToGUI += myIsHistoricalPythonDump ? "true" : "false";
00826     }
00827     else if ( strcmp(name, "forget_mesh_on_hyp_modif") == 0 )
00828     {
00829       myToForgetMeshDataOnHypModif = ( value[0] == '1' || toupper(value[0]) == 'T' ); // 1 || true
00830       msgToGUI = "preferences/SMESH/forget_mesh_on_hyp_modif/";
00831       msgToGUI += myToForgetMeshDataOnHypModif ? "true" : "false";
00832     }
00833 
00834     // update preferences in case if SetOption() is invoked from python console
00835     if ( !msgToGUI.empty() )
00836     {
00837       CORBA::Object_var obj = SMESH_Gen_i::GetNS()->Resolve( "/Kernel/Session" );
00838       SALOME::Session_var session = SALOME::Session::_narrow( obj );
00839       if ( !CORBA::is_nil( session ) )
00840         session->emitMessageOneWay(msgToGUI.c_str());
00841     }
00842   }
00843 }
00844 
00845 //=============================================================================
00849 //=============================================================================
00850 
00851 char* SMESH_Gen_i::GetOption(const char* name)
00852 {
00853   if ( name )
00854   {
00855     if ( strcmp(name, "historical_python_dump") == 0 )
00856     {
00857       return CORBA::string_dup( myIsHistoricalPythonDump ? "true" : "false" );
00858     }
00859     if ( strcmp(name, "forget_mesh_on_hyp_modif") == 0 )
00860     {
00861       return CORBA::string_dup( myToForgetMeshDataOnHypModif ? "true" : "false" );
00862     }
00863   }
00864   return CORBA::string_dup( "" );
00865 }
00866 
00867 //=============================================================================
00873 //=============================================================================
00874 
00875 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMesh( GEOM::GEOM_Object_ptr theShapeObject )
00876      throw ( SALOME::SALOME_Exception )
00877 {
00878   Unexpect aCatch(SALOME_SalomeException);
00879   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::CreateMesh" );
00880   // create mesh
00881   SMESH::SMESH_Mesh_var mesh = this->createMesh();
00882   // set shape
00883   SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( mesh );
00884   ASSERT( meshServant );
00885   meshServant->SetShape( theShapeObject );
00886 
00887   // publish mesh in the study
00888   if ( CanPublishInStudy( mesh ) ) {
00889     SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder();
00890     aStudyBuilder->NewCommand();  // There is a transaction
00891     SALOMEDS::SObject_var aSO = PublishMesh( myCurrentStudy, mesh.in() );
00892     aStudyBuilder->CommitCommand();
00893     if ( !aSO->_is_nil() ) {
00894       // Update Python script
00895       TPythonDump() << aSO << " = " << this << ".CreateMesh(" << theShapeObject << ")";
00896     }
00897   }
00898 
00899   return mesh._retn();
00900 }
00901 
00902 //=============================================================================
00908 //=============================================================================
00909 
00910 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateEmptyMesh()
00911      throw ( SALOME::SALOME_Exception )
00912 {
00913   Unexpect aCatch(SALOME_SalomeException);
00914   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::CreateMesh" );
00915   // create mesh
00916   SMESH::SMESH_Mesh_var mesh = this->createMesh();
00917 
00918   // publish mesh in the study
00919   if ( CanPublishInStudy( mesh ) ) {
00920     SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder();
00921     aStudyBuilder->NewCommand();  // There is a transaction
00922     SALOMEDS::SObject_var aSO = PublishMesh( myCurrentStudy, mesh.in() );
00923     aStudyBuilder->CommitCommand();
00924     if ( !aSO->_is_nil() ) {
00925       // Update Python script
00926       TPythonDump() << aSO << " = " << this << ".CreateEmptyMesh()";
00927     }
00928   }
00929 
00930   return mesh._retn();
00931 }
00932 
00933 //=============================================================================
00939 //=============================================================================
00940 
00941 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMeshesFromUNV( const char* theFileName )
00942   throw ( SALOME::SALOME_Exception )
00943 {
00944   Unexpect aCatch(SALOME_SalomeException);
00945   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::CreateMeshesFromUNV" );
00946 
00947   SMESH::SMESH_Mesh_var aMesh = createMesh();
00948   string aFileName;
00949   // publish mesh in the study
00950   if ( CanPublishInStudy( aMesh ) ) {
00951     SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder();
00952     aStudyBuilder->NewCommand();  // There is a transaction
00953     SALOMEDS::SObject_var aSO = PublishMesh( myCurrentStudy, aMesh.in(), aFileName.c_str() );
00954     aStudyBuilder->CommitCommand();
00955     if ( !aSO->_is_nil() ) {
00956       // Update Python script
00957       TPythonDump() << aSO << " = smeshgen.CreateMeshesFromUNV(r'" << theFileName << "')";
00958     }
00959   }
00960 
00961   SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
00962   ASSERT( aServant );
00963   aServant->ImportUNVFile( theFileName );
00964 
00965   // Dump creation of groups
00966   SMESH::ListOfGroups_var groups = aServant->GetGroups();
00967 
00968   aServant->GetImpl().GetMeshDS()->Modified();
00969   return aMesh._retn();
00970 }
00971 
00972 //=============================================================================
00978 //=============================================================================
00979 
00980 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromMEDorSAUV( const char* theFileName,
00981                                                            SMESH::DriverMED_ReadStatus& theStatus,
00982                                                            const char* theCommandNameForPython,
00983                                                            const char* theFileNameForPython)
00984 {
00985   // Retrieve mesh names from the file
00986   DriverMED_R_SMESHDS_Mesh myReader;
00987   myReader.SetFile( theFileName );
00988   myReader.SetMeshId( -1 );
00989   Driver_Mesh::Status aStatus;
00990   list<string> aNames = myReader.GetMeshNames(aStatus);
00991   SMESH::mesh_array_var aResult = new SMESH::mesh_array();
00992   theStatus = (SMESH::DriverMED_ReadStatus)aStatus;
00993 
00994   { // open a new scope to make aPythonDump die before PythonDump in SMESH_Mesh::GetGroups()
00995 
00996   // Python Dump
00997   TPythonDump aPythonDump;
00998   aPythonDump << "([";
00999 
01000   if (theStatus == SMESH::DRS_OK) {
01001     SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder();
01002     aStudyBuilder->NewCommand();  // There is a transaction
01003     aResult->length( aNames.size() );
01004     int i = 0;
01005 
01006     // Iterate through all meshes and create mesh objects
01007     for ( list<string>::iterator it = aNames.begin(); it != aNames.end(); it++ ) {
01008       // Python Dump
01009       if (i > 0) aPythonDump << ", ";
01010 
01011       // create mesh
01012       SMESH::SMESH_Mesh_var mesh = createMesh();
01013 
01014       // publish mesh in the study
01015       SALOMEDS::SObject_var aSO;
01016       if ( CanPublishInStudy( mesh ) )
01017         aSO = PublishMesh( myCurrentStudy, mesh.in(), (*it).c_str() );
01018       if ( !aSO->_is_nil() ) {
01019         // Python Dump
01020         aPythonDump << aSO;
01021       } else {
01022         // Python Dump
01023         aPythonDump << "mesh_" << i;
01024       }
01025 
01026       // Read mesh data (groups are published automatically by ImportMEDFile())
01027       SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
01028       ASSERT( meshServant );
01029       SMESH::DriverMED_ReadStatus status1 =
01030         meshServant->ImportMEDFile( theFileName, (*it).c_str() );
01031       if (status1 > theStatus)
01032         theStatus = status1;
01033 
01034       aResult[i++] = SMESH::SMESH_Mesh::_duplicate( mesh );
01035       meshServant->GetImpl().GetMeshDS()->Modified();
01036     }
01037     aStudyBuilder->CommitCommand();
01038   }
01039 
01040   // Update Python script
01041   aPythonDump << "], status) = " << this << "." << theCommandNameForPython << "(r'" << theFileNameForPython << "')";
01042   }
01043   // Dump creation of groups
01044   for ( int i = 0; i < aResult->length(); ++i )
01045     SMESH::ListOfGroups_var groups = aResult[ i ]->GetGroups();
01046 
01047   return aResult._retn();
01048 }
01049 
01050 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromMED( const char* theFileName,
01051                                                      SMESH::DriverMED_ReadStatus& theStatus)
01052      throw ( SALOME::SALOME_Exception )
01053 {
01054   Unexpect aCatch(SALOME_SalomeException);
01055   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::CreateMeshFromMED" );
01056   SMESH::mesh_array* result = CreateMeshesFromMEDorSAUV(theFileName, theStatus, "CreateMeshesFromMED", theFileName);
01057   return result;
01058 }
01059 
01060 //=============================================================================
01066 //=============================================================================
01067 
01068 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromSAUV( const char* theFileName,
01069                                                       SMESH::DriverMED_ReadStatus& theStatus)
01070      throw ( SALOME::SALOME_Exception )
01071 {
01072   Unexpect aCatch(SALOME_SalomeException);
01073   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::CreateMeshFromSAUV" );
01074   std::string sauvfilename(theFileName);
01075   std::string medfilename(theFileName);
01076   medfilename += ".med";
01077   std::string cmd;
01078 #ifdef WNT
01079   cmd = "%PYTHONBIN% ";
01080 #else
01081   cmd = "python ";
01082 #endif
01083   cmd += "-c \"";
01084   cmd += "from medutilities import convert ; convert(r'" + sauvfilename + "', 'GIBI', 'MED', 1, r'" + medfilename + "')";
01085   cmd += "\"";
01086   system(cmd.c_str());
01087   SMESH::mesh_array* result = CreateMeshesFromMEDorSAUV(medfilename.c_str(), theStatus, "CreateMeshesFromSAUV", sauvfilename.c_str());
01088 #ifdef WNT
01089   cmd = "%PYTHONBIN% ";
01090 #else
01091   cmd = "python ";
01092 #endif
01093   cmd += "-c \"";
01094   cmd += "from medutilities import my_remove ; my_remove(r'" + medfilename + "')";
01095   cmd += "\"";
01096   system(cmd.c_str());
01097   return result;
01098 }
01099 
01100 //=============================================================================
01106 //=============================================================================
01107 
01108 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMeshesFromSTL( const char* theFileName )
01109   throw ( SALOME::SALOME_Exception )
01110 {
01111   Unexpect aCatch(SALOME_SalomeException);
01112   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::CreateMeshesFromSTL" );
01113 
01114   SMESH::SMESH_Mesh_var aMesh = createMesh();
01115   string aFileName;
01116   // publish mesh in the study
01117   if ( CanPublishInStudy( aMesh ) ) {
01118     SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder();
01119     aStudyBuilder->NewCommand();  // There is a transaction
01120     SALOMEDS::SObject_var aSO = PublishInStudy
01121       ( myCurrentStudy, SALOMEDS::SObject::_nil(), aMesh.in(), aFileName.c_str() );
01122     aStudyBuilder->CommitCommand();
01123     if ( !aSO->_is_nil() ) {
01124       // Update Python script
01125       TPythonDump() << aSO << " = " << this << ".CreateMeshesFromSTL(r'" << theFileName << "')";
01126     }
01127   }
01128 
01129   SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
01130   ASSERT( aServant );
01131   aServant->ImportSTLFile( theFileName );
01132   aServant->GetImpl().GetMeshDS()->Modified();
01133   return aMesh._retn();
01134 }
01135 
01136 //================================================================================
01140 //================================================================================
01141 
01142 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromCGNS( const char* theFileName,
01143                                                       SMESH::DriverMED_ReadStatus& theStatus)
01144   throw ( SALOME::SALOME_Exception )
01145 {
01146   Unexpect aCatch(SALOME_SalomeException);
01147 
01148   SMESH::mesh_array_var aResult = new SMESH::mesh_array();
01149 
01150 #ifdef WITH_CGNS
01151   // Retrieve nb meshes from the file
01152   DriverCGNS_Read myReader;
01153   myReader.SetFile( theFileName );
01154   Driver_Mesh::Status aStatus;
01155   int nbMeshes = myReader.GetNbMeshes(aStatus);
01156   theStatus = (SMESH::DriverMED_ReadStatus)aStatus;
01157 
01158   aResult->length( nbMeshes );
01159 
01160   { // open a new scope to make aPythonDump die before PythonDump in SMESH_Mesh::GetGroups()
01161 
01162     // Python Dump
01163     TPythonDump aPythonDump;
01164     aPythonDump << "([";
01165 
01166     if (theStatus == SMESH::DRS_OK)
01167     {
01168       SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder();
01169       aStudyBuilder->NewCommand();  // There is a transaction
01170 
01171       int i = 0;
01172 
01173       // Iterate through all meshes and create mesh objects
01174       for ( ; i < nbMeshes; ++i )
01175       {
01176         // Python Dump
01177         if (i > 0) aPythonDump << ", ";
01178 
01179         // create mesh
01180         SMESH::SMESH_Mesh_var mesh = createMesh();
01181         aResult[i] = SMESH::SMESH_Mesh::_duplicate( mesh );
01182 
01183         // Read mesh data (groups are published automatically by ImportMEDFile())
01184         SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
01185         ASSERT( meshServant );
01186         string meshName;
01187         SMESH::DriverMED_ReadStatus status1 =
01188           meshServant->ImportCGNSFile( theFileName, i, meshName );
01189         if (status1 > theStatus)
01190           theStatus = status1;
01191 
01192         meshServant->GetImpl().GetMeshDS()->Modified();
01193         // publish mesh in the study
01194         SALOMEDS::SObject_var aSO;
01195         if ( CanPublishInStudy( mesh ) )
01196           aSO = PublishMesh( myCurrentStudy, mesh.in(), meshName.c_str() );
01197 
01198         // Python Dump
01199         if ( !aSO->_is_nil() )
01200           aPythonDump << aSO;
01201         else
01202           aPythonDump << "mesh_" << i;
01203       }
01204       aStudyBuilder->CommitCommand();
01205     }
01206 
01207     aPythonDump << "], status) = " << this << ".CreateMeshesFromCGNS(r'" << theFileName << "')";
01208   }
01209   // Dump creation of groups
01210   for ( int i = 0; i < aResult->length(); ++i )
01211     SMESH::ListOfGroups_var groups = aResult[ i ]->GetGroups();
01212 #else
01213   THROW_SALOME_CORBA_EXCEPTION("CGNS library is unavailable", SALOME::INTERNAL_ERROR);
01214 #endif
01215 
01216   return aResult._retn();
01217 }
01218 
01219 //=============================================================================
01225 //=============================================================================
01226 
01227 CORBA::Boolean SMESH_Gen_i::IsReadyToCompute( SMESH::SMESH_Mesh_ptr theMesh,
01228                                               GEOM::GEOM_Object_ptr theShapeObject )
01229   throw ( SALOME::SALOME_Exception )
01230 {
01231   Unexpect aCatch(SALOME_SalomeException);
01232   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::IsReadyToCompute" );
01233 
01234   if ( CORBA::is_nil( theShapeObject ) )
01235     THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
01236                                   SALOME::BAD_PARAM );
01237 
01238   if ( CORBA::is_nil( theMesh ) )
01239     THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
01240                                   SALOME::BAD_PARAM );
01241 
01242   try {
01243     // get mesh servant
01244     SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
01245     ASSERT( meshServant );
01246     if ( meshServant ) {
01247       // get local TopoDS_Shape
01248       TopoDS_Shape myLocShape = GeomObjectToShape( theShapeObject );
01249       // call implementation
01250       ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
01251       return myGen.CheckAlgoState( myLocMesh, myLocShape );
01252     }
01253   }
01254   catch ( SALOME_Exception& S_ex ) {
01255     INFOS( "catch exception "<< S_ex.what() );
01256   }
01257   return false;
01258 }
01259 
01260 //================================================================================
01264 //================================================================================
01265 
01266 SALOMEDS::SObject_ptr SMESH_Gen_i::GetAlgoSO(const ::SMESH_Algo* algo)
01267 {
01268   if ( algo ) {
01269     if ( !myCurrentStudy->_is_nil() ) {
01270       // find algo in the study
01271       SALOMEDS::SComponent_var father = SALOMEDS::SComponent::_narrow
01272         ( myCurrentStudy->FindComponent( ComponentDataType() ) );
01273       if ( !father->_is_nil() ) {
01274         SALOMEDS::ChildIterator_var itBig = myCurrentStudy->NewChildIterator( father );
01275         for ( ; itBig->More(); itBig->Next() ) {
01276           SALOMEDS::SObject_var gotBranch = itBig->Value();
01277           if ( gotBranch->Tag() == GetAlgorithmsRootTag() ) {
01278             SALOMEDS::ChildIterator_var algoIt = myCurrentStudy->NewChildIterator( gotBranch );
01279             for ( ; algoIt->More(); algoIt->Next() ) {
01280               SALOMEDS::SObject_var algoSO = algoIt->Value();
01281               CORBA::Object_var     algoIOR = SObjectToObject( algoSO );
01282               if ( !CORBA::is_nil( algoIOR )) {
01283                 SMESH_Hypothesis_i* impl = SMESH::DownCast<SMESH_Hypothesis_i*>( algoIOR );
01284                 if ( impl && impl->GetImpl() == algo )
01285                   return algoSO._retn();
01286               }
01287             } // loop on algo SO's
01288             break;
01289           } // if algo tag
01290         } // SMESH component iterator
01291       }
01292     }
01293   }
01294   return SALOMEDS::SObject::_nil();
01295 }
01296 
01297 //================================================================================
01301 //================================================================================
01302 
01303 SMESH::compute_error_array* SMESH_Gen_i::GetComputeErrors( SMESH::SMESH_Mesh_ptr theMesh,
01304                                                            GEOM::GEOM_Object_ptr theSubObject )
01305   throw ( SALOME::SALOME_Exception )
01306 {
01307   Unexpect aCatch(SALOME_SalomeException);
01308   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetComputeErrors()" );
01309 
01310   if ( CORBA::is_nil( theSubObject ) && theMesh->HasShapeToMesh())
01311     THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
01312 
01313   if ( CORBA::is_nil( theMesh ) )
01314     THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
01315 
01316   SMESH::compute_error_array_var error_array = new SMESH::compute_error_array;
01317   try {
01318     if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
01319     {
01320       TopoDS_Shape shape;
01321       if(theMesh->HasShapeToMesh())
01322         shape = GeomObjectToShape( theSubObject );
01323       else
01324         shape = SMESH_Mesh::PseudoShape();
01325 
01326       ::SMESH_Mesh& mesh = meshServant->GetImpl();
01327 
01328       error_array->length( mesh.GetMeshDS()->MaxShapeIndex() );
01329       int nbErr = 0;
01330 
01331       SMESH_subMesh *sm = mesh.GetSubMesh(shape);
01332       const bool includeSelf = true, complexShapeFirst = true;
01333       SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(includeSelf,
01334                                                                complexShapeFirst);
01335       while ( smIt->more() )
01336       {
01337         sm = smIt->next();
01338         if ( sm->GetSubShape().ShapeType() == TopAbs_VERTEX )
01339           break;
01340         SMESH_ComputeErrorPtr error = sm->GetComputeError();
01341         if ( error && !error->IsOK() && error->myAlgo )
01342         {
01343           SMESH::ComputeError & errStruct = error_array[ nbErr++ ];
01344           errStruct.code       = -( error->myName < 0 ? error->myName + 1: error->myName ); // -1 -> 0
01345           errStruct.comment    = error->myComment.c_str();
01346           errStruct.subShapeID = sm->GetId();
01347           SALOMEDS::SObject_var algoSO = GetAlgoSO( error->myAlgo );
01348           if ( !algoSO->_is_nil() )
01349             errStruct.algoName = algoSO->GetName();
01350           else
01351             errStruct.algoName = error->myAlgo->GetName();
01352           errStruct.hasBadMesh = !error->myBadElements.empty();
01353         }
01354       }
01355       error_array->length( nbErr );
01356     }
01357   }
01358   catch ( SALOME_Exception& S_ex ) {
01359     INFOS( "catch exception "<< S_ex.what() );
01360   }
01361 
01362   return error_array._retn();
01363 }
01364 
01365 //
01366 //================================================================================
01370 //================================================================================
01371 
01372 SMESH::MeshPreviewStruct*
01373 SMESH_Gen_i::GetBadInputElements( SMESH::SMESH_Mesh_ptr theMesh,
01374                                   CORBA::Short          theSubShapeID )
01375   throw ( SALOME::SALOME_Exception )
01376 {
01377   Unexpect aCatch(SALOME_SalomeException);
01378   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetBadInputElements()" );
01379 
01380   if ( CORBA::is_nil( theMesh ) )
01381     THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
01382 
01383   SMESH::MeshPreviewStruct_var result = new SMESH::MeshPreviewStruct;
01384   try {
01385     // mesh servant
01386     if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
01387     {
01388       // mesh implementation
01389       ::SMESH_Mesh& mesh = meshServant->GetImpl();
01390       // submesh by subshape id
01391       if ( SMESH_subMesh * sm = mesh.GetSubMeshContaining( theSubShapeID ))
01392       {
01393         // compute error
01394         SMESH_ComputeErrorPtr error = sm->GetComputeError();
01395         if ( error && !error->myBadElements.empty())
01396         {
01397           typedef map<const SMDS_MeshElement*, int > TNode2LocalIDMap;
01398           typedef TNode2LocalIDMap::iterator         TNodeLocalID;
01399 
01400           // get nodes of elements and count elements
01401           TNode2LocalIDMap mapNode2LocalID;
01402           list< TNodeLocalID > connectivity;
01403           int i, nbElements = 0, nbConnNodes = 0;
01404 
01405           list<const SMDS_MeshElement*>::iterator elemIt  = error->myBadElements.begin();
01406           list<const SMDS_MeshElement*>::iterator elemEnd = error->myBadElements.end();
01407           for ( ; elemIt != elemEnd; ++elemIt, ++nbElements )
01408           {
01409             SMDS_ElemIteratorPtr nIt = (*elemIt)->nodesIterator();
01410             while ( nIt->more() )
01411               connectivity.push_back
01412                 ( mapNode2LocalID.insert( make_pair( nIt->next(), ++nbConnNodes)).first );
01413           }
01414           // fill node coords and assign local ids to the nodes
01415           int nbNodes = mapNode2LocalID.size();
01416           result->nodesXYZ.length( nbNodes );
01417           TNodeLocalID node2ID = mapNode2LocalID.begin();
01418           for ( i = 0; i < nbNodes; ++i, ++node2ID ) {
01419             node2ID->second = i;
01420             const SMDS_MeshNode* node = (const SMDS_MeshNode*) node2ID->first;
01421             result->nodesXYZ[i].x = node->X();
01422             result->nodesXYZ[i].y = node->Y();
01423             result->nodesXYZ[i].z = node->Z();
01424           }
01425           // fill connectivity
01426           result->elementConnectivities.length( nbConnNodes );
01427           list< TNodeLocalID >::iterator connIt = connectivity.begin();
01428           for ( i = 0; i < nbConnNodes; ++i, ++connIt ) {
01429             result->elementConnectivities[i] = (*connIt)->second;
01430           }
01431           // fill element types
01432           result->elementTypes.length( nbElements );
01433           for ( i = 0, elemIt = error->myBadElements.begin(); i <nbElements; ++i, ++elemIt )
01434           {
01435             const SMDS_MeshElement* elem = *elemIt;
01436             result->elementTypes[i].SMDS_ElementType = (SMESH::ElementType) elem->GetType();
01437             result->elementTypes[i].isPoly           = elem->IsPoly();
01438             result->elementTypes[i].nbNodesInElement = elem->NbNodes();
01439           }
01440         }
01441       }
01442     }
01443   }
01444   catch ( SALOME_Exception& S_ex ) {
01445     INFOS( "catch exception "<< S_ex.what() );
01446   }
01447 
01448   return result._retn();
01449 }
01450 
01451 //================================================================================
01458 //================================================================================
01459 
01460 SMESH::algo_error_array* SMESH_Gen_i::GetAlgoState( SMESH::SMESH_Mesh_ptr theMesh,
01461                                                     GEOM::GEOM_Object_ptr theSubObject )
01462       throw ( SALOME::SALOME_Exception )
01463 {
01464   Unexpect aCatch(SALOME_SalomeException);
01465   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetAlgoState()" );
01466 
01467   if ( CORBA::is_nil( theSubObject ) && theMesh->HasShapeToMesh())
01468     THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
01469 
01470   if ( CORBA::is_nil( theMesh ) )
01471     THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
01472 
01473   SMESH::algo_error_array_var error_array = new SMESH::algo_error_array;
01474   try {
01475     SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
01476     ASSERT( meshServant );
01477     if ( meshServant ) {
01478       TopoDS_Shape myLocShape;
01479       if(theMesh->HasShapeToMesh())
01480         myLocShape = GeomObjectToShape( theSubObject );
01481       else
01482         myLocShape = SMESH_Mesh::PseudoShape();
01483 
01484       ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
01485       list< ::SMESH_Gen::TAlgoStateError > error_list;
01486       list< ::SMESH_Gen::TAlgoStateError >::iterator error;
01487       // call ::SMESH_Gen::GetAlgoState()
01488       myGen.GetAlgoState( myLocMesh, myLocShape, error_list );
01489       error_array->length( error_list.size() );
01490       int i = 0;
01491       for ( error = error_list.begin(); error != error_list.end(); ++error )
01492       {
01493         // fill AlgoStateError structure
01494         SMESH::AlgoStateError & errStruct = error_array[ i++ ];
01495         errStruct.state        = SMESH_Mesh_i::ConvertHypothesisStatus( error->_name );
01496         errStruct.algoDim      = error->_algoDim;
01497         errStruct.isGlobalAlgo = error->_isGlobalAlgo;
01498         errStruct.algoName     = "";
01499         SALOMEDS::SObject_var algoSO = GetAlgoSO( error->_algo );
01500         if ( !algoSO->_is_nil() )
01501           errStruct.algoName   = algoSO->GetName();
01502       }
01503     }
01504   }
01505   catch ( SALOME_Exception& S_ex ) {
01506     INFOS( "catch exception "<< S_ex.what() );
01507   }
01508   return error_array._retn();
01509 }
01510 
01511 //=============================================================================
01517 //=============================================================================
01518 
01519 SMESH::long_array* SMESH_Gen_i::GetSubShapesId( GEOM::GEOM_Object_ptr theMainShapeObject,
01520                                             const SMESH::object_array& theListOfSubShapeObject )
01521      throw ( SALOME::SALOME_Exception )
01522 {
01523   Unexpect aCatch(SALOME_SalomeException);
01524   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetSubShapesId" );
01525 
01526   SMESH::long_array_var shapesId = new SMESH::long_array;
01527   set<int> setId;
01528 
01529   if ( CORBA::is_nil( theMainShapeObject ) )
01530     THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
01531                                   SALOME::BAD_PARAM );
01532 
01533   try
01534     {
01535       TopoDS_Shape myMainShape = GeomObjectToShape(theMainShapeObject);
01536       TopTools_IndexedMapOfShape myIndexToShape;
01537       TopExp::MapShapes(myMainShape,myIndexToShape);
01538 
01539       for ( int i = 0; i < theListOfSubShapeObject.length(); i++ )
01540         {
01541           GEOM::GEOM_Object_var aShapeObject
01542             = GEOM::GEOM_Object::_narrow(theListOfSubShapeObject[i]);
01543           if ( CORBA::is_nil( aShapeObject ) )
01544             THROW_SALOME_CORBA_EXCEPTION ("bad shape object reference", \
01545                                         SALOME::BAD_PARAM );
01546 
01547           TopoDS_Shape locShape  = GeomObjectToShape(aShapeObject);
01548           for (TopExp_Explorer exp(locShape,TopAbs_FACE); exp.More(); exp.Next())
01549             {
01550               const TopoDS_Face& F = TopoDS::Face(exp.Current());
01551               setId.insert(myIndexToShape.FindIndex(F));
01552               if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(F));
01553             }
01554           for (TopExp_Explorer exp(locShape,TopAbs_EDGE); exp.More(); exp.Next())
01555             {
01556               const TopoDS_Edge& E = TopoDS::Edge(exp.Current());
01557               setId.insert(myIndexToShape.FindIndex(E));
01558               if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(E));
01559             }
01560           for (TopExp_Explorer exp(locShape,TopAbs_VERTEX); exp.More(); exp.Next())
01561             {
01562               const TopoDS_Vertex& V = TopoDS::Vertex(exp.Current());
01563               setId.insert(myIndexToShape.FindIndex(V));
01564               if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(V));
01565             }
01566         }
01567       shapesId->length(setId.size());
01568       set<int>::iterator iind;
01569       int i=0;
01570       for (iind = setId.begin(); iind != setId.end(); iind++)
01571         {
01572           if(MYDEBUG) SCRUTE((*iind));
01573           shapesId[i] = (*iind);
01574           if(MYDEBUG) SCRUTE(shapesId[i]);
01575           i++;
01576         }
01577     }
01578   catch (SALOME_Exception& S_ex)
01579     {
01580       THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
01581     }
01582 
01583   return shapesId._retn();
01584 }
01585 
01586 //=============================================================================
01592 //=============================================================================
01593 
01594 CORBA::Boolean SMESH_Gen_i::Compute( SMESH::SMESH_Mesh_ptr theMesh,
01595                                      GEOM::GEOM_Object_ptr theShapeObject )
01596      throw ( SALOME::SALOME_Exception )
01597 {
01598   MEMOSTAT;
01599   Unexpect aCatch(SALOME_SalomeException);
01600   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Compute" );
01601 
01602   if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
01603     THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
01604                                   SALOME::BAD_PARAM );
01605 
01606   if ( CORBA::is_nil( theMesh ) )
01607     THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
01608                                   SALOME::BAD_PARAM );
01609 
01610   // Update Python script
01611   TPythonDump() << "isDone = " << this << ".Compute( "
01612                 << theMesh << ", " << theShapeObject << ")";
01613 
01614   try {
01615     // get mesh servant
01616     SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
01617     meshServant->Load();
01618     ASSERT( meshServant );
01619     if ( meshServant ) {
01620       // NPAL16168: "geometrical group edition from a submesh don't modifiy mesh computation"
01621       meshServant->CheckGeomGroupModif();
01622       // get local TopoDS_Shape
01623       TopoDS_Shape myLocShape;
01624       if(theMesh->HasShapeToMesh())
01625         myLocShape = GeomObjectToShape( theShapeObject );
01626       else
01627         myLocShape = SMESH_Mesh::PseudoShape();
01628       // call implementation compute
01629       ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
01630 #ifdef WITH_SMESH_CANCEL_COMPUTE
01631       myGen.PrepareCompute( myLocMesh, myLocShape);
01632 #endif
01633       bool ok = myGen.Compute( myLocMesh, myLocShape);
01634       meshServant->CreateGroupServants(); // algos can create groups (issue 0020918)
01635       myLocMesh.GetMeshDS()->Modified();
01636       return ok;
01637     }
01638   }
01639   catch ( std::bad_alloc ) {
01640     INFOS( "Compute(): lack of memory" );
01641   }
01642   catch ( SALOME_Exception& S_ex ) {
01643     INFOS( "Compute(): catch exception "<< S_ex.what() );
01644   }
01645   catch ( ... ) {
01646     INFOS( "Compute(): unknown exception " );
01647   }
01648   return false;
01649 }
01650 
01651 //=============================================================================
01657 //=============================================================================
01658 
01659 void SMESH_Gen_i::CancelCompute( SMESH::SMESH_Mesh_ptr theMesh,
01660                                  GEOM::GEOM_Object_ptr theShapeObject )
01661 {
01662 #ifdef WITH_SMESH_CANCEL_COMPUTE
01663   SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
01664   ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
01665   TopoDS_Shape myLocShape;
01666   if(theMesh->HasShapeToMesh())
01667     myLocShape = GeomObjectToShape( theShapeObject );
01668   else
01669     myLocShape = SMESH_Mesh::PseudoShape();
01670   myGen.CancelCompute( myLocMesh, myLocShape);
01671 #endif
01672 }
01673 
01674 //=============================================================================
01680 //=============================================================================
01681 
01682 SMESH::MeshPreviewStruct* SMESH_Gen_i::Precompute( SMESH::SMESH_Mesh_ptr theMesh,
01683                                                    GEOM::GEOM_Object_ptr theShapeObject,
01684                                                    SMESH::Dimension      theDimension,
01685                                                    SMESH::long_array&    theShapesId)
01686      throw ( SALOME::SALOME_Exception )
01687 {
01688   Unexpect aCatch(SALOME_SalomeException);
01689   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Precompute" );
01690 
01691   if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
01692     THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
01693                                   SALOME::BAD_PARAM );
01694 
01695   if ( CORBA::is_nil( theMesh ) )
01696     THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
01697                                   SALOME::BAD_PARAM );
01698 
01699   SMESH::MeshPreviewStruct_var result = new SMESH::MeshPreviewStruct;
01700   try {
01701     // get mesh servant
01702     SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
01703     meshServant->Load();
01704     ASSERT( meshServant );
01705     if ( meshServant ) {
01706       // NPAL16168: "geometrical group edition from a submesh don't modifiy mesh computation"
01707       meshServant->CheckGeomGroupModif();
01708       // get local TopoDS_Shape
01709       TopoDS_Shape myLocShape;
01710       if(theMesh->HasShapeToMesh())
01711         myLocShape = GeomObjectToShape( theShapeObject );
01712       else
01713         return result._retn();;
01714 
01715       // call implementation compute
01716       ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
01717       TSetOfInt shapeIds;
01718       ::MeshDimension aDim = (MeshDimension)theDimension;
01719       if ( myGen.Compute( myLocMesh, myLocShape, false, aDim, &shapeIds ) )
01720       {
01721         int nbShapeId = shapeIds.size();
01722         theShapesId.length( nbShapeId );
01723         // iterates on shapes and collect mesh entities into mesh preview
01724         TSetOfInt::const_iterator idIt = shapeIds.begin();
01725         TSetOfInt::const_iterator idEnd = shapeIds.end();
01726         std::map< int, int > mapOfShIdNb;
01727         std::set< SMESH_TLink > setOfEdge;
01728         std::list< SMDSAbs_ElementType > listOfElemType;
01729         typedef map<const SMDS_MeshElement*, int > TNode2LocalIDMap;
01730         typedef TNode2LocalIDMap::iterator         TNodeLocalID;
01731         TNode2LocalIDMap mapNode2LocalID;
01732         list< TNodeLocalID > connectivity;
01733         int i, nbConnNodes = 0;
01734         std::set< const SMESH_subMesh* > setOfVSubMesh;
01735         // iterates on shapes
01736         for ( ; idIt != idEnd; idIt++ )
01737         {
01738           if ( mapOfShIdNb.find( *idIt ) != mapOfShIdNb.end() )
01739             continue;
01740           SMESH_subMesh* sm = myLocMesh.GetSubMeshContaining(*idIt);
01741           if ( !sm || !sm->IsMeshComputed() )
01742             continue;
01743 
01744           const TopoDS_Shape& aSh = sm->GetSubShape();
01745           const int shDim = myGen.GetShapeDim( aSh );
01746           if ( shDim < 1 || shDim > theDimension )
01747             continue;
01748 
01749           mapOfShIdNb[ *idIt ] = 0;
01750           theShapesId[ mapOfShIdNb.size() - 1 ] = *idIt;
01751 
01752           SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
01753           if ( !smDS ) continue;
01754 
01755           if ( theDimension == SMESH::DIM_2D )
01756           {
01757             SMDS_ElemIteratorPtr faceIt = smDS->GetElements();
01758             while ( faceIt->more() )
01759             {
01760               const SMDS_MeshElement* face = faceIt->next();
01761               int aNbNode = face->NbNodes();
01762               if ( aNbNode > 4 )
01763                 aNbNode /= 2; // do not take into account additional middle nodes
01764 
01765               SMDS_MeshNode* node1 = (SMDS_MeshNode*)face->GetNode( 0 );
01766               for ( int nIndx = 0; nIndx < aNbNode; nIndx++ )
01767               {
01768                 SMDS_MeshNode* node2 = (SMDS_MeshNode*)face->GetNode( nIndx+1 < aNbNode ? nIndx+1 : 0 );
01769                 if ( setOfEdge.insert( SMESH_TLink ( node1, node2 ) ).second )
01770                 {
01771                   listOfElemType.push_back( SMDSAbs_Edge );
01772                   connectivity.push_back
01773                     ( mapNode2LocalID.insert( make_pair( node1, ++nbConnNodes)).first );
01774                   connectivity.push_back
01775                     ( mapNode2LocalID.insert( make_pair( node2, ++nbConnNodes)).first );
01776                 }
01777                 node1 = node2;
01778               }
01779             }
01780           }
01781           else if ( theDimension == SMESH::DIM_1D )
01782           {
01783             SMDS_NodeIteratorPtr nodeIt = smDS->GetNodes();
01784             while ( nodeIt->more() )
01785             {
01786               listOfElemType.push_back( SMDSAbs_Node );
01787               connectivity.push_back
01788                 ( mapNode2LocalID.insert( make_pair( nodeIt->next(), ++nbConnNodes)).first );
01789             }
01790             // add corner nodes by first vertex from edge
01791             SMESH_subMeshIteratorPtr edgeSmIt =
01792               sm->getDependsOnIterator(/*includeSelf*/false,
01793                                        /*complexShapeFirst*/false);
01794             while ( edgeSmIt->more() )
01795             {
01796               SMESH_subMesh* vertexSM = edgeSmIt->next();
01797               // check that vertex is not already treated
01798               if ( !setOfVSubMesh.insert( vertexSM ).second )
01799                 continue;
01800               if ( vertexSM->GetSubShape().ShapeType() != TopAbs_VERTEX )
01801                 continue;
01802 
01803               const SMESHDS_SubMesh* vertexSmDS = vertexSM->GetSubMeshDS();
01804               SMDS_NodeIteratorPtr nodeIt = vertexSmDS->GetNodes();
01805               while ( nodeIt->more() )
01806               {
01807                 listOfElemType.push_back( SMDSAbs_Node );
01808                 connectivity.push_back
01809                   ( mapNode2LocalID.insert( make_pair( nodeIt->next(), ++nbConnNodes)).first );
01810               }
01811             }
01812           }
01813         }
01814 
01815         // fill node coords and assign local ids to the nodes
01816         int nbNodes = mapNode2LocalID.size();
01817         result->nodesXYZ.length( nbNodes );
01818         TNodeLocalID node2ID = mapNode2LocalID.begin();
01819         for ( i = 0; i < nbNodes; ++i, ++node2ID ) {
01820           node2ID->second = i;
01821           const SMDS_MeshNode* node = (const SMDS_MeshNode*) node2ID->first;
01822           result->nodesXYZ[i].x = node->X();
01823           result->nodesXYZ[i].y = node->Y();
01824           result->nodesXYZ[i].z = node->Z();
01825         }
01826         // fill connectivity
01827         result->elementConnectivities.length( nbConnNodes );
01828         list< TNodeLocalID >::iterator connIt = connectivity.begin();
01829         for ( i = 0; i < nbConnNodes; ++i, ++connIt ) {
01830           result->elementConnectivities[i] = (*connIt)->second;
01831         }
01832 
01833         // fill element types
01834         result->elementTypes.length( listOfElemType.size() );
01835         std::list< SMDSAbs_ElementType >::const_iterator typeIt = listOfElemType.begin();
01836         std::list< SMDSAbs_ElementType >::const_iterator typeEnd = listOfElemType.end();
01837         for ( i = 0; typeIt != typeEnd; ++i, ++typeIt )
01838         {
01839           SMDSAbs_ElementType elemType = *typeIt;
01840           result->elementTypes[i].SMDS_ElementType = (SMESH::ElementType)elemType;
01841           result->elementTypes[i].isPoly           = false;
01842           result->elementTypes[i].nbNodesInElement = elemType == SMDSAbs_Edge ? 2 : 1;
01843         }
01844 
01845         // correct number of shapes
01846         theShapesId.length( mapOfShIdNb.size() );
01847       }
01848     }
01849   }
01850   catch ( std::bad_alloc ) {
01851     INFOS( "Precompute(): lack of memory" );
01852   }
01853   catch ( SALOME_Exception& S_ex ) {
01854     INFOS( "Precompute(): catch exception "<< S_ex.what() );
01855   }
01856   catch ( ... ) {
01857     INFOS( "Precompute(): unknown exception " );
01858   }
01859   return result._retn();
01860 }
01861 
01862 
01863 //=============================================================================
01869 //=============================================================================
01870 
01871 SMESH::long_array* SMESH_Gen_i::Evaluate(SMESH::SMESH_Mesh_ptr theMesh,
01872                                          GEOM::GEOM_Object_ptr theShapeObject)
01873 //                                     SMESH::long_array& theNbElems)
01874      throw ( SALOME::SALOME_Exception )
01875 {
01876   Unexpect aCatch(SALOME_SalomeException);
01877   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Evaluate" );
01878 
01879   if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
01880     THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
01881                                   SALOME::BAD_PARAM );
01882 
01883   if ( CORBA::is_nil( theMesh ) )
01884     THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
01885                                   SALOME::BAD_PARAM );
01886 
01887   SMESH::long_array_var nbels = new SMESH::long_array;
01888   nbels->length(SMESH::Entity_Last);
01889   int i = SMESH::Entity_Node;
01890   for (; i < SMESH::Entity_Last; i++)
01891     nbels[i] = 0;
01892 
01893   // Update Python script
01894   TPythonDump() << "theNbElems = " << this << ".Evaluate( "
01895                 << theMesh << ", " << theShapeObject << ")";
01896 
01897   try {
01898     // get mesh servant
01899     SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
01900     ASSERT( meshServant );
01901     if ( meshServant ) {
01902       // NPAL16168: "geometrical group edition from a submesh don't modifiy mesh computation"
01903       meshServant->CheckGeomGroupModif();
01904       // get local TopoDS_Shape
01905       TopoDS_Shape myLocShape;
01906       if(theMesh->HasShapeToMesh())
01907         myLocShape = GeomObjectToShape( theShapeObject );
01908       else
01909         myLocShape = SMESH_Mesh::PseudoShape();
01910       // call implementation compute
01911       ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
01912       MapShapeNbElems aResMap;
01913       /*CORBA::Boolean ret =*/ myGen.Evaluate( myLocMesh, myLocShape, aResMap);
01914       MapShapeNbElemsItr anIt = aResMap.begin();
01915       for(; anIt!=aResMap.end(); anIt++) {
01916         const vector<int>& aVec = (*anIt).second;
01917         for(i = SMESH::Entity_Node; i < aVec.size(); i++) {
01918           int nbElem = aVec[i];
01919           if ( nbElem < 0 ) // algo failed, check that it has reported a message
01920           {
01921             SMESH_subMesh* sm = anIt->first;
01922             SMESH_ComputeErrorPtr& error = sm->GetComputeError();
01923             const SMESH_Algo* algo = myGen.GetAlgo( myLocMesh, sm->GetSubShape());
01924             if ( (algo && !error.get()) || error->IsOK() )
01925               error.reset( new SMESH_ComputeError( COMPERR_ALGO_FAILED,"Failed to evaluate",algo));
01926           }
01927           else
01928           {
01929             nbels[i] += aVec[i];
01930           }
01931         }
01932       }
01933       return nbels._retn();
01934     }
01935   }
01936   catch ( std::bad_alloc ) {
01937     INFOS( "Evaluate(): lack of memory" );
01938   }
01939   catch ( SALOME_Exception& S_ex ) {
01940     INFOS( "Evaluate(): catch exception "<< S_ex.what() );
01941   }
01942   catch ( ... ) {
01943     INFOS( "Evaluate(): unknown exception " );
01944   }
01945 
01946   return nbels._retn();
01947 }
01948 
01949 //================================================================================
01957 //================================================================================
01958 
01959 GEOM::GEOM_Object_ptr
01960 SMESH_Gen_i::GetGeometryByMeshElement( SMESH::SMESH_Mesh_ptr  theMesh,
01961                                        CORBA::Long            theElementID,
01962                                        const char*            theGeomName)
01963   throw ( SALOME::SALOME_Exception )
01964 {
01965   Unexpect aCatch(SALOME_SalomeException);
01966 
01967   GEOM::GEOM_Object_var geom = FindGeometryByMeshElement(theMesh, theElementID);
01968   if ( !geom->_is_nil() ) {
01969     GEOM::GEOM_Object_var mainShape = theMesh->GetShapeToMesh();
01970     GEOM::GEOM_Gen_ptr    geomGen   = GetGeomEngine();
01971 
01972     // try to find the corresponding SObject
01973     SALOMEDS::SObject_var SObj = ObjectToSObject( myCurrentStudy, geom.in() );
01974     if ( SObj->_is_nil() ) // submesh can be not found even if published
01975     {
01976       // try to find published submesh
01977       GEOM::ListOfLong_var list = geom->GetSubShapeIndices();
01978       if ( !geom->IsMainShape() && list->length() == 1 ) {
01979         SALOMEDS::SObject_var mainSO = ObjectToSObject( myCurrentStudy, mainShape );
01980         SALOMEDS::ChildIterator_var it;
01981         if ( !mainSO->_is_nil() )
01982           it = myCurrentStudy->NewChildIterator( mainSO );
01983         if ( !it->_is_nil() ) {
01984           for ( it->InitEx(true); SObj->_is_nil() && it->More(); it->Next() ) {
01985             GEOM::GEOM_Object_var subGeom =
01986               GEOM::GEOM_Object::_narrow( SObjectToObject( it->Value() ));
01987             if ( !subGeom->_is_nil() ) {
01988               GEOM::ListOfLong_var subList = subGeom->GetSubShapeIndices();
01989               if ( subList->length() == 1 && list[0] == subList[0] ) {
01990                 SObj = it->Value();
01991                 geom = subGeom;
01992               }
01993             }
01994           }
01995         }
01996       }
01997     }
01998     if ( SObj->_is_nil() ) // publish a new subshape
01999       SObj = geomGen->AddInStudy( myCurrentStudy, geom, theGeomName, mainShape );
02000 
02001     // return only published geometry
02002     if ( !SObj->_is_nil() )
02003       return geom._retn();
02004   }
02005   return GEOM::GEOM_Object::_nil();
02006 }
02007 
02008 //================================================================================
02015 //================================================================================
02016 
02017 GEOM::GEOM_Object_ptr
02018 SMESH_Gen_i::FindGeometryByMeshElement( SMESH::SMESH_Mesh_ptr  theMesh,
02019                                         CORBA::Long            theElementID)
02020   throw ( SALOME::SALOME_Exception )
02021 {
02022   Unexpect aCatch(SALOME_SalomeException);
02023   if ( CORBA::is_nil( theMesh ) )
02024     THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference", SALOME::BAD_PARAM );
02025 
02026   GEOM::GEOM_Object_var mainShape = theMesh->GetShapeToMesh();
02027   GEOM::GEOM_Gen_ptr    geomGen   = GetGeomEngine();
02028 
02029   // get a core mesh DS
02030   SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
02031   if ( meshServant && !geomGen->_is_nil() && !mainShape->_is_nil() )
02032   {
02033     ::SMESH_Mesh & mesh = meshServant->GetImpl();
02034     SMESHDS_Mesh* meshDS = mesh.GetMeshDS();
02035     // find the element in mesh
02036     if ( const SMDS_MeshElement * elem = meshDS->FindElement( theElementID ) ) {
02037       // find a shape id by the element
02038       if ( int shapeID = ::SMESH_MeshEditor( &mesh ).FindShape( elem )) {
02039         // get a geom object by the shape id
02040         GEOM::GEOM_Object_var geom = ShapeToGeomObject( meshDS->IndexToShape( shapeID ));
02041         if ( geom->_is_nil() ) {
02042           // try to find a published sub-shape
02043           SALOMEDS::SObject_var mainSO = ObjectToSObject( myCurrentStudy, mainShape );
02044           SALOMEDS::ChildIterator_var it;
02045           if ( !mainSO->_is_nil() )
02046             it = myCurrentStudy->NewChildIterator( mainSO );
02047           if ( !it->_is_nil() ) {
02048             for ( it->InitEx(true); it->More(); it->Next() ) {
02049               GEOM::GEOM_Object_var subGeom =
02050                 GEOM::GEOM_Object::_narrow( SObjectToObject( it->Value() ));
02051               if ( !subGeom->_is_nil() ) {
02052                 GEOM::ListOfLong_var subList = subGeom->GetSubShapeIndices();
02053                 if ( subList->length() == 1 && shapeID == subList[0] ) {
02054                   geom = subGeom;
02055                   break;
02056                 }
02057               }
02058             }
02059           }
02060         }
02061         if ( geom->_is_nil() ) {
02062           // explode
02063           GEOM::GEOM_IShapesOperations_var op =
02064             geomGen->GetIShapesOperations( GetCurrentStudyID() );
02065           if ( !op->_is_nil() )
02066             geom = op->GetSubShape( mainShape, shapeID );
02067         }
02068         if ( !geom->_is_nil() ) {
02069           GeomObjectToShape( geom ); // let geom client remember the found shape
02070           return geom._retn();
02071         }
02072       }
02073     }
02074   }
02075   return GEOM::GEOM_Object::_nil();
02076 }
02077 
02078 //================================================================================
02084 //================================================================================
02085 
02086 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::Concatenate(const SMESH::mesh_array& theMeshesArray,
02087                                                CORBA::Boolean           theUniteIdenticalGroups,
02088                                                CORBA::Boolean           theMergeNodesAndElements,
02089                                                CORBA::Double            theMergeTolerance)
02090   throw ( SALOME::SALOME_Exception )
02091 {
02092   return ConcatenateCommon(theMeshesArray,
02093                            theUniteIdenticalGroups,
02094                            theMergeNodesAndElements,
02095                            theMergeTolerance,
02096                            false);
02097 }
02098 
02099 //================================================================================
02106 //================================================================================
02107 
02108 SMESH::SMESH_Mesh_ptr
02109 SMESH_Gen_i::ConcatenateWithGroups(const SMESH::mesh_array& theMeshesArray,
02110                                    CORBA::Boolean           theUniteIdenticalGroups,
02111                                    CORBA::Boolean           theMergeNodesAndElements,
02112                                    CORBA::Double            theMergeTolerance)
02113   throw ( SALOME::SALOME_Exception )
02114 {
02115   return ConcatenateCommon(theMeshesArray,
02116                            theUniteIdenticalGroups,
02117                            theMergeNodesAndElements,
02118                            theMergeTolerance,
02119                            true);
02120 }
02121 
02122 //================================================================================
02128 //================================================================================
02129 
02130 SMESH::SMESH_Mesh_ptr
02131 SMESH_Gen_i::ConcatenateCommon(const SMESH::mesh_array& theMeshesArray,
02132                                CORBA::Boolean           theUniteIdenticalGroups,
02133                                CORBA::Boolean           theMergeNodesAndElements,
02134                                CORBA::Double            theMergeTolerance,
02135                                CORBA::Boolean           theCommonGroups)
02136   throw ( SALOME::SALOME_Exception )
02137 {
02138   typedef map<int, int> TIDsMap;
02139   typedef list<SMESH::SMESH_Group_var> TListOfNewGroups;
02140   typedef map< pair<string, SMESH::ElementType>, TListOfNewGroups > TGroupsMap;
02141   typedef std::set<SMESHDS_GroupBase*> TGroups;
02142 
02143   TPythonDump* pPythonDump = new TPythonDump;
02144   TPythonDump& aPythonDump = *pPythonDump; // prevent dump of called methods
02145 
02146   // create mesh
02147   SMESH::SMESH_Mesh_var aNewMesh = CreateEmptyMesh();
02148 
02149   SMESHDS_Mesh* aNewMeshDS = 0;
02150   if ( !aNewMesh->_is_nil() ) {
02151     SMESH_Mesh_i* aNewImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( aNewMesh ).in() );
02152     if ( aNewImpl ) {
02153       ::SMESH_Mesh& aLocMesh = aNewImpl->GetImpl();
02154       aNewMeshDS = aLocMesh.GetMeshDS();
02155 
02156       TGroupsMap aGroupsMap;
02157       TListOfNewGroups aListOfNewGroups;
02158       SMESH_MeshEditor aNewEditor = ::SMESH_MeshEditor(&aLocMesh);
02159       SMESH::ListOfGroups_var aListOfGroups = new SMESH::ListOfGroups();
02160 
02161       // loop on meshes
02162       for ( int i = 0; i < theMeshesArray.length(); i++) {
02163         SMESH::SMESH_Mesh_var anInitMesh = theMeshesArray[i];
02164         if ( !anInitMesh->_is_nil() ) {
02165           SMESH_Mesh_i* anInitImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( anInitMesh ).in() );
02166           if ( anInitImpl ) {
02167             ::SMESH_Mesh& aInitLocMesh = anInitImpl->GetImpl();
02168             SMESHDS_Mesh* anInitMeshDS = aInitLocMesh.GetMeshDS();
02169 
02170             TIDsMap nodesMap;
02171             TIDsMap elemsMap;
02172 
02173             // loop on elements of mesh
02174             SMDS_ElemIteratorPtr itElems = anInitMeshDS->elementsIterator();
02175             const SMDS_MeshElement* anElem = 0;
02176             const SMDS_MeshElement* aNewElem = 0;
02177             int anElemNbNodes = 0;
02178 
02179             int anNbNodes   = 0;
02180             int anNbEdges   = 0;
02181             int anNbFaces   = 0;
02182             int anNbVolumes = 0;
02183 
02184             SMESH::long_array_var anIDsNodes   = new SMESH::long_array();
02185             SMESH::long_array_var anIDsEdges   = new SMESH::long_array();
02186             SMESH::long_array_var anIDsFaces   = new SMESH::long_array();
02187             SMESH::long_array_var anIDsVolumes = new SMESH::long_array();
02188 
02189             if( theCommonGroups ) {
02190               anIDsNodes->length(   anInitMeshDS->NbNodes()   );
02191               anIDsEdges->length(   anInitMeshDS->NbEdges()   );
02192               anIDsFaces->length(   anInitMeshDS->NbFaces()   );
02193               anIDsVolumes->length( anInitMeshDS->NbVolumes() );
02194             }
02195 
02196             for ( int j = 0; itElems->more(); j++) {
02197               anElem = itElems->next();
02198               SMDSAbs_ElementType anElemType = anElem->GetType();
02199               anElemNbNodes = anElem->NbNodes();
02200               std::vector<const SMDS_MeshNode*> aNodesArray (anElemNbNodes);
02201 
02202               // loop on nodes of element
02203               const SMDS_MeshNode* aNode = 0;
02204               const SMDS_MeshNode* aNewNode = 0;
02205               SMDS_ElemIteratorPtr itNodes = anElem->nodesIterator();
02206 
02207               for ( int k = 0; itNodes->more(); k++) {
02208                 aNode = static_cast<const SMDS_MeshNode*>(itNodes->next());
02209                 if ( nodesMap.find(aNode->GetID()) == nodesMap.end() ) {
02210                   aNewNode = aNewMeshDS->AddNode(aNode->X(), aNode->Y(), aNode->Z());
02211                   nodesMap.insert( make_pair(aNode->GetID(), aNewNode->GetID()) );
02212                   if( theCommonGroups )
02213                     anIDsNodes[anNbNodes++] = aNewNode->GetID();
02214                 }
02215                 else
02216                   aNewNode = aNewMeshDS->FindNode( nodesMap.find(aNode->GetID())->second );
02217                 aNodesArray[k] = aNewNode;
02218               }//nodes loop
02219 
02220               // creates a corresponding element on existent nodes in new mesh
02221               if ( anElem->IsPoly() && anElemType == SMDSAbs_Volume )
02222                 {
02223                   const SMDS_VtkVolume* aVolume =
02224                     dynamic_cast<const SMDS_VtkVolume*> (anElem);
02225                   if ( aVolume ) {
02226                     aNewElem = aNewMeshDS->AddPolyhedralVolume(aNodesArray,
02227                                                                aVolume->GetQuantities());
02228                     elemsMap.insert(make_pair(anElem->GetID(), aNewElem->GetID()));
02229                     if( theCommonGroups )
02230                       anIDsVolumes[anNbVolumes++] = aNewElem->GetID();
02231                   }
02232                 }
02233               else {
02234 
02235                 aNewElem = aNewEditor.AddElement(aNodesArray,
02236                                                  anElemType,
02237                                                  anElem->IsPoly());
02238                 elemsMap.insert(make_pair(anElem->GetID(), aNewElem->GetID()));
02239                 if( theCommonGroups ) {
02240                   if( anElemType == SMDSAbs_Edge )
02241                     anIDsEdges[anNbEdges++] = aNewElem->GetID();
02242                   else if( anElemType == SMDSAbs_Face )
02243                     anIDsFaces[anNbFaces++] = aNewElem->GetID();
02244                   else if( anElemType == SMDSAbs_Volume )
02245                     anIDsVolumes[anNbVolumes++] = aNewElem->GetID();
02246                 }
02247               }
02248             }//elems loop
02249 
02250             // copy orphan nodes
02251             SMDS_NodeIteratorPtr  itNodes = anInitMeshDS->nodesIterator();
02252             while ( itNodes->more() )
02253             {
02254               const SMDS_MeshNode* aNode = itNodes->next();
02255               if ( aNode->NbInverseElements() == 0 )
02256               {
02257                 const SMDS_MeshNode* aNewNode =
02258                   aNewMeshDS->AddNode(aNode->X(), aNode->Y(), aNode->Z());
02259                 nodesMap.insert( make_pair(aNode->GetID(), aNewNode->GetID()) );
02260                 if( theCommonGroups )
02261                   anIDsNodes[anNbNodes++] = aNewNode->GetID();
02262               }
02263             }
02264 
02265 
02266             aListOfGroups = anInitImpl->GetGroups();
02267             SMESH::SMESH_GroupBase_ptr aGroup;
02268 
02269             // loop on groups of mesh
02270             SMESH::long_array_var anInitIDs = new SMESH::long_array();
02271             SMESH::long_array_var anNewIDs = new SMESH::long_array();
02272             SMESH::SMESH_Group_var aNewGroup;
02273 
02274             SMESH::ElementType aGroupType;
02275             CORBA::String_var aGroupName;
02276             if ( theCommonGroups ) {
02277               for(aGroupType=SMESH::NODE;aGroupType<=SMESH::VOLUME;aGroupType=(SMESH::ElementType)(aGroupType+1)) {
02278                 string str = "Gr";
02279                 SALOMEDS::SObject_var aMeshSObj = ObjectToSObject( myCurrentStudy, anInitMesh );
02280                 if(aMeshSObj)
02281                   str += aMeshSObj->GetName();
02282                 str += "_";
02283 
02284                 int anLen = 0;
02285 
02286                 switch(aGroupType) {
02287                 case SMESH::NODE:
02288                   str += "Nodes";
02289                   anIDsNodes->length(anNbNodes);
02290                   anLen = anNbNodes;
02291                   break;
02292                 case SMESH::EDGE:
02293                   str += "Edges";
02294                   anIDsEdges->length(anNbEdges);
02295                   anLen = anNbEdges;
02296                   break;
02297                 case SMESH::FACE:
02298                   str += "Faces";
02299                   anIDsFaces->length(anNbFaces);
02300                   anLen = anNbFaces;
02301                   break;
02302                 case SMESH::VOLUME:
02303                   str += "Volumes";
02304                   anIDsVolumes->length(anNbVolumes);
02305                   anLen = anNbVolumes;
02306                   break;
02307                 default:
02308                   break;
02309                 }
02310 
02311                 if(anLen) {
02312                   aGroupName = str.c_str();
02313 
02314                   // add a new group in the mesh
02315                   aNewGroup = aNewImpl->CreateGroup(aGroupType, aGroupName);
02316 
02317                   switch(aGroupType) {
02318                   case SMESH::NODE:
02319                     aNewGroup->Add( anIDsNodes );
02320                     break;
02321                   case SMESH::EDGE:
02322                     aNewGroup->Add( anIDsEdges );
02323                     break;
02324                   case SMESH::FACE:
02325                     aNewGroup->Add( anIDsFaces );
02326                     break;
02327                   case SMESH::VOLUME:
02328                     aNewGroup->Add( anIDsVolumes );
02329                     break;
02330                   default:
02331                     break;
02332                   }
02333 
02334                   aListOfNewGroups.clear();
02335                   aListOfNewGroups.push_back(aNewGroup);
02336                   aGroupsMap.insert(make_pair( make_pair(aGroupName, aGroupType), aListOfNewGroups ));
02337                 }
02338               }
02339             }
02340 
02341             // check that current group name and type don't have identical ones in union mesh
02342             for (int i = 0; i < aListOfGroups->length(); i++) {
02343               aGroup = aListOfGroups[i];
02344               aListOfNewGroups.clear();
02345               aGroupType = aGroup->GetType();
02346               aGroupName = aGroup->GetName();
02347 
02348               TGroupsMap::iterator anIter = aGroupsMap.find(make_pair(aGroupName, aGroupType));
02349 
02350               // convert a list of IDs
02351               anInitIDs = aGroup->GetListOfID();
02352               anNewIDs->length(anInitIDs->length());
02353               if ( aGroupType == SMESH::NODE )
02354                 for (int j = 0; j < anInitIDs->length(); j++) {
02355                   anNewIDs[j] = nodesMap.find(anInitIDs[j])->second;
02356                 }
02357               else
02358                 for (int j = 0; j < anInitIDs->length(); j++) {
02359                   anNewIDs[j] = elemsMap.find(anInitIDs[j])->second;
02360                 }
02361 
02362               // check that current group name and type don't have identical ones in union mesh
02363               if ( anIter == aGroupsMap.end() ) {
02364                 // add a new group in the mesh
02365                 aNewGroup = aNewImpl->CreateGroup(aGroupType, aGroupName);
02366                 // add elements into new group
02367                 aNewGroup->Add( anNewIDs );
02368 
02369                 aListOfNewGroups.push_back(aNewGroup);
02370                 aGroupsMap.insert(make_pair( make_pair(aGroupName, aGroupType), aListOfNewGroups ));
02371               }
02372 
02373               else if ( theUniteIdenticalGroups ) {
02374                 // unite identical groups
02375                 TListOfNewGroups& aNewGroups = anIter->second;
02376                 aNewGroups.front()->Add( anNewIDs );
02377               }
02378 
02379               else {
02380                 // rename identical groups
02381                 aNewGroup = aNewImpl->CreateGroup(aGroupType, aGroupName);
02382                 aNewGroup->Add( anNewIDs );
02383 
02384                 TListOfNewGroups& aNewGroups = anIter->second;
02385                 string aNewGroupName;
02386                 if (aNewGroups.size() == 1) {
02387                   aNewGroupName = string(aGroupName) + "_1";
02388                   aNewGroups.front()->SetName(aNewGroupName.c_str());
02389                 }
02390                 char aGroupNum[128];
02391                 sprintf(aGroupNum, "%u", aNewGroups.size()+1);
02392                 aNewGroupName = string(aGroupName) + "_" + string(aGroupNum);
02393                 aNewGroup->SetName(aNewGroupName.c_str());
02394                 aNewGroups.push_back(aNewGroup);
02395               }
02396             }//groups loop
02397           }
02398         }
02399       }//meshes loop
02400 
02401       if (theMergeNodesAndElements) {
02402         // merge nodes
02403         TIDSortedNodeSet aMeshNodes; // no input nodes
02404         SMESH_MeshEditor::TListOfListOfNodes aGroupsOfNodes;
02405         aNewEditor.FindCoincidentNodes( aMeshNodes, theMergeTolerance, aGroupsOfNodes );
02406         aNewEditor.MergeNodes( aGroupsOfNodes );
02407         // merge elements
02408         aNewEditor.MergeEqualElements();
02409       }
02410     }
02411   }
02412 
02413   // Update Python script
02414   aPythonDump << aNewMesh << " = " << this;
02415   if( !theCommonGroups )
02416     aPythonDump << ".Concatenate(";
02417   else
02418     aPythonDump << ".ConcatenateWithGroups(";
02419   aPythonDump << "[";
02420   for ( int i = 0; i < theMeshesArray.length(); i++) {
02421     if (i > 0) aPythonDump << ", ";
02422     aPythonDump << theMeshesArray[i];
02423   }
02424   aPythonDump << "], ";
02425   aPythonDump << theUniteIdenticalGroups << ", "
02426               << theMergeNodesAndElements << ", "
02427               << TVar( theMergeTolerance ) << ")";
02428 
02429   delete pPythonDump; // enable python dump from GetGroups()
02430 
02431   // 0020577: EDF 1164 SMESH: Bad dump of concatenate with create common groups
02432   if ( !aNewMesh->_is_nil() )
02433   {
02434     SMESH::ListOfGroups_var groups = aNewMesh->GetGroups();
02435   }
02436 
02437   // IPAL21468 Change icon of compound because it need not be computed.
02438   SALOMEDS::SObject_var aMeshSObj = ObjectToSObject( myCurrentStudy, aNewMesh );
02439   if( !aMeshSObj->_is_nil() ) {
02440     SALOMEDS::GenericAttribute_var anAttr;
02441     SALOMEDS::StudyBuilder_var aBuilder = myCurrentStudy->NewBuilder();
02442     anAttr = aBuilder->FindOrCreateAttribute( aMeshSObj,"AttributePixMap" );
02443     SALOMEDS::AttributePixMap_var aPixmap = SALOMEDS::AttributePixMap::_narrow(anAttr);
02444     aPixmap->SetPixMap("ICON_SMESH_TREE_MESH");
02445   }
02446   if (aNewMeshDS)
02447     aNewMeshDS->Modified();
02448   return aNewMesh._retn();
02449 }
02450 
02451 //================================================================================
02460 //================================================================================
02461 
02462 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CopyMesh(SMESH::SMESH_IDSource_ptr meshPart,
02463                                             const char*               meshName,
02464                                             CORBA::Boolean            toCopyGroups,
02465                                             CORBA::Boolean            toKeepIDs)
02466 {
02467   Unexpect aCatch(SALOME_SalomeException);
02468 
02469   TPythonDump* pyDump = new TPythonDump; // prevent dump from CreateMesh()
02470 
02471   // 1. Get source mesh
02472 
02473   if ( CORBA::is_nil( meshPart ))
02474     THROW_SALOME_CORBA_EXCEPTION( "bad IDSource", SALOME::BAD_PARAM );
02475 
02476   SMESH::SMESH_Mesh_var srcMesh = meshPart->GetMesh();
02477   SMESH_Mesh_i*       srcMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( srcMesh );
02478   if ( !srcMesh_i )
02479     THROW_SALOME_CORBA_EXCEPTION( "bad mesh of IDSource", SALOME::BAD_PARAM );
02480 
02481   SMESHDS_Mesh* srcMeshDS = srcMesh_i->GetImpl().GetMeshDS();
02482 
02483   // 2. Make a new mesh
02484 
02485   SMESH::SMESH_Mesh_var newMesh = CreateMesh(GEOM::GEOM_Object::_nil());
02486   SMESH_Mesh_i*       newMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( newMesh );
02487   if ( !newMesh_i )
02488     THROW_SALOME_CORBA_EXCEPTION( "can't create a mesh", SALOME::INTERNAL_ERROR );
02489   SALOMEDS::SObject_var meshSO = ObjectToSObject(myCurrentStudy, newMesh );
02490   if ( !meshSO->_is_nil() )
02491   {
02492     SetName( meshSO, meshName, "Mesh" );
02493     SetPixMap( meshSO, "ICON_SMESH_TREE_MESH_IMPORTED");
02494   }
02495   SMESHDS_Mesh* newMeshDS = newMesh_i->GetImpl().GetMeshDS();
02496   ::SMESH_MeshEditor editor( &newMesh_i->GetImpl() );
02497 
02498   // 3. Get elements to copy
02499 
02500   SMDS_ElemIteratorPtr srcElemIt; SMDS_NodeIteratorPtr srcNodeIt;
02501   TIDSortedElemSet srcElems;
02502   SMESH::array_of_ElementType_var srcElemTypes = meshPart->GetTypes();
02503   if ( SMESH::DownCast<SMESH_Mesh_i*>( meshPart ))
02504   {
02505     srcElemIt = srcMeshDS->elementsIterator();
02506     srcNodeIt = srcMeshDS->nodesIterator();
02507   }
02508   else
02509   {
02510     SMESH::long_array_var ids = meshPart->GetIDs();
02511     if ( srcElemTypes->length() == 1 && srcElemTypes[0] == SMESH::NODE ) // group of nodes
02512     {
02513       for (int i=0; i < ids->length(); i++)
02514         if ( const SMDS_MeshElement * elem = srcMeshDS->FindNode( ids[i] ))
02515           srcElems.insert( elem );
02516     }
02517     else
02518     {
02519       for (int i=0; i < ids->length(); i++)
02520         if ( const SMDS_MeshElement * elem = srcMeshDS->FindElement( ids[i] ))
02521           srcElems.insert( elem );
02522     }
02523     if ( srcElems.empty() )
02524       return newMesh._retn();
02525 
02526     typedef SMDS_SetIterator< SMDS_pElement, TIDSortedElemSet::const_iterator > ElIter;
02527     srcElemIt = SMDS_ElemIteratorPtr( new ElIter( srcElems.begin(), srcElems.end() ));
02528   }
02529 
02530   // 4. Copy elements
02531 
02532   typedef map<SMDS_pElement, SMDS_pElement, TIDCompare> TE2EMap;
02533   TE2EMap e2eMapByType[ SMDSAbs_NbElementTypes ];
02534   TE2EMap& n2nMap = e2eMapByType[ SMDSAbs_Node ];
02535   int iN;
02536   const SMDS_MeshNode *nSrc, *nTgt;
02537   vector< const SMDS_MeshNode* > nodes;
02538   while ( srcElemIt->more() )
02539   {
02540     const SMDS_MeshElement * elem = srcElemIt->next();
02541     nodes.resize( elem->NbNodes());
02542     SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
02543     if ( toKeepIDs ) {
02544       for ( iN = 0; nIt->more(); ++iN )
02545       {
02546         nSrc = static_cast<const SMDS_MeshNode*>( nIt->next() );
02547         nTgt = newMeshDS->FindNode( nSrc->GetID());
02548         if ( !nTgt )
02549           nTgt = newMeshDS->AddNodeWithID( nSrc->X(), nSrc->Y(), nSrc->Z(), nSrc->GetID());
02550         nodes[ iN ] = nTgt;
02551       }
02552     }
02553     else {
02554       for ( iN = 0; nIt->more(); ++iN )
02555       {
02556         nSrc = static_cast<const SMDS_MeshNode*>( nIt->next() );
02557         TE2EMap::iterator n2n = n2nMap.insert( make_pair( nSrc, SMDS_pNode(0) )).first;
02558         if ( !n2n->second )
02559           n2n->second = newMeshDS->AddNode( nSrc->X(), nSrc->Y(), nSrc->Z() );
02560         nodes[ iN ] = (const SMDS_MeshNode*) n2n->second;
02561       }
02562     }
02563     if ( elem->GetType() != SMDSAbs_Node )
02564     {
02565       int ID = toKeepIDs ? elem->GetID() : 0;
02566       const SMDS_MeshElement * newElem;
02567       if ( elem->GetEntityType() == SMDSEntity_Polyhedra )
02568         newElem = editor.GetMeshDS()->
02569           AddPolyhedralVolumeWithID( nodes,
02570                                      static_cast<const SMDS_VtkVolume*>(elem)->GetQuantities(),
02571                                      elem->GetID());
02572       else
02573         newElem = editor.AddElement( nodes,elem->GetType(),elem->IsPoly(),ID);
02574 
02575       if ( toCopyGroups && !toKeepIDs )
02576         e2eMapByType[ elem->GetType() ].insert( make_pair( elem, newElem ));
02577     }
02578   }
02579 
02580   // 4(b). Copy free nodes
02581 
02582   if ( srcNodeIt && srcMeshDS->NbNodes() != newMeshDS->NbNodes() )
02583   {
02584     while ( srcNodeIt->more() )
02585     {
02586       nSrc = srcNodeIt->next();
02587       if ( nSrc->NbInverseElements() == 0 )
02588       {
02589         if ( toKeepIDs )
02590           nTgt = newMeshDS->AddNodeWithID( nSrc->X(), nSrc->Y(), nSrc->Z(), nSrc->GetID());
02591         else
02592           n2nMap[ nSrc ] = newMeshDS->AddNode( nSrc->X(), nSrc->Y(), nSrc->Z() );
02593       }
02594     }
02595   }
02596 
02597   // 5. Copy groups
02598 
02599   int nbNewGroups = 0;
02600   if ( toCopyGroups )
02601   {
02602     SMESH_Mesh::GroupIteratorPtr gIt = srcMesh_i->GetImpl().GetGroups();
02603     while ( gIt->more() )
02604     {
02605       SMESH_Group* group = gIt->next();
02606       const SMESHDS_GroupBase* groupDS = group->GetGroupDS();
02607 
02608       // Check group type. We copy nodal groups containing nodes of copied element
02609       SMDSAbs_ElementType groupType = groupDS->GetType();
02610       if ( groupType != SMDSAbs_Node &&
02611            newMeshDS->GetMeshInfo().NbElements( groupType ) == 0 )
02612         continue; // group type differs from types of meshPart
02613 
02614       // Find copied elements in the group
02615       vector< const SMDS_MeshElement* > groupElems;
02616       SMDS_ElemIteratorPtr eIt = groupDS->GetElements();
02617       if ( toKeepIDs )
02618       {
02619         const SMDS_MeshElement* foundElem;
02620         if ( groupType == SMDSAbs_Node )
02621         {
02622           while ( eIt->more() )
02623             if (( foundElem = newMeshDS->FindNode( eIt->next()->GetID() )))
02624               groupElems.push_back( foundElem );
02625         }
02626         else
02627         {
02628           while ( eIt->more() )
02629             if (( foundElem = newMeshDS->FindElement( eIt->next()->GetID() )))
02630               groupElems.push_back( foundElem );
02631         }
02632       }
02633       else
02634       {
02635         TE2EMap & e2eMap = e2eMapByType[ groupDS->GetType() ];
02636         if ( e2eMap.empty() ) continue;
02637         int minID = e2eMap.begin()->first->GetID();
02638         int maxID = e2eMap.rbegin()->first->GetID();
02639         TE2EMap::iterator e2e;
02640         while ( eIt->more() && groupElems.size() < e2eMap.size())
02641         {
02642           const SMDS_MeshElement* e = eIt->next();
02643           if ( e->GetID() < minID || e->GetID() > maxID ) continue;
02644           if ((e2e = e2eMap.find( e )) != e2eMap.end())
02645             groupElems.push_back( e2e->second );
02646         }
02647       }
02648       // Make a new group
02649       if ( !groupElems.empty() )
02650       {
02651         SMESH::SMESH_Group_var newGroupObj =
02652           newMesh->CreateGroup( SMESH::ElementType(groupType), group->GetName() );
02653         if ( SMESH_GroupBase_i* newGroup_i = SMESH::DownCast<SMESH_GroupBase_i*>( newGroupObj))
02654         {
02655           SMESHDS_GroupBase * newGroupDS = newGroup_i->GetGroupDS();
02656           SMDS_MeshGroup& smdsGroup = ((SMESHDS_Group*)newGroupDS)->SMDSGroup();
02657           for ( unsigned i = 0; i < groupElems.size(); ++i )
02658             smdsGroup.Add( groupElems[i] );
02659 
02660           nbNewGroups++;
02661         }
02662       }
02663     }
02664   }
02665 
02666   newMeshDS->Modified();
02667 
02668   *pyDump << newMesh << " = " << this
02669           << ".CopyMesh( " << meshPart << ", "
02670           << "'" << meshName << "', "
02671           << toCopyGroups << ", "
02672           << toKeepIDs << ")";
02673 
02674   delete pyDump; pyDump = 0; // allow dump in GetGroups()
02675 
02676   if ( nbNewGroups > 0 ) // dump created groups
02677     SMESH::ListOfGroups_var groups = newMesh->GetGroups();
02678 
02679   return newMesh._retn();
02680 }
02681 
02682 //================================================================================
02688 //================================================================================
02689 CORBA::Boolean SMESH_Gen_i::GetMEDVersion(const char* theFileName,
02690                                           SMESH::MED_VERSION& theVersion)
02691 {
02692   theVersion = SMESH::MED_V2_1;
02693   MED::EVersion aVersion = MED::GetVersionId( theFileName );
02694   switch( aVersion ) {
02695     case MED::eV2_1     : theVersion = SMESH::MED_V2_1; return true;
02696     case MED::eV2_2     : theVersion = SMESH::MED_V2_2; return true;
02697     case MED::eVUnknown : return false;
02698   }
02699   return false;
02700 }
02701 
02702 //================================================================================
02708 //================================================================================
02709 SMESH::string_array* SMESH_Gen_i::GetMeshNames(const char* theFileName)
02710 {
02711   SMESH::string_array_var aResult = new SMESH::string_array();
02712   MED::PWrapper aMed = MED::CrWrapper( theFileName );
02713   MED::TErr anErr;
02714   MED::TInt aNbMeshes = aMed->GetNbMeshes( &anErr );
02715   if( anErr >= 0 ) {
02716     aResult->length( aNbMeshes );
02717     for( MED::TInt i = 0; i < aNbMeshes; i++ ) {
02718       MED::PMeshInfo aMeshInfo = aMed->GetPMeshInfo( i+1 );
02719       aResult[i] = CORBA::string_dup( aMeshInfo->GetName().c_str() );
02720     }
02721   }
02722   return aResult._retn();
02723 }
02724 
02725 //=============================================================================
02731 //=============================================================================
02732 SALOMEDS::TMPFile* SMESH_Gen_i::Save( SALOMEDS::SComponent_ptr theComponent,
02733                                       const char*              theURL,
02734                                       bool                     isMultiFile )
02735 {
02736   INFOS( "SMESH_Gen_i::Save" );
02737 
02738   //  ASSERT( theComponent->GetStudy()->StudyId() == myCurrentStudy->StudyId() )
02739   // san -- in case <myCurrentStudy> differs from theComponent's study,
02740   // use that of the component
02741   if ( myCurrentStudy->_is_nil() ||
02742     theComponent->GetStudy()->StudyId() != myCurrentStudy->StudyId() )
02743     SetCurrentStudy( theComponent->GetStudy() );
02744 
02745   // Store study contents as a set of python commands
02746   SavePython(myCurrentStudy);
02747 
02748   StudyContext* myStudyContext = GetCurrentStudyContext();
02749 
02750   // Declare a byte stream
02751   SALOMEDS::TMPFile_var aStreamFile;
02752 
02753   // Obtain a temporary dir
02754   TCollection_AsciiString tmpDir =
02755     ( isMultiFile ) ? TCollection_AsciiString( ( char* )theURL ) : ( char* )SALOMEDS_Tool::GetTmpDir().c_str();
02756 
02757   // Create a sequence of files processed
02758   SALOMEDS::ListOfFileNames_var aFileSeq = new SALOMEDS::ListOfFileNames;
02759   aFileSeq->length( NUM_TMP_FILES );
02760 
02761   TCollection_AsciiString aStudyName( "" );
02762   if ( isMultiFile )
02763     aStudyName = ( (char*)SALOMEDS_Tool::GetNameFromPath( myCurrentStudy->URL() ).c_str() );
02764 
02765   // Set names of temporary files
02766   TCollection_AsciiString filename =
02767     aStudyName + TCollection_AsciiString( "_SMESH.hdf" );        // for SMESH data itself
02768   TCollection_AsciiString meshfile =
02769     aStudyName + TCollection_AsciiString( "_SMESH_Mesh.med" );   // for mesh data to be stored in MED file
02770   aFileSeq[ 0 ] = CORBA::string_dup( filename.ToCString() );
02771   aFileSeq[ 1 ] = CORBA::string_dup( meshfile.ToCString() );
02772   filename = tmpDir + filename;
02773   meshfile = tmpDir + meshfile;
02774 
02775   HDFfile*    aFile;
02776   HDFdataset* aDataset;
02777   HDFgroup*   aTopGroup;
02778   HDFgroup*   aGroup;
02779   HDFgroup*   aSubGroup;
02780   HDFgroup*   aSubSubGroup;
02781   hdf_size    aSize[ 1 ];
02782 
02783 
02784   //Remove the files if they exist: BugID: 11225
02785 #ifndef WNT /* unix functionality */
02786   TCollection_AsciiString cmd("rm -f \"");
02787 #else /* windows */
02788   TCollection_AsciiString cmd("del /F \"");
02789 #endif
02790 
02791   cmd+=filename;
02792   cmd+="\" \"";
02793   cmd+=meshfile;
02794   cmd+="\"";
02795   system(cmd.ToCString());
02796 
02797   // MED writer to be used by storage process
02798   DriverMED_W_SMESHDS_Mesh myWriter;
02799   myWriter.SetFile( meshfile.ToCString() );
02800 
02801   // IMP issue 20918
02802   // SetStoreName() to groups before storing hypotheses to let them refer to
02803   // groups using "store name", which is "Group <group_persistent_id>"
02804   {
02805     SALOMEDS::ChildIterator_var itBig = myCurrentStudy->NewChildIterator( theComponent );
02806     for ( ; itBig->More(); itBig->Next() ) {
02807       SALOMEDS::SObject_var gotBranch = itBig->Value();
02808       if ( gotBranch->Tag() > GetAlgorithmsRootTag() ) {
02809         CORBA::Object_var anObject = SObjectToObject( gotBranch );
02810         if ( !CORBA::is_nil( anObject ) ) {
02811           SMESH::SMESH_Mesh_var myMesh = SMESH::SMESH_Mesh::_narrow( anObject ) ;
02812           if ( !myMesh->_is_nil() ) {
02813             myMesh->Load(); // load from study file if not yet done
02814             TPythonDump pd; // not to dump GetGroups()
02815             SMESH::ListOfGroups_var groups = myMesh->GetGroups();
02816             pd << ""; // to avoid optimizing pd out
02817             for ( int i = 0; i < groups->length(); ++i )
02818             {
02819               SMESH_GroupBase_i* grImpl = SMESH::DownCast<SMESH_GroupBase_i*>( groups[i]);
02820               if ( grImpl )
02821               {
02822                 CORBA::String_var objStr = GetORB()->object_to_string( grImpl->_this() );
02823                 int anId = myStudyContext->findId( string( objStr.in() ) );
02824                 char grpName[ 30 ];
02825                 sprintf( grpName, "Group %d", anId );
02826                 SMESHDS_GroupBase* aGrpBaseDS = grImpl->GetGroupDS();
02827                 aGrpBaseDS->SetStoreName( grpName );
02828               }
02829             }
02830           }
02831         }
02832       }
02833     }
02834   }
02835 
02836   // Write data
02837   // ---> create HDF file
02838   aFile = new HDFfile( (char*) filename.ToCString() );
02839   aFile->CreateOnDisk();
02840 
02841   // --> iterator for top-level objects
02842   SALOMEDS::ChildIterator_var itBig = myCurrentStudy->NewChildIterator( theComponent );
02843   for ( ; itBig->More(); itBig->Next() ) {
02844     SALOMEDS::SObject_var gotBranch = itBig->Value();
02845 
02846     // --> hypotheses root branch (only one for the study)
02847     if ( gotBranch->Tag() == GetHypothesisRootTag() ) {
02848       // create hypotheses root HDF group
02849       aTopGroup = new HDFgroup( "Hypotheses", aFile );
02850       aTopGroup->CreateOnDisk();
02851 
02852       // iterator for all hypotheses
02853       SALOMEDS::ChildIterator_var it = myCurrentStudy->NewChildIterator( gotBranch );
02854       for ( ; it->More(); it->Next() ) {
02855         SALOMEDS::SObject_var mySObject = it->Value();
02856         CORBA::Object_var anObject = SObjectToObject( mySObject );
02857         if ( !CORBA::is_nil( anObject ) ) {
02858           SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
02859           if ( !myHyp->_is_nil() ) {
02860             SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
02861             if ( myImpl ) {
02862               string hypname = string( myHyp->GetName() );
02863               string libname = string( myHyp->GetLibName() );
02864               // BUG SWP13062
02865               // Needs for save crossplatform libname, i.e. parth of name ( ".dll" for
02866               // WNT and ".so" for X-system) must be deleted
02867               int libname_len = libname.length();
02868 #ifdef WNT
02869               if( libname_len > 4 )
02870                 libname.resize( libname_len - 4 );
02871 #else
02872               // PAL17753 (Regresion: missing hypothesis in restored study)
02873               // "lib" also should be removed from the beginning
02874               //if( libname_len > 3 )
02875                 //libname.resize( libname_len - 3 );
02876               if( libname_len > 6 )
02877                 libname = libname.substr( 3, libname_len - 3 - 3 );
02878 #endif
02879               CORBA::String_var objStr = GetORB()->object_to_string( anObject );
02880               int    id      = myStudyContext->findId( string( objStr.in() ) );
02881               string hypdata = string( myImpl->SaveTo() );
02882 
02883               // for each hypothesis create HDF group basing on its id
02884               char hypGrpName[30];
02885               sprintf( hypGrpName, "Hypothesis %d", id );
02886               aGroup = new HDFgroup( hypGrpName, aTopGroup );
02887               aGroup->CreateOnDisk();
02888               // --> type name of hypothesis
02889               aSize[ 0 ] = hypname.length() + 1;
02890               aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
02891               aDataset->CreateOnDisk();
02892               aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
02893               aDataset->CloseOnDisk();
02894               // --> server plugin library name of hypothesis
02895               aSize[ 0 ] = libname.length() + 1;
02896               aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );
02897               aDataset->CreateOnDisk();
02898               aDataset->WriteOnDisk( ( char* )( libname.c_str() ) );
02899               aDataset->CloseOnDisk();
02900               // --> persistent data of hypothesis
02901               aSize[ 0 ] = hypdata.length() + 1;
02902               aDataset = new HDFdataset( "Data", aGroup, HDF_STRING, aSize, 1 );
02903               aDataset->CreateOnDisk();
02904               aDataset->WriteOnDisk( ( char* )( hypdata.c_str() ) );
02905               aDataset->CloseOnDisk();
02906               // close hypothesis HDF group
02907               aGroup->CloseOnDisk();
02908             }
02909           }
02910         }
02911       }
02912       // close hypotheses root HDF group
02913       aTopGroup->CloseOnDisk();
02914     }
02915     // --> algorithms root branch (only one for the study)
02916     else if ( gotBranch->Tag() == GetAlgorithmsRootTag() ) {
02917       // create algorithms root HDF group
02918       aTopGroup = new HDFgroup( "Algorithms", aFile );
02919       aTopGroup->CreateOnDisk();
02920 
02921       // iterator for all algorithms
02922       SALOMEDS::ChildIterator_var it = myCurrentStudy->NewChildIterator( gotBranch );
02923       for ( ; it->More(); it->Next() ) {
02924         SALOMEDS::SObject_var mySObject = it->Value();
02925         CORBA::Object_var anObject = SObjectToObject( mySObject );
02926         if ( !CORBA::is_nil( anObject ) ) {
02927           SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
02928           if ( !myHyp->_is_nil() ) {
02929             SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
02930             if ( myImpl ) {
02931               string hypname = string( myHyp->GetName() );
02932               string libname = string( myHyp->GetLibName() );
02933               // BUG SWP13062
02934               // Needs for save crossplatform libname, i.e. parth of name ( ".dll" for
02935               // WNT and ".so" for X-system) must be deleted
02936               int libname_len = libname.length();
02937 #ifdef WNT
02938               if( libname_len > 4 )
02939                 libname.resize( libname_len - 4 );
02940 #else
02941               // PAL17753 (Regresion: missing hypothesis in restored study)
02942               // "lib" also should be removed from the beginning
02943               //if( libname_len > 3 )
02944                 //libname.resize( libname_len - 3 );
02945               if( libname_len > 6 )
02946                 libname = libname.substr( 3, libname_len - 3 - 3 );
02947 #endif
02948               CORBA::String_var objStr = GetORB()->object_to_string( anObject );
02949               int    id      = myStudyContext->findId( string( objStr.in() ) );
02950               string hypdata = string( myImpl->SaveTo() );
02951 
02952               // for each algorithm create HDF group basing on its id
02953               char hypGrpName[30];
02954               sprintf( hypGrpName, "Algorithm %d", id );
02955               aGroup = new HDFgroup( hypGrpName, aTopGroup );
02956               aGroup->CreateOnDisk();
02957               // --> type name of algorithm
02958               aSize[0] = hypname.length() + 1;
02959               aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
02960               aDataset->CreateOnDisk();
02961               aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
02962               aDataset->CloseOnDisk();
02963               // --> server plugin library name of hypothesis
02964               aSize[0] = libname.length() + 1;
02965               aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );
02966               aDataset->CreateOnDisk();
02967               aDataset->WriteOnDisk( ( char* )( libname.c_str() ) );
02968               aDataset->CloseOnDisk();
02969               // --> persistent data of algorithm
02970               aSize[0] = hypdata.length() + 1;
02971               aDataset = new HDFdataset( "Data", aGroup, HDF_STRING, aSize, 1 );
02972               aDataset->CreateOnDisk();
02973               aDataset->WriteOnDisk( ( char* )( hypdata.c_str() ) );
02974               aDataset->CloseOnDisk();
02975               // close algorithm HDF group
02976               aGroup->CloseOnDisk();
02977             }
02978           }
02979         }
02980       }
02981       // close algorithms root HDF group
02982       aTopGroup->CloseOnDisk();
02983     }
02984     // --> mesh objects roots branches
02985     else if ( gotBranch->Tag() > GetAlgorithmsRootTag() ) {
02986       CORBA::Object_var anObject = SObjectToObject( gotBranch );
02987       if ( !CORBA::is_nil( anObject ) ) {
02988         SMESH::SMESH_Mesh_var myMesh = SMESH::SMESH_Mesh::_narrow( anObject ) ;
02989         if ( !myMesh->_is_nil() ) {
02990           SMESH_Mesh_i* myImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( myMesh ).in() );
02991           if ( myImpl ) {
02992             CORBA::String_var objStr = GetORB()->object_to_string( anObject );
02993             int id = myStudyContext->findId( string( objStr.in() ) );
02994             ::SMESH_Mesh& myLocMesh = myImpl->GetImpl();
02995             SMESHDS_Mesh* mySMESHDSMesh = myLocMesh.GetMeshDS();
02996             bool hasShape = myLocMesh.HasShapeToMesh();
02997 
02998             // for each mesh open the HDF group basing on its id
02999             char meshGrpName[ 30 ];
03000             sprintf( meshGrpName, "Mesh %d", id );
03001             aTopGroup = new HDFgroup( meshGrpName, aFile );
03002             aTopGroup->CreateOnDisk();
03003 
03004             // --> put dataset to hdf file which is a flag that mesh has data
03005             string strHasData = "0";
03006             // check if the mesh is not empty
03007             if ( mySMESHDSMesh->NbNodes() > 0 ) {
03008               // write mesh data to med file
03009               myWriter.SetMesh( mySMESHDSMesh );
03010               myWriter.SetMeshId( id );
03011               strHasData = "1";
03012             }
03013             aSize[ 0 ] = strHasData.length() + 1;
03014             aDataset = new HDFdataset( "Has data", aTopGroup, HDF_STRING, aSize, 1 );
03015             aDataset->CreateOnDisk();
03016             aDataset->WriteOnDisk( ( char* )( strHasData.c_str() ) );
03017             aDataset->CloseOnDisk();
03018 
03019             // ouv : NPAL12872
03020             // for each mesh open the HDF group basing on its auto color parameter
03021             char meshAutoColorName[ 30 ];
03022             sprintf( meshAutoColorName, "AutoColorMesh %d", id );
03023             int anAutoColor[1];
03024             anAutoColor[0] = myImpl->GetAutoColor();
03025             aSize[ 0 ] = 1;
03026             aDataset = new HDFdataset( meshAutoColorName, aTopGroup, HDF_INT32, aSize, 1 );
03027             aDataset->CreateOnDisk();
03028             aDataset->WriteOnDisk( anAutoColor );
03029             aDataset->CloseOnDisk();
03030 
03031             // issue 0020693. Store _isModified flag
03032             int isModified = myLocMesh.GetIsModified();
03033             aSize[ 0 ] = 1;
03034             aDataset = new HDFdataset( "_isModified", aTopGroup, HDF_INT32, aSize, 1 );
03035             aDataset->CreateOnDisk();
03036             aDataset->WriteOnDisk( &isModified );
03037             aDataset->CloseOnDisk();
03038 
03039             // issue 20918. Store Persistent Id of SMESHDS_Mesh
03040             int meshPersistentId = mySMESHDSMesh->GetPersistentId();
03041             aSize[ 0 ] = 1;
03042             aDataset = new HDFdataset( "meshPersistentId", aTopGroup, HDF_INT32, aSize, 1 );
03043             aDataset->CreateOnDisk();
03044             aDataset->WriteOnDisk( &meshPersistentId );
03045             aDataset->CloseOnDisk();
03046 
03047             // write reference on a shape if exists
03048             SALOMEDS::SObject_var myRef;
03049             bool shapeRefFound = false;
03050             bool found = gotBranch->FindSubObject( GetRefOnShapeTag(), myRef );
03051             if ( found ) {
03052               SALOMEDS::SObject_var myShape;
03053               bool ok = myRef->ReferencedObject( myShape );
03054               if ( ok ) {
03055                 shapeRefFound = (! CORBA::is_nil( myShape->GetObject() ));
03056                 string myRefOnObject = myShape->GetID();
03057                 if ( shapeRefFound && myRefOnObject.length() > 0 ) {
03058                   aSize[ 0 ] = myRefOnObject.length() + 1;
03059                   aDataset = new HDFdataset( "Ref on shape", aTopGroup, HDF_STRING, aSize, 1 );
03060                   aDataset->CreateOnDisk();
03061                   aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
03062                   aDataset->CloseOnDisk();
03063                 }
03064               }
03065             }
03066 
03067             // write applied hypotheses if exist
03068             SALOMEDS::SObject_var myHypBranch;
03069             found = gotBranch->FindSubObject( GetRefOnAppliedHypothesisTag(), myHypBranch );
03070             if ( found && !shapeRefFound && hasShape) { // remove applied hyps
03071               myCurrentStudy->NewBuilder()->RemoveObjectWithChildren( myHypBranch );
03072             }
03073             if ( found && (shapeRefFound || !hasShape) ) {
03074               aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
03075               aGroup->CreateOnDisk();
03076 
03077               SALOMEDS::ChildIterator_var it = myCurrentStudy->NewChildIterator( myHypBranch );
03078               int hypNb = 0;
03079               for ( ; it->More(); it->Next() ) {
03080                 SALOMEDS::SObject_var mySObject = it->Value();
03081                 SALOMEDS::SObject_var myRefOnHyp;
03082                 bool ok = mySObject->ReferencedObject( myRefOnHyp );
03083                 if ( ok ) {
03084                   // san - it is impossible to recover applied hypotheses
03085                   //       using their entries within Load() method,
03086                   // for there are no AttributeIORs in the study when Load() is working.
03087                   // Hence, it is better to store persistent IDs of hypotheses as references to them
03088 
03089                   //string myRefOnObject = myRefOnHyp->GetID();
03090                   CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
03091                   CORBA::String_var objStr = GetORB()->object_to_string( anObject );
03092                   int id = myStudyContext->findId( string( objStr.in() ) );
03093                   //if ( myRefOnObject.length() > 0 ) {
03094                   //aSize[ 0 ] = myRefOnObject.length() + 1;
03095                   char hypName[ 30 ], hypId[ 30 ];
03096                   sprintf( hypName, "Hyp %d", ++hypNb );
03097                   sprintf( hypId, "%d", id );
03098                   aSize[ 0 ] = strlen( hypId ) + 1;
03099                   aDataset = new HDFdataset( hypName, aGroup, HDF_STRING, aSize, 1 );
03100                   aDataset->CreateOnDisk();
03101                   //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
03102                   aDataset->WriteOnDisk( hypId );
03103                   aDataset->CloseOnDisk();
03104                   //}
03105                 }
03106               }
03107               aGroup->CloseOnDisk();
03108             }
03109 
03110             // write applied algorithms if exist
03111             SALOMEDS::SObject_var myAlgoBranch;
03112             found = gotBranch->FindSubObject( GetRefOnAppliedAlgorithmsTag(), myAlgoBranch );
03113             if ( found && !shapeRefFound && hasShape) { // remove applied algos
03114               myCurrentStudy->NewBuilder()->RemoveObjectWithChildren( myAlgoBranch );
03115             }
03116             if ( found && (shapeRefFound || !hasShape)) {
03117               aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
03118               aGroup->CreateOnDisk();
03119 
03120               SALOMEDS::ChildIterator_var it = myCurrentStudy->NewChildIterator( myAlgoBranch );
03121               int algoNb = 0;
03122               for ( ; it->More(); it->Next() ) {
03123                 SALOMEDS::SObject_var mySObject = it->Value();
03124                 SALOMEDS::SObject_var myRefOnAlgo;
03125                 bool ok = mySObject->ReferencedObject( myRefOnAlgo );
03126                 if ( ok ) {
03127                   // san - it is impossible to recover applied algorithms
03128                   //       using their entries within Load() method,
03129                   // for there are no AttributeIORs in the study when Load() is working.
03130                   // Hence, it is better to store persistent IDs of algorithms as references to them
03131 
03132                   //string myRefOnObject = myRefOnAlgo->GetID();
03133                   CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
03134                   CORBA::String_var objStr = GetORB()->object_to_string( anObject );
03135                   int id = myStudyContext->findId( string( objStr.in() ) );
03136                   //if ( myRefOnObject.length() > 0 ) {
03137                   //aSize[ 0 ] = myRefOnObject.length() + 1;
03138                   char algoName[ 30 ], algoId[ 30 ];
03139                   sprintf( algoName, "Algo %d", ++algoNb );
03140                   sprintf( algoId, "%d", id );
03141                   aSize[ 0 ] = strlen( algoId ) + 1;
03142                   aDataset = new HDFdataset( algoName, aGroup, HDF_STRING, aSize, 1 );
03143                   aDataset->CreateOnDisk();
03144                   //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
03145                   aDataset->WriteOnDisk( algoId );
03146                   aDataset->CloseOnDisk();
03147                   //}
03148                 }
03149               }
03150               aGroup->CloseOnDisk();
03151             }
03152 
03153             // --> submesh objects sub-branches
03154 
03155             for ( int i = GetSubMeshOnVertexTag(); i <= GetSubMeshOnCompoundTag(); i++ ) {
03156               SALOMEDS::SObject_var mySubmeshBranch;
03157               found = gotBranch->FindSubObject( i, mySubmeshBranch );
03158 
03159               if ( found ) // check if there is shape reference in submeshes
03160               {
03161                 bool hasShapeRef = false;
03162                 SALOMEDS::ChildIterator_var itSM =
03163                   myCurrentStudy->NewChildIterator( mySubmeshBranch );
03164                 for ( ; itSM->More(); itSM->Next() ) {
03165                   SALOMEDS::SObject_var mySubRef, myShape, mySObject = itSM->Value();
03166                   if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef ))
03167                     mySubRef->ReferencedObject( myShape );
03168                   if ( !CORBA::is_nil( myShape ) && !CORBA::is_nil( myShape->GetObject() ))
03169                     hasShapeRef = true;
03170                   else
03171                   { // remove one submesh
03172                     if ( shapeRefFound )
03173                     { // unassign hypothesis
03174                       SMESH::SMESH_subMesh_var mySubMesh =
03175                         SMESH::SMESH_subMesh::_narrow( SObjectToObject( mySObject ));
03176                       if ( !mySubMesh->_is_nil() ) {
03177                         int shapeID = mySubMesh->GetId();
03178                         TopoDS_Shape S = mySMESHDSMesh->IndexToShape( shapeID );
03179                         const list<const SMESHDS_Hypothesis*>& hypList =
03180                           mySMESHDSMesh->GetHypothesis( S );
03181                         list<const SMESHDS_Hypothesis*>::const_iterator hyp = hypList.begin();
03182                         while ( hyp != hypList.end() ) {
03183                           int hypID = (*hyp++)->GetID(); // goto next hyp here because
03184                           myLocMesh.RemoveHypothesis( S, hypID ); // hypList changes here
03185                         }
03186                       }
03187                     }
03188                     myCurrentStudy->NewBuilder()->RemoveObjectWithChildren( mySObject );
03189                   }
03190                 } // loop on submeshes of a type
03191                 if ( !shapeRefFound || !hasShapeRef ) { // remove the whole submeshes branch
03192                   myCurrentStudy->NewBuilder()->RemoveObjectWithChildren( mySubmeshBranch );
03193                   found = false;
03194                 }
03195               }  // end check if there is shape reference in submeshes
03196               if ( found ) {
03197                 char name_meshgroup[ 30 ];
03198                 if ( i == GetSubMeshOnVertexTag() )
03199                   strcpy( name_meshgroup, "SubMeshes On Vertex" );
03200                 else if ( i == GetSubMeshOnEdgeTag() )
03201                   strcpy( name_meshgroup, "SubMeshes On Edge" );
03202                 else if ( i == GetSubMeshOnWireTag() )
03203                   strcpy( name_meshgroup, "SubMeshes On Wire" );
03204                 else if ( i == GetSubMeshOnFaceTag() )
03205                   strcpy( name_meshgroup, "SubMeshes On Face" );
03206                 else if ( i == GetSubMeshOnShellTag() )
03207                   strcpy( name_meshgroup, "SubMeshes On Shell" );
03208                 else if ( i == GetSubMeshOnSolidTag() )
03209                   strcpy( name_meshgroup, "SubMeshes On Solid" );
03210                 else if ( i == GetSubMeshOnCompoundTag() )
03211                   strcpy( name_meshgroup, "SubMeshes On Compound" );
03212 
03213                 // for each type of submeshes create container HDF group
03214                 aGroup = new HDFgroup( name_meshgroup, aTopGroup );
03215                 aGroup->CreateOnDisk();
03216 
03217                 // iterator for all submeshes of given type
03218                 SALOMEDS::ChildIterator_var itSM = myCurrentStudy->NewChildIterator( mySubmeshBranch );
03219                 for ( ; itSM->More(); itSM->Next() ) {
03220                   SALOMEDS::SObject_var mySObject = itSM->Value();
03221                   CORBA::Object_var anSubObject = SObjectToObject( mySObject );
03222                   if ( !CORBA::is_nil( anSubObject ))
03223                   {
03224                     SMESH::SMESH_subMesh_var mySubMesh = SMESH::SMESH_subMesh::_narrow( anSubObject ) ;
03225                     CORBA::String_var objStr = GetORB()->object_to_string( anSubObject );
03226                     int subid = myStudyContext->findId( string( objStr.in() ) );
03227 
03228                     // for each mesh open the HDF group basing on its id
03229                     char submeshGrpName[ 30 ];
03230                     sprintf( submeshGrpName, "SubMesh %d", subid );
03231                     aSubGroup = new HDFgroup( submeshGrpName, aGroup );
03232                     aSubGroup->CreateOnDisk();
03233 
03234                     // write reference on a shape, already checked if it exists
03235                     SALOMEDS::SObject_var mySubRef, myShape;
03236                     if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef ))
03237                       mySubRef->ReferencedObject( myShape );
03238                     string myRefOnObject = myShape->GetID();
03239                     if ( myRefOnObject.length() > 0 ) {
03240                       aSize[ 0 ] = myRefOnObject.length() + 1;
03241                       aDataset = new HDFdataset( "Ref on shape", aSubGroup, HDF_STRING, aSize, 1 );
03242                       aDataset->CreateOnDisk();
03243                       aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
03244                       aDataset->CloseOnDisk();
03245                     }
03246 
03247                     // write applied hypotheses if exist
03248                     SALOMEDS::SObject_var mySubHypBranch;
03249                     found = mySObject->FindSubObject( GetRefOnAppliedHypothesisTag(), mySubHypBranch );
03250                     if ( found ) {
03251                       aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
03252                       aSubSubGroup->CreateOnDisk();
03253 
03254                       SALOMEDS::ChildIterator_var it = myCurrentStudy->NewChildIterator( mySubHypBranch );
03255                       int hypNb = 0;
03256                       for ( ; it->More(); it->Next() ) {
03257                         SALOMEDS::SObject_var mySubSObject = it->Value();
03258                         SALOMEDS::SObject_var myRefOnHyp;
03259                         bool ok = mySubSObject->ReferencedObject( myRefOnHyp );
03260                         if ( ok ) {
03261                           //string myRefOnObject = myRefOnHyp->GetID();
03262                           CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
03263                           CORBA::String_var objStr = GetORB()->object_to_string( anObject );
03264                           int id = myStudyContext->findId( string( objStr.in() ) );
03265                           //if ( myRefOnObject.length() > 0 ) {
03266                           //aSize[ 0 ] = myRefOnObject.length() + 1;
03267                           char hypName[ 30 ], hypId[ 30 ];
03268                           sprintf( hypName, "Hyp %d", ++hypNb );
03269                           sprintf( hypId, "%d", id );
03270                           aSize[ 0 ] = strlen( hypId ) + 1;
03271                           aDataset = new HDFdataset( hypName, aSubSubGroup, HDF_STRING, aSize, 1 );
03272                           aDataset->CreateOnDisk();
03273                           //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
03274                           aDataset->WriteOnDisk( hypId );
03275                           aDataset->CloseOnDisk();
03276                           //}
03277                         }
03278                       }
03279                       aSubSubGroup->CloseOnDisk();
03280                     }
03281 
03282                     // write applied algorithms if exist
03283                     SALOMEDS::SObject_var mySubAlgoBranch;
03284                     found = mySObject->FindSubObject( GetRefOnAppliedAlgorithmsTag(), mySubAlgoBranch );
03285                     if ( found ) {
03286                       aSubSubGroup = new HDFgroup( "Applied Algorithms", aSubGroup );
03287                       aSubSubGroup->CreateOnDisk();
03288 
03289                       SALOMEDS::ChildIterator_var it = myCurrentStudy->NewChildIterator( mySubAlgoBranch );
03290                       int algoNb = 0;
03291                       for ( ; it->More(); it->Next() ) {
03292                         SALOMEDS::SObject_var mySubSObject = it->Value();
03293                         SALOMEDS::SObject_var myRefOnAlgo;
03294                         bool ok = mySubSObject->ReferencedObject( myRefOnAlgo );
03295                         if ( ok ) {
03296                           //string myRefOnObject = myRefOnAlgo->GetID();
03297                           CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
03298                           CORBA::String_var objStr = GetORB()->object_to_string( anObject );
03299                           int id = myStudyContext->findId( string( objStr.in() ) );
03300                           //if ( myRefOnObject.length() > 0 ) {
03301                           //aSize[ 0 ] = myRefOnObject.length() + 1;
03302                           char algoName[ 30 ], algoId[ 30 ];
03303                           sprintf( algoName, "Algo %d", ++algoNb );
03304                           sprintf( algoId, "%d", id );
03305                           aSize[ 0 ] = strlen( algoId ) + 1;
03306                           aDataset = new HDFdataset( algoName, aSubSubGroup, HDF_STRING, aSize, 1 );
03307                           aDataset->CreateOnDisk();
03308                           //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
03309                           aDataset->WriteOnDisk( algoId );
03310                           aDataset->CloseOnDisk();
03311                           //}
03312                         }
03313                       }
03314                       aSubSubGroup->CloseOnDisk();
03315                     }
03316                     // close submesh HDF group
03317                     aSubGroup->CloseOnDisk();
03318                   }
03319                 }
03320                 // close container of submeshes by type HDF group
03321                 aGroup->CloseOnDisk();
03322               }
03323             }
03324             // All sub-meshes will be stored in MED file
03325             // .. will NOT (PAL 12992)
03326             //if ( shapeRefFound )
03327             //myWriter.AddAllSubMeshes();
03328 
03329             // store submesh order if any
03330             const TListOfListOfInt& theOrderIds = myLocMesh.GetMeshOrder();
03331             if ( theOrderIds.size() ) {
03332               char order_list[ 30 ];
03333               strcpy( order_list, "Mesh Order" );
03334               // count number of submesh ids
03335               int nbIDs = 0;
03336               TListOfListOfInt::const_iterator idIt = theOrderIds.begin();
03337               for ( ; idIt != theOrderIds.end(); idIt++ )
03338                 nbIDs += (*idIt).size();
03339               // number of values = number of IDs +
03340               //                    number of lists (for separators) - 1
03341               int* smIDs = new int [ nbIDs + theOrderIds.size() - 1 ];
03342               idIt = theOrderIds.begin();
03343               for ( int i = 0; idIt != theOrderIds.end(); idIt++ ) {
03344                 const TListOfInt& idList = *idIt;
03345                 if (idIt != theOrderIds.begin()) // not first list
03346                   smIDs[ i++ ] = -1/* *idList.size()*/; // separator between lists
03347                 // dump submesh ids from current list
03348                 TListOfInt::const_iterator id_smId = idList.begin();
03349                 for( ; id_smId != idList.end(); id_smId++ )
03350                   smIDs[ i++ ] = *id_smId;
03351               }
03352               // write HDF group
03353               aSize[ 0 ] = nbIDs + theOrderIds.size() - 1;
03354 
03355               aDataset = new HDFdataset( order_list, aTopGroup, HDF_INT32, aSize, 1 );
03356               aDataset->CreateOnDisk();
03357               aDataset->WriteOnDisk( smIDs );
03358               aDataset->CloseOnDisk();
03359               //
03360               delete[] smIDs;
03361             }
03362 
03363             // groups root sub-branch
03364             SALOMEDS::SObject_var myGroupsBranch;
03365             for ( int i = GetNodeGroupsTag(); i <= Get0DElementsGroupsTag(); i++ ) {
03366               found = gotBranch->FindSubObject( i, myGroupsBranch );
03367               if ( found ) {
03368                 char name_group[ 30 ];
03369                 if ( i == GetNodeGroupsTag() )
03370                   strcpy( name_group, "Groups of Nodes" );
03371                 else if ( i == GetEdgeGroupsTag() )
03372                   strcpy( name_group, "Groups of Edges" );
03373                 else if ( i == GetFaceGroupsTag() )
03374                   strcpy( name_group, "Groups of Faces" );
03375                 else if ( i == GetVolumeGroupsTag() )
03376                   strcpy( name_group, "Groups of Volumes" );
03377                 else if ( i == Get0DElementsGroupsTag() )
03378                   strcpy( name_group, "Groups of 0D Elements" );
03379 
03380                 aGroup = new HDFgroup( name_group, aTopGroup );
03381                 aGroup->CreateOnDisk();
03382 
03383                 SALOMEDS::ChildIterator_var it = myCurrentStudy->NewChildIterator( myGroupsBranch );
03384                 for ( ; it->More(); it->Next() ) {
03385                   SALOMEDS::SObject_var mySObject = it->Value();
03386                   CORBA::Object_var aSubObject = SObjectToObject( mySObject );
03387                   if ( !CORBA::is_nil( aSubObject ) ) {
03388                     SMESH_GroupBase_i* myGroupImpl =
03389                       dynamic_cast<SMESH_GroupBase_i*>( GetServant( aSubObject ).in() );
03390                     if ( !myGroupImpl )
03391                       continue;
03392                     SMESHDS_GroupBase* aGrpBaseDS = myGroupImpl->GetGroupDS();
03393                     if ( !aGrpBaseDS )
03394                       continue;
03395 
03396                     CORBA::String_var objStr = GetORB()->object_to_string( aSubObject );
03397                     int anId = myStudyContext->findId( string( objStr.in() ) );
03398 
03399                     // For each group, create a dataset named "Group <group_persistent_id>"
03400                     // and store the group's user name into it
03401                     const char* grpName = aGrpBaseDS->GetStoreName();
03402                     char* aUserName = myGroupImpl->GetName();
03403                     aSize[ 0 ] = strlen( aUserName ) + 1;
03404 
03405                     aDataset = new HDFdataset( grpName, aGroup, HDF_STRING, aSize, 1 );
03406                     aDataset->CreateOnDisk();
03407                     aDataset->WriteOnDisk( aUserName );
03408                     aDataset->CloseOnDisk();
03409 
03410                     // ouv : NPAL12872
03411                     // For each group, create a dataset named "Group <group_persistent_id> Color"
03412                     // and store the group's color into it
03413                     char grpColorName[ 30 ];
03414                     sprintf( grpColorName, "ColorGroup %d", anId );
03415                     SALOMEDS::Color aColor = myGroupImpl->GetColor();
03416                     double anRGB[3];
03417                     anRGB[ 0 ] = aColor.R;
03418                     anRGB[ 1 ] = aColor.G;
03419                     anRGB[ 2 ] = aColor.B;
03420                     aSize[ 0 ] = 3;
03421                     aDataset = new HDFdataset( grpColorName, aGroup, HDF_FLOAT64, aSize, 1 );
03422                     aDataset->CreateOnDisk();
03423                     aDataset->WriteOnDisk( anRGB );
03424                     aDataset->CloseOnDisk();
03425 
03426                     // Pass SMESHDS_Group to MED writer
03427                     SMESHDS_Group* aGrpDS = dynamic_cast<SMESHDS_Group*>( aGrpBaseDS );
03428                     if ( aGrpDS )
03429                       myWriter.AddGroup( aGrpDS );
03430 
03431                     // write reference on a shape if exists
03432                     SMESHDS_GroupOnGeom* aGeomGrp =
03433                       dynamic_cast<SMESHDS_GroupOnGeom*>( aGrpBaseDS );
03434                     if ( aGeomGrp ) {
03435                       SALOMEDS::SObject_var mySubRef, myShape;
03436                       if (mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef ) &&
03437                           mySubRef->ReferencedObject( myShape ) &&
03438                           !CORBA::is_nil( myShape->GetObject() ))
03439                       {
03440                         string myRefOnObject = myShape->GetID();
03441                         if ( myRefOnObject.length() > 0 ) {
03442                           char aRefName[ 30 ];
03443                           sprintf( aRefName, "Ref on shape %d", anId);
03444                           aSize[ 0 ] = myRefOnObject.length() + 1;
03445                           aDataset = new HDFdataset(aRefName, aGroup, HDF_STRING, aSize, 1);
03446                           aDataset->CreateOnDisk();
03447                           aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
03448                           aDataset->CloseOnDisk();
03449                         }
03450                       }
03451                       else // shape ref is invalid:
03452                       {
03453                         // save a group on geometry as ordinary group
03454                         myWriter.AddGroup( aGeomGrp );
03455                       }
03456                     }
03457                     else if ( SMESH_GroupOnFilter_i* aFilterGrp_i = 
03458                               dynamic_cast<SMESH_GroupOnFilter_i*>( myGroupImpl ))
03459                     {
03460                       std::string str = aFilterGrp_i->FilterToString();
03461                       std::string hdfGrpName = "Filter " + SMESH_Comment(anId);
03462                       aSize[ 0 ] = str.length() + 1;
03463                       aDataset = new HDFdataset( hdfGrpName.c_str(), aGroup, HDF_STRING, aSize, 1);
03464                       aDataset->CreateOnDisk();
03465                       aDataset->WriteOnDisk( ( char* )( str.c_str() ) );
03466                       aDataset->CloseOnDisk();
03467                     }
03468                   }
03469                 }
03470                 aGroup->CloseOnDisk();
03471               }
03472             } // loop on groups
03473 
03474             if ( strcmp( strHasData.c_str(), "1" ) == 0 )
03475             {
03476               // Flush current mesh information into MED file
03477               myWriter.Perform();
03478 
03479               // save info on nb of elements
03480               SMESH_PreMeshInfo::SaveToFile( myImpl, id, aFile );
03481 
03482               // maybe a shape was deleted in the study
03483               if ( !shapeRefFound && !mySMESHDSMesh->ShapeToMesh().IsNull() && hasShape) {
03484                 TopoDS_Shape nullShape;
03485                 myLocMesh.ShapeToMesh( nullShape ); // remove shape referring data
03486               }
03487 
03488               if ( !mySMESHDSMesh->SubMeshes().empty() )
03489               {
03490                 // Store submeshes
03491                 // ----------------
03492                 aGroup = new HDFgroup( "Submeshes", aTopGroup );
03493                 aGroup->CreateOnDisk();
03494 
03495                 // each element belongs to one or none submesh,
03496                 // so for each node/element, we store a submesh ID
03497 
03498                 // Make maps of submesh IDs of elements sorted by element IDs
03499                 typedef int TElemID;
03500                 typedef int TSubMID;
03501                 map< TElemID, TSubMID > eId2smId, nId2smId;
03502                 map< TElemID, TSubMID >::iterator hint; // insertion to map is done before hint
03503                 const map<int,SMESHDS_SubMesh*>& aSubMeshes = mySMESHDSMesh->SubMeshes();
03504                 map<int,SMESHDS_SubMesh*>::const_iterator itSubM ( aSubMeshes.begin() );
03505                 SMDS_NodeIteratorPtr itNode;
03506                 SMDS_ElemIteratorPtr itElem;
03507                 for ( itSubM = aSubMeshes.begin(); itSubM != aSubMeshes.end() ; itSubM++ )
03508                 {
03509                   TSubMID          aSubMeID = itSubM->first;
03510                   SMESHDS_SubMesh* aSubMesh = itSubM->second;
03511                   if ( aSubMesh->IsComplexSubmesh() )
03512                     continue; // submesh containing other submeshs
03513                   // nodes
03514                   hint = nId2smId.begin(); // optimize insertion basing on increasing order of elem Ids in submesh
03515                   for ( itNode = aSubMesh->GetNodes(); itNode->more(); ++hint)
03516                     hint = nId2smId.insert( hint, make_pair( itNode->next()->GetID(), aSubMeID ));
03517                   // elements
03518                   hint = eId2smId.begin();
03519                   for ( itElem = aSubMesh->GetElements(); itElem->more(); ++hint)
03520                     hint = eId2smId.insert( hint, make_pair( itElem->next()->GetID(), aSubMeID ));
03521                 }
03522 
03523                 // Care of elements that are not on submeshes
03524                 if ( mySMESHDSMesh->NbNodes() != nId2smId.size() ) {
03525                   for ( itNode = mySMESHDSMesh->nodesIterator(); itNode->more(); )
03526                     /*  --- stl_map.h says : */
03527                     /*  A %map relies on unique keys and thus a %pair is only inserted if its */
03528                     /*  first element (the key) is not already present in the %map.           */
03529                     nId2smId.insert( make_pair( itNode->next()->GetID(), 0 ));
03530                 }
03531                 int nbElems = mySMESHDSMesh->NbEdges() + mySMESHDSMesh->NbFaces() + mySMESHDSMesh->NbVolumes();
03532                 if ( nbElems != eId2smId.size() ) {
03533                   for ( itElem = mySMESHDSMesh->elementsIterator(); itElem->more(); )
03534                     eId2smId.insert( make_pair( itElem->next()->GetID(), 0 ));
03535                 }
03536 
03537                 // Store submesh IDs
03538                 for ( int isNode = 0; isNode < 2; ++isNode )
03539                 {
03540                   map< TElemID, TSubMID >& id2smId = isNode ? nId2smId : eId2smId;
03541                   if ( id2smId.empty() ) continue;
03542                   map< TElemID, TSubMID >::const_iterator id_smId = id2smId.begin();
03543                   // make and fill array of submesh IDs
03544                   int* smIDs = new int [ id2smId.size() ];
03545                   for ( int i = 0; id_smId != id2smId.end(); ++id_smId, ++i )
03546                     smIDs[ i ] = id_smId->second;
03547                   // write HDF group
03548                   aSize[ 0 ] = id2smId.size();
03549                   string aDSName( isNode ? "Node Submeshes" : "Element Submeshes");
03550                   aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_INT32, aSize, 1 );
03551                   aDataset->CreateOnDisk();
03552                   aDataset->WriteOnDisk( smIDs );
03553                   aDataset->CloseOnDisk();
03554                   //
03555                   delete[] smIDs;
03556                 }
03557 
03558                 aGroup->CloseOnDisk();
03559 
03560                 // Store node positions on sub-shapes (SMDS_Position):
03561                 // ----------------------------------------------------
03562 
03563                 aGroup = new HDFgroup( "Node Positions", aTopGroup );
03564                 aGroup->CreateOnDisk();
03565 
03566                 // in aGroup, create 5 datasets to contain:
03567                 // "Nodes on Edges" - ID of node on edge
03568                 // "Edge positions" - U parameter on node on edge
03569                 // "Nodes on Faces" - ID of node on face
03570                 // "Face U positions" - U parameter of node on face
03571                 // "Face V positions" - V parameter of node on face
03572 
03573                 // Find out nb of nodes on edges and faces
03574                 // Collect corresponing sub-meshes
03575                 int nbEdgeNodes = 0, nbFaceNodes = 0;
03576                 list<SMESHDS_SubMesh*> aEdgeSM, aFaceSM;
03577                 // loop on SMESHDS_SubMesh'es
03578                 for ( itSubM = aSubMeshes.begin(); itSubM != aSubMeshes.end() ; itSubM++ )
03579                 {
03580                   SMESHDS_SubMesh* aSubMesh = (*itSubM).second;
03581                   if ( aSubMesh->IsComplexSubmesh() )
03582                     continue; // submesh containing other submeshs
03583                   int nbNodes = aSubMesh->NbNodes();
03584                   if ( nbNodes == 0 ) continue;
03585 
03586                   int aShapeID = (*itSubM).first;
03587                   if ( aShapeID < 1 || aShapeID > mySMESHDSMesh->MaxShapeIndex() )
03588                     continue;
03589                   int aShapeType = mySMESHDSMesh->IndexToShape( aShapeID ).ShapeType();
03590                   // write only SMDS_FacePosition and SMDS_EdgePosition
03591                   switch ( aShapeType ) {
03592                   case TopAbs_FACE:
03593                     nbFaceNodes += nbNodes;
03594                     aFaceSM.push_back( aSubMesh );
03595                     break;
03596                   case TopAbs_EDGE:
03597                     nbEdgeNodes += nbNodes;
03598                     aEdgeSM.push_back( aSubMesh );
03599                     break;
03600                   default:
03601                     continue;
03602                   }
03603                 }
03604                 // Treat positions on edges or faces
03605                 for ( int onFace = 0; onFace < 2; onFace++ )
03606                 {
03607                   // Create arrays to store in datasets
03608                   int iNode = 0, nbNodes = ( onFace ? nbFaceNodes : nbEdgeNodes );
03609                   if (!nbNodes) continue;
03610                   int* aNodeIDs = new int [ nbNodes ];
03611                   double* aUPos = new double [ nbNodes ];
03612                   double* aVPos = ( onFace ? new double[ nbNodes ] : 0 );
03613 
03614                   // Fill arrays
03615                   // loop on sub-meshes
03616                   list<SMESHDS_SubMesh*> * pListSM = ( onFace ? &aFaceSM : &aEdgeSM );
03617                   list<SMESHDS_SubMesh*>::iterator itSM = pListSM->begin();
03618                   for ( ; itSM != pListSM->end(); itSM++ )
03619                   {
03620                     SMESHDS_SubMesh* aSubMesh = (*itSM);
03621 
03622                     SMDS_NodeIteratorPtr itNode = aSubMesh->GetNodes();
03623                     // loop on nodes in aSubMesh
03624                     while ( itNode->more() )
03625                     {
03626                       //node ID
03627                       const SMDS_MeshNode* node = itNode->next();
03628                       aNodeIDs [ iNode ] = node->GetID();
03629 
03630                       // Position
03631                       const SMDS_PositionPtr pos = node->GetPosition();
03632                       if ( onFace ) { // on FACE
03633                         const SMDS_FacePosition* fPos =
03634                           dynamic_cast<const SMDS_FacePosition*>( pos );
03635                         if ( fPos ) {
03636                           aUPos[ iNode ] = fPos->GetUParameter();
03637                           aVPos[ iNode ] = fPos->GetVParameter();
03638                           iNode++;
03639                         }
03640                         else
03641                           nbNodes--;
03642                       }
03643                       else { // on EDGE
03644                         const SMDS_EdgePosition* ePos =
03645                           dynamic_cast<const SMDS_EdgePosition*>( pos );
03646                         if ( ePos ) {
03647                           aUPos[ iNode ] = ePos->GetUParameter();
03648                           iNode++;
03649                         }
03650                         else
03651                           nbNodes--;
03652                       }
03653                     } // loop on nodes in aSubMesh
03654                   } // loop on sub-meshes
03655 
03656                   // Write datasets
03657                   if ( nbNodes )
03658                   {
03659                     aSize[ 0 ] = nbNodes;
03660                     // IDS
03661                     string aDSName( onFace ? "Nodes on Faces" : "Nodes on Edges");
03662                     aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_INT32, aSize, 1 );
03663                     aDataset->CreateOnDisk();
03664                     aDataset->WriteOnDisk( aNodeIDs );
03665                     aDataset->CloseOnDisk();
03666 
03667                     // U Positions
03668                     aDSName = ( onFace ? "Face U positions" : "Edge positions");
03669                     aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_FLOAT64, aSize, 1);
03670                     aDataset->CreateOnDisk();
03671                     aDataset->WriteOnDisk( aUPos );
03672                     aDataset->CloseOnDisk();
03673                     // V Positions
03674                     if ( onFace ) {
03675                       aDataset = new HDFdataset( "Face V positions", aGroup, HDF_FLOAT64, aSize, 1);
03676                       aDataset->CreateOnDisk();
03677                       aDataset->WriteOnDisk( aVPos );
03678                       aDataset->CloseOnDisk();
03679                     }
03680                   }
03681                   delete [] aNodeIDs;
03682                   delete [] aUPos;
03683                   if ( aVPos ) delete [] aVPos;
03684 
03685                 } // treat positions on edges or faces
03686 
03687                 // close "Node Positions" group
03688                 aGroup->CloseOnDisk();
03689 
03690               } // if ( there are submeshes in SMESHDS_Mesh )
03691             } // if ( hasData )
03692 
03693             // close mesh HDF group
03694             aTopGroup->CloseOnDisk();
03695           }
03696         }
03697       }
03698     }
03699   }
03700 
03701   // close HDF file
03702   aFile->CloseOnDisk();
03703   delete aFile;
03704 
03705   // Convert temporary files to stream
03706   aStreamFile = SALOMEDS_Tool::PutFilesToStream( tmpDir.ToCString(), aFileSeq.in(), isMultiFile );
03707 
03708   // Remove temporary files and directory
03709   if ( !isMultiFile )
03710     SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq.in(), true );
03711 
03712   INFOS( "SMESH_Gen_i::Save() completed" );
03713   return aStreamFile._retn();
03714 }
03715 
03716 //=============================================================================
03722 //=============================================================================
03723 
03724 SALOMEDS::TMPFile* SMESH_Gen_i::SaveASCII( SALOMEDS::SComponent_ptr theComponent,
03725                                            const char*              theURL,
03726                                            bool                     isMultiFile ) {
03727   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::SaveASCII" );
03728   SALOMEDS::TMPFile_var aStreamFile = Save( theComponent, theURL, isMultiFile );
03729   return aStreamFile._retn();
03730 
03731   //after usual saving needs to encipher binary to text string
03732   //Any binary symbol will be represent as "|xx" () hexadecimal format number
03733   int size = aStreamFile.in().length();
03734   _CORBA_Octet* buffer = new _CORBA_Octet[size*3+1];
03735   for ( int i = 0; i < size; i++ )
03736     sprintf( (char*)&(buffer[i*3]), "|%02x", aStreamFile[i] );
03737 
03738   buffer[size * 3] = '\0';
03739 
03740   SALOMEDS::TMPFile_var anAsciiStreamFile = new SALOMEDS::TMPFile(size*3, size*3, buffer, 1);
03741 
03742   return anAsciiStreamFile._retn();
03743 }
03744 
03745 //=============================================================================
03751 //=============================================================================
03752 
03753 void SMESH_Gen_i::loadGeomData( SALOMEDS::SComponent_ptr theCompRoot )
03754 {
03755   if ( theCompRoot->_is_nil() )
03756     return;
03757 
03758   SALOMEDS::Study_var aStudy = SALOMEDS::Study::_narrow( theCompRoot->GetStudy() );
03759   if ( aStudy->_is_nil() )
03760     return;
03761 
03762   SALOMEDS::StudyBuilder_var aStudyBuilder = aStudy->NewBuilder();
03763   aStudyBuilder->LoadWith( theCompRoot, GetGeomEngine() );
03764 }
03765 
03766 //=============================================================================
03772 //=============================================================================
03773 
03774 bool SMESH_Gen_i::Load( SALOMEDS::SComponent_ptr theComponent,
03775                         const SALOMEDS::TMPFile& theStream,
03776                         const char*              theURL,
03777                         bool                     isMultiFile )
03778 {
03779   INFOS( "SMESH_Gen_i::Load" );
03780 
03781   if ( myCurrentStudy->_is_nil() ||
03782        theComponent->GetStudy()->StudyId() != myCurrentStudy->StudyId() )
03783     SetCurrentStudy( theComponent->GetStudy() );
03784 
03785   /*  if( !theComponent->_is_nil() )
03786       {
03787       //SALOMEDS::Study_var aStudy = SALOMEDS::Study::_narrow( theComponent->GetStudy() );
03788       if( !myCurrentStudy->FindComponent( "GEOM" )->_is_nil() )
03789       loadGeomData( myCurrentStudy->FindComponent( "GEOM" ) );
03790       }*/
03791 
03792   StudyContext* myStudyContext = GetCurrentStudyContext();
03793 
03794   // Get temporary files location
03795   TCollection_AsciiString tmpDir =
03796     isMultiFile ? TCollection_AsciiString( ( char* )theURL ) : ( char* )SALOMEDS_Tool::GetTmpDir().c_str();
03797 
03798     INFOS( "THE URL++++++++++++++" )
03799     INFOS( theURL );
03800     INFOS( "THE TMP PATH+++++++++" );
03801     INFOS( tmpDir );
03802 
03803   // Convert the stream into sequence of files to process
03804   SALOMEDS::ListOfFileNames_var aFileSeq = SALOMEDS_Tool::PutStreamToFiles( theStream,
03805                                                                             tmpDir.ToCString(),
03806                                                                             isMultiFile );
03807   TCollection_AsciiString aStudyName( "" );
03808   if ( isMultiFile )
03809     aStudyName = ( (char*)SALOMEDS_Tool::GetNameFromPath( myCurrentStudy->URL() ).c_str() );
03810 
03811   // Set names of temporary files
03812   TCollection_AsciiString filename = tmpDir + aStudyName + TCollection_AsciiString( "_SMESH.hdf" );
03813   TCollection_AsciiString meshfile = tmpDir + aStudyName + TCollection_AsciiString( "_SMESH_Mesh.med" );
03814 
03815   int size;
03816   HDFfile*    aFile;
03817   HDFdataset* aDataset;
03818   HDFgroup*   aTopGroup;
03819   HDFgroup*   aGroup;
03820   HDFgroup*   aSubGroup;
03821   HDFgroup*   aSubSubGroup;
03822 
03823   // Read data
03824   // ---> open HDF file
03825   aFile = new HDFfile( (char*) filename.ToCString() );
03826   try {
03827     aFile->OpenOnDisk( HDF_RDONLY );
03828   }
03829   catch ( HDFexception ) {
03830     INFOS( "Load(): " << filename << " not found!" );
03831     return false;
03832   }
03833 
03834   TPythonDump pd; // prevent dump during loading
03835 
03836   // DriverMED_R_SMESHDS_Mesh myReader;
03837   // myReader.SetFile( meshfile.ToCString() );
03838 
03839   // For PAL13473 ("Repetitive mesh") implementation.
03840   // New dependencies between SMESH objects are established:
03841   // now hypotheses can refer to meshes, shapes and other hypotheses.
03842   // To keep data consistent, the following order of data restoration
03843   // imposed:
03844   // 1. Create hypotheses
03845   // 2. Create all meshes
03846   // 3. Load hypotheses' data
03847   // 4. All the rest
03848 
03849   list< pair< SMESH_Hypothesis_i*, string > >    hypDataList;
03850   list< pair< SMESH_Mesh_i*,       HDFgroup* > > meshGroupList;
03851 
03852   // get total number of top-level groups
03853   int aNbGroups = aFile->nInternalObjects();
03854   if ( aNbGroups > 0 ) {
03855     // --> in first turn we should read&create hypotheses
03856     if ( aFile->ExistInternalObject( "Hypotheses" ) ) {
03857       // open hypotheses root HDF group
03858       aTopGroup = new HDFgroup( "Hypotheses", aFile );
03859       aTopGroup->OpenOnDisk();
03860 
03861       // get number of hypotheses
03862       int aNbObjects = aTopGroup->nInternalObjects();
03863       for ( int j = 0; j < aNbObjects; j++ ) {
03864         // try to identify hypothesis
03865         char hypGrpName[ HDF_NAME_MAX_LEN+1 ];
03866         aTopGroup->InternalObjectIndentify( j, hypGrpName );
03867 
03868         if ( string( hypGrpName ).substr( 0, 10 ) == string( "Hypothesis" ) ) {
03869           // open hypothesis group
03870           aGroup = new HDFgroup( hypGrpName, aTopGroup );
03871           aGroup->OpenOnDisk();
03872 
03873           // --> get hypothesis id
03874           int    id = atoi( string( hypGrpName ).substr( 10 ).c_str() );
03875           string hypname;
03876           string libname;
03877           string hypdata;
03878 
03879           // get number of datasets
03880           int aNbSubObjects = aGroup->nInternalObjects();
03881           for ( int k = 0; k < aNbSubObjects; k++ ) {
03882             // identify dataset
03883             char name_of_subgroup[ HDF_NAME_MAX_LEN+1 ];
03884             aGroup->InternalObjectIndentify( k, name_of_subgroup );
03885             // --> get hypothesis name
03886             if ( strcmp( name_of_subgroup, "Name"  ) == 0 ) {
03887               aDataset = new HDFdataset( name_of_subgroup, aGroup );
03888               aDataset->OpenOnDisk();
03889               size = aDataset->GetSize();
03890               char* hypname_str = new char[ size ];
03891               aDataset->ReadFromDisk( hypname_str );
03892               hypname = string( hypname_str );
03893               delete [] hypname_str;
03894               aDataset->CloseOnDisk();
03895             }
03896             // --> get hypothesis plugin library name
03897             if ( strcmp( name_of_subgroup, "LibName"  ) == 0 ) {
03898               aDataset = new HDFdataset( name_of_subgroup, aGroup );
03899               aDataset->OpenOnDisk();
03900               size = aDataset->GetSize();
03901               char* libname_str = new char[ size ];
03902               aDataset->ReadFromDisk( libname_str );
03903               if(MYDEBUG) SCRUTE( libname_str );
03904               libname = string( libname_str );
03905               delete [] libname_str;
03906               aDataset->CloseOnDisk();
03907             }
03908             // --> get hypothesis data
03909             if ( strcmp( name_of_subgroup, "Data"  ) == 0 ) {
03910               aDataset = new HDFdataset( name_of_subgroup, aGroup );
03911               aDataset->OpenOnDisk();
03912               size = aDataset->GetSize();
03913               char* hypdata_str = new char[ size ];
03914               aDataset->ReadFromDisk( hypdata_str );
03915               hypdata = string( hypdata_str );
03916               delete [] hypdata_str;
03917               aDataset->CloseOnDisk();
03918             }
03919           }
03920           // close hypothesis HDF group
03921           aGroup->CloseOnDisk();
03922 
03923           // --> restore hypothesis from data
03924           if ( id > 0 && !hypname.empty()/* && !hypdata.empty()*/ ) { // VSR : persistent data can be empty
03925             if(MYDEBUG) MESSAGE("VSR - load hypothesis : id = " << id <<
03926                                 ", name = " << hypname.c_str() << ", persistent string = " << hypdata.c_str());
03927             SMESH::SMESH_Hypothesis_var myHyp;
03928 
03929             try { // protect persistence mechanism against exceptions
03930               myHyp = this->createHypothesis( hypname.c_str(), libname.c_str() );
03931             }
03932             catch (...) {
03933               INFOS( "Exception during hypothesis creation" );
03934             }
03935 
03936             SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
03937             if ( myImpl ) {
03938               // myImpl->LoadFrom( hypdata.c_str() );
03939               hypDataList.push_back( make_pair( myImpl, hypdata ));
03940               string iorString = GetORB()->object_to_string( myHyp );
03941               int newId = myStudyContext->findId( iorString );
03942               myStudyContext->mapOldToNew( id, newId );
03943             }
03944             else
03945               if(MYDEBUG) MESSAGE( "VSR - SMESH_Gen::Load - can't get servant" );
03946           }
03947         }
03948       }
03949       // close hypotheses root HDF group
03950       aTopGroup->CloseOnDisk();
03951       aTopGroup = 0;
03952     }
03953 
03954     // --> then we should read&create algorithms
03955     if ( aFile->ExistInternalObject( "Algorithms" ) ) {
03956       // open algorithms root HDF group
03957       aTopGroup = new HDFgroup( "Algorithms", aFile );
03958       aTopGroup->OpenOnDisk();
03959 
03960       // get number of algorithms
03961       int aNbObjects = aTopGroup->nInternalObjects();
03962       for ( int j = 0; j < aNbObjects; j++ ) {
03963         // try to identify algorithm
03964         char hypGrpName[ HDF_NAME_MAX_LEN+1 ];
03965         aTopGroup->InternalObjectIndentify( j, hypGrpName );
03966 
03967         if ( string( hypGrpName ).substr( 0, 9 ) == string( "Algorithm" ) ) {
03968           // open algorithm group
03969           aGroup = new HDFgroup( hypGrpName, aTopGroup );
03970           aGroup->OpenOnDisk();
03971 
03972           // --> get algorithm id
03973           int    id = atoi( string( hypGrpName ).substr( 9 ).c_str() );
03974           string hypname;
03975           string libname;
03976           string hypdata;
03977 
03978           // get number of datasets
03979           int aNbSubObjects = aGroup->nInternalObjects();
03980           for ( int k = 0; k < aNbSubObjects; k++ ) {
03981             // identify dataset
03982             char name_of_subgroup[ HDF_NAME_MAX_LEN+1 ];
03983             aGroup->InternalObjectIndentify( k, name_of_subgroup );
03984             // --> get algorithm name
03985             if ( strcmp( name_of_subgroup, "Name"  ) == 0 ) {
03986               aDataset = new HDFdataset( name_of_subgroup, aGroup );
03987               aDataset->OpenOnDisk();
03988               size = aDataset->GetSize();
03989               char* hypname_str = new char[ size ];
03990               aDataset->ReadFromDisk( hypname_str );
03991               hypname = string( hypname_str );
03992               delete [] hypname_str;
03993               aDataset->CloseOnDisk();
03994             }
03995             // --> get algorithm plugin library name
03996             if ( strcmp( name_of_subgroup, "LibName"  ) == 0 ) {
03997               aDataset = new HDFdataset( name_of_subgroup, aGroup );
03998               aDataset->OpenOnDisk();
03999               size = aDataset->GetSize();
04000               char* libname_str = new char[ size ];
04001               aDataset->ReadFromDisk( libname_str );
04002               if(MYDEBUG) SCRUTE( libname_str );
04003               libname = string( libname_str );
04004               delete [] libname_str;
04005               aDataset->CloseOnDisk();
04006             }
04007             // --> get algorithm data
04008             if ( strcmp( name_of_subgroup, "Data"  ) == 0 ) {
04009               aDataset = new HDFdataset( name_of_subgroup, aGroup );
04010               aDataset->OpenOnDisk();
04011               size = aDataset->GetSize();
04012               char* hypdata_str = new char[ size ];
04013               aDataset->ReadFromDisk( hypdata_str );
04014               if(MYDEBUG) SCRUTE( hypdata_str );
04015               hypdata = string( hypdata_str );
04016               delete [] hypdata_str;
04017               aDataset->CloseOnDisk();
04018             }
04019           }
04020           // close algorithm HDF group
04021           aGroup->CloseOnDisk();
04022 
04023           // --> restore algorithm from data
04024           if ( id > 0 && !hypname.empty()/* && !hypdata.empty()*/ ) { // VSR : persistent data can be empty
04025             if(MYDEBUG) MESSAGE("VSR - load algo : id = " << id <<
04026                                 ", name = " << hypname.c_str() << ", persistent string = " << hypdata.c_str());
04027             SMESH::SMESH_Hypothesis_var myHyp;
04028 
04029             try { // protect persistence mechanism against exceptions
04030               myHyp = this->createHypothesis( hypname.c_str(), libname.c_str() );
04031             }
04032             catch (...) {
04033               INFOS( "Exception during hypothesis creation" );
04034             }
04035 
04036             SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
04037             if ( myImpl ) {
04038               //myImpl->LoadFrom( hypdata.c_str() );
04039               hypDataList.push_back( make_pair( myImpl, hypdata ));
04040               string iorString = GetORB()->object_to_string( myHyp );
04041               int newId = myStudyContext->findId( iorString );
04042               myStudyContext->mapOldToNew( id, newId );
04043             }
04044             else
04045               if(MYDEBUG) MESSAGE( "VSR - SMESH_Gen::Load - can't get servant" );
04046           }
04047         }
04048       }
04049       // close algorithms root HDF group
04050       aTopGroup->CloseOnDisk();
04051       aTopGroup = 0;
04052     }
04053 
04054     // --> the rest groups should be meshes
04055     for ( int i = 0; i < aNbGroups; i++ ) {
04056       // identify next group
04057       char meshName[ HDF_NAME_MAX_LEN+1 ];
04058       aFile->InternalObjectIndentify( i, meshName );
04059 
04060       if ( string( meshName ).substr( 0, 4 ) == string( "Mesh" ) ) {
04061         // --> get mesh id
04062         int id = atoi( string( meshName ).substr( 4 ).c_str() );
04063         if ( id <= 0 )
04064           continue;
04065 
04066         // open mesh HDF group
04067         aTopGroup = new HDFgroup( meshName, aFile );
04068         aTopGroup->OpenOnDisk();
04069 
04070         // get number of child HDF objects
04071         int aNbObjects = aTopGroup->nInternalObjects();
04072         if ( aNbObjects > 0 ) {
04073           // create mesh
04074           if(MYDEBUG) MESSAGE( "VSR - load mesh : id = " << id );
04075           SMESH::SMESH_Mesh_var myNewMesh = this->createMesh();
04076           SMESH_Mesh_i* myNewMeshImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( myNewMesh ).in() );
04077           if ( !myNewMeshImpl )
04078             continue;
04079           meshGroupList.push_back( make_pair( myNewMeshImpl, aTopGroup ));
04080 
04081           string iorString = GetORB()->object_to_string( myNewMesh );
04082           int newId = myStudyContext->findId( iorString );
04083           myStudyContext->mapOldToNew( id, newId );
04084 
04085           // ouv : NPAL12872
04086           // try to read and set auto color flag
04087           char aMeshAutoColorName[ 30 ];
04088           sprintf( aMeshAutoColorName, "AutoColorMesh %d", id);
04089           if( aTopGroup->ExistInternalObject( aMeshAutoColorName ) )
04090           {
04091             aDataset = new HDFdataset( aMeshAutoColorName, aTopGroup );
04092             aDataset->OpenOnDisk();
04093             size = aDataset->GetSize();
04094             int* anAutoColor = new int[ size ];
04095             aDataset->ReadFromDisk( anAutoColor );
04096             aDataset->CloseOnDisk();
04097             myNewMeshImpl->GetImpl().SetAutoColor( (bool)anAutoColor[0] );
04098           }
04099 
04100           // try to read and set reference to shape
04101           GEOM::GEOM_Object_var aShapeObject;
04102           if ( aTopGroup->ExistInternalObject( "Ref on shape" ) ) {
04103             // load mesh "Ref on shape" - it's an entry to SObject
04104             aDataset = new HDFdataset( "Ref on shape", aTopGroup );
04105             aDataset->OpenOnDisk();
04106             size = aDataset->GetSize();
04107             char* refFromFile = new char[ size ];
04108             aDataset->ReadFromDisk( refFromFile );
04109             aDataset->CloseOnDisk();
04110             if ( strlen( refFromFile ) > 0 ) {
04111               SALOMEDS::SObject_var shapeSO = myCurrentStudy->FindObjectID( refFromFile );
04112 
04113               // Make sure GEOM data are loaded first
04114               //loadGeomData( shapeSO->GetFatherComponent() );
04115 
04116               CORBA::Object_var shapeObject = SObjectToObject( shapeSO );
04117               if ( !CORBA::is_nil( shapeObject ) ) {
04118                 aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
04119                 if ( !aShapeObject->_is_nil() )
04120                   myNewMeshImpl->SetShape( aShapeObject );
04121               }
04122             }
04123           }
04124 
04125           // issue 0020693. Restore _isModified flag
04126           if( aTopGroup->ExistInternalObject( "_isModified" ) )
04127           {
04128             aDataset = new HDFdataset( "_isModified", aTopGroup );
04129             aDataset->OpenOnDisk();
04130             size = aDataset->GetSize();
04131             int* isModified = new int[ size ];
04132             aDataset->ReadFromDisk( isModified );
04133             aDataset->CloseOnDisk();
04134             myNewMeshImpl->GetImpl().SetIsModified( bool(*isModified));
04135           }
04136 
04137           // issue 20918. Restore Persistent Id of SMESHDS_Mesh
04138           if( aTopGroup->ExistInternalObject( "meshPersistentId" ) )
04139           {
04140             aDataset = new HDFdataset( "meshPersistentId", aTopGroup );
04141             aDataset->OpenOnDisk();
04142             size = aDataset->GetSize();
04143             int* meshPersistentId = new int[ size ];
04144             aDataset->ReadFromDisk( meshPersistentId );
04145             aDataset->CloseOnDisk();
04146             myNewMeshImpl->GetImpl().GetMeshDS()->SetPersistentId( *meshPersistentId );
04147           }
04148         }
04149       }
04150     } // reading MESHes
04151 
04152     // As all object that can be referred by hypothesis are created,
04153     // we can restore hypothesis data
04154 
04155     list< pair< SMESH_Hypothesis_i*, string > >::iterator hyp_data;
04156     for ( hyp_data = hypDataList.begin(); hyp_data != hypDataList.end(); ++hyp_data )
04157     {
04158       SMESH_Hypothesis_i* hyp  = hyp_data->first;
04159       string &            data = hyp_data->second;
04160       hyp->LoadFrom( data.c_str() );
04161     }
04162 
04163     // Restore the rest mesh data
04164 
04165     list< pair< SMESH_Mesh_i*, HDFgroup* > >::iterator meshi_group;
04166     for ( meshi_group = meshGroupList.begin(); meshi_group != meshGroupList.end(); ++meshi_group )
04167     {
04168       aTopGroup                   = meshi_group->second;
04169       SMESH_Mesh_i* myNewMeshImpl = meshi_group->first;
04170       //::SMESH_Mesh& myLocMesh     = myNewMeshImpl->GetImpl();
04171       //SMESHDS_Mesh* mySMESHDSMesh = myLocMesh.GetMeshDS();
04172 
04173       GEOM::GEOM_Object_var aShapeObject = myNewMeshImpl->GetShapeToMesh();
04174       bool hasData = false;
04175 
04176       // get mesh old id
04177       string iorString = GetORB()->object_to_string( myNewMeshImpl->_this() );
04178       int newId = myStudyContext->findId( iorString );
04179       int id = myStudyContext->getOldId( newId );
04180 
04181       // try to find mesh data dataset
04182       if ( aTopGroup->ExistInternalObject( "Has data" ) ) {
04183         // load mesh "has data" flag
04184         aDataset = new HDFdataset( "Has data", aTopGroup );
04185         aDataset->OpenOnDisk();
04186         size = aDataset->GetSize();
04187         char* strHasData = new char[ size ];
04188         aDataset->ReadFromDisk( strHasData );
04189         aDataset->CloseOnDisk();
04190         if ( strcmp( strHasData, "1") == 0 ) {
04191           // read mesh data from MED file
04192           // myReader.SetMesh( mySMESHDSMesh );
04193           // myReader.SetMeshId( id );
04194           // myReader.Perform();
04195           hasData = true;
04196         }
04197       }
04198 
04199       // Try to get applied ALGORITHMS (mesh is not cleared by algo addition because
04200       // nodes and elements are not yet put into sub-meshes)
04201       if ( aTopGroup->ExistInternalObject( "Applied Algorithms" ) ) {
04202         aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
04203         aGroup->OpenOnDisk();
04204         // get number of applied algorithms
04205         int aNbSubObjects = aGroup->nInternalObjects();
04206         if(MYDEBUG) MESSAGE( "VSR - number of applied algos " << aNbSubObjects );
04207         for ( int j = 0; j < aNbSubObjects; j++ ) {
04208           char name_dataset[ HDF_NAME_MAX_LEN+1 ];
04209           aGroup->InternalObjectIndentify( j, name_dataset );
04210           // check if it is an algorithm
04211           if ( string( name_dataset ).substr( 0, 4 ) == string( "Algo" ) ) {
04212             aDataset = new HDFdataset( name_dataset, aGroup );
04213             aDataset->OpenOnDisk();
04214             size = aDataset->GetSize();
04215             char* refFromFile = new char[ size ];
04216             aDataset->ReadFromDisk( refFromFile );
04217             aDataset->CloseOnDisk();
04218             // san - it is impossible to recover applied algorithms using their entries within Load() method
04219             //SALOMEDS::SObject_var hypSO = myCurrentStudy->FindObjectID( refFromFile );
04220             //CORBA::Object_var hypObject = SObjectToObject( hypSO );
04221             int id = atoi( refFromFile );
04222             string anIOR = myStudyContext->getIORbyOldId( id );
04223             if ( !anIOR.empty() ) {
04224               CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
04225               if ( !CORBA::is_nil( hypObject ) ) {
04226                 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
04227                 if ( !anHyp->_is_nil() && (!aShapeObject->_is_nil()
04228                                            || !myNewMeshImpl->HasShapeToMesh()) )
04229                   myNewMeshImpl->addHypothesis( aShapeObject, anHyp );
04230               }
04231             }
04232           }
04233         }
04234         aGroup->CloseOnDisk();
04235       }
04236 
04237       // try to get applied hypotheses
04238       if ( aTopGroup->ExistInternalObject( "Applied Hypotheses" ) ) {
04239         aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
04240         aGroup->OpenOnDisk();
04241         // get number of applied hypotheses
04242         int aNbSubObjects = aGroup->nInternalObjects();
04243         for ( int j = 0; j < aNbSubObjects; j++ ) {
04244           char name_dataset[ HDF_NAME_MAX_LEN+1 ];
04245           aGroup->InternalObjectIndentify( j, name_dataset );
04246           // check if it is a hypothesis
04247           if ( string( name_dataset ).substr( 0, 3 ) == string( "Hyp" ) ) {
04248             aDataset = new HDFdataset( name_dataset, aGroup );
04249             aDataset->OpenOnDisk();
04250             size = aDataset->GetSize();
04251             char* refFromFile = new char[ size ];
04252             aDataset->ReadFromDisk( refFromFile );
04253             aDataset->CloseOnDisk();
04254             // san - it is impossible to recover applied hypotheses using their entries within Load() method
04255             //SALOMEDS::SObject_var hypSO = myCurrentStudy->FindObjectID( refFromFile );
04256             //CORBA::Object_var hypObject = SObjectToObject( hypSO );
04257             int id = atoi( refFromFile );
04258             string anIOR = myStudyContext->getIORbyOldId( id );
04259             if ( !anIOR.empty() ) {
04260               CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
04261               if ( !CORBA::is_nil( hypObject ) ) {
04262                 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
04263                 if ( !anHyp->_is_nil() && (!aShapeObject->_is_nil()
04264                                            || !myNewMeshImpl->HasShapeToMesh()) )
04265                   myNewMeshImpl->addHypothesis( aShapeObject, anHyp );
04266               }
04267             }
04268           }
04269         }
04270         aGroup->CloseOnDisk();
04271       }
04272 
04273       // --> try to find SUB-MESHES containers for each type of submesh
04274       for ( int j = GetSubMeshOnVertexTag(); j <= GetSubMeshOnCompoundTag(); j++ ) {
04275         char name_meshgroup[ 30 ];
04276         if ( j == GetSubMeshOnVertexTag() )
04277           strcpy( name_meshgroup, "SubMeshes On Vertex" );
04278         else if ( j == GetSubMeshOnEdgeTag() )
04279           strcpy( name_meshgroup, "SubMeshes On Edge" );
04280         else if ( j == GetSubMeshOnWireTag() )
04281           strcpy( name_meshgroup, "SubMeshes On Wire" );
04282         else if ( j == GetSubMeshOnFaceTag() )
04283           strcpy( name_meshgroup, "SubMeshes On Face" );
04284         else if ( j == GetSubMeshOnShellTag() )
04285           strcpy( name_meshgroup, "SubMeshes On Shell" );
04286         else if ( j == GetSubMeshOnSolidTag() )
04287           strcpy( name_meshgroup, "SubMeshes On Solid" );
04288         else if ( j == GetSubMeshOnCompoundTag() )
04289           strcpy( name_meshgroup, "SubMeshes On Compound" );
04290 
04291         // try to get submeshes container HDF group
04292         if ( aTopGroup->ExistInternalObject( name_meshgroup ) ) {
04293           // open submeshes containers HDF group
04294           aGroup = new HDFgroup( name_meshgroup, aTopGroup );
04295           aGroup->OpenOnDisk();
04296 
04297           // get number of submeshes
04298           int aNbSubMeshes = aGroup->nInternalObjects();
04299           for ( int k = 0; k < aNbSubMeshes; k++ ) {
04300             // identify submesh
04301             char name_submeshgroup[ HDF_NAME_MAX_LEN+1 ];
04302             aGroup->InternalObjectIndentify( k, name_submeshgroup );
04303             if ( string( name_submeshgroup ).substr( 0, 7 ) == string( "SubMesh" )  ) {
04304               // --> get submesh id
04305               int subid = atoi( string( name_submeshgroup ).substr( 7 ).c_str() );
04306               if ( subid <= 0 )
04307                 continue;
04308               // open submesh HDF group
04309               aSubGroup = new HDFgroup( name_submeshgroup, aGroup );
04310               aSubGroup->OpenOnDisk();
04311 
04312               // try to read and set reference to subshape
04313               GEOM::GEOM_Object_var aSubShapeObject;
04314               SMESH::SMESH_subMesh_var aSubMesh;
04315 
04316               if ( aSubGroup->ExistInternalObject( "Ref on shape" ) ) {
04317                 // load submesh "Ref on shape" - it's an entry to SObject
04318                 aDataset = new HDFdataset( "Ref on shape", aSubGroup );
04319                 aDataset->OpenOnDisk();
04320                 size = aDataset->GetSize();
04321                 char* refFromFile = new char[ size ];
04322                 aDataset->ReadFromDisk( refFromFile );
04323                 aDataset->CloseOnDisk();
04324                 if ( strlen( refFromFile ) > 0 ) {
04325                   SALOMEDS::SObject_var subShapeSO = myCurrentStudy->FindObjectID( refFromFile );
04326                   CORBA::Object_var subShapeObject = SObjectToObject( subShapeSO );
04327                   if ( !CORBA::is_nil( subShapeObject ) ) {
04328                     aSubShapeObject = GEOM::GEOM_Object::_narrow( subShapeObject );
04329                     if ( !aSubShapeObject->_is_nil() )
04330                       aSubMesh = SMESH::SMESH_subMesh::_duplicate
04331                         ( myNewMeshImpl->createSubMesh( aSubShapeObject ) );
04332                     if ( aSubMesh->_is_nil() )
04333                       continue;
04334                     string iorSubString = GetORB()->object_to_string( aSubMesh );
04335                     int newSubId = myStudyContext->findId( iorSubString );
04336                     myStudyContext->mapOldToNew( subid, newSubId );
04337                   }
04338                 }
04339               }
04340 
04341               if ( aSubMesh->_is_nil() )
04342                 continue;
04343 
04344               // try to get applied algorithms
04345               if ( aSubGroup->ExistInternalObject( "Applied Algorithms" ) ) {
04346                 // open "applied algorithms" HDF group
04347                 aSubSubGroup = new HDFgroup( "Applied Algorithms", aSubGroup );
04348                 aSubSubGroup->OpenOnDisk();
04349                 // get number of applied algorithms
04350                 int aNbSubObjects = aSubSubGroup->nInternalObjects();
04351                 for ( int l = 0; l < aNbSubObjects; l++ ) {
04352                   char name_dataset[ HDF_NAME_MAX_LEN+1 ];
04353                   aSubSubGroup->InternalObjectIndentify( l, name_dataset );
04354                   // check if it is an algorithm
04355                   if ( string( name_dataset ).substr( 0, 4 ) == string( "Algo" ) ) {
04356                     aDataset = new HDFdataset( name_dataset, aSubSubGroup );
04357                     aDataset->OpenOnDisk();
04358                     size = aDataset->GetSize();
04359                     char* refFromFile = new char[ size ];
04360                     aDataset->ReadFromDisk( refFromFile );
04361                     aDataset->CloseOnDisk();
04362 
04363                     int id = atoi( refFromFile );
04364                     string anIOR = myStudyContext->getIORbyOldId( id );
04365                     if ( !anIOR.empty() ) {
04366                       CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
04367                       if ( !CORBA::is_nil( hypObject ) ) {
04368                         SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
04369                         if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
04370                           myNewMeshImpl->addHypothesis( aSubShapeObject, anHyp );
04371                       }
04372                     }
04373                   }
04374                 }
04375                 // close "applied algorithms" HDF group
04376                 aSubSubGroup->CloseOnDisk();
04377               }
04378 
04379               // try to get applied hypotheses
04380               if ( aSubGroup->ExistInternalObject( "Applied Hypotheses" ) ) {
04381                 // open "applied hypotheses" HDF group
04382                 aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
04383                 aSubSubGroup->OpenOnDisk();
04384                 // get number of applied hypotheses
04385                 int aNbSubObjects = aSubSubGroup->nInternalObjects();
04386                 for ( int l = 0; l < aNbSubObjects; l++ ) {
04387                   char name_dataset[ HDF_NAME_MAX_LEN+1 ];
04388                   aSubSubGroup->InternalObjectIndentify( l, name_dataset );
04389                   // check if it is a hypothesis
04390                   if ( string( name_dataset ).substr( 0, 3 ) == string( "Hyp" ) ) {
04391                     aDataset = new HDFdataset( name_dataset, aSubSubGroup );
04392                     aDataset->OpenOnDisk();
04393                     size = aDataset->GetSize();
04394                     char* refFromFile = new char[ size ];
04395                     aDataset->ReadFromDisk( refFromFile );
04396                     aDataset->CloseOnDisk();
04397 
04398                     int id = atoi( refFromFile );
04399                     string anIOR = myStudyContext->getIORbyOldId( id );
04400                     if ( !anIOR.empty() ) {
04401                       CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
04402                       if ( !CORBA::is_nil( hypObject ) ) {
04403                         SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
04404                         if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
04405                           myNewMeshImpl->addHypothesis( aSubShapeObject, anHyp );
04406                       }
04407                     }
04408                   }
04409                 }
04410                 // close "APPLIED HYPOTHESES" hdf group
04411                 aSubSubGroup->CloseOnDisk();
04412               }
04413 
04414               // close SUB-MESH hdf group
04415               aSubGroup->CloseOnDisk();
04416             }
04417           }
04418           // close SUB-MESHES containers hdf group
04419           aGroup->CloseOnDisk();
04420         }
04421       }
04422 
04423       // try to get GROUPS
04424       for ( int ii = GetNodeGroupsTag(); ii <= Get0DElementsGroupsTag(); ii++ ) {
04425         char name_group[ 30 ];
04426         if ( ii == GetNodeGroupsTag() )
04427           strcpy( name_group, "Groups of Nodes" );
04428         else if ( ii == GetEdgeGroupsTag() )
04429           strcpy( name_group, "Groups of Edges" );
04430         else if ( ii == GetFaceGroupsTag() )
04431           strcpy( name_group, "Groups of Faces" );
04432         else if ( ii == GetVolumeGroupsTag() )
04433           strcpy( name_group, "Groups of Volumes" );
04434         else if ( ii == Get0DElementsGroupsTag() )
04435           strcpy( name_group, "Groups of 0D Elements" );
04436 
04437         if ( aTopGroup->ExistInternalObject( name_group ) ) {
04438           aGroup = new HDFgroup( name_group, aTopGroup );
04439           aGroup->OpenOnDisk();
04440           // get number of groups
04441           int aNbSubObjects = aGroup->nInternalObjects();
04442           for ( int j = 0; j < aNbSubObjects; j++ ) {
04443             char name_dataset[ HDF_NAME_MAX_LEN+1 ];
04444             aGroup->InternalObjectIndentify( j, name_dataset );
04445             // check if it is an group
04446             if ( string( name_dataset ).substr( 0, 5 ) == string( "Group" ) ) {
04447               // --> get group id
04448               int subid = atoi( string( name_dataset ).substr( 5 ).c_str() );
04449               if ( subid <= 0 )
04450                 continue;
04451               aDataset = new HDFdataset( name_dataset, aGroup );
04452               aDataset->OpenOnDisk();
04453 
04454               // Retrieve actual group name
04455               size = aDataset->GetSize();
04456               char* nameFromFile = new char[ size ];
04457               aDataset->ReadFromDisk( nameFromFile );
04458               aDataset->CloseOnDisk();
04459 
04460               // Try to find a shape reference
04461               TopoDS_Shape aShape;
04462               char aRefName[ 30 ];
04463               sprintf( aRefName, "Ref on shape %d", subid);
04464               if ( aGroup->ExistInternalObject( aRefName ) ) {
04465                 // load mesh "Ref on shape" - it's an entry to SObject
04466                 aDataset = new HDFdataset( aRefName, aGroup );
04467                 aDataset->OpenOnDisk();
04468                 size = aDataset->GetSize();
04469                 char* refFromFile = new char[ size ];
04470                 aDataset->ReadFromDisk( refFromFile );
04471                 aDataset->CloseOnDisk();
04472                 if ( strlen( refFromFile ) > 0 ) {
04473                   SALOMEDS::SObject_var shapeSO = myCurrentStudy->FindObjectID( refFromFile );
04474                   CORBA::Object_var shapeObject = SObjectToObject( shapeSO );
04475                   if ( !CORBA::is_nil( shapeObject ) ) {
04476                     aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
04477                     if ( !aShapeObject->_is_nil() )
04478                       aShape = GeomObjectToShape( aShapeObject );
04479                   }
04480                 }
04481               }
04482               // Try to read a filter of SMESH_GroupOnFilter
04483               SMESH::Filter_var filter;
04484               SMESH_PredicatePtr predicate;
04485               std::string hdfGrpName = "Filter " + SMESH_Comment(subid);
04486               if ( aGroup->ExistInternalObject( hdfGrpName.c_str() ))
04487               {
04488                 aDataset = new HDFdataset( hdfGrpName.c_str(), aGroup );
04489                 aDataset->OpenOnDisk();
04490                 size = aDataset->GetSize();
04491                 char* persistStr = new char[ size ];
04492                 aDataset->ReadFromDisk( persistStr );
04493                 aDataset->CloseOnDisk();
04494                 if ( strlen( persistStr ) > 0 ) {
04495                   filter = SMESH_GroupOnFilter_i::StringToFilter( persistStr );
04496                   predicate = SMESH_GroupOnFilter_i::GetPredicate( filter );
04497                 }
04498               }
04499 
04500               // Create group servant
04501               SMESH::ElementType type = (SMESH::ElementType)(ii - GetNodeGroupsTag() + 1);
04502               SMESH::SMESH_GroupBase_var aNewGroup = SMESH::SMESH_GroupBase::_duplicate
04503                 ( myNewMeshImpl->createGroup( type, nameFromFile, aShape, predicate ) );
04504               // Obtain a SMESHDS_Group object
04505               if ( aNewGroup->_is_nil() )
04506                 continue;
04507 
04508               string iorSubString = GetORB()->object_to_string( aNewGroup );
04509               int newSubId = myStudyContext->findId( iorSubString );
04510               myStudyContext->mapOldToNew( subid, newSubId );
04511 
04512               SMESH_GroupBase_i* aGroupImpl = SMESH::DownCast< SMESH_GroupBase_i*>( aNewGroup );
04513               if ( !aGroupImpl )
04514                 continue;
04515 
04516               if ( SMESH_GroupOnFilter_i* aFilterGroup =
04517                    dynamic_cast< SMESH_GroupOnFilter_i*>( aGroupImpl ))
04518                 aFilterGroup->SetFilter( filter );
04519 
04520               SMESHDS_GroupBase* aGroupBaseDS = aGroupImpl->GetGroupDS();
04521               if ( !aGroupBaseDS )
04522                 continue;
04523 
04524               aGroupBaseDS->SetStoreName( name_dataset );
04525 
04526               // ouv : NPAL12872
04527               // Read color of the group
04528               char aGroupColorName[ 30 ];
04529               sprintf( aGroupColorName, "ColorGroup %d", subid);
04530               if ( aGroup->ExistInternalObject( aGroupColorName ) )
04531               {
04532                 aDataset = new HDFdataset( aGroupColorName, aGroup );
04533                 aDataset->OpenOnDisk();
04534                 size = aDataset->GetSize();
04535                 double* anRGB = new double[ size ];
04536                 aDataset->ReadFromDisk( anRGB );
04537                 aDataset->CloseOnDisk();
04538                 Quantity_Color aColor( anRGB[0], anRGB[1], anRGB[2], Quantity_TOC_RGB );
04539                 aGroupBaseDS->SetColor( aColor );
04540               }
04541 
04542               // Fill group with contents from MED file
04543               // SMESHDS_Group* aGrp = dynamic_cast<SMESHDS_Group*>( aGroupBaseDS );
04544               // if ( aGrp )
04545               //   myReader.GetGroup( aGrp );
04546             }
04547           }
04548           aGroup->CloseOnDisk();
04549         }
04550       } // reading GROUPs
04551 
04552       // instead of reading mesh data, we read only brief information of all
04553       // objects: mesh, groups, sub-meshes (issue 0021208 )
04554       if ( hasData )
04555       {
04556         SMESH_PreMeshInfo::LoadFromFile( myNewMeshImpl, id,
04557                                          meshfile.ToCString(), filename.ToCString(),
04558                                          !isMultiFile );
04559       }
04560 
04561       // read Sub-Mesh ORDER if any
04562       if( aTopGroup->ExistInternalObject( "Mesh Order" ) ) {
04563         aDataset = new HDFdataset( "Mesh Order", aTopGroup );
04564         aDataset->OpenOnDisk();
04565         size = aDataset->GetSize();
04566         int* smIDs = new int[ size ];
04567         aDataset->ReadFromDisk( smIDs );
04568         aDataset->CloseOnDisk();
04569         TListOfListOfInt anOrderIds;
04570         anOrderIds.push_back( TListOfInt() );
04571         for ( int i = 0; i < size; i++ )
04572           if ( smIDs[ i ] < 0 ) // is separator
04573             anOrderIds.push_back( TListOfInt() );
04574           else
04575             anOrderIds.back().push_back(smIDs[ i ]);
04576 
04577         myNewMeshImpl->GetImpl().SetMeshOrder( anOrderIds );
04578       }
04579     } // loop on meshes
04580 
04581     // update hyps needing full mesh data restored (issue 20918)
04582     for ( hyp_data = hypDataList.begin(); hyp_data != hypDataList.end(); ++hyp_data )
04583     {
04584       SMESH_Hypothesis_i* hyp  = hyp_data->first;
04585       hyp->UpdateAsMeshesRestored();
04586     }
04587 
04588     // notify algos on completed restoration to set sub-mesh event listeners
04589     for ( meshi_group = meshGroupList.begin(); meshi_group != meshGroupList.end(); ++meshi_group )
04590     {
04591       SMESH_Mesh_i* myNewMeshImpl = meshi_group->first;
04592       ::SMESH_Mesh& myLocMesh     = myNewMeshImpl->GetImpl();
04593 
04594       TopoDS_Shape myLocShape;
04595       if(myLocMesh.HasShapeToMesh())
04596         myLocShape = myLocMesh.GetShapeToMesh();
04597       else
04598         myLocShape = SMESH_Mesh::PseudoShape();
04599 
04600       myLocMesh.GetSubMesh(myLocShape)->
04601         ComputeStateEngine (SMESH_subMesh::SUBMESH_RESTORED);
04602     }
04603 
04604     // close mesh group
04605     if(aTopGroup)
04606       aTopGroup->CloseOnDisk();
04607   }
04608   // close HDF file
04609   aFile->CloseOnDisk();
04610   delete aFile;
04611 
04612   // Remove temporary files created from the stream
04613   if ( !isMultiFile )
04614   {
04615     SMESH_File meshFile( meshfile.ToCString() );
04616     if ( !meshFile ) // no meshfile exists
04617     {
04618       SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq.in(), true );
04619     }
04620     else
04621     {
04622       Engines::Container_var container = GetContainerRef();
04623       if ( Engines_Container_i* container_i = SMESH::DownCast<Engines_Container_i*>( container ))
04624       {
04625         container_i->registerTemporaryFile( filename.ToCString() );
04626         container_i->registerTemporaryFile( meshfile.ToCString() );
04627         container_i->registerTemporaryFile( tmpDir.ToCString() );
04628       }
04629     }
04630   }
04631   pd << ""; // prevent optimizing pd out
04632 
04633   INFOS( "SMESH_Gen_i::Load completed" );
04634   return true;
04635 }
04636 
04637 //=============================================================================
04643 //=============================================================================
04644 
04645 bool SMESH_Gen_i::LoadASCII( SALOMEDS::SComponent_ptr theComponent,
04646                              const SALOMEDS::TMPFile& theStream,
04647                              const char*              theURL,
04648                              bool                     isMultiFile ) {
04649   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::LoadASCII" );
04650   return Load( theComponent, theStream, theURL, isMultiFile );
04651 
04652   //before call main ::Load method it's need for decipher text format to
04653   //binary ( "|xx" => x' )
04654   int size = theStream.length();
04655   if ( int((size / 3 )*3) != size ) //error size of buffer
04656     return false;
04657 
04658   int real_size = int(size / 3);
04659 
04660   _CORBA_Octet* buffer = new _CORBA_Octet[real_size];
04661   char tmp[3];
04662   tmp[2]='\0';
04663   int c = -1;
04664   for ( int i = 0; i < real_size; i++ )
04665   {
04666     memcpy( &(tmp[0]), &(theStream[i*3+1]), 2 );
04667     sscanf( tmp, "%x", &c );
04668     sprintf( (char*)&(buffer[i]), "%c", (char)c );
04669   }
04670 
04671   SALOMEDS::TMPFile_var aRealStreamFile = new SALOMEDS::TMPFile(real_size, real_size, buffer, 1);
04672 
04673   return Load( theComponent, *(aRealStreamFile._retn()), theURL, isMultiFile );
04674 }
04675 
04676 //=============================================================================
04682 //=============================================================================
04683 
04684 void SMESH_Gen_i::Close( SALOMEDS::SComponent_ptr theComponent )
04685 {
04686   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Close" );
04687 
04688   // set correct current study
04689   SALOMEDS::Study_var study = theComponent->GetStudy();
04690   if ( study->StudyId() != GetCurrentStudyID())
04691     SetCurrentStudy( study );
04692 
04693   // Clear study contexts data
04694   int studyId = GetCurrentStudyID();
04695   if ( myStudyContextMap.find( studyId ) != myStudyContextMap.end() ) {
04696     delete myStudyContextMap[ studyId ];
04697     myStudyContextMap.erase( studyId );
04698   }
04699 
04700   // delete SMESH_Mesh's
04701 //   See bug IPAL19437.
04702 //
04703 //   StudyContextStruct* context = myGen.GetStudyContext( studyId );
04704 //   map< int, SMESH_Mesh* >::iterator i_mesh = context->mapMesh.begin();
04705 //   for ( ; i_mesh != context->mapMesh.end(); ++i_mesh ) {
04706 //     printf( "--------------------------- SMESH_Gen_i::Close, delete aGroup = %p \n", i_mesh->second );
04707 //     delete i_mesh->second;
04708 //   }
04709 
04710 
04711   // delete SMESHDS_Mesh's
04712   // it's too long on big meshes
04713 //   if ( context->myDocument ) {
04714 //     delete context->myDocument;
04715 //     context->myDocument = 0;
04716 //   }
04717 
04718   // remove the tmp files meshes are loaded from
04719   SMESH_PreMeshInfo::RemoveStudyFiles_TMP_METHOD( theComponent );
04720 
04721   myCurrentStudy = SALOMEDS::Study::_nil();
04722   return;
04723 }
04724 
04725 //=============================================================================
04731 //=============================================================================
04732 
04733 char* SMESH_Gen_i::ComponentDataType()
04734 {
04735   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::ComponentDataType" );
04736   return CORBA::string_dup( "SMESH" );
04737 }
04738 
04739 
04740 //=============================================================================
04746 //=============================================================================
04747 
04748 char* SMESH_Gen_i::IORToLocalPersistentID( SALOMEDS::SObject_ptr /*theSObject*/,
04749                                            const char*           IORString,
04750                                            CORBA::Boolean        /*isMultiFile*/,
04751                                            CORBA::Boolean        /*isASCII*/ )
04752 {
04753   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::IORToLocalPersistentID" );
04754   StudyContext* myStudyContext = GetCurrentStudyContext();
04755 
04756   if ( myStudyContext && strcmp( IORString, "" ) != 0 ) {
04757     int anId = myStudyContext->findId( IORString );
04758     if ( anId ) {
04759       if(MYDEBUG) MESSAGE( "VSR " << anId )
04760       char strId[ 20 ];
04761       sprintf( strId, "%d", anId );
04762       return  CORBA::string_dup( strId );
04763     }
04764   }
04765   return CORBA::string_dup( "" );
04766 }
04767 
04768 //=============================================================================
04774 //=============================================================================
04775 
04776 char* SMESH_Gen_i::LocalPersistentIDToIOR( SALOMEDS::SObject_ptr /*theSObject*/,
04777                                            const char*           aLocalPersistentID,
04778                                            CORBA::Boolean        /*isMultiFile*/,
04779                                            CORBA::Boolean        /*isASCII*/ )
04780 {
04781   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::LocalPersistentIDToIOR(): id = " << aLocalPersistentID );
04782   StudyContext* myStudyContext = GetCurrentStudyContext();
04783 
04784   if ( myStudyContext && strcmp( aLocalPersistentID, "" ) != 0 ) {
04785     int anId = atoi( aLocalPersistentID );
04786     return CORBA::string_dup( myStudyContext->getIORbyOldId( anId ).c_str() );
04787   }
04788   return CORBA::string_dup( "" );
04789 }
04790 
04791 //=======================================================================
04792 //function : RegisterObject
04793 //purpose  :
04794 //=======================================================================
04795 
04796 int SMESH_Gen_i::RegisterObject(CORBA::Object_ptr theObject)
04797 {
04798   StudyContext* myStudyContext = GetCurrentStudyContext();
04799   if ( myStudyContext && !CORBA::is_nil( theObject )) {
04800     CORBA::String_var iorString = GetORB()->object_to_string( theObject );
04801     return myStudyContext->addObject( string( iorString.in() ) );
04802   }
04803   return 0;
04804 }
04805 
04806 //================================================================================
04812 //================================================================================
04813 
04814 CORBA::Long SMESH_Gen_i::GetObjectId(CORBA::Object_ptr theObject)
04815 {
04816   StudyContext* myStudyContext = GetCurrentStudyContext();
04817   if ( myStudyContext && !CORBA::is_nil( theObject )) {
04818     string iorString = GetORB()->object_to_string( theObject );
04819     return myStudyContext->findId( iorString );
04820   }
04821   return 0;
04822 }
04823 
04824 //=============================================================================
04830 //=============================================================================
04831 void SMESH_Gen_i::SetName(const char* theIOR,
04832                           const char* theName)
04833 {
04834   if ( theIOR && strcmp( theIOR, "" ) ) {
04835     CORBA::Object_var anObject = GetORB()->string_to_object( theIOR );
04836     SALOMEDS::SObject_var aSO = ObjectToSObject( myCurrentStudy, anObject );
04837     if ( !aSO->_is_nil() ) {
04838       SetName( aSO, theName );
04839     }
04840   }
04841 }
04842 
04843 int SMESH_Gen_i::GetCurrentStudyID()
04844 {
04845   return myCurrentStudy->_is_nil() || myCurrentStudy->_non_existent() ? -1 : myCurrentStudy->StudyId();
04846 }
04847 
04848 //=============================================================================
04854 //=============================================================================
04855 
04856 extern "C"
04857 { SMESH_I_EXPORT
04858   PortableServer::ObjectId* SMESHEngine_factory( CORBA::ORB_ptr            orb,
04859                                                  PortableServer::POA_ptr   poa,
04860                                                  PortableServer::ObjectId* contId,
04861                                                  const char*               instanceName,
04862                                                  const char*               interfaceName )
04863   {
04864     if(MYDEBUG) MESSAGE( "PortableServer::ObjectId* SMESHEngine_factory()" );
04865     if(MYDEBUG) SCRUTE(interfaceName);
04866     SMESH_Gen_i* aSMESHGen = new SMESH_Gen_i(orb, poa, contId, instanceName, interfaceName);
04867     return aSMESHGen->getId() ;
04868   }
04869 }