Salome HOME
b4d3dfe42b959ab9daab365c37c74f56adef12d2
[modules/smesh.git] / src / DriverCGNS / DriverCGNS_Write.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 // File      : DriverCGNS_Write.cxx
23 // Created   : Fri Aug  5 17:43:54 2011
24 // Author    : Edward AGAPOV (eap)
25
26 #include "DriverCGNS_Write.hxx"
27
28 #include "SMDS_IteratorOnIterators.hxx"
29 #include "SMDS_MeshNode.hxx"
30 #include "SMDS_VolumeTool.hxx"
31 #include "SMESHDS_GroupBase.hxx"
32 #include "SMESHDS_Mesh.hxx"
33 #include "SMESH_Comment.hxx"
34
35 #include <limits>
36 #include <cgnslib.h>
37
38 #if CGNS_VERSION < 3100
39 # define cgsize_t int
40 #endif
41
42 using namespace std;
43
44 namespace
45 {
46   //================================================================================
47   /*!
48    * \brief Return interlace and type of CGNS element for the given SMDSAbs_EntityType
49    */
50   //================================================================================
51
52   const int* getInterlaceAndType( const SMDSAbs_EntityType      smType,
53                                   CGNS_ENUMT( ElementType_t ) & cgType )
54   {
55     static vector< const int* >                 interlaces;
56     static vector< CGNS_ENUMT( ElementType_t )> cgTypes; 
57     if ( interlaces.empty() )
58     {
59       interlaces.resize( SMDSEntity_Last, 0 );
60       cgTypes.resize( SMDSEntity_Last, CGNS_ENUMV( ElementTypeNull ));
61       {
62         static int ids[] = {0};
63         interlaces[SMDSEntity_0D] = ids;
64         cgTypes   [SMDSEntity_0D] = CGNS_ENUMV( NODE );
65       }
66       {
67         static int ids[] = { 0, 1 };
68         interlaces[SMDSEntity_Edge] = ids;
69         cgTypes   [SMDSEntity_Edge] = CGNS_ENUMV( BAR_2 );
70       }
71       {
72         static int ids[] = { 0, 1, 2 };
73         interlaces[SMDSEntity_Quad_Edge] = ids;
74         cgTypes   [SMDSEntity_Quad_Edge] = CGNS_ENUMV( BAR_3 );
75       }
76       {
77         static int ids[] = { 0, 2, 1 };
78         interlaces[SMDSEntity_Triangle] = ids;
79         cgTypes   [SMDSEntity_Triangle] = CGNS_ENUMV( TRI_3 );
80       }
81       {
82         static int ids[] = { 0, 2, 1, 5, 4, 3 };
83         interlaces[SMDSEntity_Quad_Triangle] = ids;
84         cgTypes   [SMDSEntity_Quad_Triangle] = CGNS_ENUMV( TRI_6 );
85         interlaces[SMDSEntity_BiQuad_Triangle] = ids;
86         cgTypes   [SMDSEntity_BiQuad_Triangle] = CGNS_ENUMV( TRI_6 );
87       }
88       {
89         static int ids[] = { 0, 3, 2, 1 };
90         interlaces[SMDSEntity_Quadrangle] = ids;
91         cgTypes   [SMDSEntity_Quadrangle] = CGNS_ENUMV( QUAD_4 );
92       }
93       {
94         static int ids[] = { 0,3,2,1,7,6,5,4 };
95         interlaces[SMDSEntity_Quad_Quadrangle] = ids;
96         cgTypes   [SMDSEntity_Quad_Quadrangle] = CGNS_ENUMV( QUAD_8 );
97       }
98       {
99         static int ids[] = { 0,3,2,1,7,6,5,4,8 };
100         interlaces[SMDSEntity_BiQuad_Quadrangle] = ids;
101         cgTypes   [SMDSEntity_BiQuad_Quadrangle] = CGNS_ENUMV( QUAD_9 );
102       }
103       {
104         static int ids[] = { 0, 2, 1, 3 };
105         interlaces[SMDSEntity_Tetra] = ids;
106         cgTypes   [SMDSEntity_Tetra] = CGNS_ENUMV( TETRA_4 );
107       }
108       {
109         static int ids[] = { 0,2,1,3,6,5,4,7,9,8 };
110         interlaces[SMDSEntity_Quad_Tetra] = ids;
111         cgTypes   [SMDSEntity_Quad_Tetra] = CGNS_ENUMV( TETRA_10 );
112       }
113       {
114         static int ids[] = { 0,3,2,1,4 };
115         interlaces[SMDSEntity_Pyramid] = ids;
116         cgTypes   [SMDSEntity_Pyramid] = CGNS_ENUMV( PYRA_5 );
117       }
118       {
119         static int ids[] = { 0,3,2,1,4,8,7,6,5,9,12,11,10 };
120         interlaces[SMDSEntity_Quad_Pyramid] = ids;
121         cgTypes   [SMDSEntity_Quad_Pyramid] = CGNS_ENUMV( PYRA_13 );
122       }
123       {
124         static int ids[] = { 0,2,1,3,5,4 };
125         interlaces[SMDSEntity_Penta] = ids;
126         cgTypes   [SMDSEntity_Penta] = CGNS_ENUMV( PENTA_6 );
127       }
128       {
129         static int ids[] = { 0,2,1,3,5,4,8,7,6,9,11,10,14,13,12 };
130         interlaces[SMDSEntity_Quad_Penta] = ids;
131         cgTypes   [SMDSEntity_Quad_Penta] = CGNS_ENUMV( PENTA_15 );
132       }
133       {
134         static int ids[] = { 0,2,1,3,5,4,8,7,6,9,11,10,14,13,12,15,16,17 }; // TODO: check CGNS ORDER
135         interlaces[SMDSEntity_BiQuad_Penta] = ids;
136         cgTypes   [SMDSEntity_BiQuad_Penta] = CGNS_ENUMV( PENTA_18 );
137       }
138       {
139         static int ids[] = { 0,3,2,1,4,7,6,5 };
140         interlaces[SMDSEntity_Hexa] = ids;
141         cgTypes   [SMDSEntity_Hexa] = CGNS_ENUMV( HEXA_8 );
142       }
143       {
144         static int ids[] = { 0,3,2,1,4,7,6,5,11,10,9,8,12,15,14,13,19,18,17,16 };
145         interlaces[SMDSEntity_Quad_Hexa] = ids;
146         cgTypes   [SMDSEntity_Quad_Hexa] = CGNS_ENUMV( HEXA_20 );
147       }
148       {
149         static int ids[] = { 0,3,2,1,4,7,6,5,11,10,9,8,12,15,14,13,19,18,17,16,
150                              20, 24,23,22,21, 25, 26};
151         interlaces[SMDSEntity_TriQuad_Hexa] = ids;
152         cgTypes   [SMDSEntity_TriQuad_Hexa] = CGNS_ENUMV( HEXA_27 );
153       }
154       {
155         cgTypes[SMDSEntity_Polygon]         = CGNS_ENUMV( NGON_n );
156         cgTypes[SMDSEntity_Quad_Polygon]    = CGNS_ENUMV( NGON_n );
157         cgTypes[SMDSEntity_Polyhedra]       = CGNS_ENUMV( NFACE_n );
158         cgTypes[SMDSEntity_Hexagonal_Prism] = CGNS_ENUMV( NFACE_n );
159       }
160     }
161     cgType  = cgTypes[ smType ];
162     return interlaces[ smType ];
163   }
164
165   //================================================================================
166   /*!
167    * \brief Cut off type of boundary condition from the group name
168    */
169   //================================================================================
170
171   CGNS_ENUMT( BCType_t ) getBCType( string& groupName )
172   {
173     CGNS_ENUMT( BCType_t ) bcType = CGNS_ENUMV( BCGeneral ); // default type
174
175     // boundary condition type starts from "BC"
176     size_t bcBeg = groupName.find("BC");
177     if ( bcBeg != string::npos )
178     {
179       for ( int t = 0; t < NofValidBCTypes; ++t )
180       {
181         CGNS_ENUMT( BCType_t ) type = CGNS_ENUMT( BCType_t )( t );
182         string typeName = cg_BCTypeName( type );
183         if ( typeName == &groupName[0] + bcBeg )
184         {
185           bcType = type;
186           while ( bcBeg > 0 && isspace( bcBeg-1 ))
187             --bcBeg;
188           if ( bcBeg == 0 )
189             groupName = "Group";
190           else
191             groupName = groupName.substr( 0, bcBeg-1 );
192         }
193       }
194     }
195     return bcType;
196   }
197
198   //================================================================================
199   /*!
200    * \brief Sortable face of a polyhedron
201    */
202   struct TPolyhedFace
203   {
204     int _id; // id of NGON_n
205     vector< int > _nodes; // lowest node IDs used for sorting
206
207     TPolyhedFace( const SMDS_MeshNode** nodes, const int nbNodes, int ID):_id(ID)
208     {
209       set< int > ids;
210       for ( int i = 0; i < nbNodes; ++i )
211         ids.insert( nodes[i]->GetID() );
212
213       _nodes.resize( 3 ); // std::min( nbNodes, 4 )); hope 3 nodes is enough
214       set< int >::iterator idIt = ids.begin();
215       for ( size_t j = 0; j < _nodes.size(); ++j, ++idIt )
216         _nodes[j] = *idIt;
217     }
218     bool operator< (const TPolyhedFace& o ) const
219     {
220       return _nodes < o._nodes;
221     }
222   };
223   //================================================================================
224   /*!
225    * \brief Return CGNS id of an element
226    */
227   //================================================================================
228
229   cgsize_t cgnsID( const SMDS_MeshElement*                         elem,
230                    const map< const SMDS_MeshElement*, cgsize_t >& elem2cgID )
231   {
232     map< const SMDS_MeshElement*, cgsize_t >::const_iterator e2id = elem2cgID.find( elem );
233     return ( e2id == elem2cgID.end() ? elem->GetID() : e2id->second );
234   }
235
236   //================================================================================
237   /*!
238    * \brief save nb nodes of a polygon
239    */
240   //================================================================================
241
242   void addPolySize( const cgsize_t            nbNodes,
243                     std::vector< cgsize_t >& elemData,
244                     std::vector< cgsize_t >& polyOffset )
245   {
246 #if CGNS_VERSION < 4100
247     elemData.push_back( nbNodes );
248     polyOffset.clear(); // just avoid warning: unused parameter
249 #else
250     polyOffset.push_back((cgsize_t) elemData.size() );
251     (void)nbNodes; // avoid warning: unused parameter
252 #endif
253   }
254
255 } // namespace
256
257 //================================================================================
258 /*!
259  * \brief Write the mesh into the CGNS file
260  */
261 //================================================================================
262
263 Driver_Mesh::Status DriverCGNS_Write::Perform()
264 {
265   myErrorMessages.clear();
266
267   if ( !myMesh || myMesh->GetMeshInfo().NbElements() < 1 )
268     return addMessage( !myMesh ? "NULL mesh" : "Empty mesh (no elements)", /*fatal = */true );
269
270   // open the file
271   if ( cg_open(myFile.c_str(), CG_MODE_MODIFY, &_fn) != CG_OK &&
272        cg_open(myFile.c_str(), CG_MODE_WRITE,  &_fn) != CG_OK )
273     return addMessage( cg_get_error(), /*fatal = */true );
274
275   // create a Base
276   // --------------
277
278   const int spaceDim = 3;
279   int        meshDim = 1;
280   if ( myMesh->NbFaces()   > 0 ) meshDim = 2;
281   if ( myMesh->NbVolumes() > 0 ) meshDim = 3;
282
283   if ( myMeshName.empty() )
284   {
285     int nbases = 0;
286     if ( cg_nbases( _fn, &nbases) == CG_OK )
287       myMeshName = ( SMESH_Comment("Base_") << nbases+1 );
288     else
289       myMeshName = "Base_0";
290   }
291   int iBase;
292   if ( cg_base_write( _fn, myMeshName.c_str(), meshDim, spaceDim, &iBase ))
293     return addMessage( cg_get_error(), /*fatal = */true );
294
295   // create a Zone
296   // --------------
297
298   int nbCells = myMesh->NbEdges();
299   if ( meshDim == 3 )
300     nbCells = myMesh->NbVolumes();
301   else if ( meshDim == 2 )
302     nbCells = myMesh->NbFaces();
303
304   cgsize_t size[9] = { myMesh->NbNodes(), nbCells, /*NBoundVertex=*/0, 0,0,0,0,0,0 };
305   int iZone;
306   if ( cg_zone_write( _fn, iBase, "SMESH_Mesh", size,
307                       CGNS_ENUMV( Unstructured ), &iZone) != CG_OK )
308     return addMessage( cg_get_error(), /*fatal = */true );
309
310   // Map to store only elements whose an SMDS ID differs from a CGNS one
311   typedef map< const SMDS_MeshElement*, cgsize_t > TElem2cgIDMap;
312   vector< TElem2cgIDMap > elem2cgIDByEntity( SMDSEntity_Last );
313   TElem2cgIDMap::iterator elem2cgIDIter;
314
315   TElem2cgIDMap & n2cgID = elem2cgIDByEntity[ SMDSEntity_Node ];
316
317   // Write nodes
318   // ------------
319   {
320     vector< double > coords( myMesh->NbNodes() );
321     int iC;
322     // X
323     SMDS_NodeIteratorPtr nIt = myMesh->nodesIterator();
324     for ( int i = 0; nIt->more(); ++i ) coords[i] = nIt->next()->X();
325     if ( cg_coord_write( _fn, iBase, iZone, CGNS_ENUMV(RealDouble),
326                           "CoordinateX", &coords[0], &iC) != CG_OK )
327       return addMessage( cg_get_error(), /*fatal = */true );
328     // Y
329     nIt = myMesh->nodesIterator();
330     for ( int i = 0; nIt->more(); ++i ) coords[i] = nIt->next()->Y();
331     if ( cg_coord_write( _fn, iBase, iZone, CGNS_ENUMV(RealDouble),
332                           "CoordinateY", &coords[0], &iC) != CG_OK )
333       return addMessage( cg_get_error(), /*fatal = */true );
334     // Z
335     nIt = myMesh->nodesIterator();
336     for ( int i = 0; nIt->more(); ++i ) coords[i] = nIt->next()->Z();
337     if ( cg_coord_write( _fn, iBase, iZone, CGNS_ENUMV(RealDouble),
338                           "CoordinateZ", &coords[0], &iC) != CG_OK )
339       return addMessage( cg_get_error(), /*fatal = */true );
340
341     // store CGNS ids of nodes
342     nIt = myMesh->nodesIterator();
343     for ( int i = 0; nIt->more(); ++i )
344     {
345       const SMDS_MeshElement* n = nIt->next();
346       if ( n->GetID() != i+1 )
347         n2cgID.insert( n2cgID.end(), make_pair( n, i+1 ));
348     }
349   }
350   // Write elements
351   // ---------------
352   
353   cgsize_t cgID = 1, startID;
354
355   // write into a section all successive elements of one geom type
356   int iSec;
357   vector< cgsize_t > elemData, polyOffset;
358   SMDS_ElemIteratorPtr elemIt = myMesh->elementsIterator();
359   vector< SMDS_ElemIteratorPtr > elemItVec;
360   if ( _elementsByType )
361   {
362     // create an iterator returning all elements by type
363     for ( int type = SMDSEntity_Node + 1; type < SMDSEntity_Last; ++type )
364     {
365       if ( type == SMDSEntity_Ball )
366         continue; // not supported
367       elemIt = myMesh->elementEntityIterator( SMDSAbs_EntityType( type ));
368       if ( elemIt->more() )
369         elemItVec.push_back( elemIt );
370     }
371     typedef SMDS_IteratorOnIterators< const SMDS_MeshElement*,
372                                       vector< SMDS_ElemIteratorPtr > > TVecIterator;
373     elemIt.reset( new TVecIterator( elemItVec ));
374   }
375
376   const SMDS_MeshElement* elem = elemIt->next();
377   while ( elem )
378   {
379     const SMDSAbs_EntityType elemType = elem->GetEntityType();
380     CGNS_ENUMT( ElementType_t ) cgType;
381     const int* interlace = getInterlaceAndType( elemType, cgType );
382
383     TElem2cgIDMap & elem2cgID = elem2cgIDByEntity[ elemType ];
384
385     elemData.clear();
386     startID = cgID;
387
388     if ( interlace ) // STANDARD elements
389     {
390       int cgnsNbNodes; // get nb nodes by element type, that can be less that elem->NbNodes()
391       cg_npe( cgType, &cgnsNbNodes );
392       do
393       {
394         for ( int i = 0; i < cgnsNbNodes; ++i )
395           elemData.push_back( cgnsID( elem->GetNode( interlace[i] ), n2cgID ));
396         if ( elem->GetID() != cgID )
397           elem2cgID.insert( elem2cgID.end(), make_pair( elem, cgID ));
398         ++cgID;
399         elem = elemIt->more() ? elemIt->next() : 0;
400       }
401       while ( elem && elem->GetEntityType() == elemType );
402     }
403     else if ( elemType == SMDSEntity_Polygon ) // POLYGONS
404       do
405       {
406         addPolySize( elem->NbNodes(), elemData, polyOffset );
407         for ( int i = 0, nb = elem->NbNodes(); i < nb; ++i )
408           elemData.push_back( cgnsID( elem->GetNode(i), n2cgID ));
409         if ( elem->GetID() != cgID )
410           elem2cgID.insert( elem2cgID.end(), make_pair( elem, cgID ));
411         ++cgID;
412         elem = elemIt->more() ? elemIt->next() : 0;
413       }
414       while ( elem && elem->GetEntityType() == elemType );
415
416     else if ( elemType == SMDSEntity_Quad_Polygon ) // QUADRATIC POLYGONS
417       do // write as linear NGON_n
418       {
419         addPolySize( elem->NbNodes(), elemData, polyOffset );
420         interlace = & SMDS_MeshCell::interlacedSmdsOrder( SMDSEntity_Quad_Polygon,
421                                                           elem->NbNodes() )[0];
422         for ( int i = 0, nb = elem->NbNodes(); i < nb; ++i )
423           elemData.push_back( cgnsID( elem->GetNode( interlace[i] ), n2cgID ));
424         if ( elem->GetID() != cgID )
425           elem2cgID.insert( elem2cgID.end(), make_pair( elem, cgID ));
426         ++cgID;
427         elem = elemIt->more() ? elemIt->next() : 0;
428       }
429       while ( elem && elem->GetEntityType() == elemType );
430
431     else if ( elemType == SMDSEntity_Polyhedra ||
432               elemType == SMDSEntity_Hexagonal_Prism) // POLYHEDRA
433     {
434       // to save polyhedrons after all
435       const SMDS_MeshInfo& meshInfo = myMesh->GetMeshInfo();
436       if ( meshInfo.NbPolyhedrons() == meshInfo.NbElements() - cgID + 1 )
437         break; // only polyhedrons remain
438       while ( elem && elem->GetEntityType() == elemType )
439         elem = elemIt->more() ? elemIt->next() : 0;
440       continue;
441     }
442     else // skip NOT SUPPORTED elements
443     {
444       while ( elemIt->more() )
445       {
446         elem = elemIt->next();
447         if ( elem->GetEntityType() != elemType )
448           break;
449       }
450     }
451
452     SMESH_Comment sectionName( cg_ElementTypeName( cgType ));
453     sectionName << " " << startID << " - " << cgID-1;
454
455
456 #if CGNS_VERSION >= 4000
457     if ( !polyOffset.empty() )
458     {
459       polyOffset.push_back((cgsize_t) elemData.size() );
460       if ( cg_poly_section_write(_fn, iBase, iZone, sectionName.c_str(), cgType, startID,
461                                  cgID-1, /*nbndry=*/0,
462                                  elemData.data(), polyOffset.data(), &iSec) != CG_OK )
463         return addMessage( cg_get_error(), /*fatal = */true );
464     }
465     else
466 #endif
467     {
468       if ( cg_section_write(_fn, iBase, iZone, sectionName.c_str(), cgType, startID,
469                             cgID-1, /*nbndry=*/0, elemData.data(), &iSec) != CG_OK )
470         return addMessage( cg_get_error(), /*fatal = */true );
471     }
472   }
473
474   // Write polyhedral volumes
475   // -------------------------
476
477   if ( myMesh->GetMeshInfo().NbElements() > cgID-1 ) // polyhedra or hexagonal prisms remain
478   {
479     // the polyhedron (NFACE_n) is described as a set of signed face IDs,
480     // so first we are to write all polygones (NGON_n) bounding polyhedrons
481
482     vector< cgsize_t > faceData;
483     set< TPolyhedFace > faces;
484     set< TPolyhedFace >::iterator faceInSet;
485     vector<const SMDS_MeshNode *> faceNodesVec;
486     vector< cgsize_t > faceOffset;
487     int nbPolygones = 0, faceID;
488
489     SMDS_VolumeTool vol;
490
491     elemData.clear();
492     polyOffset.clear();
493
494     int nbPolyhTreated = 0;
495
496     TElem2cgIDMap * elem2cgID = 0;
497     TElem2cgIDMap & n2cgID    = elem2cgIDByEntity[ SMDSEntity_Node ];
498
499     SMDS_ElemIteratorPtr elemIt = myMesh->elementsIterator();
500     while ( elemIt->more() )
501     {
502       elem = elemIt->next();
503       SMDSAbs_EntityType type = elem->GetEntityType();
504       if ( type == SMDSEntity_Polyhedra ||
505            type == SMDSEntity_Hexagonal_Prism )
506       {
507         ++nbPolyhTreated;
508         vol.Set( elem );
509         vol.SetExternalNormal();
510         const int nbFaces = vol.NbFaces();
511         addPolySize( nbFaces, elemData, polyOffset );
512         for ( int iF = 0; iF < nbFaces; ++iF )
513         {
514           const int nbNodes = vol.NbFaceNodes( iF );
515           const SMDS_MeshNode** faceNodes = vol.GetFaceNodes( iF );
516           faceNodesVec.assign( faceNodes, faceNodes + nbNodes );
517           if (( elem = myMesh->FindElement( faceNodesVec, SMDSAbs_Face, /*noMedium=*/false)))
518           {
519             // a face of the polyhedron is present in the mesh
520             faceID = cgnsID( elem, elem2cgIDByEntity[ elem->GetEntityType() ]);
521           }
522           else if ( vol.IsFreeFace( iF ))
523           {
524             // the face is not shared by volumes
525             faceID = cgID++;
526             ++nbPolygones;
527             addPolySize( nbNodes, faceData, faceOffset );
528             for ( int i = 0; i < nbNodes; ++i )
529               faceData.push_back( cgnsID( faceNodes[i], n2cgID ));
530           }
531           else
532           {
533             TPolyhedFace face( faceNodes, nbNodes, cgID );
534             faceInSet = faces.insert( faces.end(), face );
535             if ( faceInSet->_id == cgID ) // the face encounters for the 1st time
536             {
537               faceID = cgID++;
538               ++nbPolygones;
539               addPolySize( nbNodes, faceData, faceOffset );
540               for ( int i = 0; i < nbNodes; ++i )
541                 faceData.push_back( cgnsID( faceNodes[i], n2cgID ));
542             }
543             else
544             {
545               // the face encounters for the 2nd time; we hope it won't encounter once more,
546               // for that we can erase it from the set of faces
547               faceID = -faceInSet->_id;
548               faces.erase( faceInSet );
549             }
550           }
551           elemData.push_back( faceID );
552         }
553       }
554     }
555
556 #if CGNS_VERSION >= 4000
557     if ( nbPolygones > 0 )
558     {
559       faceOffset.push_back((cgsize_t) faceData.size() );
560       if ( cg_poly_section_write(_fn, iBase, iZone, "Faces of Polyhedrons", CGNS_ENUMV( NGON_n ),
561                                  cgID - nbPolygones, cgID-1, /*nbndry=*/0,
562                                  faceData.data(), faceOffset.data(), &iSec) != CG_OK )
563         return addMessage( cg_get_error(), /*fatal = */true );
564     }
565
566     polyOffset.push_back((cgsize_t) elemData.size() );
567     if ( cg_poly_section_write(_fn, iBase, iZone, "Polyhedrons",
568                                CGNS_ENUMV( NFACE_n ), cgID, cgID+nbPolyhTreated-1,
569                                /*nbndry=*/0, &elemData[0], polyOffset.data(), &iSec) != CG_OK )
570       return addMessage( cg_get_error(), /*fatal = */true );
571 #else
572     if ( nbPolygones > 0 )
573     {
574       if ( cg_section_write(_fn, iBase, iZone, "Faces of Polyhedrons",
575                             CGNS_ENUMV( NGON_n ), cgID - nbPolygones, cgID-1,
576                             /*nbndry=*/0, &faceData[0], &iSec) != CG_OK )
577         return addMessage( cg_get_error(), /*fatal = */true );
578     }
579
580     if ( cg_section_write(_fn, iBase, iZone, "Polyhedrons",
581                           CGNS_ENUMV( NFACE_n ), cgID, cgID+nbPolyhTreated-1,
582                           /*nbndry=*/0, &elemData[0], &iSec) != CG_OK )
583       return addMessage( cg_get_error(), /*fatal = */true );
584 #endif
585
586     if ( !myMesh->GetGroups().empty() )
587     {
588       // store CGNS ids of polyhedrons
589       elem2cgID = &elem2cgIDByEntity[ SMDSEntity_Polyhedra ];
590       elemIt = myMesh->elementsIterator();
591       while ( elemIt->more() )
592       {
593         elem = elemIt->next();
594         if ( elem->GetEntityType() == SMDSEntity_Polyhedra )
595         {
596           if ( elem->GetID() != cgID )
597             elem2cgID->insert( elem2cgID->end(), make_pair( elem, cgID ));
598           ++cgID;
599         }
600       }
601     }
602   } // write polyhedral volumes
603
604
605   // Write groups as boundary conditions
606   // ------------------------------------
607
608   const set<SMESHDS_GroupBase*>& groups = myMesh->GetGroups();
609   set<SMESHDS_GroupBase*>::const_iterator grpIt = groups.begin();
610   set< string > groupNames; groupNames.insert(""); // to avoid duplicated and empty names
611   for ( ; grpIt != groups.end(); ++grpIt )
612   {
613     const SMESHDS_GroupBase* group = *grpIt;
614
615     // write BC location (default is Vertex)
616     CGNS_ENUMT( GridLocation_t ) location = CGNS_ENUMV( Vertex );
617     if ( group->GetType() != SMDSAbs_Node )
618     {
619       switch ( meshDim ) {
620       case 3:
621         switch ( group->GetType() ) {
622 #if CGNS_VERSION > 3130
623         case SMDSAbs_Volume: location = CGNS_ENUMV( CellCenter ); break;
624 #else
625         case SMDSAbs_Volume: location = CGNS_ENUMV( FaceCenter ); break;
626 #endif
627         case SMDSAbs_Face:   location = CGNS_ENUMV( FaceCenter ); break;
628         case SMDSAbs_Edge:   location = CGNS_ENUMV( EdgeCenter ); break;
629         default:;
630         }
631         break;
632       case 2:
633         switch ( group->GetType() ) {
634 #if CGNS_VERSION > 3130
635         case SMDSAbs_Face: location = CGNS_ENUMV( CellCenter ); break;
636 #else
637         case SMDSAbs_Face: location = CGNS_ENUMV( FaceCenter ); break;
638 #endif
639         case SMDSAbs_Edge: location = CGNS_ENUMV( EdgeCenter ); break;
640         default:;
641         }
642         break;
643       case 1:
644 #if CGNS_VERSION > 3130
645         location = CGNS_ENUMV( CellCenter ); break;
646 #else
647         location = CGNS_ENUMV( EdgeCenter ); break;
648 #endif
649         break;
650       }
651     }
652
653     // try to extract type of boundary condition from the group name
654     string name = group->GetStoreName();
655     CGNS_ENUMT( BCType_t ) bcType = getBCType( name );
656     if ( !groupNames.insert( name ).second ) // assure name uniqueness
657     {
658       int index = 1;
659       string newName;
660       do {
661         newName = SMESH_Comment( name ) << "_" << index++;
662       }
663       while ( !groupNames.insert( newName ).second );
664       name = newName;
665     }
666     // write IDs of elements
667     vector< cgsize_t > pnts;
668     pnts.reserve( group->Extent() );
669     SMDS_ElemIteratorPtr elemIt = group->GetElements();
670     while ( elemIt->more() )
671     {
672       const SMDS_MeshElement* elem = elemIt->next();
673       pnts.push_back( cgnsID( elem, elem2cgIDByEntity[ elem->GetEntityType() ]));
674     }
675     if ( pnts.size() == 0 )
676       continue; // can't store empty group
677     int iBC;
678     if ( cg_boco_write( _fn, iBase, iZone, name.c_str(), bcType,
679                         CGNS_ENUMV( PointList ), pnts.size(), &pnts[0], &iBC) != CG_OK )
680       return addMessage( cg_get_error(), /*fatal = */true);
681
682     // write BC location
683     if ( location != CGNS_ENUMV( Vertex ) || meshDim == 1 )
684     {
685       if ( cg_boco_gridlocation_write( _fn, iBase, iZone, iBC, location) != CG_OK )
686         return addMessage( cg_get_error(), /*fatal = */false);
687     }
688   }
689   return DRS_OK;
690 }
691
692 //================================================================================
693 /*!
694  * \brief Constructor
695  */
696 //================================================================================
697
698 DriverCGNS_Write::DriverCGNS_Write(): _fn(0), _elementsByType( false )
699 {
700 }
701
702 //================================================================================
703 /*!
704  * \brief Close the cgns file at destruction
705  */
706 //================================================================================
707
708 DriverCGNS_Write::~DriverCGNS_Write()
709 {
710   if ( _fn > 0 )
711     cg_close( _fn );
712 }