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