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