Salome HOME
7647dc4259024095ae4b431ba4d46c42a3582981
[modules/smesh.git] / src / DriverMED / DriverMED_W_SMESHDS_Mesh.cxx
1 // Copyright (C) 2007-2021  CEA/DEN, EDF R&D, OPEN CASCADE
2 //
3 // Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
5 //
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License, or (at your option) any later version.
10 //
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 // Lesser General Public License for more details.
15 //
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
19 //
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 //
22
23 //  SMESH DriverMED : driver to read and write 'med' files
24 //  File   : DriverMED_W_SMESHDS_Mesh.cxx
25 //  Module : SMESH
26 //
27
28 #include "DriverMED_W_SMESHDS_Mesh.h"
29
30 #include "DriverMED_Family.h"
31 #include "MED_Factory.hxx"
32 #include "MED_Utilities.hxx"
33 #include "SMDS_IteratorOnIterators.hxx"
34 #include "SMDS_MeshNode.hxx"
35 #include "SMDS_SetIterator.hxx"
36 #include "SMESHDS_Mesh.hxx"
37 #include "MED_Common.hxx"
38 #include "MED_TFile.hxx"
39
40 #include <med.h>
41
42 #include <BRep_Tool.hxx>
43 #include <TopExp_Explorer.hxx>
44 #include <TopoDS.hxx>
45
46 #include <utilities.h>
47
48
49 #define _EDF_NODE_IDS_
50 //#define _ELEMENTS_BY_DIM_
51
52 using namespace std;
53 using namespace MED;
54
55
56 DriverMED_W_SMESHDS_Mesh::DriverMED_W_SMESHDS_Mesh():
57   myAllSubMeshes (false),
58   myDoGroupOfNodes (false),
59   myDoGroupOfEdges (false),
60   myDoGroupOfFaces (false),
61   myDoGroupOfVolumes (false),
62   myDoGroupOf0DElems(false),
63   myDoGroupOfBalls(false),
64   myAutoDimension(false),
65   myAddODOnVertices(false),
66   myDoAllInGroups(false),
67   myVersion(-1),
68   myZTolerance(-1.)
69 {}
70
71 void DriverMED_W_SMESHDS_Mesh::SetFile(const std::string& theFileName, int theVersion)
72 {
73   myVersion = theVersion;
74   Driver_SMESHDS_Mesh::SetFile(theFileName);
75 }
76
77 /*!
78  * MED version is either the latest available, or with an inferior minor,
79  * to ensure backward compatibility on writing med files.
80  */
81 string DriverMED_W_SMESHDS_Mesh::GetVersionString(int theMinor, int theNbDigits)
82 {
83   TInt majeur, mineur, release;
84   majeur=MED_MAJOR_NUM;
85   mineur=MED_MINOR_NUM;
86   release=MED_RELEASE_NUM;
87   TInt imposedMineur = mineur;
88
89   if (theMinor < 0)
90     imposedMineur = mineur;
91   else if (theMinor > MED_MINOR_NUM)
92     imposedMineur = mineur;
93   else
94     imposedMineur = theMinor;
95
96   ostringstream name;
97   if ( theNbDigits > 0 )
98     name << majeur;
99   if ( theNbDigits > 1 )
100     name << "." << imposedMineur;
101   if ( theNbDigits > 2 )
102     name << "." << release;
103   return name.str();
104 }
105
106 void DriverMED_W_SMESHDS_Mesh::AddGroup(SMESHDS_GroupBase* theGroup)
107 {
108   myGroups.push_back(theGroup);
109 }
110
111 void DriverMED_W_SMESHDS_Mesh::AddAllSubMeshes()
112 {
113   myAllSubMeshes = true;
114 }
115
116 void DriverMED_W_SMESHDS_Mesh::AddSubMesh(SMESHDS_SubMesh* theSubMesh, int /*theID*/)
117 {
118   mySubMeshes.push_back( theSubMesh );
119 }
120
121 void DriverMED_W_SMESHDS_Mesh::AddGroupOfNodes()
122 {
123   myDoGroupOfNodes = true;
124 }
125
126 void DriverMED_W_SMESHDS_Mesh::AddGroupOfEdges()
127 {
128   myDoGroupOfEdges = true;
129 }
130
131 void DriverMED_W_SMESHDS_Mesh::AddGroupOfFaces()
132 {
133   myDoGroupOfFaces = true;
134 }
135
136 void DriverMED_W_SMESHDS_Mesh::AddGroupOfVolumes()
137 {
138   myDoGroupOfVolumes = true;
139 }
140
141 void DriverMED_W_SMESHDS_Mesh::AddGroupOf0DElems()
142 {
143   myDoGroupOf0DElems = true;
144 }
145
146 void DriverMED_W_SMESHDS_Mesh::AddGroupOfBalls()
147 {
148   myDoGroupOfBalls = true;
149 }
150
151 //================================================================================
152 /*!
153  * \brief Set up a flag to add all elements not belonging to any group to
154  *        some auxiliary group. This is needed for SMESH -> SAUVE -> SMESH conversion,
155  *        which since PAL0023285 reads only SAUVE elements belonging to any group,
156  *        and hence can lose some elements. That auxiliary group is ignored while
157  *        reading a MED file.
158  */
159 //================================================================================
160
161 void DriverMED_W_SMESHDS_Mesh::AddAllToGroup()
162 {
163   myDoAllInGroups = true;
164 }
165
166
167 namespace
168 {
169   typedef double (SMDS_MeshNode::* TGetCoord)() const;
170   typedef const char* TName;
171   typedef const char* TUnit;
172
173   // name length in a mesh must be equal to 16 :
174   //         1234567890123456
175   TName M = "m               ";
176   TName X = "x               ";
177   TName Y = "y               ";
178   TName Z = "z               ";
179
180   TUnit aUnit[3] = {M,M,M};
181
182   // 3 dim
183   TGetCoord aXYZGetCoord[3] = {
184     &SMDS_MeshNode::X, 
185     &SMDS_MeshNode::Y, 
186     &SMDS_MeshNode::Z
187   };
188   TName aXYZName[3] = {X,Y,Z};
189   
190   // 2 dim
191   TGetCoord aXYGetCoord[2] = {
192     &SMDS_MeshNode::X, 
193     &SMDS_MeshNode::Y
194   };
195   TName aXYName[2] = {X,Y};
196
197   TGetCoord aYZGetCoord[2] = {
198     &SMDS_MeshNode::Y, 
199     &SMDS_MeshNode::Z
200   };
201   TName aYZName[2] = {Y,Z};
202
203   TGetCoord aXZGetCoord[2] = {
204     &SMDS_MeshNode::X, 
205     &SMDS_MeshNode::Z
206   };
207   TName aXZName[2] = {X,Z};
208
209   // 1 dim
210   TGetCoord aXGetCoord[1] = {
211     &SMDS_MeshNode::X
212   };
213   TName aXName[1] = {X};
214
215   TGetCoord aYGetCoord[1] = {
216     &SMDS_MeshNode::Y
217   };
218   TName aYName[1] = {Y};
219
220   TGetCoord aZGetCoord[1] = {
221     &SMDS_MeshNode::Z
222   };
223   TName aZName[1] = {Z};
224
225
226   class TCoordHelper{
227     SMDS_NodeIteratorPtr myNodeIter;
228     const SMDS_MeshNode* myCurrentNode;
229     TGetCoord* myGetCoord;
230     TName* myName;
231     TUnit* myUnit;
232   public:
233     TCoordHelper(const SMDS_NodeIteratorPtr& theNodeIter,
234                  TGetCoord* theGetCoord,
235                  TName* theName,
236                  TUnit* theUnit = aUnit):
237       myNodeIter(theNodeIter),
238       myGetCoord(theGetCoord),
239       myName(theName),
240       myUnit(theUnit)
241     {}
242     virtual ~TCoordHelper(){}
243     bool Next(){ 
244       return myNodeIter->more() && 
245         (myCurrentNode = myNodeIter->next());
246     }
247     const SMDS_MeshNode* GetNode(){
248       return myCurrentNode;
249     }
250     MED::TIDVector::value_type GetID(){
251       return myCurrentNode->GetID();
252     }
253     MED::TFloatVector::value_type GetCoord(TInt theCoodId){
254       return (myCurrentNode->*myGetCoord[theCoodId])();
255     }
256     MED::TStringVector::value_type GetName(TInt theDimId){
257       return myName[theDimId];
258     }
259     MED::TStringVector::value_type GetUnit(TInt theDimId){
260       return myUnit[theDimId];
261     }
262   };
263   typedef boost::shared_ptr<TCoordHelper> TCoordHelperPtr;
264
265   //-------------------------------------------------------
266   /*!
267    * \brief Structure describing element type
268    */
269   //-------------------------------------------------------
270   struct TElemTypeData
271   {
272     EEntiteMaillage     _entity;
273     EGeometrieElement   _geomType;
274     TInt                _nbElems;
275     SMDSAbs_ElementType _smdsType;
276
277     TElemTypeData (EEntiteMaillage entity, EGeometrieElement geom, TInt nb, SMDSAbs_ElementType type)
278       : _entity(entity), _geomType(geom), _nbElems( nb ), _smdsType( type ) {}
279   };
280
281
282   typedef NCollection_DataMap< Standard_Address, int > TElemFamilyMap;
283
284   //================================================================================
285   /*!
286    * \brief Fills element to famaly ID map for element type.
287    * Removes all families of anElemType
288    */
289   //================================================================================
290
291   void fillElemFamilyMap( TElemFamilyMap &            anElemFamMap,
292                           list<DriverMED_FamilyPtr> & aFamilies,
293                           const SMDSAbs_ElementType   anElemType)
294   {
295     anElemFamMap.Clear();
296     list<DriverMED_FamilyPtr>::iterator aFamsIter = aFamilies.begin();
297     while ( aFamsIter != aFamilies.end() )
298     {
299       if ((*aFamsIter)->GetType() != anElemType) {
300         aFamsIter++;
301       }
302       else {
303         int aFamId = (*aFamsIter)->GetId();
304         const ElementsSet&              anElems = (*aFamsIter)->GetElements();
305         ElementsSet::const_iterator anElemsIter = anElems.begin();
306         for (; anElemsIter != anElems.end(); anElemsIter++)
307         {
308           anElemFamMap.Bind( (Standard_Address)*anElemsIter, aFamId );
309         }
310         // remove a family from the list
311         aFamilies.erase( aFamsIter++ );
312       }
313     }
314   }
315
316   //================================================================================
317   /*!
318    * \brief For an element, return family ID found in the map or a default one
319    */
320   //================================================================================
321
322   int getFamilyId( const TElemFamilyMap &  anElemFamMap,
323                    const SMDS_MeshElement* anElement,
324                    const int               aDefaultFamilyId)
325   {
326     if ( anElemFamMap.IsBound( (Standard_Address) anElement ))
327       return anElemFamMap( (Standard_Address) anElement );
328
329     return aDefaultFamilyId;
330   }
331
332   //================================================================================
333   /*!
334    * \brief Returns iterator on sub-meshes
335    */
336   //================================================================================
337
338   SMESHDS_SubMeshIteratorPtr getIterator( std::vector<SMESHDS_SubMesh*>& mySubMeshes )
339   {
340     return SMESHDS_SubMeshIteratorPtr
341       ( new SMDS_SetIterator
342         < const SMESHDS_SubMesh*, std::vector< SMESHDS_SubMesh* >::iterator >( mySubMeshes.begin(),
343                                                                                mySubMeshes.end() ));
344   }
345 }
346
347 Driver_Mesh::Status DriverMED_W_SMESHDS_Mesh::Perform()
348 {
349   MED::PWrapper myMed = CrWrapperW(myFile, myVersion);
350   return this->PerformInternal<MED::PWrapper>(myMed);
351 }
352
353 Driver_Mesh::Status DriverMED_W_SMESHDS_Mesh_Mem::Perform()
354 {
355   void *ptr(nullptr);
356   std::size_t sz(0);
357   Driver_Mesh::Status status = Driver_Mesh::DRS_OK;
358   bool isClosed(false);
359   {// let braces to flush (call of MED::PWrapper myMed destructor)
360     TMemFile *tfileInst = new TMemFile(&ptr,&sz,&isClosed);// this new will be destroyed by destructor of myMed
361     MED::PWrapper myMed = CrWrapperW(myFile, -1, tfileInst);
362     status = this->PerformInternal<MED::PWrapper>(myMed);
363   }
364   if(!isClosed)
365     EXCEPTION(std::runtime_error, "TFTMemFile destructor : on destruction file has not been closed properly -> chunk of memory data may be invalid !");
366   _data = MEDCoupling::DataArrayByte::New();
367   _data->useArray(reinterpret_cast<char *>(ptr),true,MEDCoupling::DeallocType::C_DEALLOC,sz,1);
368   if(!isClosed)
369     THROW_SALOME_EXCEPTION("DriverMED_W_SMESHDS_Mesh_Mem::Perform - MED memory file id is supposed to be closed !");
370   return status;
371 }
372
373 //================================================================================
374 /*!
375  * \brief Write my mesh
376  */
377 //================================================================================
378
379 template<class LowLevelWriter>
380 Driver_Mesh::Status DriverMED_W_SMESHDS_Mesh::PerformInternal(LowLevelWriter myMed)
381 {
382   Status aResult = DRS_OK;
383   try {
384     //MESSAGE("Perform - myFile : "<<myFile);
385
386     if ( Driver_Mesh::IsMeshTooLarge< TInt >( myMesh, /*checkIDs =*/ true ))
387       return DRS_TOO_LARGE_MESH;
388
389     // Creating the MED mesh for corresponding SMDS structure
390     //-------------------------------------------------------
391     string aMeshName;
392     if (myMeshId != -1) {
393       ostringstream aMeshNameStr;
394       aMeshNameStr<<myMeshId;
395       aMeshName = aMeshNameStr.str();
396     } else {
397       aMeshName = myMeshName;
398     }
399
400     // Mesh dimension definition
401
402     TInt aMeshDimension = 0;
403     if ( myMesh->NbEdges() > 0 )
404       aMeshDimension = 1;
405     if ( myMesh->NbFaces() > 0 )
406       aMeshDimension = 2;
407     if ( myMesh->NbVolumes() > 0 )
408       aMeshDimension = 3;
409
410     TInt aSpaceDimension = 3;
411     TCoordHelperPtr aCoordHelperPtr;
412     {
413       bool anIsXDimension = false;
414       bool anIsYDimension = false;
415       bool anIsZDimension = false;
416       if ( myAutoDimension && aMeshDimension < 3 )
417       {
418         SMDS_NodeIteratorPtr aNodesIter = myMesh->nodesIterator();
419         double aBounds[6] = {0.,0.,0.,0.,0.,0.};
420         if(aNodesIter->more()){
421           const SMDS_MeshNode* aNode = aNodesIter->next();
422           aBounds[0] = aBounds[1] = aNode->X();
423           aBounds[2] = aBounds[3] = aNode->Y();
424           aBounds[4] = aBounds[5] = aNode->Z();
425         }
426         while(aNodesIter->more()){
427           const SMDS_MeshNode* aNode = aNodesIter->next();
428           aBounds[0] = min(aBounds[0],aNode->X());
429           aBounds[1] = max(aBounds[1],aNode->X());
430
431           aBounds[2] = min(aBounds[2],aNode->Y());
432           aBounds[3] = max(aBounds[3],aNode->Y());
433
434           aBounds[4] = min(aBounds[4],aNode->Z());
435           aBounds[5] = max(aBounds[5],aNode->Z());
436         }
437
438         double EPS = 1.0E-7;
439         TopoDS_Shape mainShape = myMesh->ShapeToMesh();
440         bool    hasShapeToMesh = ( myMesh->SubMeshIndices().size() > 1 );
441         if ( !mainShape.IsNull() && hasShapeToMesh )
442         {
443           // define EPS by max tolerance of the mainShape (IPAL53097)
444           TopExp_Explorer subShape;
445           for ( subShape.Init( mainShape, TopAbs_FACE ); subShape.More(); subShape.Next() ) {
446             EPS = Max( EPS, BRep_Tool::Tolerance( TopoDS::Face( subShape.Current() )));
447           }
448           for ( subShape.Init( mainShape, TopAbs_EDGE ); subShape.More(); subShape.Next() ) {
449             EPS = Max( EPS, BRep_Tool::Tolerance( TopoDS::Edge( subShape.Current() )));
450           }
451           for ( subShape.Init( mainShape, TopAbs_VERTEX ); subShape.More(); subShape.Next() ) {
452             EPS = Max( EPS, BRep_Tool::Tolerance( TopoDS::Vertex( subShape.Current() )));
453           }
454           EPS *= 2.;
455         }
456         anIsXDimension = (aBounds[1] - aBounds[0]) + abs(aBounds[1]) + abs(aBounds[0]) > EPS;
457         anIsYDimension = (aBounds[3] - aBounds[2]) + abs(aBounds[3]) + abs(aBounds[2]) > EPS;
458         anIsZDimension = (aBounds[5] - aBounds[4]) + abs(aBounds[5]) + abs(aBounds[4]) > EPS;
459         if ( myZTolerance > 0 && anIsZDimension )
460           anIsZDimension = (aBounds[5] > myZTolerance || aBounds[4] < -myZTolerance );
461         aSpaceDimension = Max( aMeshDimension, anIsXDimension + anIsYDimension + anIsZDimension );
462         if ( !aSpaceDimension )
463           aSpaceDimension = 3;
464         // PAL16857(SMESH not conform to the MED convention):
465         if ( aSpaceDimension == 2 && anIsZDimension ) // 2D only if mesh is in XOY plane
466           aSpaceDimension = 3;
467         // PAL18941(a saved study with a mesh belong Z is opened and the mesh is belong X)
468         if ( aSpaceDimension == 1 && !anIsXDimension ) {// 1D only if mesh is along OX
469           if ( anIsYDimension ) {
470             aSpaceDimension = 2;
471             anIsXDimension = true;
472           } else {
473             aSpaceDimension = 3;
474           }
475         }
476       }
477
478       SMDS_NodeIteratorPtr aNodesIter = myMesh->nodesIterator();
479       switch ( aSpaceDimension ) {
480       case 3:
481         aCoordHelperPtr.reset(new TCoordHelper(aNodesIter,aXYZGetCoord,aXYZName));
482         break;
483       case 2:
484         if(anIsXDimension && anIsYDimension)
485           aCoordHelperPtr.reset(new TCoordHelper(aNodesIter,aXYGetCoord,aXYName));
486         if(anIsYDimension && anIsZDimension)
487           aCoordHelperPtr.reset(new TCoordHelper(aNodesIter,aYZGetCoord,aYZName));
488         if(anIsXDimension && anIsZDimension)
489           aCoordHelperPtr.reset(new TCoordHelper(aNodesIter,aXZGetCoord,aXZName));
490         break;
491       case 1:
492         if(anIsXDimension)
493           aCoordHelperPtr.reset(new TCoordHelper(aNodesIter,aXGetCoord,aXName));
494         if(anIsYDimension)
495           aCoordHelperPtr.reset(new TCoordHelper(aNodesIter,aYGetCoord,aYName));
496         if(anIsZDimension)
497           aCoordHelperPtr.reset(new TCoordHelper(aNodesIter,aZGetCoord,aZName));
498         break;
499       }
500     }
501
502     PMeshInfo aMeshInfo = myMed->CrMeshInfo(aMeshDimension,aSpaceDimension,aMeshName);
503     //MESSAGE("Add - aMeshName : "<<aMeshName<<"; "<<aMeshInfo->GetName());
504     myMed->SetMeshInfo(aMeshInfo);
505
506     // Storing SMDS groups and sub-meshes as med families
507     //----------------------------------------------------
508     int myNodesDefaultFamilyId      = 0;
509     int my0DElementsDefaultFamilyId = 0;
510     int myBallsDefaultFamilyId      = 0;
511     int myEdgesDefaultFamilyId      = 0;
512     int myFacesDefaultFamilyId      = 0;
513     int myVolumesDefaultFamilyId    = 0;
514     smIdType nbNodes      = myMesh->NbNodes();
515     smIdType nb0DElements = myMesh->Nb0DElements();
516     smIdType nbBalls      = myMesh->NbBalls();
517     smIdType nbEdges      = myMesh->NbEdges();
518     smIdType nbFaces      = myMesh->NbFaces();
519     smIdType nbVolumes    = myMesh->NbVolumes();
520     if (myDoGroupOfNodes)   myNodesDefaultFamilyId      = REST_NODES_FAMILY;
521     if (myDoGroupOfEdges)   myEdgesDefaultFamilyId      = REST_EDGES_FAMILY;
522     if (myDoGroupOfFaces)   myFacesDefaultFamilyId      = REST_FACES_FAMILY;
523     if (myDoGroupOfVolumes) myVolumesDefaultFamilyId    = REST_VOLUMES_FAMILY;
524     if (myDoGroupOf0DElems) my0DElementsDefaultFamilyId = REST_0DELEM_FAMILY;
525     if (myDoGroupOfBalls)   myBallsDefaultFamilyId      = REST_BALL_FAMILY;
526     if (myDoAllInGroups )
527     {
528       if (!myDoGroupOfEdges)   myEdgesDefaultFamilyId      = NIG_EDGES_FAMILY   ;
529       if (!myDoGroupOfFaces)   myFacesDefaultFamilyId      = NIG_FACES_FAMILY   ;
530       if (!myDoGroupOfVolumes) myVolumesDefaultFamilyId    = NIG_VOLS_FAMILY    ;
531       if (!myDoGroupOf0DElems) my0DElementsDefaultFamilyId = NIG_0DELEM_FAMILY  ;
532       if (!myDoGroupOfBalls)   myBallsDefaultFamilyId      = NIG_BALL_FAMILY    ;
533     }
534
535     //MESSAGE("Perform - aFamilyInfo");
536     list<DriverMED_FamilyPtr> aFamilies;
537     if (myAllSubMeshes) {
538       aFamilies = DriverMED_Family::MakeFamilies
539         (myMesh->SubMeshes(), myGroups,
540          myDoGroupOfNodes   && nbNodes,
541          myDoGroupOfEdges   && nbEdges,
542          myDoGroupOfFaces   && nbFaces,
543          myDoGroupOfVolumes && nbVolumes,
544          myDoGroupOf0DElems && nb0DElements,
545          myDoGroupOfBalls   && nbBalls,
546          myDoAllInGroups);
547     }
548     else {
549       aFamilies = DriverMED_Family::MakeFamilies
550         (getIterator( mySubMeshes ), myGroups,
551          myDoGroupOfNodes   && nbNodes,
552          myDoGroupOfEdges   && nbEdges,
553          myDoGroupOfFaces   && nbFaces,
554          myDoGroupOfVolumes && nbVolumes,
555          myDoGroupOf0DElems && nb0DElements,
556          myDoGroupOfBalls   && nbBalls,
557          myDoAllInGroups);
558     }
559     list<DriverMED_FamilyPtr>::iterator aFamsIter;
560     for (aFamsIter = aFamilies.begin(); aFamsIter != aFamilies.end(); aFamsIter++)
561     {
562       PFamilyInfo aFamilyInfo = (*aFamsIter)->GetFamilyInfo<LowLevelWriter>(myMed,aMeshInfo);
563       myMed->SetFamilyInfo(aFamilyInfo);
564     }
565
566     // Storing SMDS nodes to the MED file for the MED mesh
567     //----------------------------------------------------
568 #ifdef _EDF_NODE_IDS_
569     typedef map<TInt,TInt> TNodeIdMap;
570     TNodeIdMap aNodeIdMap;
571 #endif
572     const EModeSwitch   theMode        = eFULL_INTERLACE;
573     const ERepere       theSystem      = eCART;
574     const EBooleen      theIsElemNum   = eVRAI;
575     const EBooleen      theIsElemNames = eFAUX;
576     const EConnectivite theConnMode    = eNOD;
577
578     TInt aNbNodes = FromSmIdType<TInt>( myMesh->NbNodes() );
579     PNodeInfo aNodeInfo = myMed->CrNodeInfo(aMeshInfo, aNbNodes,
580                                             theMode, theSystem, theIsElemNum, theIsElemNames);
581
582     // find family numbers for nodes
583     TElemFamilyMap anElemFamMap;
584     fillElemFamilyMap( anElemFamMap, aFamilies, SMDSAbs_Node );
585
586     for (TInt iNode = 0; aCoordHelperPtr->Next(); iNode++)
587     {
588       // coordinates
589       TCoordSlice aTCoordSlice = aNodeInfo->GetCoordSlice( iNode );
590       for(TInt iCoord = 0; iCoord < aSpaceDimension; iCoord++){
591         aTCoordSlice[iCoord] = aCoordHelperPtr->GetCoord(iCoord);
592       }
593       if ( aSpaceDimension == 3 &&
594            -myZTolerance < aTCoordSlice[2] && aTCoordSlice[2] < myZTolerance )
595         aTCoordSlice[2] = 0.;
596
597       // node number
598       TInt aNodeID = FromSmIdType<TInt>( aCoordHelperPtr->GetID() );
599       aNodeInfo->SetElemNum( iNode, aNodeID );
600 #ifdef _EDF_NODE_IDS_
601       aNodeIdMap.insert( aNodeIdMap.end(), make_pair( aNodeID, iNode+1 ));
602 #endif
603       // family number
604       const SMDS_MeshNode* aNode = aCoordHelperPtr->GetNode();
605       int famNum = getFamilyId( anElemFamMap, aNode, myNodesDefaultFamilyId );
606       aNodeInfo->SetFamNum( iNode, famNum );
607     }
608     anElemFamMap.Clear();
609
610     // coordinate names and units
611     for (TInt iCoord = 0; iCoord < aSpaceDimension; iCoord++) {
612       aNodeInfo->SetCoordName( iCoord, aCoordHelperPtr->GetName(iCoord));
613       aNodeInfo->SetCoordUnit( iCoord, aCoordHelperPtr->GetUnit(iCoord));
614     }
615
616     //MESSAGE("Perform - aNodeInfo->GetNbElem() = "<<aNbNodes);
617     myMed->SetNodeInfo(aNodeInfo);
618     aNodeInfo.reset(); // free memory used for arrays
619
620
621     // Storing SMDS elements to the MED file for the MED mesh
622     //-------------------------------------------------------
623     // Write one element type at once in order to minimize memory usage (PAL19276)
624
625     const SMDS_MeshInfo& nbElemInfo = myMesh->GetMeshInfo();
626
627     // poly elements are not supported by med-2.1
628     bool polyTypesSupported = ( myMed->CrPolygoneInfo(aMeshInfo,eMAILLE,ePOLYGONE,0,0).get() != 0 );
629     TInt nbPolygonNodes = 0, nbPolyhedronNodes = 0, nbPolyhedronFaces = 0;
630
631     // nodes on VERTEXes where 0D elements are absent
632     std::vector<const SMDS_MeshElement*> nodesOf0D;
633     std::vector< SMDS_ElemIteratorPtr > iterVec;
634     SMDS_ElemIteratorPtr iterVecIter;
635     if ( myAddODOnVertices && getNodesOfMissing0DOnVert( myMesh, nodesOf0D ))
636     {
637       iterVec.resize(2);
638       iterVec[0] = myMesh->elementsIterator( SMDSAbs_0DElement );
639       iterVec[1] = SMDS_ElemIteratorPtr
640         ( new SMDS_ElementVectorIterator( nodesOf0D.begin(), nodesOf0D.end() ));
641
642       typedef SMDS_IteratorOnIterators
643         < const SMDS_MeshElement *, std::vector< SMDS_ElemIteratorPtr > > TItIterator;
644       iterVecIter = SMDS_ElemIteratorPtr( new TItIterator( iterVec ));
645     }
646
647     // collect info on all geom types
648
649     list< TElemTypeData > aTElemTypeDatas;
650
651     EEntiteMaillage anEntity = eMAILLE;
652 #ifdef _ELEMENTS_BY_DIM_
653     anEntity = eNOEUD_ELEMENT;
654 #endif
655     aTElemTypeDatas.push_back(TElemTypeData(anEntity,
656                                             ePOINT1,
657                                             nbElemInfo.Nb0DElements() + nodesOf0D.size(),
658                                             SMDSAbs_0DElement));
659 #ifdef _ELEMENTS_BY_DIM_
660     anEntity = eSTRUCT_ELEMENT;
661 #endif
662     aTElemTypeDatas.push_back( TElemTypeData(anEntity,
663                                              eBALL,
664                                              FromSmIdType<TInt>(nbElemInfo.NbBalls()),
665                                              SMDSAbs_Ball));
666 #ifdef _ELEMENTS_BY_DIM_
667     anEntity = eARETE;
668 #endif
669     aTElemTypeDatas.push_back( TElemTypeData(anEntity,
670                                              eSEG2,
671                                              FromSmIdType<TInt>(nbElemInfo.NbEdges( ORDER_LINEAR )),
672                                              SMDSAbs_Edge));
673     aTElemTypeDatas.push_back( TElemTypeData(anEntity,
674                                              eSEG3,
675                                              FromSmIdType<TInt>(nbElemInfo.NbEdges( ORDER_QUADRATIC )),
676                                              SMDSAbs_Edge));
677 #ifdef _ELEMENTS_BY_DIM_
678     anEntity = eFACE;
679 #endif
680     aTElemTypeDatas.push_back( TElemTypeData(anEntity,
681                                              eTRIA3,
682                                              FromSmIdType<TInt>(nbElemInfo.NbTriangles( ORDER_LINEAR )),
683                                              SMDSAbs_Face));
684     aTElemTypeDatas.push_back( TElemTypeData(anEntity,
685                                              eTRIA6,
686                                              FromSmIdType<TInt>(nbElemInfo.NbTriangles( ORDER_QUADRATIC ) -
687                                              nbElemInfo.NbBiQuadTriangles()),
688                                              SMDSAbs_Face));
689     aTElemTypeDatas.push_back( TElemTypeData(anEntity,
690                                              eTRIA7,
691                                              FromSmIdType<TInt>(nbElemInfo.NbBiQuadTriangles()),
692                                              SMDSAbs_Face));
693     aTElemTypeDatas.push_back( TElemTypeData(anEntity,
694                                              eQUAD4,
695                                              FromSmIdType<TInt>(nbElemInfo.NbQuadrangles( ORDER_LINEAR )),
696                                              SMDSAbs_Face));
697     aTElemTypeDatas.push_back( TElemTypeData(anEntity,
698                                              eQUAD8,
699                                              FromSmIdType<TInt>(nbElemInfo.NbQuadrangles( ORDER_QUADRATIC ) -
700                                              nbElemInfo.NbBiQuadQuadrangles()),
701                                              SMDSAbs_Face));
702     aTElemTypeDatas.push_back( TElemTypeData(anEntity,
703                                              eQUAD9,
704                                              FromSmIdType<TInt>(nbElemInfo.NbBiQuadQuadrangles()),
705                                              SMDSAbs_Face));
706     if ( polyTypesSupported ) {
707       aTElemTypeDatas.push_back( TElemTypeData(anEntity,
708                                                ePOLYGONE,
709                                                FromSmIdType<TInt>(nbElemInfo.NbPolygons( ORDER_LINEAR )),
710                                                SMDSAbs_Face));
711       // we need one more loop on poly elements to count nb of their nodes
712       aTElemTypeDatas.push_back( TElemTypeData(anEntity,
713                                                ePOLYGONE,
714                                                FromSmIdType<TInt>(nbElemInfo.NbPolygons( ORDER_LINEAR )),
715                                                SMDSAbs_Face));
716       aTElemTypeDatas.push_back( TElemTypeData(anEntity,
717                                                ePOLYGON2,
718                                                FromSmIdType<TInt>(nbElemInfo.NbPolygons( ORDER_QUADRATIC )),
719                                                SMDSAbs_Face));
720       // we need one more loop on QUAD poly elements to count nb of their nodes
721       aTElemTypeDatas.push_back( TElemTypeData(anEntity,
722                                                ePOLYGON2,
723                                                FromSmIdType<TInt>(nbElemInfo.NbPolygons( ORDER_QUADRATIC )),
724                                                SMDSAbs_Face));
725     }
726 #ifdef _ELEMENTS_BY_DIM_
727     anEntity = eMAILLE;
728 #endif
729     aTElemTypeDatas.push_back( TElemTypeData(anEntity,
730                                              eTETRA4,
731                                              FromSmIdType<TInt>(nbElemInfo.NbTetras( ORDER_LINEAR )),
732                                              SMDSAbs_Volume));
733     aTElemTypeDatas.push_back( TElemTypeData(anEntity,
734                                              eTETRA10,
735                                              FromSmIdType<TInt>(nbElemInfo.NbTetras( ORDER_QUADRATIC )),
736                                              SMDSAbs_Volume));
737     aTElemTypeDatas.push_back( TElemTypeData(anEntity,
738                                              ePYRA5,
739                                              FromSmIdType<TInt>(nbElemInfo.NbPyramids( ORDER_LINEAR )),
740                                              SMDSAbs_Volume));
741     aTElemTypeDatas.push_back( TElemTypeData(anEntity,
742                                              ePYRA13,
743                                              FromSmIdType<TInt>(nbElemInfo.NbPyramids( ORDER_QUADRATIC )),
744                                              SMDSAbs_Volume));
745     aTElemTypeDatas.push_back( TElemTypeData(anEntity,
746                                              ePENTA6,
747                                              FromSmIdType<TInt>(nbElemInfo.NbPrisms( ORDER_LINEAR )),
748                                              SMDSAbs_Volume));
749     aTElemTypeDatas.push_back( TElemTypeData(anEntity,
750                                              ePENTA15,
751                                              FromSmIdType<TInt>(nbElemInfo.NbQuadPrisms()),
752                                              SMDSAbs_Volume));
753     aTElemTypeDatas.push_back( TElemTypeData(anEntity,
754                                              ePENTA18,
755                                              FromSmIdType<TInt>(nbElemInfo.NbBiQuadPrisms()),
756                                              SMDSAbs_Volume));
757     aTElemTypeDatas.push_back( TElemTypeData(anEntity,
758                                              eHEXA8,
759                                              FromSmIdType<TInt>(nbElemInfo.NbHexas( ORDER_LINEAR )),
760                                              SMDSAbs_Volume));
761     aTElemTypeDatas.push_back( TElemTypeData(anEntity,
762                                              eHEXA20,
763                                              FromSmIdType<TInt>(nbElemInfo.NbHexas( ORDER_QUADRATIC )-
764                                              nbElemInfo.NbTriQuadHexas()),
765                                              SMDSAbs_Volume));
766     aTElemTypeDatas.push_back( TElemTypeData(anEntity,
767                                              eHEXA27,
768                                              FromSmIdType<TInt>(nbElemInfo.NbTriQuadHexas()),
769                                              SMDSAbs_Volume));
770     aTElemTypeDatas.push_back( TElemTypeData(anEntity,
771                                              eOCTA12,
772                                              FromSmIdType<TInt>(nbElemInfo.NbHexPrisms()),
773                                              SMDSAbs_Volume));
774     if ( polyTypesSupported ) {
775       aTElemTypeDatas.push_back( TElemTypeData(anEntity,
776                                                ePOLYEDRE,
777                                                FromSmIdType<TInt>(nbElemInfo.NbPolyhedrons()),
778                                                SMDSAbs_Volume));
779       // we need one more loop on poly elements to count nb of their nodes
780       aTElemTypeDatas.push_back( TElemTypeData(anEntity,
781                                                ePOLYEDRE,
782                                                FromSmIdType<TInt>(nbElemInfo.NbPolyhedrons()),
783                                                SMDSAbs_Volume));
784     }
785
786     vector< bool > isElemFamMapBuilt( SMDSAbs_NbElementTypes, false );
787
788     // loop on all geom types of elements
789
790     list< TElemTypeData >::iterator aElemTypeData = aTElemTypeDatas.begin();
791     for ( ; aElemTypeData != aTElemTypeDatas.end(); ++aElemTypeData )
792     {
793       if ( aElemTypeData->_nbElems == 0 )
794         continue;
795
796       int defaultFamilyId = 0;
797       switch ( aElemTypeData->_smdsType ) {
798       case SMDSAbs_0DElement: defaultFamilyId = my0DElementsDefaultFamilyId; break;
799       case SMDSAbs_Ball:      defaultFamilyId = myBallsDefaultFamilyId;      break;
800       case SMDSAbs_Edge:      defaultFamilyId = myEdgesDefaultFamilyId;      break;
801       case SMDSAbs_Face:      defaultFamilyId = myFacesDefaultFamilyId;      break;
802       case SMDSAbs_Volume:    defaultFamilyId = myVolumesDefaultFamilyId;    break;
803       default:
804         continue;
805       }
806
807       // build map of family numbers for this type
808       if ( !isElemFamMapBuilt[ aElemTypeData->_smdsType ])
809       {
810         fillElemFamilyMap( anElemFamMap, aFamilies, aElemTypeData->_smdsType );
811         isElemFamMapBuilt[ aElemTypeData->_smdsType ] = true;
812       }
813
814       // iterator on elements of a current type
815       SMDS_ElemIteratorPtr elemIterator;
816       TInt iElem = 0;
817
818       // Treat POLYGONs
819       // ---------------
820       if ( aElemTypeData->_geomType == ePOLYGONE ||
821            aElemTypeData->_geomType == ePOLYGON2 )
822       {
823         if ( aElemTypeData->_geomType == ePOLYGONE )
824           elemIterator = myMesh->elementEntityIterator( SMDSEntity_Polygon );
825         else
826           elemIterator = myMesh->elementEntityIterator( SMDSEntity_Quad_Polygon );
827
828         if ( nbPolygonNodes == 0 ) {
829           // Count nb of nodes
830           while ( elemIterator->more() ) {
831             const SMDS_MeshElement* anElem = elemIterator->next();
832             nbPolygonNodes += anElem->NbNodes();
833             if ( ++iElem == aElemTypeData->_nbElems )
834               break;
835           }
836         }
837         else {
838           // Store in med file
839           PPolygoneInfo aPolygoneInfo = myMed->CrPolygoneInfo(aMeshInfo,
840                                                               aElemTypeData->_entity,
841                                                               aElemTypeData->_geomType,
842                                                               aElemTypeData->_nbElems,
843                                                               nbPolygonNodes,
844                                                               theConnMode, theIsElemNum,
845                                                               theIsElemNames);
846           TElemNum & index = *(aPolygoneInfo->myIndex.get());
847           index[0] = 1;
848
849           while ( elemIterator->more() )
850           {
851             const SMDS_MeshElement* anElem = elemIterator->next();
852             // index
853             TInt aNbNodes = anElem->NbNodes();
854             index[ iElem+1 ] = index[ iElem ] + aNbNodes;
855
856             // connectivity
857             TConnSlice aTConnSlice = aPolygoneInfo->GetConnSlice( iElem );
858             for(TInt iNode = 0; iNode < aNbNodes; iNode++) {
859               const SMDS_MeshElement* aNode = anElem->GetNode( iNode );
860 #ifdef _EDF_NODE_IDS_
861               aTConnSlice[ iNode ] = aNodeIdMap[FromSmIdType<TInt>(aNode->GetID())];
862 #else
863               aTConnSlice[ iNode ] = aNode->GetID();
864 #endif
865             }
866             // element number
867             aPolygoneInfo->SetElemNum( iElem, FromSmIdType<TInt>(anElem->GetID()) );
868
869             // family number
870             int famNum = getFamilyId( anElemFamMap, anElem, defaultFamilyId );
871             aPolygoneInfo->SetFamNum( iElem, famNum );
872
873             if ( ++iElem == aPolygoneInfo->GetNbElem() )
874               break;
875           }
876           myMed->SetPolygoneInfo(aPolygoneInfo);
877
878           nbPolygonNodes = 0; // to treat next polygon type
879         }
880       }
881
882       // Treat POLYEDREs
883       // ----------------
884       else if ( aElemTypeData->_geomType == ePOLYEDRE )
885       {
886         elemIterator = myMesh->elementGeomIterator( SMDSGeom_POLYHEDRA );
887
888         if ( nbPolyhedronNodes == 0 ) {
889           // Count nb of nodes
890           while ( elemIterator->more() ) {
891             const SMDS_MeshElement*  anElem = elemIterator->next();
892             nbPolyhedronNodes += anElem->NbNodes();
893             nbPolyhedronFaces += anElem->NbFaces();
894             if ( ++iElem == aElemTypeData->_nbElems )
895               break;
896           }
897         }
898         else {
899           // Store in med file
900           PPolyedreInfo aPolyhInfo = myMed->CrPolyedreInfo(aMeshInfo,
901                                                            aElemTypeData->_entity,
902                                                            aElemTypeData->_geomType,
903                                                            aElemTypeData->_nbElems,
904                                                            nbPolyhedronFaces+1,
905                                                            nbPolyhedronNodes,
906                                                            theConnMode,
907                                                            theIsElemNum,
908                                                            theIsElemNames);
909           TElemNum & index = *(aPolyhInfo->myIndex.get());
910           TElemNum & faces = *(aPolyhInfo->myFaces.get());
911           TElemNum & conn  = *(aPolyhInfo->myConn.get());
912           index[0] = 1;
913           faces[0] = 1;
914
915           TInt iFace = 0, iNode = 0;
916           while ( elemIterator->more() )
917           {
918             const SMDS_MeshElement* anElem = elemIterator->next();
919             const SMDS_MeshVolume *aPolyedre = myMesh->DownCast< SMDS_MeshVolume >( anElem );
920             if ( !aPolyedre ) continue;
921             // index
922             TInt aNbFaces = aPolyedre->NbFaces();
923             index[ iElem+1 ] = index[ iElem ] + aNbFaces;
924
925             // face index
926             for (TInt f = 1; f <= aNbFaces; ++f, ++iFace ) {
927               int aNbFaceNodes = aPolyedre->NbFaceNodes( f );
928               faces[ iFace+1 ] = faces[ iFace ] + aNbFaceNodes;
929             }
930             // connectivity
931             SMDS_ElemIteratorPtr nodeIt = anElem->nodesIterator();
932             while ( nodeIt->more() ) {
933               const SMDS_MeshElement* aNode = nodeIt->next();
934 #ifdef _EDF_NODE_IDS_
935               conn[ iNode ] = aNodeIdMap[FromSmIdType<TInt>(aNode->GetID())];
936 #else
937               conn[ iNode ] = aNode->GetID();
938 #endif
939               ++iNode;
940             }
941             // element number
942             aPolyhInfo->SetElemNum( iElem, FromSmIdType<TInt>(anElem->GetID()) );
943
944             // family number
945             int famNum = getFamilyId( anElemFamMap, anElem, defaultFamilyId );
946             aPolyhInfo->SetFamNum( iElem, famNum );
947
948             if ( ++iElem == aPolyhInfo->GetNbElem() )
949               break;
950           }
951           myMed->SetPolyedreInfo(aPolyhInfo);
952         }
953       } // if (aElemTypeData->_geomType == ePOLYEDRE )
954
955       // Treat BALLs
956       // ----------------
957       else if (aElemTypeData->_geomType == eBALL )
958       {
959         // allocate data arrays
960         PBallInfo aBallInfo = myMed->CrBallInfo( aMeshInfo, aElemTypeData->_nbElems );
961
962         elemIterator = myMesh->elementsIterator( SMDSAbs_Ball );
963         while ( elemIterator->more() )
964         {
965           const SMDS_MeshElement* anElem = elemIterator->next();
966           // connectivity
967           const SMDS_MeshElement* aNode = anElem->GetNode( 0 );
968 #ifdef _EDF_NODE_IDS_
969           (*aBallInfo->myConn)[ iElem ] = aNodeIdMap[FromSmIdType<TInt>(aNode->GetID())];
970 #else
971           (*aBallInfo->myConn)[ iElem ] = aNode->GetID();
972 #endif
973           // element number
974           aBallInfo->SetElemNum( iElem, FromSmIdType<TInt>(anElem->GetID()) );
975
976           // diameter
977           aBallInfo->myDiameters[ iElem ] =
978             static_cast<const SMDS_BallElement*>( anElem )->GetDiameter();
979
980           // family number
981           int famNum = getFamilyId( anElemFamMap, anElem, defaultFamilyId );
982           aBallInfo->SetFamNum( iElem, famNum );
983           ++iElem;
984         }
985         // store data in a file
986         myMed->SetBallInfo(aBallInfo);
987       }
988
989       else
990       {
991         // Treat standard types
992         // ---------------------
993         // allocate data arrays
994         PCellInfo aCellInfo = myMed->CrCellInfo( aMeshInfo,
995                                                  aElemTypeData->_entity,
996                                                  aElemTypeData->_geomType,
997                                                  aElemTypeData->_nbElems,
998                                                  theConnMode,
999                                                  theIsElemNum,
1000                                                  theIsElemNames);
1001
1002         TInt aNbNodes = MED::GetNbNodes(aElemTypeData->_geomType);
1003         elemIterator = myMesh->elementsIterator( aElemTypeData->_smdsType );
1004         if ( aElemTypeData->_smdsType == SMDSAbs_0DElement && ! nodesOf0D.empty() )
1005           elemIterator = iterVecIter;
1006         while ( elemIterator->more() )
1007         {
1008           const SMDS_MeshElement* anElem = elemIterator->next();
1009           if ( anElem->NbNodes() != aNbNodes || anElem->IsPoly() )
1010             continue; // other geometry
1011
1012           // connectivity
1013           TConnSlice aTConnSlice = aCellInfo->GetConnSlice( iElem );
1014           for (TInt iNode = 0; iNode < aNbNodes; iNode++) {
1015             const SMDS_MeshElement* aNode = anElem->GetNode( iNode );
1016 #ifdef _EDF_NODE_IDS_
1017             aTConnSlice[ iNode ] = aNodeIdMap[FromSmIdType<TInt>(aNode->GetID())];
1018 #else
1019             aTConnSlice[ iNode ] = aNode->GetID();
1020 #endif
1021           }
1022           // element number
1023           aCellInfo->SetElemNum( iElem, FromSmIdType<TInt>(anElem->GetID()) );
1024
1025           // family number
1026           int famNum = getFamilyId( anElemFamMap, anElem, defaultFamilyId );
1027           aCellInfo->SetFamNum( iElem, famNum );
1028
1029           if ( ++iElem == aCellInfo->GetNbElem() )
1030             break;
1031         }
1032         // store data in a file
1033         myMed->SetCellInfo(aCellInfo);
1034       }
1035     } // loop on geom types
1036   }
1037   catch(const std::exception& exc) {
1038     INFOS("The following exception was caught:\n\t"<<exc.what());
1039     throw;
1040   }
1041   catch(...) {
1042     INFOS("Unknown exception was caught !!!");
1043     throw;
1044   }
1045
1046   myMeshId = -1;
1047   myGroups.clear();
1048   mySubMeshes.clear();
1049   return aResult;
1050 }
1051
1052 //================================================================================
1053 /*!
1054  * \brief Returns nodes on VERTEXes where 0D elements are absent
1055  */
1056 //================================================================================
1057
1058 bool DriverMED_W_SMESHDS_Mesh::
1059 getNodesOfMissing0DOnVert(SMESHDS_Mesh*                         meshDS,
1060                           std::vector<const SMDS_MeshElement*>& nodes)
1061 {
1062   nodes.clear();
1063   for ( int i = 1; i <= meshDS->MaxShapeIndex(); ++i )
1064   {
1065     if ( meshDS->IndexToShape( i ).ShapeType() != TopAbs_VERTEX )
1066       continue;
1067     if ( SMESHDS_SubMesh* sm = meshDS->MeshElements(i) ) {
1068       SMDS_NodeIteratorPtr nIt= sm->GetNodes();
1069       while (nIt->more())
1070       {
1071         const SMDS_MeshNode* n = nIt->next();
1072         if ( n->NbInverseElements( SMDSAbs_0DElement ) == 0 )
1073           nodes.push_back( n );
1074       }
1075     }
1076   }
1077   return !nodes.empty();
1078 }