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