Salome HOME
#include SMESH_MeshEditor.hxx via SMESH_MesherHelper.hxx
[modules/smesh.git] / src / StdMeshers / StdMeshers_Prism_3D.cxx
1 //  Copyright (C) 2007-2008  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 //  SMESH SMESH : implementaion of SMESH idl descriptions
23 // File      : StdMeshers_Prism_3D.cxx
24 // Module    : SMESH
25 // Created   : Fri Oct 20 11:37:07 2006
26 // Author    : Edward AGAPOV (eap)
27 //
28 #include "StdMeshers_Prism_3D.hxx"
29
30 #include "StdMeshers_ProjectionUtils.hxx"
31 #include "SMESH_MesherHelper.hxx"
32 #include "SMDS_VolumeTool.hxx"
33 #include "SMDS_VolumeOfNodes.hxx"
34 #include "SMDS_EdgePosition.hxx"
35 #include "SMESH_Comment.hxx"
36
37 #include "utilities.h"
38
39 #include <BRep_Tool.hxx>
40 #include <Geom2dAdaptor_Curve.hxx>
41 #include <Geom2d_Line.hxx>
42 #include <TopExp.hxx>
43 #include <TopExp_Explorer.hxx>
44 #include <TopTools_ListIteratorOfListOfShape.hxx>
45 #include <TopoDS.hxx>
46
47 using namespace std;
48
49 #define RETURN_BAD_RESULT(msg) { MESSAGE(")-: Error: " << msg); return false; }
50 #define gpXYZ(n) gp_XYZ(n->X(),n->Y(),n->Z())
51 #define SHOWYXZ(msg, xyz) // {\
52 // gp_Pnt p (xyz); \
53 // cout << msg << " ("<< p.X() << "; " <<p.Y() << "; " <<p.Z() << ") " <<endl;\
54 // }
55
56 typedef StdMeshers_ProjectionUtils TAssocTool;
57 typedef SMESH_Comment              TCom;
58
59 enum { ID_BOT_FACE = SMESH_Block::ID_Fxy0,
60        ID_TOP_FACE = SMESH_Block::ID_Fxy1,
61        BOTTOM_EDGE = 0, TOP_EDGE, V0_EDGE, V1_EDGE, // edge IDs in face
62        NB_WALL_FACES = 4 }; //
63
64 namespace {
65
66   //================================================================================
67   /*!
68    * \brief Return iterator pointing to node column for the given parameter
69    * \param columnsMap - node column map
70    * \param parameter - parameter
71    * \retval TParam2ColumnMap::iterator - result
72    *
73    * it returns closest left column
74    */
75   //================================================================================
76
77   TParam2ColumnIt getColumn( const TParam2ColumnMap* columnsMap,
78                              const double            parameter )
79   {
80     TParam2ColumnIt u_col = columnsMap->upper_bound( parameter );
81     if ( u_col != columnsMap->begin() )
82       --u_col;
83     return u_col; // return left column
84   }
85
86   //================================================================================
87   /*!
88    * \brief Return nodes around given parameter and a ratio
89    * \param column - node column
90    * \param param - parameter
91    * \param node1 - lower node
92    * \param node2 - upper node
93    * \retval double - ratio
94    */
95   //================================================================================
96
97   double getRAndNodes( const TNodeColumn*     column,
98                        const double           param,
99                        const SMDS_MeshNode* & node1,
100                        const SMDS_MeshNode* & node2)
101   {
102     if ( param >= 1.0 || column->size() == 1) {
103       node1 = node2 = column->back();
104       return 0;
105     }
106
107     int i = int( param * ( column->size() - 1 ));
108     double u0 = double( i )/ double( column->size() - 1 );
109     double r = ( param - u0 ) * ( column->size() - 1 );
110
111     node1 = (*column)[ i ];
112     node2 = (*column)[ i + 1];
113     return r;
114   }
115
116   //================================================================================
117   /*!
118    * \brief Compute boundary parameters of face parts
119     * \param nbParts - nb of parts to split columns into
120     * \param columnsMap - node columns of the face to split
121     * \param params - computed parameters
122    */
123   //================================================================================
124
125   void splitParams( const int               nbParts,
126                     const TParam2ColumnMap* columnsMap,
127                     vector< double > &      params)
128   {
129     params.clear();
130     params.reserve( nbParts + 1 );
131     TParam2ColumnIt last_par_col = --columnsMap->end();
132     double par = columnsMap->begin()->first; // 0.
133     double parLast = last_par_col->first;
134     params.push_back( par );
135     for ( int i = 0; i < nbParts - 1; ++ i )
136     {
137       double partSize = ( parLast - par ) / double ( nbParts - i );
138       TParam2ColumnIt par_col = getColumn( columnsMap, par + partSize );
139       if ( par_col->first == par ) {
140         ++par_col;
141         if ( par_col == last_par_col ) {
142           while ( i < nbParts - 1 )
143             params.push_back( par + partSize * i++ );
144           break;
145         }
146       }
147       par = par_col->first;
148       params.push_back( par );
149     }
150     params.push_back( parLast ); // 1.
151   }
152 }
153
154 //=======================================================================
155 //function : StdMeshers_Prism_3D
156 //purpose  : 
157 //=======================================================================
158
159 StdMeshers_Prism_3D::StdMeshers_Prism_3D(int hypId, int studyId, SMESH_Gen* gen)
160   :SMESH_3D_Algo(hypId, studyId, gen)
161 {
162   _name = "Prism_3D";
163   _shapeType = (1 << TopAbs_SHELL) | (1 << TopAbs_SOLID);       // 1 bit per shape type
164   myProjectTriangles = false;
165 }
166
167 //================================================================================
168 /*!
169  * \brief Destructor
170  */
171 //================================================================================
172
173 StdMeshers_Prism_3D::~StdMeshers_Prism_3D()
174 {}
175
176 //=======================================================================
177 //function : CheckHypothesis
178 //purpose  : 
179 //=======================================================================
180
181 bool StdMeshers_Prism_3D::CheckHypothesis(SMESH_Mesh&                          aMesh,
182                                           const TopoDS_Shape&                  aShape,
183                                           SMESH_Hypothesis::Hypothesis_Status& aStatus)
184 {
185   // Check shape geometry
186 /*  PAL16229
187   aStatus = SMESH_Hypothesis::HYP_BAD_GEOMETRY;
188
189   // find not quadrangle faces
190   list< TopoDS_Shape > notQuadFaces;
191   int nbEdge, nbWire, nbFace = 0;
192   TopExp_Explorer exp( aShape, TopAbs_FACE );
193   for ( ; exp.More(); exp.Next() ) {
194     ++nbFace;
195     const TopoDS_Shape& face = exp.Current();
196     nbEdge = TAssocTool::Count( face, TopAbs_EDGE, 0 );
197     nbWire = TAssocTool::Count( face, TopAbs_WIRE, 0 );
198     if (  nbEdge!= 4 || nbWire!= 1 ) {
199       if ( !notQuadFaces.empty() ) {
200         if ( TAssocTool::Count( notQuadFaces.back(), TopAbs_EDGE, 0 ) != nbEdge ||
201              TAssocTool::Count( notQuadFaces.back(), TopAbs_WIRE, 0 ) != nbWire )
202           RETURN_BAD_RESULT("Different not quad faces");
203       }
204       notQuadFaces.push_back( face );
205     }
206   }
207   if ( !notQuadFaces.empty() )
208   {
209     if ( notQuadFaces.size() != 2 )
210       RETURN_BAD_RESULT("Bad nb not quad faces: " << notQuadFaces.size());
211
212     // check total nb faces
213     nbEdge = TAssocTool::Count( notQuadFaces.back(), TopAbs_EDGE, 0 );
214     if ( nbFace != nbEdge + 2 )
215       RETURN_BAD_RESULT("Bad nb of faces: " << nbFace << " but must be " << nbEdge + 2);
216   }
217 */
218   // no hypothesis
219   aStatus = SMESH_Hypothesis::HYP_OK;
220   return true;
221 }
222
223 //=======================================================================
224 //function : Compute
225 //purpose  : 
226 //=======================================================================
227
228 bool StdMeshers_Prism_3D::Compute(SMESH_Mesh& theMesh, const TopoDS_Shape& theShape)
229 {
230   SMESH_MesherHelper helper( theMesh );
231   myHelper = &helper;
232
233   myHelper->IsQuadraticSubMesh( theShape );
234
235   // Analyse mesh and geomerty to find block subshapes and submeshes
236   if ( !myBlock.Init( myHelper, theShape ))
237     return error( myBlock.GetError());
238
239   SMESHDS_Mesh* meshDS = theMesh.GetMeshDS();
240
241   int volumeID = meshDS->ShapeToIndex( theShape );
242
243
244   // To compute coordinates of a node inside a block, it is necessary to know
245   // 1. normalized parameters of the node by which
246   // 2. coordinates of node projections on all block sub-shapes are computed
247
248   // So we fill projections on vertices at once as they are same for all nodes
249   myShapeXYZ.resize( myBlock.NbSubShapes() );
250   for ( int iV = SMESH_Block::ID_FirstV; iV < SMESH_Block::ID_FirstE; ++iV ) {
251     myBlock.VertexPoint( iV, myShapeXYZ[ iV ]);
252     SHOWYXZ("V point " <<iV << " ", myShapeXYZ[ iV ]);
253   }
254
255   // Projections on the top and bottom faces are taken from nodes existing
256   // on these faces; find correspondence between bottom and top nodes
257   myBotToColumnMap.clear();
258   if ( !assocOrProjBottom2Top() ) // it also fill myBotToColumnMap
259     return false;
260
261
262   // Create nodes inside the block
263
264   // loop on nodes inside the bottom face
265   TNode2ColumnMap::iterator bot_column = myBotToColumnMap.begin();
266   for ( ; bot_column != myBotToColumnMap.end(); ++bot_column )
267   {
268     const TNode& tBotNode = bot_column->first; // bottom TNode
269     if ( tBotNode.GetPositionType() != SMDS_TOP_FACE )
270       continue; // node is not inside face 
271
272     // column nodes; middle part of the column are zero pointers
273     TNodeColumn& column = bot_column->second;
274
275     // bottom node parameters and coords
276     myShapeXYZ[ ID_BOT_FACE ] = tBotNode.GetCoords();
277     gp_XYZ botParams          = tBotNode.GetParams();
278
279     // compute top node parameters
280     myShapeXYZ[ ID_TOP_FACE ] = gpXYZ( column.back() );
281     gp_XYZ topParams = botParams;
282     topParams.SetZ( 1 );
283     if ( column.size() > 2 ) {
284       gp_Pnt topCoords = myShapeXYZ[ ID_TOP_FACE ];
285       if ( !myBlock.ComputeParameters( topCoords, topParams, ID_TOP_FACE, topParams ))
286         return error(TCom("Can't compute normalized parameters ")
287                      << "for node " << column.back()->GetID()
288                      << " on the face #"<< column.back()->GetPosition()->GetShapeId() );
289     }
290
291     // vertical loop
292     TNodeColumn::iterator columnNodes = column.begin();
293     for ( int z = 0; columnNodes != column.end(); ++columnNodes, ++z)
294     {
295       const SMDS_MeshNode* & node = *columnNodes;
296       if ( node ) continue; // skip bottom or top node
297
298       // params of a node to create
299       double rz = (double) z / (double) ( column.size() - 1 );
300       gp_XYZ params = botParams * ( 1 - rz ) + topParams * rz;
301
302       // set coords on all faces and nodes
303       const int nbSideFaces = 4;
304       int sideFaceIDs[nbSideFaces] = { SMESH_Block::ID_Fx0z,
305                                        SMESH_Block::ID_Fx1z,
306                                        SMESH_Block::ID_F0yz,
307                                        SMESH_Block::ID_F1yz };
308       for ( int iF = 0; iF < nbSideFaces; ++iF )
309         if ( !setFaceAndEdgesXYZ( sideFaceIDs[ iF ], params, z ))
310           return false;
311
312       // compute coords for a new node
313       gp_XYZ coords;
314       if ( !SMESH_Block::ShellPoint( params, myShapeXYZ, coords ))
315         return error("Can't compute coordinates by normalized parameters");
316
317       SHOWYXZ("TOPFacePoint ",myShapeXYZ[ ID_TOP_FACE]);
318       SHOWYXZ("BOT Node "<< tBotNode.myNode->GetID(),gpXYZ(tBotNode.myNode));
319       SHOWYXZ("ShellPoint ",coords);
320
321       // create a node
322       node = meshDS->AddNode( coords.X(), coords.Y(), coords.Z() );
323       meshDS->SetNodeInVolume( node, volumeID );
324     }
325   } // loop on bottom nodes
326
327
328   // Create volumes
329
330   SMESHDS_SubMesh* smDS = myBlock.SubMeshDS( ID_BOT_FACE );
331   if ( !smDS ) return error(COMPERR_BAD_INPUT_MESH, "Null submesh");
332
333   // loop on bottom mesh faces
334   SMDS_ElemIteratorPtr faceIt = smDS->GetElements();
335   while ( faceIt->more() )
336   {
337     const SMDS_MeshElement* face = faceIt->next();
338     if ( !face || face->GetType() != SMDSAbs_Face )
339       continue;
340     int nbNodes = face->NbNodes();
341     if ( face->IsQuadratic() )
342       nbNodes /= 2;
343
344     // find node columns for each node
345     vector< const TNodeColumn* > columns( nbNodes );
346     for ( int i = 0; i < nbNodes; ++i )
347     {
348       const SMDS_MeshNode* n = face->GetNode( i );
349       if ( n->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE ) {
350         bot_column = myBotToColumnMap.find( n );
351         if ( bot_column == myBotToColumnMap.end() )
352           return error(TCom("No nodes found above node ") << n->GetID() );
353         columns[ i ] = & bot_column->second;
354       }
355       else {
356         columns[ i ] = myBlock.GetNodeColumn( n );
357         if ( !columns[ i ] )
358           return error(TCom("No side nodes found above node ") << n->GetID() );
359       }
360     }
361     // create prisms
362     AddPrisms( columns, myHelper );
363
364   } // loop on bottom mesh faces
365         
366   return true;
367 }
368
369 //================================================================================
370 /*!
371  * \brief Create prisms
372  * \param columns - columns of nodes generated from nodes of a mesh face
373  * \param helper - helper initialized by mesh and shape to add prisms to
374  */
375 //================================================================================
376
377 void StdMeshers_Prism_3D::AddPrisms( vector<const TNodeColumn*> & columns,
378                                      SMESH_MesherHelper*          helper)
379 {
380   SMESHDS_Mesh * meshDS = helper->GetMeshDS();
381   int shapeID = helper->GetSubShapeID();
382
383   int nbNodes = columns.size();
384   int nbZ     = columns[0]->size();
385   if ( nbZ < 2 ) return;
386
387   // find out orientation
388   bool isForward = true;
389   SMDS_VolumeTool vTool;
390   int z = 1;
391   switch ( nbNodes ) {
392   case 3: {
393     const SMDS_MeshNode* botNodes[3] = { (*columns[0])[z-1],
394                                          (*columns[1])[z-1],
395                                          (*columns[2])[z-1] };
396     const SMDS_MeshNode* topNodes[3] = { (*columns[0])[z],
397                                          (*columns[1])[z],
398                                          (*columns[2])[z] };
399     SMDS_VolumeOfNodes tmpVol ( botNodes[0], botNodes[1], botNodes[2],
400                                 topNodes[0], topNodes[1], topNodes[2]);
401     vTool.Set( &tmpVol );
402     isForward  = vTool.IsForward();
403     break;
404   }
405   case 4: {
406     const SMDS_MeshNode* botNodes[4] = { (*columns[0])[z-1], (*columns[1])[z-1],
407                                          (*columns[2])[z-1], (*columns[3])[z-1] };
408     const SMDS_MeshNode* topNodes[4] = { (*columns[0])[z], (*columns[1])[z],
409                                          (*columns[2])[z], (*columns[3])[z] };
410     SMDS_VolumeOfNodes tmpVol ( botNodes[0], botNodes[1], botNodes[2], botNodes[3],
411                                 topNodes[0], topNodes[1], topNodes[2], topNodes[3]);
412     vTool.Set( &tmpVol );
413     isForward  = vTool.IsForward();
414     break;
415   }
416   }
417
418   // vertical loop on columns
419   for ( z = 1; z < nbZ; ++z )
420   {
421     SMDS_MeshElement* vol = 0;
422     switch ( nbNodes ) {
423
424     case 3: {
425       const SMDS_MeshNode* botNodes[3] = { (*columns[0])[z-1],
426                                            (*columns[1])[z-1],
427                                            (*columns[2])[z-1] };
428       const SMDS_MeshNode* topNodes[3] = { (*columns[0])[z],
429                                            (*columns[1])[z],
430                                            (*columns[2])[z] };
431       if ( isForward )
432         vol = helper->AddVolume( botNodes[0], botNodes[1], botNodes[2],
433                                  topNodes[0], topNodes[1], topNodes[2]);
434       else
435         vol = helper->AddVolume( topNodes[0], topNodes[1], topNodes[2],
436                                  botNodes[0], botNodes[1], botNodes[2]);
437       break;
438       }
439     case 4: {
440       const SMDS_MeshNode* botNodes[4] = { (*columns[0])[z-1], (*columns[1])[z-1],
441                                            (*columns[2])[z-1], (*columns[3])[z-1] };
442       const SMDS_MeshNode* topNodes[4] = { (*columns[0])[z], (*columns[1])[z],
443                                            (*columns[2])[z], (*columns[3])[z] };
444       if ( isForward )
445         vol = helper->AddVolume( botNodes[0], botNodes[1], botNodes[2], botNodes[3],
446                                  topNodes[0], topNodes[1], topNodes[2], topNodes[3]);
447       else
448         vol = helper->AddVolume( topNodes[0], topNodes[1], topNodes[2], topNodes[3],
449                                  botNodes[0], botNodes[1], botNodes[2], botNodes[3]);
450       break;
451       }
452     default:
453       // polyhedron
454       vector<const SMDS_MeshNode*> nodes( 2*nbNodes + 4*nbNodes);
455       vector<int> quantities( 2 + nbNodes, 4 );
456       quantities[0] = quantities[1] = nbNodes;
457       columns.resize( nbNodes + 1 );
458       columns[ nbNodes ] = columns[ 0 ];
459       for ( int i = 0; i < nbNodes; ++i ) {
460         nodes[ i         ] = (*columns[ i ])[z-1]; // bottom
461         nodes[ i+nbNodes ] = (*columns[ i ])[z  ]; // top
462         // side
463         int di = 2*nbNodes + 4*i - 1;
464         nodes[ di   ] = (*columns[i  ])[z-1];
465         nodes[ di+1 ] = (*columns[i+1])[z-1];
466         nodes[ di+2 ] = (*columns[i+1])[z  ];
467         nodes[ di+3 ] = (*columns[i  ])[z  ];
468       }
469       vol = meshDS->AddPolyhedralVolume( nodes, quantities );
470     }
471     if ( vol && shapeID > 0 )
472       meshDS->SetMeshElementOnShape( vol, shapeID );
473   }
474 }
475
476 //================================================================================
477 /*!
478  * \brief Find correspondence between bottom and top nodes
479  *  If elements on the bottom and top faces are topologically different,
480  *  and projection is possible and allowed, perform the projection
481  *  \retval bool - is a success or not
482  */
483 //================================================================================
484
485 bool StdMeshers_Prism_3D::assocOrProjBottom2Top()
486 {
487   SMESH_subMesh * botSM = myBlock.SubMesh( ID_BOT_FACE );
488   SMESH_subMesh * topSM = myBlock.SubMesh( ID_TOP_FACE );
489
490   SMESHDS_SubMesh * botSMDS = botSM->GetSubMeshDS();
491   SMESHDS_SubMesh * topSMDS = topSM->GetSubMeshDS();
492
493   if ( !botSMDS || botSMDS->NbElements() == 0 )
494     return error(TCom("No elememts on face #") << botSM->GetId());
495
496   bool needProject = false;
497   if ( !topSMDS || 
498        botSMDS->NbElements() != topSMDS->NbElements() ||
499        botSMDS->NbNodes()    != topSMDS->NbNodes())
500   {
501     if ( myBlock.HasNotQuadElemOnTop() )
502       return error(TCom("Mesh on faces #") << botSM->GetId()
503                    <<" and #"<< topSM->GetId() << " seems different" );
504     needProject = true;
505   }
506
507   if ( 0/*needProject && !myProjectTriangles*/ )
508     return error(TCom("Mesh on faces #") << botSM->GetId()
509                  <<" and #"<< topSM->GetId() << " seems different" );
510   ///RETURN_BAD_RESULT("Need to project but not allowed");
511
512   if ( needProject )
513   {
514     return projectBottomToTop();
515   }
516
517   TopoDS_Face botFace = TopoDS::Face( myBlock.Shape( ID_BOT_FACE ));
518   TopoDS_Face topFace = TopoDS::Face( myBlock.Shape( ID_TOP_FACE ));
519   // associate top and bottom faces
520   TAssocTool::TShapeShapeMap shape2ShapeMap;
521   if ( !TAssocTool::FindSubShapeAssociation( botFace, myBlock.Mesh(),
522                                              topFace, myBlock.Mesh(),
523                                              shape2ShapeMap) )
524     return error(TCom("Topology of faces #") << botSM->GetId()
525                  <<" and #"<< topSM->GetId() << " seems different" );
526
527   // Find matching nodes of top and bottom faces
528   TNodeNodeMap n2nMap;
529   if ( ! TAssocTool::FindMatchingNodesOnFaces( botFace, myBlock.Mesh(),
530                                                topFace, myBlock.Mesh(),
531                                                shape2ShapeMap, n2nMap ))
532     return error(TCom("Mesh on faces #") << botSM->GetId()
533                  <<" and #"<< topSM->GetId() << " seems different" );
534
535   // Fill myBotToColumnMap
536
537   int zSize = myBlock.VerticalSize();
538   TNode prevTNode;
539   TNodeNodeMap::iterator bN_tN = n2nMap.begin();
540   for ( ; bN_tN != n2nMap.end(); ++bN_tN )
541   {
542     const SMDS_MeshNode* botNode = bN_tN->first;
543     const SMDS_MeshNode* topNode = bN_tN->second;
544     if ( botNode->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE )
545       continue; // wall columns are contained in myBlock
546     // compute bottom node params
547     TNode bN( botNode );
548     if ( zSize > 2 ) {
549       gp_XYZ paramHint(-1,-1,-1);
550       if ( prevTNode.IsNeighbor( bN ))
551         paramHint = prevTNode.GetParams();
552       if ( !myBlock.ComputeParameters( bN.GetCoords(), bN.ChangeParams(),
553                                        ID_BOT_FACE, paramHint ))
554         return error(TCom("Can't compute normalized parameters for node ")
555                      << botNode->GetID() << " on the face #"<< botSM->GetId() );
556       prevTNode = bN;
557     }
558     // create node column
559     TNode2ColumnMap::iterator bN_col = 
560       myBotToColumnMap.insert( make_pair ( bN, TNodeColumn() )).first;
561     TNodeColumn & column = bN_col->second;
562     column.resize( zSize );
563     column.front() = botNode;
564     column.back()  = topNode;
565   }
566   return true;
567 }
568
569 //================================================================================
570 /*!
571  * \brief Remove quadrangles from the top face and
572  * create triangles there by projection from the bottom
573  * \retval bool - a success or not
574  */
575 //================================================================================
576
577 bool StdMeshers_Prism_3D::projectBottomToTop()
578 {
579   SMESH_subMesh * botSM = myBlock.SubMesh( ID_BOT_FACE );
580   SMESH_subMesh * topSM = myBlock.SubMesh( ID_TOP_FACE );
581
582   SMESHDS_SubMesh * botSMDS = botSM->GetSubMeshDS();
583   SMESHDS_SubMesh * topSMDS = topSM->GetSubMeshDS();
584
585   if ( topSMDS )
586     topSM->ComputeStateEngine( SMESH_subMesh::CLEAN );
587
588   SMESHDS_Mesh* meshDS = myBlock.MeshDS();
589   int shapeID = myHelper->GetSubShapeID();
590   int topFaceID = meshDS->ShapeToIndex( topSM->GetSubShape() );
591
592   // Fill myBotToColumnMap
593
594   int zSize = myBlock.VerticalSize();
595   TNode prevTNode;
596   SMDS_NodeIteratorPtr nIt = botSMDS->GetNodes();
597   while ( nIt->more() )
598   {
599     const SMDS_MeshNode* botNode = nIt->next();
600     if ( botNode->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE )
601       continue; // strange
602     // compute bottom node params
603     TNode bN( botNode );
604     gp_XYZ paramHint(-1,-1,-1);
605     if ( prevTNode.IsNeighbor( bN ))
606       paramHint = prevTNode.GetParams();
607     if ( !myBlock.ComputeParameters( bN.GetCoords(), bN.ChangeParams(),
608                                      ID_BOT_FACE, paramHint ))
609       return error(TCom("Can't compute normalized parameters for node ")
610                    << botNode->GetID() << " on the face #"<< botSM->GetId() );
611     prevTNode = bN;
612     // compute top node coords
613     gp_XYZ topXYZ; gp_XY topUV;
614     if ( !myBlock.FacePoint( ID_TOP_FACE, bN.GetParams(), topXYZ ) ||
615          !myBlock.FaceUV   ( ID_TOP_FACE, bN.GetParams(), topUV ))
616       return error(TCom("Can't compute coordinates "
617                         "by normalized parameters on the face #")<< topSM->GetId() );
618     SMDS_MeshNode * topNode = meshDS->AddNode( topXYZ.X(),topXYZ.Y(),topXYZ.Z() );
619     meshDS->SetNodeOnFace( topNode, topFaceID, topUV.X(), topUV.Y() );
620     // create node column
621     TNode2ColumnMap::iterator bN_col = 
622       myBotToColumnMap.insert( make_pair ( bN, TNodeColumn() )).first;
623     TNodeColumn & column = bN_col->second;
624     column.resize( zSize );
625     column.front() = botNode;
626     column.back()  = topNode;
627   }
628
629   // Create top faces
630
631   // loop on bottom mesh faces
632   SMDS_ElemIteratorPtr faceIt = botSMDS->GetElements();
633   while ( faceIt->more() )
634   {
635     const SMDS_MeshElement* face = faceIt->next();
636     if ( !face || face->GetType() != SMDSAbs_Face )
637       continue;
638     int nbNodes = face->NbNodes();
639     if ( face->IsQuadratic() )
640       nbNodes /= 2;
641
642     // find top node in columns for each bottom node
643     vector< const SMDS_MeshNode* > nodes( nbNodes );
644     for ( int i = 0; i < nbNodes; ++i )
645     {
646       const SMDS_MeshNode* n = face->GetNode( nbNodes - i - 1 );
647       if ( n->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE ) {
648         TNode2ColumnMap::iterator bot_column = myBotToColumnMap.find( n );
649         if ( bot_column == myBotToColumnMap.end() )
650           return error(TCom("No nodes found above node ") << n->GetID() );
651         nodes[ i ] = bot_column->second.back();
652       }
653       else {
654         const TNodeColumn* column = myBlock.GetNodeColumn( n );
655         if ( !column )
656           return error(TCom("No side nodes found above node ") << n->GetID() );
657         nodes[ i ] = column->back();
658       }
659     }
660     // create a face, with reversed orientation
661     SMDS_MeshElement* newFace = 0;
662     switch ( nbNodes ) {
663
664     case 3: {
665       newFace = myHelper->AddFace(nodes[0], nodes[1], nodes[2]);
666       break;
667       }
668     case 4: {
669       newFace = myHelper->AddFace( nodes[0], nodes[1], nodes[2], nodes[3] );
670       break;
671       }
672     default:
673       newFace = meshDS->AddPolygonalFace( nodes );
674     }
675     if ( newFace && shapeID > 0 )
676       meshDS->SetMeshElementOnShape( newFace, shapeID );
677   }
678
679   return true;
680 }
681
682 //================================================================================
683 /*!
684  * \brief Set projection coordinates of a node to a face and it's subshapes
685  * \param faceID - the face given by in-block ID
686  * \param params - node normalized parameters
687  * \retval bool - is a success
688  */
689 //================================================================================
690
691 bool StdMeshers_Prism_3D::setFaceAndEdgesXYZ( const int faceID, const gp_XYZ& params, int z )
692 {
693   // find base and top edges of the face
694   enum { BASE = 0, TOP, LEFT, RIGHT };
695   vector< int > edgeVec; // 0-base, 1-top
696   SMESH_Block::GetFaceEdgesIDs( faceID, edgeVec );
697
698   myBlock.EdgePoint( edgeVec[ BASE ], params, myShapeXYZ[ edgeVec[ BASE ]]);
699   myBlock.EdgePoint( edgeVec[ TOP ], params, myShapeXYZ[ edgeVec[ TOP ]]);
700
701   SHOWYXZ("\nparams ", params);
702   SHOWYXZ("TOP is "<<edgeVec[ TOP], myShapeXYZ[ edgeVec[ TOP]]);
703   SHOWYXZ("BASE is "<<edgeVec[ BASE], myShapeXYZ[ edgeVec[ BASE]]);
704
705   if ( faceID == SMESH_Block::ID_Fx0z || faceID == SMESH_Block::ID_Fx1z )
706   {
707     myBlock.EdgePoint( edgeVec[ LEFT ], params, myShapeXYZ[ edgeVec[ LEFT ]]);
708     myBlock.EdgePoint( edgeVec[ RIGHT ], params, myShapeXYZ[ edgeVec[ RIGHT ]]);
709
710     SHOWYXZ("VER "<<edgeVec[ LEFT], myShapeXYZ[ edgeVec[ LEFT]]);
711     SHOWYXZ("VER "<<edgeVec[ RIGHT], myShapeXYZ[ edgeVec[ RIGHT]]);
712   }
713   myBlock.FacePoint( faceID, params, myShapeXYZ[ faceID ]);
714   SHOWYXZ("FacePoint "<<faceID, myShapeXYZ[ faceID]);
715
716   return true;
717 }
718
719 //================================================================================
720 /*!
721  * \brief Return true if this node and other one belong to one face
722  */
723 //================================================================================
724
725 bool TNode::IsNeighbor( const TNode& other ) const
726 {
727   if ( !other.myNode || !myNode ) return false;
728
729   SMDS_ElemIteratorPtr fIt = other.myNode->GetInverseElementIterator(SMDSAbs_Face);
730   while ( fIt->more() )
731     if ( fIt->next()->GetNodeIndex( myNode ) >= 0 )
732       return true;
733   return false;
734 }
735
736 //================================================================================
737 /*!
738  * \brief Constructor. Initialization is needed
739  */
740 //================================================================================
741
742 StdMeshers_PrismAsBlock::StdMeshers_PrismAsBlock()
743 {
744   mySide = 0;
745 }
746
747 StdMeshers_PrismAsBlock::~StdMeshers_PrismAsBlock()
748 {
749   if ( mySide ) {
750     delete mySide; mySide = 0;
751   }
752 }
753
754 //================================================================================
755 /*!
756  * \brief Initialization.
757  * \param helper - helper loaded with mesh and 3D shape
758  * \param shape3D - a closed shell or solid
759  * \retval bool - false if a mesh or a shape are KO
760  */
761 //================================================================================
762
763 bool StdMeshers_PrismAsBlock::Init(SMESH_MesherHelper* helper,
764                                    const TopoDS_Shape& shape3D)
765 {
766   if ( mySide ) {
767     delete mySide; mySide = 0;
768   }
769   vector< TSideFace* > sideFaces( NB_WALL_FACES, 0 );
770   vector< pair< double, double> > params ( NB_WALL_FACES );
771   mySide = new TSideFace( sideFaces, params );
772
773   myHelper = helper;
774   SMESHDS_Mesh* meshDS = myHelper->GetMeshDS();
775
776   SMESH_Block::init();
777   myShapeIDMap.Clear();
778   myShapeIndex2ColumnMap.clear();
779   
780   int wallFaceIds[ NB_WALL_FACES ] = { // to walk around a block
781     SMESH_Block::ID_Fx0z, SMESH_Block::ID_F1yz,
782     SMESH_Block::ID_Fx1z, SMESH_Block::ID_F0yz
783   };
784
785   myError = SMESH_ComputeError::New();
786
787   // -------------------------------------------------------------
788   // Look for top and bottom faces: not quadrangle ones or meshed
789   // with not quadrangle elements
790   // -------------------------------------------------------------
791
792   list< SMESH_subMesh* > notQuadGeomSubMesh;
793   list< SMESH_subMesh* > notQuadElemSubMesh;
794   int nbFaces = 0;
795   //
796   SMESH_subMesh* mainSubMesh = myHelper->GetMesh()->GetSubMeshContaining( shape3D );
797   if ( !mainSubMesh ) return error(COMPERR_BAD_INPUT_MESH,"Null submesh of shape3D");
798
799   // analyse face submeshes
800   SMESH_subMeshIteratorPtr smIt = mainSubMesh->getDependsOnIterator(false,false);
801   while ( smIt->more() )
802   {
803     SMESH_subMesh* sm = smIt->next();
804     const TopoDS_Shape& face = sm->GetSubShape();
805     if ( face.ShapeType() != TopAbs_FACE )
806       continue;
807     nbFaces++;
808
809     // is quadrangle face?
810     list< TopoDS_Edge > orderedEdges;
811     list< int >         nbEdgesInWires;
812     TopoDS_Vertex       V000;
813     int nbWires = GetOrderedEdges( TopoDS::Face( face ),
814                                    V000, orderedEdges, nbEdgesInWires );
815     if ( nbWires != 1 || nbEdgesInWires.front() != 4 )
816       notQuadGeomSubMesh.push_back( sm );
817
818     // look for not quadrangle mesh elements
819     if ( SMESHDS_SubMesh* smDS = sm->GetSubMeshDS() ) {
820       bool hasNotQuad = false;
821       SMDS_ElemIteratorPtr eIt = smDS->GetElements();
822       while ( eIt->more() && !hasNotQuad ) {
823         const SMDS_MeshElement* elem = eIt->next();
824         if ( elem->GetType() == SMDSAbs_Face ) {
825           int nbNodes = elem->NbNodes();
826           if ( elem->IsQuadratic() )
827             nbNodes /= 2;
828           hasNotQuad = ( nbNodes != 4 );
829         }
830       }
831       if ( hasNotQuad )
832         notQuadElemSubMesh.push_back( sm );
833     }
834     else {
835       return error(COMPERR_BAD_INPUT_MESH,TCom("Not meshed face #")<<sm->GetId());
836     }
837     // check if a quadrangle face is meshed with a quadranglar grid
838     if ( notQuadGeomSubMesh.back() != sm &&
839          notQuadElemSubMesh.back() != sm )
840     {
841       // count nb edges on face sides
842       vector< int > nbEdges;
843       nbEdges.reserve( nbEdgesInWires.front() );
844       for ( list< TopoDS_Edge >::iterator edge = orderedEdges.begin();
845             edge != orderedEdges.end(); ++edge )
846       {
847         if ( SMESHDS_SubMesh* smDS = meshDS->MeshElements( *edge ))
848           nbEdges.push_back ( smDS->NbElements() );
849         else
850           nbEdges.push_back ( 0 );
851       }
852       int nbQuads = sm->GetSubMeshDS()->NbElements();
853       if ( nbEdges[0] *  nbEdges[1] != nbQuads ||
854            nbEdges[0] != nbEdges[2] ||
855            nbEdges[1] != nbEdges[3] )
856         notQuadElemSubMesh.push_back( sm );
857     }
858   }
859
860   // ----------------------------------------------------------------------
861   // Analyse faces mesh and topology: choose the bottom submesh.
862   // If there are not quadrangle geom faces, they are top and bottom ones.
863   // Not quadrangle geom faces must be only on top and bottom.
864   // ----------------------------------------------------------------------
865
866   SMESH_subMesh * botSM = 0;
867   SMESH_subMesh * topSM = 0;
868
869   int nbNotQuad       = notQuadGeomSubMesh.size();
870   int nbNotQuadMeshed = notQuadElemSubMesh.size();
871   bool hasNotQuad = ( nbNotQuad || nbNotQuadMeshed );
872
873   // detect bad cases
874   if ( nbNotQuad > 0 && nbNotQuad != 2 )
875     return error(COMPERR_BAD_SHAPE,
876                  TCom("More than 2 not quadrilateral faces: ")
877                  <<nbNotQuad);
878   if ( nbNotQuadMeshed > 2 )
879     return error(COMPERR_BAD_INPUT_MESH,
880                  TCom("More than 2 faces with not quadrangle elements: ")
881                  <<nbNotQuadMeshed);
882
883   // get found submeshes
884   if ( hasNotQuad )
885   {
886     if ( nbNotQuadMeshed > 0 ) botSM = notQuadElemSubMesh.front();
887     else                       botSM = notQuadGeomSubMesh.front();
888     if ( nbNotQuadMeshed > 1 ) topSM = notQuadElemSubMesh.back();
889     else if ( nbNotQuad  > 1 ) topSM = notQuadGeomSubMesh.back();
890   }
891   // detect other bad cases
892   if ( nbNotQuad == 2 && nbNotQuadMeshed > 0 ) {
893     bool ok = false;
894     if ( nbNotQuadMeshed == 1 )
895       ok = ( find( notQuadGeomSubMesh.begin(),
896                    notQuadGeomSubMesh.end(), botSM ) != notQuadGeomSubMesh.end() );
897     else
898       ok = ( notQuadGeomSubMesh == notQuadElemSubMesh );
899     if ( !ok )
900       return error(COMPERR_BAD_INPUT_MESH, "Side face meshed with not quadrangle elements");
901   }
902
903   myNotQuadOnTop = ( nbNotQuadMeshed > 1 );
904  
905   // ----------------------------------------------------------
906
907   if ( nbNotQuad == 0 ) // Standard block of 6 quadrangle faces ?
908   {
909     // SMESH_Block will perform geometry analysis, we need just to find 2
910     // connected vertices on top and bottom
911
912     TopoDS_Vertex Vbot, Vtop;
913     if ( nbNotQuadMeshed > 0 ) // Look for vertices
914     {
915       TopTools_IndexedMapOfShape edgeMap;
916       TopExp::MapShapes( botSM->GetSubShape(), TopAbs_EDGE, edgeMap );
917       // vertex 1 is any vertex of the bottom face
918       Vbot = TopExp::FirstVertex( TopoDS::Edge( edgeMap( 1 )));
919       // vertex 2 is end vertex of edge sharing Vbot and not belonging to the bottom face
920       TopTools_ListIteratorOfListOfShape ancestIt = Mesh()->GetAncestors( Vbot );
921       for ( ; Vtop.IsNull() && ancestIt.More(); ancestIt.Next() )
922       {
923         const TopoDS_Shape & ancestor = ancestIt.Value();
924         if ( ancestor.ShapeType() == TopAbs_EDGE && !edgeMap.FindIndex( ancestor ))
925         {
926           TopoDS_Vertex V1, V2;
927           TopExp::Vertices( TopoDS::Edge( ancestor ), V1, V2);
928           if      ( Vbot.IsSame ( V1 )) Vtop = V2;
929           else if ( Vbot.IsSame ( V2 )) Vtop = V1;
930           // check that Vtop belongs to shape3D
931           TopExp_Explorer exp( shape3D, TopAbs_VERTEX );
932           for ( ; exp.More(); exp.Next() )
933             if ( Vtop.IsSame( exp.Current() ))
934               break;
935           if ( !exp.More() )
936             Vtop.Nullify();
937         }
938       }
939     }
940     // get shell from shape3D
941     TopoDS_Shell shell;
942     TopExp_Explorer exp( shape3D, TopAbs_SHELL );
943     int nbShell = 0;
944     for ( ; exp.More(); exp.Next(), ++nbShell )
945       shell = TopoDS::Shell( exp.Current() );
946 //     if ( nbShell != 1 )
947 //       RETURN_BAD_RESULT("There must be 1 shell in the block");
948
949     // Load geometry in SMESH_Block
950     if ( !SMESH_Block::FindBlockShapes( shell, Vbot, Vtop, myShapeIDMap )) {
951       if ( !hasNotQuad )
952         return error(COMPERR_BAD_SHAPE, "Can't detect top and bottom of a prism");
953     }
954     else {
955       if ( !botSM ) botSM = Mesh()->GetSubMeshContaining( myShapeIDMap( ID_BOT_FACE ));
956       if ( !topSM ) topSM = Mesh()->GetSubMeshContaining( myShapeIDMap( ID_TOP_FACE ));
957     }
958
959   } // end  Standard block of 6 quadrangle faces
960   // --------------------------------------------------------
961
962   // Here the top and bottom faces are found
963   if ( nbNotQuadMeshed == 2 ) // roughly check correspondence of horiz meshes
964   {
965 //     SMESHDS_SubMesh* topSMDS = topSM->GetSubMeshDS();
966 //     SMESHDS_SubMesh* botSMDS = botSM->GetSubMeshDS();
967 //     if ( topSMDS->NbNodes() != botSMDS->NbNodes() ||
968 //          topSMDS->NbElements() != botSMDS->NbElements() )
969 //       RETURN_BAD_RESULT("Top mesh doesn't correspond to bottom one");
970   }
971
972   // ---------------------------------------------------------
973   // If there are not quadrangle geom faces, we emulate
974   // a block of 6 quadrangle faces.
975   // Load SMESH_Block with faces and edges geometry
976   // ---------------------------------------------------------
977
978   
979   // find vertex 000 - the one with smallest coordinates (for easy DEBUG :-)
980   TopoDS_Vertex V000;
981   double minVal = DBL_MAX, minX, val;
982   for ( TopExp_Explorer exp( botSM->GetSubShape(), TopAbs_VERTEX );
983         exp.More(); exp.Next() )
984   {
985     const TopoDS_Vertex& v = TopoDS::Vertex( exp.Current() );
986     gp_Pnt P = BRep_Tool::Pnt( v );
987     val = P.X() + P.Y() + P.Z();
988     if ( val < minVal || ( val == minVal && P.X() < minX )) {
989       V000 = v;
990       minVal = val;
991       minX = P.X();
992     }
993   }
994
995   // Get ordered bottom edges
996   list< TopoDS_Edge > orderedEdges;
997   list< int >         nbVertexInWires;
998   SMESH_Block::GetOrderedEdges( TopoDS::Face( botSM->GetSubShape().Reversed() ),
999                                 V000, orderedEdges, nbVertexInWires );
1000 //   if ( nbVertexInWires.size() != 1 )
1001 //     RETURN_BAD_RESULT("Wrong prism geometry");
1002
1003   // Get Wall faces corresponding to the ordered bottom edges
1004   list< TopoDS_Face > wallFaces;
1005   if ( !GetWallFaces( Mesh(), shape3D, botSM->GetSubShape(), orderedEdges, wallFaces))
1006     return error(COMPERR_BAD_SHAPE, "Can't find side faces");
1007
1008   // Find columns of wall nodes and calculate edges' lengths
1009   // --------------------------------------------------------
1010
1011   myParam2ColumnMaps.clear();
1012   myParam2ColumnMaps.resize( orderedEdges.size() ); // total nb edges
1013
1014   int iE, nbEdges = nbVertexInWires.front(); // nb outer edges
1015   vector< double > edgeLength( nbEdges );
1016   map< double, int > len2edgeMap;
1017
1018   list< TopoDS_Edge >::iterator edgeIt = orderedEdges.begin();
1019   list< TopoDS_Face >::iterator faceIt = wallFaces.begin();
1020   for ( iE = 0; iE < nbEdges; ++edgeIt, ++faceIt )
1021   {
1022     TParam2ColumnMap & faceColumns = myParam2ColumnMaps[ iE ];
1023     if ( !myHelper->LoadNodeColumns( faceColumns, *faceIt, *edgeIt, meshDS ))
1024       return error(COMPERR_BAD_INPUT_MESH, TCom("Can't find regular quadrangle mesh ")
1025                    << "on a side face #" << MeshDS()->ShapeToIndex( *faceIt ));
1026
1027     SHOWYXZ("\np1 F "<<iE, gpXYZ(faceColumns.begin()->second.front() ));
1028     SHOWYXZ("p2 F "<<iE, gpXYZ(faceColumns.rbegin()->second.front() ));
1029     SHOWYXZ("V First "<<iE, BRep_Tool::Pnt( TopExp::FirstVertex(*edgeIt,true )));
1030
1031     edgeLength[ iE ] = SMESH_Algo::EdgeLength( *edgeIt );
1032
1033     if ( nbEdges < NB_WALL_FACES ) // fill map used to split faces
1034     {
1035       SMESHDS_SubMesh* smDS = meshDS->MeshElements( *edgeIt);
1036       if ( !smDS )
1037         return error(COMPERR_BAD_INPUT_MESH, TCom("Null submesh on the edge #")
1038                      << MeshDS()->ShapeToIndex( *edgeIt ));
1039       // assure length uniqueness
1040       edgeLength[ iE ] *= smDS->NbNodes() + edgeLength[ iE ] / ( 1000 + iE );
1041       len2edgeMap[ edgeLength[ iE ]] = iE;
1042     }
1043     ++iE;
1044   }
1045   // Load columns of internal edges (forming holes)
1046   // and fill map ShapeIndex to TParam2ColumnMap for them
1047   for ( ; edgeIt != orderedEdges.end() ; ++edgeIt, ++faceIt )
1048   {
1049     TParam2ColumnMap & faceColumns = myParam2ColumnMaps[ iE ];
1050     if ( !myHelper->LoadNodeColumns( faceColumns, *faceIt, *edgeIt, meshDS ))
1051       return error(COMPERR_BAD_INPUT_MESH, TCom("Can't find regular quadrangle mesh ")
1052                    << "on a side face #" << MeshDS()->ShapeToIndex( *faceIt ));
1053     // edge columns
1054     int id = MeshDS()->ShapeToIndex( *edgeIt );
1055     bool isForward = true; // meaningless for intenal wires
1056     myShapeIndex2ColumnMap[ id ] = make_pair( & faceColumns, isForward );
1057     // columns for vertices
1058     // 1
1059     const SMDS_MeshNode* n0 = faceColumns.begin()->second.front();
1060     id = n0->GetPosition()->GetShapeId();
1061     myShapeIndex2ColumnMap[ id ] = make_pair( & faceColumns, isForward );
1062     // 2
1063     const SMDS_MeshNode* n1 = faceColumns.rbegin()->second.front();
1064     id = n1->GetPosition()->GetShapeId();
1065     myShapeIndex2ColumnMap[ id ] = make_pair( & faceColumns, isForward );
1066 //     SHOWYXZ("\np1 F "<<iE, gpXYZ(faceColumns.begin()->second.front() ));
1067 //     SHOWYXZ("p2 F "<<iE, gpXYZ(faceColumns.rbegin()->second.front() ));
1068 //     SHOWYXZ("V First "<<iE, BRep_Tool::Pnt( TopExp::FirstVertex(*edgeIt,true )));
1069     ++iE;
1070   }
1071
1072   // Create 4 wall faces of a block
1073   // -------------------------------
1074
1075   if ( nbEdges <= NB_WALL_FACES ) // ************* Split faces if necessary
1076   {
1077     map< int, int > iE2nbSplit;
1078     if ( nbEdges != NB_WALL_FACES ) // define how to split
1079     {
1080       if ( len2edgeMap.size() != nbEdges )
1081         RETURN_BAD_RESULT("Uniqueness of edge lengths not assured");
1082       map< double, int >::reverse_iterator maxLen_i = len2edgeMap.rbegin();
1083       map< double, int >::reverse_iterator midLen_i = ++len2edgeMap.rbegin();
1084       double maxLen = maxLen_i->first;
1085       double midLen = ( len2edgeMap.size() == 1 ) ? 0 : midLen_i->first;
1086       switch ( nbEdges ) {
1087       case 1: // 0-th edge is split into 4 parts
1088         iE2nbSplit.insert( make_pair( 0, 4 )); break;
1089       case 2: // either the longest edge is split into 3 parts, or both edges into halves
1090         if ( maxLen / 3 > midLen / 2 ) {
1091           iE2nbSplit.insert( make_pair( maxLen_i->second, 3 ));
1092         }
1093         else {
1094           iE2nbSplit.insert( make_pair( maxLen_i->second, 2 ));
1095           iE2nbSplit.insert( make_pair( midLen_i->second, 2 ));
1096         }
1097         break;
1098       case 3:
1099         // split longest into halves
1100         iE2nbSplit.insert( make_pair( maxLen_i->second, 2 ));
1101       }
1102     }
1103     // Create TSideFace's
1104     faceIt = wallFaces.begin();
1105     edgeIt = orderedEdges.begin();
1106     int iSide = 0;
1107     for ( iE = 0; iE < nbEdges; ++edgeIt, ++faceIt )
1108     {
1109      // split?
1110       map< int, int >::iterator i_nb = iE2nbSplit.find( iE );
1111       if ( i_nb != iE2nbSplit.end() ) {
1112         // split!
1113         int nbSplit = i_nb->second;
1114         vector< double > params;
1115         splitParams( nbSplit, &myParam2ColumnMaps[ iE ], params );
1116         bool isForward = ( edgeIt->Orientation() == TopAbs_FORWARD );
1117         for ( int i = 0; i < nbSplit; ++i ) {
1118           double f = ( isForward ? params[ i ] : params[ nbSplit - i-1 ]);
1119           double l = ( isForward ? params[ i+1 ] : params[ nbSplit - i ]);
1120           TSideFace* comp = new TSideFace( myHelper, wallFaceIds[ iSide ],
1121                                            *faceIt, *edgeIt,
1122                                            &myParam2ColumnMaps[ iE ], f, l );
1123           mySide->SetComponent( iSide++, comp );
1124         }
1125       }
1126       else {
1127         TSideFace* comp = new TSideFace( myHelper, wallFaceIds[ iSide ],
1128                                          *faceIt, *edgeIt,
1129                                          &myParam2ColumnMaps[ iE ]);
1130         mySide->SetComponent( iSide++, comp );
1131       }
1132       ++iE;
1133     }
1134   }
1135   else { // **************************** Unite faces
1136
1137     // unite first faces
1138     int nbExraFaces = nbEdges - 3;
1139     int iSide = 0, iE;
1140     double u0 = 0, sumLen = 0;
1141     for ( iE = 0; iE < nbExraFaces; ++iE )
1142       sumLen += edgeLength[ iE ];
1143
1144     vector< TSideFace* > components( nbExraFaces );
1145     vector< pair< double, double> > params( nbExraFaces );
1146     faceIt = wallFaces.begin();
1147     edgeIt = orderedEdges.begin();
1148     for ( iE = 0; iE < nbExraFaces; ++edgeIt, ++faceIt )
1149     {
1150       components[ iE ] = new TSideFace( myHelper, wallFaceIds[ iSide ],
1151                                         *faceIt, *edgeIt,
1152                                         &myParam2ColumnMaps[ iE ]);
1153       double u1 = u0 + edgeLength[ iE ] / sumLen;
1154       params[ iE ] = make_pair( u0 , u1 );
1155       u0 = u1;
1156       ++iE;
1157     }
1158     mySide->SetComponent( iSide++, new TSideFace( components, params ));
1159
1160     // fill the rest faces
1161     for ( ; iE < nbEdges; ++faceIt, ++edgeIt )
1162     {
1163       TSideFace* comp = new TSideFace( myHelper, wallFaceIds[ iSide ],
1164                                        *faceIt, *edgeIt,
1165                                        &myParam2ColumnMaps[ iE ]);
1166       mySide->SetComponent( iSide++, comp );
1167       ++iE;
1168     }
1169   }
1170
1171
1172   // Fill geometry fields of SMESH_Block
1173   // ------------------------------------
1174
1175   TopoDS_Face botF = TopoDS::Face( botSM->GetSubShape() );
1176   TopoDS_Face topF = TopoDS::Face( topSM->GetSubShape() );
1177
1178   vector< int > botEdgeIdVec;
1179   SMESH_Block::GetFaceEdgesIDs( ID_BOT_FACE, botEdgeIdVec );
1180
1181   bool isForward[NB_WALL_FACES] = { true, true, true, true };
1182   Adaptor2d_Curve2d* botPcurves[NB_WALL_FACES];
1183   Adaptor2d_Curve2d* topPcurves[NB_WALL_FACES];
1184
1185   for ( int iF = 0; iF < NB_WALL_FACES; ++iF )
1186   {
1187     TSideFace * sideFace = mySide->GetComponent( iF );
1188     if ( !sideFace )
1189       RETURN_BAD_RESULT("NULL TSideFace");
1190     int fID = sideFace->FaceID();
1191
1192     // fill myShapeIDMap
1193     if ( sideFace->InsertSubShapes( myShapeIDMap ) != 8 &&
1194          !sideFace->IsComplex())
1195       MESSAGE( ": Warning : InsertSubShapes() < 8 on side " << iF );
1196
1197     // side faces geometry
1198     Adaptor2d_Curve2d* pcurves[NB_WALL_FACES];
1199     if ( !sideFace->GetPCurves( pcurves ))
1200       RETURN_BAD_RESULT("TSideFace::GetPCurves() failed");
1201
1202     SMESH_Block::TFace& tFace = myFace[ fID - ID_FirstF ];
1203     tFace.Set( fID, sideFace->Surface(), pcurves, isForward );
1204
1205     SHOWYXZ( endl<<"F "<< iF << " id " << fID << " FRW " << sideFace->IsForward(), sideFace->Value(0,0));
1206     // edges 3D geometry
1207     vector< int > edgeIdVec;
1208     SMESH_Block::GetFaceEdgesIDs( fID, edgeIdVec );
1209     for ( int isMax = 0; isMax < 2; ++isMax ) {
1210       {
1211         int eID = edgeIdVec[ isMax ];
1212         SMESH_Block::TEdge& tEdge = myEdge[ eID - ID_FirstE ];
1213         tEdge.Set( eID, sideFace->HorizCurve(isMax), true);
1214         SHOWYXZ(eID<<" HOR"<<isMax<<"(0)", sideFace->HorizCurve(isMax)->Value(0));
1215         SHOWYXZ(eID<<" HOR"<<isMax<<"(1)", sideFace->HorizCurve(isMax)->Value(1));
1216       }
1217       {
1218         int eID = edgeIdVec[ isMax+2 ];
1219         SMESH_Block::TEdge& tEdge = myEdge[ eID - ID_FirstE  ];
1220         tEdge.Set( eID, sideFace->VertiCurve(isMax), true);
1221         SHOWYXZ(eID<<" VER"<<isMax<<"(0)", sideFace->VertiCurve(isMax)->Value(0));
1222         SHOWYXZ(eID<<" VER"<<isMax<<"(1)", sideFace->VertiCurve(isMax)->Value(1));
1223
1224         // corner points
1225         vector< int > vertexIdVec;
1226         SMESH_Block::GetEdgeVertexIDs( eID, vertexIdVec );
1227         myPnt[ vertexIdVec[0] - ID_FirstV ] = tEdge.GetCurve()->Value(0).XYZ();
1228         myPnt[ vertexIdVec[1] - ID_FirstV ] = tEdge.GetCurve()->Value(1).XYZ();
1229       }
1230     }
1231     // pcurves on horizontal faces
1232     for ( iE = 0; iE < NB_WALL_FACES; ++iE ) {
1233       if ( edgeIdVec[ BOTTOM_EDGE ] == botEdgeIdVec[ iE ] ) {
1234         botPcurves[ iE ] = sideFace->HorizPCurve( false, botF );
1235         topPcurves[ iE ] = sideFace->HorizPCurve( true,  topF );
1236         break;
1237       }
1238     }
1239   }
1240   // horizontal faces geometry
1241   {
1242     SMESH_Block::TFace& tFace = myFace[ ID_BOT_FACE - ID_FirstF ];
1243     tFace.Set( ID_BOT_FACE, new BRepAdaptor_Surface( botF ), botPcurves, isForward );
1244     SMESH_Block::Insert( botF, ID_BOT_FACE, myShapeIDMap );
1245   }
1246   {
1247     SMESH_Block::TFace& tFace = myFace[ ID_TOP_FACE - ID_FirstF ];
1248     tFace.Set( ID_TOP_FACE, new BRepAdaptor_Surface( topF ), topPcurves, isForward );
1249     SMESH_Block::Insert( topF, ID_TOP_FACE, myShapeIDMap );
1250   }
1251
1252   // Fill map ShapeIndex to TParam2ColumnMap
1253   // ----------------------------------------
1254
1255   list< TSideFace* > fList;
1256   list< TSideFace* >::iterator fListIt;
1257   fList.push_back( mySide );
1258   for ( fListIt = fList.begin(); fListIt != fList.end(); ++fListIt)
1259   {
1260     int nb = (*fListIt)->NbComponents();
1261     for ( int i = 0; i < nb; ++i ) {
1262       if ( TSideFace* comp = (*fListIt)->GetComponent( i ))
1263         fList.push_back( comp );
1264     }
1265     if ( TParam2ColumnMap* cols = (*fListIt)->GetColumns()) {
1266       // columns for a base edge
1267       int id = MeshDS()->ShapeToIndex( (*fListIt)->BaseEdge() );
1268       bool isForward = (*fListIt)->IsForward();
1269       myShapeIndex2ColumnMap[ id ] = make_pair( cols, isForward );
1270
1271       // columns for vertices
1272       const SMDS_MeshNode* n0 = cols->begin()->second.front();
1273       id = n0->GetPosition()->GetShapeId();
1274       myShapeIndex2ColumnMap[ id ] = make_pair( cols, isForward );
1275
1276       const SMDS_MeshNode* n1 = cols->rbegin()->second.front();
1277       id = n1->GetPosition()->GetShapeId();
1278       myShapeIndex2ColumnMap[ id ] = make_pair( cols, !isForward );
1279     }
1280   }
1281
1282 //   gp_XYZ testPar(0.25, 0.25, 0), testCoord;
1283 //   if ( !FacePoint( ID_BOT_FACE, testPar, testCoord ))
1284 //     RETURN_BAD_RESULT("TEST FacePoint() FAILED");
1285 //   SHOWYXZ("IN TEST PARAM" , testPar);
1286 //   SHOWYXZ("OUT TEST CORD" , testCoord);
1287 //   if ( !ComputeParameters( testCoord, testPar , ID_BOT_FACE))
1288 //     RETURN_BAD_RESULT("TEST ComputeParameters() FAILED");
1289 //   SHOWYXZ("OUT TEST PARAM" , testPar);
1290
1291   return true;
1292 }
1293
1294 //================================================================================
1295 /*!
1296  * \brief Return pointer to column of nodes
1297  * \param node - bottom node from which the returned column goes up
1298  * \retval const TNodeColumn* - the found column
1299  */
1300 //================================================================================
1301
1302 const TNodeColumn* StdMeshers_PrismAsBlock::GetNodeColumn(const SMDS_MeshNode* node) const
1303 {
1304   int sID = node->GetPosition()->GetShapeId();
1305
1306   map<int, pair< TParam2ColumnMap*, bool > >::const_iterator col_frw =
1307     myShapeIndex2ColumnMap.find( sID );
1308   if ( col_frw != myShapeIndex2ColumnMap.end() ) {
1309     const TParam2ColumnMap* cols = col_frw->second.first;
1310     TParam2ColumnIt u_col = cols->begin();
1311     for ( ; u_col != cols->end(); ++u_col )
1312       if ( u_col->second[ 0 ] == node )
1313         return & u_col->second;
1314   }
1315   return 0;
1316 }
1317
1318 //================================================================================
1319 /*!
1320  * \brief Check curve orientation of a bootom edge
1321   * \param meshDS - mesh DS
1322   * \param columnsMap - node columns map of side face
1323   * \param bottomEdge - the bootom edge
1324   * \param sideFaceID - side face in-block ID
1325   * \retval bool - true if orientation coinside with in-block froward orientation
1326  */
1327 //================================================================================
1328
1329 bool StdMeshers_PrismAsBlock::IsForwardEdge(SMESHDS_Mesh*           meshDS,
1330                                             const TParam2ColumnMap& columnsMap,
1331                                             const TopoDS_Edge &     bottomEdge,
1332                                             const int               sideFaceID)
1333 {
1334   bool isForward = false;
1335   if ( TAssocTool::IsClosedEdge( bottomEdge ))
1336   {
1337     isForward = ( bottomEdge.Orientation() == TopAbs_FORWARD );
1338   }
1339   else
1340   {
1341     const TNodeColumn& firstCol = columnsMap.begin()->second;
1342     const SMDS_MeshNode* bottomNode = firstCol[0];
1343     TopoDS_Shape firstVertex = SMESH_MesherHelper::GetSubShapeByNode( bottomNode, meshDS );
1344     isForward = ( firstVertex.IsSame( TopExp::FirstVertex( bottomEdge, true )));
1345   }
1346   // on 2 of 4 sides first vertex is end
1347   if ( sideFaceID == ID_Fx1z || sideFaceID == ID_F0yz )
1348     isForward = !isForward;
1349   return isForward;
1350 }
1351
1352 //================================================================================
1353   /*!
1354    * \brief Find wall faces by bottom edges
1355     * \param mesh - the mesh
1356     * \param mainShape - the prism
1357     * \param bottomFace - the bottom face
1358     * \param bottomEdges - edges bounding the bottom face
1359     * \param wallFaces - faces list to fill in
1360    */
1361 //================================================================================
1362
1363 bool StdMeshers_PrismAsBlock::GetWallFaces( SMESH_Mesh*                     mesh,
1364                                             const TopoDS_Shape &            mainShape,
1365                                             const TopoDS_Shape &            bottomFace,
1366                                             const std::list< TopoDS_Edge >& bottomEdges,
1367                                             std::list< TopoDS_Face >&       wallFaces)
1368 {
1369   wallFaces.clear();
1370
1371   TopTools_IndexedMapOfShape faceMap;
1372   TopExp::MapShapes( mainShape, TopAbs_FACE, faceMap );
1373
1374   list< TopoDS_Edge >::const_iterator edge = bottomEdges.begin();
1375   for ( ; edge != bottomEdges.end(); ++edge )
1376   {
1377     TopTools_ListIteratorOfListOfShape ancestIt = mesh->GetAncestors( *edge );
1378     for ( ; ancestIt.More(); ancestIt.Next() )
1379     {
1380       const TopoDS_Shape& ancestor = ancestIt.Value();
1381       if ( ancestor.ShapeType() == TopAbs_FACE && // face
1382            !bottomFace.IsSame( ancestor ) &&      // not bottom
1383            faceMap.FindIndex( ancestor ))         // belongs to the prism
1384       {
1385         wallFaces.push_back( TopoDS::Face( ancestor ));
1386         break;
1387       }
1388     }
1389   }
1390   return ( wallFaces.size() == bottomEdges.size() );
1391 }
1392
1393 //================================================================================
1394 /*!
1395  * \brief Constructor
1396   * \param faceID - in-block ID
1397   * \param face - geom face
1398   * \param columnsMap - map of node columns
1399   * \param first - first normalized param
1400   * \param last - last normalized param
1401  */
1402 //================================================================================
1403
1404 StdMeshers_PrismAsBlock::TSideFace::TSideFace(SMESH_MesherHelper* helper,
1405                                               const int           faceID,
1406                                               const TopoDS_Face&  face,
1407                                               const TopoDS_Edge&  baseEdge,
1408                                               TParam2ColumnMap*   columnsMap,
1409                                               const double        first,
1410                                               const double        last):
1411   myID( faceID ),
1412   myParamToColumnMap( columnsMap ),
1413   myBaseEdge( baseEdge ),
1414   myHelper( helper )
1415 {
1416   mySurface.Initialize( face );
1417   myParams.resize( 1 );
1418   myParams[ 0 ] = make_pair( first, last );
1419   myIsForward = StdMeshers_PrismAsBlock::IsForwardEdge( myHelper->GetMeshDS(),
1420                                                         *myParamToColumnMap,
1421                                                         myBaseEdge, myID );
1422 }
1423
1424 //================================================================================
1425 /*!
1426  * \brief Constructor of complex side face
1427  */
1428 //================================================================================
1429
1430 StdMeshers_PrismAsBlock::TSideFace::
1431 TSideFace(const vector< TSideFace* >&             components,
1432           const vector< pair< double, double> > & params)
1433   :myID( components[0] ? components[0]->myID : 0 ),
1434    myParamToColumnMap( 0 ),
1435    myParams( params ),
1436    myIsForward( true ),
1437    myComponents( components ),
1438    myHelper( components[0] ? components[0]->myHelper : 0 )
1439 {}
1440 //================================================================================
1441 /*!
1442  * \brief Copy constructor
1443   * \param other - other side
1444  */
1445 //================================================================================
1446
1447 StdMeshers_PrismAsBlock::TSideFace::TSideFace( const TSideFace& other )
1448 {
1449   myID               = other.myID;
1450   mySurface          = other.mySurface;
1451   myBaseEdge         = other.myBaseEdge;
1452   myParams           = other.myParams;
1453   myIsForward        = other.myIsForward;
1454   myHelper           = other.myHelper;
1455   myParamToColumnMap = other.myParamToColumnMap;
1456
1457   myComponents.resize( other.myComponents.size());
1458   for (int i = 0 ; i < myComponents.size(); ++i )
1459     myComponents[ i ] = new TSideFace( *other.myComponents[ i ]);
1460 }
1461
1462 //================================================================================
1463 /*!
1464  * \brief Deletes myComponents
1465  */
1466 //================================================================================
1467
1468 StdMeshers_PrismAsBlock::TSideFace::~TSideFace()
1469 {
1470   for (int i = 0 ; i < myComponents.size(); ++i )
1471     if ( myComponents[ i ] )
1472       delete myComponents[ i ];
1473 }
1474
1475 //================================================================================
1476 /*!
1477  * \brief Return geometry of the vertical curve
1478   * \param isMax - true means curve located closer to (1,1,1) block point
1479   * \retval Adaptor3d_Curve* - curve adaptor
1480  */
1481 //================================================================================
1482
1483 Adaptor3d_Curve* StdMeshers_PrismAsBlock::TSideFace::VertiCurve(const bool isMax) const
1484 {
1485   if ( !myComponents.empty() ) {
1486     if ( isMax )
1487       return myComponents.back()->VertiCurve(isMax);
1488     else
1489       return myComponents.front()->VertiCurve(isMax);
1490   }
1491   double f = myParams[0].first, l = myParams[0].second;
1492   if ( !myIsForward ) std::swap( f, l );
1493   return new TVerticalEdgeAdaptor( myParamToColumnMap, isMax ? l : f );
1494 }
1495
1496 //================================================================================
1497 /*!
1498  * \brief Return geometry of the top or bottom curve
1499   * \param isTop - 
1500   * \retval Adaptor3d_Curve* - 
1501  */
1502 //================================================================================
1503
1504 Adaptor3d_Curve* StdMeshers_PrismAsBlock::TSideFace::HorizCurve(const bool isTop) const
1505 {
1506   return new THorizontalEdgeAdaptor( this, isTop );
1507 }
1508
1509 //================================================================================
1510 /*!
1511  * \brief Return pcurves
1512   * \param pcurv - array of 4 pcurves
1513   * \retval bool - is a success
1514  */
1515 //================================================================================
1516
1517 bool StdMeshers_PrismAsBlock::TSideFace::GetPCurves(Adaptor2d_Curve2d* pcurv[4]) const
1518 {
1519   int iEdge[ 4 ] = { BOTTOM_EDGE, TOP_EDGE, V0_EDGE, V1_EDGE };
1520
1521   for ( int i = 0 ; i < 4 ; ++i ) {
1522     Handle(Geom2d_Line) line;
1523     switch ( iEdge[ i ] ) {
1524     case TOP_EDGE:
1525       line = new Geom2d_Line( gp_Pnt2d( 0, 1 ), gp::DX2d() ); break;
1526     case BOTTOM_EDGE:
1527       line = new Geom2d_Line( gp::Origin2d(), gp::DX2d() ); break;
1528     case V0_EDGE:
1529       line = new Geom2d_Line( gp::Origin2d(), gp::DY2d() ); break;
1530     case V1_EDGE:
1531       line = new Geom2d_Line( gp_Pnt2d( 1, 0 ), gp::DY2d() ); break;
1532     }
1533     pcurv[ i ] = new Geom2dAdaptor_Curve( line, 0, 1 );
1534   }
1535   return true;
1536 }
1537
1538 //================================================================================
1539 /*!
1540  * \brief Returns geometry of pcurve on a horizontal face
1541   * \param isTop - is top or bottom face
1542   * \param horFace - a horizontal face
1543   * \retval Adaptor2d_Curve2d* - curve adaptor
1544  */
1545 //================================================================================
1546
1547 Adaptor2d_Curve2d*
1548 StdMeshers_PrismAsBlock::TSideFace::HorizPCurve(const bool         isTop,
1549                                                 const TopoDS_Face& horFace) const
1550 {
1551   return new TPCurveOnHorFaceAdaptor( this, isTop, horFace );
1552 }
1553
1554 //================================================================================
1555 /*!
1556  * \brief Return a component corresponding to parameter
1557   * \param U - parameter along a horizontal size
1558   * \param localU - parameter along a horizontal size of a component
1559   * \retval TSideFace* - found component
1560  */
1561 //================================================================================
1562
1563 StdMeshers_PrismAsBlock::TSideFace*
1564 StdMeshers_PrismAsBlock::TSideFace::GetComponent(const double U,double & localU) const
1565 {
1566   localU = U;
1567   if ( myComponents.empty() )
1568     return const_cast<TSideFace*>( this );
1569
1570   int i;
1571   for ( i = 0; i < myComponents.size(); ++i )
1572     if ( U < myParams[ i ].second )
1573       break;
1574   if ( i >= myComponents.size() )
1575     i = myComponents.size() - 1;
1576
1577   double f = myParams[ i ].first, l = myParams[ i ].second;
1578   localU = ( U - f ) / ( l - f );
1579   return myComponents[ i ];
1580 }
1581
1582 //================================================================================
1583 /*!
1584  * \brief Find node columns for a parameter
1585   * \param U - parameter along a horizontal edge
1586   * \param col1 - the 1st found column
1587   * \param col2 - the 2nd found column
1588   * \retval r - normalized position of U between the found columns
1589  */
1590 //================================================================================
1591
1592 double StdMeshers_PrismAsBlock::TSideFace::GetColumns(const double      U,
1593                                                       TParam2ColumnIt & col1,
1594                                                       TParam2ColumnIt & col2) const
1595 {
1596   double u = U, r = 0;
1597   if ( !myComponents.empty() ) {
1598     TSideFace * comp = GetComponent(U,u);
1599     return comp->GetColumns( u, col1, col2 );
1600   }
1601
1602   if ( !myIsForward )
1603     u = 1 - u;
1604   double f = myParams[0].first, l = myParams[0].second;
1605   u = f + u * ( l - f );
1606
1607   col1 = col2 = getColumn( myParamToColumnMap, u );
1608   if ( ++col2 == myParamToColumnMap->end() ) {
1609     --col2;
1610     r = 0.5;
1611   }
1612   else {
1613 //     if ( !myIsForward )
1614 //       std::swap( col1, col2 );
1615     double uf = col1->first;
1616     double ul = col2->first;
1617     r = ( u - uf ) / ( ul - uf );
1618   }
1619   return r;
1620 }
1621
1622 //================================================================================
1623 /*!
1624  * \brief Return coordinates by normalized params
1625   * \param U - horizontal param
1626   * \param V - vertical param
1627   * \retval gp_Pnt - result point
1628  */
1629 //================================================================================
1630
1631 gp_Pnt StdMeshers_PrismAsBlock::TSideFace::Value(const Standard_Real U,
1632                                                  const Standard_Real V) const
1633 {
1634   double u;
1635   if ( !myComponents.empty() ) {
1636     TSideFace * comp = GetComponent(U,u);
1637     return comp->Value( u, V );
1638   }
1639
1640   TParam2ColumnIt u_col1, u_col2;
1641   double vR, hR = GetColumns( U, u_col1, u_col2 );
1642
1643   const SMDS_MeshNode* n1 = 0;
1644   const SMDS_MeshNode* n2 = 0;
1645   const SMDS_MeshNode* n3 = 0;
1646   const SMDS_MeshNode* n4 = 0;
1647   gp_XYZ pnt;
1648
1649   vR = getRAndNodes( & u_col1->second, V, n1, n2 );
1650   vR = getRAndNodes( & u_col2->second, V, n3, n4 );
1651   
1652   gp_XY uv1 = myHelper->GetNodeUV( mySurface.Face(), n1, n4);
1653   gp_XY uv2 = myHelper->GetNodeUV( mySurface.Face(), n2, n3);
1654   gp_XY uv12 = uv1 * ( 1 - vR ) + uv2 * vR;
1655
1656   gp_XY uv3 = myHelper->GetNodeUV( mySurface.Face(), n3, n2);
1657   gp_XY uv4 = myHelper->GetNodeUV( mySurface.Face(), n4, n1);
1658   gp_XY uv34 = uv3 * ( 1 - vR ) + uv4 * vR;
1659
1660   gp_XY uv = uv12 * ( 1 - hR ) + uv34 * hR;
1661   
1662   return mySurface.Value( uv.X(), uv.Y() );
1663 }
1664
1665
1666 //================================================================================
1667 /*!
1668  * \brief Return boundary edge
1669   * \param edge - edge index
1670   * \retval TopoDS_Edge - found edge
1671  */
1672 //================================================================================
1673
1674 TopoDS_Edge StdMeshers_PrismAsBlock::TSideFace::GetEdge(const int iEdge) const
1675 {
1676   if ( !myComponents.empty() ) {
1677     switch ( iEdge ) {
1678     case V0_EDGE : return myComponents.front()->GetEdge( iEdge );
1679     case V1_EDGE : return myComponents.back() ->GetEdge( iEdge );
1680     default: return TopoDS_Edge();
1681     }
1682   }
1683   TopoDS_Shape edge;
1684   const SMDS_MeshNode* node = 0;
1685   SMESHDS_Mesh * meshDS = myHelper->GetMesh()->GetMeshDS();
1686   TNodeColumn* column;
1687
1688   switch ( iEdge ) {
1689   case TOP_EDGE:
1690   case BOTTOM_EDGE:
1691     column = & (( ++myParamToColumnMap->begin())->second );
1692     node = ( iEdge == TOP_EDGE ) ? column->back() : column->front();
1693     edge = myHelper->GetSubShapeByNode ( node, meshDS );
1694     if ( edge.ShapeType() == TopAbs_VERTEX ) {
1695       column = & ( myParamToColumnMap->begin()->second );
1696       node = ( iEdge == TOP_EDGE ) ? column->back() : column->front();
1697     }
1698     break;
1699   case V0_EDGE:
1700   case V1_EDGE: {
1701     bool back = ( iEdge == V1_EDGE );
1702     if ( !myIsForward ) back = !back;
1703     if ( back )
1704       column = & ( myParamToColumnMap->rbegin()->second );
1705     else
1706       column = & ( myParamToColumnMap->begin()->second );
1707     if ( column->size() > 0 )
1708       edge = myHelper->GetSubShapeByNode( (*column)[ 1 ], meshDS );
1709     if ( edge.IsNull() || edge.ShapeType() == TopAbs_VERTEX )
1710       node = column->front();
1711     break;
1712   }
1713   default:;
1714   }
1715   if ( !edge.IsNull() && edge.ShapeType() == TopAbs_EDGE )
1716     return TopoDS::Edge( edge );
1717
1718   // find edge by 2 vertices
1719   TopoDS_Shape V1 = edge;
1720   TopoDS_Shape V2 = myHelper->GetSubShapeByNode( node, meshDS );
1721   if ( V2.ShapeType() == TopAbs_VERTEX && !V2.IsSame( V1 ))
1722   {
1723     TopTools_ListIteratorOfListOfShape ancestIt =
1724       myHelper->GetMesh()->GetAncestors( V1 );
1725     for ( ; ancestIt.More(); ancestIt.Next() )
1726     {
1727       const TopoDS_Shape & ancestor = ancestIt.Value();
1728       if ( ancestor.ShapeType() == TopAbs_EDGE )
1729         for ( TopExp_Explorer e( ancestor, TopAbs_VERTEX ); e.More(); e.Next() )
1730           if ( V2.IsSame( e.Current() ))
1731             return TopoDS::Edge( ancestor );
1732     }
1733   }
1734   return TopoDS_Edge();
1735 }
1736
1737 //================================================================================
1738 /*!
1739  * \brief Fill block subshapes
1740   * \param shapeMap - map to fill in
1741   * \retval int - nb inserted subshapes
1742  */
1743 //================================================================================
1744
1745 int StdMeshers_PrismAsBlock::TSideFace::InsertSubShapes(TBlockShapes& shapeMap) const
1746 {
1747   int nbInserted = 0;
1748
1749   // Insert edges
1750   vector< int > edgeIdVec;
1751   SMESH_Block::GetFaceEdgesIDs( myID, edgeIdVec );
1752
1753   for ( int i = BOTTOM_EDGE; i <=V1_EDGE ; ++i ) {
1754     TopoDS_Edge e = GetEdge( i );
1755     if ( !e.IsNull() ) {
1756       nbInserted += SMESH_Block::Insert( e, edgeIdVec[ i ], shapeMap);
1757     }
1758   }
1759
1760   // Insert corner vertices
1761
1762   TParam2ColumnIt col1, col2 ;
1763   vector< int > vertIdVec;
1764
1765   // from V0 column
1766   SMESH_Block::GetEdgeVertexIDs( edgeIdVec[ V0_EDGE ], vertIdVec);
1767   GetColumns(0, col1, col2 );
1768   const SMDS_MeshNode* node0 = col1->second.front();
1769   const SMDS_MeshNode* node1 = col1->second.back();
1770   TopoDS_Shape v0 = myHelper->GetSubShapeByNode( node0, myHelper->GetMeshDS());
1771   TopoDS_Shape v1 = myHelper->GetSubShapeByNode( node1, myHelper->GetMeshDS());
1772   if ( v0.ShapeType() == TopAbs_VERTEX ) {
1773     nbInserted += SMESH_Block::Insert( v0, vertIdVec[ 0 ], shapeMap);
1774   }
1775   if ( v1.ShapeType() == TopAbs_VERTEX ) {
1776     nbInserted += SMESH_Block::Insert( v1, vertIdVec[ 1 ], shapeMap);
1777   }
1778   
1779   // from V1 column
1780   SMESH_Block::GetEdgeVertexIDs( edgeIdVec[ V1_EDGE ], vertIdVec);
1781   GetColumns(1, col1, col2 );
1782   node0 = col2->second.front();
1783   node1 = col2->second.back();
1784   v0 = myHelper->GetSubShapeByNode( node0, myHelper->GetMeshDS());
1785   v1 = myHelper->GetSubShapeByNode( node1, myHelper->GetMeshDS());
1786   if ( v0.ShapeType() == TopAbs_VERTEX ) {
1787     nbInserted += SMESH_Block::Insert( v0, vertIdVec[ 0 ], shapeMap);
1788   }
1789   if ( v1.ShapeType() == TopAbs_VERTEX ) {
1790     nbInserted += SMESH_Block::Insert( v1, vertIdVec[ 1 ], shapeMap);
1791   }
1792
1793 //   TopoDS_Vertex V0, V1, Vcom;
1794 //   TopExp::Vertices( myBaseEdge, V0, V1, true );
1795 //   if ( !myIsForward ) std::swap( V0, V1 );
1796
1797 //   // bottom vertex IDs
1798 //   SMESH_Block::GetEdgeVertexIDs( edgeIdVec[ _u0 ], vertIdVec);
1799 //   SMESH_Block::Insert( V0, vertIdVec[ 0 ], shapeMap);
1800 //   SMESH_Block::Insert( V1, vertIdVec[ 1 ], shapeMap);
1801
1802 //   TopoDS_Edge sideEdge = GetEdge( V0_EDGE );
1803 //   if ( sideEdge.IsNull() || !TopExp::CommonVertex( botEdge, sideEdge, Vcom ))
1804 //     return false;
1805
1806 //   // insert one side edge
1807 //   int edgeID;
1808 //   if ( Vcom.IsSame( V0 )) edgeID = edgeIdVec[ _v0 ];
1809 //   else                    edgeID = edgeIdVec[ _v1 ];
1810 //   SMESH_Block::Insert( sideEdge, edgeID, shapeMap);
1811
1812 //   // top vertex of the side edge
1813 //   SMESH_Block::GetEdgeVertexIDs( edgeID, vertIdVec);
1814 //   TopoDS_Vertex Vtop = TopExp::FirstVertex( sideEdge );
1815 //   if ( Vcom.IsSame( Vtop ))
1816 //     Vtop = TopExp::LastVertex( sideEdge );
1817 //   SMESH_Block::Insert( Vtop, vertIdVec[ 1 ], shapeMap);
1818
1819 //   // other side edge
1820 //   sideEdge = GetEdge( V1_EDGE );
1821 //   if ( sideEdge.IsNull() )
1822 //     return false;
1823 //   if ( edgeID = edgeIdVec[ _v1 ]) edgeID = edgeIdVec[ _v0 ];
1824 //   else                            edgeID = edgeIdVec[ _v1 ];
1825 //   SMESH_Block::Insert( sideEdge, edgeID, shapeMap);
1826   
1827 //   // top edge
1828 //   TopoDS_Edge topEdge = GetEdge( TOP_EDGE );
1829 //   SMESH_Block::Insert( topEdge, edgeIdVec[ _u1 ], shapeMap);
1830
1831 //   // top vertex of the other side edge
1832 //   if ( !TopExp::CommonVertex( topEdge, sideEdge, Vcom ))
1833 //     return false;
1834 //   SMESH_Block::GetEdgeVertexIDs( edgeID, vertIdVec );
1835 //   SMESH_Block::Insert( Vcom, vertIdVec[ 1 ], shapeMap);
1836
1837   return nbInserted;
1838 }
1839
1840 //================================================================================
1841 /*!
1842  * \brief Creates TVerticalEdgeAdaptor 
1843   * \param columnsMap - node column map
1844   * \param parameter - normalized parameter
1845  */
1846 //================================================================================
1847
1848 StdMeshers_PrismAsBlock::TVerticalEdgeAdaptor::
1849 TVerticalEdgeAdaptor( const TParam2ColumnMap* columnsMap, const double parameter)
1850 {
1851   myNodeColumn = & getColumn( columnsMap, parameter )->second;
1852 }
1853
1854 //================================================================================
1855 /*!
1856  * \brief Return coordinates for the given normalized parameter
1857   * \param U - normalized parameter
1858   * \retval gp_Pnt - coordinates
1859  */
1860 //================================================================================
1861
1862 gp_Pnt StdMeshers_PrismAsBlock::TVerticalEdgeAdaptor::Value(const Standard_Real U) const
1863 {
1864   const SMDS_MeshNode* n1;
1865   const SMDS_MeshNode* n2;
1866   double r = getRAndNodes( myNodeColumn, U, n1, n2 );
1867   return gpXYZ(n1) * ( 1 - r ) + gpXYZ(n2) * r;
1868 }
1869
1870 //================================================================================
1871 /*!
1872  * \brief Return coordinates for the given normalized parameter
1873   * \param U - normalized parameter
1874   * \retval gp_Pnt - coordinates
1875  */
1876 //================================================================================
1877
1878 gp_Pnt StdMeshers_PrismAsBlock::THorizontalEdgeAdaptor::Value(const Standard_Real U) const
1879 {
1880   return mySide->TSideFace::Value( U, myV );
1881 }
1882
1883 //================================================================================
1884 /*!
1885  * \brief Return UV on pcurve for the given normalized parameter
1886   * \param U - normalized parameter
1887   * \retval gp_Pnt - coordinates
1888  */
1889 //================================================================================
1890
1891 gp_Pnt2d StdMeshers_PrismAsBlock::TPCurveOnHorFaceAdaptor::Value(const Standard_Real U) const
1892 {
1893   TParam2ColumnIt u_col1, u_col2;
1894   double r = mySide->GetColumns( U, u_col1, u_col2 );
1895   gp_XY uv1 = mySide->GetNodeUV( myFace, u_col1->second[ myZ ]);
1896   gp_XY uv2 = mySide->GetNodeUV( myFace, u_col2->second[ myZ ]);
1897   return uv1 * ( 1 - r ) + uv2 * r;
1898 }