Salome HOME
64d6b6a3b687b3ac68c3030c1cb28744e93107b0
[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 }
74
75 void DriverMED_W_SMESHDS_Mesh::SetFile(const std::string& theFileName)
76 {
77   Driver_SMESHDS_Mesh::SetFile(theFileName);
78 }
79
80 string DriverMED_W_SMESHDS_Mesh::GetVersionString(const MED::EVersion theVersion, int theNbDigits)
81 {
82   TInt majeur, mineur, release;
83   majeur =  mineur = release = 0;
84 //   if ( theVersion == eV2_1 )
85 //     MED::GetVersionRelease<eV2_1>(majeur, mineur, release);
86 //   else
87     MED::GetVersionRelease<eV2_2>(majeur, mineur, release);
88   ostringstream name;
89   if ( theNbDigits > 0 )
90     name << majeur;
91   if ( theNbDigits > 1 )
92     name << "." << mineur;
93   if ( theNbDigits > 2 )
94     name << "." << release;
95   return name.str();
96 }
97
98 void DriverMED_W_SMESHDS_Mesh::AddGroup(SMESHDS_GroupBase* theGroup)
99 {
100   myGroups.push_back(theGroup);
101 }
102
103 void DriverMED_W_SMESHDS_Mesh::AddAllSubMeshes()
104 {
105   myAllSubMeshes = true;
106 }
107
108 void DriverMED_W_SMESHDS_Mesh::AddSubMesh(SMESHDS_SubMesh* theSubMesh, int theID)
109 {
110   mySubMeshes.push_back( theSubMesh );
111 }
112
113 void DriverMED_W_SMESHDS_Mesh::AddGroupOfNodes()
114 {
115   myDoGroupOfNodes = true;
116 }
117
118 void DriverMED_W_SMESHDS_Mesh::AddGroupOfEdges()
119 {
120   myDoGroupOfEdges = true;
121 }
122
123 void DriverMED_W_SMESHDS_Mesh::AddGroupOfFaces()
124 {
125   myDoGroupOfFaces = true;
126 }
127
128 void DriverMED_W_SMESHDS_Mesh::AddGroupOfVolumes()
129 {
130   myDoGroupOfVolumes = true;
131 }
132
133 void DriverMED_W_SMESHDS_Mesh::AddGroupOf0DElems()
134 {
135   myDoGroupOf0DElems = true;
136 }
137
138 void DriverMED_W_SMESHDS_Mesh::AddGroupOfBalls()
139 {
140   myDoGroupOfBalls = true;
141 }
142
143 //================================================================================
144 /*!
145  * \brief Set up a flag to add all elements not belonging to any group to
146  *        some auxiliary group. This is needed for SMESH -> SAUVE -> SMESH conversion,
147  *        which since PAL0023285 reads only SAUVE elements belonging to any group,
148  *        and hence can lose some elements. That auxiliary group is ignored while
149  *        reading a MED file.
150  */
151 //================================================================================
152
153 void DriverMED_W_SMESHDS_Mesh::AddAllToGroup()
154 {
155   myDoAllInGroups = true;
156 }
157
158
159 namespace
160 {
161   typedef double (SMDS_MeshNode::* TGetCoord)() const;
162   typedef const char* TName;
163   typedef const char* TUnit;
164
165   // name length in a mesh must be equal to 16 :
166   //         1234567890123456
167   TName M = "m               ";
168   TName X = "x               ";
169   TName Y = "y               ";
170   TName Z = "z               ";
171
172   TUnit aUnit[3] = {M,M,M};
173
174   // 3 dim
175   TGetCoord aXYZGetCoord[3] = {
176     &SMDS_MeshNode::X, 
177     &SMDS_MeshNode::Y, 
178     &SMDS_MeshNode::Z
179   };
180   TName aXYZName[3] = {X,Y,Z};
181   
182   // 2 dim
183   TGetCoord aXYGetCoord[2] = {
184     &SMDS_MeshNode::X, 
185     &SMDS_MeshNode::Y
186   };
187   TName aXYName[2] = {X,Y};
188
189   TGetCoord aYZGetCoord[2] = {
190     &SMDS_MeshNode::Y, 
191     &SMDS_MeshNode::Z
192   };
193   TName aYZName[2] = {Y,Z};
194
195   TGetCoord aXZGetCoord[2] = {
196     &SMDS_MeshNode::X, 
197     &SMDS_MeshNode::Z
198   };
199   TName aXZName[2] = {X,Z};
200
201   // 1 dim
202   TGetCoord aXGetCoord[1] = {
203     &SMDS_MeshNode::X
204   };
205   TName aXName[1] = {X};
206
207   TGetCoord aYGetCoord[1] = {
208     &SMDS_MeshNode::Y
209   };
210   TName aYName[1] = {Y};
211
212   TGetCoord aZGetCoord[1] = {
213     &SMDS_MeshNode::Z
214   };
215   TName aZName[1] = {Z};
216
217
218   class TCoordHelper{
219     SMDS_NodeIteratorPtr myNodeIter;
220     const SMDS_MeshNode* myCurrentNode;
221     TGetCoord* myGetCoord;
222     TName* myName;
223     TUnit* myUnit;
224   public:
225     TCoordHelper(const SMDS_NodeIteratorPtr& theNodeIter,
226                  TGetCoord* theGetCoord,
227                  TName* theName,
228                  TUnit* theUnit = aUnit):
229       myNodeIter(theNodeIter),
230       myGetCoord(theGetCoord),
231       myName(theName),
232       myUnit(theUnit)
233     {}
234     virtual ~TCoordHelper(){}
235     bool Next(){ 
236       return myNodeIter->more() && 
237         (myCurrentNode = myNodeIter->next());
238     }
239     const SMDS_MeshNode* GetNode(){
240       return myCurrentNode;
241     }
242     MED::TIntVector::value_type GetID(){
243       return myCurrentNode->GetID();
244     }
245     MED::TFloatVector::value_type GetCoord(TInt theCoodId){
246       return (myCurrentNode->*myGetCoord[theCoodId])();
247     }
248     MED::TStringVector::value_type GetName(TInt theDimId){
249       return myName[theDimId];
250     }
251     MED::TStringVector::value_type GetUnit(TInt theDimId){
252       return myUnit[theDimId];
253     }
254   };
255   typedef boost::shared_ptr<TCoordHelper> TCoordHelperPtr;
256
257   //-------------------------------------------------------
258   /*!
259    * \brief Structure describing element type
260    */
261   //-------------------------------------------------------
262   struct TElemTypeData
263   {
264     EEntiteMaillage     _entity;
265     EGeometrieElement   _geomType;
266     TInt                _nbElems;
267     SMDSAbs_ElementType _smdsType;
268
269     TElemTypeData (EEntiteMaillage entity, EGeometrieElement geom, TInt nb, SMDSAbs_ElementType type)
270       : _entity(entity), _geomType(geom), _nbElems( nb ), _smdsType( type ) {}
271   };
272
273
274   typedef NCollection_DataMap< Standard_Address, int > TElemFamilyMap;
275
276   //================================================================================
277   /*!
278    * \brief Fills element to famaly ID map for element type.
279    * Removes all families of anElemType
280    */
281   //================================================================================
282
283   void fillElemFamilyMap( TElemFamilyMap &            anElemFamMap,
284                           list<DriverMED_FamilyPtr> & aFamilies,
285                           const SMDSAbs_ElementType   anElemType)
286   {
287     anElemFamMap.Clear();
288     list<DriverMED_FamilyPtr>::iterator aFamsIter = aFamilies.begin();
289     while ( aFamsIter != aFamilies.end() )
290     {
291       if ((*aFamsIter)->GetType() != anElemType) {
292         aFamsIter++;
293       }
294       else {
295         int aFamId = (*aFamsIter)->GetId();
296         const ElementsSet&              anElems = (*aFamsIter)->GetElements();
297         ElementsSet::const_iterator anElemsIter = anElems.begin();
298         for (; anElemsIter != anElems.end(); anElemsIter++)
299         {
300           anElemFamMap.Bind( (Standard_Address)*anElemsIter, aFamId );
301         }
302         // remove a family from the list
303         aFamilies.erase( aFamsIter++ );
304       }
305     }
306   }
307
308   //================================================================================
309   /*!
310    * \brief For an element, return family ID found in the map or a default one
311    */
312   //================================================================================
313
314   int getFamilyId( const TElemFamilyMap &  anElemFamMap,
315                    const SMDS_MeshElement* anElement,
316                    const int               aDefaultFamilyId)
317   {
318     if ( anElemFamMap.IsBound( (Standard_Address) anElement ))
319       return anElemFamMap( (Standard_Address) anElement );
320
321     return aDefaultFamilyId;
322   }
323
324   //================================================================================
325   /*!
326    * \brief Returns iterator on sub-meshes
327    */
328   //================================================================================
329
330   SMESHDS_SubMeshIteratorPtr getIterator( std::vector<SMESHDS_SubMesh*>& mySubMeshes )
331   {
332     return SMESHDS_SubMeshIteratorPtr
333       ( new SMDS_SetIterator
334         < const SMESHDS_SubMesh*, std::vector< SMESHDS_SubMesh* >::iterator >( mySubMeshes.begin(),
335                                                                                mySubMeshes.end() ));
336   }
337 }
338
339 Driver_Mesh::Status DriverMED_W_SMESHDS_Mesh::Perform()
340 {
341   Status aResult = DRS_OK;
342   if (myMesh->hasConstructionEdges() || myMesh->hasConstructionFaces()) {
343     INFOS("SMDS_MESH with hasConstructionEdges() or hasConstructionFaces() do not supports!!!");
344     return DRS_FAIL;
345   }
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(/*idInceasingOrder=*/true);
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 = CrWrapper(myFile,myMedVersion);
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.NbPrisms( ORDER_QUADRATIC ),
707                                              SMDSAbs_Volume));
708     aTElemTypeDatas.push_back( TElemTypeData(anEntity,
709                                              eHEXA8,
710                                              nbElemInfo.NbHexas( ORDER_LINEAR ),
711                                              SMDSAbs_Volume));
712     aTElemTypeDatas.push_back( TElemTypeData(anEntity,
713                                              eHEXA20,
714                                              nbElemInfo.NbHexas( ORDER_QUADRATIC )-
715                                              nbElemInfo.NbTriQuadHexas(),
716                                              SMDSAbs_Volume));
717     aTElemTypeDatas.push_back( TElemTypeData(anEntity,
718                                              eHEXA27,
719                                              nbElemInfo.NbTriQuadHexas(),
720                                              SMDSAbs_Volume));
721     aTElemTypeDatas.push_back( TElemTypeData(anEntity,
722                                              eOCTA12,
723                                              nbElemInfo.NbHexPrisms(),
724                                              SMDSAbs_Volume));
725     if ( polyTypesSupported ) {
726       aTElemTypeDatas.push_back( TElemTypeData(anEntity,
727                                                ePOLYEDRE,
728                                                nbElemInfo.NbPolyhedrons(),
729                                                SMDSAbs_Volume));
730       // we need one more loop on poly elements to count nb of their nodes
731       aTElemTypeDatas.push_back( TElemTypeData(anEntity,
732                                                ePOLYEDRE,
733                                                nbElemInfo.NbPolyhedrons(),
734                                                SMDSAbs_Volume));
735     }
736
737     vector< bool > isElemFamMapBuilt( SMDSAbs_NbElementTypes, false );
738
739     // loop on all geom types of elements
740
741     list< TElemTypeData >::iterator aElemTypeData = aTElemTypeDatas.begin();
742     for ( ; aElemTypeData != aTElemTypeDatas.end(); ++aElemTypeData )
743     {
744       if ( aElemTypeData->_nbElems == 0 )
745         continue;
746
747       int defaultFamilyId = 0;
748       switch ( aElemTypeData->_smdsType ) {
749       case SMDSAbs_0DElement: defaultFamilyId = my0DElementsDefaultFamilyId; break;
750       case SMDSAbs_Ball:      defaultFamilyId = myBallsDefaultFamilyId;      break;
751       case SMDSAbs_Edge:      defaultFamilyId = myEdgesDefaultFamilyId;      break;
752       case SMDSAbs_Face:      defaultFamilyId = myFacesDefaultFamilyId;      break;
753       case SMDSAbs_Volume:    defaultFamilyId = myVolumesDefaultFamilyId;    break;
754       default:
755         continue;
756       }
757
758       // iterator on elements of a current type
759       SMDS_ElemIteratorPtr elemIterator;
760       int iElem = 0;
761
762       // Treat POLYGONs
763       // ---------------
764       if ( aElemTypeData->_geomType == ePOLYGONE ||
765            aElemTypeData->_geomType == ePOLYGON2 )
766       {
767         if ( aElemTypeData->_geomType == ePOLYGONE )
768           elemIterator = myMesh->elementEntityIterator( SMDSEntity_Polygon );
769         else
770           elemIterator = myMesh->elementEntityIterator( SMDSEntity_Quad_Polygon );
771
772         if ( nbPolygonNodes == 0 ) {
773           // Count nb of nodes
774           while ( elemIterator->more() ) {
775             const SMDS_MeshElement* anElem = elemIterator->next();
776             nbPolygonNodes += anElem->NbNodes();
777             if ( ++iElem == aElemTypeData->_nbElems )
778               break;
779           }
780         }
781         else {
782           // Store in med file
783           PPolygoneInfo aPolygoneInfo = myMed->CrPolygoneInfo(aMeshInfo,
784                                                               aElemTypeData->_entity,
785                                                               aElemTypeData->_geomType,
786                                                               aElemTypeData->_nbElems,
787                                                               nbPolygonNodes,
788                                                               theConnMode, theIsElemNum,
789                                                               theIsElemNames);
790           TElemNum & index = *(aPolygoneInfo->myIndex.get());
791           index[0] = 1;
792
793           while ( elemIterator->more() )
794           {
795             const SMDS_MeshElement* anElem = elemIterator->next();
796             // index
797             TInt aNbNodes = anElem->NbNodes();
798             index[ iElem+1 ] = index[ iElem ] + aNbNodes;
799
800             // connectivity
801             TConnSlice aTConnSlice = aPolygoneInfo->GetConnSlice( iElem );
802             for(TInt iNode = 0; iNode < aNbNodes; iNode++) {
803               const SMDS_MeshElement* aNode = anElem->GetNode( iNode );
804 #ifdef _EDF_NODE_IDS_
805               aTConnSlice[ iNode ] = aNodeIdMap[aNode->GetID()];
806 #else
807               aTConnSlice[ iNode ] = aNode->GetID();
808 #endif
809             }
810             // element number
811             aPolygoneInfo->SetElemNum( iElem, anElem->GetID() );
812
813             // family number
814             int famNum = getFamilyId( anElemFamMap, anElem, defaultFamilyId );
815             aPolygoneInfo->SetFamNum( iElem, famNum );
816
817             if ( ++iElem == aPolygoneInfo->GetNbElem() )
818               break;
819           }
820           myMed->SetPolygoneInfo(aPolygoneInfo);
821
822           nbPolygonNodes = 0; // to treat next polygon type
823         }
824       }
825
826       // Treat POLYEDREs
827       // ----------------
828       else if (aElemTypeData->_geomType == ePOLYEDRE )
829       {
830         elemIterator = myMesh->elementGeomIterator( SMDSGeom_POLYHEDRA );
831         
832         if ( nbPolyhedronNodes == 0 ) {
833           // Count nb of nodes
834           while ( elemIterator->more() ) {
835             const SMDS_MeshElement*  anElem = elemIterator->next();
836             const SMDS_VtkVolume *aPolyedre = dynamic_cast<const SMDS_VtkVolume*>(anElem);
837             if ( !aPolyedre ) continue;
838             nbPolyhedronNodes += aPolyedre->NbNodes();
839             nbPolyhedronFaces += aPolyedre->NbFaces();
840             if ( ++iElem == aElemTypeData->_nbElems )
841               break;
842           }
843         }
844         else {
845           // Store in med file
846           PPolyedreInfo aPolyhInfo = myMed->CrPolyedreInfo(aMeshInfo,
847                                                            aElemTypeData->_entity,
848                                                            aElemTypeData->_geomType,
849                                                            aElemTypeData->_nbElems,
850                                                            nbPolyhedronFaces+1,
851                                                            nbPolyhedronNodes,
852                                                            theConnMode,
853                                                            theIsElemNum,
854                                                            theIsElemNames);
855           TElemNum & index = *(aPolyhInfo->myIndex.get());
856           TElemNum & faces = *(aPolyhInfo->myFaces.get());
857           TElemNum & conn  = *(aPolyhInfo->myConn.get());
858           index[0] = 1;
859           faces[0] = 1;
860
861           TInt iFace = 0, iNode = 0;
862           while ( elemIterator->more() )
863           {
864             const SMDS_MeshElement*  anElem = elemIterator->next();
865             const SMDS_VtkVolume *aPolyedre = dynamic_cast<const SMDS_VtkVolume*>(anElem);
866             if ( !aPolyedre ) continue;
867             // index
868             TInt aNbFaces = aPolyedre->NbFaces();
869             index[ iElem+1 ] = index[ iElem ] + aNbFaces;
870
871             // face index
872             for (TInt f = 1; f <= aNbFaces; ++f, ++iFace ) {
873               int aNbFaceNodes = aPolyedre->NbFaceNodes( f );
874               faces[ iFace+1 ] = faces[ iFace ] + aNbFaceNodes;
875             }
876             // connectivity
877             SMDS_ElemIteratorPtr nodeIt = anElem->nodesIterator();
878             while ( nodeIt->more() ) {
879               const SMDS_MeshElement* aNode = nodeIt->next();
880 #ifdef _EDF_NODE_IDS_
881               conn[ iNode ] = aNodeIdMap[aNode->GetID()];
882 #else
883               conn[ iNode ] = aNode->GetID();
884 #endif
885               ++iNode;
886             }
887             // element number
888             aPolyhInfo->SetElemNum( iElem, anElem->GetID() );
889
890             // family number
891             int famNum = getFamilyId( anElemFamMap, anElem, defaultFamilyId );
892             aPolyhInfo->SetFamNum( iElem, famNum );
893
894             if ( ++iElem == aPolyhInfo->GetNbElem() )
895               break;
896           }
897           myMed->SetPolyedreInfo(aPolyhInfo);
898         }
899       } // if (aElemTypeData->_geomType == ePOLYEDRE )
900
901       // Treat BALLs
902       // ----------------
903       else if (aElemTypeData->_geomType == eBALL )
904       {
905         // allocate data arrays
906         PBallInfo aBallInfo = myMed->CrBallInfo( aMeshInfo, aElemTypeData->_nbElems );
907
908         // build map of family numbers for this type
909         if ( !isElemFamMapBuilt[ aElemTypeData->_smdsType ])
910         {
911           fillElemFamilyMap( anElemFamMap, aFamilies, aElemTypeData->_smdsType );
912           isElemFamMapBuilt[ aElemTypeData->_smdsType ] = true;
913         }
914
915         elemIterator = myMesh->elementsIterator( SMDSAbs_Ball );
916         while ( elemIterator->more() )
917         {
918           const SMDS_MeshElement* anElem = elemIterator->next();
919           // connectivity
920           const SMDS_MeshElement* aNode = anElem->GetNode( 0 );
921 #ifdef _EDF_NODE_IDS_
922           (*aBallInfo->myConn)[ iElem ] = aNodeIdMap[aNode->GetID()];
923 #else
924           (*aBallInfo->myConn)[ iElem ] = aNode->GetID();
925 #endif
926           // element number
927           aBallInfo->SetElemNum( iElem, anElem->GetID() );
928
929           // diameter
930           aBallInfo->myDiameters[ iElem ] =
931             static_cast<const SMDS_BallElement*>( anElem )->GetDiameter();
932
933           // family number
934           int famNum = getFamilyId( anElemFamMap, anElem, defaultFamilyId );
935           aBallInfo->SetFamNum( iElem, famNum );
936           ++iElem;
937         }
938         // store data in a file
939         myMed->SetBallInfo(aBallInfo);
940       }
941
942       else
943       {
944         // Treat standard types
945         // ---------------------
946
947         // allocate data arrays
948         PCellInfo aCellInfo = myMed->CrCellInfo( aMeshInfo,
949                                                  aElemTypeData->_entity,
950                                                  aElemTypeData->_geomType,
951                                                  aElemTypeData->_nbElems,
952                                                  theConnMode,
953                                                  theIsElemNum,
954                                                  theIsElemNames);
955         // build map of family numbers for this type
956         if ( !isElemFamMapBuilt[ aElemTypeData->_smdsType ])
957         {
958           //cout << " fillElemFamilyMap()" << endl;
959           fillElemFamilyMap( anElemFamMap, aFamilies, aElemTypeData->_smdsType );
960           isElemFamMapBuilt[ aElemTypeData->_smdsType ] = true;
961         }
962
963         TInt aNbNodes = MED::GetNbNodes(aElemTypeData->_geomType);
964         elemIterator = myMesh->elementsIterator( aElemTypeData->_smdsType );
965         if ( aElemTypeData->_smdsType == SMDSAbs_0DElement && ! nodesOf0D.empty() )
966           elemIterator = iterVecIter;
967         while ( elemIterator->more() )
968         {
969           const SMDS_MeshElement* anElem = elemIterator->next();
970           if ( anElem->NbNodes() != aNbNodes || anElem->IsPoly() )
971             continue; // other geometry
972
973           // connectivity
974           TConnSlice aTConnSlice = aCellInfo->GetConnSlice( iElem );
975           for (TInt iNode = 0; iNode < aNbNodes; iNode++) {
976             const SMDS_MeshElement* aNode = anElem->GetNode( iNode );
977 #ifdef _EDF_NODE_IDS_
978             aTConnSlice[ iNode ] = aNodeIdMap[aNode->GetID()];
979 #else
980             aTConnSlice[ iNode ] = aNode->GetID();
981 #endif
982           }
983           // element number
984           aCellInfo->SetElemNum( iElem, anElem->GetID() );
985
986           // family number
987           int famNum = getFamilyId( anElemFamMap, anElem, defaultFamilyId );
988           aCellInfo->SetFamNum( iElem, famNum );
989
990           if ( ++iElem == aCellInfo->GetNbElem() )
991             break;
992         }
993         // store data in a file
994         myMed->SetCellInfo(aCellInfo);
995       }
996
997     } // loop on geom types
998
999
1000   }
1001   catch(const std::exception& exc) {
1002     INFOS("The following exception was caught:\n\t"<<exc.what());
1003     throw;
1004   }
1005   catch(...) {
1006     INFOS("Unknown exception was caught !!!");
1007     throw;
1008   }
1009
1010   myMeshId = -1;
1011   myGroups.clear();
1012   mySubMeshes.clear();
1013   return aResult;
1014 }
1015
1016 //================================================================================
1017 /*!
1018  * \brief Returns nodes on VERTEXes where 0D elements are absent
1019  */
1020 //================================================================================
1021
1022 bool DriverMED_W_SMESHDS_Mesh::
1023 getNodesOfMissing0DOnVert(SMESHDS_Mesh*                         meshDS,
1024                           std::vector<const SMDS_MeshElement*>& nodes)
1025 {
1026   nodes.clear();
1027   for ( int i = 1; i <= meshDS->MaxShapeIndex(); ++i )
1028   {
1029     if ( meshDS->IndexToShape( i ).ShapeType() != TopAbs_VERTEX )
1030       continue;
1031     if ( SMESHDS_SubMesh* sm = meshDS->MeshElements(i) ) {
1032       SMDS_NodeIteratorPtr nIt= sm->GetNodes();
1033       while (nIt->more())
1034       {
1035         const SMDS_MeshNode* n = nIt->next();
1036         if ( n->NbInverseElements( SMDSAbs_0DElement ) == 0 )
1037           nodes.push_back( n );
1038       }
1039     }
1040   }
1041   return !nodes.empty();
1042 }