Salome HOME
Fix pb with Animation
[modules/visu.git] / src / VISU_I / VISU_Result_i.cc
1 //  VISU OBJECT : interactive object for VISU entities implementation
2 //
3 //  Copyright (C) 2003  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 //  CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
5 //
6 //  This library is free software; you can redistribute it and/or
7 //  modify it under the terms of the GNU Lesser General Public
8 //  License as published by the Free Software Foundation; either
9 //  version 2.1 of the License.
10 //
11 //  This library is distributed in the hope that it will be useful,
12 //  but WITHOUT ANY WARRANTY; without even the implied warranty of
13 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 //  Lesser General Public License for more details.
15 //
16 //  You should have received a copy of the GNU Lesser General Public
17 //  License along with this library; if not, write to the Free Software
18 //  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
19 //
20 //  See http://www.opencascade.org/SALOME/ or email : webmaster.salome@opencascade.org
21 //
22 //
23 //  File   : VISU_Result_i.cc
24 //  Author : Alexey PETROV
25 //  Module : VISU
26
27 #include "VISU_Result_i.hh"
28
29 #include "VISU_Convertor_impl.hxx"
30 #include "VISU_CorbaMedConvertor.hxx"
31 #include "VISU_PipeLine.hxx"
32
33 #include "SUIT_ResourceMgr.h"
34
35 #include "SALOMEDS_Tool.hxx"
36 #include "HDFascii.hxx"
37
38 // QT Includes
39 #include <qstring.h>
40 #include <qfileinfo.h>
41
42 // VTK Includes
43 #include <vtkCell.h>
44 #include <vtkUnstructuredGrid.h>
45
46 // OCCT Includes
47 #include <Bnd_Box.hxx>
48
49 using namespace VISU;
50 using namespace std;
51
52 #ifdef _DEBUG_
53 static int MYDEBUG = 0;
54 #else
55 static int MYDEBUG = 0;
56 #endif
57
58 VISU::Result_var VISU::FindResult (SALOMEDS::SObject_ptr theSObject)
59 {
60   SALOMEDS::SComponent_var aSComponent = theSObject->GetFatherComponent();
61   SALOMEDS::SObject_var aFather = theSObject->GetFather();
62   CORBA::String_var aComponentID (aSComponent->GetID());
63   CORBA::String_var aFatherID    (aFather->GetID());
64   VISU::Result_var aResult;
65   while (strcmp(aComponentID, aFatherID) != 0) {
66     CORBA::Object_var anObject = VISU::SObjectToObject(aFather);
67     if (!CORBA::is_nil(anObject)) {
68       aResult = VISU::Result::_narrow(anObject);
69       if (!aResult->_is_nil()) return aResult;
70     }
71     aFather = aFather->GetFather();
72     aFatherID = aFather->GetID();
73   }
74   return aResult;
75 }
76
77 QString GenerateName (const char* theName)
78 {
79   typedef map<string,int> TNameMap;
80   static TNameMap aMap;
81   TNameMap::const_iterator i = aMap.find(theName);
82   QString tmp;
83   if (i == aMap.end()) {
84     aMap[theName] = 0;
85     tmp = theName;
86   } else {
87     tmp = VISU::GenerateName(theName,++aMap[theName]);
88   }
89   if(MYDEBUG) MESSAGE("GenerateName - "<<tmp<<" from - "<<theName<<"; " <<aMap[theName]);
90   return tmp;
91 }
92
93 QString GenerateFieldName (const string& theName, const string& theUnits)
94 {
95   static QString aName;
96   const string tmp (theUnits.size(),' ');
97   if (theUnits == "" || theUnits == tmp)
98     aName.sprintf("%s, -",theName.c_str());
99   else
100     aName.sprintf("%s, %s",theName.c_str(),theUnits.c_str());
101   aName = aName.simplifyWhiteSpace();
102   return aName.latin1();
103 }
104
105 void CreateReference (SALOMEDS::Study_ptr theStudyDocument,
106                       const string& theFatherEntry, const string& theRefEntry)
107 {
108   SALOMEDS::StudyBuilder_var aStudyBuilder = theStudyDocument->NewBuilder();
109   SALOMEDS::SObject_var aFather = theStudyDocument->FindObjectID(theFatherEntry.c_str());
110   SALOMEDS::SObject_var newObj = aStudyBuilder->NewObject(aFather);
111   SALOMEDS::SObject_var aRefSObj = theStudyDocument->FindObjectID(theRefEntry.c_str());
112   aStudyBuilder->Addreference(newObj,aRefSObj);
113 }
114
115 string GetComponentDataType (SALOMEDS::SObject_ptr theSObject)
116 {
117   SALOMEDS::SComponent_var aCompRefSObj = theSObject->GetFatherComponent();
118   CORBA::String_var aDataType = aCompRefSObj->ComponentDataType();
119   return aDataType.in();
120 }
121
122 //==============================================================================
123
124 const string VISU::Result_i::myComment = "RESULT";
125 const char* VISU::Result_i::GetComment() const { return myComment.c_str();}
126
127 VISU::Result_i::Result_i (SALOMEDS::Study_ptr theStudy,
128                           const ESourceId& theSourceId,
129                           const ECreationId& theCreationId):
130   myStudyDocument(SALOMEDS::Study::_duplicate(theStudy)),
131   myCreationId(theCreationId),
132   mySourceId(theSourceId),
133   myInput(NULL),
134   myIsDone(0)
135 {
136 }
137
138
139 void VISU::Result_i::RemoveFromStudy()
140 {
141   // Remove the result with all presentations and other possible sub-objects
142   VISU::RemoveFromStudy(mySObject,false);
143 }
144
145
146 int
147 VISU::Result_i::
148 IsPossible()
149 {
150   try{
151     float aSize = myInput->GetSize();
152     bool aResult = VISU_PipeLine::CheckAvailableMemory(aSize);
153     MESSAGE("Result_i::IsPossible - CheckAvailableMemory = "<<float(aSize)<<"; aResult = "<<float(aResult));
154     return aResult;
155   }catch(std::exception& exc){
156     INFOS("Follow exception was occured :\n"<<exc.what());
157   }catch(...){
158     INFOS("Unknown exception was occured!");
159   }
160   return 0;
161 }
162
163
164 CORBA::Boolean
165 VISU::Result_i::
166 BuildAll()
167 {
168   if(MYDEBUG) MESSAGE("Result_i::Build - myIsDone = "<<myIsDone);
169   if(myIsDone) return 1;
170   if(!IsPossible()) return 0;
171   try{
172     const VISU::TMeshMap& aMeshMap = myInput->GetMeshMap();
173     VISU::TMeshMap::const_iterator aMeshMapIter = aMeshMap.begin();
174     for(; aMeshMapIter != aMeshMap.end(); aMeshMapIter++){
175       const string& aMeshName = aMeshMapIter->first;
176       const VISU::PMesh aMesh = aMeshMapIter->second;
177       const VISU::TMeshOnEntityMap& aMeshOnEntityMap = aMesh->myMeshOnEntityMap;
178       VISU::TMeshOnEntityMap::const_iterator aMeshOnEntityMapIter;
179       //Import fields
180       aMeshOnEntityMapIter = aMeshOnEntityMap.begin();
181       for(; aMeshOnEntityMapIter != aMeshOnEntityMap.end(); aMeshOnEntityMapIter++){
182         const VISU::TEntity& anEntity = aMeshOnEntityMapIter->first;
183         const VISU::PMeshOnEntity aMeshOnEntity = aMeshOnEntityMapIter->second;
184         const VISU::TFieldMap& aFieldMap = aMeshOnEntity->myFieldMap;
185         VISU::TFieldMap::const_iterator aFieldMapIter = aFieldMap.begin();
186         for(; aFieldMapIter != aFieldMap.end(); aFieldMapIter++){
187           const string& aFieldName = aFieldMapIter->first;
188           const VISU::PField aField = aFieldMapIter->second;
189           const VISU::TValField& aValField = aField->myValField;
190           VISU::TValField::const_iterator aValFieldIter = aValField.begin();
191           for(; aValFieldIter != aValField.end(); aValFieldIter++){
192             int aTimeStamp = aValFieldIter->first;
193             try{
194               myInput->GetTimeStampOnMesh(aMeshName,anEntity,aFieldName,aTimeStamp);
195             }catch(std::exception& exc){
196               INFOS("Follow exception was occured :\n"<<exc.what());
197             }catch(...){
198               INFOS("Unknown exception was occured!!!");
199             }
200           }
201         }
202         //Importing groups
203         const VISU::TGroupMap& aGroupMap = aMesh->myGroupMap;
204         VISU::TGroupMap::const_iterator aGroupMapIter = aGroupMap.begin();
205         for(; aGroupMapIter != aGroupMap.end(); aGroupMapIter++){
206           const string& aGroupName = aGroupMapIter->first;
207           try{
208             myInput->GetMeshOnGroup(aMeshName,aGroupName);
209           }catch(std::exception& exc){
210             INFOS("Follow exception was occured :\n"<<exc.what());
211           }catch(...){
212             INFOS("Unknown exception was occured!!!");
213           }
214         }
215         //Import families
216         const VISU::TFamilyMap& aFamilyMap = aMeshOnEntity->myFamilyMap;
217         VISU::TFamilyMap::const_iterator aFamilyMapIter = aFamilyMap.begin();
218         for(; aFamilyMapIter != aFamilyMap.end(); aFamilyMapIter++){
219           const string& aFamilyName = aFamilyMapIter->first;
220           try{
221             myInput->GetMeshOnEntity(aMeshName,anEntity,aFamilyName);
222           }catch(std::exception& exc){
223             INFOS("Follow exception was occured :\n"<<exc.what());
224           }catch(...){
225             INFOS("Unknown exception was occured!!!");
226           }
227         }
228         //Import mesh on entity
229         try{
230           myInput->GetMeshOnEntity(aMeshName,anEntity);
231         }catch(std::exception& exc){
232           INFOS("Follow exception was occured :\n"<<exc.what());
233         }catch(...){
234           INFOS("Unknown exception was occured!!!");
235         }
236       }
237     }
238     myIsDone = 1;
239   }catch(std::exception& exc){
240     INFOS("Follow exception was occured :\n"<<exc.what());
241   }catch(...){
242     INFOS("Unknown exception was occured!!!");
243   }
244   return myIsDone;
245 }
246
247
248 VISU::Storable*
249 VISU::Result_i::
250 Build(SALOMEDS::SObject_ptr theSObject)
251 {
252   SALOMEDS::StudyBuilder_var aStudyBuilder = myStudyDocument->NewBuilder();
253   aStudyBuilder->NewCommand();  // There is a transaction
254   if(MYDEBUG) MESSAGE("Result_i::Build");
255   try{
256     const TMeshMap& aMeshMap = myInput->GetMeshMap();
257     if(aMeshMap.empty())
258       throw std::runtime_error("Build - There is no any mesh information in the file !!!");
259     mySComponent = FindOrCreateVisuComponent(myStudyDocument);
260     CORBA::String_var aSComponentEntry = mySComponent->GetID(), anIOR(GetID());
261     string aRefFatherEntry = GetRefFatherEntry();
262     QString aComment;
263     aComment.sprintf("myComment=%s;myType=%d;myFileName=%s;myInitFileName=%s",
264                      GetComment(),
265                      VISU::TRESULT,
266                      myFileInfo.filePath().latin1(),
267                      myInitFileName.c_str()); // Restoring of Python dump
268     string aResultEntry =
269       CreateAttributes(myStudyDocument,
270                        aSComponentEntry,
271                        aRefFatherEntry.c_str(),
272                        anIOR,
273                        myName.c_str(),
274                        "",
275                        aComment.latin1(),
276                        true);
277     mySObject = myStudyDocument->FindObjectID(aResultEntry.c_str());
278     if(mySObject->_is_nil()) throw std::runtime_error("Build - There is no SObject for the Result !!!");
279     if(!CORBA::is_nil(theSObject)){
280       CORBA::String_var aString = theSObject->GetID();
281       CreateReference(myStudyDocument,aResultEntry,aString.in());
282     }
283     TMeshMap::const_iterator aMeshMapIter = aMeshMap.begin();
284     for(; aMeshMapIter != aMeshMap.end(); aMeshMapIter++){
285       const string& aMeshName = aMeshMapIter->first;
286       const VISU::PMesh aMesh = aMeshMapIter->second;
287       const VISU::TMeshOnEntityMap& aMeshOnEntityMap = aMesh->myMeshOnEntityMap;
288       VISU::TMeshOnEntityMap::const_iterator aMeshOnEntityMapIter;
289       aComment.sprintf("myComment=MESH;myName=%s;myDim=%d",
290                        aMeshName.c_str(),aMesh->myDim);
291       string aMeshEntry = CreateAttributes(myStudyDocument,aResultEntry.c_str(),aRefFatherEntry.c_str(),
292                                            "",aMeshName.c_str(),"",aComment.latin1(),true);
293       if(aMeshOnEntityMap.empty()) continue;
294       aComment.sprintf("myComment=FAMILIES;myMeshName=%s",aMeshName.c_str());
295       string aSubMeshesEntry = CreateAttributes(myStudyDocument,aMeshEntry.c_str(),aRefFatherEntry.c_str(),
296                                                 "","Families","",aComment.latin1(),true);
297       //Import entities and according families
298       aMeshOnEntityMapIter = aMeshOnEntityMap.begin();
299       typedef std::map<std::string,std::string> TComment2EntryMap;
300       TComment2EntryMap aComment2EntryMap;
301       typedef std::map<VISU::TEntity,std::string> TEntity2EntryMap;
302       TEntity2EntryMap aEntity2EntryMap;
303       for(; aMeshOnEntityMapIter != aMeshOnEntityMap.end(); aMeshOnEntityMapIter++){
304         const VISU::TEntity& anEntity = aMeshOnEntityMapIter->first;
305         aComment.sprintf("myComment=ENTITY;myType=%d;myMeshName=%s;myId=%d",
306                          VISU::TENTITY,
307                          aMeshName.c_str(),
308                          anEntity);
309         string anEntityName;
310         switch(anEntity){
311         case VISU::NODE_ENTITY : anEntityName = "onNodes"; break;
312         case VISU::EDGE_ENTITY : anEntityName = "onEdges"; break;
313         case VISU::FACE_ENTITY : anEntityName = "onFaces"; break;
314         case VISU::CELL_ENTITY : anEntityName = "onCells"; break;
315         default:
316           throw std::runtime_error("Build >> Value of entity is incorrect!");
317         }
318         aEntity2EntryMap[anEntity] = CreateAttributes
319           (myStudyDocument, aSubMeshesEntry.c_str(), aRefFatherEntry.c_str(),
320            "", anEntityName.c_str(), "", aComment.latin1(), true);
321         const VISU::PMeshOnEntity aMeshOnEntity = aMeshOnEntityMapIter->second;
322         const VISU::TFamilyMap& aFamilyMap = aMeshOnEntity->myFamilyMap;
323         VISU::TFamilyMap::const_iterator aFamilyMapIter = aFamilyMap.begin();
324         for(; aFamilyMapIter != aFamilyMap.end(); aFamilyMapIter++){
325           const string& aFamilyName = aFamilyMapIter->first;
326           aComment.sprintf("myComment=FAMILY;myType=%d;myMeshName=%s;myEntityId=%d;myName=%s",
327                            VISU::TFAMILY,
328                            aMeshName.c_str(),
329                            anEntity,
330                            aFamilyName.c_str());
331           aComment2EntryMap[aComment.latin1()] =
332             CreateAttributes(myStudyDocument,
333                              aEntity2EntryMap[anEntity].c_str(),
334                              aRefFatherEntry.c_str(),
335                              "",
336                              aFamilyName.c_str(),
337                              "",
338                              aComment.latin1(),
339                              true);
340         }
341       }
342       //Importing groups
343       const VISU::TGroupMap& aGroupMap = aMesh->myGroupMap;
344       if(aGroupMap.size() > 0){
345         aComment.sprintf("myComment=GROUPS;myMeshName=%s",
346                          aMeshName.c_str());
347         string aGroupsEntry =
348           CreateAttributes(myStudyDocument,
349                            aMeshEntry.c_str(),
350                            aRefFatherEntry.c_str(),
351                            "",
352                            "Groups",
353                            "",
354                            aComment.latin1(),
355                            true);
356         VISU::TGroupMap::const_iterator aGroupMapIter = aGroupMap.begin();
357         for(; aGroupMapIter != aGroupMap.end(); aGroupMapIter++){
358           const string& aGroupName = aGroupMapIter->first;
359           aComment.sprintf("myComment=GROUP;myType=%d;myMeshName=%s;myName=%s",
360                            VISU::TGROUP,aMeshName.c_str(),aGroupName.c_str());
361           string aGroupEntry = CreateAttributes(myStudyDocument,aGroupsEntry.c_str(),aRefFatherEntry.c_str(),
362                                                 "",aGroupName.c_str(),"",aComment.latin1(),true);
363           const VISU::PGroup aGroup = aGroupMapIter->second;
364           const VISU::TFamilyAndEntitySet& aFamilyAndEntitySet = aGroup->myFamilyAndEntitySet;
365           VISU::TFamilyAndEntitySet::const_iterator aFamilyAndEntitySetIter = aFamilyAndEntitySet.begin();
366           for(; aFamilyAndEntitySetIter != aFamilyAndEntitySet.end(); aFamilyAndEntitySetIter++){
367             const VISU::TFamilyAndEntity& aFamilyAndEntity = *aFamilyAndEntitySetIter;
368             const string& aFamilyName = aFamilyAndEntity.first;
369             const VISU::TEntity& anEntity = aFamilyAndEntity.second;
370             aComment.sprintf("myComment=FAMILY;myType=%d;myMeshName=%s;myEntityId=%d;myName=%s",
371                              VISU::TFAMILY,
372                              aMeshName.c_str(),
373                              anEntity,
374                              aFamilyName.c_str());
375             CreateReference(myStudyDocument,aGroupEntry,aComment2EntryMap[aComment.latin1()]);
376           }
377         }
378       }
379       //Import fields
380       string aFieldsEntry;
381       bool isFieldEntryCreated = 0;
382       aMeshOnEntityMapIter = aMeshOnEntityMap.begin();
383       for(; aMeshOnEntityMapIter != aMeshOnEntityMap.end(); aMeshOnEntityMapIter++){
384         const VISU::TEntity& anEntity = aMeshOnEntityMapIter->first;
385         const VISU::PMeshOnEntity aMeshOnEntity = aMeshOnEntityMapIter->second;
386         const VISU::TFieldMap& aFieldMap = aMeshOnEntity->myFieldMap;
387         VISU::TFieldMap::const_iterator aFieldMapIter = aFieldMap.begin();
388         for(; aFieldMapIter != aFieldMap.end(); aFieldMapIter++){
389           if(!isFieldEntryCreated){
390             aComment.sprintf("myComment=FIELDS;myMeshName=%s",
391                              aMeshName.c_str());
392             aFieldsEntry =
393               CreateAttributes(myStudyDocument,
394                                aMeshEntry.c_str(),
395                                aRefFatherEntry.c_str(),
396                                "",
397                                "Fields",
398                                "",
399                                aComment.latin1(),
400                                true);
401             isFieldEntryCreated = true;
402           }
403           const string& aFieldName = aFieldMapIter->first;
404           const VISU::PField aField = aFieldMapIter->second;
405           const VISU::TValField& aValField = aField->myValField;
406           QString aFieldNameWithUnit = ::GenerateFieldName(aFieldName,aField->myUnitNames[0]);
407           aComment.sprintf("myComment=FIELD;myType=%d;myMeshName=%s;myEntityId=%d;myName=%s;myNbTimeStamps=%d;myNumComponent=%d",
408                            VISU::TFIELD,aMeshName.c_str(),anEntity,aFieldName.c_str(),aValField.size(),aField->myNbComp);
409           string aFieldEntry = CreateAttributes(myStudyDocument,aFieldsEntry.c_str(),aRefFatherEntry.c_str(),
410                                                 "",aFieldNameWithUnit.latin1(),"",aComment.latin1(),true);
411           CreateReference(myStudyDocument,aFieldEntry,aEntity2EntryMap[anEntity]);
412           VISU::TValField::const_iterator aValFieldIter = aValField.begin();
413           for(; aValFieldIter != aValField.end(); aValFieldIter++){
414             int aTimeStamp = aValFieldIter->first;
415             const VISU::PValForTime aValForTime = aValFieldIter->second;
416             aComment.sprintf("myComment=TIMESTAMP;myType=%d;myMeshName=%s;myEntityId=%d;myFieldName=%s;myTimeStampId=%d;myNumComponent=%d",
417                              VISU::TTIMESTAMP,aMeshName.c_str(),anEntity,aFieldName.c_str(),aTimeStamp,aField->myNbComp);
418             string aTimeStampId = VISU_Convertor::GenerateName(aValForTime->myTime);
419             CreateAttributes(myStudyDocument,aFieldEntry.c_str(),aRefFatherEntry.c_str(),
420                              "",aTimeStampId.c_str(),"",aComment.latin1(),true);
421           }
422         }
423       }
424     }
425     bool isBuildAll = VISU::GetResourceMgr()->booleanValue("VISU", "full_med_loading", false);
426     if(isBuildAll) BuildAll();
427   }catch(std::exception& exc){
428     INFOS("Follow exception was occured :\n"<<exc.what());
429     return NULL;
430   }catch(...){
431     INFOS("Unknown exception was occured!!!");
432     return NULL;
433   }
434   aStudyBuilder->CommitCommand();
435   return this;
436 }
437
438
439 VISU::Storable*
440 VISU::Result_i::
441 Create(const char* theFileName)
442 {
443   try{
444     myFileInfo.setFile(theFileName);
445     myInitFileName = myFileInfo.filePath().latin1();
446     myName = ::GenerateName(myFileInfo.fileName()).latin1();
447     if(mySourceId == eRestoredFile){
448       std::string aTmpDir(SALOMEDS_Tool::GetTmpDir());
449       static QString aCommand;
450       aCommand.sprintf("cp %s %s",myFileInfo.absFilePath().latin1(),aTmpDir.c_str());
451       if(system(aCommand) == -1){
452         MESSAGE("Create - Can't execute the command :"<<aCommand);
453         return NULL;
454       }
455       if(MYDEBUG) MESSAGE("Result_i::Create - aCommand = "<<aCommand);
456       myFileInfo.setFile(QString(aTmpDir.c_str()) + myFileInfo.fileName());
457     }
458     myInput = CreateConvertor(myFileInfo.absFilePath().latin1());
459     if(!myInput)
460       throw std::runtime_error("Create - Cannot create a Convertor for this file!!!");
461     return Build();
462   }catch(std::exception& exc){
463     INFOS("Follow exception was occured :\n"<<exc.what());
464   }catch(...){
465     INFOS("Unknown exception was occured!!!");
466   }
467   return NULL;
468 }
469
470
471 VISU::Storable*
472 VISU::Result_i::
473 Create(SALOMEDS::SObject_ptr theMedSObject)
474 {
475   if(MYDEBUG)  MESSAGE("Result_i::Create MedObject from SALOMEDS::SObject_ptr");
476   try{
477     myInput = CreateMEDConvertor(theMedSObject);
478     if(myInput == NULL)
479       return NULL;
480
481     string aCompDataType = GetComponentDataType(theMedSObject);
482     myFileInfo.setFile(aCompDataType.c_str());
483     myInitFileName = aCompDataType;
484
485     myName = ::GenerateName("aResult").latin1();
486
487     VISU::Storable* aStorable = Build(theMedSObject);
488     return aStorable;
489   }catch(std::exception& exc){
490     INFOS("Follow exception was occured :\n"<<exc.what());
491   }catch(...){
492     INFOS("Unknown exception was occured!!!");
493   }
494   return NULL;
495 }
496
497 VISU::Storable*
498 VISU::Result_i::
499 Create(SALOME_MED::FIELD_ptr theField)
500 {
501   if(MYDEBUG)  MESSAGE("Result_i::Create MedObject from SALOME_MED::FIELD_ptr");
502   try{
503     myInput = CreateMEDFieldConvertor(theField);
504     if(myInput == NULL)
505       return NULL;
506
507     string aCompDataType = "MED";
508     myFileInfo.setFile(aCompDataType.c_str());
509     myInitFileName = aCompDataType;
510
511     myName = ::GenerateName("aResult").latin1();
512
513     CORBA::String_var anIOR = myStudyDocument->ConvertObjectToIOR(theField);
514     SALOMEDS::SObject_var aFieldSObject = myStudyDocument->FindObjectIOR(anIOR);
515
516     VISU::Storable* aStorable = Build(aFieldSObject);
517     return aStorable;
518   }catch(std::exception& exc){
519     INFOS("Follow exception was occured :\n"<<exc.what());
520   }catch(...){
521     INFOS("Unknown exception was occured!!!");
522   }
523   return NULL;
524 }
525
526
527 VISU::Storable*
528 VISU::Result_i::
529 Restore(SALOMEDS::SObject_ptr theSObject,
530         const Storable::TRestoringMap& theMap,
531         const string& thePrefix)
532 {
533   if(MYDEBUG) MESSAGE("Result_i::Restore - " << thePrefix);
534   try {
535     mySObject = SALOMEDS::SObject::_duplicate(theSObject);
536     myStudyDocument = mySObject->GetStudy();
537     mySComponent = mySObject->GetFatherComponent();
538     myName = VISU::Storable::FindValue(theMap, "myName").latin1();
539     myInitFileName = VISU::Storable::FindValue(theMap, "myInitFileName").latin1();
540
541     SALOMEDS::SObject_var aRefSObj, aTargetRefSObj;
542     if (mySObject->FindSubObject(1, aRefSObj) &&
543         aRefSObj->ReferencedObject(aTargetRefSObj)) {
544       if(MYDEBUG) MESSAGE("Result_i::GetInput - There is some reference.");
545       SALOMEDS::SComponent_var aCompRefSObj = aTargetRefSObj->GetFatherComponent();
546       CORBA::String_var aDataType = aCompRefSObj->ComponentDataType();
547       myFileInfo.setFile(aDataType.in());
548       if(MYDEBUG) MESSAGE("Result_i::GetInput - aDataType = " << aDataType);
549       Engines::Component_var aEngComp =
550         Base_i::myEnginesLifeCycle->FindOrLoad_Component("FactoryServer", aDataType.in());
551       if (CORBA::is_nil(aEngComp))
552         throw std::runtime_error("Restore - There is no aEngComp for the aDataType !!!");
553       SALOMEDS::StudyBuilder_var aStudyBuilder = myStudyDocument->NewBuilder();
554       SALOMEDS::Driver_var aDriver = SALOMEDS::Driver::_narrow(aEngComp);
555       aStudyBuilder->LoadWith(aCompRefSObj, aDriver);
556       if (strcmp(aDataType, "MED") == 0)
557         myInput = CreateMEDConvertor(aTargetRefSObj);
558       else
559         throw std::runtime_error("GetInput - There is no convertor for the aDataType !!!");
560     } else {
561       myFileInfo.setFile(thePrefix.c_str());
562
563       string aStudyPrefix ("");
564       if (IsMultifile())
565         aStudyPrefix = SALOMEDS_Tool::GetNameFromPath(myStudyDocument->URL());
566       if (!myFileInfo.isFile()) {
567         string aFileName = thePrefix + aStudyPrefix + "_" + myName;
568         myFileInfo.setFile(aFileName.c_str());
569       }
570       if(MYDEBUG)
571         MESSAGE("Result_i::Restore - aFileName = " << myFileInfo.filePath() << "; " << myFileInfo.isFile());
572
573       const char* aPathLatin = myFileInfo.filePath().latin1();
574       if (HDFascii::isASCII(aPathLatin)) {
575         MESSAGE("ConvertFromASCIIToHDF(" << aPathLatin << ")");
576         char* aResultPath = HDFascii::ConvertFromASCIIToHDF(aPathLatin);
577         MESSAGE("ConvertFromASCIIToHDF() DONE : " << aResultPath);
578         char* aHDFFileName = new char[strlen(aResultPath) + 19];
579         sprintf(aHDFFileName, "%shdf_from_ascii.hdf", aResultPath);
580
581         if (IsMultifile()) { // set this file as new - temporary
582           static QString aCommand;
583           aCommand.sprintf("mv %s %s%s",aHDFFileName, aResultPath, myFileInfo.baseName().latin1());
584           if (system(aCommand) == -1) {
585             if(MYDEBUG) MESSAGE("VISU::Result_i::Restore - Can't execute the command :" << aCommand);
586             return NULL;
587           } else {
588             if(MYDEBUG) MESSAGE("VISU::Result_i::Restore - " << aCommand);
589           }
590           myFileInfo.setFile(QString(aResultPath) + QString(myFileInfo.baseName().latin1()));
591         } else { // change current temporary file to the new: with hdf-format
592           static QString aCommand;
593           aCommand.sprintf("mv %s %s\0",aHDFFileName, myFileInfo.filePath().latin1());
594           if (system(aCommand.latin1()) == -1) {
595             if(MYDEBUG) MESSAGE("VISU::Result_i::Restore - Can't execute the command :" << aCommand);
596             return NULL;
597           } else {
598             if(MYDEBUG) MESSAGE("VISU::Result_i::Restore - " << aCommand);
599           }
600           SALOMEDS::ListOfFileNames_var anEmptyList = new SALOMEDS::ListOfFileNames;
601           SALOMEDS_Tool::RemoveTemporaryFiles(aResultPath, anEmptyList.in(), true);
602         }
603         mySourceId = eRestoredFile;
604         delete(aResultPath);
605         delete(aHDFFileName);
606       } else if (!IsMultifile()) {
607         mySourceId = eRestoredFile;
608       } else {
609         mySourceId = eFile;
610       }
611       if(MYDEBUG) MESSAGE("VISU::Result_i::Restore - mySourceId = " << mySourceId);
612       myInput = CreateConvertor(myFileInfo.filePath().latin1());
613       QString aComment;
614       aComment.sprintf("myComment=%s;myType=%d;myFileName=%s;myInitFileName=%s",
615                        GetComment(), VISU::TRESULT, myFileInfo.filePath().latin1(),
616                        myInitFileName.c_str()); // Restoring of Python dump
617       SALOMEDS::GenericAttribute_var anAttr;
618       if (!theSObject->FindAttribute(anAttr, "AttributeComment"))
619         throw std::runtime_error("Build - There is no AttributeComment for the SObject !!!");
620       SALOMEDS::AttributeComment_var aCmnt = SALOMEDS::AttributeComment::_narrow(anAttr);
621       aCmnt->SetValue(aComment.latin1());
622     }
623     bool isBuildAll = VISU::GetResourceMgr()->booleanValue("VISU", "full_med_loading", false);
624     if (isBuildAll)
625       BuildAll();
626     return this;
627   } catch(std::exception& exc) {
628     INFOS("Follow exception was occured :\n"<<exc.what());
629   } catch(...) {
630     INFOS("Unknown exception was occured!!!");
631   }
632   return NULL;
633 }
634
635 VISU::Result_i::TInput* VISU::Result_i::GetInput() {
636   return myInput;
637 }
638
639 void VISU::Result_i::ToStream(std::ostringstream& theStr){
640   if(MYDEBUG) MESSAGE(GetComment());
641   Storable::DataToStream(theStr,"myName",myName.c_str());
642   Storable::DataToStream(theStr,"myInitFileName",myInitFileName.c_str());
643   Storable::DataToStream(theStr,"myCreationId",myCreationId);
644 }
645
646 VISU::Storable*
647 VISU::Result_i::Restore(SALOMEDS::SObject_ptr theSObject,
648                         const string& thePrefix,
649                         const Storable::TRestoringMap& theMap)
650 {
651   SALOMEDS::Study_var aStudy = theSObject->GetStudy();
652
653   ECreationId aCreationId = ECreationId(Storable::FindValue(theMap,"myCreationId").toInt());
654   ESourceId aSourceId = eRestoredFile;
655   if(aCreationId == eImportMed || aCreationId == eImportMedField)
656     aSourceId = eRestoredComponent;
657
658   VISU::Result_i* pResult = new VISU::Result_i(aStudy,aSourceId,aCreationId);
659   if (pResult == NULL)
660     return NULL;
661
662   return pResult->Restore(theSObject,theMap,thePrefix);
663 }
664
665 string VISU::Result_i::GetRefFatherEntry() {
666   //return QAD_Application::getDesktop()->getActiveStudy()->getActiveStudyFrame()->entry();
667   return "";
668 }
669
670 string VISU::Result_i::GetEntry(){
671   CORBA::String_var anEntry = mySObject->GetID();
672   return string(anEntry);
673 }
674
675 const SALOMEDS::SObject_var& VISU::Result_i::GetSObject() const { return mySObject;}
676 const SALOMEDS::Study_var& VISU::Result_i::GetStudyDocument() const { return myStudyDocument;}
677 const SALOMEDS::SComponent_var& VISU::Result_i::GetSComponent() const { return mySComponent;}
678 std::string VISU::Result_i::GetEntry(const std::string& theComment)
679 {
680   return FindEntryWithComment(myStudyDocument,GetEntry().c_str(),theComment.c_str());
681 }
682
683 VISU::Result_i::~Result_i()
684 {
685   MESSAGE("Result_i::~Result_i() - this = "<<this);
686   if (mySourceId == eRestoredFile) {
687     static QString aCommand;
688     aCommand.sprintf("rm %s",myFileInfo.filePath().latin1());
689     MESSAGE("Result_i::~Result_i - system("<<aCommand<<") = "<<system(aCommand));
690     aCommand.sprintf("rmdir --ignore-fail-on-non-empty %s",myFileInfo.dirPath().latin1());
691     MESSAGE("Result_i::~Result_i - system("<<aCommand<<") = "<<system(aCommand));
692   }
693   if(myInput) delete myInput;
694 }
695
696 //=======================================================================
697 //function : GetAxisInfo
698 //purpose  :
699 //=======================================================================
700 const vector< float >* Result_i::GetAxisInfo(const string& theMeshName,
701                                              TAxis         theAxis,
702                                              gp_Dir&       thePlaneNormal)
703 {
704   const vector< float >* components = NULL;
705
706   if ( theAxis < AXIS_X || theAxis > AXIS_Z ) {
707     MESSAGE(" Bad axis index " << theAxis );
708     return components;
709   }
710
711   map< string, TGridInfo >::iterator name_info;
712   name_info = myMeshName2GridInfoMap.find( theMeshName );
713   TGridInfo * gInfo = 0;
714
715   if ( name_info != myMeshName2GridInfoMap.end() )
716   {
717     gInfo = & name_info->second;
718   }
719   else if ( myInput && IsPossible() && theAxis >= AXIS_X && theAxis <= AXIS_Z )
720   {
721     // check presence of theMeshName
722     const VISU::TMeshMap& meshMap = myInput->GetMeshMap();
723     if ( meshMap.find( theMeshName ) == meshMap.end() ) {
724       MESSAGE("No mesh named " << theMeshName );
725       return components;
726     }
727     VISU_Convertor::TOutput* vtkMesh = myInput->GetMeshOnEntity (theMeshName,
728                                                                  CELL_ENTITY);
729     if ( !vtkMesh || vtkMesh->GetNumberOfCells() == 0 ) {
730       MESSAGE( "No cells in the mesh: " << theMeshName );
731       return components;
732     }
733
734     // define axis directions and min cell size in each direction
735     const int nbAxes = 3;
736     int iAx;
737     gp_Vec axDirs[ nbAxes ];
738     float minSize[3] = { FLT_MAX, FLT_MAX, FLT_MAX };
739     bool axesComputed = false;
740     for ( vtkIdType iCell = 0; iCell < vtkMesh->GetNumberOfCells(); ++iCell )
741     {
742       vtkCell* cell = vtkMesh->GetCell( iCell );
743       int nbPnt = cell->GetNumberOfPoints();
744       if ( nbPnt != 8 )
745         continue;
746       vtkPoints * points = cell->GetPoints();
747       float* coords[ 4 ];
748       coords[0] = points->GetPoint( 0 );
749       coords[1] = points->GetPoint( 1 );
750       coords[2] = points->GetPoint( 3 );
751       coords[3] = points->GetPoint( 4 );
752       gp_Pnt p0( coords[0][0], coords[0][1], coords[0][2] );
753       for ( iAx = 0; iAx < nbAxes; ++iAx )
754       {
755         float* coo = coords[ iAx + 1 ];
756         gp_Pnt p( coo[0], coo[1], coo[2] );
757         // min size
758         float size = p0.SquareDistance( p );
759         if ( size > FLT_MIN && size < minSize[ iAx ] )
760           minSize[ iAx ] = size;
761         // axis direction
762         if ( !axesComputed ) {
763           gp_Vec dir( p0, p );
764           if ( dir.SquareMagnitude() <= DBL_MIN )
765             break;
766           axDirs[ iAx ] = dir;
767         }
768       }
769       if ( iAx == nbAxes )
770         axesComputed = true;
771     }
772     if ( !axesComputed ) {
773       MESSAGE("No good hexahedrons in the mesh: " << theMeshName );
774       return components;
775     }
776
777     // compute axes dirs
778     gInfo = & myMeshName2GridInfoMap[ theMeshName ];
779     for ( iAx = 0; iAx < nbAxes; ++iAx )
780     {
781       int iPrev = ( iAx == 0 ) ? 2 : iAx - 1;
782       int iNext = ( iAx == 2 ) ? 0 : iAx + 1;
783       gInfo->myAxis[ iAx ] = axDirs[ iPrev ] ^ axDirs[ iNext ];
784     }
785
786     // get and sort intermediate component values - projections of nodes
787     // on axis direction; define bnd box
788     set< float > comps[ 3 ];
789     Bnd_Box box;
790     vtkPoints * points = vtkMesh->GetPoints();
791     vtkIdType iP, nbP = vtkMesh->GetNumberOfPoints();
792     for ( iP = 0; iP < nbP; ++iP )
793     {
794       float* coo = points->GetPoint( iP );
795       gp_Pnt p( coo[0], coo[1], coo[2] );
796       box.Add( p );
797       for ( iAx = 0; iAx < nbAxes; ++iAx ) {
798         const gp_Dir& dir = gInfo->myAxis[ iAx ];
799         float dot = dir.XYZ() * p.XYZ();
800         comps[ iAx ].insert( dot );
801       }
802     }
803
804     // find a range of projections of bnd box corners on each axis
805     float range[3], firstValue[3];
806     double x[2],y[2],z[2];
807     box.Get(x[0],y[0],z[0],x[1],y[1],z[1]);
808     for ( iAx = 0; iAx < nbAxes; ++iAx ) {
809       set< float > bndComps;
810       const gp_Dir& dir = gInfo->myAxis[ iAx ];
811       for ( int iX = 0; iX < 2; ++iX ) {
812         for ( int iY = 0; iY < 2; ++iY ) {
813           for ( int iZ = 0; iZ < 2; ++iZ ) {
814             gp_Pnt p( x[ iX ], y[ iY ], z[ iZ ] );
815             float dot = dir.XYZ() * p.XYZ();
816             bndComps.insert( dot );
817           }
818         }
819       }
820       firstValue[ iAx ] = *bndComps.begin();
821       range[ iAx ] = *bndComps.rbegin() - *bndComps.begin();
822     }
823
824     // compute component values
825     for ( iAx = 0; iAx < nbAxes; ++iAx )
826     {
827       list< float > values;
828       int nbVals = 0;
829       set< float >& comp = comps[ iAx ];
830       set< float >::iterator val = comp.begin();
831       float bnd = -1., rng = range[ iAx ], first = firstValue[ iAx ];
832       float tol = 0.1 * sqrt( minSize[ iAx ]) / rng;
833       for ( ; val != comp.end(); ++val ) {
834         float value = ( *val - first ) / rng;
835         if ( value > bnd ) {
836           values.push_back( value );
837           bnd = value + tol;
838           nbVals++;
839         }
840       }
841       // store values in gInfo
842       vector< float >& myComp = gInfo->myComponets[ iAx ];
843       myComp.resize( nbVals );
844       list< float >::iterator v = values.begin();
845       for ( int i = 0; v != values.end(); ++v )
846         myComp[ i++ ] = *v;
847     }
848   }
849
850   // set return values
851   if ( gInfo )
852   {
853     thePlaneNormal = gInfo->myAxis[ theAxis ];
854     components = & gInfo->myComponets[ theAxis ];
855   }
856
857   return components;
858 }