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