Salome HOME
Fix compilation errors under Windows: VS-2017
[modules/smesh.git] / src / StdMeshers / StdMeshers_CompositeHexa_3D.cxx
index 7c9dca548a82d1b0f12bd63bec0590e07ca3ecf1..b3e420619c48de4e03a0b0b87ade22bbc5c92696 100644 (file)
@@ -1,4 +1,4 @@
-// Copyright (C) 2007-2015  CEA/DEN, EDF R&D, OPEN CASCADE
+// Copyright (C) 2007-2020  CEA/DEN, EDF R&D, OPEN CASCADE
 //
 // This library is free software; you can redistribute it and/or
 // modify it under the terms of the GNU Lesser General Public
@@ -17,7 +17,7 @@
 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
 //
 
-//  SMESH SMESH : implementaion of SMESH idl descriptions
+//  SMESH SMESH : implementation of SMESH idl descriptions
 // File      : StdMeshers_CompositeHexa_3D.cxx
 // Module    : SMESH
 // Created   : Tue Nov 25 11:04:59 2008
 #include "SMDS_Mesh.hxx"
 #include "SMDS_MeshNode.hxx"
 #include "SMDS_SetIterator.hxx"
+#include "SMESHDS_Mesh.hxx"
+#include "SMESHDS_SubMesh.hxx"
 #include "SMESH_Block.hxx"
 #include "SMESH_Comment.hxx"
 #include "SMESH_ComputeError.hxx"
+#include "SMESH_HypoFilter.hxx"
 #include "SMESH_Mesh.hxx"
 #include "SMESH_MeshAlgos.hxx"
 #include "SMESH_MesherHelper.hxx"
 #include "SMESH_subMesh.hxx"
+#include "StdMeshers_BlockRenumber.hxx"
+#include "StdMeshers_FaceSide.hxx"
+#include "StdMeshers_ViscousLayers.hxx"
 
 #include <BRepAdaptor_Surface.hxx>
 #include <BRep_Tool.hxx>
 #include <list>
 #include <set>
 #include <vector>
+#include <numeric>
+#include <Bnd_B3d.hxx>
 
+using namespace std;
 
 #ifdef _DEBUG_
 // #define DEB_FACES
 // #define DEB_GRID
-// #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;}
+// #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; }
 #endif
 
 #ifndef DUMP_VERT
@@ -80,9 +87,11 @@ enum EQuadSides{ Q_BOTTOM=0, Q_RIGHT, Q_TOP, Q_LEFT,   Q_CHILD, Q_PARENT };
 
 enum EBoxSides{ B_BOTTOM=0, B_RIGHT, B_TOP, B_LEFT, B_FRONT, B_BACK, B_UNDEFINED };
 
