Salome HOME
Merge from V6_5_BR 05/06/2012
[modules/smesh.git] / src / StdMeshers / StdMeshers_Prism_3D.cxx
1 // Copyright (C) 2007-2012  CEA/DEN, EDF R&D, OPEN CASCADE
2 //
3 // Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
5 //
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License.
10 //
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 // Lesser General Public License for more details.
15 //
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
19 //
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 //
22
23 //  SMESH SMESH : implementaion of SMESH idl descriptions
24 // File      : StdMeshers_Prism_3D.cxx
25 // Module    : SMESH
26 // Created   : Fri Oct 20 11:37:07 2006
27 // Author    : Edward AGAPOV (eap)
28 //
29 #include "StdMeshers_Prism_3D.hxx"
30
31 #include "StdMeshers_ProjectionUtils.hxx"
32 #include "SMESH_MesherHelper.hxx"
33 #include "SMDS_VolumeTool.hxx"
34 #include "SMDS_VolumeOfNodes.hxx"
35 #include "SMDS_EdgePosition.hxx"
36 #include "SMESH_Comment.hxx"
37
38 #include "utilities.h"
39
40 #include <BRep_Tool.hxx>
41 #include <Bnd_B3d.hxx>
42 #include <Geom2dAdaptor_Curve.hxx>
43 #include <Geom2d_Line.hxx>
44 #include <Geom_Curve.hxx>
45 #include <TopExp.hxx>
46 #include <TopExp_Explorer.hxx>
47 #include <TopTools_ListIteratorOfListOfShape.hxx>
48 #include <TopTools_MapOfShape.hxx>
49 #include <TopTools_SequenceOfShape.hxx>
50 #include <TopoDS.hxx>
51 #include <gp_Ax2.hxx>
52 #include <gp_Ax3.hxx>
53
54 using namespace std;
55
56 #define RETURN_BAD_RESULT(msg) { MESSAGE(")-: Error: " << msg); return false; }
57 #define gpXYZ(n) gp_XYZ(n->X(),n->Y(),n->Z())
58 #define SHOWYXZ(msg, xyz) // {\
59 // gp_Pnt p (xyz); \
60 // cout << msg << " ("<< p.X() << "; " <<p.Y() << "; " <<p.Z() << ") " <<endl;\
61 // }
62
63 typedef StdMeshers_ProjectionUtils TAssocTool;
64 typedef SMESH_Comment              TCom;
65
66 enum { ID_BOT_FACE = SMESH_Block::ID_Fxy0,
67        ID_TOP_FACE = SMESH_Block::ID_Fxy1,
68        BOTTOM_EDGE = 0, TOP_EDGE, V0_EDGE, V1_EDGE, // edge IDs in face
69        NB_WALL_FACES = 4 }; //
70
71 namespace {
72
73   //================================================================================
74   /*!
75    * \brief Return iterator pointing to node column for the given parameter
76    * \param columnsMap - node column map
77    * \param parameter - parameter
78    * \retval TParam2ColumnMap::iterator - result
79    *
80    * it returns closest left column
81    */
82   //================================================================================
83
84   TParam2ColumnIt getColumn( const TParam2ColumnMap* columnsMap,
85                              const double            parameter )
86   {
87     TParam2ColumnIt u_col = columnsMap->upper_bound( parameter );
88     if ( u_col != columnsMap->begin() )
89       --u_col;
90     return u_col; // return left column
91   }
92
93   //================================================================================
94   /*!
95    * \brief Return nodes around given parameter and a ratio
96    * \param column - node column
97    * \param param - parameter
98    * \param node1 - lower node
99    * \param node2 - upper node
100    * \retval double - ratio
101    */
102   //================================================================================
103
104   double getRAndNodes( const TNodeColumn*     column,
105                        const double           param,
106                        const SMDS_MeshNode* & node1,
107                        const SMDS_MeshNode* & node2)
108   {
109     if ( param >= 1.0 || column->size() == 1) {
110       node1 = node2 = column->back();
111       return 0;
112     }
113
114     int i = int( param * ( column->size() - 1 ));
115     double u0 = double( i )/ double( column->size() - 1 );
116     double r = ( param - u0 ) * ( column->size() - 1 );
117
118     node1 = (*column)[ i ];
119     node2 = (*column)[ i + 1];
120     return r;
121   }
122
123   //================================================================================
124   /*!
125    * \brief Compute boundary parameters of face parts
126     * \param nbParts - nb of parts to split columns into
127     * \param columnsMap - node columns of the face to split
128     * \param params - computed parameters
129    */
130   //================================================================================
131
132   void splitParams( const int               nbParts,
133                     const TParam2ColumnMap* columnsMap,
134                     vector< double > &      params)
135   {
136     params.clear();
137     params.reserve( nbParts + 1 );
138     TParam2ColumnIt last_par_col = --columnsMap->end();
139     double par = columnsMap->begin()->first; // 0.
140     double parLast = last_par_col->first;
141     params.push_back( par );
142     for ( int i = 0; i < nbParts - 1; ++ i )
143     {
144       double partSize = ( parLast - par ) / double ( nbParts - i );
145       TParam2ColumnIt par_col = getColumn( columnsMap, par + partSize );
146       if ( par_col->first == par ) {
147         ++par_col;
148         if ( par_col == last_par_col ) {
149           while ( i < nbParts - 1 )
150             params.push_back( par + partSize * i++ );
151           break;
152         }
153       }
154       par = par_col->first;
155       params.push_back( par );
156     }
157     params.push_back( parLast ); // 1.
158   }
159
160   //================================================================================
161   /*!
162    * \brief Return coordinate system for z-th layer of nodes
163    */
164   //================================================================================
165
166   gp_Ax2 getLayerCoordSys(const int                           z,
167                           const vector< const TNodeColumn* >& columns,
168                           int&                                xColumn)
169   {
170     // gravity center of a layer
171     gp_XYZ O(0,0,0);
172     int vertexCol = -1;
173     for ( int i = 0; i < columns.size(); ++i )
174     {
175       O += gpXYZ( (*columns[ i ])[ z ]);
176       if ( vertexCol < 0 &&
177            columns[ i ]->front()->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX )
178         vertexCol = i;
179     }
180     O /= columns.size();
181
182     // Z axis
183     gp_Vec Z(0,0,0);
184     int iPrev = columns.size()-1;
185     for ( int i = 0; i < columns.size(); ++i )
186     {
187       gp_Vec v1( O, gpXYZ( (*columns[ iPrev ])[ z ]));
188       gp_Vec v2( O, gpXYZ( (*columns[ i ]    )[ z ]));
189       Z += v1 ^ v2;
190       iPrev = i;
191     }
192
193     if ( vertexCol >= 0 )
194     {
195       O = gpXYZ( (*columns[ vertexCol ])[ z ]);
196     }
197     if ( xColumn < 0 || xColumn >= columns.size() )
198     {
199       // select a column for X dir
200       double maxDist = 0;
201       for ( int i = 0; i < columns.size(); ++i )
202       {
203         double dist = ( O - gpXYZ((*columns[ i ])[ z ])).SquareModulus();
204         if ( dist > maxDist )
205         {
206           xColumn = i;
207           maxDist = dist;
208         }
209       }
210     }
211
212     // X axis
213     gp_Vec X( O, gpXYZ( (*columns[ xColumn ])[ z ]));
214
215     return gp_Ax2( O, Z, X);
216   }
217
218   //================================================================================
219   /*!
220    * \brief Removes submeshes meshed with regular grid from given list
221    *  \retval int - nb of removed submeshes
222    */
223   //================================================================================
224
225   int removeQuasiQuads(list< SMESH_subMesh* >& notQuadSubMesh)
226   {
227     int oldNbSM = notQuadSubMesh.size();
228     SMESHDS_Mesh* mesh = notQuadSubMesh.front()->GetFather()->GetMeshDS();
229     list< SMESH_subMesh* >::iterator smIt = notQuadSubMesh.begin();
230 #define __NEXT_SM { ++smIt; continue; }
231     while ( smIt != notQuadSubMesh.end() )
232     {
233       SMESH_subMesh* faceSm = *smIt;
234       SMESHDS_SubMesh* faceSmDS = faceSm->GetSubMeshDS();
235       int nbQuads = faceSmDS->NbElements();
236       if ( nbQuads == 0 ) __NEXT_SM;
237
238       // get oredered edges
239       list< TopoDS_Edge > orderedEdges;
240       list< int >         nbEdgesInWires;
241       TopoDS_Vertex       V000;
242       int nbWires = SMESH_Block::GetOrderedEdges( TopoDS::Face( faceSm->GetSubShape() ),
243                                                   V000, orderedEdges, nbEdgesInWires );
244       if ( nbWires != 1 || nbEdgesInWires.front() <= 4 )
245         __NEXT_SM;
246
247       // get nb of segements on edges
248       list<int> nbSegOnEdge;
249       list< TopoDS_Edge >::iterator edge = orderedEdges.begin();
250       for ( ; edge != orderedEdges.end(); ++edge )
251       {
252         if ( SMESHDS_SubMesh* edgeSmDS = mesh->MeshElements( *edge ))
253           nbSegOnEdge.push_back( edgeSmDS->NbElements() );
254         else
255           nbSegOnEdge.push_back(0);
256       }
257
258       // unite nbSegOnEdge of continues edges
259       int nbEdges = nbEdgesInWires.front();
260       list<int>::iterator nbSegIt = nbSegOnEdge.begin();
261       for ( edge = orderedEdges.begin(); edge != orderedEdges.end(); )
262       {
263         const TopoDS_Edge& e1 = *edge++;
264         const TopoDS_Edge& e2 = ( edge == orderedEdges.end() ? orderedEdges.front() : *edge );
265         if ( SMESH_Algo::IsContinuous( e1, e2 ))
266         {
267           // common vertex of continues edges must be shared by two 2D mesh elems of geom face
268           TopoDS_Vertex vCommon = TopExp::LastVertex( e1, true );
269           const SMDS_MeshNode* vNode = SMESH_Algo::VertexNode( vCommon, mesh );
270           int nbF = 0;
271           if ( vNode )
272           {
273             SMDS_ElemIteratorPtr fIt = vNode->GetInverseElementIterator(SMDSAbs_Face);
274             while ( fIt->more() )
275               nbF += faceSmDS->Contains( fIt->next() );
276           }
277           list<int>::iterator nbSegIt1 = nbSegIt++;
278           if ( !vNode || nbF == 2 ) // !vNode - two edges can be meshed as one
279           {
280             // unite
281             if ( nbSegIt == nbSegOnEdge.end() ) nbSegIt = nbSegOnEdge.begin();
282             *nbSegIt += *nbSegIt1;
283             nbSegOnEdge.erase( nbSegIt1 );
284             --nbEdges;
285           }
286         }
287         else
288         {
289           ++nbSegIt;
290         }
291       }
292       vector<int> nbSegVec( nbSegOnEdge.begin(), nbSegOnEdge.end());
293       if ( nbSegVec.size() == 4 &&
294            nbSegVec[0] == nbSegVec[2] &&
295            nbSegVec[1] == nbSegVec[3] &&
296            nbSegVec[0] * nbSegVec[1] == nbQuads
297            )
298         smIt = notQuadSubMesh.erase( smIt );
299       else
300         __NEXT_SM;
301     }
302
303     return oldNbSM - notQuadSubMesh.size();
304   }
305 }
306
307 //=======================================================================
308 //function : StdMeshers_Prism_3D
309 //purpose  : 
310 //=======================================================================
311
312 StdMeshers_Prism_3D::StdMeshers_Prism_3D(int hypId, int studyId, SMESH_Gen* gen)
313   :SMESH_3D_Algo(hypId, studyId, gen)
314 {
315   _name = "Prism_3D";
316   _shapeType = (1 << TopAbs_SHELL) | (1 << TopAbs_SOLID);       // 1 bit per shape type
317   myProjectTriangles = false;
318 }
319
320 //================================================================================
321 /*!
322  * \brief Destructor
323  */
324 //================================================================================
325
326 StdMeshers_Prism_3D::~StdMeshers_Prism_3D()
327 {}
328
329 //=======================================================================
330 //function : CheckHypothesis
331 //purpose  : 
332 //=======================================================================
333
334 bool StdMeshers_Prism_3D::CheckHypothesis(SMESH_Mesh&                          aMesh,
335                                           const TopoDS_Shape&                  aShape,
336                                           SMESH_Hypothesis::Hypothesis_Status& aStatus)
337 {
338   // Check shape geometry
339 /*  PAL16229
340   aStatus = SMESH_Hypothesis::HYP_BAD_GEOMETRY;
341
342   // find not quadrangle faces
343   list< TopoDS_Shape > notQuadFaces;
344   int nbEdge, nbWire, nbFace = 0;
345   TopExp_Explorer exp( aShape, TopAbs_FACE );
346   for ( ; exp.More(); exp.Next() ) {
347     ++nbFace;
348     const TopoDS_Shape& face = exp.Current();
349     nbEdge = TAssocTool::Count( face, TopAbs_EDGE, 0 );
350     nbWire = TAssocTool::Count( face, TopAbs_WIRE, 0 );
351     if (  nbEdge!= 4 || nbWire!= 1 ) {
352       if ( !notQuadFaces.empty() ) {
353         if ( TAssocTool::Count( notQuadFaces.back(), TopAbs_EDGE, 0 ) != nbEdge ||
354              TAssocTool::Count( notQuadFaces.back(), TopAbs_WIRE, 0 ) != nbWire )
355           RETURN_BAD_RESULT("Different not quad faces");
356       }
357       notQuadFaces.push_back( face );
358     }
359   }
360   if ( !notQuadFaces.empty() )
361   {
362     if ( notQuadFaces.size() != 2 )
363       RETURN_BAD_RESULT("Bad nb not quad faces: " << notQuadFaces.size());
364
365     // check total nb faces
366     nbEdge = TAssocTool::Count( notQuadFaces.back(), TopAbs_EDGE, 0 );
367     if ( nbFace != nbEdge + 2 )
368       RETURN_BAD_RESULT("Bad nb of faces: " << nbFace << " but must be " << nbEdge + 2);
369   }
370 */
371   // no hypothesis
372   aStatus = SMESH_Hypothesis::HYP_OK;
373   return true;
374 }
375
376 //=======================================================================
377 //function : Compute
378 //purpose  : 
379 //=======================================================================
380
381 bool StdMeshers_Prism_3D::Compute(SMESH_Mesh& theMesh, const TopoDS_Shape& theShape)
382 {
383   SMESH_MesherHelper helper( theMesh );
384   myHelper = &helper;
385
386   myHelper->IsQuadraticSubMesh( theShape );
387
388   // Analyse mesh and geomerty to find block sub-shapes and submeshes
389   if ( !myBlock.Init( myHelper, theShape ))
390     return error( myBlock.GetError());
391
392   SMESHDS_Mesh* meshDS = theMesh.GetMeshDS();
393
394   int volumeID = meshDS->ShapeToIndex( theShape );
395
396
397   // To compute coordinates of a node inside a block, it is necessary to know
398   // 1. normalized parameters of the node by which
399   // 2. coordinates of node projections on all block sub-shapes are computed
400
401   // So we fill projections on vertices at once as they are same for all nodes
402   myShapeXYZ.resize( myBlock.NbSubShapes() );
403   for ( int iV = SMESH_Block::ID_FirstV; iV < SMESH_Block::ID_FirstE; ++iV ) {
404     myBlock.VertexPoint( iV, myShapeXYZ[ iV ]);
405     SHOWYXZ("V point " <<iV << " ", myShapeXYZ[ iV ]);
406   }
407
408   // Projections on the top and bottom faces are taken from nodes existing
409   // on these faces; find correspondence between bottom and top nodes
410   myBotToColumnMap.clear();
411   if ( !assocOrProjBottom2Top() ) // it also fills myBotToColumnMap
412     return false;
413
414
415   // Create nodes inside the block
416
417   // try to use transformation (issue 0020680)
418   vector<gp_Trsf> trsf;
419   if ( myBlock.GetLayersTransformation(trsf))
420   {
421     // loop on nodes inside the bottom face
422     TNode2ColumnMap::iterator bot_column = myBotToColumnMap.begin();
423     for ( ; bot_column != myBotToColumnMap.end(); ++bot_column )
424     {
425       const TNode& tBotNode = bot_column->first; // bottom TNode
426       if ( tBotNode.GetPositionType() != SMDS_TOP_FACE )
427         continue; // node is not inside face 
428
429       // column nodes; middle part of the column are zero pointers
430       TNodeColumn& column = bot_column->second;
431       TNodeColumn::iterator columnNodes = column.begin();
432       for ( int z = 0; columnNodes != column.end(); ++columnNodes, ++z)
433       {
434         const SMDS_MeshNode* & node = *columnNodes;
435         if ( node ) continue; // skip bottom or top node
436
437         gp_XYZ coords = tBotNode.GetCoords();
438         trsf[z-1].Transforms( coords );
439         node = meshDS->AddNode( coords.X(), coords.Y(), coords.Z() );
440         meshDS->SetNodeInVolume( node, volumeID );
441       }
442     } // loop on bottom nodes
443   }
444   else // use block approach
445   {
446     // loop on nodes inside the bottom face
447     TNode prevBNode;
448     TNode2ColumnMap::iterator bot_column = myBotToColumnMap.begin();
449     for ( ; bot_column != myBotToColumnMap.end(); ++bot_column )
450     {
451       const TNode& tBotNode = bot_column->first; // bottom TNode
452       if ( tBotNode.GetPositionType() != SMDS_TOP_FACE )
453         continue; // node is not inside face 
454
455       // column nodes; middle part of the column are zero pointers
456       TNodeColumn& column = bot_column->second;
457
458       // compute bottom node parameters
459       gp_XYZ paramHint(-1,-1,-1);
460       if ( prevBNode.IsNeighbor( tBotNode ))
461         paramHint = prevBNode.GetParams();
462       if ( !myBlock.ComputeParameters( tBotNode.GetCoords(), tBotNode.ChangeParams(),
463                                        ID_BOT_FACE, paramHint ))
464         return error(TCom("Can't compute normalized parameters for node ")
465                      << tBotNode.myNode->GetID() << " on the face #"
466                      << myBlock.SubMesh( ID_BOT_FACE )->GetId() );
467       prevBNode = tBotNode;
468
469       myShapeXYZ[ ID_BOT_FACE ] = tBotNode.GetCoords();
470       gp_XYZ botParams          = tBotNode.GetParams();
471
472       // compute top node parameters
473       myShapeXYZ[ ID_TOP_FACE ] = gpXYZ( column.back() );
474       gp_XYZ topParams = botParams;
475       topParams.SetZ( 1 );
476       if ( column.size() > 2 ) {
477         gp_Pnt topCoords = myShapeXYZ[ ID_TOP_FACE ];
478         if ( !myBlock.ComputeParameters( topCoords, topParams, ID_TOP_FACE, topParams ))
479           return error(TCom("Can't compute normalized parameters ")
480                        << "for node " << column.back()->GetID()
481                        << " on the face #"<< column.back()->getshapeId() );
482       }
483
484       // vertical loop
485       TNodeColumn::iterator columnNodes = column.begin();
486       for ( int z = 0; columnNodes != column.end(); ++columnNodes, ++z)
487       {
488         const SMDS_MeshNode* & node = *columnNodes;
489         if ( node ) continue; // skip bottom or top node
490
491         // params of a node to create
492         double rz = (double) z / (double) ( column.size() - 1 );
493         gp_XYZ params = botParams * ( 1 - rz ) + topParams * rz;
494
495         // set coords on all faces and nodes
496         const int nbSideFaces = 4;
497         int sideFaceIDs[nbSideFaces] = { SMESH_Block::ID_Fx0z,
498                                          SMESH_Block::ID_Fx1z,
499                                          SMESH_Block::ID_F0yz,
500                                          SMESH_Block::ID_F1yz };
501         for ( int iF = 0; iF < nbSideFaces; ++iF )
502           if ( !setFaceAndEdgesXYZ( sideFaceIDs[ iF ], params, z ))
503             return false;
504
505         // compute coords for a new node
506         gp_XYZ coords;
507         if ( !SMESH_Block::ShellPoint( params, myShapeXYZ, coords ))
508           return error("Can't compute coordinates by normalized parameters");
509
510         SHOWYXZ("TOPFacePoint ",myShapeXYZ[ ID_TOP_FACE]);
511         SHOWYXZ("BOT Node "<< tBotNode.myNode->GetID(),gpXYZ(tBotNode.myNode));
512         SHOWYXZ("ShellPoint ",coords);
513
514         // create a node
515         node = meshDS->AddNode( coords.X(), coords.Y(), coords.Z() );
516         meshDS->SetNodeInVolume( node, volumeID );
517       }
518     } // loop on bottom nodes
519   }
520
521   // Create volumes
522
523   SMESHDS_SubMesh* smDS = myBlock.SubMeshDS( ID_BOT_FACE );
524   if ( !smDS ) return error(COMPERR_BAD_INPUT_MESH, "Null submesh");
525
526   // loop on bottom mesh faces
527   SMDS_ElemIteratorPtr faceIt = smDS->GetElements();
528   while ( faceIt->more() )
529   {
530     const SMDS_MeshElement* face = faceIt->next();
531     if ( !face || face->GetType() != SMDSAbs_Face )
532       continue;
533     int nbNodes = face->NbNodes();
534     if ( face->IsQuadratic() )
535       nbNodes /= 2;
536
537     // find node columns for each node
538     vector< const TNodeColumn* > columns( nbNodes );
539     for ( int i = 0; i < nbNodes; ++i )
540     {
541       const SMDS_MeshNode* n = face->GetNode( i );
542       if ( n->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE ) {
543         TNode2ColumnMap::iterator bot_column = myBotToColumnMap.find( n );
544         if ( bot_column == myBotToColumnMap.end() )
545           return error(TCom("No nodes found above node ") << n->GetID() );
546         columns[ i ] = & bot_column->second;
547       }
548       else {
549         columns[ i ] = myBlock.GetNodeColumn( n );
550         if ( !columns[ i ] )
551           return error(TCom("No side nodes found above node ") << n->GetID() );
552       }
553     }
554     // create prisms
555     AddPrisms( columns, myHelper );
556
557   } // loop on bottom mesh faces
558
559   // clear data
560   myBotToColumnMap.clear();
561   myBlock.Clear();
562         
563   return true;
564 }
565
566
567 //=======================================================================
568 //function : Evaluate
569 //purpose  : 
570 //=======================================================================
571
572 bool StdMeshers_Prism_3D::Evaluate(SMESH_Mesh& theMesh,
573                                    const TopoDS_Shape& theShape,
574                                    MapShapeNbElems& aResMap)
575 {
576   // find face contains only triangles
577   vector < SMESH_subMesh * >meshFaces;
578   TopTools_SequenceOfShape aFaces;
579   int NumBase = 0, i = 0, NbQFs = 0;
580   for (TopExp_Explorer exp(theShape, TopAbs_FACE); exp.More(); exp.Next()) {
581     i++;
582     aFaces.Append(exp.Current());
583     SMESH_subMesh *aSubMesh = theMesh.GetSubMesh(exp.Current());
584     meshFaces.push_back(aSubMesh);
585     MapShapeNbElemsItr anIt = aResMap.find(meshFaces[i-1]);
586     if( anIt==aResMap.end() ) {
587       SMESH_ComputeErrorPtr& smError = aSubMesh->GetComputeError();
588       smError.reset( new SMESH_ComputeError(COMPERR_ALGO_FAILED,"Submesh can not be evaluated",this));
589       return false;
590     }
591     std::vector<int> aVec = (*anIt).second;
592     int nbtri = Max(aVec[SMDSEntity_Triangle],aVec[SMDSEntity_Quad_Triangle]);
593     int nbqua = Max(aVec[SMDSEntity_Quadrangle],aVec[SMDSEntity_Quad_Quadrangle]);
594     if( nbtri==0 && nbqua>0 ) {
595       NbQFs++;
596     }
597     if( nbtri>0 ) {
598       NumBase = i;
599     }
600   }
601
602   if(NbQFs<4) {
603     std::vector<int> aResVec(SMDSEntity_Last);
604     for(int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aResVec[i] = 0;
605     SMESH_subMesh * sm = theMesh.GetSubMesh(theShape);
606     aResMap.insert(std::make_pair(sm,aResVec));
607     SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
608     smError.reset( new SMESH_ComputeError(COMPERR_ALGO_FAILED,"Submesh can not be evaluated",this));
609     return false;
610   }
611
612   if(NumBase==0) NumBase = 1; // only quads => set 1 faces as base
613
614   // find number of 1d elems for base face
615   int nb1d = 0;
616   TopTools_MapOfShape Edges1;
617   for (TopExp_Explorer exp(aFaces.Value(NumBase), TopAbs_EDGE); exp.More(); exp.Next()) {
618     Edges1.Add(exp.Current());
619     SMESH_subMesh *sm = theMesh.GetSubMesh(exp.Current());
620     if( sm ) {
621       MapShapeNbElemsItr anIt = aResMap.find(sm);
622       if( anIt == aResMap.end() ) continue;
623       std::vector<int> aVec = (*anIt).second;
624       nb1d += Max(aVec[SMDSEntity_Edge],aVec[SMDSEntity_Quad_Edge]);
625     }
626   }
627   // find face opposite to base face
628   int OppNum = 0;
629   for(i=1; i<=6; i++) {
630     if(i==NumBase) continue;
631     bool IsOpposite = true;
632     for(TopExp_Explorer exp(aFaces.Value(i), TopAbs_EDGE); exp.More(); exp.Next()) {
633       if( Edges1.Contains(exp.Current()) ) {
634         IsOpposite = false;
635         break;
636       }
637     }
638     if(IsOpposite) {
639       OppNum = i;
640       break;
641     }
642   }
643   // find number of 2d elems on side faces
644   int nb2d = 0;
645   for(i=1; i<=6; i++) {
646     if( i==OppNum || i==NumBase ) continue;
647     MapShapeNbElemsItr anIt = aResMap.find( meshFaces[i-1] );
648     if( anIt == aResMap.end() ) continue;
649     std::vector<int> aVec = (*anIt).second;
650     nb2d += Max(aVec[SMDSEntity_Quadrangle],aVec[SMDSEntity_Quad_Quadrangle]);
651   }
652   
653   MapShapeNbElemsItr anIt = aResMap.find( meshFaces[NumBase-1] );
654   std::vector<int> aVec = (*anIt).second;
655   bool IsQuadratic = (aVec[SMDSEntity_Quad_Triangle]>aVec[SMDSEntity_Triangle]) ||
656                      (aVec[SMDSEntity_Quad_Quadrangle]>aVec[SMDSEntity_Quadrangle]);
657   int nb2d_face0_3 = Max(aVec[SMDSEntity_Triangle],aVec[SMDSEntity_Quad_Triangle]);
658   int nb2d_face0_4 = Max(aVec[SMDSEntity_Quadrangle],aVec[SMDSEntity_Quad_Quadrangle]);
659   int nb0d_face0 = aVec[SMDSEntity_Node];
660   int nb1d_face0_int = ( nb2d_face0_3*3 + nb2d_face0_4*4 - nb1d ) / 2;
661
662   std::vector<int> aResVec(SMDSEntity_Last);
663   for(int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aResVec[i] = 0;
664   if(IsQuadratic) {
665     aResVec[SMDSEntity_Quad_Penta] = nb2d_face0_3 * ( nb2d/nb1d );
666     aResVec[SMDSEntity_Quad_Hexa] = nb2d_face0_4 * ( nb2d/nb1d );
667     aResVec[SMDSEntity_Node] = nb0d_face0 * ( 2*nb2d/nb1d - 1 ) - nb1d_face0_int * nb2d/nb1d;
668   }
669   else {
670     aResVec[SMDSEntity_Node] = nb0d_face0 * ( nb2d/nb1d - 1 );
671     aResVec[SMDSEntity_Penta] = nb2d_face0_3 * ( nb2d/nb1d );
672     aResVec[SMDSEntity_Hexa] = nb2d_face0_4 * ( nb2d/nb1d );
673   }
674   SMESH_subMesh * sm = theMesh.GetSubMesh(theShape);
675   aResMap.insert(std::make_pair(sm,aResVec));
676
677   return true;
678 }
679
680
681 //================================================================================
682 /*!
683  * \brief Create prisms
684  * \param columns - columns of nodes generated from nodes of a mesh face
685  * \param helper - helper initialized by mesh and shape to add prisms to
686  */
687 //================================================================================
688
689 void StdMeshers_Prism_3D::AddPrisms( vector<const TNodeColumn*> & columns,
690                                      SMESH_MesherHelper*          helper)
691 {
692   SMESHDS_Mesh * meshDS = helper->GetMeshDS();
693   int shapeID = helper->GetSubShapeID();
694
695   int nbNodes = columns.size();
696   int nbZ     = columns[0]->size();
697   if ( nbZ < 2 ) return;
698
699   // find out orientation
700   bool isForward = true;
701   SMDS_VolumeTool vTool;
702   int z = 1;
703   switch ( nbNodes ) {
704   case 3: {
705     const SMDS_MeshNode* botNodes[3] = { (*columns[0])[z-1],
706                                          (*columns[1])[z-1],
707                                          (*columns[2])[z-1] };
708     const SMDS_MeshNode* topNodes[3] = { (*columns[0])[z],
709                                          (*columns[1])[z],
710                                          (*columns[2])[z] };
711     SMDS_VolumeOfNodes tmpVol ( botNodes[0], botNodes[1], botNodes[2],
712                                 topNodes[0], topNodes[1], topNodes[2]);
713     vTool.Set( &tmpVol );
714     isForward  = vTool.IsForward();
715     break;
716   }
717   case 4: {
718     const SMDS_MeshNode* botNodes[4] = { (*columns[0])[z-1], (*columns[1])[z-1],
719                                          (*columns[2])[z-1], (*columns[3])[z-1] };
720     const SMDS_MeshNode* topNodes[4] = { (*columns[0])[z], (*columns[1])[z],
721                                          (*columns[2])[z], (*columns[3])[z] };
722     SMDS_VolumeOfNodes tmpVol ( botNodes[0], botNodes[1], botNodes[2], botNodes[3],
723                                 topNodes[0], topNodes[1], topNodes[2], topNodes[3]);
724     vTool.Set( &tmpVol );
725     isForward  = vTool.IsForward();
726     break;
727   }
728   }
729
730   // vertical loop on columns
731   for ( z = 1; z < nbZ; ++z )
732   {
733     SMDS_MeshElement* vol = 0;
734     switch ( nbNodes ) {
735
736     case 3: {
737       const SMDS_MeshNode* botNodes[3] = { (*columns[0])[z-1],
738                                            (*columns[1])[z-1],
739                                            (*columns[2])[z-1] };
740       const SMDS_MeshNode* topNodes[3] = { (*columns[0])[z],
741                                            (*columns[1])[z],
742                                            (*columns[2])[z] };
743       if ( isForward )
744         vol = helper->AddVolume( botNodes[0], botNodes[1], botNodes[2],
745                                  topNodes[0], topNodes[1], topNodes[2]);
746       else
747         vol = helper->AddVolume( topNodes[0], topNodes[1], topNodes[2],
748                                  botNodes[0], botNodes[1], botNodes[2]);
749       break;
750       }
751     case 4: {
752       const SMDS_MeshNode* botNodes[4] = { (*columns[0])[z-1], (*columns[1])[z-1],
753                                            (*columns[2])[z-1], (*columns[3])[z-1] };
754       const SMDS_MeshNode* topNodes[4] = { (*columns[0])[z], (*columns[1])[z],
755                                            (*columns[2])[z], (*columns[3])[z] };
756       if ( isForward )
757         vol = helper->AddVolume( botNodes[0], botNodes[1], botNodes[2], botNodes[3],
758                                  topNodes[0], topNodes[1], topNodes[2], topNodes[3]);
759       else
760         vol = helper->AddVolume( topNodes[0], topNodes[1], topNodes[2], topNodes[3],
761                                  botNodes[0], botNodes[1], botNodes[2], botNodes[3]);
762       break;
763       }
764     default:
765       // polyhedron
766       vector<const SMDS_MeshNode*> nodes( 2*nbNodes + 4*nbNodes);
767       vector<int> quantities( 2 + nbNodes, 4 );
768       quantities[0] = quantities[1] = nbNodes;
769       columns.resize( nbNodes + 1 );
770       columns[ nbNodes ] = columns[ 0 ];
771       for ( int i = 0; i < nbNodes; ++i ) {
772         nodes[ i         ] = (*columns[ i ])[z-1]; // bottom
773         nodes[ i+nbNodes ] = (*columns[ i ])[z  ]; // top
774         // side
775         int di = 2*nbNodes + 4*i - 1;
776         nodes[ di   ] = (*columns[i  ])[z-1];
777         nodes[ di+1 ] = (*columns[i+1])[z-1];
778         nodes[ di+2 ] = (*columns[i+1])[z  ];
779         nodes[ di+3 ] = (*columns[i  ])[z  ];
780       }
781       vol = meshDS->AddPolyhedralVolume( nodes, quantities );
782     }
783     if ( vol && shapeID > 0 )
784       meshDS->SetMeshElementOnShape( vol, shapeID );
785   }
786 }
787
788 //================================================================================
789 /*!
790  * \brief Find correspondence between bottom and top nodes
791  *  If elements on the bottom and top faces are topologically different,
792  *  and projection is possible and allowed, perform the projection
793  *  \retval bool - is a success or not
794  */
795 //================================================================================
796
797 bool StdMeshers_Prism_3D::assocOrProjBottom2Top()
798 {
799   SMESH_subMesh * botSM = myBlock.SubMesh( ID_BOT_FACE );
800   SMESH_subMesh * topSM = myBlock.SubMesh( ID_TOP_FACE );
801
802   SMESHDS_SubMesh * botSMDS = botSM->GetSubMeshDS();
803   SMESHDS_SubMesh * topSMDS = topSM->GetSubMeshDS();
804
805   if ( !botSMDS || botSMDS->NbElements() == 0 )
806     return error(TCom("No elememts on face #") << botSM->GetId());
807
808   bool needProject = false;
809   if ( !topSMDS || 
810        botSMDS->NbElements() != topSMDS->NbElements() ||
811        botSMDS->NbNodes()    != topSMDS->NbNodes())
812   {
813     MESSAGE("nb elem bot " << botSMDS->NbElements() << " top " << topSMDS->NbElements());
814     MESSAGE("nb node bot " << botSMDS->NbNodes() << " top " << topSMDS->NbNodes());
815     if ( myBlock.HasNotQuadElemOnTop() )
816       return error(TCom("Mesh on faces #") << botSM->GetId()
817                    <<" and #"<< topSM->GetId() << " seems different" );
818     needProject = true;
819   }
820
821   if ( 0/*needProject && !myProjectTriangles*/ )
822     return error(TCom("Mesh on faces #") << botSM->GetId()
823                  <<" and #"<< topSM->GetId() << " seems different" );
824   ///RETURN_BAD_RESULT("Need to project but not allowed");
825
826   if ( needProject )
827   {
828     return projectBottomToTop();
829   }
830
831   TopoDS_Face botFace = TopoDS::Face( myBlock.Shape( ID_BOT_FACE ));
832   TopoDS_Face topFace = TopoDS::Face( myBlock.Shape( ID_TOP_FACE ));
833   // associate top and bottom faces
834   TAssocTool::TShapeShapeMap shape2ShapeMap;
835   if ( !TAssocTool::FindSubShapeAssociation( botFace, myBlock.Mesh(),
836                                              topFace, myBlock.Mesh(),
837                                              shape2ShapeMap) )
838     return error(TCom("Topology of faces #") << botSM->GetId()
839                  <<" and #"<< topSM->GetId() << " seems different" );
840
841   // Find matching nodes of top and bottom faces
842   TNodeNodeMap n2nMap;
843   if ( ! TAssocTool::FindMatchingNodesOnFaces( botFace, myBlock.Mesh(),
844                                                topFace, myBlock.Mesh(),
845                                                shape2ShapeMap, n2nMap ))
846     return error(TCom("Mesh on faces #") << botSM->GetId()
847                  <<" and #"<< topSM->GetId() << " seems different" );
848
849   // Fill myBotToColumnMap
850
851   int zSize = myBlock.VerticalSize();
852   //TNode prevTNode;
853   TNodeNodeMap::iterator bN_tN = n2nMap.begin();
854   for ( ; bN_tN != n2nMap.end(); ++bN_tN )
855   {
856     const SMDS_MeshNode* botNode = bN_tN->first;
857     const SMDS_MeshNode* topNode = bN_tN->second;
858     if ( botNode->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE )
859       continue; // wall columns are contained in myBlock
860     // create node column
861     TNode bN( botNode );
862     TNode2ColumnMap::iterator bN_col = 
863       myBotToColumnMap.insert( make_pair ( bN, TNodeColumn() )).first;
864     TNodeColumn & column = bN_col->second;
865     column.resize( zSize );
866     column.front() = botNode;
867     column.back()  = topNode;
868   }
869   return true;
870 }
871
872 //================================================================================
873 /*!
874  * \brief Remove quadrangles from the top face and
875  * create triangles there by projection from the bottom
876  * \retval bool - a success or not
877  */
878 //================================================================================
879
880 bool StdMeshers_Prism_3D::projectBottomToTop()
881 {
882   SMESH_subMesh * botSM = myBlock.SubMesh( ID_BOT_FACE );
883   SMESH_subMesh * topSM = myBlock.SubMesh( ID_TOP_FACE );
884
885   SMESHDS_SubMesh * botSMDS = botSM->GetSubMeshDS();
886   SMESHDS_SubMesh * topSMDS = topSM->GetSubMeshDS();
887
888   if ( topSMDS )
889     topSM->ComputeStateEngine( SMESH_subMesh::CLEAN );
890
891   SMESHDS_Mesh* meshDS = myBlock.MeshDS();
892   int shapeID = myHelper->GetSubShapeID();
893   int topFaceID = meshDS->ShapeToIndex( topSM->GetSubShape() );
894
895   // Fill myBotToColumnMap
896
897   int zSize = myBlock.VerticalSize();
898   TNode prevTNode;
899   SMDS_NodeIteratorPtr nIt = botSMDS->GetNodes();
900   while ( nIt->more() )
901   {
902     const SMDS_MeshNode* botNode = nIt->next();
903     if ( botNode->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE )
904       continue; // strange
905     // compute bottom node params
906     TNode bN( botNode );
907     gp_XYZ paramHint(-1,-1,-1);
908     if ( prevTNode.IsNeighbor( bN ))
909       paramHint = prevTNode.GetParams();
910     if ( !myBlock.ComputeParameters( bN.GetCoords(), bN.ChangeParams(),
911                                      ID_BOT_FACE, paramHint ))
912       return error(TCom("Can't compute normalized parameters for node ")
913                    << botNode->GetID() << " on the face #"<< botSM->GetId() );
914     prevTNode = bN;
915     // compute top node coords
916     gp_XYZ topXYZ; gp_XY topUV;
917     if ( !myBlock.FacePoint( ID_TOP_FACE, bN.GetParams(), topXYZ ) ||
918          !myBlock.FaceUV   ( ID_TOP_FACE, bN.GetParams(), topUV ))
919       return error(TCom("Can't compute coordinates "
920                         "by normalized parameters on the face #")<< topSM->GetId() );
921     SMDS_MeshNode * topNode = meshDS->AddNode( topXYZ.X(),topXYZ.Y(),topXYZ.Z() );
922     meshDS->SetNodeOnFace( topNode, topFaceID, topUV.X(), topUV.Y() );
923     // create node column
924     TNode2ColumnMap::iterator bN_col = 
925       myBotToColumnMap.insert( make_pair ( bN, TNodeColumn() )).first;
926     TNodeColumn & column = bN_col->second;
927     column.resize( zSize );
928     column.front() = botNode;
929     column.back()  = topNode;
930   }
931
932   // Create top faces
933
934   // loop on bottom mesh faces
935   SMDS_ElemIteratorPtr faceIt = botSMDS->GetElements();
936   while ( faceIt->more() )
937   {
938     const SMDS_MeshElement* face = faceIt->next();
939     if ( !face || face->GetType() != SMDSAbs_Face )
940       continue;
941     int nbNodes = face->NbNodes();
942     if ( face->IsQuadratic() )
943       nbNodes /= 2;
944
945     // find top node in columns for each bottom node
946     vector< const SMDS_MeshNode* > nodes( nbNodes );
947     for ( int i = 0; i < nbNodes; ++i )
948     {
949       const SMDS_MeshNode* n = face->GetNode( nbNodes - i - 1 );
950       if ( n->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE ) {
951         TNode2ColumnMap::iterator bot_column = myBotToColumnMap.find( n );
952         if ( bot_column == myBotToColumnMap.end() )
953           return error(TCom("No nodes found above node ") << n->GetID() );
954         nodes[ i ] = bot_column->second.back();
955       }
956       else {
957         const TNodeColumn* column = myBlock.GetNodeColumn( n );
958         if ( !column )
959           return error(TCom("No side nodes found above node ") << n->GetID() );
960         nodes[ i ] = column->back();
961       }
962     }
963     // create a face, with reversed orientation
964     SMDS_MeshElement* newFace = 0;
965     switch ( nbNodes ) {
966
967     case 3: {
968       newFace = myHelper->AddFace(nodes[0], nodes[1], nodes[2]);
969       break;
970       }
971     case 4: {
972       newFace = myHelper->AddFace( nodes[0], nodes[1], nodes[2], nodes[3] );
973       break;
974       }
975     default:
976       newFace = meshDS->AddPolygonalFace( nodes );
977     }
978     if ( newFace && shapeID > 0 )
979       meshDS->SetMeshElementOnShape( newFace, shapeID );
980   }
981
982   return true;
983 }
984
985 //================================================================================
986 /*!
987  * \brief Set projection coordinates of a node to a face and it's sub-shapes
988  * \param faceID - the face given by in-block ID
989  * \param params - node normalized parameters
990  * \retval bool - is a success
991  */
992 //================================================================================
993
994 bool StdMeshers_Prism_3D::setFaceAndEdgesXYZ( const int faceID, const gp_XYZ& params, int z )
995 {
996   // find base and top edges of the face
997   enum { BASE = 0, TOP, LEFT, RIGHT };
998   vector< int > edgeVec; // 0-base, 1-top
999   SMESH_Block::GetFaceEdgesIDs( faceID, edgeVec );
1000
1001   myBlock.EdgePoint( edgeVec[ BASE ], params, myShapeXYZ[ edgeVec[ BASE ]]);
1002   myBlock.EdgePoint( edgeVec[ TOP  ], params, myShapeXYZ[ edgeVec[ TOP ]]);
1003
1004   SHOWYXZ("\nparams ", params);
1005   SHOWYXZ("TOP is " <<edgeVec[ TOP ], myShapeXYZ[ edgeVec[ TOP]]);
1006   SHOWYXZ("BASE is "<<edgeVec[ BASE], myShapeXYZ[ edgeVec[ BASE]]);
1007
1008   if ( faceID == SMESH_Block::ID_Fx0z || faceID == SMESH_Block::ID_Fx1z )
1009   {
1010     myBlock.EdgePoint( edgeVec[ LEFT ], params, myShapeXYZ[ edgeVec[ LEFT ]]);
1011     myBlock.EdgePoint( edgeVec[ RIGHT ], params, myShapeXYZ[ edgeVec[ RIGHT ]]);
1012
1013     SHOWYXZ("VER "<<edgeVec[ LEFT], myShapeXYZ[ edgeVec[ LEFT]]);
1014     SHOWYXZ("VER "<<edgeVec[ RIGHT], myShapeXYZ[ edgeVec[ RIGHT]]);
1015   }
1016   myBlock.FacePoint( faceID, params, myShapeXYZ[ faceID ]);
1017   SHOWYXZ("FacePoint "<<faceID, myShapeXYZ[ faceID]);
1018
1019   return true;
1020 }
1021
1022 //================================================================================
1023 /*!
1024  * \brief Return true if this node and other one belong to one face
1025  */
1026 //================================================================================
1027
1028 bool TNode::IsNeighbor( const TNode& other ) const
1029 {
1030   if ( !other.myNode || !myNode ) return false;
1031
1032   SMDS_ElemIteratorPtr fIt = other.myNode->GetInverseElementIterator(SMDSAbs_Face);
1033   while ( fIt->more() )
1034     if ( fIt->next()->GetNodeIndex( myNode ) >= 0 )
1035       return true;
1036   return false;
1037 }
1038
1039 //================================================================================
1040 /*!
1041  * \brief Constructor. Initialization is needed
1042  */
1043 //================================================================================
1044
1045 StdMeshers_PrismAsBlock::StdMeshers_PrismAsBlock()
1046 {
1047   mySide = 0;
1048 }
1049
1050 StdMeshers_PrismAsBlock::~StdMeshers_PrismAsBlock()
1051 {
1052   Clear();
1053 }
1054 void StdMeshers_PrismAsBlock::Clear()
1055 {
1056   myHelper = 0;
1057   myShapeIDMap.Clear();
1058   myError.reset();
1059
1060   if ( mySide ) {
1061     delete mySide; mySide = 0;
1062   }
1063   myParam2ColumnMaps.clear();
1064   myShapeIndex2ColumnMap.clear();
1065 }
1066
1067 //================================================================================
1068 /*!
1069  * \brief Initialization.
1070  * \param helper - helper loaded with mesh and 3D shape
1071  * \param shape3D - a closed shell or solid
1072  * \retval bool - false if a mesh or a shape are KO
1073  */
1074 //================================================================================
1075
1076 bool StdMeshers_PrismAsBlock::Init(SMESH_MesherHelper* helper,
1077                                    const TopoDS_Shape& shape3D)
1078 {
1079   if ( mySide ) {
1080     delete mySide; mySide = 0;
1081   }
1082   vector< TSideFace* > sideFaces( NB_WALL_FACES, 0 );
1083   vector< pair< double, double> > params ( NB_WALL_FACES );
1084   mySide = new TSideFace( sideFaces, params );
1085
1086   myHelper = helper;
1087   SMESHDS_Mesh* meshDS = myHelper->GetMeshDS();
1088
1089   SMESH_Block::init();
1090   myShapeIDMap.Clear();
1091   myShapeIndex2ColumnMap.clear();
1092   
1093   int wallFaceIds[ NB_WALL_FACES ] = { // to walk around a block
1094     SMESH_Block::ID_Fx0z, SMESH_Block::ID_F1yz,
1095     SMESH_Block::ID_Fx1z, SMESH_Block::ID_F0yz
1096   };
1097
1098   myError = SMESH_ComputeError::New();
1099
1100   // -------------------------------------------------------------
1101   // Look for top and bottom faces: not quadrangle ones or meshed
1102   // with not quadrangle elements
1103   // -------------------------------------------------------------
1104
1105   list< SMESH_subMesh* > notQuadGeomSubMesh;
1106   list< SMESH_subMesh* > notQuadElemSubMesh;
1107   int nbFaces = 0;
1108   //
1109   SMESH_subMesh* mainSubMesh = myHelper->GetMesh()->GetSubMeshContaining( shape3D );
1110   if ( !mainSubMesh ) return error(COMPERR_BAD_INPUT_MESH,"Null submesh of shape3D");
1111
1112   // analyse face submeshes
1113   SMESH_subMeshIteratorPtr smIt = mainSubMesh->getDependsOnIterator(false,false);
1114   while ( smIt->more() )
1115   {
1116     SMESH_subMesh* sm = smIt->next();
1117     const TopoDS_Shape& face = sm->GetSubShape();
1118     if ( face.ShapeType() != TopAbs_FACE )
1119       continue;
1120     nbFaces++;
1121
1122     // is quadrangle face?
1123     list< TopoDS_Edge > orderedEdges;
1124     list< int >         nbEdgesInWires;
1125     TopoDS_Vertex       V000;
1126     int nbWires = GetOrderedEdges( TopoDS::Face( face ),
1127                                    V000, orderedEdges, nbEdgesInWires );
1128     if ( nbWires != 1 || nbEdgesInWires.front() != 4 )
1129       notQuadGeomSubMesh.push_back( sm );
1130
1131     // look for not quadrangle mesh elements
1132     if ( SMESHDS_SubMesh* smDS = sm->GetSubMeshDS() ) {
1133       bool hasNotQuad = false;
1134       SMDS_ElemIteratorPtr eIt = smDS->GetElements();
1135       while ( eIt->more() && !hasNotQuad ) {
1136         const SMDS_MeshElement* elem = eIt->next();
1137         if ( elem->GetType() == SMDSAbs_Face ) {
1138           int nbNodes = elem->NbNodes();
1139           if ( elem->IsQuadratic() )
1140             nbNodes /= 2;
1141           hasNotQuad = ( nbNodes != 4 );
1142         }
1143       }
1144       if ( hasNotQuad )
1145         notQuadElemSubMesh.push_back( sm );
1146     }
1147     else {
1148       return error(COMPERR_BAD_INPUT_MESH,TCom("Not meshed face #")<<sm->GetId());
1149     }
1150     // check if a quadrangle face is meshed with a quadranglar grid
1151     if ( notQuadGeomSubMesh.back() != sm &&
1152          notQuadElemSubMesh.back() != sm )
1153     {
1154       // count nb edges on face sides
1155       vector< int > nbEdges;
1156       nbEdges.reserve( nbEdgesInWires.front() );
1157       for ( list< TopoDS_Edge >::iterator edge = orderedEdges.begin();
1158             edge != orderedEdges.end(); ++edge )
1159       {
1160         if ( SMESHDS_SubMesh* smDS = meshDS->MeshElements( *edge ))
1161           nbEdges.push_back ( smDS->NbElements() );
1162         else
1163           nbEdges.push_back ( 0 );
1164       }
1165       int nbQuads = sm->GetSubMeshDS()->NbElements();
1166       if ( nbEdges[0] *  nbEdges[1] != nbQuads ||
1167            nbEdges[0] != nbEdges[2] ||
1168            nbEdges[1] != nbEdges[3] )
1169         notQuadElemSubMesh.push_back( sm );
1170     }
1171   }
1172
1173   // ----------------------------------------------------------------------
1174   // Analyse mesh and topology of faces: choose the bottom submesh.
1175   // If there are not quadrangle geom faces, they are top and bottom ones.
1176   // Not quadrangle geom faces must be only on top and bottom.
1177   // ----------------------------------------------------------------------
1178
1179   SMESH_subMesh * botSM = 0;
1180   SMESH_subMesh * topSM = 0;
1181
1182   int nbNotQuad       = notQuadGeomSubMesh.size();
1183   int nbNotQuadMeshed = notQuadElemSubMesh.size();
1184   bool hasNotQuad = ( nbNotQuad || nbNotQuadMeshed );
1185
1186   // detect bad cases
1187   if ( nbNotQuadMeshed > 2 )
1188   {
1189     return error(COMPERR_BAD_INPUT_MESH,
1190                  TCom("More than 2 faces with not quadrangle elements: ")
1191                  <<nbNotQuadMeshed);
1192   }
1193   int nbQuasiQuads = 0;
1194   if ( nbNotQuad > 0 && nbNotQuad != 2 )
1195   {
1196     // Issue 0020843 - one of side faces is quasi-quadrilateral.
1197     // Remove from notQuadGeomSubMesh faces meshed with regular grid
1198     nbQuasiQuads = removeQuasiQuads( notQuadGeomSubMesh );
1199     nbNotQuad -= nbQuasiQuads;
1200     if ( nbNotQuad > 0 && nbNotQuad != 2 )
1201       return error(COMPERR_BAD_SHAPE,
1202                    TCom("More than 2 not quadrilateral faces: ")
1203                    <<nbNotQuad);
1204   }
1205
1206   // get found submeshes
1207   if ( hasNotQuad )
1208   {
1209     if ( nbNotQuadMeshed > 0 ) botSM = notQuadElemSubMesh.front();
1210     else                       botSM = notQuadGeomSubMesh.front();
1211     if ( nbNotQuadMeshed > 1 ) topSM = notQuadElemSubMesh.back();
1212     else if ( nbNotQuad  > 1 ) topSM = notQuadGeomSubMesh.back();
1213   }
1214   // detect other bad cases
1215   if ( nbNotQuad == 2 && nbNotQuadMeshed > 0 ) {
1216     bool ok = false;
1217     if ( nbNotQuadMeshed == 1 )
1218       ok = ( find( notQuadGeomSubMesh.begin(),
1219                    notQuadGeomSubMesh.end(), botSM ) != notQuadGeomSubMesh.end() );
1220     else
1221       ok = ( notQuadGeomSubMesh == notQuadElemSubMesh );
1222     if ( !ok )
1223       return error(COMPERR_BAD_INPUT_MESH, "Side face meshed with not quadrangle elements");
1224   }
1225
1226   myNotQuadOnTop = ( nbNotQuadMeshed > 1 );
1227   MESSAGE("myNotQuadOnTop " << myNotQuadOnTop << " nbNotQuadMeshed " << nbNotQuadMeshed);
1228  
1229   // ----------------------------------------------------------
1230
1231   if ( nbNotQuad == 0 ) // Standard block of 6 quadrangle faces ?
1232   {
1233     // SMESH_Block will perform geometry analysis, we need just to find 2
1234     // connected vertices on top and bottom
1235
1236     TopoDS_Vertex Vbot, Vtop;
1237     if ( nbNotQuadMeshed > 0 ) // Look for vertices
1238     {
1239       TopTools_IndexedMapOfShape edgeMap;
1240       TopExp::MapShapes( botSM->GetSubShape(), TopAbs_EDGE, edgeMap );
1241       // vertex 1 is any vertex of the bottom face
1242       Vbot = TopExp::FirstVertex( TopoDS::Edge( edgeMap( 1 )));
1243       // vertex 2 is end vertex of edge sharing Vbot and not belonging to the bottom face
1244       TopTools_ListIteratorOfListOfShape ancestIt = Mesh()->GetAncestors( Vbot );
1245       for ( ; Vtop.IsNull() && ancestIt.More(); ancestIt.Next() )
1246       {
1247         const TopoDS_Shape & ancestor = ancestIt.Value();
1248         if ( ancestor.ShapeType() == TopAbs_EDGE && !edgeMap.FindIndex( ancestor ))
1249         {
1250           TopoDS_Vertex V1, V2;
1251           TopExp::Vertices( TopoDS::Edge( ancestor ), V1, V2);
1252           if      ( Vbot.IsSame ( V1 )) Vtop = V2;
1253           else if ( Vbot.IsSame ( V2 )) Vtop = V1;
1254           // check that Vtop belongs to shape3D
1255           TopExp_Explorer exp( shape3D, TopAbs_VERTEX );
1256           for ( ; exp.More(); exp.Next() )
1257             if ( Vtop.IsSame( exp.Current() ))
1258               break;
1259           if ( !exp.More() )
1260             Vtop.Nullify();
1261         }
1262       }
1263     }
1264     // get shell from shape3D
1265     TopoDS_Shell shell;
1266     TopExp_Explorer exp( shape3D, TopAbs_SHELL );
1267     int nbShell = 0;
1268     for ( ; exp.More(); exp.Next(), ++nbShell )
1269       shell = TopoDS::Shell( exp.Current() );
1270 //     if ( nbShell != 1 )
1271 //       RETURN_BAD_RESULT("There must be 1 shell in the block");
1272
1273     // Load geometry in SMESH_Block
1274     if ( !SMESH_Block::FindBlockShapes( shell, Vbot, Vtop, myShapeIDMap )) {
1275       if ( !hasNotQuad )
1276         return error(COMPERR_BAD_SHAPE, "Can't detect top and bottom of a prism");
1277     }
1278     else {
1279       if ( !botSM ) botSM = Mesh()->GetSubMeshContaining( myShapeIDMap( ID_BOT_FACE ));
1280       if ( !topSM ) topSM = Mesh()->GetSubMeshContaining( myShapeIDMap( ID_TOP_FACE ));
1281     }
1282
1283   } // end  Standard block of 6 quadrangle faces
1284   // --------------------------------------------------------
1285
1286   // Here the top and bottom faces are found
1287   if ( nbNotQuadMeshed == 2 ) // roughly check correspondence of horiz meshes
1288   {
1289 //     SMESHDS_SubMesh* topSMDS = topSM->GetSubMeshDS();
1290 //     SMESHDS_SubMesh* botSMDS = botSM->GetSubMeshDS();
1291 //     if ( topSMDS->NbNodes() != botSMDS->NbNodes() ||
1292 //          topSMDS->NbElements() != botSMDS->NbElements() )
1293 //       RETURN_BAD_RESULT("Top mesh doesn't correspond to bottom one");
1294   }
1295
1296   // ---------------------------------------------------------
1297   // If there are not quadrangle geom faces, we emulate
1298   // a block of 6 quadrangle faces.
1299   // Load SMESH_Block with faces and edges geometry
1300   // ---------------------------------------------------------
1301
1302   
1303   // find vertex 000 - the one with smallest coordinates (for easy DEBUG :-)
1304   TopoDS_Vertex V000;
1305   double minVal = DBL_MAX, minX, val;
1306   for ( TopExp_Explorer exp( botSM->GetSubShape(), TopAbs_VERTEX );
1307         exp.More(); exp.Next() )
1308   {
1309     const TopoDS_Vertex& v = TopoDS::Vertex( exp.Current() );
1310     gp_Pnt P = BRep_Tool::Pnt( v );
1311     val = P.X() + P.Y() + P.Z();
1312     if ( val < minVal || ( val == minVal && P.X() < minX )) {
1313       V000 = v;
1314       minVal = val;
1315       minX = P.X();
1316     }
1317   }
1318
1319   // Get ordered bottom edges
1320   list< TopoDS_Edge > orderedEdges;
1321   list< int >         nbEInW;
1322   SMESH_Block::GetOrderedEdges( TopoDS::Face( botSM->GetSubShape().Reversed() ),
1323                                 V000, orderedEdges, nbEInW );
1324 //   if ( nbEInW.size() != 1 )
1325 //     RETURN_BAD_RESULT("Wrong prism geometry");
1326
1327   // Get Wall faces corresponding to the ordered bottom edges
1328   list< TopoDS_Face > wallFaces;
1329   if ( !GetWallFaces( Mesh(), shape3D, botSM->GetSubShape(), orderedEdges, nbEInW, wallFaces))
1330     return error(COMPERR_BAD_SHAPE, "Can't find side faces");
1331
1332   // check that the found top and bottom faces are opposite
1333   {
1334     for (TopExp_Explorer edge(botSM->GetSubShape(), TopAbs_EDGE); edge.More(); edge.Next())
1335       if ( helper->IsSubShape( edge.Current(), topSM->GetSubShape() ))
1336         return error(notQuadGeomSubMesh.empty() ? COMPERR_BAD_INPUT_MESH : COMPERR_BAD_SHAPE,
1337                      "Non-quadrilateral faces are not opposite");
1338   }
1339
1340   // Protect from a distorted block (test 3D_mesh_HEXA3D/B7 on 32bit platform)
1341   // check that all wall faces have an edge common with the top face
1342   {
1343     list< TopoDS_Face >::iterator faceIt = wallFaces.begin();
1344     for ( ; faceIt != wallFaces.end(); ++faceIt )
1345     {
1346       bool hasCommon = false;
1347       for (TopExp_Explorer edge(*faceIt, TopAbs_EDGE); !hasCommon && edge.More(); edge.Next())
1348         if ( helper->IsSubShape( edge.Current(), topSM->GetSubShape() ))
1349           hasCommon = true;
1350       if ( !hasCommon )
1351         return error(COMPERR_BAD_SHAPE);
1352     }
1353   }
1354
1355   // Find columns of wall nodes and calculate edges' lengths
1356   // --------------------------------------------------------
1357
1358   myParam2ColumnMaps.clear();
1359   myParam2ColumnMaps.resize( orderedEdges.size() ); // total nb edges
1360
1361   int iE, nbEdges = nbEInW.front(); // nb outer edges
1362   vector< double > edgeLength( nbEdges );
1363   map< double, int > len2edgeMap;
1364
1365   list< TopoDS_Edge >::iterator edgeIt = orderedEdges.begin();
1366   list< TopoDS_Face >::iterator faceIt = wallFaces.begin();
1367   for ( iE = 0; iE < nbEdges; ++edgeIt, ++faceIt )
1368   {
1369     TParam2ColumnMap & faceColumns = myParam2ColumnMaps[ iE ];
1370     if ( !myHelper->LoadNodeColumns( faceColumns, *faceIt, *edgeIt, meshDS ))
1371       return error(COMPERR_BAD_INPUT_MESH, TCom("Can't find regular quadrangle mesh ")
1372                    << "on a side face #" << MeshDS()->ShapeToIndex( *faceIt ));
1373
1374     SHOWYXZ("\np1 F "<<iE, gpXYZ(faceColumns.begin()->second.front() ));
1375     SHOWYXZ("p2 F "<<iE, gpXYZ(faceColumns.rbegin()->second.front() ));
1376     SHOWYXZ("V First "<<iE, BRep_Tool::Pnt( TopExp::FirstVertex(*edgeIt,true )));
1377
1378     edgeLength[ iE ] = SMESH_Algo::EdgeLength( *edgeIt );
1379
1380     if ( nbEdges < NB_WALL_FACES ) // fill map used to split faces
1381     {
1382       SMESHDS_SubMesh* smDS = meshDS->MeshElements( *edgeIt);
1383       if ( !smDS )
1384         return error(COMPERR_BAD_INPUT_MESH, TCom("Null submesh on the edge #")
1385                      << MeshDS()->ShapeToIndex( *edgeIt ));
1386       // assure length uniqueness
1387       edgeLength[ iE ] *= smDS->NbNodes() + edgeLength[ iE ] / ( 1000 + iE );
1388       len2edgeMap[ edgeLength[ iE ]] = iE;
1389     }
1390     ++iE;
1391   }
1392   // Load columns of internal edges (forming holes)
1393   // and fill map ShapeIndex to TParam2ColumnMap for them
1394   for ( ; edgeIt != orderedEdges.end() ; ++edgeIt, ++faceIt )
1395   {
1396     TParam2ColumnMap & faceColumns = myParam2ColumnMaps[ iE ];
1397     if ( !myHelper->LoadNodeColumns( faceColumns, *faceIt, *edgeIt, meshDS ))
1398       return error(COMPERR_BAD_INPUT_MESH, TCom("Can't find regular quadrangle mesh ")
1399                    << "on a side face #" << MeshDS()->ShapeToIndex( *faceIt ));
1400     // edge columns
1401     int id = MeshDS()->ShapeToIndex( *edgeIt );
1402     bool isForward = true; // meaningless for intenal wires
1403     myShapeIndex2ColumnMap[ id ] = make_pair( & faceColumns, isForward );
1404     // columns for vertices
1405     // 1
1406     const SMDS_MeshNode* n0 = faceColumns.begin()->second.front();
1407     id = n0->getshapeId();
1408     myShapeIndex2ColumnMap[ id ] = make_pair( & faceColumns, isForward );
1409     // 2
1410     const SMDS_MeshNode* n1 = faceColumns.rbegin()->second.front();
1411     id = n1->getshapeId();
1412     myShapeIndex2ColumnMap[ id ] = make_pair( & faceColumns, isForward );
1413 //     SHOWYXZ("\np1 F "<<iE, gpXYZ(faceColumns.begin()->second.front() ));
1414 //     SHOWYXZ("p2 F "<<iE, gpXYZ(faceColumns.rbegin()->second.front() ));
1415 //     SHOWYXZ("V First "<<iE, BRep_Tool::Pnt( TopExp::FirstVertex(*edgeIt,true )));
1416     ++iE;
1417   }
1418
1419   // Create 4 wall faces of a block
1420   // -------------------------------
1421
1422   if ( nbEdges <= NB_WALL_FACES ) // ************* Split faces if necessary
1423   {
1424     map< int, int > iE2nbSplit;
1425     if ( nbEdges != NB_WALL_FACES ) // define how to split
1426     {
1427       if ( len2edgeMap.size() != nbEdges )
1428         RETURN_BAD_RESULT("Uniqueness of edge lengths not assured");
1429       map< double, int >::reverse_iterator maxLen_i = len2edgeMap.rbegin();
1430       map< double, int >::reverse_iterator midLen_i = ++len2edgeMap.rbegin();
1431       double maxLen = maxLen_i->first;
1432       double midLen = ( len2edgeMap.size() == 1 ) ? 0 : midLen_i->first;
1433       switch ( nbEdges ) {
1434       case 1: // 0-th edge is split into 4 parts
1435         iE2nbSplit.insert( make_pair( 0, 4 )); break;
1436       case 2: // either the longest edge is split into 3 parts, or both edges into halves
1437         if ( maxLen / 3 > midLen / 2 ) {
1438           iE2nbSplit.insert( make_pair( maxLen_i->second, 3 ));
1439         }
1440         else {
1441           iE2nbSplit.insert( make_pair( maxLen_i->second, 2 ));
1442           iE2nbSplit.insert( make_pair( midLen_i->second, 2 ));
1443         }
1444         break;
1445       case 3:
1446         // split longest into halves
1447         iE2nbSplit.insert( make_pair( maxLen_i->second, 2 ));
1448       }
1449     }
1450     // Create TSideFace's
1451     faceIt = wallFaces.begin();
1452     edgeIt = orderedEdges.begin();
1453     int iSide = 0;
1454     for ( iE = 0; iE < nbEdges; ++edgeIt, ++faceIt )
1455     {
1456      // split?
1457       map< int, int >::iterator i_nb = iE2nbSplit.find( iE );
1458       if ( i_nb != iE2nbSplit.end() ) {
1459         // split!
1460         int nbSplit = i_nb->second;
1461         vector< double > params;
1462         splitParams( nbSplit, &myParam2ColumnMaps[ iE ], params );
1463         const bool isForward =
1464           StdMeshers_PrismAsBlock::IsForwardEdge( myHelper->GetMeshDS(),
1465                                                   myParam2ColumnMaps[iE],
1466                                                   *edgeIt, SMESH_Block::ID_Fx0z );
1467         for ( int i = 0; i < nbSplit; ++i ) {
1468           double f = ( isForward ? params[ i ]   : params[ nbSplit - i-1 ]);
1469           double l = ( isForward ? params[ i+1 ] : params[ nbSplit - i ]);
1470           TSideFace* comp = new TSideFace( myHelper, wallFaceIds[ iSide ],
1471                                            *faceIt, *edgeIt,
1472                                            &myParam2ColumnMaps[ iE ], f, l );
1473           mySide->SetComponent( iSide++, comp );
1474         }
1475       }
1476       else {
1477         TSideFace* comp = new TSideFace( myHelper, wallFaceIds[ iSide ],
1478                                          *faceIt, *edgeIt,
1479                                          &myParam2ColumnMaps[ iE ]);
1480         mySide->SetComponent( iSide++, comp );
1481       }
1482       ++iE;
1483     }
1484   }
1485   else { // **************************** Unite faces
1486
1487     // unite first faces
1488     int nbExraFaces = nbEdges - 3;
1489     int iSide = 0, iE;
1490     double u0 = 0, sumLen = 0;
1491     for ( iE = 0; iE < nbExraFaces; ++iE )
1492       sumLen += edgeLength[ iE ];
1493
1494     vector< TSideFace* > components( nbExraFaces );
1495     vector< pair< double, double> > params( nbExraFaces );
1496     faceIt = wallFaces.begin();
1497     edgeIt = orderedEdges.begin();
1498     for ( iE = 0; iE < nbExraFaces; ++edgeIt, ++faceIt )
1499     {
1500       components[ iE ] = new TSideFace( myHelper, wallFaceIds[ iSide ],
1501                                         *faceIt, *edgeIt,
1502                                         &myParam2ColumnMaps[ iE ]);
1503       double u1 = u0 + edgeLength[ iE ] / sumLen;
1504       params[ iE ] = make_pair( u0 , u1 );
1505       u0 = u1;
1506       ++iE;
1507     }
1508     mySide->SetComponent( iSide++, new TSideFace( components, params ));
1509
1510     // fill the rest faces
1511     for ( ; iE < nbEdges; ++faceIt, ++edgeIt )
1512     {
1513       TSideFace* comp = new TSideFace( myHelper, wallFaceIds[ iSide ],
1514                                        *faceIt, *edgeIt,
1515                                        &myParam2ColumnMaps[ iE ]);
1516       mySide->SetComponent( iSide++, comp );
1517       ++iE;
1518     }
1519   }
1520
1521
1522   // Fill geometry fields of SMESH_Block
1523   // ------------------------------------
1524
1525   TopoDS_Face botF = TopoDS::Face( botSM->GetSubShape() );
1526   TopoDS_Face topF = TopoDS::Face( topSM->GetSubShape() );
1527
1528   vector< int > botEdgeIdVec;
1529   SMESH_Block::GetFaceEdgesIDs( ID_BOT_FACE, botEdgeIdVec );
1530
1531   bool isForward[NB_WALL_FACES] = { true, true, true, true };
1532   Adaptor2d_Curve2d* botPcurves[NB_WALL_FACES];
1533   Adaptor2d_Curve2d* topPcurves[NB_WALL_FACES];
1534
1535   for ( int iF = 0; iF < NB_WALL_FACES; ++iF )
1536   {
1537     TSideFace * sideFace = mySide->GetComponent( iF );
1538     if ( !sideFace )
1539       RETURN_BAD_RESULT("NULL TSideFace");
1540     int fID = sideFace->FaceID();
1541
1542     // fill myShapeIDMap
1543     if ( sideFace->InsertSubShapes( myShapeIDMap ) != 8 &&
1544          !sideFace->IsComplex())
1545       MESSAGE( ": Warning : InsertSubShapes() < 8 on side " << iF );
1546
1547     // side faces geometry
1548     Adaptor2d_Curve2d* pcurves[NB_WALL_FACES];
1549     if ( !sideFace->GetPCurves( pcurves ))
1550       RETURN_BAD_RESULT("TSideFace::GetPCurves() failed");
1551
1552     SMESH_Block::TFace& tFace = myFace[ fID - ID_FirstF ];
1553     tFace.Set( fID, sideFace->Surface(), pcurves, isForward );
1554
1555     SHOWYXZ( endl<<"F "<< iF << " id " << fID << " FRW " << sideFace->IsForward(), sideFace->Value(0,0));
1556     // edges 3D geometry
1557     vector< int > edgeIdVec;
1558     SMESH_Block::GetFaceEdgesIDs( fID, edgeIdVec );
1559     for ( int isMax = 0; isMax < 2; ++isMax ) {
1560       {
1561         int eID = edgeIdVec[ isMax ];
1562         SMESH_Block::TEdge& tEdge = myEdge[ eID - ID_FirstE ];
1563         tEdge.Set( eID, sideFace->HorizCurve(isMax), true);
1564         SHOWYXZ(eID<<" HOR"<<isMax<<"(0)", sideFace->HorizCurve(isMax)->Value(0));
1565         SHOWYXZ(eID<<" HOR"<<isMax<<"(1)", sideFace->HorizCurve(isMax)->Value(1));
1566       }
1567       {
1568         int eID = edgeIdVec[ isMax+2 ];
1569         SMESH_Block::TEdge& tEdge = myEdge[ eID - ID_FirstE  ];
1570         tEdge.Set( eID, sideFace->VertiCurve(isMax), true);
1571         SHOWYXZ(eID<<" VER"<<isMax<<"(0)", sideFace->VertiCurve(isMax)->Value(0));
1572         SHOWYXZ(eID<<" VER"<<isMax<<"(1)", sideFace->VertiCurve(isMax)->Value(1));
1573
1574         // corner points
1575         vector< int > vertexIdVec;
1576         SMESH_Block::GetEdgeVertexIDs( eID, vertexIdVec );
1577         myPnt[ vertexIdVec[0] - ID_FirstV ] = tEdge.GetCurve()->Value(0).XYZ();
1578         myPnt[ vertexIdVec[1] - ID_FirstV ] = tEdge.GetCurve()->Value(1).XYZ();
1579       }
1580     }
1581     // pcurves on horizontal faces
1582     for ( iE = 0; iE < NB_WALL_FACES; ++iE ) {
1583       if ( edgeIdVec[ BOTTOM_EDGE ] == botEdgeIdVec[ iE ] ) {
1584         botPcurves[ iE ] = sideFace->HorizPCurve( false, botF );
1585         topPcurves[ iE ] = sideFace->HorizPCurve( true,  topF );
1586         break;
1587       }
1588     }
1589     //sideFace->dumpNodes( 4 ); // debug
1590   }
1591   // horizontal faces geometry
1592   {
1593     SMESH_Block::TFace& tFace = myFace[ ID_BOT_FACE - ID_FirstF ];
1594     tFace.Set( ID_BOT_FACE, new BRepAdaptor_Surface( botF ), botPcurves, isForward );
1595     SMESH_Block::Insert( botF, ID_BOT_FACE, myShapeIDMap );
1596   }
1597   {
1598     SMESH_Block::TFace& tFace = myFace[ ID_TOP_FACE - ID_FirstF ];
1599     tFace.Set( ID_TOP_FACE, new BRepAdaptor_Surface( topF ), topPcurves, isForward );
1600     SMESH_Block::Insert( topF, ID_TOP_FACE, myShapeIDMap );
1601   }
1602
1603   // Fill map ShapeIndex to TParam2ColumnMap
1604   // ----------------------------------------
1605
1606   list< TSideFace* > fList;
1607   list< TSideFace* >::iterator fListIt;
1608   fList.push_back( mySide );
1609   for ( fListIt = fList.begin(); fListIt != fList.end(); ++fListIt)
1610   {
1611     int nb = (*fListIt)->NbComponents();
1612     for ( int i = 0; i < nb; ++i ) {
1613       if ( TSideFace* comp = (*fListIt)->GetComponent( i ))
1614         fList.push_back( comp );
1615     }
1616     if ( TParam2ColumnMap* cols = (*fListIt)->GetColumns()) {
1617       // columns for a base edge
1618       int id = MeshDS()->ShapeToIndex( (*fListIt)->BaseEdge() );
1619       bool isForward = (*fListIt)->IsForward();
1620       myShapeIndex2ColumnMap[ id ] = make_pair( cols, isForward );
1621
1622       // columns for vertices
1623       const SMDS_MeshNode* n0 = cols->begin()->second.front();
1624       id = n0->getshapeId();
1625       myShapeIndex2ColumnMap[ id ] = make_pair( cols, isForward );
1626
1627       const SMDS_MeshNode* n1 = cols->rbegin()->second.front();
1628       id = n1->getshapeId();
1629       myShapeIndex2ColumnMap[ id ] = make_pair( cols, !isForward );
1630     }
1631   }
1632
1633 //   gp_XYZ testPar(0.25, 0.25, 0), testCoord;
1634 //   if ( !FacePoint( ID_BOT_FACE, testPar, testCoord ))
1635 //     RETURN_BAD_RESULT("TEST FacePoint() FAILED");
1636 //   SHOWYXZ("IN TEST PARAM" , testPar);
1637 //   SHOWYXZ("OUT TEST CORD" , testCoord);
1638 //   if ( !ComputeParameters( testCoord, testPar , ID_BOT_FACE))
1639 //     RETURN_BAD_RESULT("TEST ComputeParameters() FAILED");
1640 //   SHOWYXZ("OUT TEST PARAM" , testPar);
1641
1642   return true;
1643 }
1644
1645 //================================================================================
1646 /*!
1647  * \brief Return pointer to column of nodes
1648  * \param node - bottom node from which the returned column goes up
1649  * \retval const TNodeColumn* - the found column
1650  */
1651 //================================================================================
1652
1653 const TNodeColumn* StdMeshers_PrismAsBlock::GetNodeColumn(const SMDS_MeshNode* node) const
1654 {
1655   int sID = node->getshapeId();
1656
1657   map<int, pair< TParam2ColumnMap*, bool > >::const_iterator col_frw =
1658     myShapeIndex2ColumnMap.find( sID );
1659   if ( col_frw != myShapeIndex2ColumnMap.end() ) {
1660     const TParam2ColumnMap* cols = col_frw->second.first;
1661     TParam2ColumnIt u_col = cols->begin();
1662     for ( ; u_col != cols->end(); ++u_col )
1663       if ( u_col->second[ 0 ] == node )
1664         return & u_col->second;
1665   }
1666   return 0;
1667 }
1668
1669 //=======================================================================
1670 //function : GetLayersTransformation
1671 //purpose  : Return transformations to get coordinates of nodes of each layer
1672 //           by nodes of the bottom. Layer is a set of nodes at a certain step
1673 //           from bottom to top.
1674 //=======================================================================
1675
1676 bool StdMeshers_PrismAsBlock::GetLayersTransformation(vector<gp_Trsf> & trsf) const
1677 {
1678   const int zSize = VerticalSize();
1679   if ( zSize < 3 ) return true;
1680   trsf.resize( zSize - 2 );
1681
1682   // Select some node columns by which we will define coordinate system of layers
1683
1684   vector< const TNodeColumn* > columns;
1685   {
1686     const TopoDS_Shape& baseFace = Shape(ID_BOT_FACE);
1687     list< TopoDS_Edge > orderedEdges;
1688     list< int >         nbEdgesInWires;
1689     GetOrderedEdges( TopoDS::Face( baseFace ), TopoDS_Vertex(), orderedEdges, nbEdgesInWires );
1690     bool isReverse;
1691     list< TopoDS_Edge >::iterator edgeIt = orderedEdges.begin();
1692     for ( int iE = 0; iE < nbEdgesInWires.front(); ++iE, ++edgeIt )
1693     {
1694       if ( BRep_Tool::Degenerated( *edgeIt )) continue;
1695       const TParam2ColumnMap* u2colMap =
1696         GetParam2ColumnMap( myHelper->GetMeshDS()->ShapeToIndex( *edgeIt ), isReverse );
1697       if ( !u2colMap ) return false;
1698       isReverse = ( edgeIt->Orientation() == TopAbs_REVERSED );
1699       double f = u2colMap->begin()->first, l = u2colMap->rbegin()->first;
1700       if ( isReverse ) swap ( f, l );
1701       const int nbCol = 5;
1702       for ( int i = 0; i < nbCol; ++i )
1703       {
1704         double u = f + i/double(nbCol) * ( l - f );
1705         const TNodeColumn* col = & getColumn( u2colMap, u )->second;
1706         if ( columns.empty() || col != columns.back() )
1707           columns.push_back( col );
1708       }
1709     }
1710   }
1711
1712   // Find tolerance to check transformations
1713
1714   double tol2;
1715   {
1716     Bnd_B3d bndBox;
1717     for ( int i = 0; i < columns.size(); ++i )
1718       bndBox.Add( gpXYZ( columns[i]->front() ));
1719     tol2 = bndBox.SquareExtent() * 1e-5;
1720   }
1721
1722   // Compute transformations
1723
1724   int xCol = -1;
1725   gp_Trsf fromCsZ, toCs0;
1726   gp_Ax3 cs0 = getLayerCoordSys(0, columns, xCol );
1727   //double dist0 = cs0.Location().Distance( gpXYZ( (*columns[0])[0]));
1728   toCs0.SetTransformation( cs0 );
1729   for ( int z = 1; z < zSize-1; ++z )
1730   {
1731     gp_Ax3 csZ = getLayerCoordSys(z, columns, xCol );
1732     //double distZ = csZ.Location().Distance( gpXYZ( (*columns[0])[z]));
1733     fromCsZ.SetTransformation( csZ );
1734     fromCsZ.Invert();
1735     gp_Trsf& t = trsf[ z-1 ];
1736     t = fromCsZ * toCs0;
1737     //t.SetScaleFactor( distZ/dist0 ); - it does not work properly, wrong base point
1738
1739     // check a transformation
1740     for ( int i = 0; i < columns.size(); ++i )
1741     {
1742       gp_Pnt p0 = gpXYZ( (*columns[i])[0] );
1743       gp_Pnt pz = gpXYZ( (*columns[i])[z] );
1744       t.Transforms( p0.ChangeCoord() );
1745       if ( p0.SquareDistance( pz ) > tol2 )
1746         return false;
1747     }
1748   }
1749   return true;
1750 }
1751
1752 //================================================================================
1753 /*!
1754  * \brief Check curve orientation of a bootom edge
1755   * \param meshDS - mesh DS
1756   * \param columnsMap - node columns map of side face
1757   * \param bottomEdge - the bootom edge
1758   * \param sideFaceID - side face in-block ID
1759   * \retval bool - true if orientation coinside with in-block forward orientation
1760  */
1761 //================================================================================
1762
1763 bool StdMeshers_PrismAsBlock::IsForwardEdge(SMESHDS_Mesh*           meshDS,
1764                                             const TParam2ColumnMap& columnsMap,
1765                                             const TopoDS_Edge &     bottomEdge,
1766                                             const int               sideFaceID)
1767 {
1768   bool isForward = false;
1769   if ( SMESH_MesherHelper::IsClosedEdge( bottomEdge ))
1770   {
1771     isForward = ( bottomEdge.Orientation() == TopAbs_FORWARD );
1772   }
1773   else
1774   {
1775     const TNodeColumn& firstCol = columnsMap.begin()->second;
1776     const SMDS_MeshNode* bottomNode = firstCol[0];
1777     TopoDS_Shape firstVertex = SMESH_MesherHelper::GetSubShapeByNode( bottomNode, meshDS );
1778     isForward = ( firstVertex.IsSame( TopExp::FirstVertex( bottomEdge, true )));
1779   }
1780   // on 2 of 4 sides first vertex is end
1781   if ( sideFaceID == ID_Fx1z || sideFaceID == ID_F0yz )
1782     isForward = !isForward;
1783   return isForward;
1784 }
1785
1786 //================================================================================
1787 /*!
1788  * \brief Find wall faces by bottom edges
1789  * \param mesh - the mesh
1790  * \param mainShape - the prism
1791  * \param bottomFace - the bottom face
1792  * \param bottomEdges - edges bounding the bottom face
1793  * \param wallFaces - faces list to fill in
1794  */
1795 //================================================================================
1796
1797 bool StdMeshers_PrismAsBlock::GetWallFaces( SMESH_Mesh*               mesh,
1798                                             const TopoDS_Shape &      mainShape,
1799                                             const TopoDS_Shape &      bottomFace,
1800                                             std::list< TopoDS_Edge >& bottomEdges,
1801                                             std::list< int > &        nbEInW,
1802                                             std::list< TopoDS_Face >& wallFaces)
1803 {
1804   wallFaces.clear();
1805
1806   TopTools_IndexedMapOfShape faceMap;
1807   TopExp::MapShapes( mainShape, TopAbs_FACE, faceMap );
1808
1809   list< TopoDS_Edge >::iterator edge = bottomEdges.begin();
1810   std::list< int >::iterator nbE = nbEInW.begin();
1811   int iE = 0;
1812   while ( edge != bottomEdges.end() )
1813   {
1814     ++iE;
1815     if ( BRep_Tool::Degenerated( *edge ))
1816     {
1817       edge = bottomEdges.erase( edge );
1818       --iE;
1819       --(*nbE);
1820     }
1821     else
1822     {
1823       PShapeIteratorPtr fIt = myHelper->GetAncestors( *edge, *mesh, TopAbs_FACE );
1824       while ( fIt->more() )
1825       {
1826         const TopoDS_Shape* face = fIt->next();
1827         if ( !bottomFace.IsSame( *face ) &&      // not bottom
1828              faceMap.FindIndex( *face ))         // belongs to the prism
1829         {
1830           wallFaces.push_back( TopoDS::Face( *face ));
1831           break;
1832         }
1833       }
1834       ++edge;
1835     }
1836     if ( iE == *nbE )
1837     {
1838       iE = 0;
1839       ++nbE;
1840     }
1841   }
1842   return ( wallFaces.size() == bottomEdges.size() );
1843 }
1844
1845 //================================================================================
1846 /*!
1847  * \brief Constructor
1848   * \param faceID - in-block ID
1849   * \param face - geom face
1850   * \param columnsMap - map of node columns
1851   * \param first - first normalized param
1852   * \param last - last normalized param
1853  */
1854 //================================================================================
1855
1856 StdMeshers_PrismAsBlock::TSideFace::TSideFace(SMESH_MesherHelper* helper,
1857                                               const int           faceID,
1858                                               const TopoDS_Face&  face,
1859                                               const TopoDS_Edge&  baseEdge,
1860                                               TParam2ColumnMap*   columnsMap,
1861                                               const double        first,
1862                                               const double        last):
1863   myID( faceID ),
1864   myParamToColumnMap( columnsMap ),
1865   myBaseEdge( baseEdge ),
1866   myHelper( helper )
1867 {
1868   mySurface.Initialize( face );
1869   myParams.resize( 1 );
1870   myParams[ 0 ] = make_pair( first, last );
1871   myIsForward = StdMeshers_PrismAsBlock::IsForwardEdge( myHelper->GetMeshDS(),
1872                                                         *myParamToColumnMap,
1873                                                         myBaseEdge, myID );
1874 }
1875
1876 //================================================================================
1877 /*!
1878  * \brief Constructor of complex side face
1879  */
1880 //================================================================================
1881
1882 StdMeshers_PrismAsBlock::TSideFace::
1883 TSideFace(const vector< TSideFace* >&             components,
1884           const vector< pair< double, double> > & params)
1885   :myID( components[0] ? components[0]->myID : 0 ),
1886    myParamToColumnMap( 0 ),
1887    myParams( params ),
1888    myIsForward( true ),
1889    myComponents( components ),
1890    myHelper( components[0] ? components[0]->myHelper : 0 )
1891 {}
1892 //================================================================================
1893 /*!
1894  * \brief Copy constructor
1895   * \param other - other side
1896  */
1897 //================================================================================
1898
1899 StdMeshers_PrismAsBlock::TSideFace::TSideFace( const TSideFace& other )
1900 {
1901   myID               = other.myID;
1902   mySurface          = other.mySurface;
1903   myBaseEdge         = other.myBaseEdge;
1904   myParams           = other.myParams;
1905   myIsForward        = other.myIsForward;
1906   myHelper           = other.myHelper;
1907   myParamToColumnMap = other.myParamToColumnMap;
1908
1909   myComponents.resize( other.myComponents.size());
1910   for (int i = 0 ; i < myComponents.size(); ++i )
1911     myComponents[ i ] = new TSideFace( *other.myComponents[ i ]);
1912 }
1913
1914 //================================================================================
1915 /*!
1916  * \brief Deletes myComponents
1917  */
1918 //================================================================================
1919
1920 StdMeshers_PrismAsBlock::TSideFace::~TSideFace()
1921 {
1922   for (int i = 0 ; i < myComponents.size(); ++i )
1923     if ( myComponents[ i ] )
1924       delete myComponents[ i ];
1925 }
1926
1927 //================================================================================
1928 /*!
1929  * \brief Return geometry of the vertical curve
1930   * \param isMax - true means curve located closer to (1,1,1) block point
1931   * \retval Adaptor3d_Curve* - curve adaptor
1932  */
1933 //================================================================================
1934
1935 Adaptor3d_Curve* StdMeshers_PrismAsBlock::TSideFace::VertiCurve(const bool isMax) const
1936 {
1937   if ( !myComponents.empty() ) {
1938     if ( isMax )
1939       return myComponents.back()->VertiCurve(isMax);
1940     else
1941       return myComponents.front()->VertiCurve(isMax);
1942   }
1943   double f = myParams[0].first, l = myParams[0].second;
1944   if ( !myIsForward ) std::swap( f, l );
1945   return new TVerticalEdgeAdaptor( myParamToColumnMap, isMax ? l : f );
1946 }
1947
1948 //================================================================================
1949 /*!
1950  * \brief Return geometry of the top or bottom curve
1951   * \param isTop - 
1952   * \retval Adaptor3d_Curve* - 
1953  */
1954 //================================================================================
1955
1956 Adaptor3d_Curve* StdMeshers_PrismAsBlock::TSideFace::HorizCurve(const bool isTop) const
1957 {
1958   return new THorizontalEdgeAdaptor( this, isTop );
1959 }
1960
1961 //================================================================================
1962 /*!
1963  * \brief Return pcurves
1964   * \param pcurv - array of 4 pcurves
1965   * \retval bool - is a success
1966  */
1967 //================================================================================
1968
1969 bool StdMeshers_PrismAsBlock::TSideFace::GetPCurves(Adaptor2d_Curve2d* pcurv[4]) const
1970 {
1971   int iEdge[ 4 ] = { BOTTOM_EDGE, TOP_EDGE, V0_EDGE, V1_EDGE };
1972
1973   for ( int i = 0 ; i < 4 ; ++i ) {
1974     Handle(Geom2d_Line) line;
1975     switch ( iEdge[ i ] ) {
1976     case TOP_EDGE:
1977       line = new Geom2d_Line( gp_Pnt2d( 0, 1 ), gp::DX2d() ); break;
1978     case BOTTOM_EDGE:
1979       line = new Geom2d_Line( gp::Origin2d(), gp::DX2d() ); break;
1980     case V0_EDGE:
1981       line = new Geom2d_Line( gp::Origin2d(), gp::DY2d() ); break;
1982     case V1_EDGE:
1983       line = new Geom2d_Line( gp_Pnt2d( 1, 0 ), gp::DY2d() ); break;
1984     }
1985     pcurv[ i ] = new Geom2dAdaptor_Curve( line, 0, 1 );
1986   }
1987   return true;
1988 }
1989
1990 //================================================================================
1991 /*!
1992  * \brief Returns geometry of pcurve on a horizontal face
1993   * \param isTop - is top or bottom face
1994   * \param horFace - a horizontal face
1995   * \retval Adaptor2d_Curve2d* - curve adaptor
1996  */
1997 //================================================================================
1998
1999 Adaptor2d_Curve2d*
2000 StdMeshers_PrismAsBlock::TSideFace::HorizPCurve(const bool         isTop,
2001                                                 const TopoDS_Face& horFace) const
2002 {
2003   return new TPCurveOnHorFaceAdaptor( this, isTop, horFace );
2004 }
2005
2006 //================================================================================
2007 /*!
2008  * \brief Return a component corresponding to parameter
2009   * \param U - parameter along a horizontal size
2010   * \param localU - parameter along a horizontal size of a component
2011   * \retval TSideFace* - found component
2012  */
2013 //================================================================================
2014
2015 StdMeshers_PrismAsBlock::TSideFace*
2016 StdMeshers_PrismAsBlock::TSideFace::GetComponent(const double U,double & localU) const
2017 {
2018   localU = U;
2019   if ( myComponents.empty() )
2020     return const_cast<TSideFace*>( this );
2021
2022   int i;
2023   for ( i = 0; i < myComponents.size(); ++i )
2024     if ( U < myParams[ i ].second )
2025       break;
2026   if ( i >= myComponents.size() )
2027     i = myComponents.size() - 1;
2028
2029   double f = myParams[ i ].first, l = myParams[ i ].second;
2030   localU = ( U - f ) / ( l - f );
2031   return myComponents[ i ];
2032 }
2033
2034 //================================================================================
2035 /*!
2036  * \brief Find node columns for a parameter
2037   * \param U - parameter along a horizontal edge
2038   * \param col1 - the 1st found column
2039   * \param col2 - the 2nd found column
2040   * \retval r - normalized position of U between the found columns
2041  */
2042 //================================================================================
2043
2044 double StdMeshers_PrismAsBlock::TSideFace::GetColumns(const double      U,
2045                                                       TParam2ColumnIt & col1,
2046                                                       TParam2ColumnIt & col2) const
2047 {
2048   double u = U, r = 0;
2049   if ( !myComponents.empty() ) {
2050     TSideFace * comp = GetComponent(U,u);
2051     return comp->GetColumns( u, col1, col2 );
2052   }
2053
2054   if ( !myIsForward )
2055     u = 1 - u;
2056   double f = myParams[0].first, l = myParams[0].second;
2057   u = f + u * ( l - f );
2058
2059   col1 = col2 = getColumn( myParamToColumnMap, u );
2060   if ( ++col2 == myParamToColumnMap->end() ) {
2061     --col2;
2062     r = 0.5;
2063   }
2064   else {
2065     double uf = col1->first;
2066     double ul = col2->first;
2067     r = ( u - uf ) / ( ul - uf );
2068   }
2069   return r;
2070 }
2071
2072 //================================================================================
2073 /*!
2074  * \brief Return coordinates by normalized params
2075   * \param U - horizontal param
2076   * \param V - vertical param
2077   * \retval gp_Pnt - result point
2078  */
2079 //================================================================================
2080
2081 gp_Pnt StdMeshers_PrismAsBlock::TSideFace::Value(const Standard_Real U,
2082                                                  const Standard_Real V) const
2083 {
2084   if ( !myComponents.empty() ) {
2085     double u;
2086     TSideFace * comp = GetComponent(U,u);
2087     return comp->Value( u, V );
2088   }
2089
2090   TParam2ColumnIt u_col1, u_col2;
2091   double vR, hR = GetColumns( U, u_col1, u_col2 );
2092
2093   const SMDS_MeshNode* n1 = 0;
2094   const SMDS_MeshNode* n2 = 0;
2095   const SMDS_MeshNode* n3 = 0;
2096   const SMDS_MeshNode* n4 = 0;
2097
2098   // BEGIN issue 0020680: EDF 1252 SMESH: Bad cell created by Radial prism in center of torus
2099   // Workaround for a wrongly located point returned by mySurface.Value() for
2100   // UV located near boundary of BSpline surface.
2101   // To bypass the problem, we take point from 3D curve of edge.
2102   // It solves pb of the bloc_fiss_new.py
2103   const double tol = 1e-3;
2104   if ( V < tol || V+tol >= 1. )
2105   {
2106     n1 = V < tol ? u_col1->second.front() : u_col1->second.back();
2107     n3 = V < tol ? u_col2->second.front() : u_col2->second.back();
2108     TopoDS_Edge edge;
2109     if ( V < tol )
2110     {
2111       edge = myBaseEdge;
2112     }
2113     else
2114     {
2115       TopoDS_Shape s = myHelper->GetSubShapeByNode( n1, myHelper->GetMeshDS() );
2116       if ( s.ShapeType() != TopAbs_EDGE )
2117         s = myHelper->GetSubShapeByNode( n3, myHelper->GetMeshDS() );
2118       if ( s.ShapeType() == TopAbs_EDGE )
2119         edge = TopoDS::Edge( s );
2120     }
2121     if ( !edge.IsNull() )
2122     {
2123       double u1 = myHelper->GetNodeU( edge, n1 );
2124       double u3 = myHelper->GetNodeU( edge, n3 );
2125       double u = u1 * ( 1 - hR ) + u3 * hR;
2126       TopLoc_Location loc; double f,l;
2127       Handle(Geom_Curve) curve = BRep_Tool::Curve( edge,loc,f,l );
2128       return curve->Value( u ).Transformed( loc );
2129     }
2130   }
2131   // END issue 0020680: EDF 1252 SMESH: Bad cell created by Radial prism in center of torus
2132
2133   vR = getRAndNodes( & u_col1->second, V, n1, n2 );
2134   vR = getRAndNodes( & u_col2->second, V, n3, n4 );
2135   
2136   gp_XY uv1 = myHelper->GetNodeUV( mySurface.Face(), n1, n4);
2137   gp_XY uv2 = myHelper->GetNodeUV( mySurface.Face(), n2, n3);
2138   gp_XY uv12 = uv1 * ( 1 - vR ) + uv2 * vR;
2139
2140   gp_XY uv3 = myHelper->GetNodeUV( mySurface.Face(), n3, n2);
2141   gp_XY uv4 = myHelper->GetNodeUV( mySurface.Face(), n4, n1);
2142   gp_XY uv34 = uv3 * ( 1 - vR ) + uv4 * vR;
2143
2144   gp_XY uv = uv12 * ( 1 - hR ) + uv34 * hR;
2145
2146   gp_Pnt p = mySurface.Value( uv.X(), uv.Y() );
2147   return p;
2148 }
2149
2150
2151 //================================================================================
2152 /*!
2153  * \brief Return boundary edge
2154   * \param edge - edge index
2155   * \retval TopoDS_Edge - found edge
2156  */
2157 //================================================================================
2158
2159 TopoDS_Edge StdMeshers_PrismAsBlock::TSideFace::GetEdge(const int iEdge) const
2160 {
2161   if ( !myComponents.empty() ) {
2162     switch ( iEdge ) {
2163     case V0_EDGE : return myComponents.front()->GetEdge( iEdge );
2164     case V1_EDGE : return myComponents.back() ->GetEdge( iEdge );
2165     default: return TopoDS_Edge();
2166     }
2167   }
2168   TopoDS_Shape edge;
2169   const SMDS_MeshNode* node = 0;
2170   SMESHDS_Mesh * meshDS = myHelper->GetMesh()->GetMeshDS();
2171   TNodeColumn* column;
2172
2173   switch ( iEdge ) {
2174   case TOP_EDGE:
2175   case BOTTOM_EDGE:
2176     column = & (( ++myParamToColumnMap->begin())->second );
2177     node = ( iEdge == TOP_EDGE ) ? column->back() : column->front();
2178     edge = myHelper->GetSubShapeByNode ( node, meshDS );
2179     if ( edge.ShapeType() == TopAbs_VERTEX ) {
2180       column = & ( myParamToColumnMap->begin()->second );
2181       node = ( iEdge == TOP_EDGE ) ? column->back() : column->front();
2182     }
2183     break;
2184   case V0_EDGE:
2185   case V1_EDGE: {
2186     bool back = ( iEdge == V1_EDGE );
2187     if ( !myIsForward ) back = !back;
2188     if ( back )
2189       column = & ( myParamToColumnMap->rbegin()->second );
2190     else
2191       column = & ( myParamToColumnMap->begin()->second );
2192     if ( column->size() > 0 )
2193       edge = myHelper->GetSubShapeByNode( (*column)[ 1 ], meshDS );
2194     if ( edge.IsNull() || edge.ShapeType() == TopAbs_VERTEX )
2195       node = column->front();
2196     break;
2197   }
2198   default:;
2199   }
2200   if ( !edge.IsNull() && edge.ShapeType() == TopAbs_EDGE )
2201     return TopoDS::Edge( edge );
2202
2203   // find edge by 2 vertices
2204   TopoDS_Shape V1 = edge;
2205   TopoDS_Shape V2 = myHelper->GetSubShapeByNode( node, meshDS );
2206   if ( V2.ShapeType() == TopAbs_VERTEX && !V2.IsSame( V1 ))
2207   {
2208     TopoDS_Shape ancestor = myHelper->GetCommonAncestor( V1, V2, *myHelper->GetMesh(), TopAbs_EDGE);
2209     if ( !ancestor.IsNull() )
2210       return TopoDS::Edge( ancestor );
2211   }
2212   return TopoDS_Edge();
2213 }
2214
2215 //================================================================================
2216 /*!
2217  * \brief Fill block sub-shapes
2218   * \param shapeMap - map to fill in
2219   * \retval int - nb inserted sub-shapes
2220  */
2221 //================================================================================
2222
2223 int StdMeshers_PrismAsBlock::TSideFace::InsertSubShapes(TBlockShapes& shapeMap) const
2224 {
2225   int nbInserted = 0;
2226
2227   // Insert edges
2228   vector< int > edgeIdVec;
2229   SMESH_Block::GetFaceEdgesIDs( myID, edgeIdVec );
2230
2231   for ( int i = BOTTOM_EDGE; i <=V1_EDGE ; ++i ) {
2232     TopoDS_Edge e = GetEdge( i );
2233     if ( !e.IsNull() ) {
2234       nbInserted += SMESH_Block::Insert( e, edgeIdVec[ i ], shapeMap);
2235     }
2236   }
2237
2238   // Insert corner vertices
2239
2240   TParam2ColumnIt col1, col2 ;
2241   vector< int > vertIdVec;
2242
2243   // from V0 column
2244   SMESH_Block::GetEdgeVertexIDs( edgeIdVec[ V0_EDGE ], vertIdVec);
2245   GetColumns(0, col1, col2 );
2246   const SMDS_MeshNode* node0 = col1->second.front();
2247   const SMDS_MeshNode* node1 = col1->second.back();
2248   TopoDS_Shape v0 = myHelper->GetSubShapeByNode( node0, myHelper->GetMeshDS());
2249   TopoDS_Shape v1 = myHelper->GetSubShapeByNode( node1, myHelper->GetMeshDS());
2250   if ( v0.ShapeType() == TopAbs_VERTEX ) {
2251     nbInserted += SMESH_Block::Insert( v0, vertIdVec[ 0 ], shapeMap);
2252   }
2253   if ( v1.ShapeType() == TopAbs_VERTEX ) {
2254     nbInserted += SMESH_Block::Insert( v1, vertIdVec[ 1 ], shapeMap);
2255   }
2256   
2257   // from V1 column
2258   SMESH_Block::GetEdgeVertexIDs( edgeIdVec[ V1_EDGE ], vertIdVec);
2259   GetColumns(1, col1, col2 );
2260   node0 = col2->second.front();
2261   node1 = col2->second.back();
2262   v0 = myHelper->GetSubShapeByNode( node0, myHelper->GetMeshDS());
2263   v1 = myHelper->GetSubShapeByNode( node1, myHelper->GetMeshDS());
2264   if ( v0.ShapeType() == TopAbs_VERTEX ) {
2265     nbInserted += SMESH_Block::Insert( v0, vertIdVec[ 0 ], shapeMap);
2266   }
2267   if ( v1.ShapeType() == TopAbs_VERTEX ) {
2268     nbInserted += SMESH_Block::Insert( v1, vertIdVec[ 1 ], shapeMap);
2269   }
2270
2271 //   TopoDS_Vertex V0, V1, Vcom;
2272 //   TopExp::Vertices( myBaseEdge, V0, V1, true );
2273 //   if ( !myIsForward ) std::swap( V0, V1 );
2274
2275 //   // bottom vertex IDs
2276 //   SMESH_Block::GetEdgeVertexIDs( edgeIdVec[ _u0 ], vertIdVec);
2277 //   SMESH_Block::Insert( V0, vertIdVec[ 0 ], shapeMap);
2278 //   SMESH_Block::Insert( V1, vertIdVec[ 1 ], shapeMap);
2279
2280 //   TopoDS_Edge sideEdge = GetEdge( V0_EDGE );
2281 //   if ( sideEdge.IsNull() || !TopExp::CommonVertex( botEdge, sideEdge, Vcom ))
2282 //     return false;
2283
2284 //   // insert one side edge
2285 //   int edgeID;
2286 //   if ( Vcom.IsSame( V0 )) edgeID = edgeIdVec[ _v0 ];
2287 //   else                    edgeID = edgeIdVec[ _v1 ];
2288 //   SMESH_Block::Insert( sideEdge, edgeID, shapeMap);
2289
2290 //   // top vertex of the side edge
2291 //   SMESH_Block::GetEdgeVertexIDs( edgeID, vertIdVec);
2292 //   TopoDS_Vertex Vtop = TopExp::FirstVertex( sideEdge );
2293 //   if ( Vcom.IsSame( Vtop ))
2294 //     Vtop = TopExp::LastVertex( sideEdge );
2295 //   SMESH_Block::Insert( Vtop, vertIdVec[ 1 ], shapeMap);
2296
2297 //   // other side edge
2298 //   sideEdge = GetEdge( V1_EDGE );
2299 //   if ( sideEdge.IsNull() )
2300 //     return false;
2301 //   if ( edgeID = edgeIdVec[ _v1 ]) edgeID = edgeIdVec[ _v0 ];
2302 //   else                            edgeID = edgeIdVec[ _v1 ];
2303 //   SMESH_Block::Insert( sideEdge, edgeID, shapeMap);
2304   
2305 //   // top edge
2306 //   TopoDS_Edge topEdge = GetEdge( TOP_EDGE );
2307 //   SMESH_Block::Insert( topEdge, edgeIdVec[ _u1 ], shapeMap);
2308
2309 //   // top vertex of the other side edge
2310 //   if ( !TopExp::CommonVertex( topEdge, sideEdge, Vcom ))
2311 //     return false;
2312 //   SMESH_Block::GetEdgeVertexIDs( edgeID, vertIdVec );
2313 //   SMESH_Block::Insert( Vcom, vertIdVec[ 1 ], shapeMap);
2314
2315   return nbInserted;
2316 }
2317
2318 //================================================================================
2319 /*!
2320  * \brief Dump ids of nodes of sides
2321  */
2322 //================================================================================
2323
2324 void StdMeshers_PrismAsBlock::TSideFace::dumpNodes(int nbNodes) const
2325 {
2326 #ifdef _DEBUG_
2327   cout << endl << "NODES OF FACE "; SMESH_Block::DumpShapeID( myID, cout ) << endl;
2328   THorizontalEdgeAdaptor* hSize0 = (THorizontalEdgeAdaptor*) HorizCurve(0);
2329   cout << "Horiz side 0: "; hSize0->dumpNodes(nbNodes); cout << endl;
2330   THorizontalEdgeAdaptor* hSize1 = (THorizontalEdgeAdaptor*) HorizCurve(1);
2331   cout << "Horiz side 1: "; hSize1->dumpNodes(nbNodes); cout << endl;
2332   TVerticalEdgeAdaptor* vSide0 = (TVerticalEdgeAdaptor*) VertiCurve(0);
2333   cout << "Verti side 0: "; vSide0->dumpNodes(nbNodes); cout << endl;
2334   TVerticalEdgeAdaptor* vSide1 = (TVerticalEdgeAdaptor*) VertiCurve(1);
2335   cout << "Verti side 1: "; vSide1->dumpNodes(nbNodes); cout << endl;
2336   delete hSize0; delete hSize1; delete vSide0; delete vSide1;
2337 #endif
2338 }
2339
2340 //================================================================================
2341 /*!
2342  * \brief Creates TVerticalEdgeAdaptor 
2343   * \param columnsMap - node column map
2344   * \param parameter - normalized parameter
2345  */
2346 //================================================================================
2347
2348 StdMeshers_PrismAsBlock::TVerticalEdgeAdaptor::
2349 TVerticalEdgeAdaptor( const TParam2ColumnMap* columnsMap, const double parameter)
2350 {
2351   myNodeColumn = & getColumn( columnsMap, parameter )->second;
2352 }
2353
2354 //================================================================================
2355 /*!
2356  * \brief Return coordinates for the given normalized parameter
2357   * \param U - normalized parameter
2358   * \retval gp_Pnt - coordinates
2359  */
2360 //================================================================================
2361
2362 gp_Pnt StdMeshers_PrismAsBlock::TVerticalEdgeAdaptor::Value(const Standard_Real U) const
2363 {
2364   const SMDS_MeshNode* n1;
2365   const SMDS_MeshNode* n2;
2366   double r = getRAndNodes( myNodeColumn, U, n1, n2 );
2367   return gpXYZ(n1) * ( 1 - r ) + gpXYZ(n2) * r;
2368 }
2369
2370 //================================================================================
2371 /*!
2372  * \brief Dump ids of nodes
2373  */
2374 //================================================================================
2375
2376 void StdMeshers_PrismAsBlock::TVerticalEdgeAdaptor::dumpNodes(int nbNodes) const
2377 {
2378 #ifdef _DEBUG_
2379   for ( int i = 0; i < nbNodes && i < myNodeColumn->size(); ++i )
2380     cout << (*myNodeColumn)[i]->GetID() << " ";
2381   if ( nbNodes < myNodeColumn->size() )
2382     cout << myNodeColumn->back()->GetID();
2383 #endif
2384 }
2385
2386 //================================================================================
2387 /*!
2388  * \brief Return coordinates for the given normalized parameter
2389   * \param U - normalized parameter
2390   * \retval gp_Pnt - coordinates
2391  */
2392 //================================================================================
2393
2394 gp_Pnt StdMeshers_PrismAsBlock::THorizontalEdgeAdaptor::Value(const Standard_Real U) const
2395 {
2396   return mySide->TSideFace::Value( U, myV );
2397 }
2398
2399 //================================================================================
2400 /*!
2401  * \brief Dump ids of <nbNodes> first nodes and the last one
2402  */
2403 //================================================================================
2404
2405 void StdMeshers_PrismAsBlock::THorizontalEdgeAdaptor::dumpNodes(int nbNodes) const
2406 {
2407 #ifdef _DEBUG_
2408   // Not bedugged code. Last node is sometimes incorrect
2409   const TSideFace* side = mySide;
2410   double u = 0;
2411   if ( mySide->IsComplex() )
2412     side = mySide->GetComponent(0,u);
2413
2414   TParam2ColumnIt col, col2;
2415   TParam2ColumnMap* u2cols = side->GetColumns();
2416   side->GetColumns( u , col, col2 );
2417   
2418   int j, i = myV ? mySide->ColumnHeight()-1 : 0;
2419
2420   const SMDS_MeshNode* n = 0;
2421   const SMDS_MeshNode* lastN
2422     = side->IsForward() ? u2cols->rbegin()->second[ i ] : u2cols->begin()->second[ i ];
2423   for ( j = 0; j < nbNodes && n != lastN; ++j )
2424   {
2425     n = col->second[ i ];
2426     cout << n->GetID() << " ";
2427     if ( side->IsForward() )
2428       ++col;
2429     else
2430       --col;
2431   }
2432
2433   // last node
2434   u = 1;
2435   if ( mySide->IsComplex() )
2436     side = mySide->GetComponent(1,u);
2437
2438   side->GetColumns( u , col, col2 );
2439   if ( n != col->second[ i ] )
2440     cout << col->second[ i ]->GetID();
2441 #endif
2442 }
2443 //================================================================================
2444 /*!
2445  * \brief Return UV on pcurve for the given normalized parameter
2446   * \param U - normalized parameter
2447   * \retval gp_Pnt - coordinates
2448  */
2449 //================================================================================
2450
2451 gp_Pnt2d StdMeshers_PrismAsBlock::TPCurveOnHorFaceAdaptor::Value(const Standard_Real U) const
2452 {
2453   TParam2ColumnIt u_col1, u_col2;
2454   double r = mySide->GetColumns( U, u_col1, u_col2 );
2455   gp_XY uv1 = mySide->GetNodeUV( myFace, u_col1->second[ myZ ]);
2456   gp_XY uv2 = mySide->GetNodeUV( myFace, u_col2->second[ myZ ]);
2457   return uv1 * ( 1 - r ) + uv2 * r;
2458 }