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