+enum EAxes{ COO_X=1, COO_Y, COO_Z };
+
 //================================================================================
 /*!
- * \brief Convertor of a pair of integers to a sole index
+ * \brief Converter of a pair of integers to a sole index
  */
 struct _Indexer
 {
@@ -115,8 +124,9 @@ public:
   bool Contain( const TopoDS_Vertex& vertex ) const;
   void AppendSide( const _FaceSide& side );
   void SetBottomSide( int i );
-  int GetNbSegments(SMESH_Mesh& mesh) const;
-  bool StoreNodes(SMESH_Mesh& mesh, vector<const SMDS_MeshNode*>& myGrid, bool reverse );
+  int GetNbSegments(SMESH_ProxyMesh& mesh, const SMESHDS_SubMesh* smToCheckEdges=0) const;
+  bool StoreNodes(SMESH_ProxyMesh& mesh, vector<const SMDS_MeshNode*>& myGrid,
+                  bool reverse, bool isProxy, const SMESHDS_SubMesh* smToCheckEdges=0 );
   void SetID(EQuadSides id) { myID = id; }
   static inline const TopoDS_TShape* ptr(const TopoDS_Shape& theShape)
   { return theShape.TShape().operator->(); }
@@ -147,7 +157,7 @@ public:
 public: //** Methods to find and orient faces of 6 sides of the box **//
   
   //!< initialization
-  bool Init(const TopoDS_Face& f, SMESH_Mesh& mesh );
+  bool Init(const TopoDS_Face& f, SMESH_ProxyMesh& mesh );
 
   //!< try to unite self with other face
   bool AddContinuousFace( const _QuadFaceGrid& f, const TopTools_MapOfShape& internalEdges );
@@ -159,7 +169,7 @@ public: //** Methods to find and orient faces of 6 sides of the box **//
   _QuadFaceGrid* FindAdjacentForSide(int i, list<_QuadFaceGrid>& faces, EBoxSides id) const;
 
   //!< Reverse edges in order to have the bottom edge going along axes of the unit box
-  void ReverseEdges(/*int e1, int e2*/);
+  void ReverseEdges();
 
   bool IsComplex() const { return !myChildren.empty(); }
 
@@ -174,16 +184,21 @@ public: //** Methods to find and orient faces of 6 sides of the box **//
   TChildIterator GetChildren() const
   { return TChildIterator( myChildren.begin(), myChildren.end()); }
 
+  bool Contain( const TopoDS_Vertex& vertex ) const { return mySides.Contain( vertex ); }
+
 public: //** Loading and access to mesh **//
 
   //!< Load nodes of a mesh
-  bool LoadGrid( SMESH_Mesh& mesh );
+  bool LoadGrid( SMESH_ProxyMesh& mesh );
+
+  //!< Computes normalized parameters of nodes of myGrid
+  void ComputeIJK( int i1, int i2, double v3 );
 
   //!< Return number of segments on the hirizontal sides
-  int GetNbHoriSegments(SMESH_Mesh& mesh, bool withBrothers=false) const;
+  int GetNbHoriSegments(SMESH_ProxyMesh& mesh, bool withBrothers=false) const;
 
   //!< Return number of segments on the vertical sides
-  int GetNbVertSegments(SMESH_Mesh& mesh, bool withBrothers=false) const;
+  int GetNbVertSegments(SMESH_ProxyMesh& mesh, bool withBrothers=false) const;
 
   //!< Return edge on the hirizontal bottom sides
   int GetHoriEdges(vector<TopoDS_Edge> & edges) const;
@@ -194,6 +209,9 @@ public: //** Loading and access to mesh **//
   //!< Return node coordinates by its position
   gp_XYZ GetXYZ(int iHori, int iVert) const;
 
+  //!< Return normalized parameters of nodes within the unitary cube
+  gp_XYZ& GetIJK(int iCol, int iRow) { return myIJK[ myIndexer( iCol, iRow )]; }
+
 public: //** Access to member fields **//
 
   //!< Return i-th face side (0<i<4)
@@ -221,9 +239,9 @@ private:
   bool error(const SMESH_ComputeErrorPtr& err)
   { myError = err; return ( !myError || myError->IsOK() ); }
 
-  bool loadCompositeGrid(SMESH_Mesh& mesh);
+  bool loadCompositeGrid(SMESH_ProxyMesh& mesh);
 
-  bool fillGrid(SMESH_Mesh&                    theMesh,
+  bool fillGrid(SMESH_ProxyMesh&               theMesh,
                 vector<const SMDS_MeshNode*> & theGrid,
                 const _Indexer&                theIndexer,
                 int                            theX,
@@ -243,8 +261,9 @@ private:
   _QuadFaceGrid* myRightBrother;
   _QuadFaceGrid* myUpBrother;
 
-  _Indexer    myIndexer;
+  _Indexer                      myIndexer;
   vector<const SMDS_MeshNode*>  myGrid;
+  vector<gp_XYZ>                myIJK; // normalized parameters of nodes
 
   SMESH_ComputeErrorPtr         myError;
 
@@ -257,8 +276,8 @@ private:
  */
 //================================================================================
 
-StdMeshers_CompositeHexa_3D::StdMeshers_CompositeHexa_3D(int hypId, int studyId, SMESH_Gen* gen)
-  :SMESH_3D_Algo(hypId, studyId, gen)
+StdMeshers_CompositeHexa_3D::StdMeshers_CompositeHexa_3D(int hypId, SMESH_Gen* gen)
+  :SMESH_3D_Algo(hypId, gen), _blockRenumberHyp( nullptr )
 {
   _name = "CompositeHexa_3D";
   _shapeType = (1 << TopAbs_SHELL) | (1 << TopAbs_SOLID);       // 1 bit /shape type
@@ -274,6 +293,7 @@ bool StdMeshers_CompositeHexa_3D::CheckHypothesis(SMESH_Mesh&         aMesh,
                                                   const TopoDS_Shape& aShape,
                                                   Hypothesis_Status&  aStatus)
 {
+  _blockRenumberHyp = nullptr;
   aStatus = HYP_OK;
   return true;
 }
@@ -288,10 +308,10 @@ namespace
    */
   //================================================================================
 
-  bool isContinuousMesh(TopoDS_Edge        E1,
-                        TopoDS_Edge        E2,
-                        const TopoDS_Face& F,
-                        const SMESH_Mesh&  mesh)
+  bool isContinuousMesh(TopoDS_Edge            E1,
+                        TopoDS_Edge            E2,
+                        const TopoDS_Face&     F,
+                        const SMESH_ProxyMesh& mesh)
   {
     if (E1.Orientation() > TopAbs_REVERSED) // INTERNAL
       E1.Orientation( TopAbs_FORWARD );
@@ -302,13 +322,17 @@ namespace
     if ( !TopExp::CommonVertex( E1, E2, V )) return false;
 
     const SMDS_MeshNode* n = SMESH_Algo::VertexNode( V, mesh.GetMeshDS() );
-    if ( !n ) return false;
+    if ( !n ) return SMESH_Algo::IsContinuous( E1, E2 ); // meshed by "composite segment"
+
+    n = mesh.GetProxyNode( n );
 
-    SMESHDS_SubMesh* sm = mesh.GetSubMeshContaining( F )->GetSubMeshDS();
+    const SMESHDS_SubMesh* sm = mesh.GetSubMesh( F );
     if ( !sm ) return false;
 
     int nbQuads = 0;
-    SMDS_ElemIteratorPtr fIt = n->GetInverseElementIterator(SMDSAbs_Face);
+    SMDS_ElemIteratorPtr fIt = mesh.GetInverseElementIterator( n, SMDSAbs_Face );
+    if ( !fIt->more() )
+      return SMESH_Algo::IsContinuous( E1, E2 ); // meshed by "composite segment"
     while ( fIt->more() )
     {
       const SMDS_MeshElement* f = fIt->next();
@@ -322,17 +346,39 @@ namespace
     return nbQuads == 2;
   }
 
+  //================================================================================
+  /*!
+   * \brief Return true if a vertex holds a node and this node is used by some quadrangle
+   */
+  //================================================================================
+
+  // bool isMeshedVertex( TopoDS_Vertex&     V,
+  //                      const SMESH_Mesh&  mesh )
+  // {
+  //   const SMDS_MeshNode* n = SMESH_Algo::VertexNode( V, mesh.GetMeshDS() );
+  //   if ( !n ) return false;
+    
+  //   SMDS_ElemIteratorPtr fIt = n->GetInverseElementIterator(SMDSAbs_Face);
+  //   while ( fIt->more() )
+  //   {
+  //     const SMDS_MeshElement* f = fIt->next();
+  //     if ( f->NbCornerNodes() == 4 )
+  //       return true;
+  //   }
+  //   return false;
+  // }
+
   //================================================================================
   /*!
    * \brief Finds VERTEXes located at block corners
    */
   //================================================================================
 
-  void getBlockCorners( SMESH_Mesh&          mesh,
+  void getBlockCorners( SMESH_ProxyMesh&     mesh,
                         const TopoDS_Shape&  shape,
                         TopTools_MapOfShape& cornerVV)
   {
-    set<int> faceIDs; // ids of FACEs in the shape
+    std::set<int> faceIDs; // ids of FACEs in the shape
     TopExp_Explorer exp;
     for ( exp.Init( shape, TopAbs_FACE ); exp.More(); exp.Next() )
       faceIDs.insert( mesh.GetMeshDS()->ShapeToIndex( exp.Current() ));
@@ -346,13 +392,20 @@ namespace
       const SMDS_MeshNode* n = SMESH_Algo::VertexNode( V, mesh.GetMeshDS() );
       if ( !n ) continue;
 
+      const SMDS_MeshNode* nProxy = mesh.GetProxyNode( n );
+      bool isProxy = ( nProxy != n );
+      n = nProxy;
+
       int nbQuads = 0;
-      SMDS_ElemIteratorPtr fIt = n->GetInverseElementIterator(SMDSAbs_Face);
+      SMDS_ElemIteratorPtr fIt = mesh.GetInverseElementIterator( n, SMDSAbs_Face );
       while ( fIt->more() )
       {
         const SMDS_MeshElement* f = fIt->next();
         if ( !faceIDs.count( f->getshapeId() )) continue;
 
+        if ( isProxy && !mesh.GetSubMesh( f->getshapeId() )->Contains( f ))
+          continue;
+
         if ( f->NbCornerNodes() == 4 )
           ++nbQuads;
         else
@@ -379,7 +432,7 @@ namespace
     TopExp::MapShapes( shape, TopAbs_FACE, subFF );
 
     TopoDS_Vertex VV[2];
-    TopTools_MapOfShape subChecked/*, ridgeEE*/;
+    TopTools_MapOfShape subChecked, ridgeEE;
     TopTools_MapIteratorOfMapOfShape vIt( cornerVV );
     for ( ; vIt.More(); vIt.Next() )
     {
@@ -393,6 +446,8 @@ namespace
         TopoDS_Edge ridgeE = TopoDS::Edge( *riE );
         while ( !ridgeE.IsNull() )
         {
+          if ( !ridgeEE.Add( ridgeE ))
+            break;
           TopExp::Vertices( ridgeE, VV[0], VV[1] );
           TopoDS_Shape V1 = VV[ V0.IsSame( VV[0] )];
           if ( cornerVV.Contains( V1 ) )
@@ -412,6 +467,8 @@ namespace
             {
               if ( !SMESH_MesherHelper::IsSubShape( ridgeE, *F ))
                 continue;
+              if ( !subFF.Contains( *F ))
+                continue;
               if ( isContinuousMesh( ridgeE, TopoDS::Edge( *E ), TopoDS::Face( *F ), mesh ))
               {
                 nextRidgeE = *E;
@@ -443,8 +500,215 @@ namespace
       } // loop on ridge EDGEs around a corner VERTEX
     } // loop on on corner VERTEXes
 
+    if ( subEE.Extent() > ridgeEE.Extent() + internEE.Extent() ) // PAL23269
+      for ( int i = 1; i < subEE.Extent(); ++i )
+        if ( !ridgeEE.Contains( subEE(i) ))
+          internEE.Add( subEE(i) );
+
     return true;
   } // getInternalEdges()
+
+  //================================================================================
+  /*!
+   * \brief Find a face including two given nodes
+   */
+  //================================================================================
+
+  const SMDS_MeshElement* FindFaceByNodes( const SMDS_MeshNode* n1,
+                                           const SMDS_MeshNode* n2,
+                                           TIDSortedElemSet     avoidSet,
+                                           SMESH_ProxyMesh&     mesh)
+  {
+    SMDS_ElemIteratorPtr faceIt = mesh.GetInverseElementIterator( n1, SMDSAbs_Face );
+    while ( faceIt->more() )
+    {
+      const SMDS_MeshElement* f = faceIt->next();
+      if ( !avoidSet.count( f ) && f->GetNodeIndex( n2 ) >= 0 )
+        return f;
+    }
+    return 0;
+  }
+
+  //================================================================================
+  /*!
+   * \brief Check that a segment bounds a face belonging to smOfFaces
+   */
+  //================================================================================
+
+  bool IsSegmentOnSubMeshBoundary( const SMDS_MeshNode*   n1,
+                                   const SMDS_MeshNode*   n2,
+                                   const SMESHDS_SubMesh* smOfFaces,
+                                   SMESH_ProxyMesh&       mesh)
+  {
+    TIDSortedElemSet avoidSet;
+    bool faceFound = false;
+
+    while ( const SMDS_MeshElement* f = FindFaceByNodes( n1, n2, avoidSet, mesh ))
+    {
+      if (( faceFound = smOfFaces->Contains( f )))
+        break;
+      avoidSet.insert( f );
+    }
+    return faceFound;
+  }
+
+    //================================================================================
+  /*!
+   * \brief Rearrange block sides according to StdMeshers_BlockRenumber hypothesis
+   */
+  //================================================================================
+
+  bool arrangeForRenumber( list< _QuadFaceGrid >&     blockSides,
+                           const TopTools_MapOfShape& cornerVertices,
+                           SMESH_Mesh*                mesh,
+                           TopoDS_Vertex&             v000,
+                           TopoDS_Vertex&             v001 )
+  {
+    if ( v000.IsNull() )
+    {
+      // block CS is not defined;
+      // renumber only if the block has an edge parallel to an axis of global CS
+
+      v000 = StdMeshers_RenumberHelper::GetVertex000( cornerVertices );
+    }
+
+    Bnd_B3d bbox;
+    for ( auto it = cornerVertices.cbegin(); it != cornerVertices.cend(); ++it )
+      bbox.Add( BRep_Tool::Pnt( TopoDS::Vertex( *it )));
+    double tol = 1e-5 * Sqrt( bbox.SquareExtent() );
+
+    // get block edges starting at v000
+
+    std::vector< const _FaceSide* > edgesAtV000;
+    std::vector< gp_Vec >           edgeDir;
+    std::vector< int >              iParallel; // 0 - none, 1 - X, 2 - Y, 3 - Z
+    TopTools_MapOfShape             lastVertices;
+    for ( _QuadFaceGrid & quad: blockSides )
+    {
+      for ( int iS = 0; iS < 4 &&  edgesAtV000.size() < 3; ++iS )
+      {
+        const _FaceSide* side = & quad.GetSide( iS );
+        TopoDS_Vertex v1 = side->FirstVertex(), v2 = side->LastVertex();
+        if (( v1.IsSame( v000 ) && !lastVertices.Contains( v2 )) ||
+            ( v2.IsSame( v000 ) && !lastVertices.Contains( v1 )))
+        {
+          bool reverse = v2.IsSame( v000 );
+          if ( reverse )
+            std::swap( v1, v2 );
+          lastVertices.Add( v2 );
+
+          edgesAtV000.push_back( side );
+
+          gp_Pnt pf = BRep_Tool::Pnt( v1 );
+          gp_Pnt pl = BRep_Tool::Pnt( v2 );
+          gp_Vec vec( pf, pl );
+          edgeDir.push_back( vec );
+
+          iParallel.push_back( 0 );
+          if ( !v001.IsNull() )
+          {
+            if ( quad.IsComplex() )
+              for ( _QuadFaceGrid::TChildIterator chIt = quad.GetChildren(); chIt.more(); )
+              {
+                const _QuadFaceGrid& child = chIt.next();
+                if ( child.GetSide( iS ).Contain( v001 ))
+                {
+                  iParallel.back() = 3;
+                  break;
+                }
+              }
+            else if ( side->Contain( v001 ))
+              iParallel.back() = 3;
+          }
+          else
+          {
+            bool isStraight = true;
+            std::list< TopoDS_Edge > edges;
+            for ( int iE = 0; true; ++iE )
+            {
+              TopoDS_Edge edge = side->Edge( iE );
+              if ( edge.IsNull() )
+                break;
+              edges.push_back( edge );
+              if ( isStraight )
+                isStraight = SMESH_Algo::IsStraight( edge );
+            }
+            // is parallel to a GCS axis?
+            if ( isStraight )
+            {
+              int nbDiff = (( Abs( vec.X() ) > tol ) +
+                            ( Abs( vec.Y() ) > tol ) +
+                            ( Abs( vec.Z() ) > tol ) );
+              if ( nbDiff == 1 )
+                iParallel.back() = ( Abs( vec.X() ) > tol ) ? 1 : ( Abs( vec.Y() ) > tol ) ? 2 : 3;
+            }
+            else
+            {
+              TopoDS_Face nullFace;
+              StdMeshers_FaceSide fSide( nullFace, edges, mesh, true, true );
+              edgeDir.back() = gp_Vec( pf, fSide.Value3d( reverse ? 0.99 : 0.01 ));
+            }
+          }
+        }
+      }
+    }
+    if ( std::accumulate( iParallel.begin(), iParallel.end(), 0 ) == 0 )
+      return false;
+
+    // find edge OZ and edge OX
+    const _FaceSide* edgeOZ = nullptr, *edgeOY = nullptr, *edgeOX = nullptr;
+    auto iZIt = std::find( iParallel.begin(), iParallel.end(), 3 );
+    if ( iZIt != iParallel.end() )
+    {
+      int i = std::distance( iParallel.begin(), iZIt );
+      edgeOZ = edgesAtV000[ i ];
+      int iE1 = SMESH_MesherHelper::WrapIndex( i + 1, edgesAtV000.size() );
+      int iE2 = SMESH_MesherHelper::WrapIndex( i + 2, edgesAtV000.size() );
+      if (( edgeDir[ iE1 ] ^ edgeDir[ iE2 ] ) * edgeDir[ i ] < 0 )
+        std::swap( iE1, iE2 );
+      edgeOX = edgesAtV000[ iE1 ];
+      edgeOY = edgesAtV000[ iE2 ];
+    }
+    else
+    {
+      for ( size_t i = 0; i < edgesAtV000.size(); ++i )
+      {
+        if ( !iParallel[ i ] )
+          continue;
+        int iE1 = SMESH_MesherHelper::WrapIndex( i + 1, edgesAtV000.size() );
+        int iE2 = SMESH_MesherHelper::WrapIndex( i + 2, edgesAtV000.size() );
+        if (( edgeDir[ iE1 ] ^ edgeDir[ iE2 ] ) * edgeDir[ i ] < 0 )
+          std::swap( iE1, iE2 );
+        edgeOZ = edgesAtV000[ iParallel[i] == 1 ? iE2 : iE1 ];
+        edgeOX = edgesAtV000[ iParallel[i] == 1 ? i : iE1 ];
+        edgeOY = edgesAtV000[ iParallel[i] == 1 ? iE1 : i ];
+        break;
+      }
+    }
+
+    if ( !edgeOZ || !edgeOX || !edgeOY )
+      return false;
+
+    TopoDS_Vertex v100 = edgeOX->LastVertex();
+    if ( v100.IsSame( v000 ))
+      v100 = edgeOX->FirstVertex();
+
+    // Find the left quad, one including v000 but not v100
+
+    for ( auto quad = blockSides.begin(); quad != blockSides.end(); ++quad )
+    {
+      if ( quad->Contain( v000 ) && !quad->Contain( v100 )) // it's a left quad
+      {
+        if ( quad != blockSides.begin() )
+          blockSides.splice( blockSides.begin(), blockSides, quad );
+        blockSides.front().SetBottomSide( *edgeOZ ); // edgeOY
+
+        return true;
+      }
+    }
+    return false;
+  }
+
 } // namespace
 
 //================================================================================
@@ -456,6 +720,8 @@ namespace
 bool StdMeshers_CompositeHexa_3D::findBoxFaces( const TopoDS_Shape&    shape,
                                                 list< _QuadFaceGrid >& boxFaces,
                                                 SMESH_Mesh&            mesh,
+                                                SMESH_ProxyMesh&       proxyMesh,
+                                                bool&                  toRenumber,
                                                 _QuadFaceGrid * &      fBottom,
                                                 _QuadFaceGrid * &      fTop,
                                                 _QuadFaceGrid * &      fFront,
@@ -464,7 +730,7 @@ bool StdMeshers_CompositeHexa_3D::findBoxFaces( const TopoDS_Shape&    shape,
                                                 _QuadFaceGrid * &      fRight)
 {
   TopTools_MapOfShape cornerVertices;
-  getBlockCorners( mesh, shape, cornerVertices );
+  getBlockCorners( proxyMesh, shape, cornerVertices );
   if ( cornerVertices.Extent() != 8 )
     return error( COMPERR_BAD_INPUT_MESH, "Can't find 8 corners of a block by 2D mesh" );
   TopTools_MapOfShape internalEdges;
@@ -477,7 +743,7 @@ bool StdMeshers_CompositeHexa_3D::findBoxFaces( const TopoDS_Shape&    shape,
   for ( exp.Init( shape, TopAbs_FACE ); exp.More(); exp.Next(), ++nbFaces )
   {
     _QuadFaceGrid f;
-    if ( !f.Init( TopoDS::Face( exp.Current() ), mesh ))
+    if ( !f.Init( TopoDS::Face( exp.Current() ), proxyMesh ))
       return error (COMPERR_BAD_SHAPE);
 
     _QuadFaceGrid* prevContinuous = 0;
@@ -506,8 +772,24 @@ bool StdMeshers_CompositeHexa_3D::findBoxFaces( const TopoDS_Shape&    shape,
     boxFaces.resize( 6 );
     boxFace = boxFaces.begin();
     for ( exp.Init( shape, TopAbs_FACE); exp.More(); exp.Next(), ++boxFace )
-      boxFace->Init( TopoDS::Face( exp.Current() ), mesh );
+      boxFace->Init( TopoDS::Face( exp.Current() ), proxyMesh );
+  }
+
+  toRenumber = _blockRenumberHyp;
+  if ( toRenumber )
+  {
+    TopoDS_Vertex v000, v001;
+    _blockRenumberHyp->IsSolidIncluded( mesh, shape, v000, v001 );
+
+    toRenumber = arrangeForRenumber( boxFaces, cornerVertices, &mesh, v000, v001 );
+
+    if ( toRenumber )
+    {
+      mesh.GetMeshDS()->Modified();
+      mesh.GetMeshDS()->CompactMesh(); // remove numbering holes
+    }
   }
+  
   // ----------------------------------------
   // Find out position of faces within a box
   // ----------------------------------------
@@ -547,7 +829,7 @@ bool StdMeshers_CompositeHexa_3D::findBoxFaces( const TopoDS_Shape&    shape,
   if ( !fTop )
     return error(COMPERR_BAD_SHAPE);
 
-  // orient bottom egde of faces along axes of the unit box
+  // orient bottom edge of faces along axes of the unit box
   fBottom->ReverseEdges();
   fBack  ->ReverseEdges();
   fLeft  ->ReverseEdges();
@@ -560,7 +842,7 @@ bool StdMeshers_CompositeHexa_3D::findBoxFaces( const TopoDS_Shape&    shape,
  * \brief Computes hexahedral mesh on a box with composite sides
  *  \param aMesh - mesh to compute
  *  \param aShape - shape to mesh
- *  \retval bool - succes sign
+ *  \retval bool - success sign
  */
 //================================================================================
 
@@ -571,12 +853,23 @@ bool StdMeshers_CompositeHexa_3D::Compute(SMESH_Mesh&         theMesh,
   _quadraticMesh = helper.IsQuadraticSubMesh( theShape );
   helper.SetElementsOnShape( true );
 
+  // get Viscous Mesh
+  SMESH_ProxyMesh::Ptr proxyMesh;
+  SMESH_HypoFilter vlFilter( SMESH_HypoFilter::HasName( StdMeshers_ViscousLayers::GetHypType() ));
+  const SMESH_Hypothesis *          hyp = theMesh.GetHypothesis( theShape, vlFilter, true );
+  const StdMeshers_ViscousLayers* vlHyp = static_cast< const StdMeshers_ViscousLayers* >( hyp );
+  if ( vlHyp )
+    proxyMesh = vlHyp->Compute( theMesh, theShape, /*toMakeN2NMap=*/true );
+  else
+    proxyMesh.reset( new SMESH_ProxyMesh( theMesh ));
+
   // -------------------------
   // Try to find 6 side faces
   // -------------------------
   list< _QuadFaceGrid > boxFaceContainer;
+  bool toRenumber = false;
   _QuadFaceGrid *fBottom, *fTop, *fFront, *fBack, *fLeft, *fRight;
-  if ( ! findBoxFaces( theShape, boxFaceContainer, theMesh,
+  if ( ! findBoxFaces( theShape, boxFaceContainer, theMesh, *proxyMesh, toRenumber,
                        fBottom, fTop, fFront, fBack, fLeft, fRight))
     return false;
 
@@ -585,16 +878,26 @@ bool StdMeshers_CompositeHexa_3D::Compute(SMESH_Mesh&         theMesh,
   // ------------------------------------------
 
   // let faces load their grids
-  if ( !fBottom->LoadGrid( theMesh )) return error( fBottom->GetError() );
-  if ( !fBack  ->LoadGrid( theMesh )) return error( fBack  ->GetError() );
-  if ( !fLeft  ->LoadGrid( theMesh )) return error( fLeft  ->GetError() );
-  if ( !fFront ->LoadGrid( theMesh )) return error( fFront ->GetError() );
-  if ( !fRight ->LoadGrid( theMesh )) return error( fRight ->GetError() );
-  if ( !fTop   ->LoadGrid( theMesh )) return error( fTop   ->GetError() );
-
-  int x, xSize = fBottom->GetNbHoriSegments(theMesh) + 1, X = xSize - 1;
-  int y, ySize = fBottom->GetNbVertSegments(theMesh) + 1, Y = ySize - 1;
-  int z, zSize = fFront ->GetNbVertSegments(theMesh) + 1, Z = zSize - 1;
+  if ( !fBottom->LoadGrid( *proxyMesh )) return error( fBottom->GetError() );
+  if ( !fBack  ->LoadGrid( *proxyMesh )) return error( fBack  ->GetError() );
+  if ( !fLeft  ->LoadGrid( *proxyMesh )) return error( fLeft  ->GetError() );
+  if ( !fFront ->LoadGrid( *proxyMesh )) return error( fFront ->GetError() );
+  if ( !fRight ->LoadGrid( *proxyMesh )) return error( fRight ->GetError() );
+  if ( !fTop   ->LoadGrid( *proxyMesh )) return error( fTop   ->GetError() );
+
+  // compute normalized parameters of nodes on sides (PAL23189)
+  fBottom->ComputeIJK( COO_X, COO_Y, /*z=*/0. );
+  fBack  ->ComputeIJK( COO_X, COO_Z, /*y=*/1. );
+  fLeft  ->ComputeIJK( COO_Y, COO_Z, /*x=*/0. );
+  fFront ->ComputeIJK( COO_X, COO_Z, /*y=*/0. );
+  fRight ->ComputeIJK( COO_Y, COO_Z, /*x=*/1. );
+  fTop   ->ComputeIJK( COO_X, COO_Y, /*z=*/1. );
+
+  StdMeshers_RenumberHelper renumHelper( theMesh, _blockRenumberHyp );
+
+  int x, xSize = fBottom->GetNbHoriSegments(*proxyMesh) + 1, X = xSize - 1;
+  int y, ySize = fBottom->GetNbVertSegments(*proxyMesh) + 1, Y = ySize - 1;
+  int z, zSize = fFront ->GetNbVertSegments(*proxyMesh) + 1, Z = zSize - 1;
   _Indexer colIndex( xSize, ySize );
   vector< vector< const SMDS_MeshNode* > > columns( colIndex.size() );
 
@@ -647,13 +950,29 @@ bool StdMeshers_CompositeHexa_3D::Compute(SMESH_Mesh&         theMesh,
   pointsOnShapes[ SMESH_Block::ID_V011 ] = fTop->GetXYZ( 0, Y );
   pointsOnShapes[ SMESH_Block::ID_V111 ] = fTop->GetXYZ( X, Y );
 
-  for ( x = 1; x < xSize-1; ++x )
+  gp_XYZ params; // normalized parameters of an internal node within the unit box
+
+  if ( toRenumber )
+    for ( y = 0; y < ySize; ++y )
+    {
+      vector< const SMDS_MeshNode* >& columnXy = columns[ colIndex( X, y )];
+      for ( z = 0; z < zSize; ++z )
+        renumHelper.AddReplacingNode( columnXy[ z ] );
+    }
+
+  for ( x = X-1; x > 0; --x )
   {
-    gp_XYZ params; // normalized parameters of internal node within a unit box
-    params.SetCoord( 1, x / double(X) );
+    if ( toRenumber )
+    {
+      vector< const SMDS_MeshNode* >& columnX0 = columns[ colIndex( x, 0 )];
+      for ( z = 0; z < zSize; ++z )
+        renumHelper.AddReplacingNode( columnX0[ z ] );
+    }
+
+    const double rX = x / double(X);
     for ( y = 1; y < ySize-1; ++y )
     {
-      params.SetCoord( 2, y / double(Y) );
+      const double rY = y / double(Y);
       // column to fill during z loop
       vector< const SMDS_MeshNode* >& column = columns[ colIndex( x, y )];
       // points projections on horizontal edges
@@ -668,16 +987,34 @@ bool StdMeshers_CompositeHexa_3D::Compute(SMESH_Mesh&         theMesh,
       // points projections on horizontal faces
       pointsOnShapes[ SMESH_Block::ID_Fxy0 ] = fBottom->GetXYZ( x, y );
       pointsOnShapes[ SMESH_Block::ID_Fxy1 ] = fTop   ->GetXYZ( x, y );
+
+      if ( toRenumber )
+        renumHelper.AddReplacingNode( column[ 0 ] );
+
       for ( z = 1; z < zSize-1; ++z ) // z loop
       {
-        params.SetCoord( 3, z / double(Z) );
+        // compute normalized parameters of an internal node within the unit box
+        const double   rZ = z / double(Z);
+        const gp_XYZ& pBo = fBottom->GetIJK( x, y );
+        const gp_XYZ& pTo = fTop   ->GetIJK( x, y );
+        const gp_XYZ& pFr = fFront ->GetIJK( x, z );
+        const gp_XYZ& pBa = fBack  ->GetIJK( x, z );
+        const gp_XYZ& pLe = fLeft  ->GetIJK( y, z );
+        const gp_XYZ& pRi = fRight ->GetIJK( y, z );
+        params.SetCoord( 1, 0.5 * ( pBo.X() * ( 1. - rZ ) + pTo.X() * rZ  +
+                                    pFr.X() * ( 1. - rY ) + pBa.X() * rY ));
+        params.SetCoord( 2, 0.5 * ( pBo.Y() * ( 1. - rZ ) + pTo.Y() * rZ  +
+                                    pLe.Y() * ( 1. - rX ) + pRi.Y() * rX ));
+        params.SetCoord( 3, 0.5 * ( pFr.Z() * ( 1. - rY ) + pBa.Z() * rY  +
+                                    pLe.Z() * ( 1. - rX ) + pRi.Z() * rX ));
+
         // point projections on vertical edges
-        pointsOnShapes[ SMESH_Block::ID_E00z ] = fFront->GetXYZ( 0, z );    
-        pointsOnShapes[ SMESH_Block::ID_E10z ] = fFront->GetXYZ( X, z );    
-        pointsOnShapes[ SMESH_Block::ID_E01z ] = fBack->GetXYZ( 0, z );    
+        pointsOnShapes[ SMESH_Block::ID_E00z ] = fFront->GetXYZ( 0, z );
+        pointsOnShapes[ SMESH_Block::ID_E10z ] = fFront->GetXYZ( X, z );
+        pointsOnShapes[ SMESH_Block::ID_E01z ] = fBack->GetXYZ( 0, z );
         pointsOnShapes[ SMESH_Block::ID_E11z ] = fBack->GetXYZ( X, z );
         // point projections on vertical faces
-        pointsOnShapes[ SMESH_Block::ID_Fx0z ] = fFront->GetXYZ( x, z );    
+        pointsOnShapes[ SMESH_Block::ID_Fx0z ] = fFront->GetXYZ( x, z );
         pointsOnShapes[ SMESH_Block::ID_Fx1z ] = fBack ->GetXYZ( x, z );    
         pointsOnShapes[ SMESH_Block::ID_F0yz ] = fLeft ->GetXYZ( y, z );    
         pointsOnShapes[ SMESH_Block::ID_F1yz ] = fRight->GetXYZ( y, z );
@@ -698,16 +1035,35 @@ bool StdMeshers_CompositeHexa_3D::Compute(SMESH_Mesh&         theMesh,
         //cout << "Params: ( "<< params.X()<<", "<<params.Y()<<", "<<params.Z()<<" )"<<endl;
         //cout << "coords: ( "<< coords.X()<<", "<<coords.Y()<<", "<<coords.Z()<<" )"<<endl;
 #endif
-      }
+      } // z loop
+      if ( toRenumber )
+        renumHelper.AddReplacingNode( column[ Z ] );
+
+    } // y loop
+    if ( toRenumber )
+    {
+      vector< const SMDS_MeshNode* >& columnXY = columns[ colIndex( x, Y )];
+      for ( z = 0; z < zSize; ++z )
+        renumHelper.AddReplacingNode( columnXY[ z ] );
     }
-  }
+  } // for ( x = X-1; x > 0; --x )
+
+  if ( toRenumber )
+    for ( y = 0; y < ySize; ++y )
+    {
+      vector< const SMDS_MeshNode* >& column0Y = columns[ colIndex( 0, y )];
+      for ( z = 0; z < zSize; ++z )
+        renumHelper.AddReplacingNode( column0Y[ z ] );
+    }
+
+
   // faces no more needed, free memory
   boxFaceContainer.clear();
 
   // ----------------
   // Add hexahedrons
   // ----------------
-  for ( x = 0; x < xSize-1; ++x ) {
+  for ( x = xSize-2; true; --x ) {
     for ( y = 0; y < ySize-1; ++y ) {
       vector< const SMDS_MeshNode* >& col00 = columns[ colIndex( x, y )];
       vector< const SMDS_MeshNode* >& col10 = columns[ colIndex( x+1, y )];
@@ -716,11 +1072,22 @@ bool StdMeshers_CompositeHexa_3D::Compute(SMESH_Mesh&         theMesh,
       for ( z = 0; z < zSize-1; ++z )
       {
         // bottom face normal of a hexa mush point outside the volume
-        helper.AddVolume(col00[z],   col01[z],   col11[z],   col10[z],
-                         col00[z+1], col01[z+1], col11[z+1], col10[z+1]);
+        helper.AddVolume(col10[z], col11[z], col11[z+1], col10[z+1],
+                         col00[z], col01[z], col01[z+1], col00[z+1]);
       }
     }
+    if ( x == 0)
+      break;
+
+  }
+  if ( toRenumber )
+    renumHelper.DoReplaceNodes();
+
+  if ( _blockRenumberHyp )
+  {
+    return error( _blockRenumberHyp->CheckHypothesis( theMesh, theShape ));
   }
+
   return true;
 }
 
@@ -734,12 +1101,15 @@ bool StdMeshers_CompositeHexa_3D::Evaluate(SMESH_Mesh&         theMesh,
                                            const TopoDS_Shape& theShape,
                                            MapShapeNbElems&    aResMap)
 {
+  SMESH_ProxyMesh::Ptr proxyMesh( new SMESH_ProxyMesh( theMesh ));
+
   // -------------------------
   // Try to find 6 side faces
   // -------------------------
   list< _QuadFaceGrid > boxFaceContainer;
   _QuadFaceGrid *fBottom, *fTop, *fFront, *fBack, *fLeft, *fRight;
-  if ( ! findBoxFaces( theShape, boxFaceContainer, theMesh,
+  bool toRenumber = false;
+  if ( ! findBoxFaces( theShape, boxFaceContainer, theMesh, *proxyMesh, toRenumber,
                        fBottom, fTop, fFront, fBack, fLeft, fRight))
     return false;
 
@@ -762,7 +1132,7 @@ bool StdMeshers_CompositeHexa_3D::Evaluate(SMESH_Mesh&         theMesh,
       nbSeg1 += Max( nbElems[ SMDSEntity_Edge ], nbElems[ SMDSEntity_Quad_Edge ]);
   }
 
-  // Get an 1D size of a box side ortogonal to lessComplexSide
+  // Get an 1D size of a box side orthogonal to lessComplexSide
   int nbSeg2 = 0;
   _QuadFaceGrid* ortoSide =
     lessComplexSide->FindAdjacentForSide( Q_LEFT, boxFaceContainer, B_UNDEFINED );
@@ -775,7 +1145,7 @@ bool StdMeshers_CompositeHexa_3D::Evaluate(SMESH_Mesh&         theMesh,
       nbSeg2 += Max( nbElems[ SMDSEntity_Edge ], nbElems[ SMDSEntity_Quad_Edge ]);
   }
 
-  // Get an 2D size of a box side ortogonal to lessComplexSide
+  // Get an 2D size of a box side orthogonal to lessComplexSide
   int nbFaces = 0, nbQuadFace = 0;
   list< TopoDS_Face > sideFaces;
   if ( ortoSide->IsComplex() )
@@ -825,7 +1195,7 @@ _QuadFaceGrid::_QuadFaceGrid():
  */
 //================================================================================
 
-bool _QuadFaceGrid::Init(const TopoDS_Face& f, SMESH_Mesh& mesh)
+bool _QuadFaceGrid::Init(const TopoDS_Face& f, SMESH_ProxyMesh& mesh)
 {
   myFace         = f;
   mySides        = _FaceSide();
@@ -853,14 +1223,10 @@ bool _QuadFaceGrid::Init(const TopoDS_Face& f, SMESH_Mesh& mesh)
     while ( !edges.empty()) {
       sideEdges.clear();
       sideEdges.splice( sideEdges.end(), edges, edges.begin());// edges.front()->sideEdges.back()
+      if ( SMESH_Algo::isDegenerated( sideEdges.back() ))
+        continue;
       while ( !edges.empty() ) {
-        if ( SMESH_Algo::IsContinuous( sideEdges.back(), edges.front() )) {
-          sideEdges.splice( sideEdges.end(), edges, edges.begin());
-        }
-        else if ( SMESH_Algo::IsContinuous( sideEdges.front(), edges.back() )) {
-          sideEdges.splice( sideEdges.begin(), edges, --edges.end());
-        }
-        else if ( isContinuousMesh( sideEdges.back(), edges.front(), f, mesh )) {
+        if ( isContinuousMesh( sideEdges.back(), edges.front(), f, mesh )) {
           sideEdges.splice( sideEdges.end(), edges, edges.begin());
         }
         else if ( isContinuousMesh( sideEdges.front(), edges.back(), f, mesh )) {
@@ -899,7 +1265,7 @@ bool _QuadFaceGrid::AddContinuousFace( const _QuadFaceGrid&       other,
   {
     const _FaceSide& otherSide = other.GetSide( i );
     int iMyCommon;
-    if ( mySides.Contain( otherSide, &iMyCommon ) )
+    if ( mySides.Contain( otherSide, &iMyCommon ))
     {
       if ( internalEdges.Contains( otherSide.Edge( 0 )))
       {
@@ -907,13 +1273,23 @@ bool _QuadFaceGrid::AddContinuousFace( const _QuadFaceGrid&       other,
         DUMP_VERT("Cont 2", mySides.GetSide(iMyCommon)->LastVertex());
         DUMP_VERT("Cont 3", otherSide.FirstVertex());
         DUMP_VERT("Cont 4", otherSide.LastVertex());
-        if ( myChildren.empty() ) {
+
+        if ( myChildren.empty() )
+        {
           myChildren.push_back( *this );
           myFace.Nullify();
         }
+        else // find iMyCommon in myChildren
+        {
+          for ( TChildIterator children = GetChildren(); children.more(); ) {
+            const _QuadFaceGrid& child = children.next();
+            if ( child.mySides.Contain( otherSide, &iMyCommon ))
+              break;
+          }
+        }
 
         // orient new children equally
-        int otherBottomIndex = ( 4 + i - iMyCommon + 2 ) % 4;
+        int otherBottomIndex = SMESH_MesherHelper::WrapIndex( i - iMyCommon + 2, 4 );
         if ( other.IsComplex() )
           for ( TChildIterator children = other.GetChildren(); children.more(); ) {
             myChildren.push_back( children.next() );
@@ -930,7 +1306,7 @@ bool _QuadFaceGrid::AddContinuousFace( const _QuadFaceGrid&       other,
         if ( other.IsComplex() )
           for ( TChildIterator children = other.GetChildren(); children.more(); )
           {
-            const _QuadFaceGrid& child =  children.next();
+            const _QuadFaceGrid& child = children.next();
             for ( int i = 0; i < 4; ++i )
               mySides.AppendSide( child.GetSide(i) );
           }
@@ -972,9 +1348,9 @@ bool _QuadFaceGrid::SetBottomSide(const _FaceSide& bottom, int* sideIndex)
     {
       if ( childFace->SetBottomSide( bottom, &myBottomIndex ))
       {
-        TChildren::iterator orientedCild = childFace;
+        TChildren::iterator orientedChild = childFace;
         for ( childFace = myChildren.begin(); childFace != childEnd; ++childFace ) {
-          if ( childFace != orientedCild )
+          if ( childFace != orientedChild )
             childFace->SetBottomSide( childFace->GetSide( myBottomIndex ));
         }
         if ( sideIndex )
@@ -1046,7 +1422,7 @@ const _FaceSide& _QuadFaceGrid::GetSide(int i) const
  */
 //================================================================================
 
-void _QuadFaceGrid::ReverseEdges(/*int e1, int e2*/)
+void _QuadFaceGrid::ReverseEdges()
 {
   myReverse = !myReverse;
 
@@ -1057,8 +1433,6 @@ void _QuadFaceGrid::ReverseEdges(/*int e1, int e2*/)
 
   if ( myChildren.empty() )
   {
-//     mySides.GetSide( e1 )->Reverse();
-//     mySides.GetSide( e2 )->Reverse();
     DumpVertices();
   }
   else
@@ -1066,7 +1440,7 @@ void _QuadFaceGrid::ReverseEdges(/*int e1, int e2*/)
     DumpVertices();
     TChildren::iterator child = myChildren.begin(), childEnd = myChildren.end();
     for ( ; child != childEnd; ++child )
-      child->ReverseEdges( /*e1, e2*/ );
+      child->ReverseEdges();
   }
 }
 
@@ -1076,7 +1450,7 @@ void _QuadFaceGrid::ReverseEdges(/*int e1, int e2*/)
  */
 //================================================================================
 
-bool _QuadFaceGrid::LoadGrid( SMESH_Mesh& mesh )
+bool _QuadFaceGrid::LoadGrid( SMESH_ProxyMesh& mesh )
 {
   if ( !myChildren.empty() )
   {
@@ -1098,27 +1472,36 @@ bool _QuadFaceGrid::LoadGrid( SMESH_Mesh& mesh )
   if ( !myGrid.empty() )
     return true;
 
-  SMESHDS_SubMesh* faceSubMesh = mesh.GetSubMesh( myFace )->GetSubMeshDS();
+  const SMESHDS_SubMesh* faceSubMesh = mesh.GetSubMesh( myFace );
+
   // check that all faces are quadrangular
   SMDS_ElemIteratorPtr fIt = faceSubMesh->GetElements();
   while ( fIt->more() )
     if ( fIt->next()->NbNodes() % 4 > 0 )
       return error("Non-quadrangular mesh faces are not allowed on sides of a composite block");
-  
-  myIndexer._xSize = 1 + mySides.GetSide( Q_BOTTOM )->GetNbSegments( mesh );
-  myIndexer._ySize = 1 + mySides.GetSide( Q_LEFT   )->GetNbSegments( mesh );
+
+  bool isProxy, isTmpElem;
+  if ( faceSubMesh && faceSubMesh->NbElements() > 0 )
+  {
+    isProxy   = dynamic_cast< const SMESH_ProxyMesh::SubMesh* >( faceSubMesh );
+    isTmpElem = mesh.IsTemporary( faceSubMesh->GetElements()->next() );
+  }
+  const SMESHDS_SubMesh* smToCheckEdges = ( isProxy && !isTmpElem ) ? faceSubMesh : 0;
+
+  myIndexer._xSize = 1 + mySides.GetSide( Q_BOTTOM )->GetNbSegments( mesh, smToCheckEdges );
+  myIndexer._ySize = 1 + mySides.GetSide( Q_LEFT   )->GetNbSegments( mesh, smToCheckEdges );
 
   myGrid.resize( myIndexer.size() );
 
-  // strore nodes bound to the bottom edge
-  mySides.GetSide( Q_BOTTOM )->StoreNodes( mesh, myGrid, myReverse );
+  // store nodes bound to the bottom edge
+  mySides.GetSide( Q_BOTTOM )->StoreNodes( mesh, myGrid, myReverse, isProxy, smToCheckEdges );
 
   // store the rest nodes row by row
 
-  TIDSortedElemSet emptySet, avoidSet;
+  TIDSortedElemSet avoidSet;
   const SMDS_MeshElement* firstQuad = 0; // most left face above the last row of found nodes
 
-  int nbFoundNodes = myIndexer._xSize;
+  size_t nbFoundNodes = myIndexer._xSize;
   while ( nbFoundNodes != myGrid.size() )
   {
     // first and last nodes of the last filled row of nodes
@@ -1134,10 +1517,10 @@ bool _QuadFaceGrid::LoadGrid( SMESH_Mesh& mesh )
     //     o---o  o  o  o  o
     //n1down    n2down
     //
-    firstQuad = SMESH_MeshAlgos::FindFaceInSet( n1down, n2down, emptySet, avoidSet);
+    firstQuad = FindFaceByNodes( n1down, n2down, avoidSet, mesh );
     while ( firstQuad && !faceSubMesh->Contains( firstQuad )) {
       avoidSet.insert( firstQuad );
-      firstQuad = SMESH_MeshAlgos::FindFaceInSet( n1down, n2down, emptySet, avoidSet);
+      firstQuad = FindFaceByNodes( n1down, n2down, avoidSet, mesh);
     }
     if ( !firstQuad || !faceSubMesh->Contains( firstQuad ))
       return error(ERR_LI("Error in _QuadFaceGrid::LoadGrid()"));
@@ -1167,7 +1550,7 @@ bool _QuadFaceGrid::LoadGrid( SMESH_Mesh& mesh )
     {
       // next face
       avoidSet.clear(); avoidSet.insert( quad );
-      quad = SMESH_MeshAlgos::FindFaceInSet( n1down, n1up, emptySet, avoidSet );
+      quad = FindFaceByNodes( n1down, n1up, avoidSet, mesh );
       if ( !quad || quad->NbNodes() % 4 > 0)
         return error(ERR_LI("Error in _QuadFaceGrid::LoadGrid()"));
 
@@ -1187,6 +1570,53 @@ bool _QuadFaceGrid::LoadGrid( SMESH_Mesh& mesh )
   return true;
 }
 
+//================================================================================
+/*!
+ * \brief Fill myIJK with normalized parameters of nodes in myGrid
+ *  \param [in] i1 - coordinate index along rows of myGrid
+ *  \param [in] i2 - coordinate index along columns of myGrid
+ *  \param [in] v3 - value of the constant parameter
+ */
+//================================================================================
+
+void _QuadFaceGrid::ComputeIJK( int i1, int i2, double v3 )
+{
+  gp_XYZ ijk( v3, v3, v3 );
+  myIJK.resize( myIndexer.size(), ijk );
+
+  const size_t nbCol = myIndexer._xSize;
+  const size_t nbRow = myIndexer._ySize;
+
+  vector< double > len( nbRow );
+  len[0] = 0;
+  for ( size_t i = 0; i < nbCol; ++i )
+  {
+    gp_Pnt pPrev = GetXYZ( i, 0 );
+    for ( size_t j = 1; j < nbRow; ++j )
+    {
+      gp_Pnt p = GetXYZ( i, j );
+      len[ j ] = len[ j-1 ] + p.Distance( pPrev );
+      pPrev = p;
+    }
+    for ( size_t j = 0; j < nbRow; ++j )
+      GetIJK( i, j ).SetCoord( i2, len[ j ]/len.back() );
+  }
+
+  len.resize( nbCol );
+  for ( size_t j = 0; j < nbRow; ++j )
+  {
+    gp_Pnt pPrev = GetXYZ( 0, j );
+    for ( size_t i = 1; i < nbCol; ++i )
+    {
+      gp_Pnt p = GetXYZ( i, j );
+      len[ i ] = len[ i-1 ] + p.Distance( pPrev );
+      pPrev = p;
+    }
+    for ( size_t i = 0; i < nbCol; ++i )
+      GetIJK( i, j ).SetCoord( i1, len[ i ]/len.back() );
+  }
+}
+
 //================================================================================
 /*!
  * \brief Find out mutual location of children: find their right and up brothers
@@ -1237,7 +1667,7 @@ bool _QuadFaceGrid::locateChildren()
  */
 //================================================================================
 
-bool _QuadFaceGrid::loadCompositeGrid(SMESH_Mesh& mesh)
+bool _QuadFaceGrid::loadCompositeGrid(SMESH_ProxyMesh& mesh)
 {
   // Find out mutual location of children: find their right and up brothers
   if ( !locateChildren() )
@@ -1246,13 +1676,13 @@ bool _QuadFaceGrid::loadCompositeGrid(SMESH_Mesh& mesh)
   // Load nodes according to mutual location of children
 
   // grid size
-  myIndexer._xSize = 1 + myLeftBottomChild->GetNbHoriSegments(mesh, /*withBrothers=*/true);
-  myIndexer._ySize = 1 + myLeftBottomChild->GetNbVertSegments(mesh, /*withBrothers=*/true);
+  myIndexer._xSize = 1 + myLeftBottomChild->GetNbHoriSegments( mesh, /*withBrothers=*/true );
+  myIndexer._ySize = 1 + myLeftBottomChild->GetNbVertSegments( mesh, /*withBrothers=*/true );
 
   myGrid.resize( myIndexer.size() );
 
   int fromX = myReverse ? myIndexer._xSize : 0;
-  if (!myLeftBottomChild->fillGrid( mesh, myGrid, myIndexer, fromX, 0 ))
+  if ( !myLeftBottomChild->fillGrid( mesh, myGrid, myIndexer, fromX, 0 ))
     return error( myLeftBottomChild->GetError() );
 
   DumpGrid();
@@ -1314,7 +1744,7 @@ void _QuadFaceGrid::setBrothers( set< _QuadFaceGrid* >& notLocatedBrothers )
  */
 //================================================================================
 
-bool _QuadFaceGrid::fillGrid(SMESH_Mesh&                    theMesh,
+bool _QuadFaceGrid::fillGrid(SMESH_ProxyMesh&               theMesh,
                              vector<const SMDS_MeshNode*> & theGrid,
                              const _Indexer&                theIndexer,
                              int                            theX,
@@ -1357,7 +1787,7 @@ bool _QuadFaceGrid::fillGrid(SMESH_Mesh&                    theMesh,
  */
 //================================================================================
 
-int _QuadFaceGrid::GetNbHoriSegments(SMESH_Mesh& mesh, bool withBrothers) const
+int _QuadFaceGrid::GetNbHoriSegments(SMESH_ProxyMesh& mesh, bool withBrothers) const
 {
   int nbSegs = 0;
   if ( myLeftBottomChild )
@@ -1366,7 +1796,7 @@ int _QuadFaceGrid::GetNbHoriSegments(SMESH_Mesh& mesh, bool withBrothers) const
   }
   else
   {
-    nbSegs = mySides.GetSide( Q_BOTTOM )->GetNbSegments(mesh);
+    nbSegs = mySides.GetSide( Q_BOTTOM )->GetNbSegments( mesh );
     if ( withBrothers && myRightBrother )
       nbSegs += myRightBrother->GetNbHoriSegments( mesh, withBrothers );
   }
@@ -1379,7 +1809,7 @@ int _QuadFaceGrid::GetNbHoriSegments(SMESH_Mesh& mesh, bool withBrothers) const
  */
 //================================================================================
 
-int _QuadFaceGrid::GetNbVertSegments(SMESH_Mesh& mesh, bool withBrothers) const
+int _QuadFaceGrid::GetNbVertSegments(SMESH_ProxyMesh& mesh, bool withBrothers) const
 {
   int nbSegs = 0;
   if ( myLeftBottomChild )
@@ -1388,7 +1818,7 @@ int _QuadFaceGrid::GetNbVertSegments(SMESH_Mesh& mesh, bool withBrothers) const
   }
   else
   {
-    nbSegs = mySides.GetSide( Q_LEFT )->GetNbSegments(mesh);
+    nbSegs = mySides.GetSide( Q_LEFT )->GetNbSegments(mesh,0);
     if ( withBrothers && myUpBrother )
       nbSegs += myUpBrother->GetNbVertSegments( mesh, withBrothers );
   }
@@ -1443,8 +1873,8 @@ const SMDS_MeshNode* _QuadFaceGrid::GetNode(int iHori, int iVert) const
 
 gp_XYZ _QuadFaceGrid::GetXYZ(int iHori, int iVert) const
 {
-  const SMDS_MeshNode* n = myGrid[ myIndexer( iHori, iVert )];
-  return gp_XYZ( n->X(), n->Y(), n->Z() );
+  SMESH_TNodeXYZ xyz = myGrid[ myIndexer( iHori, iVert )];
+  return xyz;
 }
 
 //================================================================================
@@ -1595,8 +2025,6 @@ _FaceSide::_FaceSide(const list<TopoDS_Edge>& edges):
   for ( ; edge != eEnd; ++edge ) {
     myChildren.push_back( _FaceSide( *edge ));
     myNbChildren++;
-//     myVertices.insert( myChildren.back().myVertices.begin(),
-//                        myChildren.back().myVertices.end() );
     myVertices.Add( myChildren.back().FirstVertex() );
     myVertices.Add( myChildren.back().LastVertex() );
     myChildren.back().SetID( Q_CHILD ); // not to splice them
@@ -1605,7 +2033,7 @@ _FaceSide::_FaceSide(const list<TopoDS_Edge>& edges):
 
 //=======================================================================
 //function : GetSide
-//purpose  : 
+//purpose  :
 //=======================================================================
 
 _FaceSide* _FaceSide::GetSide(const int i)
@@ -1801,30 +2229,46 @@ void _FaceSide::SetBottomSide( int i )
 //purpose  : 
 //=======================================================================
 
-int _FaceSide::GetNbSegments(SMESH_Mesh& mesh) const
+int _FaceSide::GetNbSegments(SMESH_ProxyMesh& mesh, const SMESHDS_SubMesh* smToCheckEdges) const
 {
   int nb = 0;
   if ( myChildren.empty() )
   {
-    nb = mesh.GetSubMesh(myEdge)->GetSubMeshDS()->NbElements();
+    nb = mesh.GetSubMesh(myEdge)->NbElements();
+
+    if ( smToCheckEdges )
+    {
+      // check that segments bound faces belonging to smToCheckEdges
+      SMDS_ElemIteratorPtr segIt = mesh.GetSubMesh(myEdge)->GetElements();
+      while ( segIt->more() )
+      {
+        const SMDS_MeshElement* seg = segIt->next();
+        if ( !IsSegmentOnSubMeshBoundary( mesh.GetProxyNode( seg->GetNode(0) ),
+                                          mesh.GetProxyNode( seg->GetNode(1) ),
+                                          smToCheckEdges, mesh ))
+          --nb;
+      }
+    }
   }
   else
   {
     list< _FaceSide >::const_iterator side = myChildren.begin(), sideEnd = myChildren.end();
     for ( ; side != sideEnd; ++side )
-      nb += side->GetNbSegments(mesh);
+      nb += side->GetNbSegments( mesh, smToCheckEdges );
   }
   return nb;
 }
 
 //=======================================================================
 //function : StoreNodes
-//purpose  : 
+//purpose  :
 //=======================================================================
 
-bool _FaceSide::StoreNodes(SMESH_Mesh&                   mesh,
+bool _FaceSide::StoreNodes(SMESH_ProxyMesh&              mesh,
                            vector<const SMDS_MeshNode*>& myGrid,
-                           bool                          reverse )
+                           bool                          reverse,
+                           bool                          isProxy,
+                           const SMESHDS_SubMesh*        smToCheckEdges)
 {
   list< TopoDS_Edge > edges;
   if ( myChildren.empty() )
@@ -1844,24 +2288,61 @@ bool _FaceSide::StoreNodes(SMESH_Mesh&                   mesh,
   list< TopoDS_Edge >::iterator edge = edges.begin(), eEnd = edges.end();
   for ( ; edge != eEnd; ++edge )
   {
-    map< double, const SMDS_MeshNode* > nodes;
+    typedef map< double, const SMDS_MeshNode* > TParamNodeMap;
+    TParamNodeMap nodes;
     bool ok = SMESH_Algo::GetSortedNodesOnEdge( mesh.GetMeshDS(),
                                                 *edge,
                                                 /*ignoreMediumNodes=*/true,
                                                 nodes);
     if ( !ok ) return false;
 
+    // skip nodes on VERTEXes not included in faces
+    if ( !nodes.begin()->second->GetInverseElementIterator(SMDSAbs_Face)->more() )
+      nodes.erase( nodes.begin() );
+    if ( !nodes.empty() &&
+         !nodes.rbegin()->second->GetInverseElementIterator(SMDSAbs_Face)->more() )
+      nodes.erase( --nodes.end() );
+
+    if ( isProxy )
+    {
+      TParamNodeMap::iterator u_node, nEnd = nodes.end();
+      for ( u_node = nodes.begin(); u_node != nEnd; ++u_node )
+        u_node->second = mesh.GetProxyNode( u_node->second );
+    }
+
+    if ( smToCheckEdges ) // erase nodes of segments not bounding faces of smToCheckEdges
+    {
+      {
+        TParamNodeMap::iterator u_node1, u_node2 = nodes.begin(), nEnd = nodes.end();
+        for ( u_node1 = u_node2++; u_node2 != nEnd; u_node1 = u_node2++ )
+          if ( IsSegmentOnSubMeshBoundary( u_node1->second, u_node2->second,
+                                           smToCheckEdges, mesh ))
+            break;
+          else
+            nodes.erase( u_node1 );
+      }
+      {
+        TParamNodeMap::reverse_iterator u_node1, u_node2 = nodes.rbegin(), nEnd = nodes.rend();
+        for ( u_node1 = u_node2++; u_node2 != nEnd; u_node1 = u_node2++ )
+          if ( IsSegmentOnSubMeshBoundary( u_node1->second, u_node2->second,
+                                           smToCheckEdges, mesh ))
+            break;
+          else
+            nodes.erase( --(( u_node2 = u_node1 ).base() ));
+      }
+    }
+
     bool forward = ( edge->Orientation() == TopAbs_FORWARD );
     if ( reverse ) forward = !forward;
     if ( forward )
     {
-      map< double, const SMDS_MeshNode* >::iterator u_node, nEnd = nodes.end();
+      TParamNodeMap::iterator u_node, nEnd = nodes.end();
       for ( u_node = nodes.begin(); u_node != nEnd; ++u_node )
         myGrid[ nbNodes++ ] = u_node->second;
     }
-    else 
+    else
     {
-      map< double, const SMDS_MeshNode* >::reverse_iterator u_node, nEnd = nodes.rend();
+      TParamNodeMap::reverse_iterator u_node, nEnd = nodes.rend();
       for ( u_node = nodes.rbegin(); u_node != nEnd; ++u_node )
         myGrid[ nbNodes++ ] = u_node->second;
     }