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