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