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