Salome HOME
d09ce5713b43ab571fc0347b83e24fa2eef90d90
[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 "MEDCoupling_Wrapper.hxx"
34 #include "SMDS_IteratorOnIterators.hxx"
35 #include "SMDS_MeshNode.hxx"
36 #include "SMDS_SetIterator.hxx"
37 #include "SMESHDS_Mesh.hxx"
38 #include "MED_Common.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::PerformMedcoupling()
354 {
355   MED::MCPWrapper myMed(new MED::MCTWrapper);
356   return this->PerformInternal<MED::MCPWrapper>(myMed);
357 }
358
359 //================================================================================
360 /*!
361  * \brief Write my mesh
362  */
363 //================================================================================
364
365 template<class LowLevelWriter>
366 Driver_Mesh::Status DriverMED_W_SMESHDS_Mesh::PerformInternal(LowLevelWriter myMed)
367 {
368   Status aResult = DRS_OK;
369   try {
370     //MESSAGE("Perform - myFile : "<<myFile);
371
372     if ( Driver_Mesh::IsMeshTooLarge< TInt >( myMesh, /*checkIDs =*/ true ))
373       return DRS_TOO_LARGE_MESH;
374
375     // Creating the MED mesh for corresponding SMDS structure
376     //-------------------------------------------------------
377     string aMeshName;
378     if (myMeshId != -1) {
379       ostringstream aMeshNameStr;
380       aMeshNameStr<<myMeshId;
381       aMeshName = aMeshNameStr.str();
382     } else {
383       aMeshName = myMeshName;
384     }
385
386     // Mesh dimension definition
387
388     TInt aMeshDimension = 0;
389     if ( myMesh->NbEdges() > 0 )
390       aMeshDimension = 1;
391     if ( myMesh->NbFaces() > 0 )
392       aMeshDimension = 2;
393     if ( myMesh->NbVolumes() > 0 )
394       aMeshDimension = 3;
395
396     TInt aSpaceDimension = 3;
397     TCoordHelperPtr aCoordHelperPtr;
398     {
399       bool anIsXDimension = false;
400       bool anIsYDimension = false;
401       bool anIsZDimension = false;
402       if ( myAutoDimension && aMeshDimension < 3 )
403       {
404         SMDS_NodeIteratorPtr aNodesIter = myMesh->nodesIterator();
405         double aBounds[6] = {0.,0.,0.,0.,0.,0.};
406         if(aNodesIter->more()){
407           const SMDS_MeshNode* aNode = aNodesIter->next();
408           aBounds[0] = aBounds[1] = aNode->X();
409           aBounds[2] = aBounds[3] = aNode->Y();
410           aBounds[4] = aBounds[5] = aNode->Z();
411         }
412         while(aNodesIter->more()){
413           const SMDS_MeshNode* aNode = aNodesIter->next();
414           aBounds[0] = min(aBounds[0],aNode->X());
415           aBounds[1] = max(aBounds[1],aNode->X());
416
417           aBounds[2] = min(aBounds[2],aNode->Y());
418           aBounds[3] = max(aBounds[3],aNode->Y());
419
420           aBounds[4] = min(aBounds[4],aNode->Z());
421           aBounds[5] = max(aBounds[5],aNode->Z());
422         }
423
424         double EPS = 1.0E-7;
425         TopoDS_Shape mainShape = myMesh->ShapeToMesh();
426         bool    hasShapeToMesh = ( myMesh->SubMeshIndices().size() > 1 );
427         if ( !mainShape.IsNull() && hasShapeToMesh )
428         {
429           // define EPS by max tolerance of the mainShape (IPAL53097)
430           TopExp_Explorer subShape;
431           for ( subShape.Init( mainShape, TopAbs_FACE ); subShape.More(); subShape.Next() ) {
432             EPS = Max( EPS, BRep_Tool::Tolerance( TopoDS::Face( subShape.Current() )));
433           }
434           for ( subShape.Init( mainShape, TopAbs_EDGE ); subShape.More(); subShape.Next() ) {
435             EPS = Max( EPS, BRep_Tool::Tolerance( TopoDS::Edge( subShape.Current() )));
436           }
437           for ( subShape.Init( mainShape, TopAbs_VERTEX ); subShape.More(); subShape.Next() ) {
438             EPS = Max( EPS, BRep_Tool::Tolerance( TopoDS::Vertex( subShape.Current() )));
439           }
440           EPS *= 2.;
441         }
442         anIsXDimension = (aBounds[1] - aBounds[0]) + abs(aBounds[1]) + abs(aBounds[0]) > EPS;
443         anIsYDimension = (aBounds[3] - aBounds[2]) + abs(aBounds[3]) + abs(aBounds[2]) > EPS;
444         anIsZDimension = (aBounds[5] - aBounds[4]) + abs(aBounds[5]) + abs(aBounds[4]) > EPS;
445         if ( myZTolerance > 0 && anIsZDimension )
446           anIsZDimension = (aBounds[5] > myZTolerance || aBounds[4] < -myZTolerance );
447         aSpaceDimension = Max( aMeshDimension, anIsXDimension + anIsYDimension + anIsZDimension );
448         if ( !aSpaceDimension )
449           aSpaceDimension = 3;
450         // PAL16857(SMESH not conform to the MED convention):
451         if ( aSpaceDimension == 2 && anIsZDimension ) // 2D only if mesh is in XOY plane
452           aSpaceDimension = 3;
453         // PAL18941(a saved study with a mesh belong Z is opened and the mesh is belong X)
454         if ( aSpaceDimension == 1 && !anIsXDimension ) {// 1D only if mesh is along OX
455           if ( anIsYDimension ) {
456             aSpaceDimension = 2;
457             anIsXDimension = true;
458           } else {
459             aSpaceDimension = 3;
460           }
461         }
462       }
463
464       SMDS_NodeIteratorPtr aNodesIter = myMesh->nodesIterator();
465       switch ( aSpaceDimension ) {
466       case 3:
467         aCoordHelperPtr.reset(new TCoordHelper(aNodesIter,aXYZGetCoord,aXYZName));
468         break;
469       case 2:
470         if(anIsXDimension && anIsYDimension)
471           aCoordHelperPtr.reset(new TCoordHelper(aNodesIter,aXYGetCoord,aXYName));
472         if(anIsYDimension && anIsZDimension)
473           aCoordHelperPtr.reset(new TCoordHelper(aNodesIter,aYZGetCoord,aYZName));
474         if(anIsXDimension && anIsZDimension)
475           aCoordHelperPtr.reset(new TCoordHelper(aNodesIter,aXZGetCoord,aXZName));
476         break;
477       case 1:
478         if(anIsXDimension)
479           aCoordHelperPtr.reset(new TCoordHelper(aNodesIter,aXGetCoord,aXName));
480         if(anIsYDimension)
481           aCoordHelperPtr.reset(new TCoordHelper(aNodesIter,aYGetCoord,aYName));
482         if(anIsZDimension)
483           aCoordHelperPtr.reset(new TCoordHelper(aNodesIter,aZGetCoord,aZName));
484         break;
485       }
486     }
487
488     PMeshInfo aMeshInfo = myMed->CrMeshInfo(aMeshDimension,aSpaceDimension,aMeshName);
489     //MESSAGE("Add - aMeshName : "<<aMeshName<<"; "<<aMeshInfo->GetName());
490     myMed->SetMeshInfo(aMeshInfo);
491
492     // Storing SMDS groups and sub-meshes as med families
493     //----------------------------------------------------
494     int myNodesDefaultFamilyId      = 0;
495     int my0DElementsDefaultFamilyId = 0;
496     int myBallsDefaultFamilyId      = 0;
497     int myEdgesDefaultFamilyId      = 0;
498     int myFacesDefaultFamilyId      = 0;
499     int myVolumesDefaultFamilyId    = 0;
500     smIdType nbNodes      = myMesh->NbNodes();
501     smIdType nb0DElements = myMesh->Nb0DElements();
502     smIdType nbBalls      = myMesh->NbBalls();
503     smIdType nbEdges      = myMesh->NbEdges();
504     smIdType nbFaces      = myMesh->NbFaces();
505     smIdType nbVolumes    = myMesh->NbVolumes();
506     if (myDoGroupOfNodes)   myNodesDefaultFamilyId      = REST_NODES_FAMILY;
507     if (myDoGroupOfEdges)   myEdgesDefaultFamilyId      = REST_EDGES_FAMILY;
508     if (myDoGroupOfFaces)   myFacesDefaultFamilyId      = REST_FACES_FAMILY;
509     if (myDoGroupOfVolumes) myVolumesDefaultFamilyId    = REST_VOLUMES_FAMILY;
510     if (myDoGroupOf0DElems) my0DElementsDefaultFamilyId = REST_0DELEM_FAMILY;
511     if (myDoGroupOfBalls)   myBallsDefaultFamilyId      = REST_BALL_FAMILY;
512     if (myDoAllInGroups )
513     {
514       if (!myDoGroupOfEdges)   myEdgesDefaultFamilyId      = NIG_EDGES_FAMILY   ;
515       if (!myDoGroupOfFaces)   myFacesDefaultFamilyId      = NIG_FACES_FAMILY   ;
516       if (!myDoGroupOfVolumes) myVolumesDefaultFamilyId    = NIG_VOLS_FAMILY    ;
517       if (!myDoGroupOf0DElems) my0DElementsDefaultFamilyId = NIG_0DELEM_FAMILY  ;
518       if (!myDoGroupOfBalls)   myBallsDefaultFamilyId      = NIG_BALL_FAMILY    ;
519     }
520
521     //MESSAGE("Perform - aFamilyInfo");
522     list<DriverMED_FamilyPtr> aFamilies;
523     if (myAllSubMeshes) {
524       aFamilies = DriverMED_Family::MakeFamilies
525         (myMesh->SubMeshes(), myGroups,
526          myDoGroupOfNodes   && nbNodes,
527          myDoGroupOfEdges   && nbEdges,
528          myDoGroupOfFaces   && nbFaces,
529          myDoGroupOfVolumes && nbVolumes,
530          myDoGroupOf0DElems && nb0DElements,
531          myDoGroupOfBalls   && nbBalls,
532          myDoAllInGroups);
533     }
534     else {
535       aFamilies = DriverMED_Family::MakeFamilies
536         (getIterator( mySubMeshes ), myGroups,
537          myDoGroupOfNodes   && nbNodes,
538          myDoGroupOfEdges   && nbEdges,
539          myDoGroupOfFaces   && nbFaces,
540          myDoGroupOfVolumes && nbVolumes,
541          myDoGroupOf0DElems && nb0DElements,
542          myDoGroupOfBalls   && nbBalls,
543          myDoAllInGroups);
544     }
545     list<DriverMED_FamilyPtr>::iterator aFamsIter;
546     for (aFamsIter = aFamilies.begin(); aFamsIter != aFamilies.end(); aFamsIter++)
547     {
548       PFamilyInfo aFamilyInfo = (*aFamsIter)->GetFamilyInfo<LowLevelWriter>(myMed,aMeshInfo);
549       myMed->SetFamilyInfo(aFamilyInfo);
550     }
551
552     // Storing SMDS nodes to the MED file for the MED mesh
553     //----------------------------------------------------
554 #ifdef _EDF_NODE_IDS_
555     typedef map<TInt,TInt> TNodeIdMap;
556     TNodeIdMap aNodeIdMap;
557 #endif
558     const EModeSwitch   theMode        = eFULL_INTERLACE;
559     const ERepere       theSystem      = eCART;
560     const EBooleen      theIsElemNum   = eVRAI;
561     const EBooleen      theIsElemNames = eFAUX;
562     const EConnectivite theConnMode    = eNOD;
563
564     TInt aNbNodes = FromSmIdType<TInt>( myMesh->NbNodes() );
565     PNodeInfo aNodeInfo = myMed->CrNodeInfo(aMeshInfo, aNbNodes,
566                                             theMode, theSystem, theIsElemNum, theIsElemNames);
567
568     // find family numbers for nodes
569     TElemFamilyMap anElemFamMap;
570     fillElemFamilyMap( anElemFamMap, aFamilies, SMDSAbs_Node );
571
572     for (TInt iNode = 0; aCoordHelperPtr->Next(); iNode++)
573     {
574       // coordinates
575       TCoordSlice aTCoordSlice = aNodeInfo->GetCoordSlice( iNode );
576       for(TInt iCoord = 0; iCoord < aSpaceDimension; iCoord++){
577         aTCoordSlice[iCoord] = aCoordHelperPtr->GetCoord(iCoord);
578       }
579       if ( aSpaceDimension == 3 &&
580            -myZTolerance < aTCoordSlice[2] && aTCoordSlice[2] < myZTolerance )
581         aTCoordSlice[2] = 0.;
582
583       // node number
584       TInt aNodeID = FromSmIdType<TInt>( aCoordHelperPtr->GetID() );
585       aNodeInfo->SetElemNum( iNode, aNodeID );
586 #ifdef _EDF_NODE_IDS_
587       aNodeIdMap.insert( aNodeIdMap.end(), make_pair( aNodeID, iNode+1 ));
588 #endif
589       // family number
590       const SMDS_MeshNode* aNode = aCoordHelperPtr->GetNode();
591       int famNum = getFamilyId( anElemFamMap, aNode, myNodesDefaultFamilyId );
592       aNodeInfo->SetFamNum( iNode, famNum );
593     }
594     anElemFamMap.Clear();
595
596     // coordinate names and units
597     for (TInt iCoord = 0; iCoord < aSpaceDimension; iCoord++) {
598       aNodeInfo->SetCoordName( iCoord, aCoordHelperPtr->GetName(iCoord));
599       aNodeInfo->SetCoordUnit( iCoord, aCoordHelperPtr->GetUnit(iCoord));
600     }
601
602     //MESSAGE("Perform - aNodeInfo->GetNbElem() = "<<aNbNodes);
603     myMed->SetNodeInfo(aNodeInfo);
604     aNodeInfo.reset(); // free memory used for arrays
605
606
607     // Storing SMDS elements to the MED file for the MED mesh
608     //-------------------------------------------------------
609     // Write one element type at once in order to minimize memory usage (PAL19276)
610
611     const SMDS_MeshInfo& nbElemInfo = myMesh->GetMeshInfo();
612
613     // poly elements are not supported by med-2.1
614     bool polyTypesSupported = ( myMed->CrPolygoneInfo(aMeshInfo,eMAILLE,ePOLYGONE,0,0).get() != 0 );
615     TInt nbPolygonNodes = 0, nbPolyhedronNodes = 0, nbPolyhedronFaces = 0;
616
617     // nodes on VERTEXes where 0D elements are absent
618     std::vector<const SMDS_MeshElement*> nodesOf0D;
619     std::vector< SMDS_ElemIteratorPtr > iterVec;
620     SMDS_ElemIteratorPtr iterVecIter;
621     if ( myAddODOnVertices && getNodesOfMissing0DOnVert( myMesh, nodesOf0D ))
622     {
623       iterVec.resize(2);
624       iterVec[0] = myMesh->elementsIterator( SMDSAbs_0DElement );
625       iterVec[1] = SMDS_ElemIteratorPtr
626         ( new SMDS_ElementVectorIterator( nodesOf0D.begin(), nodesOf0D.end() ));
627
628       typedef SMDS_IteratorOnIterators
629         < const SMDS_MeshElement *, std::vector< SMDS_ElemIteratorPtr > > TItIterator;
630       iterVecIter = SMDS_ElemIteratorPtr( new TItIterator( iterVec ));
631     }
632
633     // collect info on all geom types
634
635     list< TElemTypeData > aTElemTypeDatas;
636
637     EEntiteMaillage anEntity = eMAILLE;
638 #ifdef _ELEMENTS_BY_DIM_
639     anEntity = eNOEUD_ELEMENT;
640 #endif
641     aTElemTypeDatas.push_back(TElemTypeData(anEntity,
642                                             ePOINT1,
643                                             nbElemInfo.Nb0DElements() + nodesOf0D.size(),
644                                             SMDSAbs_0DElement));
645 #ifdef _ELEMENTS_BY_DIM_
646     anEntity = eSTRUCT_ELEMENT;
647 #endif
648     aTElemTypeDatas.push_back( TElemTypeData(anEntity,
649                                              eBALL,
650                                              FromSmIdType<TInt>(nbElemInfo.NbBalls()),
651                                              SMDSAbs_Ball));
652 #ifdef _ELEMENTS_BY_DIM_
653     anEntity = eARETE;
654 #endif
655     aTElemTypeDatas.push_back( TElemTypeData(anEntity,
656                                              eSEG2,
657                                              FromSmIdType<TInt>(nbElemInfo.NbEdges( ORDER_LINEAR )),
658                                              SMDSAbs_Edge));
659     aTElemTypeDatas.push_back( TElemTypeData(anEntity,
660                                              eSEG3,
661                                              FromSmIdType<TInt>(nbElemInfo.NbEdges( ORDER_QUADRATIC )),
662                                              SMDSAbs_Edge));
663 #ifdef _ELEMENTS_BY_DIM_
664     anEntity = eFACE;
665 #endif
666     aTElemTypeDatas.push_back( TElemTypeData(anEntity,
667                                              eTRIA3,
668                                              FromSmIdType<TInt>(nbElemInfo.NbTriangles( ORDER_LINEAR )),
669                                              SMDSAbs_Face));
670     aTElemTypeDatas.push_back( TElemTypeData(anEntity,
671                                              eTRIA6,
672                                              FromSmIdType<TInt>(nbElemInfo.NbTriangles( ORDER_QUADRATIC ) -
673                                              nbElemInfo.NbBiQuadTriangles()),
674                                              SMDSAbs_Face));
675     aTElemTypeDatas.push_back( TElemTypeData(anEntity,
676                                              eTRIA7,
677                                              FromSmIdType<TInt>(nbElemInfo.NbBiQuadTriangles()),
678                                              SMDSAbs_Face));
679     aTElemTypeDatas.push_back( TElemTypeData(anEntity,
680                                              eQUAD4,
681                                              FromSmIdType<TInt>(nbElemInfo.NbQuadrangles( ORDER_LINEAR )),
682                                              SMDSAbs_Face));
683     aTElemTypeDatas.push_back( TElemTypeData(anEntity,
684                                              eQUAD8,
685                                              FromSmIdType<TInt>(nbElemInfo.NbQuadrangles( ORDER_QUADRATIC ) -
686                                              nbElemInfo.NbBiQuadQuadrangles()),
687                                              SMDSAbs_Face));
688     aTElemTypeDatas.push_back( TElemTypeData(anEntity,
689                                              eQUAD9,
690                                              FromSmIdType<TInt>(nbElemInfo.NbBiQuadQuadrangles()),
691                                              SMDSAbs_Face));
692     if ( polyTypesSupported ) {
693       aTElemTypeDatas.push_back( TElemTypeData(anEntity,
694                                                ePOLYGONE,
695                                                FromSmIdType<TInt>(nbElemInfo.NbPolygons( ORDER_LINEAR )),
696                                                SMDSAbs_Face));
697       // we need one more loop on poly elements to count nb of their nodes
698       aTElemTypeDatas.push_back( TElemTypeData(anEntity,
699                                                ePOLYGONE,
700                                                FromSmIdType<TInt>(nbElemInfo.NbPolygons( ORDER_LINEAR )),
701                                                SMDSAbs_Face));
702       aTElemTypeDatas.push_back( TElemTypeData(anEntity,
703                                                ePOLYGON2,
704                                                FromSmIdType<TInt>(nbElemInfo.NbPolygons( ORDER_QUADRATIC )),
705                                                SMDSAbs_Face));
706       // we need one more loop on QUAD poly elements to count nb of their nodes
707       aTElemTypeDatas.push_back( TElemTypeData(anEntity,
708                                                ePOLYGON2,
709                                                FromSmIdType<TInt>(nbElemInfo.NbPolygons( ORDER_QUADRATIC )),
710                                                SMDSAbs_Face));
711     }
712 #ifdef _ELEMENTS_BY_DIM_
713     anEntity = eMAILLE;
714 #endif
715     aTElemTypeDatas.push_back( TElemTypeData(anEntity,
716                                              eTETRA4,
717                                              FromSmIdType<TInt>(nbElemInfo.NbTetras( ORDER_LINEAR )),
718                                              SMDSAbs_Volume));
719     aTElemTypeDatas.push_back( TElemTypeData(anEntity,
720                                              eTETRA10,
721                                              FromSmIdType<TInt>(nbElemInfo.NbTetras( ORDER_QUADRATIC )),
722                                              SMDSAbs_Volume));
723     aTElemTypeDatas.push_back( TElemTypeData(anEntity,
724                                              ePYRA5,
725                                              FromSmIdType<TInt>(nbElemInfo.NbPyramids( ORDER_LINEAR )),
726                                              SMDSAbs_Volume));
727     aTElemTypeDatas.push_back( TElemTypeData(anEntity,
728                                              ePYRA13,
729                                              FromSmIdType<TInt>(nbElemInfo.NbPyramids( ORDER_QUADRATIC )),
730                                              SMDSAbs_Volume));
731     aTElemTypeDatas.push_back( TElemTypeData(anEntity,
732                                              ePENTA6,
733                                              FromSmIdType<TInt>(nbElemInfo.NbPrisms( ORDER_LINEAR )),
734                                              SMDSAbs_Volume));
735     aTElemTypeDatas.push_back( TElemTypeData(anEntity,
736                                              ePENTA15,
737                                              FromSmIdType<TInt>(nbElemInfo.NbQuadPrisms()),
738                                              SMDSAbs_Volume));
739     aTElemTypeDatas.push_back( TElemTypeData(anEntity,
740                                              ePENTA18,
741                                              FromSmIdType<TInt>(nbElemInfo.NbBiQuadPrisms()),
742                                              SMDSAbs_Volume));
743     aTElemTypeDatas.push_back( TElemTypeData(anEntity,
744                                              eHEXA8,
745                                              FromSmIdType<TInt>(nbElemInfo.NbHexas( ORDER_LINEAR )),
746                                              SMDSAbs_Volume));
747     aTElemTypeDatas.push_back( TElemTypeData(anEntity,
748                                              eHEXA20,
749                                              FromSmIdType<TInt>(nbElemInfo.NbHexas( ORDER_QUADRATIC )-
750                                              nbElemInfo.NbTriQuadHexas()),
751                                              SMDSAbs_Volume));
752     aTElemTypeDatas.push_back( TElemTypeData(anEntity,
753                                              eHEXA27,
754                                              FromSmIdType<TInt>(nbElemInfo.NbTriQuadHexas()),
755                                              SMDSAbs_Volume));
756     aTElemTypeDatas.push_back( TElemTypeData(anEntity,
757                                              eOCTA12,
758                                              FromSmIdType<TInt>(nbElemInfo.NbHexPrisms()),
759                                              SMDSAbs_Volume));
760     if ( polyTypesSupported ) {
761       aTElemTypeDatas.push_back( TElemTypeData(anEntity,
762                                                ePOLYEDRE,
763                                                FromSmIdType<TInt>(nbElemInfo.NbPolyhedrons()),
764                                                SMDSAbs_Volume));
765       // we need one more loop on poly elements to count nb of their nodes
766       aTElemTypeDatas.push_back( TElemTypeData(anEntity,
767                                                ePOLYEDRE,
768                                                FromSmIdType<TInt>(nbElemInfo.NbPolyhedrons()),
769                                                SMDSAbs_Volume));
770     }
771
772     vector< bool > isElemFamMapBuilt( SMDSAbs_NbElementTypes, false );
773
774     // loop on all geom types of elements
775
776     list< TElemTypeData >::iterator aElemTypeData = aTElemTypeDatas.begin();
777     for ( ; aElemTypeData != aTElemTypeDatas.end(); ++aElemTypeData )
778     {
779       if ( aElemTypeData->_nbElems == 0 )
780         continue;
781
782       int defaultFamilyId = 0;
783       switch ( aElemTypeData->_smdsType ) {
784       case SMDSAbs_0DElement: defaultFamilyId = my0DElementsDefaultFamilyId; break;
785       case SMDSAbs_Ball:      defaultFamilyId = myBallsDefaultFamilyId;      break;
786       case SMDSAbs_Edge:      defaultFamilyId = myEdgesDefaultFamilyId;      break;
787       case SMDSAbs_Face:      defaultFamilyId = myFacesDefaultFamilyId;      break;
788       case SMDSAbs_Volume:    defaultFamilyId = myVolumesDefaultFamilyId;    break;
789       default:
790         continue;
791       }
792
793       // build map of family numbers for this type
794       if ( !isElemFamMapBuilt[ aElemTypeData->_smdsType ])
795       {
796         fillElemFamilyMap( anElemFamMap, aFamilies, aElemTypeData->_smdsType );
797         isElemFamMapBuilt[ aElemTypeData->_smdsType ] = true;
798       }
799
800       // iterator on elements of a current type
801       SMDS_ElemIteratorPtr elemIterator;
802       int iElem = 0;
803
804       // Treat POLYGONs
805       // ---------------
806       if ( aElemTypeData->_geomType == ePOLYGONE ||
807            aElemTypeData->_geomType == ePOLYGON2 )
808       {
809         if ( aElemTypeData->_geomType == ePOLYGONE )
810           elemIterator = myMesh->elementEntityIterator( SMDSEntity_Polygon );
811         else
812           elemIterator = myMesh->elementEntityIterator( SMDSEntity_Quad_Polygon );
813
814         if ( nbPolygonNodes == 0 ) {
815           // Count nb of nodes
816           while ( elemIterator->more() ) {
817             const SMDS_MeshElement* anElem = elemIterator->next();
818             nbPolygonNodes += anElem->NbNodes();
819             if ( ++iElem == aElemTypeData->_nbElems )
820               break;
821           }
822         }
823         else {
824           // Store in med file
825           PPolygoneInfo aPolygoneInfo = myMed->CrPolygoneInfo(aMeshInfo,
826                                                               aElemTypeData->_entity,
827                                                               aElemTypeData->_geomType,
828                                                               aElemTypeData->_nbElems,
829                                                               nbPolygonNodes,
830                                                               theConnMode, theIsElemNum,
831                                                               theIsElemNames);
832           TElemNum & index = *(aPolygoneInfo->myIndex.get());
833           index[0] = 1;
834
835           while ( elemIterator->more() )
836           {
837             const SMDS_MeshElement* anElem = elemIterator->next();
838             // index
839             TInt aNbNodes = anElem->NbNodes();
840             index[ iElem+1 ] = index[ iElem ] + aNbNodes;
841
842             // connectivity
843             TConnSlice aTConnSlice = aPolygoneInfo->GetConnSlice( iElem );
844             for(TInt iNode = 0; iNode < aNbNodes; iNode++) {
845               const SMDS_MeshElement* aNode = anElem->GetNode( iNode );
846 #ifdef _EDF_NODE_IDS_
847               aTConnSlice[ iNode ] = aNodeIdMap[FromSmIdType<TInt>(aNode->GetID())];
848 #else
849               aTConnSlice[ iNode ] = aNode->GetID();
850 #endif
851             }
852             // element number
853             aPolygoneInfo->SetElemNum( iElem, FromSmIdType<TInt>(anElem->GetID()) );
854
855             // family number
856             int famNum = getFamilyId( anElemFamMap, anElem, defaultFamilyId );
857             aPolygoneInfo->SetFamNum( iElem, famNum );
858
859             if ( ++iElem == aPolygoneInfo->GetNbElem() )
860               break;
861           }
862           myMed->SetPolygoneInfo(aPolygoneInfo);
863
864           nbPolygonNodes = 0; // to treat next polygon type
865         }
866       }
867
868       // Treat POLYEDREs
869       // ----------------
870       else if ( aElemTypeData->_geomType == ePOLYEDRE )
871       {
872         elemIterator = myMesh->elementGeomIterator( SMDSGeom_POLYHEDRA );
873
874         if ( nbPolyhedronNodes == 0 ) {
875           // Count nb of nodes
876           while ( elemIterator->more() ) {
877             const SMDS_MeshElement*  anElem = elemIterator->next();
878             nbPolyhedronNodes += anElem->NbNodes();
879             nbPolyhedronFaces += anElem->NbFaces();
880             if ( ++iElem == aElemTypeData->_nbElems )
881               break;
882           }
883         }
884         else {
885           // Store in med file
886           PPolyedreInfo aPolyhInfo = myMed->CrPolyedreInfo(aMeshInfo,
887                                                            aElemTypeData->_entity,
888                                                            aElemTypeData->_geomType,
889                                                            aElemTypeData->_nbElems,
890                                                            nbPolyhedronFaces+1,
891                                                            nbPolyhedronNodes,
892                                                            theConnMode,
893                                                            theIsElemNum,
894                                                            theIsElemNames);
895           TElemNum & index = *(aPolyhInfo->myIndex.get());
896           TElemNum & faces = *(aPolyhInfo->myFaces.get());
897           TElemNum & conn  = *(aPolyhInfo->myConn.get());
898           index[0] = 1;
899           faces[0] = 1;
900
901           TInt iFace = 0, iNode = 0;
902           while ( elemIterator->more() )
903           {
904             const SMDS_MeshElement* anElem = elemIterator->next();
905             const SMDS_MeshVolume *aPolyedre = myMesh->DownCast< SMDS_MeshVolume >( anElem );
906             if ( !aPolyedre ) continue;
907             // index
908             TInt aNbFaces = aPolyedre->NbFaces();
909             index[ iElem+1 ] = index[ iElem ] + aNbFaces;
910
911             // face index
912             for (TInt f = 1; f <= aNbFaces; ++f, ++iFace ) {
913               int aNbFaceNodes = aPolyedre->NbFaceNodes( f );
914               faces[ iFace+1 ] = faces[ iFace ] + aNbFaceNodes;
915             }
916             // connectivity
917             SMDS_ElemIteratorPtr nodeIt = anElem->nodesIterator();
918             while ( nodeIt->more() ) {
919               const SMDS_MeshElement* aNode = nodeIt->next();
920 #ifdef _EDF_NODE_IDS_
921               conn[ iNode ] = aNodeIdMap[FromSmIdType<TInt>(aNode->GetID())];
922 #else
923               conn[ iNode ] = aNode->GetID();
924 #endif
925               ++iNode;
926             }
927             // element number
928             aPolyhInfo->SetElemNum( iElem, FromSmIdType<TInt>(anElem->GetID()) );
929
930             // family number
931             int famNum = getFamilyId( anElemFamMap, anElem, defaultFamilyId );
932             aPolyhInfo->SetFamNum( iElem, famNum );
933
934             if ( ++iElem == aPolyhInfo->GetNbElem() )
935               break;
936           }
937           myMed->SetPolyedreInfo(aPolyhInfo);
938         }
939       } // if (aElemTypeData->_geomType == ePOLYEDRE )
940
941       // Treat BALLs
942       // ----------------
943       else if (aElemTypeData->_geomType == eBALL )
944       {
945         // allocate data arrays
946         PBallInfo aBallInfo = myMed->CrBallInfo( aMeshInfo, aElemTypeData->_nbElems );
947
948         elemIterator = myMesh->elementsIterator( SMDSAbs_Ball );
949         while ( elemIterator->more() )
950         {
951           const SMDS_MeshElement* anElem = elemIterator->next();
952           // connectivity
953           const SMDS_MeshElement* aNode = anElem->GetNode( 0 );
954 #ifdef _EDF_NODE_IDS_
955           (*aBallInfo->myConn)[ iElem ] = aNodeIdMap[FromSmIdType<TInt>(aNode->GetID())];
956 #else
957           (*aBallInfo->myConn)[ iElem ] = aNode->GetID();
958 #endif
959           // element number
960           aBallInfo->SetElemNum( iElem, FromSmIdType<TInt>(anElem->GetID()) );
961
962           // diameter
963           aBallInfo->myDiameters[ iElem ] =
964             static_cast<const SMDS_BallElement*>( anElem )->GetDiameter();
965
966           // family number
967           int famNum = getFamilyId( anElemFamMap, anElem, defaultFamilyId );
968           aBallInfo->SetFamNum( iElem, famNum );
969           ++iElem;
970         }
971         // store data in a file
972         myMed->SetBallInfo(aBallInfo);
973       }
974
975       else
976       {
977         // Treat standard types
978         // ---------------------
979         // allocate data arrays
980         PCellInfo aCellInfo = myMed->CrCellInfo( aMeshInfo,
981                                                  aElemTypeData->_entity,
982                                                  aElemTypeData->_geomType,
983                                                  aElemTypeData->_nbElems,
984                                                  theConnMode,
985                                                  theIsElemNum,
986                                                  theIsElemNames);
987
988         TInt aNbNodes = MED::GetNbNodes(aElemTypeData->_geomType);
989         elemIterator = myMesh->elementsIterator( aElemTypeData->_smdsType );
990         if ( aElemTypeData->_smdsType == SMDSAbs_0DElement && ! nodesOf0D.empty() )
991           elemIterator = iterVecIter;
992         while ( elemIterator->more() )
993         {
994           const SMDS_MeshElement* anElem = elemIterator->next();
995           if ( anElem->NbNodes() != aNbNodes || anElem->IsPoly() )
996             continue; // other geometry
997
998           // connectivity
999           TConnSlice aTConnSlice = aCellInfo->GetConnSlice( iElem );
1000           for (TInt iNode = 0; iNode < aNbNodes; iNode++) {
1001             const SMDS_MeshElement* aNode = anElem->GetNode( iNode );
1002 #ifdef _EDF_NODE_IDS_
1003             aTConnSlice[ iNode ] = aNodeIdMap[FromSmIdType<TInt>(aNode->GetID())];
1004 #else
1005             aTConnSlice[ iNode ] = aNode->GetID();
1006 #endif
1007           }
1008           // element number
1009           aCellInfo->SetElemNum( iElem, FromSmIdType<TInt>(anElem->GetID()) );
1010
1011           // family number
1012           int famNum = getFamilyId( anElemFamMap, anElem, defaultFamilyId );
1013           aCellInfo->SetFamNum( iElem, famNum );
1014
1015           if ( ++iElem == aCellInfo->GetNbElem() )
1016             break;
1017         }
1018         // store data in a file
1019         myMed->SetCellInfo(aCellInfo);
1020       }
1021     } // loop on geom types
1022   }
1023   catch(const std::exception& exc) {
1024     INFOS("The following exception was caught:\n\t"<<exc.what());
1025     throw;
1026   }
1027   catch(...) {
1028     INFOS("Unknown exception was caught !!!");
1029     throw;
1030   }
1031
1032   myMeshId = -1;
1033   myGroups.clear();
1034   mySubMeshes.clear();
1035   return aResult;
1036 }
1037
1038 //================================================================================
1039 /*!
1040  * \brief Returns nodes on VERTEXes where 0D elements are absent
1041  */
1042 //================================================================================
1043
1044 bool DriverMED_W_SMESHDS_Mesh::
1045 getNodesOfMissing0DOnVert(SMESHDS_Mesh*                         meshDS,
1046                           std::vector<const SMDS_MeshElement*>& nodes)
1047 {
1048   nodes.clear();
1049   for ( int i = 1; i <= meshDS->MaxShapeIndex(); ++i )
1050   {
1051     if ( meshDS->IndexToShape( i ).ShapeType() != TopAbs_VERTEX )
1052       continue;
1053     if ( SMESHDS_SubMesh* sm = meshDS->MeshElements(i) ) {
1054       SMDS_NodeIteratorPtr nIt= sm->GetNodes();
1055       while (nIt->more())
1056       {
1057         const SMDS_MeshNode* n = nIt->next();
1058         if ( n->NbInverseElements( SMDSAbs_0DElement ) == 0 )
1059           nodes.push_back( n );
1060       }
1061     }
1062   }
1063   return !nodes.empty();
1064 }