Salome HOME
Merge remote-tracking branch 'origin/master' into V9_dev
[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 : 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 "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 Convertor 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 egde 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 - succes 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 ortogonal 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 ortogonal 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       while ( !edges.empty() ) {
897         if ( SMESH_Algo::IsContinuous( sideEdges.back(), edges.front() )) {
898           sideEdges.splice( sideEdges.end(), edges, edges.begin());
899         }
900         else if ( SMESH_Algo::IsContinuous( sideEdges.front(), edges.back() )) {
901           sideEdges.splice( sideEdges.begin(), edges, --edges.end());
902         }
903         else if ( isContinuousMesh( sideEdges.back(), edges.front(), f, mesh )) {
904           sideEdges.splice( sideEdges.end(), edges, edges.begin());
905         }
906         else if ( isContinuousMesh( sideEdges.front(), edges.back(), f, mesh )) {
907           sideEdges.splice( sideEdges.begin(), edges, --edges.end());
908         }
909         else {
910           break;
911         }
912       }
913       mySides.AppendSide( _FaceSide( sideEdges ));
914     }
915   }
916   if (mySides.size() != 4)
917     return false;
918
919 #ifdef _DEBUG_
920   mySides.GetSide( Q_BOTTOM )->SetID( Q_BOTTOM );
921   mySides.GetSide( Q_RIGHT  )->SetID( Q_RIGHT );
922   mySides.GetSide( Q_TOP    )->SetID( Q_TOP );
923   mySides.GetSide( Q_LEFT   )->SetID( Q_LEFT );
924 #endif
925
926   return true;
927 }
928
929 //================================================================================
930 /*!
931  * \brief Try to unite self with other ordinary face
932  */
933 //================================================================================
934
935 bool _QuadFaceGrid::AddContinuousFace( const _QuadFaceGrid&       other,
936                                        const TopTools_MapOfShape& internalEdges)
937 {
938   for ( int i = 0; i < 4; ++i )
939   {
940     const _FaceSide& otherSide = other.GetSide( i );
941     int iMyCommon;
942     if ( mySides.Contain( otherSide, &iMyCommon ))
943     {
944       if ( internalEdges.Contains( otherSide.Edge( 0 )))
945       {
946         DUMP_VERT("Cont 1", mySides.GetSide(iMyCommon)->FirstVertex());
947         DUMP_VERT("Cont 2", mySides.GetSide(iMyCommon)->LastVertex());
948         DUMP_VERT("Cont 3", otherSide.FirstVertex());
949         DUMP_VERT("Cont 4", otherSide.LastVertex());
950
951         if ( myChildren.empty() )
952         {
953           myChildren.push_back( *this );
954           myFace.Nullify();
955         }
956         else // find iMyCommon in myChildren
957         {
958           for ( TChildIterator children = GetChildren(); children.more(); ) {
959             const _QuadFaceGrid& child = children.next();
960             if ( child.mySides.Contain( otherSide, &iMyCommon ))
961               break;
962           }
963         }
964
965         // orient new children equally
966         int otherBottomIndex = SMESH_MesherHelper::WrapIndex( i - iMyCommon + 2, 4 );
967         if ( other.IsComplex() )
968           for ( TChildIterator children = other.GetChildren(); children.more(); ) {
969             myChildren.push_back( children.next() );
970             myChildren.back().SetBottomSide( myChildren.back().GetSide( otherBottomIndex ));
971           }
972         else {
973           myChildren.push_back( other );
974           myChildren.back().SetBottomSide( myChildren.back().GetSide( otherBottomIndex ));
975         }
976
977         myLeftBottomChild = 0;
978
979         // collect vertices in mySides
980         if ( other.IsComplex() )
981           for ( TChildIterator children = other.GetChildren(); children.more(); )
982           {
983             const _QuadFaceGrid& child = children.next();
984             for ( int i = 0; i < 4; ++i )
985               mySides.AppendSide( child.GetSide(i) );
986           }
987         else
988           for ( int i = 0; i < 4; ++i )
989             mySides.AppendSide( other.GetSide(i) );
990
991         return true;
992       }
993     }
994   }
995   return false;
996 }
997
998 //================================================================================
999 /*!
1000  * \brief Try to set the side as bottom hirizontal side
1001  */
1002 //================================================================================
1003
1004 bool _QuadFaceGrid::SetBottomSide(const _FaceSide& bottom, int* sideIndex)
1005 {
1006   myLeftBottomChild = myRightBrother = myUpBrother = 0;
1007
1008   int myBottomIndex;
1009   if ( myChildren.empty() )
1010   {
1011     if ( mySides.Contain( bottom, &myBottomIndex )) {
1012       mySides.SetBottomSide( myBottomIndex );
1013       if ( sideIndex )
1014         *sideIndex = myBottomIndex;
1015       return true;
1016     }
1017   }
1018   else
1019   {
1020     TChildren::iterator childFace = myChildren.begin(), childEnd = myChildren.end();
1021     for ( ; childFace != childEnd; ++childFace )
1022     {
1023       if ( childFace->SetBottomSide( bottom, &myBottomIndex ))
1024       {
1025         TChildren::iterator orientedChild = childFace;
1026         for ( childFace = myChildren.begin(); childFace != childEnd; ++childFace ) {
1027           if ( childFace != orientedChild )
1028             childFace->SetBottomSide( childFace->GetSide( myBottomIndex ));
1029         }
1030         if ( sideIndex )
1031           *sideIndex = myBottomIndex;
1032         return true;
1033       }
1034     }
1035   }
1036   return false;
1037 }
1038
1039 //================================================================================
1040 /*!
1041  * \brief Return face adjacent to i-th side of this face, (0<i<4)
1042  */
1043 //================================================================================
1044
1045 _QuadFaceGrid* _QuadFaceGrid::FindAdjacentForSide(int                  i,
1046                                                   list<_QuadFaceGrid>& faces,
1047                                                   EBoxSides            id) const
1048 {
1049   const _FaceSide & iSide = GetSide( i );
1050   list< _QuadFaceGrid >::iterator boxFace = faces.begin();
1051   for ( ; boxFace != faces.end(); ++boxFace )
1052   {
1053     _QuadFaceGrid* f  = & (*boxFace);
1054     if ( f != this && f->SetBottomSide( iSide ))
1055       return f->SetID( id ), f;
1056   }
1057   return (_QuadFaceGrid*) 0;
1058 }
1059
1060 //================================================================================
1061 /*!
1062  * \brief Return i-th side
1063  */
1064 //================================================================================
1065
1066 const _FaceSide& _QuadFaceGrid::GetSide(int i) const
1067 {
1068   if ( myChildren.empty() )
1069     return *mySides.GetSide(i);
1070
1071   _QuadFaceGrid* me = const_cast<_QuadFaceGrid*>(this);
1072   if ( !me->locateChildren() || !myLeftBottomChild )
1073     return *mySides.GetSide(i);
1074
1075   const _QuadFaceGrid* child = myLeftBottomChild;
1076   switch ( i ){
1077   case Q_BOTTOM:
1078   case Q_LEFT:
1079     break;
1080   case Q_RIGHT:
1081     while ( child->myRightBrother )
1082       child = child->myRightBrother;
1083     break;
1084   case Q_TOP:
1085     while ( child->myUpBrother )
1086       child = child->myUpBrother;
1087     break;
1088   default: ;
1089   }
1090   return child->GetSide( i );
1091 }
1092
1093 //================================================================================
1094 /*!
1095  * \brief Reverse edges in order to have them oriented along axes of the unit box
1096  */
1097 //================================================================================
1098
1099 void _QuadFaceGrid::ReverseEdges()
1100 {
1101   myReverse = !myReverse;
1102
1103 // #ifdef DEB_FACES
1104 //   if ( !myFace.IsNull() )
1105 //     TopAbs::Print(myFace.Orientation(), cout);
1106 // #endif
1107
1108   if ( myChildren.empty() )
1109   {
1110     DumpVertices();
1111   }
1112   else
1113   {
1114     DumpVertices();
1115     TChildren::iterator child = myChildren.begin(), childEnd = myChildren.end();
1116     for ( ; child != childEnd; ++child )
1117       child->ReverseEdges();
1118   }
1119 }
1120
1121 //================================================================================
1122 /*!
1123  * \brief Load nodes of a mesh
1124  */
1125 //================================================================================
1126
1127 bool _QuadFaceGrid::LoadGrid( SMESH_Mesh& mesh )
1128 {
1129   if ( !myChildren.empty() )
1130   {
1131     // Let child faces load their grids
1132     TChildren::iterator child = myChildren.begin(), childEnd = myChildren.end();
1133     for ( ; child != childEnd; ++child ) {
1134       child->SetID( myID );
1135       if ( !child->LoadGrid( mesh ) )
1136         return error( child->GetError() );
1137     }
1138     // Fill myGrid with nodes of patches
1139     return loadCompositeGrid( mesh );
1140   }
1141
1142   // ---------------------------------------
1143   // Fill myGrid with nodes bound to myFace
1144   // ---------------------------------------
1145
1146   if ( !myGrid.empty() )
1147     return true;
1148
1149   SMESHDS_SubMesh* faceSubMesh = mesh.GetSubMesh( myFace )->GetSubMeshDS();
1150   // check that all faces are quadrangular
1151   SMDS_ElemIteratorPtr fIt = faceSubMesh->GetElements();
1152   while ( fIt->more() )
1153     if ( fIt->next()->NbNodes() % 4 > 0 )
1154       return error("Non-quadrangular mesh faces are not allowed on sides of a composite block");
1155   
1156   myIndexer._xSize = 1 + mySides.GetSide( Q_BOTTOM )->GetNbSegments( mesh );
1157   myIndexer._ySize = 1 + mySides.GetSide( Q_LEFT   )->GetNbSegments( mesh );
1158
1159   myGrid.resize( myIndexer.size() );
1160
1161   // strore nodes bound to the bottom edge
1162   mySides.GetSide( Q_BOTTOM )->StoreNodes( mesh, myGrid, myReverse );
1163
1164   // store the rest nodes row by row
1165
1166   TIDSortedElemSet emptySet, avoidSet;
1167   const SMDS_MeshElement* firstQuad = 0; // most left face above the last row of found nodes
1168
1169   size_t nbFoundNodes = myIndexer._xSize;
1170   while ( nbFoundNodes != myGrid.size() )
1171   {
1172     // first and last nodes of the last filled row of nodes
1173     const SMDS_MeshNode* n1down = myGrid[ nbFoundNodes - myIndexer._xSize ];
1174     const SMDS_MeshNode* n2down = myGrid[ nbFoundNodes - myIndexer._xSize + 1];
1175     const SMDS_MeshNode* n1downLast = myGrid[ nbFoundNodes-1 ];
1176
1177     // find the first face above the row by the first two left nodes
1178     //
1179     // n1up     n2up
1180     //     o---o
1181     //     |   |
1182     //     o---o  o  o  o  o
1183     //n1down    n2down
1184     //
1185     firstQuad = SMESH_MeshAlgos::FindFaceInSet( n1down, n2down, emptySet, avoidSet);
1186     while ( firstQuad && !faceSubMesh->Contains( firstQuad )) {
1187       avoidSet.insert( firstQuad );
1188       firstQuad = SMESH_MeshAlgos::FindFaceInSet( n1down, n2down, emptySet, avoidSet);
1189     }
1190     if ( !firstQuad || !faceSubMesh->Contains( firstQuad ))
1191       return error(ERR_LI("Error in _QuadFaceGrid::LoadGrid()"));
1192
1193     // find the node of quad bound to the left geom edge
1194     int i2down = firstQuad->GetNodeIndex( n2down );
1195     const SMDS_MeshNode* n1up = firstQuad->GetNode(( i2down+2 ) % 4 );
1196     myGrid[ nbFoundNodes++ ] = n1up;
1197     // the 4-the node of the first quad
1198     int i1down = firstQuad->GetNodeIndex( n1down );
1199     const SMDS_MeshNode* n2up = firstQuad->GetNode(( i1down+2 ) % 4 );
1200     myGrid[ nbFoundNodes++ ] = n2up;
1201
1202     n1down = n2down;
1203     n1up   = n2up;
1204     const SMDS_MeshElement* quad = firstQuad;
1205
1206     // find the rest nodes by remaining faces above the row
1207     //
1208     //             n1up
1209     //     o---o--o
1210     //     |   |  | ->
1211     //     o---o--o  o  o  o
1212     //                      n1downLast
1213     //
1214     while ( n1down != n1downLast )
1215     {
1216       // next face
1217       avoidSet.clear(); avoidSet.insert( quad );
1218       quad = SMESH_MeshAlgos::FindFaceInSet( n1down, n1up, emptySet, avoidSet );
1219       if ( !quad || quad->NbNodes() % 4 > 0)
1220         return error(ERR_LI("Error in _QuadFaceGrid::LoadGrid()"));
1221
1222       // next node
1223       if ( quad->GetNode( i1down ) != n1down ) // check already found index
1224         i1down = quad->GetNodeIndex( n1down );
1225       n2up = quad->GetNode(( i1down+2 ) % 4 );
1226       myGrid[ nbFoundNodes++ ] = n2up;
1227
1228       n1down = myGrid[ nbFoundNodes - myIndexer._xSize - 1 ];
1229       n1up   = n2up;
1230     }
1231     avoidSet.clear(); avoidSet.insert( firstQuad );
1232   }
1233   DumpGrid(); // debug
1234
1235   return true;
1236 }
1237
1238 //================================================================================
1239 /*!
1240  * \brief Fill myIJK with normalized parameters of nodes in myGrid
1241  *  \param [in] i1 - coordinate index along rows of myGrid
1242  *  \param [in] i2 - coordinate index along columns of myGrid
1243  *  \param [in] v3 - value of the constant parameter
1244  */
1245 //================================================================================
1246
1247 void _QuadFaceGrid::ComputeIJK( int i1, int i2, double v3 )
1248 {
1249   gp_XYZ ijk( v3, v3, v3 );
1250   myIJK.resize( myIndexer.size(), ijk );
1251
1252   const size_t nbCol = myIndexer._xSize;
1253   const size_t nbRow = myIndexer._ySize;
1254
1255   vector< double > len( nbRow );
1256   len[0] = 0;
1257   for ( size_t i = 0; i < nbCol; ++i )
1258   {
1259     gp_Pnt pPrev = GetXYZ( i, 0 );
1260     for ( size_t j = 1; j < nbRow; ++j )
1261     {
1262       gp_Pnt p = GetXYZ( i, j );
1263       len[ j ] = len[ j-1 ] + p.Distance( pPrev );
1264       pPrev = p;
1265     }
1266     for ( size_t j = 0; j < nbRow; ++j )
1267       GetIJK( i, j ).SetCoord( i2, len[ j ]/len.back() );
1268   }
1269
1270   len.resize( nbCol );
1271   for ( size_t j = 0; j < nbRow; ++j )
1272   {
1273     gp_Pnt pPrev = GetXYZ( 0, j );
1274     for ( size_t i = 1; i < nbCol; ++i )
1275     {
1276       gp_Pnt p = GetXYZ( i, j );
1277       len[ i ] = len[ i-1 ] + p.Distance( pPrev );
1278       pPrev = p;
1279     }
1280     for ( size_t i = 0; i < nbCol; ++i )
1281       GetIJK( i, j ).SetCoord( i1, len[ i ]/len.back() );
1282   }
1283 }
1284
1285 //================================================================================
1286 /*!
1287  * \brief Find out mutual location of children: find their right and up brothers
1288  */
1289 //================================================================================
1290
1291 bool _QuadFaceGrid::locateChildren()
1292 {
1293   if ( myLeftBottomChild )
1294     return true;
1295
1296   TChildren::iterator child = myChildren.begin(), childEnd = myChildren.end();
1297
1298   // find a child sharing it's first bottom vertex with no other brother
1299   myLeftBottomChild = 0;
1300   for ( ; !myLeftBottomChild && child != childEnd; ++child )
1301   {
1302     TopoDS_Vertex leftVertex = child->GetSide( Q_BOTTOM ).FirstVertex();
1303     bool sharedVertex = false;
1304     TChildren::iterator otherChild = myChildren.begin();
1305     for ( ; otherChild != childEnd && !sharedVertex; ++otherChild )
1306       if ( otherChild != child )
1307         sharedVertex = otherChild->mySides.Contain( leftVertex );
1308     if ( !sharedVertex ) {
1309       myLeftBottomChild = & (*child);
1310       DUMP_VERT("0 left bottom Vertex: ",leftVertex );
1311     }
1312   }
1313   if (!myLeftBottomChild)
1314     return error(ERR_LI("Error in locateChildren()"));
1315
1316   set< _QuadFaceGrid* > notLocatedChilren;
1317   for (child = myChildren.begin() ; child != childEnd; ++child )
1318     notLocatedChilren.insert( & (*child));
1319
1320   // connect myLeftBottomChild to it's right and upper brothers
1321   notLocatedChilren.erase( myLeftBottomChild );
1322   myLeftBottomChild->setBrothers( notLocatedChilren );
1323   if ( !notLocatedChilren.empty() )
1324     return error(ERR_LI("Error in locateChildren()"));
1325
1326   return true;
1327 }
1328
1329 //================================================================================
1330 /*!
1331  * \brief Fill myGrid with nodes of patches
1332  */
1333 //================================================================================
1334
1335 bool _QuadFaceGrid::loadCompositeGrid(SMESH_Mesh& mesh)
1336 {
1337   // Find out mutual location of children: find their right and up brothers
1338   if ( !locateChildren() )
1339     return false;
1340
1341   // Load nodes according to mutual location of children
1342
1343   // grid size
1344   myIndexer._xSize = 1 + myLeftBottomChild->GetNbHoriSegments(mesh, /*withBrothers=*/true);
1345   myIndexer._ySize = 1 + myLeftBottomChild->GetNbVertSegments(mesh, /*withBrothers=*/true);
1346
1347   myGrid.resize( myIndexer.size() );
1348
1349   int fromX = myReverse ? myIndexer._xSize : 0;
1350   if (!myLeftBottomChild->fillGrid( mesh, myGrid, myIndexer, fromX, 0 ))
1351     return error( myLeftBottomChild->GetError() );
1352
1353   DumpGrid();
1354
1355   return true;
1356 }
1357
1358 //================================================================================
1359 /*!
1360  * \brief Find right an upper brothers among notLocatedBrothers
1361  */
1362 //================================================================================
1363
1364 void _QuadFaceGrid::setBrothers( set< _QuadFaceGrid* >& notLocatedBrothers )
1365 {
1366   if ( !notLocatedBrothers.empty() )
1367   {
1368     // find right brother
1369     TopoDS_Vertex rightVertex = GetSide( Q_BOTTOM ).LastVertex();
1370     DUMP_VERT("1 right bottom Vertex: ",rightVertex );
1371     set< _QuadFaceGrid* >::iterator brIt, brEnd = notLocatedBrothers.end();
1372     for ( brIt = notLocatedBrothers.begin(); brIt != brEnd; ++brIt )
1373     {
1374       _QuadFaceGrid* brother = *brIt;
1375       TopoDS_Vertex brotherLeftVertex = brother->GetSide( Q_BOTTOM ).FirstVertex();
1376       DUMP_VERT( "brother left bottom: ", brotherLeftVertex );
1377       if ( rightVertex.IsSame( brotherLeftVertex )) {
1378         myRightBrother = brother;
1379         notLocatedBrothers.erase( brIt );
1380         break;
1381       }
1382     }
1383     // find upper brother
1384     TopoDS_Vertex upVertex = GetSide( Q_LEFT ).FirstVertex();
1385     DUMP_VERT("1 left up Vertex: ",upVertex);
1386     brIt = notLocatedBrothers.begin(), brEnd = notLocatedBrothers.end();
1387     for ( ; brIt != brEnd; ++brIt )
1388     {
1389       _QuadFaceGrid* brother = *brIt;
1390       TopoDS_Vertex brotherLeftVertex = brother->GetSide( Q_BOTTOM ).FirstVertex();
1391       DUMP_VERT("brother left bottom: ", brotherLeftVertex);
1392       if ( upVertex.IsSame( brotherLeftVertex )) {
1393         myUpBrother = brother;
1394         notLocatedBrothers.erase( myUpBrother );
1395         break;
1396       }
1397     }
1398     // recursive call
1399     if ( myRightBrother )
1400       myRightBrother->setBrothers( notLocatedBrothers );
1401     if ( myUpBrother )
1402       myUpBrother->setBrothers( notLocatedBrothers );
1403   }
1404 }
1405
1406 //================================================================================
1407 /*!
1408  * \brief Store nodes of a simple face into grid starting from (x,y) position
1409  */
1410 //================================================================================
1411
1412 bool _QuadFaceGrid::fillGrid(SMESH_Mesh&                    theMesh,
1413                              vector<const SMDS_MeshNode*> & theGrid,
1414                              const _Indexer&                theIndexer,
1415                              int                            theX,
1416                              int                            theY)
1417 {
1418   if ( myGrid.empty() && !LoadGrid( theMesh ))
1419     return false;
1420
1421   // store my own grid in the global grid
1422
1423   int fromX = myReverse ? theX - myIndexer._xSize: theX;
1424
1425   for ( int i = 0, x = fromX; i < myIndexer._xSize; ++i, ++x )
1426     for ( int j = 0, y = theY; j < myIndexer._ySize; ++j, ++y )
1427       theGrid[ theIndexer( x, y )] = myGrid[ myIndexer( i, j )];
1428
1429   // store grids of my right and upper brothers
1430
1431   if ( myRightBrother )
1432   {
1433     if ( myReverse )
1434       fromX += 1;
1435     else
1436       fromX += myIndexer._xSize - 1;
1437     if ( !myRightBrother->fillGrid( theMesh, theGrid, theIndexer, fromX, theY ))
1438       return error( myRightBrother->GetError() );
1439   }
1440   if ( myUpBrother )
1441   {
1442     if ( !myUpBrother->fillGrid( theMesh, theGrid, theIndexer,
1443                                  theX, theY + myIndexer._ySize - 1))
1444       return error( myUpBrother->GetError() );
1445   }
1446   return true;
1447 }
1448
1449 //================================================================================
1450 /*!
1451  * \brief Return number of segments on the hirizontal sides
1452  */
1453 //================================================================================
1454
1455 int _QuadFaceGrid::GetNbHoriSegments(SMESH_Mesh& mesh, bool withBrothers) const
1456 {
1457   int nbSegs = 0;
1458   if ( myLeftBottomChild )
1459   {
1460     nbSegs += myLeftBottomChild->GetNbHoriSegments( mesh, true );
1461   }
1462   else
1463   {
1464     nbSegs = mySides.GetSide( Q_BOTTOM )->GetNbSegments(mesh);
1465     if ( withBrothers && myRightBrother )
1466       nbSegs += myRightBrother->GetNbHoriSegments( mesh, withBrothers );
1467   }
1468   return nbSegs;
1469 }
1470
1471 //================================================================================
1472 /*!
1473  * \brief Return number of segments on the vertical sides
1474  */
1475 //================================================================================
1476
1477 int _QuadFaceGrid::GetNbVertSegments(SMESH_Mesh& mesh, bool withBrothers) const
1478 {
1479   int nbSegs = 0;
1480   if ( myLeftBottomChild )
1481   {
1482     nbSegs += myLeftBottomChild->GetNbVertSegments( mesh, true );
1483   }
1484   else
1485   {
1486     nbSegs = mySides.GetSide( Q_LEFT )->GetNbSegments(mesh);
1487     if ( withBrothers && myUpBrother )
1488       nbSegs += myUpBrother->GetNbVertSegments( mesh, withBrothers );
1489   }
1490   return nbSegs;
1491 }
1492
1493 //================================================================================
1494 /*!
1495  * \brief Return edge on the hirizontal bottom sides
1496  */
1497 //================================================================================
1498
1499 int _QuadFaceGrid::GetHoriEdges(vector<TopoDS_Edge> & edges) const
1500 {
1501   if ( myLeftBottomChild )
1502   {
1503     return myLeftBottomChild->GetHoriEdges( edges );
1504   }
1505   else
1506   {
1507     const _FaceSide* bottom  = mySides.GetSide( Q_BOTTOM );
1508     int i = 0;
1509     while ( true ) {
1510       TopoDS_Edge e = bottom->Edge( i++ );
1511       if ( e.IsNull() )
1512         break;
1513       else
1514         edges.push_back( e );
1515     }
1516     if ( myRightBrother )
1517       myRightBrother->GetHoriEdges( edges );
1518   }
1519   return edges.size();
1520 }
1521
1522 //================================================================================
1523 /*!
1524  * \brief Return a node by its position
1525  */
1526 //================================================================================
1527
1528 const SMDS_MeshNode* _QuadFaceGrid::GetNode(int iHori, int iVert) const
1529 {
1530   return myGrid[ myIndexer( iHori, iVert )];
1531 }
1532
1533 //================================================================================
1534 /*!
1535  * \brief Return node coordinates by its position
1536  */
1537 //================================================================================
1538
1539 gp_XYZ _QuadFaceGrid::GetXYZ(int iHori, int iVert) const
1540 {
1541   SMESH_TNodeXYZ xyz = myGrid[ myIndexer( iHori, iVert )];
1542   return xyz;
1543 }
1544
1545 //================================================================================
1546 /*!
1547  * \brief Return normal to the face at vertex v
1548  */
1549 //================================================================================
1550
1551 bool _QuadFaceGrid::GetNormal( const TopoDS_Vertex& v, gp_Vec& n ) const
1552 {
1553   if ( myChildren.empty() )
1554   {
1555     if ( mySides.Contain( v )) {
1556       try {
1557         gp_Pnt2d uv = BRep_Tool::Parameters( v, myFace );
1558         BRepAdaptor_Surface surface( myFace );
1559         gp_Pnt p; gp_Vec d1u, d1v;
1560         surface.D1( uv.X(), uv.Y(), p, d1u, d1v );
1561         n = d1u.Crossed( d1v );
1562         return true;
1563       }
1564       catch (Standard_Failure) {
1565         return false;
1566       }
1567     }
1568   }
1569   else
1570   {
1571     TChildren::const_iterator child = myChildren.begin(), childEnd = myChildren.end();
1572     for ( ; child != childEnd; ++child )
1573       if ( child->GetNormal( v, n ))
1574         return true;
1575   }
1576   return false;
1577 }
1578
1579 //================================================================================
1580 /*!
1581  * \brief Dumps coordinates of grid nodes
1582  */
1583 //================================================================================
1584
1585 void _QuadFaceGrid::DumpGrid() const
1586 {
1587 #ifdef DEB_GRID
1588   const char* names[] = { "B_BOTTOM", "B_RIGHT", "B_TOP", "B_LEFT", "B_FRONT", "B_BACK" };
1589   cout << "****** Face " << names[ myID ] << endl;
1590
1591   if ( myChildren.empty() || !myGrid.empty() )
1592   {
1593     cout << "x size: " << myIndexer._xSize << "; y size: " << myIndexer._ySize << endl;
1594     for ( int y = 0; y < myIndexer._ySize; ++y ) {
1595       cout << "-- row " << y << endl;
1596       for ( int x = 0; x < myIndexer._xSize; ++x ) {
1597         const SMDS_MeshNode* n = myGrid[ myIndexer( x, y ) ];
1598         cout << x << " ( " << n->X() << ", " << n->Y() << ", " << n->Z() << " )" << endl;
1599       }
1600     }
1601   }
1602   else
1603   {
1604     cout << "Nb children: " << myChildren.size() << endl;
1605     TChildren::const_iterator child = myChildren.begin(), childEnd = myChildren.end();
1606     for ( int i=0; child != childEnd; ++child, ++i ) {
1607       cout << "   *** SUBFACE " << i+1 << endl;
1608       ((_QuadFaceGrid&)(*child)).SetID( myID );
1609       child->DumpGrid();
1610     }
1611   }
1612 #endif
1613 }
1614
1615 //================================================================================
1616 /*!
1617  * \brief Dump vertices
1618  */
1619 //================================================================================
1620
1621 void _QuadFaceGrid::DumpVertices() const
1622 {
1623 #ifdef DEB_FACES
1624   cout << "****** Face ";
1625   const char* names[] = { "B_BOTTOM", "B_RIGHT", "B_TOP", "B_LEFT", "B_FRONT", "B_BACK" };
1626   if ( myID >= B_BOTTOM && myID < B_BACK )
1627     cout << names[ myID ] << endl;
1628   else
1629     cout << "UNDEFINED" << endl;
1630
1631   if ( myChildren.empty() )
1632   {
1633     for ( int i = 0; i < 4; ++i )
1634     {
1635       cout << "  Side "; mySides.GetSide( i )->Dump();
1636     }
1637   }
1638   else
1639   {
1640     cout << "-- Nb children: " << myChildren.size() << endl;
1641     TChildren::const_iterator child = myChildren.begin(), childEnd = myChildren.end();
1642     for ( int i=0; child != childEnd; ++child, ++i ) {
1643       cout << "   *** SUBFACE " << i+1 << endl;
1644       ((_QuadFaceGrid&)(*child)).SetID( myID );
1645       child->DumpVertices();
1646     }
1647   }
1648 #endif
1649 }
1650
1651 //=======================================================================
1652 //function : _FaceSide
1653 //purpose  : copy constructor
1654 //=======================================================================
1655
1656 _FaceSide::_FaceSide(const _FaceSide& other)
1657 {
1658   myEdge = other.myEdge;
1659   myChildren = other.myChildren;
1660   myNbChildren = other.myNbChildren;
1661   myVertices.Assign( other.myVertices );
1662   myID = other.myID;
1663 }
1664
1665 //================================================================================
1666 /*!
1667  * \brief Construct a face side of one edge
1668  */
1669 //================================================================================
1670
1671 _FaceSide::_FaceSide(const TopoDS_Edge& edge):
1672   myEdge( edge ), myNbChildren(0)
1673 {
1674   if ( !edge.IsNull() )
1675     for ( TopExp_Explorer exp( edge, TopAbs_VERTEX ); exp.More(); exp.Next() )
1676       //myVertices.insert( ptr ( exp.Current() ));
1677       myVertices.Add( exp.Current() );
1678 }
1679
1680 //================================================================================
1681 /*!
1682  * \brief Construct a face side of several edges
1683  */
1684 //================================================================================
1685
1686 _FaceSide::_FaceSide(const list<TopoDS_Edge>& edges):
1687   myNbChildren(0)
1688 {
1689   list<TopoDS_Edge>::const_iterator edge = edges.begin(), eEnd = edges.end();
1690   for ( ; edge != eEnd; ++edge ) {
1691     myChildren.push_back( _FaceSide( *edge ));
1692     myNbChildren++;
1693     myVertices.Add( myChildren.back().FirstVertex() );
1694     myVertices.Add( myChildren.back().LastVertex() );
1695     myChildren.back().SetID( Q_CHILD ); // not to splice them
1696   }
1697 }
1698
1699 //=======================================================================
1700 //function : GetSide
1701 //purpose  :
1702 //=======================================================================
1703
1704 _FaceSide* _FaceSide::GetSide(const int i)
1705 {
1706   if ( i >= myNbChildren )
1707     return 0;
1708
1709   list< _FaceSide >::iterator side = myChildren.begin();
1710   if ( i )
1711     std::advance( side, i );
1712   return & (*side);
1713 }
1714
1715 //=======================================================================
1716 //function : GetSide
1717 //purpose  : 
1718 //=======================================================================
1719
1720 const _FaceSide* _FaceSide::GetSide(const int i) const
1721 {
1722   return const_cast< _FaceSide* >(this)->GetSide(i);
1723 }
1724
1725 //=======================================================================
1726 //function : NbVertices
1727 //purpose  : return nb of vertices in the side
1728 //=======================================================================
1729
1730 int _FaceSide::NbVertices() const
1731 {
1732   if ( myChildren.empty() )
1733     return myVertices.Extent();
1734
1735   return myNbChildren + 1;
1736 }
1737
1738 //=======================================================================
1739 //function : NbCommonVertices
1740 //purpose  : Returns number of my vertices common with the given ones
1741 //=======================================================================
1742
1743 int _FaceSide::NbCommonVertices( const TopTools_MapOfShape& VV ) const
1744 {
1745   int nbCommon = 0;
1746   TopTools_MapIteratorOfMapOfShape vIt ( myVertices );
1747   for ( ; vIt.More(); vIt.Next() )
1748     nbCommon += ( VV.Contains( vIt.Key() ));
1749
1750   return nbCommon;
1751 }
1752
1753 //=======================================================================
1754 //function : FirstVertex
1755 //purpose  :
1756 //=======================================================================
1757
1758 TopoDS_Vertex _FaceSide::FirstVertex() const
1759 {
1760   if ( myChildren.empty() )
1761     return TopExp::FirstVertex( myEdge, Standard_True );
1762
1763   return myChildren.front().FirstVertex();
1764 }
1765
1766 //=======================================================================
1767 //function : LastVertex
1768 //purpose  : 
1769 //=======================================================================
1770
1771 TopoDS_Vertex _FaceSide::LastVertex() const
1772 {
1773   if ( myChildren.empty() )
1774     return TopExp::LastVertex( myEdge, Standard_True );
1775
1776   return myChildren.back().LastVertex();
1777 }
1778
1779 //=======================================================================
1780 //function : Vertex
1781 //purpose  : 
1782 //=======================================================================
1783
1784 TopoDS_Vertex _FaceSide::Vertex(int i) const
1785 {
1786   if ( myChildren.empty() )
1787     return i ? LastVertex() : FirstVertex();
1788       
1789   if ( i >= myNbChildren )
1790     return myChildren.back().LastVertex();
1791   
1792   return GetSide(i)->FirstVertex();
1793 }
1794
1795 //================================================================================
1796 /*!
1797  * \brief Return i-the zero-based edge of the side
1798  */
1799 //================================================================================
1800
1801 TopoDS_Edge _FaceSide::Edge(int i) const
1802 {
1803   if ( i == 0 && !myEdge.IsNull() )
1804     return myEdge;
1805
1806   if ( const _FaceSide* iSide = GetSide( i ))
1807     return iSide->myEdge;
1808
1809   return TopoDS_Edge();
1810 }
1811
1812 //=======================================================================
1813 //function : Contain
1814 //purpose  : 
1815 //=======================================================================
1816
1817 bool _FaceSide::Contain( const _FaceSide& side, int* which ) const
1818 {
1819   if ( !which || myChildren.empty() )
1820   {
1821     if ( which )
1822       *which = 0;
1823     int nbCommon = 0;
1824     TopTools_MapIteratorOfMapOfShape vIt ( side.myVertices );
1825     for ( ; vIt.More(); vIt.Next() )
1826       nbCommon += ( myVertices.Contains( vIt.Key() ));
1827     return (nbCommon > 1);
1828   }
1829   list< _FaceSide >::const_iterator mySide = myChildren.begin(), sideEnd = myChildren.end();
1830   for ( int i = 0; mySide != sideEnd; ++mySide, ++i ) {
1831     if ( mySide->Contain( side )) {
1832       *which = i;
1833       return true;
1834     }
1835   }
1836   return false;
1837 }
1838
1839 //=======================================================================
1840 //function : Contain
1841 //purpose  : 
1842 //=======================================================================
1843
1844 bool _FaceSide::Contain( const TopoDS_Vertex& vertex ) const
1845 {
1846   return myVertices.Contains( vertex );
1847 }
1848
1849 //=======================================================================
1850 //function : AppendSide
1851 //purpose  : 
1852 //=======================================================================
1853
1854 void _FaceSide::AppendSide( const _FaceSide& side )
1855 {
1856   if ( !myEdge.IsNull() )
1857   {
1858     myChildren.push_back( *this );
1859     myNbChildren = 1;
1860     myEdge.Nullify();
1861   }
1862   myChildren.push_back( side );
1863   myNbChildren++;
1864   TopTools_MapIteratorOfMapOfShape vIt ( side.myVertices );
1865   for ( ; vIt.More(); vIt.Next() )
1866     myVertices.Add( vIt.Key() );
1867
1868   myID = Q_PARENT;
1869   myChildren.back().SetID( EQuadSides( myNbChildren-1 ));
1870 }
1871
1872 //=======================================================================
1873 //function : SetBottomSide
1874 //purpose  : 
1875 //=======================================================================
1876
1877 void _FaceSide::SetBottomSide( int i )
1878 {
1879   if ( i > 0 && myID == Q_PARENT ) {
1880     list< _FaceSide >::iterator sideEnd, side = myChildren.begin();
1881     std::advance( side, i );
1882     myChildren.splice( myChildren.begin(), myChildren, side, myChildren.end() );
1883
1884     side = myChildren.begin(), sideEnd = myChildren.end();
1885     for ( int i = 0; side != sideEnd; ++side, ++i ) {
1886       side->SetID( EQuadSides(i) );
1887       side->SetBottomSide(i);
1888     }
1889   }
1890 }
1891
1892 //=======================================================================
1893 //function : GetNbSegments
1894 //purpose  : 
1895 //=======================================================================
1896
1897 int _FaceSide::GetNbSegments(SMESH_Mesh& mesh) const
1898 {
1899   int nb = 0;
1900   if ( myChildren.empty() )
1901   {
1902     nb = mesh.GetSubMesh(myEdge)->GetSubMeshDS()->NbElements();
1903   }
1904   else
1905   {
1906     list< _FaceSide >::const_iterator side = myChildren.begin(), sideEnd = myChildren.end();
1907     for ( ; side != sideEnd; ++side )
1908       nb += side->GetNbSegments(mesh);
1909   }
1910   return nb;
1911 }
1912
1913 //=======================================================================
1914 //function : StoreNodes
1915 //purpose  : 
1916 //=======================================================================
1917
1918 bool _FaceSide::StoreNodes(SMESH_Mesh&                   mesh,
1919                            vector<const SMDS_MeshNode*>& myGrid,
1920                            bool                          reverse )
1921 {
1922   list< TopoDS_Edge > edges;
1923   if ( myChildren.empty() )
1924   {
1925     edges.push_back( myEdge );
1926   }
1927   else
1928   {
1929     list< _FaceSide >::const_iterator side = myChildren.begin(), sideEnd = myChildren.end();
1930     for ( ; side != sideEnd; ++side )
1931       if ( reverse )
1932         edges.push_front( side->myEdge );
1933       else
1934         edges.push_back ( side->myEdge );
1935   }
1936   int nbNodes = 0;
1937   list< TopoDS_Edge >::iterator edge = edges.begin(), eEnd = edges.end();
1938   for ( ; edge != eEnd; ++edge )
1939   {
1940     map< double, const SMDS_MeshNode* > nodes;
1941     bool ok = SMESH_Algo::GetSortedNodesOnEdge( mesh.GetMeshDS(),
1942                                                 *edge,
1943                                                 /*ignoreMediumNodes=*/true,
1944                                                 nodes);
1945     if ( !ok ) return false;
1946
1947     bool forward = ( edge->Orientation() == TopAbs_FORWARD );
1948     if ( reverse ) forward = !forward;
1949     if ( forward )
1950     {
1951       map< double, const SMDS_MeshNode* >::iterator u_node, nEnd = nodes.end();
1952       for ( u_node = nodes.begin(); u_node != nEnd; ++u_node )
1953         myGrid[ nbNodes++ ] = u_node->second;
1954     }
1955     else 
1956     {
1957       map< double, const SMDS_MeshNode* >::reverse_iterator u_node, nEnd = nodes.rend();
1958       for ( u_node = nodes.rbegin(); u_node != nEnd; ++u_node )
1959         myGrid[ nbNodes++ ] = u_node->second;
1960     }
1961     nbNodes--; // node on vertex present in two adjacent edges
1962   }
1963   return nbNodes > 0;
1964 }
1965
1966 //=======================================================================
1967 //function : Dump
1968 //purpose  : dump end vertices
1969 //=======================================================================
1970
1971 void _FaceSide::Dump() const
1972 {
1973   if ( myChildren.empty() )
1974   {
1975     const char* sideNames[] = { "Q_BOTTOM", "Q_RIGHT", "Q_TOP", "Q_LEFT", "Q_CHILD", "Q_PARENT" };
1976     if ( myID >= Q_BOTTOM && myID < Q_PARENT )
1977       cout << sideNames[ myID ] << endl;
1978     else
1979       cout << "<UNDEFINED ID>" << endl;
1980     TopoDS_Vertex f = FirstVertex();
1981     TopoDS_Vertex l = LastVertex();
1982     gp_Pnt pf = BRep_Tool::Pnt(f);
1983     gp_Pnt pl = BRep_Tool::Pnt(l);
1984     cout << "\t ( "<< ptr( f ) << " - " << ptr( l )<< " )"
1985          << "\t ( "<< pf.X()<<", "<<pf.Y()<<", "<<pf.Z()<<" ) - "
1986          << " ( "<< pl.X()<<", "<<pl.Y()<<", "<<pl.Z()<<" )"<<endl;
1987   }
1988   else
1989   {
1990     list< _FaceSide >::const_iterator side = myChildren.begin(), sideEnd = myChildren.end();
1991     for ( ; side != sideEnd; ++side ) {
1992       side->Dump();
1993       cout << "\t";
1994     }
1995   }
1996 }