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