Salome HOME
Fix regressions caused by improvements
[modules/smesh.git] / src / StdMeshers / StdMeshers_CompositeHexa_3D.cxx
1 // Copyright (C) 2007-2015  CEA/DEN, EDF R&D, OPEN CASCADE
2 //
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 // Lesser General Public License for more details.
12 //
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16 //
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
18 //
19
20 //  SMESH SMESH : implementaion of SMESH idl descriptions
21 // File      : StdMeshers_CompositeHexa_3D.cxx
22 // Module    : SMESH
23 // Created   : Tue Nov 25 11:04:59 2008
24 // Author    : Edward AGAPOV (eap)
25
26 #include "StdMeshers_CompositeHexa_3D.hxx"
27
28 #include "SMDS_Mesh.hxx"
29 #include "SMDS_MeshNode.hxx"
30 #include "SMDS_SetIterator.hxx"
31 #include "SMESH_Block.hxx"
32 #include "SMESH_Comment.hxx"
33 #include "SMESH_ComputeError.hxx"
34 #include "SMESH_Mesh.hxx"
35 #include "SMESH_MeshAlgos.hxx"
36 #include "SMESH_MesherHelper.hxx"
37 #include "SMESH_subMesh.hxx"
38
39 #include <BRepAdaptor_Surface.hxx>
40 #include <BRep_Tool.hxx>
41 #include <Standard_ErrorHandler.hxx>
42 #include <Standard_Failure.hxx>
43 #include <TopExp_Explorer.hxx>
44 #include <TopTools_IndexedMapOfShape.hxx>
45 #include <TopTools_MapIteratorOfMapOfShape.hxx>
46 #include <TopTools_MapOfShape.hxx>
47 #include <TopTools_SequenceOfShape.hxx>
48 #include <TopoDS.hxx>
49 #include <TopoDS_Edge.hxx>
50 #include <TopoDS_Face.hxx>
51 #include <TopoDS_Vertex.hxx>
52 #include <gp_Pnt.hxx>
53 #include <gp_Pnt2d.hxx>
54 #include <gp_Vec.hxx>
55 #include <gp_XYZ.hxx>
56
57 #include <list>
58 #include <set>
59 #include <vector>
60
61
62 #ifdef _DEBUG_
63 // #define DEB_FACES
64 // #define DEB_GRID
65 // #define DUMP_VERT(msg,V) \
66 //   { TopoDS_Vertex v = V; gp_Pnt p = BRep_Tool::Pnt(v);                  \
67 //     cout << msg << "( "<< p.X()<<", "<<p.Y()<<", "<<p.Z()<<" )"<<endl;}
68 #endif
69
70 #ifndef DUMP_VERT
71 #define DUMP_VERT(msg,v)
72 #endif
73
74 //================================================================================
75 // text for message about an internal error
76 #define ERR_LI(txt) SMESH_Comment(txt) << ":" << __LINE__
77
78 // order corresponds to right order of edges in CASCADE face
79 enum EQuadSides{ Q_BOTTOM=0, Q_RIGHT, Q_TOP, Q_LEFT,   Q_CHILD, Q_PARENT };
80
81 enum EBoxSides{ B_BOTTOM=0, B_RIGHT, B_TOP, B_LEFT, B_FRONT, B_BACK, B_UNDEFINED };
82
83 //================================================================================
84 /*!
85  * \brief Convertor of a pair of integers to a sole index
86  */
87 struct _Indexer
88 {
89   int _xSize, _ySize;
90   _Indexer( int xSize, int ySize ): _xSize(xSize), _ySize(ySize) {}
91   int size() const { return _xSize * _ySize; }
92   int operator()(const int x, const int y) const { return y * _xSize + x; }
93 };
94
95 //================================================================================
96 /*!
97  * \brief Wrapper of a composite or an ordinary edge.
98  */
99 class _FaceSide
100 {
101 public:
102   _FaceSide(const _FaceSide& other);
103   _FaceSide(const TopoDS_Edge& edge=TopoDS_Edge());
104   _FaceSide(const list<TopoDS_Edge>& edges);
105   _FaceSide* GetSide(const int i);
106   const _FaceSide* GetSide(const int i) const;
107   int size() const { return myChildren.size(); }
108   int NbVertices() const;
109   int NbCommonVertices( const TopTools_MapOfShape& VV ) const;
110   TopoDS_Vertex FirstVertex() const;
111   TopoDS_Vertex LastVertex() const;
112   TopoDS_Vertex Vertex(int i) const;
113   TopoDS_Edge   Edge(int i) const;
114   bool Contain( const _FaceSide& side, int* which=0 ) const;
115   bool Contain( const TopoDS_Vertex& vertex ) const;
116   void AppendSide( const _FaceSide& side );
117   void SetBottomSide( int i );
118   int GetNbSegments(SMESH_Mesh& mesh) const;
119   bool StoreNodes(SMESH_Mesh& mesh, vector<const SMDS_MeshNode*>& myGrid, bool reverse );
120   void SetID(EQuadSides id) { myID = id; }
121   static inline const TopoDS_TShape* ptr(const TopoDS_Shape& theShape)
122   { return theShape.TShape().operator->(); }
123   void Dump() const;
124
125 private:
126
127
128   TopoDS_Edge       myEdge;
129   list< _FaceSide > myChildren;
130   int               myNbChildren;
131
132   TopTools_MapOfShape myVertices;
133
134   EQuadSides        myID; // debug
135 };
136 //================================================================================
137 /*!
138  * \brief Class corresponding to a meshed composite face of a box.
139  *        Provides simplified access to it's sub-mesh data.
140  */
141 class _QuadFaceGrid
142 {
143   typedef list< _QuadFaceGrid > TChildren;
144 public:
145   _QuadFaceGrid();
146
147 public: //** Methods to find and orient faces of 6 sides of the box **//
148   
149   //!< initialization
150   bool Init(const TopoDS_Face& f, SMESH_Mesh& mesh );
151
152   //!< try to unite self with other face
153   bool AddContinuousFace( const _QuadFaceGrid& f, const TopTools_MapOfShape& internalEdges );
154
155   //!< Try to set the side as bottom hirizontal side
156   bool SetBottomSide(const _FaceSide& side, int* sideIndex=0);
157
158   //!< Return face adjacent to zero-based i-th side of this face
159   _QuadFaceGrid* FindAdjacentForSide(int i, list<_QuadFaceGrid>& faces, EBoxSides id) const;
160
161   //!< Reverse edges in order to have the bottom edge going along axes of the unit box
162   void ReverseEdges(/*int e1, int e2*/);
163
164   bool IsComplex() const { return !myChildren.empty(); }
165
166   int NbChildren() const { return myChildren.size(); }
167
168   typedef SMDS_SetIterator< const _QuadFaceGrid&,
169                             TChildren::const_iterator,
170                             SMDS::SimpleAccessor<const _QuadFaceGrid&,TChildren::const_iterator>,
171                             SMDS::PassAllValueFilter<_QuadFaceGrid> >
172     TChildIterator;
173
174   TChildIterator GetChildren() const
175   { return TChildIterator( myChildren.begin(), myChildren.end()); }
176
177 public: //** Loading and access to mesh **//
178
179   //!< Load nodes of a mesh
180   bool LoadGrid( SMESH_Mesh& mesh );
181
182   //!< Return number of segments on the hirizontal sides
183   int GetNbHoriSegments(SMESH_Mesh& mesh, bool withBrothers=false) const;
184
185   //!< Return number of segments on the vertical sides
186   int GetNbVertSegments(SMESH_Mesh& mesh, bool withBrothers=false) const;
187
188   //!< Return edge on the hirizontal bottom sides
189   int GetHoriEdges(vector<TopoDS_Edge> & edges) const;
190
191   //!< Return a node by its position
192   const SMDS_MeshNode* GetNode(int iHori, int iVert) const;
193
194   //!< Return node coordinates by its position
195   gp_XYZ GetXYZ(int iHori, int iVert) const;
196
197 public: //** Access to member fields **//
198
199   //!< Return i-th face side (0<i<4)
200   const _FaceSide& GetSide(int i) const;
201
202   //!< Return it's face, NULL if it is composite
203   TopoDS_Face GetFace() const { return myFace; }
204
205   //!< Return normal to the face at vertex v
206   bool GetNormal( const TopoDS_Vertex& v, gp_Vec& n ) const;
207
208   SMESH_ComputeErrorPtr GetError() const { return myError; }
209
210   void SetID(EBoxSides id) { myID = id; }
211
212   void DumpGrid() const;
213
214   void DumpVertices() const;
215
216 private:
217
218   bool error(const std::string& text, int code = COMPERR_ALGO_FAILED)
219   { myError = SMESH_ComputeError::New( code, text ); return false; }
220
221   bool error(const SMESH_ComputeErrorPtr& err)
222   { myError = err; return ( !myError || myError->IsOK() ); }
223
224   bool loadCompositeGrid(SMESH_Mesh& mesh);
225
226   bool fillGrid(SMESH_Mesh&                    theMesh,
227                 vector<const SMDS_MeshNode*> & theGrid,
228                 const _Indexer&                theIndexer,
229                 int                            theX,
230                 int                            theY);
231
232   bool locateChildren();
233
234   void setBrothers( set< _QuadFaceGrid* >& notLocatedBrothers );
235
236   TopoDS_Face myFace;
237   _FaceSide   mySides;
238   bool        myReverse;
239
240   TChildren   myChildren;
241
242   _QuadFaceGrid* myLeftBottomChild;
243   _QuadFaceGrid* myRightBrother;
244   _QuadFaceGrid* myUpBrother;
245
246   _Indexer    myIndexer;
247   vector<const SMDS_MeshNode*>  myGrid;
248
249   SMESH_ComputeErrorPtr         myError;
250
251   EBoxSides   myID; // debug
252 };
253
254 //================================================================================
255 /*!
256  * \brief Constructor
257  */
258 //================================================================================
259
260 StdMeshers_CompositeHexa_3D::StdMeshers_CompositeHexa_3D(int hypId, int studyId, SMESH_Gen* gen)
261   :SMESH_3D_Algo(hypId, studyId, gen)
262 {
263   _name = "CompositeHexa_3D";
264   _shapeType = (1 << TopAbs_SHELL) | (1 << TopAbs_SOLID);       // 1 bit /shape type
265 }
266
267 //================================================================================
268 /*!
269  * \brief always return true
270  */
271 //================================================================================
272
273 bool StdMeshers_CompositeHexa_3D::CheckHypothesis(SMESH_Mesh&         aMesh,
274                                                   const TopoDS_Shape& aShape,
275                                                   Hypothesis_Status&  aStatus)
276 {
277   aStatus = HYP_OK;
278   return true;
279 }
280
281 namespace
282 {
283
284   //================================================================================
285   /*!
286    * \brief Checks structure of a quadrangular mesh at the common VERTEX of two EDGEs.
287    *        Returns true if there are two quadrangles near the VERTEX.
288    */
289   //================================================================================
290
291   bool isContinuousMesh(TopoDS_Edge        E1,
292                         TopoDS_Edge        E2,
293                         const TopoDS_Face& F,
294                         const SMESH_Mesh&  mesh)
295   {
296     if (E1.Orientation() > TopAbs_REVERSED) // INTERNAL
297       E1.Orientation( TopAbs_FORWARD );
298     if (E2.Orientation() > TopAbs_REVERSED) // INTERNAL
299       E2.Orientation( TopAbs_FORWARD );
300
301     TopoDS_Vertex V;
302     if ( !TopExp::CommonVertex( E1, E2, V )) return false;
303
304     const SMDS_MeshNode* n = SMESH_Algo::VertexNode( V, mesh.GetMeshDS() );
305     if ( !n ) return false;
306
307     SMESHDS_SubMesh* sm = mesh.GetSubMeshContaining( F )->GetSubMeshDS();
308     if ( !sm ) return false;
309
310     int nbQuads = 0;
311     SMDS_ElemIteratorPtr fIt = n->GetInverseElementIterator(SMDSAbs_Face);
312     while ( fIt->more() )
313     {
314       const SMDS_MeshElement* f = fIt->next();
315       if ( !sm->Contains( f )) continue;
316
317       if ( f->NbCornerNodes() == 4 )
318         ++nbQuads;
319       else
320         return false;
321     }
322     return nbQuads == 2;
323   }
324
325   //================================================================================
326   /*!
327    * \brief Finds VERTEXes located at block corners
328    */
329   //================================================================================
330
331   void getBlockCorners( SMESH_Mesh&          mesh,
332                         const TopoDS_Shape&  shape,
333                         TopTools_MapOfShape& cornerVV)
334   {
335     set<int> faceIDs; // ids of FACEs in the shape
336     TopExp_Explorer exp;
337     for ( exp.Init( shape, TopAbs_FACE ); exp.More(); exp.Next() )
338       faceIDs.insert( mesh.GetMeshDS()->ShapeToIndex( exp.Current() ));
339
340     TopTools_MapOfShape checkedVV;
341     for ( exp.Init( shape, TopAbs_VERTEX ); exp.More(); exp.Next() )
342     {
343       TopoDS_Vertex V = TopoDS::Vertex( exp.Current() );
344       if ( !checkedVV.Add( V )) continue;
345
346       const SMDS_MeshNode* n = SMESH_Algo::VertexNode( V, mesh.GetMeshDS() );
347       if ( !n ) continue;
348
349       int nbQuads = 0;
350       SMDS_ElemIteratorPtr fIt = n->GetInverseElementIterator(SMDSAbs_Face);
351       while ( fIt->more() )
352       {
353         const SMDS_MeshElement* f = fIt->next();
354         if ( !faceIDs.count( f->getshapeId() )) continue;
355
356         if ( f->NbCornerNodes() == 4 )
357           ++nbQuads;
358         else
359           nbQuads = 100;
360       }
361       if ( nbQuads == 3 )
362         cornerVV.Add( V );
363     }
364   }
365
366   //================================================================================
367   /*!
368    * \brief Return EDGEs dividing one box side
369    */
370   //================================================================================
371
372   bool getInternalEdges( SMESH_Mesh&                mesh,
373                          const TopoDS_Shape&        shape,
374                          const TopTools_MapOfShape& cornerVV,
375                          TopTools_MapOfShape&       internEE)
376   {
377     TopTools_IndexedMapOfShape subEE, subFF;
378     TopExp::MapShapes( shape, TopAbs_EDGE, subEE );
379     TopExp::MapShapes( shape, TopAbs_FACE, subFF );
380
381     TopoDS_Vertex VV[2];
382     TopTools_MapOfShape subChecked;
383     TopTools_MapIteratorOfMapOfShape vIt( cornerVV );
384     for ( ; vIt.More(); vIt.Next() )
385     {
386       TopoDS_Shape V0 = vIt.Key();
387       PShapeIteratorPtr riIt = SMESH_MesherHelper::GetAncestors( V0, mesh, TopAbs_EDGE );
388       while ( const TopoDS_Shape* riE = riIt->next() )
389       {
390         if ( !subEE.Contains( *riE ) || !subChecked.Add( *riE ))
391           continue;
392         TopoDS_Edge ridgeE = TopoDS::Edge( *riE );
393         while ( !ridgeE.IsNull() )
394         {
395           TopExp::Vertices( ridgeE, VV[0], VV[1] );
396           TopoDS_Shape V1 = VV[ V0.IsSame( VV[0] )];
397           if ( cornerVV.Contains( V1 ) )
398             break; // ridgeE reached a corner VERTEX
399
400           // detect internal EDGEs among those sharing V1. There can be 2, 3 or 4 EDGEs and
401           // number of internal EDGEs is N-2
402           TopoDS_Shape nextRidgeE;
403           PShapeIteratorPtr eIt = SMESH_MesherHelper::GetAncestors( V1, mesh, TopAbs_EDGE );
404           while ( const TopoDS_Shape* E = eIt->next() )
405           {
406             if ( E->IsSame( ridgeE ) || !subEE.Contains( *E ) || !subChecked.Add( *E ))
407               continue;
408             // look for FACEs sharing E and ridgeE
409             PShapeIteratorPtr fIt = SMESH_MesherHelper::GetAncestors( *E, mesh, TopAbs_FACE );
410             while ( const TopoDS_Shape* F = fIt->next() )
411             {
412               if ( !SMESH_MesherHelper::IsSubShape( ridgeE, *F ))
413                 continue;
414               if ( isContinuousMesh( ridgeE, TopoDS::Edge( *E ), TopoDS::Face( *F ), mesh ))
415               {
416                 nextRidgeE = *E;
417               }
418               else
419               {
420                 internEE.Add( *E );
421               }
422               break;
423             }
424           }
425           // look for the next ridge EDGE
426           if ( nextRidgeE.IsNull() )
427           {
428             eIt = SMESH_MesherHelper::GetAncestors( V1, mesh, TopAbs_EDGE );
429             while ( const TopoDS_Shape* E = eIt->next() )
430               if ( !ridgeE.IsSame( *E ) && !internEE.Contains( *E ) )
431               {
432                 nextRidgeE = *E;
433                 break;
434               }
435           }
436           ridgeE = TopoDS::Edge( nextRidgeE );
437           V0 = V1;
438
439           if ( ridgeE.IsNull() )
440             return false;
441         } // check EDGEs around the last VERTEX of ridgeE 
442       } // loop on ridge EDGEs around a corner VERTEX
443     } // loop on on corner VERTEXes
444
445     return true;
446   } // getInternalEdges()
447 } // namespace
448
449 //================================================================================
450 /*!
451  * \brief Tries to find 6 sides of a box
452  */
453 //================================================================================
454
455 bool StdMeshers_CompositeHexa_3D::findBoxFaces( const TopoDS_Shape&    shape,
456                                                 list< _QuadFaceGrid >& boxFaces,
457                                                 SMESH_Mesh&            mesh,
458                                                 _QuadFaceGrid * &      fBottom,
459                                                 _QuadFaceGrid * &      fTop,
460                                                 _QuadFaceGrid * &      fFront,
461                                                 _QuadFaceGrid * &      fBack,
462                                                 _QuadFaceGrid * &      fLeft,
463                                                 _QuadFaceGrid * &      fRight)
464 {
465   TopTools_MapOfShape cornerVertices;
466   getBlockCorners( mesh, shape, cornerVertices );
467   if ( cornerVertices.Extent() != 8 )
468     return error( COMPERR_BAD_INPUT_MESH, "Can't find 8 corners of a block" );
469   TopTools_MapOfShape internalEdges;
470   if ( !getInternalEdges( mesh, shape, cornerVertices, internalEdges ))
471     return error( COMPERR_BAD_INPUT_MESH, "2D mesh is not suitable for i,j,k hexa meshing" );
472
473   list< _QuadFaceGrid >::iterator boxFace;
474   TopExp_Explorer exp;
475   int nbFaces = 0;
476   for ( exp.Init( shape, TopAbs_FACE ); exp.More(); exp.Next(), ++nbFaces )
477   {
478     _QuadFaceGrid f;
479     if ( !f.Init( TopoDS::Face( exp.Current() ), mesh ))
480       return error (COMPERR_BAD_SHAPE);
481
482     _QuadFaceGrid* prevContinuous = 0;
483     for ( boxFace = boxFaces.begin(); boxFace != boxFaces.end(); ++boxFace )
484     {
485       if ( prevContinuous )
486       {
487         if ( prevContinuous->AddContinuousFace( *boxFace, internalEdges ))
488           boxFace = --boxFaces.erase( boxFace );
489       }
490       else if ( boxFace->AddContinuousFace( f, internalEdges ))
491       {
492         prevContinuous = & (*boxFace);
493       }
494     }
495     if ( !prevContinuous )
496       boxFaces.push_back( f );
497   }
498   // Check what we have
499   if ( boxFaces.size() != 6 && nbFaces != 6)
500     return error
501       (COMPERR_BAD_SHAPE,
502        SMESH_Comment("Can't find 6 sides of a box. Number of found sides - ")<<boxFaces.size());
503
504   if ( boxFaces.size() != 6 && nbFaces == 6 ) { // strange ordinary box with continuous faces
505     boxFaces.resize( 6 );
506     boxFace = boxFaces.begin();
507     for ( exp.Init( shape, TopAbs_FACE); exp.More(); exp.Next(), ++boxFace )
508       boxFace->Init( TopoDS::Face( exp.Current() ), mesh );
509   }
510   // ----------------------------------------
511   // Find out position of faces within a box
512   // ----------------------------------------
513   // start from a bottom face
514   fBottom = &boxFaces.front();
515   fBottom->SetID( B_BOTTOM );
516   // find vertical faces
517   fFront = fBottom->FindAdjacentForSide( Q_BOTTOM, boxFaces, B_FRONT );
518   fLeft  = fBottom->FindAdjacentForSide( Q_RIGHT,  boxFaces, B_LEFT  );
519   fBack  = fBottom->FindAdjacentForSide( Q_TOP,    boxFaces, B_BACK  );
520   fRight = fBottom->FindAdjacentForSide( Q_LEFT,   boxFaces, B_RIGHT );
521   // check the found
522   if ( !fFront || !fBack || !fLeft || !fRight )
523     return error(COMPERR_BAD_SHAPE);
524   // find a top face
525   fTop = 0;
526   for ( boxFace = ++boxFaces.begin(); boxFace != boxFaces.end() && !fTop; ++boxFace )
527   {
528     fTop = & (*boxFace);
529     fTop->SetID( B_TOP );
530     if ( fTop==fFront || fTop==fLeft || fTop==fBack || fTop==fRight )
531       fTop = 0;
532   }
533   // set bottom of the top side
534   if ( !fTop->SetBottomSide( fFront->GetSide( Q_TOP ) )) {
535     if ( !fFront->IsComplex() )
536       return error( ERR_LI("Error in StdMeshers_CompositeHexa_3D::Compute()"));
537     else {
538       _QuadFaceGrid::TChildIterator chIt = fFront->GetChildren();
539       while ( chIt.more() ) {
540         const _QuadFaceGrid& frontChild = chIt.next();
541         if ( fTop->SetBottomSide( frontChild.GetSide( Q_TOP )))
542           break;
543       }
544     }
545   }
546   if ( !fTop )
547     return error(COMPERR_BAD_SHAPE);
548
549   // orient bottom egde of faces along axes of the unit box
550   fBottom->ReverseEdges();
551   fBack  ->ReverseEdges();
552   fLeft  ->ReverseEdges();
553
554   return true;
555 }
556
557 //================================================================================
558 /*!
559  * \brief Computes hexahedral mesh on a box with composite sides
560  *  \param aMesh - mesh to compute
561  *  \param aShape - shape to mesh
562  *  \retval bool - succes sign
563  */
564 //================================================================================
565
566 bool StdMeshers_CompositeHexa_3D::Compute(SMESH_Mesh&         theMesh,
567                                           const TopoDS_Shape& theShape)
568 {
569   SMESH_MesherHelper helper( theMesh );
570   _quadraticMesh = helper.IsQuadraticSubMesh( theShape );
571   helper.SetElementsOnShape( true );
572
573   // -------------------------
574   // Try to find 6 side faces
575   // -------------------------
576   list< _QuadFaceGrid > boxFaceContainer;
577   _QuadFaceGrid *fBottom, *fTop, *fFront, *fBack, *fLeft, *fRight;
578   if ( ! findBoxFaces( theShape, boxFaceContainer, theMesh,
579                        fBottom, fTop, fFront, fBack, fLeft, fRight))
580     return false;
581
582   // ------------------------------------------
583   // Fill columns of nodes with existing nodes
584   // ------------------------------------------
585
586   // let faces load their grids
587   if ( !fBottom->LoadGrid( theMesh )) return error( fBottom->GetError() );
588   if ( !fBack  ->LoadGrid( theMesh )) return error( fBack  ->GetError() );
589   if ( !fLeft  ->LoadGrid( theMesh )) return error( fLeft  ->GetError() );
590   if ( !fFront ->LoadGrid( theMesh )) return error( fFront ->GetError() );
591   if ( !fRight ->LoadGrid( theMesh )) return error( fRight ->GetError() );
592   if ( !fTop   ->LoadGrid( theMesh )) return error( fTop   ->GetError() );
593
594   int x, xSize = fBottom->GetNbHoriSegments(theMesh) + 1, X = xSize - 1;
595   int y, ySize = fBottom->GetNbVertSegments(theMesh) + 1, Y = ySize - 1;
596   int z, zSize = fFront ->GetNbVertSegments(theMesh) + 1, Z = zSize - 1;
597   _Indexer colIndex( xSize, ySize );
598   vector< vector< const SMDS_MeshNode* > > columns( colIndex.size() );
599
600   // fill node columns by front and back box sides
601   for ( x = 0; x < xSize; ++x ) {
602     vector< const SMDS_MeshNode* >& column0 = columns[ colIndex( x, 0 )];
603     vector< const SMDS_MeshNode* >& column1 = columns[ colIndex( x, Y )];
604     column0.resize( zSize );
605     column1.resize( zSize );
606     for ( z = 0; z < zSize; ++z ) {
607       column0[ z ] = fFront->GetNode( x, z );
608       column1[ z ] = fBack ->GetNode( x, z );
609     }
610   }
611   // fill node columns by left and right box sides
612   for ( y = 1; y < ySize-1; ++y ) {
613     vector< const SMDS_MeshNode* >& column0 = columns[ colIndex( 0, y )];
614     vector< const SMDS_MeshNode* >& column1 = columns[ colIndex( X, y )];
615     column0.resize( zSize );
616     column1.resize( zSize );
617     for ( z = 0; z < zSize; ++z ) {
618       column0[ z ] = fLeft ->GetNode( y, z );
619       column1[ z ] = fRight->GetNode( y, z );
620     }
621   }
622   // get nodes from top and bottom box sides
623   for ( x = 1; x < xSize-1; ++x ) {
624     for ( y = 1; y < ySize-1; ++y ) {
625       vector< const SMDS_MeshNode* >& column = columns[ colIndex( x, y )];
626       column.resize( zSize );
627       column.front() = fBottom->GetNode( x, y );
628       column.back()  = fTop   ->GetNode( x, y );
629     }
630   }
631
632   // ----------------------------
633   // Add internal nodes of a box
634   // ----------------------------
635   // projection points of internal nodes on box sub-shapes by which
636   // coordinates of internal nodes are computed
637   vector<gp_XYZ> pointsOnShapes( SMESH_Block::ID_Shell );
638
639   // projections on vertices are constant
640   pointsOnShapes[ SMESH_Block::ID_V000 ] = fBottom->GetXYZ( 0, 0 );
641   pointsOnShapes[ SMESH_Block::ID_V100 ] = fBottom->GetXYZ( X, 0 );
642   pointsOnShapes[ SMESH_Block::ID_V010 ] = fBottom->GetXYZ( 0, Y );
643   pointsOnShapes[ SMESH_Block::ID_V110 ] = fBottom->GetXYZ( X, Y );
644   pointsOnShapes[ SMESH_Block::ID_V001 ] = fTop->GetXYZ( 0, 0 );
645   pointsOnShapes[ SMESH_Block::ID_V101 ] = fTop->GetXYZ( X, 0 );
646   pointsOnShapes[ SMESH_Block::ID_V011 ] = fTop->GetXYZ( 0, Y );
647   pointsOnShapes[ SMESH_Block::ID_V111 ] = fTop->GetXYZ( X, Y );
648
649   for ( x = 1; x < xSize-1; ++x )
650   {
651     gp_XYZ params; // normalized parameters of internal node within a unit box
652     params.SetCoord( 1, x / double(X) );
653     for ( y = 1; y < ySize-1; ++y )
654     {
655       params.SetCoord( 2, y / double(Y) );
656       // column to fill during z loop
657       vector< const SMDS_MeshNode* >& column = columns[ colIndex( x, y )];
658       // points projections on horizontal edges
659       pointsOnShapes[ SMESH_Block::ID_Ex00 ] = fBottom->GetXYZ( x, 0 );
660       pointsOnShapes[ SMESH_Block::ID_Ex10 ] = fBottom->GetXYZ( x, Y );
661       pointsOnShapes[ SMESH_Block::ID_E0y0 ] = fBottom->GetXYZ( 0, y );
662       pointsOnShapes[ SMESH_Block::ID_E1y0 ] = fBottom->GetXYZ( X, y );
663       pointsOnShapes[ SMESH_Block::ID_Ex01 ] = fTop->GetXYZ( x, 0 );
664       pointsOnShapes[ SMESH_Block::ID_Ex11 ] = fTop->GetXYZ( x, Y );
665       pointsOnShapes[ SMESH_Block::ID_E0y1 ] = fTop->GetXYZ( 0, y );
666       pointsOnShapes[ SMESH_Block::ID_E1y1 ] = fTop->GetXYZ( X, y );
667       // points projections on horizontal faces
668       pointsOnShapes[ SMESH_Block::ID_Fxy0 ] = fBottom->GetXYZ( x, y );
669       pointsOnShapes[ SMESH_Block::ID_Fxy1 ] = fTop   ->GetXYZ( x, y );
670       for ( z = 1; z < zSize-1; ++z ) // z loop
671       {
672         params.SetCoord( 3, z / double(Z) );
673         // point projections on vertical edges
674         pointsOnShapes[ SMESH_Block::ID_E00z ] = fFront->GetXYZ( 0, z );    
675         pointsOnShapes[ SMESH_Block::ID_E10z ] = fFront->GetXYZ( X, z );    
676         pointsOnShapes[ SMESH_Block::ID_E01z ] = fBack->GetXYZ( 0, z );    
677         pointsOnShapes[ SMESH_Block::ID_E11z ] = fBack->GetXYZ( X, z );
678         // point projections on vertical faces
679         pointsOnShapes[ SMESH_Block::ID_Fx0z ] = fFront->GetXYZ( x, z );    
680         pointsOnShapes[ SMESH_Block::ID_Fx1z ] = fBack ->GetXYZ( x, z );    
681         pointsOnShapes[ SMESH_Block::ID_F0yz ] = fLeft ->GetXYZ( y, z );    
682         pointsOnShapes[ SMESH_Block::ID_F1yz ] = fRight->GetXYZ( y, z );
683
684         // compute internal node coordinates
685         gp_XYZ coords;
686         SMESH_Block::ShellPoint( params, pointsOnShapes, coords );
687         column[ z ] = helper.AddNode( coords.X(), coords.Y(), coords.Z() );
688
689 #ifdef DEB_GRID
690         // debug
691         //cout << "----------------------------------------------------------------------"<<endl;
692         //for ( int id = SMESH_Block::ID_V000; id < SMESH_Block::ID_Shell; ++id)
693         //{
694         //  gp_XYZ p = pointsOnShapes[ id ];
695         //  SMESH_Block::DumpShapeID( id,cout)<<" ( "<<p.X()<<", "<<p.Y()<<", "<<p.Z()<<" )"<<endl;
696         //}
697         //cout << "Params: ( "<< params.X()<<", "<<params.Y()<<", "<<params.Z()<<" )"<<endl;
698         //cout << "coords: ( "<< coords.X()<<", "<<coords.Y()<<", "<<coords.Z()<<" )"<<endl;
699 #endif
700       }
701     }
702   }
703   // faces no more needed, free memory
704   boxFaceContainer.clear();
705
706   // ----------------
707   // Add hexahedrons
708   // ----------------
709   for ( x = 0; x < xSize-1; ++x ) {
710     for ( y = 0; y < ySize-1; ++y ) {
711       vector< const SMDS_MeshNode* >& col00 = columns[ colIndex( x, y )];
712       vector< const SMDS_MeshNode* >& col10 = columns[ colIndex( x+1, y )];
713       vector< const SMDS_MeshNode* >& col01 = columns[ colIndex( x, y+1 )];
714       vector< const SMDS_MeshNode* >& col11 = columns[ colIndex( x+1, y+1 )];
715       for ( z = 0; z < zSize-1; ++z )
716       {
717         // bottom face normal of a hexa mush point outside the volume
718         helper.AddVolume(col00[z],   col01[z],   col11[z],   col10[z],
719                          col00[z+1], col01[z+1], col11[z+1], col10[z+1]);
720       }
721     }
722   }
723   return true;
724 }
725
726 //================================================================================
727 /*!
728  *  Evaluate
729  */
730 //================================================================================
731
732 bool StdMeshers_CompositeHexa_3D::Evaluate(SMESH_Mesh&         theMesh,
733                                            const TopoDS_Shape& theShape,
734                                            MapShapeNbElems&    aResMap)
735 {
736   // -------------------------
737   // Try to find 6 side faces
738   // -------------------------
739   list< _QuadFaceGrid > boxFaceContainer;
740   _QuadFaceGrid *fBottom, *fTop, *fFront, *fBack, *fLeft, *fRight;
741   if ( ! findBoxFaces( theShape, boxFaceContainer, theMesh,
742                        fBottom, fTop, fFront, fBack, fLeft, fRight))
743     return false;
744
745   // Find a less complex side
746   _QuadFaceGrid * lessComplexSide = & boxFaceContainer.front();
747   list< _QuadFaceGrid >::iterator face = boxFaceContainer.begin();
748   for ( ++face; face != boxFaceContainer.end() && lessComplexSide->IsComplex(); ++face )
749     if ( face->NbChildren() < lessComplexSide->NbChildren() )
750       lessComplexSide = & *face;
751
752   // Get an 1D size of lessComplexSide
753   int nbSeg1 = 0;
754   vector<TopoDS_Edge> edges;
755   if ( !lessComplexSide->GetHoriEdges(edges) )
756     return false;
757   for ( size_t i = 0; i < edges.size(); ++i )
758   {
759     const vector<int>& nbElems = aResMap[ theMesh.GetSubMesh( edges[i] )];
760     if ( !nbElems.empty() )
761       nbSeg1 += Max( nbElems[ SMDSEntity_Edge ], nbElems[ SMDSEntity_Quad_Edge ]);
762   }
763
764   // Get an 1D size of a box side ortogonal to lessComplexSide
765   int nbSeg2 = 0;
766   _QuadFaceGrid* ortoSide =
767     lessComplexSide->FindAdjacentForSide( Q_LEFT, boxFaceContainer, B_UNDEFINED );
768   edges.clear();
769   if ( !ortoSide || !ortoSide->GetHoriEdges(edges) ) return false;
770   for ( size_t i = 0; i < edges.size(); ++i )
771   {
772     const vector<int>& nbElems = aResMap[ theMesh.GetSubMesh( edges[i] )];
773     if ( !nbElems.empty() )
774       nbSeg2 += Max( nbElems[ SMDSEntity_Edge ], nbElems[ SMDSEntity_Quad_Edge ]);
775   }
776
777   // Get an 2D size of a box side ortogonal to lessComplexSide
778   int nbFaces = 0, nbQuadFace = 0;
779   list< TopoDS_Face > sideFaces;
780   if ( ortoSide->IsComplex() )
781     for ( _QuadFaceGrid::TChildIterator child = ortoSide->GetChildren(); child.more(); )
782       sideFaces.push_back( child.next().GetFace() );
783   else
784     sideFaces.push_back( ortoSide->GetFace() );
785   //
786   list< TopoDS_Face >::iterator f = sideFaces.begin();
787   for ( ; f != sideFaces.end(); ++f )
788   {
789     const vector<int>& nbElems = aResMap[ theMesh.GetSubMesh( *f )];
790     if ( !nbElems.empty() )
791     {
792       nbFaces    = nbElems[ SMDSEntity_Quadrangle ];
793       nbQuadFace = nbElems[ SMDSEntity_Quad_Quadrangle ];
794     }
795   }
796
797   // Fill nb of elements
798   vector<int> aResVec(SMDSEntity_Last,0);
799   int nbSeg3 = ( nbFaces + nbQuadFace ) / nbSeg2;
800   aResVec[SMDSEntity_Node]       = (nbSeg1-1) * (nbSeg2-1) * (nbSeg3-1);
801   aResVec[SMDSEntity_Hexa]       = nbSeg1 * nbFaces;
802   aResVec[SMDSEntity_Quad_Hexa]  = nbSeg1 * nbQuadFace;
803
804   aResMap.insert( make_pair( theMesh.GetSubMesh(theShape), aResVec ));
805
806   return true;
807 }
808
809
810 //================================================================================
811 /*!
812  * \brief constructor of non-initialized _QuadFaceGrid
813  */
814 //================================================================================
815
816 _QuadFaceGrid::_QuadFaceGrid():
817   myReverse(false), myRightBrother(0), myUpBrother(0), myIndexer(0,0), myID(B_UNDEFINED)
818 {
819 }
820
821 //================================================================================
822 /*!
823  * \brief Initialization
824  */
825 //================================================================================
826
827 bool _QuadFaceGrid::Init(const TopoDS_Face& f, SMESH_Mesh& mesh)
828 {
829   myFace         = f;
830   mySides        = _FaceSide();
831   myReverse      = false;
832   myLeftBottomChild = myRightBrother = myUpBrother = 0;
833   myChildren.clear();
834   myGrid.clear();
835   //if ( myFace.Orientation() != TopAbs_FORWARD )
836     //myFace.Reverse();
837
838   list< TopoDS_Edge > edges;
839   list< int > nbEdgesInWire;
840   int nbWire = SMESH_Block::GetOrderedEdges (myFace, edges, nbEdgesInWire);
841   if ( nbWire != 1 )
842     return false;
843
844   list< TopoDS_Edge >::iterator edgeIt = edges.begin();
845   if ( nbEdgesInWire.front() == 4 ) // exactly 4 edges
846   {
847     for ( ; edgeIt != edges.end(); ++edgeIt )
848       mySides.AppendSide( _FaceSide( *edgeIt ));
849   }
850   else if ( nbEdgesInWire.front() > 4 ) { // more than 4 edges - try to unite some
851     list< TopoDS_Edge > sideEdges;
852     while ( !edges.empty()) {
853       sideEdges.clear();
854       sideEdges.splice( sideEdges.end(), edges, edges.begin());// edges.front()->sideEdges.back()
855       while ( !edges.empty() ) {
856         if ( SMESH_Algo::IsContinuous( sideEdges.back(), edges.front() )) {
857           sideEdges.splice( sideEdges.end(), edges, edges.begin());
858         }
859         else if ( SMESH_Algo::IsContinuous( sideEdges.front(), edges.back() )) {
860           sideEdges.splice( sideEdges.begin(), edges, --edges.end());
861         }
862         else if ( isContinuousMesh( sideEdges.back(), edges.front(), f, mesh )) {
863           sideEdges.splice( sideEdges.end(), edges, edges.begin());
864         }
865         else if ( isContinuousMesh( sideEdges.front(), edges.back(), f, mesh )) {
866           sideEdges.splice( sideEdges.begin(), edges, --edges.end());
867         }
868         else {
869           break;
870         }
871       }
872       mySides.AppendSide( _FaceSide( sideEdges ));
873     }
874   }
875   if (mySides.size() != 4)
876     return false;
877
878 #ifdef _DEBUG_
879   mySides.GetSide( Q_BOTTOM )->SetID( Q_BOTTOM );
880   mySides.GetSide( Q_RIGHT  )->SetID( Q_RIGHT );
881   mySides.GetSide( Q_TOP    )->SetID( Q_TOP );
882   mySides.GetSide( Q_LEFT   )->SetID( Q_LEFT );
883 #endif
884
885   return true;
886 }
887
888 //================================================================================
889 /*!
890  * \brief Try to unite self with other ordinary face
891  */
892 //================================================================================
893
894 bool _QuadFaceGrid::AddContinuousFace( const _QuadFaceGrid&       other,
895                                        const TopTools_MapOfShape& internalEdges)
896 {
897   for ( int i = 0; i < 4; ++i )
898   {
899     const _FaceSide& otherSide = other.GetSide( i );
900     int iMyCommon;
901     if ( mySides.Contain( otherSide, &iMyCommon ) )
902     {
903       if ( internalEdges.Contains( otherSide.Edge( 0 )))
904       {
905         DUMP_VERT("Cont 1", mySides.GetSide(iMyCommon)->FirstVertex());
906         DUMP_VERT("Cont 2", mySides.GetSide(iMyCommon)->LastVertex());
907         DUMP_VERT("Cont 3", otherSide.FirstVertex());
908         DUMP_VERT("Cont 4", otherSide.LastVertex());
909         if ( myChildren.empty() ) {
910           myChildren.push_back( *this );
911           myFace.Nullify();
912         }
913
914         // orient new children equally
915         int otherBottomIndex = ( 4 + i - iMyCommon + 2 ) % 4;
916         if ( other.IsComplex() )
917           for ( TChildIterator children = other.GetChildren(); children.more(); ) {
918             myChildren.push_back( children.next() );
919             myChildren.back().SetBottomSide( myChildren.back().GetSide( otherBottomIndex ));
920           }
921         else {
922           myChildren.push_back( other );
923           myChildren.back().SetBottomSide( myChildren.back().GetSide( otherBottomIndex ));
924         }
925
926         myLeftBottomChild = 0;
927
928         // collect vertices in mySides
929         if ( other.IsComplex() )
930           for ( TChildIterator children = other.GetChildren(); children.more(); )
931           {
932             const _QuadFaceGrid& child =  children.next();
933             for ( int i = 0; i < 4; ++i )
934               mySides.AppendSide( child.GetSide(i) );
935           }
936         else
937           for ( int i = 0; i < 4; ++i )
938             mySides.AppendSide( other.GetSide(i) );
939
940         return true;
941       }
942     }
943   }
944   return false;
945 }
946
947 //================================================================================
948 /*!
949  * \brief Try to set the side as bottom hirizontal side
950  */
951 //================================================================================
952
953 bool _QuadFaceGrid::SetBottomSide(const _FaceSide& bottom, int* sideIndex)
954 {
955   myLeftBottomChild = myRightBrother = myUpBrother = 0;
956
957   int myBottomIndex;
958   if ( myChildren.empty() )
959   {
960     if ( mySides.Contain( bottom, &myBottomIndex )) {
961       mySides.SetBottomSide( myBottomIndex );
962       if ( sideIndex )
963         *sideIndex = myBottomIndex;
964       return true;
965     }
966   }
967   else
968   {
969     TChildren::iterator childFace = myChildren.begin(), childEnd = myChildren.end();
970     for ( ; childFace != childEnd; ++childFace )
971     {
972       if ( childFace->SetBottomSide( bottom, &myBottomIndex ))
973       {
974         TChildren::iterator orientedCild = childFace;
975         for ( childFace = myChildren.begin(); childFace != childEnd; ++childFace ) {
976           if ( childFace != orientedCild )
977             childFace->SetBottomSide( childFace->GetSide( myBottomIndex ));
978         }
979         if ( sideIndex )
980           *sideIndex = myBottomIndex;
981         return true;
982       }
983     }
984   }
985   return false;
986 }
987
988 //================================================================================
989 /*!
990  * \brief Return face adjacent to i-th side of this face, (0<i<4)
991  */
992 //================================================================================
993
994 _QuadFaceGrid* _QuadFaceGrid::FindAdjacentForSide(int                  i,
995                                                   list<_QuadFaceGrid>& faces,
996                                                   EBoxSides            id) const
997 {
998   const _FaceSide & iSide = GetSide( i );
999   list< _QuadFaceGrid >::iterator boxFace = faces.begin();
1000   for ( ; boxFace != faces.end(); ++boxFace )
1001   {
1002     _QuadFaceGrid* f  = & (*boxFace);
1003     if ( f != this && f->SetBottomSide( iSide ))
1004       return f->SetID( id ), f;
1005   }
1006   return (_QuadFaceGrid*) 0;
1007 }
1008
1009 //================================================================================
1010 /*!
1011  * \brief Return i-th side
1012  */
1013 //================================================================================
1014
1015 const _FaceSide& _QuadFaceGrid::GetSide(int i) const
1016 {
1017   if ( myChildren.empty() )
1018     return *mySides.GetSide(i);
1019
1020   _QuadFaceGrid* me = const_cast<_QuadFaceGrid*>(this);
1021   if ( !me->locateChildren() || !myLeftBottomChild )
1022     return *mySides.GetSide(i);
1023
1024   const _QuadFaceGrid* child = myLeftBottomChild;
1025   switch ( i ){
1026   case Q_BOTTOM:
1027   case Q_LEFT:
1028     break;
1029   case Q_RIGHT:
1030     while ( child->myRightBrother )
1031       child = child->myRightBrother;
1032     break;
1033   case Q_TOP:
1034     while ( child->myUpBrother )
1035       child = child->myUpBrother;
1036     break;
1037   default: ;
1038   }
1039   return child->GetSide( i );
1040 }
1041
1042 //================================================================================
1043 /*!
1044  * \brief Reverse edges in order to have them oriented along axes of the unit box
1045  */
1046 //================================================================================
1047
1048 void _QuadFaceGrid::ReverseEdges(/*int e1, int e2*/)
1049 {
1050   myReverse = !myReverse;
1051
1052 // #ifdef DEB_FACES
1053 //   if ( !myFace.IsNull() )
1054 //     TopAbs::Print(myFace.Orientation(), cout);
1055 // #endif
1056
1057   if ( myChildren.empty() )
1058   {
1059 //     mySides.GetSide( e1 )->Reverse();
1060 //     mySides.GetSide( e2 )->Reverse();
1061     DumpVertices();
1062   }
1063   else
1064   {
1065     DumpVertices();
1066     TChildren::iterator child = myChildren.begin(), childEnd = myChildren.end();
1067     for ( ; child != childEnd; ++child )
1068       child->ReverseEdges( /*e1, e2*/ );
1069   }
1070 }
1071
1072 //================================================================================
1073 /*!
1074  * \brief Load nodes of a mesh
1075  */
1076 //================================================================================
1077
1078 bool _QuadFaceGrid::LoadGrid( SMESH_Mesh& mesh )
1079 {
1080   if ( !myChildren.empty() )
1081   {
1082     // Let child faces load their grids
1083     TChildren::iterator child = myChildren.begin(), childEnd = myChildren.end();
1084     for ( ; child != childEnd; ++child ) {
1085       child->SetID( myID );
1086       if ( !child->LoadGrid( mesh ) )
1087         return error( child->GetError() );
1088     }
1089     // Fill myGrid with nodes of patches
1090     return loadCompositeGrid( mesh );
1091   }
1092
1093   // ---------------------------------------
1094   // Fill myGrid with nodes bound to myFace
1095   // ---------------------------------------
1096
1097   if ( !myGrid.empty() )
1098     return true;
1099
1100   SMESHDS_SubMesh* faceSubMesh = mesh.GetSubMesh( myFace )->GetSubMeshDS();
1101   // check that all faces are quadrangular
1102   SMDS_ElemIteratorPtr fIt = faceSubMesh->GetElements();
1103   while ( fIt->more() )
1104     if ( fIt->next()->NbNodes() % 4 > 0 )
1105       return error("Non-quadrangular mesh faces are not allowed on sides of a composite block");
1106   
1107   myIndexer._xSize = 1 + mySides.GetSide( Q_BOTTOM )->GetNbSegments( mesh );
1108   myIndexer._ySize = 1 + mySides.GetSide( Q_LEFT   )->GetNbSegments( mesh );
1109
1110   myGrid.resize( myIndexer.size() );
1111
1112   // strore nodes bound to the bottom edge
1113   mySides.GetSide( Q_BOTTOM )->StoreNodes( mesh, myGrid, myReverse );
1114
1115   // store the rest nodes row by row
1116
1117   const SMDS_MeshNode* dummy = mesh.GetMeshDS()->AddNode(0,0,0);
1118   const SMDS_MeshElement* firstQuad = dummy; // most left face above the last row of found nodes
1119   
1120   int nbFoundNodes = myIndexer._xSize;
1121   while ( nbFoundNodes != myGrid.size() )
1122   {
1123     // first and last nodes of the last filled row of nodes
1124     const SMDS_MeshNode* n1down = myGrid[ nbFoundNodes - myIndexer._xSize ];
1125     const SMDS_MeshNode* n2down = myGrid[ nbFoundNodes - myIndexer._xSize + 1];
1126     const SMDS_MeshNode* n1downLast = myGrid[ nbFoundNodes-1 ];
1127
1128     // find the first face above the row by the first two left nodes
1129     //
1130     // n1up     n2up
1131     //     o---o
1132     //     |   |
1133     //     o---o  o  o  o  o
1134     //n1down    n2down
1135     //
1136     TIDSortedElemSet emptySet, avoidSet;
1137     avoidSet.insert( firstQuad );
1138     firstQuad = SMESH_MeshAlgos::FindFaceInSet( n1down, n2down, emptySet, avoidSet);
1139     while ( firstQuad && !faceSubMesh->Contains( firstQuad )) {
1140       avoidSet.insert( firstQuad );
1141       firstQuad = SMESH_MeshAlgos::FindFaceInSet( n1down, n2down, emptySet, avoidSet);
1142     }
1143     if ( !firstQuad || !faceSubMesh->Contains( firstQuad ))
1144       return error(ERR_LI("Error in _QuadFaceGrid::LoadGrid()"));
1145
1146     // find the node of quad bound to the left geom edge
1147     int i2down = firstQuad->GetNodeIndex( n2down );
1148     const SMDS_MeshNode* n1up = firstQuad->GetNode(( i2down+2 ) % 4 );
1149     myGrid[ nbFoundNodes++ ] = n1up;
1150     // the 4-the node of the first quad
1151     int i1down = firstQuad->GetNodeIndex( n1down );
1152     const SMDS_MeshNode* n2up = firstQuad->GetNode(( i1down+2 ) % 4 );
1153     myGrid[ nbFoundNodes++ ] = n2up;
1154
1155     n1down = n2down;
1156     n1up   = n2up;
1157     const SMDS_MeshElement* quad = firstQuad;
1158
1159     // find the rest nodes by remaining faces above the row
1160     //
1161     //             n1up
1162     //     o---o--o
1163     //     |   |  | ->
1164     //     o---o--o  o  o  o
1165     //                      n1downLast
1166     //
1167     while ( n1down != n1downLast )
1168     {
1169       // next face
1170       avoidSet.clear(); avoidSet.insert( quad );
1171       quad = SMESH_MeshAlgos::FindFaceInSet( n1down, n1up, emptySet, avoidSet );
1172       if ( !quad || quad->NbNodes() % 4 > 0)
1173         return error(ERR_LI("Error in _QuadFaceGrid::LoadGrid()"));
1174
1175       // next node
1176       if ( quad->GetNode( i1down ) != n1down ) // check already found index
1177         i1down = quad->GetNodeIndex( n1down );
1178       n2up = quad->GetNode(( i1down+2 ) % 4 );
1179       myGrid[ nbFoundNodes++ ] = n2up;
1180
1181       n1down = myGrid[ nbFoundNodes - myIndexer._xSize - 1 ];
1182       n1up   = n2up;
1183     }
1184   }
1185   mesh.GetMeshDS()->RemoveNode(dummy);
1186   DumpGrid(); // debug
1187
1188   return true;
1189 }
1190
1191 //================================================================================
1192 /*!
1193  * \brief Find out mutual location of children: find their right and up brothers
1194  */
1195 //================================================================================
1196
1197 bool _QuadFaceGrid::locateChildren()
1198 {
1199   if ( myLeftBottomChild )
1200     return true;
1201
1202   TChildren::iterator child = myChildren.begin(), childEnd = myChildren.end();
1203
1204   // find a child sharing it's first bottom vertex with no other brother
1205   myLeftBottomChild = 0;
1206   for ( ; !myLeftBottomChild && child != childEnd; ++child )
1207   {
1208     TopoDS_Vertex leftVertex = child->GetSide( Q_BOTTOM ).FirstVertex();
1209     bool sharedVertex = false;
1210     TChildren::iterator otherChild = myChildren.begin();
1211     for ( ; otherChild != childEnd && !sharedVertex; ++otherChild )
1212       if ( otherChild != child )
1213         sharedVertex = otherChild->mySides.Contain( leftVertex );
1214     if ( !sharedVertex ) {
1215       myLeftBottomChild = & (*child);
1216       DUMP_VERT("0 left bottom Vertex: ",leftVertex );
1217     }
1218   }
1219   if (!myLeftBottomChild)
1220     return error(ERR_LI("Error in locateChildren()"));
1221
1222   set< _QuadFaceGrid* > notLocatedChilren;
1223   for (child = myChildren.begin() ; child != childEnd; ++child )
1224     notLocatedChilren.insert( & (*child));
1225
1226   // connect myLeftBottomChild to it's right and upper brothers
1227   notLocatedChilren.erase( myLeftBottomChild );
1228   myLeftBottomChild->setBrothers( notLocatedChilren );
1229   if ( !notLocatedChilren.empty() )
1230     return error(ERR_LI("Error in locateChildren()"));
1231
1232   return true;
1233 }
1234
1235 //================================================================================
1236 /*!
1237  * \brief Fill myGrid with nodes of patches
1238  */
1239 //================================================================================
1240
1241 bool _QuadFaceGrid::loadCompositeGrid(SMESH_Mesh& mesh)
1242 {
1243   // Find out mutual location of children: find their right and up brothers
1244   if ( !locateChildren() )
1245     return false;
1246
1247   // Load nodes according to mutual location of children
1248
1249   // grid size
1250   myIndexer._xSize = 1 + myLeftBottomChild->GetNbHoriSegments(mesh, /*withBrothers=*/true);
1251   myIndexer._ySize = 1 + myLeftBottomChild->GetNbVertSegments(mesh, /*withBrothers=*/true);
1252
1253   myGrid.resize( myIndexer.size() );
1254
1255   int fromX = myReverse ? myIndexer._xSize : 0;
1256   if (!myLeftBottomChild->fillGrid( mesh, myGrid, myIndexer, fromX, 0 ))
1257     return error( myLeftBottomChild->GetError() );
1258
1259   DumpGrid();
1260
1261   return true;
1262 }
1263
1264 //================================================================================
1265 /*!
1266  * \brief Find right an upper brothers among notLocatedBrothers
1267  */
1268 //================================================================================
1269
1270 void _QuadFaceGrid::setBrothers( set< _QuadFaceGrid* >& notLocatedBrothers )
1271 {
1272   if ( !notLocatedBrothers.empty() )
1273   {
1274     // find right brother
1275     TopoDS_Vertex rightVertex = GetSide( Q_BOTTOM ).LastVertex();
1276     DUMP_VERT("1 right bottom Vertex: ",rightVertex );
1277     set< _QuadFaceGrid* >::iterator brIt, brEnd = notLocatedBrothers.end();
1278     for ( brIt = notLocatedBrothers.begin(); brIt != brEnd; ++brIt )
1279     {
1280       _QuadFaceGrid* brother = *brIt;
1281       TopoDS_Vertex brotherLeftVertex = brother->GetSide( Q_BOTTOM ).FirstVertex();
1282       DUMP_VERT( "brother left bottom: ", brotherLeftVertex );
1283       if ( rightVertex.IsSame( brotherLeftVertex )) {
1284         myRightBrother = brother;
1285         notLocatedBrothers.erase( brIt );
1286         break;
1287       }
1288     }
1289     // find upper brother
1290     TopoDS_Vertex upVertex = GetSide( Q_LEFT ).FirstVertex();
1291     DUMP_VERT("1 left up Vertex: ",upVertex);
1292     brIt = notLocatedBrothers.begin(), brEnd = notLocatedBrothers.end();
1293     for ( ; brIt != brEnd; ++brIt )
1294     {
1295       _QuadFaceGrid* brother = *brIt;
1296       TopoDS_Vertex brotherLeftVertex = brother->GetSide( Q_BOTTOM ).FirstVertex();
1297       DUMP_VERT("brother left bottom: ", brotherLeftVertex);
1298       if ( upVertex.IsSame( brotherLeftVertex )) {
1299         myUpBrother = brother;
1300         notLocatedBrothers.erase( myUpBrother );
1301         break;
1302       }
1303     }
1304     // recursive call
1305     if ( myRightBrother )
1306       myRightBrother->setBrothers( notLocatedBrothers );
1307     if ( myUpBrother )
1308       myUpBrother->setBrothers( notLocatedBrothers );
1309   }
1310 }
1311
1312 //================================================================================
1313 /*!
1314  * \brief Store nodes of a simple face into grid starting from (x,y) position
1315  */
1316 //================================================================================
1317
1318 bool _QuadFaceGrid::fillGrid(SMESH_Mesh&                    theMesh,
1319                              vector<const SMDS_MeshNode*> & theGrid,
1320                              const _Indexer&                theIndexer,
1321                              int                            theX,
1322                              int                            theY)
1323 {
1324   if ( myGrid.empty() && !LoadGrid( theMesh ))
1325     return false;
1326
1327   // store my own grid in the global grid
1328
1329   int fromX = myReverse ? theX - myIndexer._xSize: theX;
1330
1331   for ( int i = 0, x = fromX; i < myIndexer._xSize; ++i, ++x )
1332     for ( int j = 0, y = theY; j < myIndexer._ySize; ++j, ++y )
1333       theGrid[ theIndexer( x, y )] = myGrid[ myIndexer( i, j )];
1334
1335   // store grids of my right and upper brothers
1336
1337   if ( myRightBrother )
1338   {
1339     if ( myReverse )
1340       fromX += 1;
1341     else
1342       fromX += myIndexer._xSize - 1;
1343     if ( !myRightBrother->fillGrid( theMesh, theGrid, theIndexer, fromX, theY ))
1344       return error( myRightBrother->GetError() );
1345   }
1346   if ( myUpBrother )
1347   {
1348     if ( !myUpBrother->fillGrid( theMesh, theGrid, theIndexer,
1349                                  theX, theY + myIndexer._ySize - 1))
1350       return error( myUpBrother->GetError() );
1351   }
1352   return true;
1353 }
1354
1355 //================================================================================
1356 /*!
1357  * \brief Return number of segments on the hirizontal sides
1358  */
1359 //================================================================================
1360
1361 int _QuadFaceGrid::GetNbHoriSegments(SMESH_Mesh& mesh, bool withBrothers) const
1362 {
1363   int nbSegs = 0;
1364   if ( myLeftBottomChild )
1365   {
1366     nbSegs += myLeftBottomChild->GetNbHoriSegments( mesh, true );
1367   }
1368   else
1369   {
1370     nbSegs = mySides.GetSide( Q_BOTTOM )->GetNbSegments(mesh);
1371     if ( withBrothers && myRightBrother )
1372       nbSegs += myRightBrother->GetNbHoriSegments( mesh, withBrothers );
1373   }
1374   return nbSegs;
1375 }
1376
1377 //================================================================================
1378 /*!
1379  * \brief Return number of segments on the vertical sides
1380  */
1381 //================================================================================
1382
1383 int _QuadFaceGrid::GetNbVertSegments(SMESH_Mesh& mesh, bool withBrothers) const
1384 {
1385   int nbSegs = 0;
1386   if ( myLeftBottomChild )
1387   {
1388     nbSegs += myLeftBottomChild->GetNbVertSegments( mesh, true );
1389   }
1390   else
1391   {
1392     nbSegs = mySides.GetSide( Q_LEFT )->GetNbSegments(mesh);
1393     if ( withBrothers && myUpBrother )
1394       nbSegs += myUpBrother->GetNbVertSegments( mesh, withBrothers );
1395   }
1396   return nbSegs;
1397 }
1398
1399 //================================================================================
1400 /*!
1401  * \brief Return edge on the hirizontal bottom sides
1402  */
1403 //================================================================================
1404
1405 int _QuadFaceGrid::GetHoriEdges(vector<TopoDS_Edge> & edges) const
1406 {
1407   if ( myLeftBottomChild )
1408   {
1409     return myLeftBottomChild->GetHoriEdges( edges );
1410   }
1411   else
1412   {
1413     const _FaceSide* bottom  = mySides.GetSide( Q_BOTTOM );
1414     int i = 0;
1415     while ( true ) {
1416       TopoDS_Edge e = bottom->Edge( i++ );
1417       if ( e.IsNull() )
1418         break;
1419       else
1420         edges.push_back( e );
1421     }
1422     if ( myRightBrother )
1423       myRightBrother->GetHoriEdges( edges );
1424   }
1425   return edges.size();
1426 }
1427
1428 //================================================================================
1429 /*!
1430  * \brief Return a node by its position
1431  */
1432 //================================================================================
1433
1434 const SMDS_MeshNode* _QuadFaceGrid::GetNode(int iHori, int iVert) const
1435 {
1436   return myGrid[ myIndexer( iHori, iVert )];
1437 }
1438
1439 //================================================================================
1440 /*!
1441  * \brief Return node coordinates by its position
1442  */
1443 //================================================================================
1444
1445 gp_XYZ _QuadFaceGrid::GetXYZ(int iHori, int iVert) const
1446 {
1447   const SMDS_MeshNode* n = myGrid[ myIndexer( iHori, iVert )];
1448   return gp_XYZ( n->X(), n->Y(), n->Z() );
1449 }
1450
1451 //================================================================================
1452 /*!
1453  * \brief Return normal to the face at vertex v
1454  */
1455 //================================================================================
1456
1457 bool _QuadFaceGrid::GetNormal( const TopoDS_Vertex& v, gp_Vec& n ) const
1458 {
1459   if ( myChildren.empty() )
1460   {
1461     if ( mySides.Contain( v )) {
1462       try {
1463         gp_Pnt2d uv = BRep_Tool::Parameters( v, myFace );
1464         BRepAdaptor_Surface surface( myFace );
1465         gp_Pnt p; gp_Vec d1u, d1v;
1466         surface.D1( uv.X(), uv.Y(), p, d1u, d1v );
1467         n = d1u.Crossed( d1v );
1468         return true;
1469       }
1470       catch (Standard_Failure) {
1471         return false;
1472       }
1473     }
1474   }
1475   else
1476   {
1477     TChildren::const_iterator child = myChildren.begin(), childEnd = myChildren.end();
1478     for ( ; child != childEnd; ++child )
1479       if ( child->GetNormal( v, n ))
1480         return true;
1481   }
1482   return false;
1483 }
1484
1485 //================================================================================
1486 /*!
1487  * \brief Dumps coordinates of grid nodes
1488  */
1489 //================================================================================
1490
1491 void _QuadFaceGrid::DumpGrid() const
1492 {
1493 #ifdef DEB_GRID
1494   const char* names[] = { "B_BOTTOM", "B_RIGHT", "B_TOP", "B_LEFT", "B_FRONT", "B_BACK" };
1495   cout << "****** Face " << names[ myID ] << endl;
1496
1497   if ( myChildren.empty() || !myGrid.empty() )
1498   {
1499     cout << "x size: " << myIndexer._xSize << "; y size: " << myIndexer._ySize << endl;
1500     for ( int y = 0; y < myIndexer._ySize; ++y ) {
1501       cout << "-- row " << y << endl;
1502       for ( int x = 0; x < myIndexer._xSize; ++x ) {
1503         const SMDS_MeshNode* n = myGrid[ myIndexer( x, y ) ];
1504         cout << x << " ( " << n->X() << ", " << n->Y() << ", " << n->Z() << " )" << endl;
1505       }
1506     }
1507   }
1508   else
1509   {
1510     cout << "Nb children: " << myChildren.size() << endl;
1511     TChildren::const_iterator child = myChildren.begin(), childEnd = myChildren.end();
1512     for ( int i=0; child != childEnd; ++child, ++i ) {
1513       cout << "   *** SUBFACE " << i+1 << endl;
1514       ((_QuadFaceGrid&)(*child)).SetID( myID );
1515       child->DumpGrid();
1516     }
1517   }
1518 #endif
1519 }
1520
1521 //================================================================================
1522 /*!
1523  * \brief Dump vertices
1524  */
1525 //================================================================================
1526
1527 void _QuadFaceGrid::DumpVertices() const
1528 {
1529 #ifdef DEB_FACES
1530   cout << "****** Face ";
1531   const char* names[] = { "B_BOTTOM", "B_RIGHT", "B_TOP", "B_LEFT", "B_FRONT", "B_BACK" };
1532   if ( myID >= B_BOTTOM && myID < B_BACK )
1533     cout << names[ myID ] << endl;
1534   else
1535     cout << "UNDEFINED" << endl;
1536
1537   if ( myChildren.empty() )
1538   {
1539     for ( int i = 0; i < 4; ++i )
1540     {
1541       cout << "  Side "; mySides.GetSide( i )->Dump();
1542     }
1543   }
1544   else
1545   {
1546     cout << "-- Nb children: " << myChildren.size() << endl;
1547     TChildren::const_iterator child = myChildren.begin(), childEnd = myChildren.end();
1548     for ( int i=0; child != childEnd; ++child, ++i ) {
1549       cout << "   *** SUBFACE " << i+1 << endl;
1550       ((_QuadFaceGrid&)(*child)).SetID( myID );
1551       child->DumpVertices();
1552     }
1553   }
1554 #endif
1555 }
1556
1557 //=======================================================================
1558 //function : _FaceSide
1559 //purpose  : copy constructor
1560 //=======================================================================
1561
1562 _FaceSide::_FaceSide(const _FaceSide& other)
1563 {
1564   myEdge = other.myEdge;
1565   myChildren = other.myChildren;
1566   myNbChildren = other.myNbChildren;
1567   myVertices.Assign( other.myVertices );
1568   myID = other.myID;
1569 }
1570
1571 //================================================================================
1572 /*!
1573  * \brief Construct a face side of one edge
1574  */
1575 //================================================================================
1576
1577 _FaceSide::_FaceSide(const TopoDS_Edge& edge):
1578   myEdge( edge ), myNbChildren(0)
1579 {
1580   if ( !edge.IsNull() )
1581     for ( TopExp_Explorer exp( edge, TopAbs_VERTEX ); exp.More(); exp.Next() )
1582       //myVertices.insert( ptr ( exp.Current() ));
1583       myVertices.Add( exp.Current() );
1584 }
1585
1586 //================================================================================
1587 /*!
1588  * \brief Construct a face side of several edges
1589  */
1590 //================================================================================
1591
1592 _FaceSide::_FaceSide(const list<TopoDS_Edge>& edges):
1593   myNbChildren(0)
1594 {
1595   list<TopoDS_Edge>::const_iterator edge = edges.begin(), eEnd = edges.end();
1596   for ( ; edge != eEnd; ++edge ) {
1597     myChildren.push_back( _FaceSide( *edge ));
1598     myNbChildren++;
1599 //     myVertices.insert( myChildren.back().myVertices.begin(),
1600 //                        myChildren.back().myVertices.end() );
1601     myVertices.Add( myChildren.back().FirstVertex() );
1602     myVertices.Add( myChildren.back().LastVertex() );
1603     myChildren.back().SetID( Q_CHILD ); // not to splice them
1604   }
1605 }
1606
1607 //=======================================================================
1608 //function : GetSide
1609 //purpose  : 
1610 //=======================================================================
1611
1612 _FaceSide* _FaceSide::GetSide(const int i)
1613 {
1614   if ( i >= myNbChildren )
1615     return 0;
1616
1617   list< _FaceSide >::iterator side = myChildren.begin();
1618   if ( i )
1619     std::advance( side, i );
1620   return & (*side);
1621 }
1622
1623 //=======================================================================
1624 //function : GetSide
1625 //purpose  : 
1626 //=======================================================================
1627
1628 const _FaceSide* _FaceSide::GetSide(const int i) const
1629 {
1630   return const_cast< _FaceSide* >(this)->GetSide(i);
1631 }
1632
1633 //=======================================================================
1634 //function : NbVertices
1635 //purpose  : return nb of vertices in the side
1636 //=======================================================================
1637
1638 int _FaceSide::NbVertices() const
1639 {
1640   if ( myChildren.empty() )
1641     return myVertices.Extent();
1642
1643   return myNbChildren + 1;
1644 }
1645
1646 //=======================================================================
1647 //function : NbCommonVertices
1648 //purpose  : Returns number of my vertices common with the given ones
1649 //=======================================================================
1650
1651 int _FaceSide::NbCommonVertices( const TopTools_MapOfShape& VV ) const
1652 {
1653   int nbCommon = 0;
1654   TopTools_MapIteratorOfMapOfShape vIt ( myVertices );
1655   for ( ; vIt.More(); vIt.Next() )
1656     nbCommon += ( VV.Contains( vIt.Key() ));
1657
1658   return nbCommon;
1659 }
1660
1661 //=======================================================================
1662 //function : FirstVertex
1663 //purpose  :
1664 //=======================================================================
1665
1666 TopoDS_Vertex _FaceSide::FirstVertex() const
1667 {
1668   if ( myChildren.empty() )
1669     return TopExp::FirstVertex( myEdge, Standard_True );
1670
1671   return myChildren.front().FirstVertex();
1672 }
1673
1674 //=======================================================================
1675 //function : LastVertex
1676 //purpose  : 
1677 //=======================================================================
1678
1679 TopoDS_Vertex _FaceSide::LastVertex() const
1680 {
1681   if ( myChildren.empty() )
1682     return TopExp::LastVertex( myEdge, Standard_True );
1683
1684   return myChildren.back().LastVertex();
1685 }
1686
1687 //=======================================================================
1688 //function : Vertex
1689 //purpose  : 
1690 //=======================================================================
1691
1692 TopoDS_Vertex _FaceSide::Vertex(int i) const
1693 {
1694   if ( myChildren.empty() )
1695     return i ? LastVertex() : FirstVertex();
1696       
1697   if ( i >= myNbChildren )
1698     return myChildren.back().LastVertex();
1699   
1700   return GetSide(i)->FirstVertex();
1701 }
1702
1703 //================================================================================
1704 /*!
1705  * \brief Return i-the zero-based edge of the side
1706  */
1707 //================================================================================
1708
1709 TopoDS_Edge _FaceSide::Edge(int i) const
1710 {
1711   if ( i == 0 && !myEdge.IsNull() )
1712     return myEdge;
1713
1714   if ( const _FaceSide* iSide = GetSide( i ))
1715     return iSide->myEdge;
1716
1717   return TopoDS_Edge();
1718 }
1719
1720 //=======================================================================
1721 //function : Contain
1722 //purpose  : 
1723 //=======================================================================
1724
1725 bool _FaceSide::Contain( const _FaceSide& side, int* which ) const
1726 {
1727   if ( !which || myChildren.empty() )
1728   {
1729     if ( which )
1730       *which = 0;
1731     int nbCommon = 0;
1732     TopTools_MapIteratorOfMapOfShape vIt ( side.myVertices );
1733     for ( ; vIt.More(); vIt.Next() )
1734       nbCommon += ( myVertices.Contains( vIt.Key() ));
1735     return (nbCommon > 1);
1736   }
1737   list< _FaceSide >::const_iterator mySide = myChildren.begin(), sideEnd = myChildren.end();
1738   for ( int i = 0; mySide != sideEnd; ++mySide, ++i ) {
1739     if ( mySide->Contain( side )) {
1740       *which = i;
1741       return true;
1742     }
1743   }
1744   return false;
1745 }
1746
1747 //=======================================================================
1748 //function : Contain
1749 //purpose  : 
1750 //=======================================================================
1751
1752 bool _FaceSide::Contain( const TopoDS_Vertex& vertex ) const
1753 {
1754   return myVertices.Contains( vertex );
1755 }
1756
1757 //=======================================================================
1758 //function : AppendSide
1759 //purpose  : 
1760 //=======================================================================
1761
1762 void _FaceSide::AppendSide( const _FaceSide& side )
1763 {
1764   if ( !myEdge.IsNull() )
1765   {
1766     myChildren.push_back( *this );
1767     myNbChildren = 1;
1768     myEdge.Nullify();
1769   }
1770   myChildren.push_back( side );
1771   myNbChildren++;
1772   TopTools_MapIteratorOfMapOfShape vIt ( side.myVertices );
1773   for ( ; vIt.More(); vIt.Next() )
1774     myVertices.Add( vIt.Key() );
1775
1776   myID = Q_PARENT;
1777   myChildren.back().SetID( EQuadSides( myNbChildren-1 ));
1778 }
1779
1780 //=======================================================================
1781 //function : SetBottomSide
1782 //purpose  : 
1783 //=======================================================================
1784
1785 void _FaceSide::SetBottomSide( int i )
1786 {
1787   if ( i > 0 && myID == Q_PARENT ) {
1788     list< _FaceSide >::iterator sideEnd, side = myChildren.begin();
1789     std::advance( side, i );
1790     myChildren.splice( myChildren.begin(), myChildren, side, myChildren.end() );
1791
1792     side = myChildren.begin(), sideEnd = myChildren.end();
1793     for ( int i = 0; side != sideEnd; ++side, ++i ) {
1794       side->SetID( EQuadSides(i) );
1795       side->SetBottomSide(i);
1796     }
1797   }
1798 }
1799
1800 //=======================================================================
1801 //function : GetNbSegments
1802 //purpose  : 
1803 //=======================================================================
1804
1805 int _FaceSide::GetNbSegments(SMESH_Mesh& mesh) const
1806 {
1807   int nb = 0;
1808   if ( myChildren.empty() )
1809   {
1810     nb = mesh.GetSubMesh(myEdge)->GetSubMeshDS()->NbElements();
1811   }
1812   else
1813   {
1814     list< _FaceSide >::const_iterator side = myChildren.begin(), sideEnd = myChildren.end();
1815     for ( ; side != sideEnd; ++side )
1816       nb += side->GetNbSegments(mesh);
1817   }
1818   return nb;
1819 }
1820
1821 //=======================================================================
1822 //function : StoreNodes
1823 //purpose  : 
1824 //=======================================================================
1825
1826 bool _FaceSide::StoreNodes(SMESH_Mesh&                   mesh,
1827                            vector<const SMDS_MeshNode*>& myGrid,
1828                            bool                          reverse )
1829 {
1830   list< TopoDS_Edge > edges;
1831   if ( myChildren.empty() )
1832   {
1833     edges.push_back( myEdge );
1834   }
1835   else
1836   {
1837     list< _FaceSide >::const_iterator side = myChildren.begin(), sideEnd = myChildren.end();
1838     for ( ; side != sideEnd; ++side )
1839       if ( reverse )
1840         edges.push_front( side->myEdge );
1841       else
1842         edges.push_back ( side->myEdge );
1843   }
1844   int nbNodes = 0;
1845   list< TopoDS_Edge >::iterator edge = edges.begin(), eEnd = edges.end();
1846   for ( ; edge != eEnd; ++edge )
1847   {
1848     map< double, const SMDS_MeshNode* > nodes;
1849     bool ok = SMESH_Algo::GetSortedNodesOnEdge( mesh.GetMeshDS(),
1850                                                 *edge,
1851                                                 /*ignoreMediumNodes=*/true,
1852                                                 nodes);
1853     if ( !ok ) return false;
1854
1855     bool forward = ( edge->Orientation() == TopAbs_FORWARD );
1856     if ( reverse ) forward = !forward;
1857     if ( forward )
1858     {
1859       map< double, const SMDS_MeshNode* >::iterator u_node, nEnd = nodes.end();
1860       for ( u_node = nodes.begin(); u_node != nEnd; ++u_node )
1861         myGrid[ nbNodes++ ] = u_node->second;
1862     }
1863     else 
1864     {
1865       map< double, const SMDS_MeshNode* >::reverse_iterator u_node, nEnd = nodes.rend();
1866       for ( u_node = nodes.rbegin(); u_node != nEnd; ++u_node )
1867         myGrid[ nbNodes++ ] = u_node->second;
1868     }
1869     nbNodes--; // node on vertex present in two adjacent edges
1870   }
1871   return nbNodes > 0;
1872 }
1873
1874 //=======================================================================
1875 //function : Dump
1876 //purpose  : dump end vertices
1877 //=======================================================================
1878
1879 void _FaceSide::Dump() const
1880 {
1881   if ( myChildren.empty() )
1882   {
1883     const char* sideNames[] = { "Q_BOTTOM", "Q_RIGHT", "Q_TOP", "Q_LEFT", "Q_CHILD", "Q_PARENT" };
1884     if ( myID >= Q_BOTTOM && myID < Q_PARENT )
1885       cout << sideNames[ myID ] << endl;
1886     else
1887       cout << "<UNDEFINED ID>" << endl;
1888     TopoDS_Vertex f = FirstVertex();
1889     TopoDS_Vertex l = LastVertex();
1890     gp_Pnt pf = BRep_Tool::Pnt(f);
1891     gp_Pnt pl = BRep_Tool::Pnt(l);
1892     cout << "\t ( "<< ptr( f ) << " - " << ptr( l )<< " )"
1893          << "\t ( "<< pf.X()<<", "<<pf.Y()<<", "<<pf.Z()<<" ) - "
1894          << " ( "<< pl.X()<<", "<<pl.Y()<<", "<<pl.Z()<<" )"<<endl;
1895   }
1896   else
1897   {
1898     list< _FaceSide >::const_iterator side = myChildren.begin(), sideEnd = myChildren.end();
1899     for ( ; side != sideEnd; ++side ) {
1900       side->Dump();
1901       cout << "\t";
1902     }
1903   }
1904 }