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