Salome HOME
0022202: EDF SMESH: Regression in a script meshing prisms and hexaedrons
[modules/smesh.git] / src / StdMeshers / StdMeshers_Prism_3D.cxx
1 // Copyright (C) 2007-2013  CEA/DEN, EDF R&D, OPEN CASCADE
2 //
3 // Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
5 //
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License.
10 //
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 // Lesser General Public License for more details.
15 //
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
19 //
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 //
22
23 // 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 "SMDS_EdgePosition.hxx"
31 #include "SMDS_VolumeOfNodes.hxx"
32 #include "SMDS_VolumeTool.hxx"
33 #include "SMESH_Comment.hxx"
34 #include "SMESH_Gen.hxx"
35 #include "SMESH_HypoFilter.hxx"
36 #include "SMESH_MesherHelper.hxx"
37 #include "StdMeshers_FaceSide.hxx"
38 #include "StdMeshers_ProjectionSource1D.hxx"
39 #include "StdMeshers_ProjectionSource2D.hxx"
40 #include "StdMeshers_ProjectionUtils.hxx"
41 #include "StdMeshers_Projection_1D.hxx"
42 #include "StdMeshers_Projection_1D2D.hxx"
43 #include "StdMeshers_Quadrangle_2D.hxx"
44
45 #include "utilities.h"
46
47 #include <BRepAdaptor_CompCurve.hxx>
48 #include <BRep_Tool.hxx>
49 #include <Bnd_B3d.hxx>
50 #include <Geom2dAdaptor_Curve.hxx>
51 #include <Geom2d_Line.hxx>
52 #include <Geom_Curve.hxx>
53 #include <TopExp.hxx>
54 #include <TopExp_Explorer.hxx>
55 #include <TopTools_ListIteratorOfListOfShape.hxx>
56 #include <TopTools_ListOfShape.hxx>
57 #include <TopTools_MapOfShape.hxx>
58 #include <TopTools_SequenceOfShape.hxx>
59 #include <TopoDS.hxx>
60 #include <gp_Ax2.hxx>
61 #include <gp_Ax3.hxx>
62
63 using namespace std;
64
65 #define RETURN_BAD_RESULT(msg) { MESSAGE(")-: Error: " << msg); return false; }
66 #define gpXYZ(n) gp_XYZ(n->X(),n->Y(),n->Z())
67 #define SHOWYXZ(msg, xyz) // {\
68 // gp_Pnt p (xyz); \
69 // cout << msg << " ("<< p.X() << "; " <<p.Y() << "; " <<p.Z() << ") " <<endl;\
70 // }
71 #ifdef _DEBUG_
72 #define DBGOUT(msg) //cout << msg << endl;
73 #else
74 #define DBGOUT(msg)
75 #endif
76
77 namespace TAssocTool = StdMeshers_ProjectionUtils;
78
79 typedef SMESH_Comment TCom;
80
81 enum { ID_BOT_FACE = SMESH_Block::ID_Fxy0,
82        ID_TOP_FACE = SMESH_Block::ID_Fxy1,
83        BOTTOM_EDGE = 0, TOP_EDGE, V0_EDGE, V1_EDGE, // edge IDs in face
84        NB_WALL_FACES = 4 }; //
85
86 namespace {
87
88   //=======================================================================
89   /*!
90    * \brief Quadrangle algorithm
91    */
92   struct TQuadrangleAlgo : public StdMeshers_Quadrangle_2D
93   {
94     TQuadrangleAlgo(int studyId, SMESH_Gen* gen)
95       : StdMeshers_Quadrangle_2D( gen->GetANewId(), studyId, gen)
96     {
97     }
98     static StdMeshers_Quadrangle_2D* instance( SMESH_Algo*         fatherAlgo,
99                                                SMESH_MesherHelper* helper=0)
100     {
101       static TQuadrangleAlgo* algo = new TQuadrangleAlgo( fatherAlgo->GetStudyId(),
102                                                           fatherAlgo->GetGen() );
103       if ( helper &&
104            algo->myProxyMesh &&
105            algo->myProxyMesh->GetMesh() != helper->GetMesh() )
106         algo->myProxyMesh.reset( new SMESH_ProxyMesh( *helper->GetMesh() ));
107
108       algo->myQuadStruct.reset();
109
110       if ( helper )
111         algo->_quadraticMesh = helper->GetIsQuadratic();
112
113       return algo;
114     }
115   };
116   //=======================================================================
117   /*!
118    * \brief Algorithm projecting 1D mesh
119    */
120   struct TProjction1dAlgo : public StdMeshers_Projection_1D
121   {
122     StdMeshers_ProjectionSource1D myHyp;
123
124     TProjction1dAlgo(int studyId, SMESH_Gen* gen)
125       : StdMeshers_Projection_1D( gen->GetANewId(), studyId, gen),
126         myHyp( gen->GetANewId(), studyId, gen)
127     {
128       StdMeshers_Projection_1D::_sourceHypo = & myHyp;
129     }
130     static TProjction1dAlgo* instance( SMESH_Algo* fatherAlgo )
131     {
132       static TProjction1dAlgo* algo = new TProjction1dAlgo( fatherAlgo->GetStudyId(),
133                                                             fatherAlgo->GetGen() );
134       return algo;
135     }
136   };
137   //=======================================================================
138   /*!
139    * \brief Algorithm projecting 2D mesh
140    */
141   struct TProjction2dAlgo : public StdMeshers_Projection_1D2D
142   {
143     StdMeshers_ProjectionSource2D myHyp;
144
145     TProjction2dAlgo(int studyId, SMESH_Gen* gen)
146       : StdMeshers_Projection_1D2D( gen->GetANewId(), studyId, gen),
147         myHyp( gen->GetANewId(), studyId, gen)
148     {
149       StdMeshers_Projection_2D::_sourceHypo = & myHyp;
150     }
151     static TProjction2dAlgo* instance( SMESH_Algo* fatherAlgo )
152     {
153       static TProjction2dAlgo* algo = new TProjction2dAlgo( fatherAlgo->GetStudyId(),
154                                                             fatherAlgo->GetGen() );
155       return algo;
156     }
157   };
158
159   //================================================================================
160   /*!
161    * \brief Make \a botE be the BOTTOM_SIDE of \a quad.
162    *        Return false if the BOTTOM_SIDE is composite
163    */
164   //================================================================================
165
166   bool setBottomEdge( const TopoDS_Edge&   botE,
167                       faceQuadStruct::Ptr& quad,
168                       const TopoDS_Shape&  face)
169   {
170     quad->side[ QUAD_TOP_SIDE  ]->Reverse();
171     quad->side[ QUAD_LEFT_SIDE ]->Reverse();
172     int edgeIndex = 0;
173     for ( size_t i = 0; i < quad->side.size(); ++i )
174     {
175       StdMeshers_FaceSide* quadSide = quad->side[i];
176       for ( int iE = 0; iE < quadSide->NbEdges(); ++iE )
177         if ( botE.IsSame( quadSide->Edge( iE )))
178         {
179           if ( quadSide->NbEdges() > 1 )
180             return false;
181           edgeIndex = i;
182           i = quad->side.size(); // to quit from the outer loop
183           break;
184         }
185     }
186     if ( edgeIndex != QUAD_BOTTOM_SIDE )
187       quad->shift( quad->side.size() - edgeIndex, /*keepUnitOri=*/false );
188
189     quad->face = TopoDS::Face( face );
190
191     return true;
192   }
193
194   //================================================================================
195   /*!
196    * \brief Return iterator pointing to node column for the given parameter
197    * \param columnsMap - node column map
198    * \param parameter - parameter
199    * \retval TParam2ColumnMap::iterator - result
200    *
201    * it returns closest left column
202    */
203   //================================================================================
204
205   TParam2ColumnIt getColumn( const TParam2ColumnMap* columnsMap,
206                              const double            parameter )
207   {
208     TParam2ColumnIt u_col = columnsMap->upper_bound( parameter );
209     if ( u_col != columnsMap->begin() )
210       --u_col;
211     return u_col; // return left column
212   }
213
214   //================================================================================
215   /*!
216    * \brief Return nodes around given parameter and a ratio
217    * \param column - node column
218    * \param param - parameter
219    * \param node1 - lower node
220    * \param node2 - upper node
221    * \retval double - ratio
222    */
223   //================================================================================
224
225   double getRAndNodes( const TNodeColumn*     column,
226                        const double           param,
227                        const SMDS_MeshNode* & node1,
228                        const SMDS_MeshNode* & node2)
229   {
230     if ( param >= 1.0 || column->size() == 1) {
231       node1 = node2 = column->back();
232       return 0;
233     }
234
235     int i = int( param * ( column->size() - 1 ));
236     double u0 = double( i )/ double( column->size() - 1 );
237     double r = ( param - u0 ) * ( column->size() - 1 );
238
239     node1 = (*column)[ i ];
240     node2 = (*column)[ i + 1];
241     return r;
242   }
243
244   //================================================================================
245   /*!
246    * \brief Compute boundary parameters of face parts
247     * \param nbParts - nb of parts to split columns into
248     * \param columnsMap - node columns of the face to split
249     * \param params - computed parameters
250    */
251   //================================================================================
252
253   void splitParams( const int               nbParts,
254                     const TParam2ColumnMap* columnsMap,
255                     vector< double > &      params)
256   {
257     params.clear();
258     params.reserve( nbParts + 1 );
259     TParam2ColumnIt last_par_col = --columnsMap->end();
260     double par = columnsMap->begin()->first; // 0.
261     double parLast = last_par_col->first;
262     params.push_back( par );
263     for ( int i = 0; i < nbParts - 1; ++ i )
264     {
265       double partSize = ( parLast - par ) / double ( nbParts - i );
266       TParam2ColumnIt par_col = getColumn( columnsMap, par + partSize );
267       if ( par_col->first == par ) {
268         ++par_col;
269         if ( par_col == last_par_col ) {
270           while ( i < nbParts - 1 )
271             params.push_back( par + partSize * i++ );
272           break;
273         }
274       }
275       par = par_col->first;
276       params.push_back( par );
277     }
278     params.push_back( parLast ); // 1.
279   }
280
281   //================================================================================
282   /*!
283    * \brief Return coordinate system for z-th layer of nodes
284    */
285   //================================================================================
286
287   gp_Ax2 getLayerCoordSys(const int                           z,
288                           const vector< const TNodeColumn* >& columns,
289                           int&                                xColumn)
290   {
291     // gravity center of a layer
292     gp_XYZ O(0,0,0);
293     int vertexCol = -1;
294     for ( int i = 0; i < columns.size(); ++i )
295     {
296       O += gpXYZ( (*columns[ i ])[ z ]);
297       if ( vertexCol < 0 &&
298            columns[ i ]->front()->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX )
299         vertexCol = i;
300     }
301     O /= columns.size();
302
303     // Z axis
304     gp_Vec Z(0,0,0);
305     int iPrev = columns.size()-1;
306     for ( int i = 0; i < columns.size(); ++i )
307     {
308       gp_Vec v1( O, gpXYZ( (*columns[ iPrev ])[ z ]));
309       gp_Vec v2( O, gpXYZ( (*columns[ i ]    )[ z ]));
310       Z += v1 ^ v2;
311       iPrev = i;
312     }
313
314     if ( vertexCol >= 0 )
315     {
316       O = gpXYZ( (*columns[ vertexCol ])[ z ]);
317     }
318     if ( xColumn < 0 || xColumn >= columns.size() )
319     {
320       // select a column for X dir
321       double maxDist = 0;
322       for ( int i = 0; i < columns.size(); ++i )
323       {
324         double dist = ( O - gpXYZ((*columns[ i ])[ z ])).SquareModulus();
325         if ( dist > maxDist )
326         {
327           xColumn = i;
328           maxDist = dist;
329         }
330       }
331     }
332
333     // X axis
334     gp_Vec X( O, gpXYZ( (*columns[ xColumn ])[ z ]));
335
336     return gp_Ax2( O, Z, X);
337   }
338
339   //================================================================================
340   /*!
341    * \brief Removes submeshes that are or can be meshed with regular grid from given list
342    *  \retval int - nb of removed submeshes
343    */
344   //================================================================================
345
346   int removeQuasiQuads(list< SMESH_subMesh* >&   notQuadSubMesh,
347                        SMESH_MesherHelper*       helper,
348                        StdMeshers_Quadrangle_2D* quadAlgo)
349   {
350     int nbRemoved = 0;
351     //SMESHDS_Mesh* mesh = notQuadSubMesh.front()->GetFather()->GetMeshDS();
352     list< SMESH_subMesh* >::iterator smIt = notQuadSubMesh.begin();
353     while ( smIt != notQuadSubMesh.end() )
354     {
355       SMESH_subMesh* faceSm = *smIt;
356       SMESHDS_SubMesh* faceSmDS = faceSm->GetSubMeshDS();
357       int nbQuads = faceSmDS ? faceSmDS->NbElements() : 0;
358       bool toRemove;
359       if ( nbQuads > 0 )
360         toRemove = helper->IsStructured( faceSm );
361       else
362         toRemove = quadAlgo->CheckNbEdges( *helper->GetMesh(),
363                                            faceSm->GetSubShape() );
364       nbRemoved += toRemove;
365       if ( toRemove )
366         smIt = notQuadSubMesh.erase( smIt );
367       else
368         ++smIt;
369     }
370
371     return nbRemoved;
372   }
373
374 } // namespace
375
376 //=======================================================================
377 //function : StdMeshers_Prism_3D
378 //purpose  : 
379 //=======================================================================
380
381 StdMeshers_Prism_3D::StdMeshers_Prism_3D(int hypId, int studyId, SMESH_Gen* gen)
382   :SMESH_3D_Algo(hypId, studyId, gen)
383 {
384   _name                    = "Prism_3D";
385   _shapeType               = (1 << TopAbs_SOLID); // 1 bit per shape type
386   _onlyUnaryInput          = false; // accept all SOLIDs at once
387   _requireDiscreteBoundary = false; // mesh FACEs and EDGEs by myself
388   _supportSubmeshes        = true;  // "source" FACE must be meshed by other algo
389   _neededLowerHyps[ 1 ]    = true;  // suppress warning on hiding a global 1D algo
390   _neededLowerHyps[ 2 ]    = true;  // suppress warning on hiding a global 2D algo
391
392   //myProjectTriangles       = false;
393   mySetErrorToSM           = true;  // to pass an error to a sub-mesh of a current solid or not
394 }
395
396 //================================================================================
397 /*!
398  * \brief Destructor
399  */
400 //================================================================================
401
402 StdMeshers_Prism_3D::~StdMeshers_Prism_3D()
403 {}
404
405 //=======================================================================
406 //function : CheckHypothesis
407 //purpose  : 
408 //=======================================================================
409
410 bool StdMeshers_Prism_3D::CheckHypothesis(SMESH_Mesh&                          aMesh,
411                                           const TopoDS_Shape&                  aShape,
412                                           SMESH_Hypothesis::Hypothesis_Status& aStatus)
413 {
414   // Check shape geometry
415 /*  PAL16229
416   aStatus = SMESH_Hypothesis::HYP_BAD_GEOMETRY;
417
418   // find not quadrangle faces
419   list< TopoDS_Shape > notQuadFaces;
420   int nbEdge, nbWire, nbFace = 0;
421   TopExp_Explorer exp( aShape, TopAbs_FACE );
422   for ( ; exp.More(); exp.Next() ) {
423     ++nbFace;
424     const TopoDS_Shape& face = exp.Current();
425     nbEdge = TAssocTool::Count( face, TopAbs_EDGE, 0 );
426     nbWire = TAssocTool::Count( face, TopAbs_WIRE, 0 );
427     if (  nbEdge!= 4 || nbWire!= 1 ) {
428       if ( !notQuadFaces.empty() ) {
429         if ( TAssocTool::Count( notQuadFaces.back(), TopAbs_EDGE, 0 ) != nbEdge ||
430              TAssocTool::Count( notQuadFaces.back(), TopAbs_WIRE, 0 ) != nbWire )
431           RETURN_BAD_RESULT("Different not quad faces");
432       }
433       notQuadFaces.push_back( face );
434     }
435   }
436   if ( !notQuadFaces.empty() )
437   {
438     if ( notQuadFaces.size() != 2 )
439       RETURN_BAD_RESULT("Bad nb not quad faces: " << notQuadFaces.size());
440
441     // check total nb faces
442     nbEdge = TAssocTool::Count( notQuadFaces.back(), TopAbs_EDGE, 0 );
443     if ( nbFace != nbEdge + 2 )
444       RETURN_BAD_RESULT("Bad nb of faces: " << nbFace << " but must be " << nbEdge + 2);
445   }
446 */
447   // no hypothesis
448   aStatus = SMESH_Hypothesis::HYP_OK;
449   return true;
450 }
451
452 //=======================================================================
453 //function : Compute
454 //purpose  : Compute mesh on a COMPOUND of SOLIDs
455 //=======================================================================
456
457 bool StdMeshers_Prism_3D::Compute(SMESH_Mesh& theMesh, const TopoDS_Shape& theShape)
458 {
459   SMESH_MesherHelper helper( theMesh );
460   myHelper = &helper;
461
462   int nbSolids = helper.Count( theShape, TopAbs_SOLID, /*skipSame=*/false );
463   if ( nbSolids < 1 )
464     return true;
465
466   TopTools_IndexedDataMapOfShapeListOfShape faceToSolids;
467   TopExp::MapShapesAndAncestors( theShape, TopAbs_FACE, TopAbs_SOLID, faceToSolids );
468
469   // look for meshed FACEs ("source" FACEs) that must be prism bottoms
470   list< TopoDS_Face > meshedFaces, notQuadMeshedFaces, notQuadFaces;
471   const bool meshHasQuads = ( theMesh.NbQuadrangles() > 0 );
472   //StdMeshers_Quadrangle_2D* quadAlgo = TQuadrangleAlgo::instance( this );
473   for ( int iF = 1; iF <= faceToSolids.Extent(); ++iF )
474   {
475     const TopoDS_Face& face = TopoDS::Face( faceToSolids.FindKey( iF ));
476     SMESH_subMesh*   faceSM = theMesh.GetSubMesh( face );
477     if ( !faceSM->IsEmpty() )
478     {
479       if ( !meshHasQuads ||
480            !helper.IsSameElemGeometry( faceSM->GetSubMeshDS(), SMDSGeom_QUADRANGLE ) ||
481            !helper.IsStructured( faceSM )
482            )
483         notQuadMeshedFaces.push_front( face );
484       else if ( myHelper->Count( face, TopAbs_EDGE, /*ignoreSame=*/false ) != 4 )
485         meshedFaces.push_front( face );
486       else
487         meshedFaces.push_back( face );
488     }
489     // not add not quadrilateral FACE as we can't compute it
490     // else if ( !quadAlgo->CheckNbEdges( theMesh, face ))
491     // // not add not quadrilateral FACE as it can be a prism side
492     // // else if ( myHelper->Count( face, TopAbs_EDGE, /*ignoreSame=*/false ) != 4 )
493     // {
494     //   notQuadFaces.push_back( face );
495     // }
496   }
497   // notQuadFaces are of medium priority, put them before ordinary meshed faces
498   meshedFaces.splice( meshedFaces.begin(), notQuadFaces );
499   // notQuadMeshedFaces are of highest priority, put them before notQuadFaces
500   meshedFaces.splice( meshedFaces.begin(), notQuadMeshedFaces );
501
502   Prism_3D::TPrismTopo prism;
503
504   if ( nbSolids == 1 )
505   {
506     if ( !meshedFaces.empty() )
507       prism.myBottom = meshedFaces.front();
508     return ( initPrism( prism, TopExp_Explorer( theShape, TopAbs_SOLID ).Current() ) &&
509              compute( prism ));
510   }
511
512   TopTools_MapOfShape meshedSolids;
513   list< Prism_3D::TPrismTopo > meshedPrism;
514   TopTools_ListIteratorOfListOfShape solidIt;
515
516   while ( meshedSolids.Extent() < nbSolids )
517   {
518     if ( _computeCanceled )
519       return toSM( error( SMESH_ComputeError::New(COMPERR_CANCELED)));
520
521     // compute prisms having avident computed source FACE
522     while ( !meshedFaces.empty() )
523     {
524       TopoDS_Face face = meshedFaces.front();
525       meshedFaces.pop_front();
526       TopTools_ListOfShape& solidList = faceToSolids.ChangeFromKey( face );
527       while ( !solidList.IsEmpty() )
528       {
529         TopoDS_Shape solid = solidList.First();
530         solidList.RemoveFirst();
531         if ( meshedSolids.Add( solid ))
532         {
533           prism.Clear();
534           prism.myBottom = face;
535           if ( !initPrism( prism, solid ) ||
536                !compute( prism ))
537             return false;
538
539           meshedFaces.push_front( prism.myTop );
540           meshedPrism.push_back( prism );
541         }
542       }
543     }
544     if ( meshedSolids.Extent() == nbSolids )
545       break;
546
547     // below in the loop we try to find source FACEs somehow
548
549     // project mesh from source FACEs of computed prisms to
550     // prisms sharing wall FACEs
551     list< Prism_3D::TPrismTopo >::iterator prismIt = meshedPrism.begin();
552     for ( ; prismIt != meshedPrism.end(); ++prismIt )
553     {
554       for ( size_t iW = 0; iW < prismIt->myWallQuads.size(); ++iW )
555       {
556         Prism_3D::TQuadList::iterator wQuad = prismIt->myWallQuads[iW].begin();
557         for ( ; wQuad != prismIt->myWallQuads[iW].end(); ++ wQuad )
558         {
559           const TopoDS_Face& wFace = (*wQuad)->face;
560           TopTools_ListOfShape& solidList = faceToSolids.ChangeFromKey( wFace );
561           solidIt.Initialize( solidList );
562           while ( solidIt.More() )
563           {
564             const TopoDS_Shape& solid = solidIt.Value();
565             if ( meshedSolids.Contains( solid )) {
566               solidList.Remove( solidIt );
567               continue; // already computed prism
568             }
569             // find a source FACE of the SOLID: it's a FACE sharing a bottom EDGE with wFace
570             const TopoDS_Edge& wEdge = (*wQuad)->side[ QUAD_TOP_SIDE ]->Edge(0);
571             PShapeIteratorPtr faceIt = myHelper->GetAncestors( wEdge, *myHelper->GetMesh(),
572                                                                TopAbs_FACE);
573             while ( const TopoDS_Shape* f = faceIt->next() )
574             {
575               const TopoDS_Face& candidateF = TopoDS::Face( *f );
576               prism.Clear();
577               prism.myBottom  = candidateF;
578               mySetErrorToSM = false;
579               if ( !myHelper->IsSubShape( candidateF, prismIt->myShape3D ) &&
580                    !myHelper->GetMesh()->GetSubMesh( candidateF )->IsMeshComputed() &&
581                    initPrism( prism, solid ) &&
582                    project2dMesh( prismIt->myBottom, candidateF))
583               {
584                 mySetErrorToSM = true;
585                 if ( !compute( prism ))
586                   return false;
587                 meshedFaces.push_front( prism.myTop );
588                 meshedFaces.push_front( prism.myBottom );
589                 meshedPrism.push_back( prism );
590                 meshedSolids.Add( solid );
591               }
592               InitComputeError();
593             }
594             mySetErrorToSM = true;
595             InitComputeError();
596             if ( meshedSolids.Contains( solid ))
597               solidList.Remove( solidIt );
598             else
599               solidIt.Next();
600           }
601         }
602       }
603       if ( !meshedFaces.empty() )
604         break; // to compute prisms with avident sources
605     }
606
607     // find FACEs with local 1D hyps, which has to be computed by now,
608     // or at least any computed FACEs
609     for ( int iF = 1; ( meshedFaces.empty() && iF < faceToSolids.Extent() ); ++iF )
610     {
611       const TopoDS_Face&               face = TopoDS::Face( faceToSolids.FindKey( iF ));
612       const TopTools_ListOfShape& solidList = faceToSolids.FindFromKey( face );
613       if ( solidList.IsEmpty() ) continue;
614       SMESH_subMesh*                 faceSM = theMesh.GetSubMesh( face );
615       if ( !faceSM->IsEmpty() )
616       {
617         meshedFaces.push_back( face ); // lower priority
618       }
619       else
620       {
621         bool allSubMeComputed = true;
622         SMESH_subMeshIteratorPtr smIt = faceSM->getDependsOnIterator(false,true);
623         while ( smIt->more() && allSubMeComputed )
624           allSubMeComputed = smIt->next()->IsMeshComputed();
625         if ( allSubMeComputed )
626         {
627           faceSM->ComputeStateEngine( SMESH_subMesh::COMPUTE );
628           if ( !faceSM->IsEmpty() )
629             meshedFaces.push_front( face ); // higher priority
630           else
631             faceSM->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
632         }
633       }
634     }
635
636
637     // TODO. there are other ways to find out the source FACE:
638     // propagation, topological similarity, ect.
639
640     // simply try to mesh all not meshed SOLIDs
641     if ( meshedFaces.empty() )
642     {
643       for ( TopExp_Explorer solid( theShape, TopAbs_SOLID ); solid.More(); solid.Next() )
644       {
645         mySetErrorToSM = false;
646         prism.Clear();
647         if ( !meshedSolids.Contains( solid.Current() ) &&
648              initPrism( prism, solid.Current() ))
649         {
650           mySetErrorToSM = true;
651           if ( !compute( prism ))
652             return false;
653           meshedFaces.push_front( prism.myTop );
654           meshedFaces.push_front( prism.myBottom );
655           meshedPrism.push_back( prism );
656           meshedSolids.Add( solid.Current() );
657         }
658         mySetErrorToSM = true;
659       }
660     }
661
662     if ( meshedFaces.empty() ) // set same error to 10 not-computed solids
663     {
664       SMESH_ComputeErrorPtr err = SMESH_ComputeError::New
665         ( COMPERR_BAD_INPUT_MESH, "No meshed source face found", this );
666
667       const int maxNbErrors = 10; // limit nb errors not to overload the Compute dialog
668       TopExp_Explorer solid( theShape, TopAbs_SOLID );
669       for ( int i = 0; ( i < maxNbErrors && solid.More() ); ++i, solid.Next() )
670         if ( !meshedSolids.Contains( solid.Current() ))
671         {
672           SMESH_subMesh* sm = theMesh.GetSubMesh( solid.Current() );
673           sm->GetComputeError() = err;
674         }
675       return error( err );
676     }
677   }
678   return true;
679 }
680
681 //================================================================================
682 /*!
683  * \brief Find wall faces by bottom edges
684  */
685 //================================================================================
686
687 bool StdMeshers_Prism_3D::getWallFaces( Prism_3D::TPrismTopo & thePrism,
688                                         const int              totalNbFaces)
689 {
690   thePrism.myWallQuads.clear();
691
692   SMESH_Mesh* mesh = myHelper->GetMesh();
693
694   StdMeshers_Quadrangle_2D* quadAlgo = TQuadrangleAlgo::instance( this, myHelper );
695
696   TopTools_MapOfShape faceMap;
697   TopTools_IndexedDataMapOfShapeListOfShape edgeToFaces;   
698   TopExp::MapShapesAndAncestors( thePrism.myShape3D,
699                                  TopAbs_EDGE, TopAbs_FACE, edgeToFaces );
700
701   // ------------------------------
702   // Get the 1st row of wall FACEs
703   // ------------------------------
704
705   list< TopoDS_Edge >::iterator edge = thePrism.myBottomEdges.begin();
706   std::list< int >::iterator     nbE = thePrism.myNbEdgesInWires.begin();
707   int iE = 0;
708   while ( edge != thePrism.myBottomEdges.end() )
709   {
710     ++iE;
711     if ( BRep_Tool::Degenerated( *edge ))
712     {
713       edge = thePrism.myBottomEdges.erase( edge );
714       --iE;
715       --(*nbE);
716     }
717     else
718     {
719       TopTools_ListIteratorOfListOfShape faceIt( edgeToFaces.FindFromKey( *edge ));
720       for ( ; faceIt.More(); faceIt.Next() )
721       {
722         const TopoDS_Face& face = TopoDS::Face( faceIt.Value() );
723         if ( !thePrism.myBottom.IsSame( face ))
724         {
725           Prism_3D::TQuadList quadList( 1, quadAlgo->CheckNbEdges( *mesh, face ));
726           if ( !quadList.back() )
727             return toSM( error(TCom("Side face #") << shapeID( face )
728                                << " not meshable with quadrangles"));
729           if ( ! setBottomEdge( *edge, quadList.back(), face ))
730             return toSM( error(TCom("Composite 'horizontal' edges are not supported")));
731           thePrism.myWallQuads.push_back( quadList );
732           faceMap.Add( face );
733           break;
734         }
735       }
736       ++edge;
737     }
738     if ( iE == *nbE )
739     {
740       iE = 0;
741       ++nbE;
742     }
743   }
744
745   // -------------------------
746   // Find the rest wall FACEs
747   // -------------------------
748
749   // Compose a vector of indixes of right neighbour FACE for each wall FACE
750   // that is not so evident in case of several WIREs in the bottom FACE
751   thePrism.myRightQuadIndex.clear();
752   for ( size_t i = 0; i < thePrism.myWallQuads.size(); ++i )
753     thePrism.myRightQuadIndex.push_back( i+1 );
754   list< int >::iterator nbEinW = thePrism.myNbEdgesInWires.begin();
755   for ( int iLeft = 0; nbEinW != thePrism.myNbEdgesInWires.end(); ++nbEinW )
756   {
757     thePrism.myRightQuadIndex[ iLeft + *nbEinW - 1 ] = iLeft; // 1st EDGE index of a current WIRE
758     iLeft += *nbEinW;
759   }
760
761   while ( totalNbFaces - faceMap.Extent() > 2 )
762   {
763     // find wall FACEs adjacent to each of wallQuads by the right side EDGE
764     int nbKnownFaces;
765     do {
766       nbKnownFaces = faceMap.Extent();
767       StdMeshers_FaceSide *rightSide, *topSide; // sides of the quad
768       for ( size_t i = 0; i < thePrism.myWallQuads.size(); ++i )
769       {
770         rightSide = thePrism.myWallQuads[i].back()->side[ QUAD_RIGHT_SIDE ];
771         for ( int iE = 0; iE < rightSide->NbEdges(); ++iE ) // rightSide can be composite
772         {
773           const TopoDS_Edge & rightE = rightSide->Edge( iE );
774           TopTools_ListIteratorOfListOfShape face( edgeToFaces.FindFromKey( rightE ));
775           for ( ; face.More(); face.Next() )
776             if ( faceMap.Add( face.Value() ))
777             {
778               // a new wall FACE encountered, store it in thePrism.myWallQuads
779               const int iRight = thePrism.myRightQuadIndex[i];
780               topSide = thePrism.myWallQuads[ iRight ].back()->side[ QUAD_TOP_SIDE ];
781               const TopoDS_Edge&   newBotE = topSide->Edge(0);
782               const TopoDS_Shape& newWallF = face.Value();
783               thePrism.myWallQuads[ iRight ].push_back( quadAlgo->CheckNbEdges( *mesh, newWallF ));
784               if ( !thePrism.myWallQuads[ iRight ].back() )
785                 return toSM( error(TCom("Side face #") << shapeID( newWallF ) <<
786                                    " not meshable with quadrangles"));
787               if ( ! setBottomEdge( newBotE, thePrism.myWallQuads[ iRight ].back(), newWallF ))
788                 return toSM( error(TCom("Composite 'horizontal' edges are not supported")));
789             }
790         }
791       }
792     } while ( nbKnownFaces != faceMap.Extent() );
793
794     // find wall FACEs adjacent to each of thePrism.myWallQuads by the top side EDGE
795     if ( totalNbFaces - faceMap.Extent() > 2 )
796     {
797       for ( size_t i = 0; i < thePrism.myWallQuads.size(); ++i )
798       {
799         StdMeshers_FaceSide* topSide = thePrism.myWallQuads[i].back()->side[ QUAD_TOP_SIDE ];
800         const TopoDS_Edge &     topE = topSide->Edge( 0 );
801         if ( topSide->NbEdges() > 1 )
802           return toSM( error(COMPERR_BAD_SHAPE, TCom("Side face #") <<
803                              shapeID( thePrism.myWallQuads[i].back()->face )
804                              << " has a composite top edge"));
805         TopTools_ListIteratorOfListOfShape faceIt( edgeToFaces.FindFromKey( topE ));
806         for ( ; faceIt.More(); faceIt.Next() )
807           if ( faceMap.Add( faceIt.Value() ))
808           {
809             // a new wall FACE encountered, store it in wallQuads
810             thePrism.myWallQuads[ i ].push_back( quadAlgo->CheckNbEdges( *mesh, faceIt.Value() ));
811             if ( !thePrism.myWallQuads[ i ].back() )
812               return toSM( error(TCom("Side face #") << shapeID( faceIt.Value() ) <<
813                                  " not meshable with quadrangles"));
814             if ( ! setBottomEdge( topE, thePrism.myWallQuads[ i ].back(), faceIt.Value() ))
815               return toSM( error(TCom("Composite 'horizontal' edges are not supported")));
816             if ( totalNbFaces - faceMap.Extent() == 2 )
817             {
818               i = thePrism.myWallQuads.size(); // to quit from the outer loop
819               break;
820             }
821           }
822       }
823     }
824   } // while ( totalNbFaces - faceMap.Extent() > 2 )
825
826   // ------------------
827   // Find the top FACE
828   // ------------------
829
830   if ( thePrism.myTop.IsNull() )
831   {
832     // now only top and bottom FACEs are not in the faceMap
833     faceMap.Add( thePrism.myBottom );
834     for ( TopExp_Explorer f( thePrism.myShape3D, TopAbs_FACE );f.More(); f.Next() )
835       if ( !faceMap.Contains( f.Current() )) {
836         thePrism.myTop = TopoDS::Face( f.Current() );
837         break;
838       }
839     if ( thePrism.myTop.IsNull() )
840       return toSM( error("Top face not found"));
841   }
842
843   // Check that the top FACE shares all the top EDGEs
844   for ( size_t i = 0; i < thePrism.myWallQuads.size(); ++i )
845   {
846     StdMeshers_FaceSide* topSide = thePrism.myWallQuads[i].back()->side[ QUAD_TOP_SIDE ];
847     const TopoDS_Edge &     topE = topSide->Edge( 0 );
848     if ( !myHelper->IsSubShape( topE, thePrism.myTop ))
849       return toSM( error( TCom("Wrong source face (#") << shapeID( thePrism.myBottom )));
850   }
851
852   return true;
853 }
854
855 //=======================================================================
856 //function : compute
857 //purpose  : Compute mesh on a SOLID
858 //=======================================================================
859
860 bool StdMeshers_Prism_3D::compute(const Prism_3D::TPrismTopo& thePrism)
861 {
862   myHelper->IsQuadraticSubMesh( thePrism.myShape3D );
863   if ( _computeCanceled )
864     return toSM( error( SMESH_ComputeError::New(COMPERR_CANCELED)));
865
866   // Make all side FACEs of thePrism meshed with quads
867   if ( !computeWalls( thePrism ))
868     return false;
869
870   // Analyse mesh and geometry to find block sub-shapes and submeshes
871   if ( !myBlock.Init( myHelper, thePrism ))
872     return toSM( error( myBlock.GetError()));
873
874   SMESHDS_Mesh* meshDS = myHelper->GetMeshDS();
875
876   int volumeID = meshDS->ShapeToIndex( thePrism.myShape3D );
877
878
879   // To compute coordinates of a node inside a block, it is necessary to know
880   // 1. normalized parameters of the node by which
881   // 2. coordinates of node projections on all block sub-shapes are computed
882
883   // So we fill projections on vertices at once as they are same for all nodes
884   myShapeXYZ.resize( myBlock.NbSubShapes() );
885   for ( int iV = SMESH_Block::ID_FirstV; iV < SMESH_Block::ID_FirstE; ++iV ) {
886     myBlock.VertexPoint( iV, myShapeXYZ[ iV ]);
887     SHOWYXZ("V point " <<iV << " ", myShapeXYZ[ iV ]);
888   }
889
890   // Projections on the top and bottom faces are taken from nodes existing
891   // on these faces; find correspondence between bottom and top nodes
892   myBotToColumnMap.clear();
893   if ( !assocOrProjBottom2Top() ) // it also fills myBotToColumnMap
894     return false;
895
896
897   // Create nodes inside the block
898
899   // try to use transformation (issue 0020680)
900   vector<gp_Trsf> trsf;
901   if ( myBlock.GetLayersTransformation( trsf, thePrism ))
902   {
903     // loop on nodes inside the bottom face
904     TNode2ColumnMap::iterator bot_column = myBotToColumnMap.begin();
905     for ( ; bot_column != myBotToColumnMap.end(); ++bot_column )
906     {
907       const Prism_3D::TNode& tBotNode = bot_column->first; // bottom TNode
908       if ( tBotNode.GetPositionType() != SMDS_TOP_FACE )
909         continue; // node is not inside face 
910
911       // column nodes; middle part of the column are zero pointers
912       TNodeColumn& column = bot_column->second;
913       TNodeColumn::iterator columnNodes = column.begin();
914       for ( int z = 0; columnNodes != column.end(); ++columnNodes, ++z)
915       {
916         const SMDS_MeshNode* & node = *columnNodes;
917         if ( node ) continue; // skip bottom or top node
918
919         gp_XYZ coords = tBotNode.GetCoords();
920         trsf[z-1].Transforms( coords );
921         node = meshDS->AddNode( coords.X(), coords.Y(), coords.Z() );
922         meshDS->SetNodeInVolume( node, volumeID );
923       }
924     } // loop on bottom nodes
925   }
926   else // use block approach
927   {
928     // loop on nodes inside the bottom face
929     Prism_3D::TNode prevBNode;
930     TNode2ColumnMap::iterator bot_column = myBotToColumnMap.begin();
931     for ( ; bot_column != myBotToColumnMap.end(); ++bot_column )
932     {
933       const Prism_3D::TNode& tBotNode = bot_column->first; // bottom TNode
934       if ( tBotNode.GetPositionType() != SMDS_TOP_FACE )
935         continue; // node is not inside face 
936
937       // column nodes; middle part of the column are zero pointers
938       TNodeColumn& column = bot_column->second;
939
940       // compute bottom node parameters
941       gp_XYZ paramHint(-1,-1,-1);
942       if ( prevBNode.IsNeighbor( tBotNode ))
943         paramHint = prevBNode.GetParams();
944       if ( !myBlock.ComputeParameters( tBotNode.GetCoords(), tBotNode.ChangeParams(),
945                                        ID_BOT_FACE, paramHint ))
946         return toSM( error(TCom("Can't compute normalized parameters for node ")
947                            << tBotNode.myNode->GetID() << " on the face #"
948                            << myBlock.SubMesh( ID_BOT_FACE )->GetId() ));
949       prevBNode = tBotNode;
950
951       myShapeXYZ[ ID_BOT_FACE ] = tBotNode.GetCoords();
952       gp_XYZ botParams          = tBotNode.GetParams();
953
954       // compute top node parameters
955       myShapeXYZ[ ID_TOP_FACE ] = gpXYZ( column.back() );
956       gp_XYZ topParams = botParams;
957       topParams.SetZ( 1 );
958       if ( column.size() > 2 ) {
959         gp_Pnt topCoords = myShapeXYZ[ ID_TOP_FACE ];
960         if ( !myBlock.ComputeParameters( topCoords, topParams, ID_TOP_FACE, topParams ))
961           return toSM( error(TCom("Can't compute normalized parameters ")
962                              << "for node " << column.back()->GetID()
963                              << " on the face #"<< column.back()->getshapeId() ));
964       }
965
966       // vertical loop
967       TNodeColumn::iterator columnNodes = column.begin();
968       for ( int z = 0; columnNodes != column.end(); ++columnNodes, ++z)
969       {
970         const SMDS_MeshNode* & node = *columnNodes;
971         if ( node ) continue; // skip bottom or top node
972
973         // params of a node to create
974         double rz = (double) z / (double) ( column.size() - 1 );
975         gp_XYZ params = botParams * ( 1 - rz ) + topParams * rz;
976
977         // set coords on all faces and nodes
978         const int nbSideFaces = 4;
979         int sideFaceIDs[nbSideFaces] = { SMESH_Block::ID_Fx0z,
980                                          SMESH_Block::ID_Fx1z,
981                                          SMESH_Block::ID_F0yz,
982                                          SMESH_Block::ID_F1yz };
983         for ( int iF = 0; iF < nbSideFaces; ++iF )
984           if ( !setFaceAndEdgesXYZ( sideFaceIDs[ iF ], params, z ))
985             return false;
986
987         // compute coords for a new node
988         gp_XYZ coords;
989         if ( !SMESH_Block::ShellPoint( params, myShapeXYZ, coords ))
990           return toSM( error("Can't compute coordinates by normalized parameters"));
991
992         SHOWYXZ("TOPFacePoint ",myShapeXYZ[ ID_TOP_FACE]);
993         SHOWYXZ("BOT Node "<< tBotNode.myNode->GetID(),gpXYZ(tBotNode.myNode));
994         SHOWYXZ("ShellPoint ",coords);
995
996         // create a node
997         node = meshDS->AddNode( coords.X(), coords.Y(), coords.Z() );
998         meshDS->SetNodeInVolume( node, volumeID );
999       }
1000     } // loop on bottom nodes
1001   }
1002
1003   // Create volumes
1004
1005   SMESHDS_SubMesh* smDS = myBlock.SubMeshDS( ID_BOT_FACE );
1006   if ( !smDS ) return toSM( error(COMPERR_BAD_INPUT_MESH, "Null submesh"));
1007
1008   // loop on bottom mesh faces
1009   SMDS_ElemIteratorPtr faceIt = smDS->GetElements();
1010   while ( faceIt->more() )
1011   {
1012     const SMDS_MeshElement* face = faceIt->next();
1013     if ( !face || face->GetType() != SMDSAbs_Face )
1014       continue;
1015
1016     // find node columns for each node
1017     int nbNodes = face->NbCornerNodes();
1018     vector< const TNodeColumn* > columns( nbNodes );
1019     for ( int i = 0; i < nbNodes; ++i )
1020     {
1021       const SMDS_MeshNode* n = face->GetNode( i );
1022       if ( n->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE ) {
1023         TNode2ColumnMap::iterator bot_column = myBotToColumnMap.find( n );
1024         if ( bot_column == myBotToColumnMap.end() )
1025           return toSM( error(TCom("No nodes found above node ") << n->GetID() ));
1026         columns[ i ] = & bot_column->second;
1027       }
1028       else {
1029         columns[ i ] = myBlock.GetNodeColumn( n );
1030         if ( !columns[ i ] )
1031           return toSM( error(TCom("No side nodes found above node ") << n->GetID() ));
1032       }
1033     }
1034     // create prisms
1035     AddPrisms( columns, myHelper );
1036
1037   } // loop on bottom mesh faces
1038
1039   // clear data
1040   myBotToColumnMap.clear();
1041   myBlock.Clear();
1042         
1043   return true;
1044 }
1045
1046 //=======================================================================
1047 //function : computeWalls
1048 //purpose  : Compute 2D mesh on walls FACEs of a prism
1049 //=======================================================================
1050
1051 bool StdMeshers_Prism_3D::computeWalls(const Prism_3D::TPrismTopo& thePrism)
1052 {
1053   SMESH_Mesh*     mesh = myHelper->GetMesh();
1054   SMESHDS_Mesh* meshDS = myHelper->GetMeshDS();
1055   DBGOUT( endl << "COMPUTE Prism " << meshDS->ShapeToIndex( thePrism.myShape3D ));
1056
1057   TProjction1dAlgo* projector1D = TProjction1dAlgo::instance( this );
1058   StdMeshers_Quadrangle_2D* quadAlgo = TQuadrangleAlgo::instance( this, myHelper );
1059
1060   SMESH_HypoFilter hyp1dFilter( SMESH_HypoFilter::IsAlgo(),/*not=*/true);
1061   hyp1dFilter.And( SMESH_HypoFilter::HasDim( 1 ));
1062   hyp1dFilter.And( SMESH_HypoFilter::IsMoreLocalThan( thePrism.myShape3D, *mesh ));
1063
1064   // Discretize equally 'vertical' EDGEs
1065   // -----------------------------------
1066   // find source FACE sides for projection: either already computed ones or
1067   // the 'most composite' ones
1068   multimap< int, int > wgt2quad;
1069   for ( size_t iW = 0; iW != thePrism.myWallQuads.size(); ++iW )
1070   {
1071     Prism_3D::TQuadList::const_iterator quad = thePrism.myWallQuads[iW].begin();
1072     int wgt = 0; // "weight"
1073     for ( ; quad != thePrism.myWallQuads[iW].end(); ++quad )
1074     {
1075       StdMeshers_FaceSide* lftSide = (*quad)->side[ QUAD_LEFT_SIDE ];
1076       for ( int i = 0; i < lftSide->NbEdges(); ++i )
1077       {
1078         ++wgt;
1079         const TopoDS_Edge& E = lftSide->Edge(i);
1080         if ( mesh->GetSubMesh( E )->IsMeshComputed() )
1081           wgt += 10;
1082         else if ( mesh->GetHypothesis( E, hyp1dFilter, true )) // local hypothesis!
1083           wgt += 100;
1084       }
1085     }
1086     wgt2quad.insert( make_pair( wgt, iW ));
1087
1088     // in quadratic mesh, pass ignoreMediumNodes to quad sides
1089     if ( myHelper->GetIsQuadratic() )
1090     {
1091       quad = thePrism.myWallQuads[iW].begin();
1092       for ( ; quad != thePrism.myWallQuads[iW].end(); ++quad )
1093         for ( int i = 0; i < NB_QUAD_SIDES; ++i )
1094           (*quad)->side[ i ]->SetIgnoreMediumNodes( true );
1095     }
1096   }
1097
1098   // Project 'vertical' EDGEs, from left to right
1099   multimap< int, int >::reverse_iterator w2q = wgt2quad.rbegin();
1100   for ( ; w2q != wgt2quad.rend(); ++w2q )
1101   {
1102     const int iW = w2q->second;
1103     const Prism_3D::TQuadList&         quads = thePrism.myWallQuads[ iW ];
1104     Prism_3D::TQuadList::const_iterator quad = quads.begin();
1105     for ( ; quad != quads.end(); ++quad )
1106     {
1107       StdMeshers_FaceSide* rgtSide = (*quad)->side[ QUAD_RIGHT_SIDE ]; // tgt
1108       StdMeshers_FaceSide* lftSide = (*quad)->side[ QUAD_LEFT_SIDE ];  // src
1109       bool swapLeftRight = ( lftSide->NbSegments( /*update=*/true ) == 0 &&
1110                              rgtSide->NbSegments( /*update=*/true )  > 0 );
1111       if ( swapLeftRight )
1112         std::swap( lftSide, rgtSide );
1113
1114       // assure that all the source (left) EDGEs are meshed
1115       int nbSrcSegments = 0;
1116       for ( int i = 0; i < lftSide->NbEdges(); ++i )
1117       {
1118         const TopoDS_Edge& srcE = lftSide->Edge(i);
1119         SMESH_subMesh*    srcSM = mesh->GetSubMesh( srcE );
1120         if ( !srcSM->IsMeshComputed() ) {
1121           DBGOUT( "COMPUTE V edge " << srcSM->GetId() );
1122           srcSM->ComputeSubMeshStateEngine( SMESH_subMesh::COMPUTE );
1123           srcSM->ComputeStateEngine       ( SMESH_subMesh::COMPUTE );
1124           if ( !srcSM->IsMeshComputed() )
1125             return false;
1126         }
1127         nbSrcSegments += srcSM->GetSubMeshDS()->NbElements();
1128       }
1129       // check target EDGEs
1130       int nbTgtMeshed = 0, nbTgtSegments = 0;
1131       vector< bool > isTgtEdgeComputed( rgtSide->NbEdges() );
1132       for ( int i = 0; i < rgtSide->NbEdges(); ++i )
1133       {
1134         const TopoDS_Edge& tgtE = rgtSide->Edge(i);
1135         SMESH_subMesh*    tgtSM = mesh->GetSubMesh( tgtE );
1136         if (( isTgtEdgeComputed[ i ] = tgtSM->IsMeshComputed() )) {
1137           ++nbTgtMeshed;
1138           nbTgtSegments += tgtSM->GetSubMeshDS()->NbElements();
1139         }
1140       }
1141       if ( rgtSide->NbEdges() == nbTgtMeshed ) // all tgt EDGEs meshed
1142       {
1143         if ( nbTgtSegments != nbSrcSegments )
1144         {
1145           for ( int i = 0; i < lftSide->NbEdges(); ++i )
1146             addBadInputElements( meshDS->MeshElements( lftSide->Edge( i )));
1147           for ( int i = 0; i < rgtSide->NbEdges(); ++i )
1148             addBadInputElements( meshDS->MeshElements( rgtSide->Edge( i )));
1149           return toSM( error( TCom("Different nb of segment on logically vertical edges #")
1150                               << shapeID( lftSide->Edge(0) ) << " and #"
1151                               << shapeID( rgtSide->Edge(0) ) << ": "
1152                               << nbSrcSegments << " != " << nbTgtSegments ));
1153         }
1154         continue;
1155       }
1156       // Compute 'vertical projection'
1157       if ( nbTgtMeshed == 0 )
1158       {
1159         // compute nodes on target VERTEXes
1160         const UVPtStructVec&  srcNodeStr = lftSide->GetUVPtStruct();
1161         if ( srcNodeStr.size() == 0 )
1162           return toSM( error( TCom("Invalid node positions on edge #") <<
1163                               shapeID( lftSide->Edge(0) )));
1164         vector< SMDS_MeshNode* > newNodes( srcNodeStr.size() );
1165         for ( int is2ndV = 0; is2ndV < 2; ++is2ndV )
1166         {
1167           const TopoDS_Edge& E = rgtSide->Edge( is2ndV ? rgtSide->NbEdges()-1 : 0 );
1168           TopoDS_Vertex      v = myHelper->IthVertex( is2ndV, E );
1169           mesh->GetSubMesh( v )->ComputeStateEngine( SMESH_subMesh::COMPUTE );
1170           const SMDS_MeshNode* n = SMESH_Algo::VertexNode( v, meshDS );
1171           newNodes[ is2ndV ? 0 : newNodes.size()-1 ] = (SMDS_MeshNode*) n;
1172         }
1173
1174         // compute nodes on target EDGEs
1175         DBGOUT( "COMPUTE V edge (proj) " << shapeID( lftSide->Edge(0)));
1176         rgtSide->Reverse(); // direct it same as the lftSide
1177         myHelper->SetElementsOnShape( false ); // myHelper holds the prism shape
1178         TopoDS_Edge tgtEdge;
1179         for ( size_t iN = 1; iN < srcNodeStr.size()-1; ++iN ) // add nodes
1180         {
1181           gp_Pnt       p = rgtSide->Value3d  ( srcNodeStr[ iN ].normParam );
1182           double       u = rgtSide->Parameter( srcNodeStr[ iN ].normParam, tgtEdge );
1183           newNodes[ iN ] = meshDS->AddNode( p.X(), p.Y(), p.Z() );
1184           meshDS->SetNodeOnEdge( newNodes[ iN ], tgtEdge, u );
1185         }
1186         for ( size_t iN = 1; iN < srcNodeStr.size(); ++iN ) // add segments
1187         {
1188           // find an EDGE to set a new segment
1189           std::pair<int, TopAbs_ShapeEnum> id2type = 
1190             myHelper->GetMediumPos( newNodes[ iN-1 ], newNodes[ iN ] );
1191           if ( id2type.second != TopAbs_EDGE )
1192           {
1193             // new nodes are on different EDGEs; put one of them on VERTEX
1194             const int      edgeIndex = rgtSide->EdgeIndex( srcNodeStr[ iN-1 ].normParam );
1195             const double vertexParam = rgtSide->LastParameter( edgeIndex );
1196             const gp_Pnt           p = BRep_Tool::Pnt( rgtSide->LastVertex( edgeIndex ));
1197             const int         isPrev = ( Abs( srcNodeStr[ iN-1 ].normParam - vertexParam ) <
1198                                          Abs( srcNodeStr[ iN   ].normParam - vertexParam ));
1199             meshDS->UnSetNodeOnShape( newNodes[ iN-isPrev ] );
1200             meshDS->SetNodeOnVertex ( newNodes[ iN-isPrev ], rgtSide->LastVertex( edgeIndex ));
1201             meshDS->MoveNode        ( newNodes[ iN-isPrev ], p.X(), p.Y(), p.Z() );
1202             id2type.first = newNodes[ iN-(1-isPrev) ]->getshapeId();
1203           }
1204           SMDS_MeshElement* newEdge = myHelper->AddEdge( newNodes[ iN-1 ], newNodes[ iN ] );
1205           meshDS->SetMeshElementOnShape( newEdge, id2type.first );
1206         }
1207         myHelper->SetElementsOnShape( true );
1208         for ( int i = 0; i < rgtSide->NbEdges(); ++i ) // update state of sub-meshes
1209         {
1210           const TopoDS_Edge& E = rgtSide->Edge( i );
1211           SMESH_subMesh* tgtSM = mesh->GetSubMesh( E );
1212           tgtSM->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1213         }
1214
1215         // to continue projection from the just computed side as a source
1216         if ( !swapLeftRight && rgtSide->NbEdges() > 1 && w2q->second == iW )
1217         {
1218           std::pair<int,int> wgt2quadKeyVal( w2q->first + 1, thePrism.myRightQuadIndex[ iW ]);
1219           wgt2quad.insert( wgt2quadKeyVal ); // it will be skipped by ++w2q
1220           wgt2quad.insert( wgt2quadKeyVal );
1221           w2q = wgt2quad.rbegin();
1222         }
1223       }
1224       else
1225       {
1226         // HOPE assigned hypotheses are OK, so that equal nb of segments will be generated
1227         //return toSM( error("Partial projection not implemented"));
1228       }
1229     } // loop on quads of a composite wall side
1230   } // loop on the ordered wall sides
1231
1232
1233
1234   for ( size_t iW = 0; iW != thePrism.myWallQuads.size(); ++iW )
1235   {
1236     Prism_3D::TQuadList::const_iterator quad = thePrism.myWallQuads[iW].begin();
1237     for ( ; quad != thePrism.myWallQuads[iW].end(); ++quad )
1238     {
1239       // Top EDGEs must be projections from the bottom ones
1240       // to compute stuctured quad mesh on wall FACEs
1241       // ---------------------------------------------------
1242       {
1243         const TopoDS_Edge& botE = (*quad)->side[ QUAD_BOTTOM_SIDE ]->Edge(0);
1244         const TopoDS_Edge& topE = (*quad)->side[ QUAD_TOP_SIDE    ]->Edge(0);
1245         SMESH_subMesh*    botSM = mesh->GetSubMesh( botE );
1246         SMESH_subMesh*    topSM = mesh->GetSubMesh( topE );
1247         SMESH_subMesh*    srcSM = botSM;
1248         SMESH_subMesh*    tgtSM = topSM;
1249         if ( !srcSM->IsMeshComputed() && topSM->IsMeshComputed() )
1250           std::swap( srcSM, tgtSM );
1251
1252         if ( !srcSM->IsMeshComputed() )
1253         {
1254           DBGOUT( "COMPUTE H edge " << srcSM->GetId());
1255           srcSM->ComputeSubMeshStateEngine( SMESH_subMesh::COMPUTE ); // nodes on VERTEXes
1256           srcSM->ComputeStateEngine( SMESH_subMesh::COMPUTE );        // segments on the EDGE
1257         }
1258         srcSM->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1259
1260         if ( !tgtSM->IsMeshComputed() )
1261         {
1262           // compute nodes on VERTEXes
1263           tgtSM->ComputeSubMeshStateEngine( SMESH_subMesh::COMPUTE );
1264           // project segments
1265           DBGOUT( "COMPUTE H edge (proj) " << tgtSM->GetId());
1266           projector1D->myHyp.SetSourceEdge( TopoDS::Edge( srcSM->GetSubShape() ));
1267           projector1D->InitComputeError();
1268           bool ok = projector1D->Compute( *mesh, tgtSM->GetSubShape() );
1269           if ( !ok )
1270           {
1271             SMESH_ComputeErrorPtr err = projector1D->GetComputeError();
1272             if ( err->IsOK() ) err->myName = COMPERR_ALGO_FAILED;
1273             tgtSM->GetComputeError() = err;
1274             return false;
1275           }
1276         }
1277         tgtSM->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1278       }
1279
1280       // Compute quad mesh on wall FACEs
1281       // -------------------------------
1282       const TopoDS_Face& face = (*quad)->face;
1283       SMESH_subMesh* fSM = mesh->GetSubMesh( face );
1284       if ( ! fSM->IsMeshComputed() )
1285       {
1286         // make all EDGES meshed
1287         fSM->ComputeSubMeshStateEngine( SMESH_subMesh::COMPUTE );
1288         if ( !fSM->SubMeshesComputed() )
1289           return toSM( error( COMPERR_BAD_INPUT_MESH,
1290                               "Not all edges have valid algorithm and hypothesis"));
1291         // mesh the <face>
1292         quadAlgo->InitComputeError();
1293         DBGOUT( "COMPUTE Quad face " << fSM->GetId());
1294         bool ok = quadAlgo->Compute( *mesh, face );
1295         fSM->GetComputeError() = quadAlgo->GetComputeError();
1296         if ( !ok )
1297           return false;
1298         fSM->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1299       }
1300       if ( myHelper->GetIsQuadratic() )
1301       {
1302         // fill myHelper with medium nodes built by quadAlgo
1303         SMDS_ElemIteratorPtr fIt = fSM->GetSubMeshDS()->GetElements();
1304         while ( fIt->more() )
1305           myHelper->AddTLinks( dynamic_cast<const SMDS_MeshFace*>( fIt->next() ));
1306       }
1307     }
1308   }
1309
1310   return true;
1311 }
1312
1313 //=======================================================================
1314 //function : Evaluate
1315 //purpose  : 
1316 //=======================================================================
1317
1318 bool StdMeshers_Prism_3D::Evaluate(SMESH_Mesh&         theMesh,
1319                                    const TopoDS_Shape& theShape,
1320                                    MapShapeNbElems&    aResMap)
1321 {
1322   if ( theShape.ShapeType() == TopAbs_COMPOUND )
1323   {
1324     bool ok = true;
1325     for ( TopoDS_Iterator it( theShape ); it.More(); it.Next() )
1326       ok &= Evaluate( theMesh, it.Value(), aResMap );
1327     return ok;
1328   }
1329   SMESH_MesherHelper helper( theMesh );
1330   myHelper = &helper;
1331   myHelper->SetSubShape( theShape );
1332
1333   // find face contains only triangles
1334   vector < SMESH_subMesh * >meshFaces;
1335   TopTools_SequenceOfShape aFaces;
1336   int NumBase = 0, i = 0, NbQFs = 0;
1337   for (TopExp_Explorer exp(theShape, TopAbs_FACE); exp.More(); exp.Next()) {
1338     i++;
1339     aFaces.Append(exp.Current());
1340     SMESH_subMesh *aSubMesh = theMesh.GetSubMesh(exp.Current());
1341     meshFaces.push_back(aSubMesh);
1342     MapShapeNbElemsItr anIt = aResMap.find(meshFaces[i-1]);
1343     if( anIt==aResMap.end() )
1344       return toSM( error( "Submesh can not be evaluated"));
1345
1346     std::vector<int> aVec = (*anIt).second;
1347     int nbtri = Max(aVec[SMDSEntity_Triangle],aVec[SMDSEntity_Quad_Triangle]);
1348     int nbqua = Max(aVec[SMDSEntity_Quadrangle],aVec[SMDSEntity_Quad_Quadrangle]);
1349     if( nbtri==0 && nbqua>0 ) {
1350       NbQFs++;
1351     }
1352     if( nbtri>0 ) {
1353       NumBase = i;
1354     }
1355   }
1356
1357   if(NbQFs<4) {
1358     std::vector<int> aResVec(SMDSEntity_Last);
1359     for(int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aResVec[i] = 0;
1360     SMESH_subMesh * sm = theMesh.GetSubMesh(theShape);
1361     aResMap.insert(std::make_pair(sm,aResVec));
1362     return toSM( error( "Submesh can not be evaluated" ));
1363   }
1364
1365   if(NumBase==0) NumBase = 1; // only quads => set 1 faces as base
1366
1367   // find number of 1d elems for base face
1368   int nb1d = 0;
1369   TopTools_MapOfShape Edges1;
1370   for (TopExp_Explorer exp(aFaces.Value(NumBase), TopAbs_EDGE); exp.More(); exp.Next()) {
1371     Edges1.Add(exp.Current());
1372     SMESH_subMesh *sm = theMesh.GetSubMesh(exp.Current());
1373     if( sm ) {
1374       MapShapeNbElemsItr anIt = aResMap.find(sm);
1375       if( anIt == aResMap.end() ) continue;
1376       std::vector<int> aVec = (*anIt).second;
1377       nb1d += Max(aVec[SMDSEntity_Edge],aVec[SMDSEntity_Quad_Edge]);
1378     }
1379   }
1380   // find face opposite to base face
1381   int OppNum = 0;
1382   for(i=1; i<=6; i++) {
1383     if(i==NumBase) continue;
1384     bool IsOpposite = true;
1385     for(TopExp_Explorer exp(aFaces.Value(i), TopAbs_EDGE); exp.More(); exp.Next()) {
1386       if( Edges1.Contains(exp.Current()) ) {
1387         IsOpposite = false;
1388         break;
1389       }
1390     }
1391     if(IsOpposite) {
1392       OppNum = i;
1393       break;
1394     }
1395   }
1396   // find number of 2d elems on side faces
1397   int nb2d = 0;
1398   for(i=1; i<=6; i++) {
1399     if( i==OppNum || i==NumBase ) continue;
1400     MapShapeNbElemsItr anIt = aResMap.find( meshFaces[i-1] );
1401     if( anIt == aResMap.end() ) continue;
1402     std::vector<int> aVec = (*anIt).second;
1403     nb2d += Max(aVec[SMDSEntity_Quadrangle],aVec[SMDSEntity_Quad_Quadrangle]);
1404   }
1405   
1406   MapShapeNbElemsItr anIt = aResMap.find( meshFaces[NumBase-1] );
1407   std::vector<int> aVec = (*anIt).second;
1408   bool IsQuadratic = (aVec[SMDSEntity_Quad_Triangle]>aVec[SMDSEntity_Triangle]) ||
1409                      (aVec[SMDSEntity_Quad_Quadrangle]>aVec[SMDSEntity_Quadrangle]);
1410   int nb2d_face0_3 = Max(aVec[SMDSEntity_Triangle],aVec[SMDSEntity_Quad_Triangle]);
1411   int nb2d_face0_4 = Max(aVec[SMDSEntity_Quadrangle],aVec[SMDSEntity_Quad_Quadrangle]);
1412   int nb0d_face0 = aVec[SMDSEntity_Node];
1413   int nb1d_face0_int = ( nb2d_face0_3*3 + nb2d_face0_4*4 - nb1d ) / 2;
1414
1415   std::vector<int> aResVec(SMDSEntity_Last);
1416   for(int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aResVec[i] = 0;
1417   if(IsQuadratic) {
1418     aResVec[SMDSEntity_Quad_Penta] = nb2d_face0_3 * ( nb2d/nb1d );
1419     aResVec[SMDSEntity_Quad_Hexa] = nb2d_face0_4 * ( nb2d/nb1d );
1420     aResVec[SMDSEntity_Node] = nb0d_face0 * ( 2*nb2d/nb1d - 1 ) - nb1d_face0_int * nb2d/nb1d;
1421   }
1422   else {
1423     aResVec[SMDSEntity_Node] = nb0d_face0 * ( nb2d/nb1d - 1 );
1424     aResVec[SMDSEntity_Penta] = nb2d_face0_3 * ( nb2d/nb1d );
1425     aResVec[SMDSEntity_Hexa] = nb2d_face0_4 * ( nb2d/nb1d );
1426   }
1427   SMESH_subMesh * sm = theMesh.GetSubMesh(theShape);
1428   aResMap.insert(std::make_pair(sm,aResVec));
1429
1430   return true;
1431 }
1432
1433 //================================================================================
1434 /*!
1435  * \brief Create prisms
1436  * \param columns - columns of nodes generated from nodes of a mesh face
1437  * \param helper - helper initialized by mesh and shape to add prisms to
1438  */
1439 //================================================================================
1440
1441 void StdMeshers_Prism_3D::AddPrisms( vector<const TNodeColumn*> & columns,
1442                                      SMESH_MesherHelper*          helper)
1443 {
1444   int nbNodes = columns.size();
1445   int nbZ     = columns[0]->size();
1446   if ( nbZ < 2 ) return;
1447
1448   // find out orientation
1449   bool isForward = true;
1450   SMDS_VolumeTool vTool;
1451   int z = 1;
1452   switch ( nbNodes ) {
1453   case 3: {
1454     SMDS_VolumeOfNodes tmpPenta ( (*columns[0])[z-1], // bottom
1455                                   (*columns[1])[z-1],
1456                                   (*columns[2])[z-1],
1457                                   (*columns[0])[z],   // top
1458                                   (*columns[1])[z],
1459                                   (*columns[2])[z] );
1460     vTool.Set( &tmpPenta );
1461     isForward  = vTool.IsForward();
1462     break;
1463   }
1464   case 4: {
1465     SMDS_VolumeOfNodes tmpHex( (*columns[0])[z-1], (*columns[1])[z-1], // bottom
1466                                (*columns[2])[z-1], (*columns[3])[z-1],
1467                                (*columns[0])[z],   (*columns[1])[z],   // top
1468                                (*columns[2])[z],   (*columns[3])[z] );
1469     vTool.Set( &tmpHex );
1470     isForward  = vTool.IsForward();
1471     break;
1472   }
1473   default:
1474     const int di = (nbNodes+1) / 3;
1475     SMDS_VolumeOfNodes tmpVol ( (*columns[0]   )[z-1],
1476                                 (*columns[di]  )[z-1],
1477                                 (*columns[2*di])[z-1],
1478                                 (*columns[0]   )[z],
1479                                 (*columns[di]  )[z],
1480                                 (*columns[2*di])[z] );
1481     vTool.Set( &tmpVol );
1482     isForward  = vTool.IsForward();
1483   }
1484
1485   // vertical loop on columns
1486
1487   helper->SetElementsOnShape( true );
1488
1489   switch ( nbNodes ) {
1490
1491   case 3: { // ---------- pentahedra
1492     const int i1 = isForward ? 1 : 2;
1493     const int i2 = isForward ? 2 : 1;
1494     for ( z = 1; z < nbZ; ++z )
1495       helper->AddVolume( (*columns[0 ])[z-1], // bottom
1496                          (*columns[i1])[z-1],
1497                          (*columns[i2])[z-1],
1498                          (*columns[0 ])[z],   // top
1499                          (*columns[i1])[z],
1500                          (*columns[i2])[z] );
1501     break;
1502   }
1503   case 4: { // ---------- hexahedra
1504     const int i1 = isForward ? 1 : 3;
1505     const int i3 = isForward ? 3 : 1;
1506     for ( z = 1; z < nbZ; ++z )
1507       helper->AddVolume( (*columns[0])[z-1], (*columns[i1])[z-1], // bottom
1508                          (*columns[2])[z-1], (*columns[i3])[z-1],
1509                          (*columns[0])[z],   (*columns[i1])[z],     // top
1510                          (*columns[2])[z],   (*columns[i3])[z] );
1511     break;
1512   }
1513   case 6: { // ---------- octahedra
1514     const int iBase1 = isForward ? -1 : 0;
1515     const int iBase2 = isForward ?  0 :-1;
1516     for ( z = 1; z < nbZ; ++z )
1517       helper->AddVolume( (*columns[0])[z+iBase1], (*columns[1])[z+iBase1], // bottom or top
1518                          (*columns[2])[z+iBase1], (*columns[3])[z+iBase1],
1519                          (*columns[4])[z+iBase1], (*columns[5])[z+iBase1],
1520                          (*columns[0])[z+iBase2], (*columns[1])[z+iBase2], // top or bottom
1521                          (*columns[2])[z+iBase2], (*columns[3])[z+iBase2],
1522                          (*columns[4])[z+iBase2], (*columns[5])[z+iBase2] );
1523     break;
1524   }
1525   default: // ---------- polyhedra
1526     vector<int> quantities( 2 + nbNodes, 4 );
1527     quantities[0] = quantities[1] = nbNodes;
1528     columns.resize( nbNodes + 1 );
1529     columns[ nbNodes ] = columns[ 0 ];
1530     const int i1 = isForward ? 1 : 3;
1531     const int i3 = isForward ? 3 : 1;
1532     const int iBase1 = isForward ? -1 : 0;
1533     const int iBase2 = isForward ?  0 :-1;
1534     vector<const SMDS_MeshNode*> nodes( 2*nbNodes + 4*nbNodes);
1535     for ( z = 1; z < nbZ; ++z )
1536     {
1537       for ( int i = 0; i < nbNodes; ++i ) {
1538         nodes[ i             ] = (*columns[ i ])[z+iBase1]; // bottom or top
1539         nodes[ 2*nbNodes-i-1 ] = (*columns[ i ])[z+iBase2]; // top or bottom
1540         // side
1541         int di = 2*nbNodes + 4*i;
1542         nodes[ di+0 ] = (*columns[i  ])[z  ];
1543         nodes[ di+i1] = (*columns[i+1])[z  ];
1544         nodes[ di+2 ] = (*columns[i+1])[z-1];
1545         nodes[ di+i3] = (*columns[i  ])[z-1];
1546       }
1547       helper->AddPolyhedralVolume( nodes, quantities );
1548     }
1549
1550   } // switch ( nbNodes )
1551 }
1552
1553 //================================================================================
1554 /*!
1555  * \brief Find correspondence between bottom and top nodes
1556  *  If elements on the bottom and top faces are topologically different,
1557  *  and projection is possible and allowed, perform the projection
1558  *  \retval bool - is a success or not
1559  */
1560 //================================================================================
1561
1562 bool StdMeshers_Prism_3D::assocOrProjBottom2Top()
1563 {
1564   SMESH_subMesh * botSM = myBlock.SubMesh( ID_BOT_FACE );
1565   SMESH_subMesh * topSM = myBlock.SubMesh( ID_TOP_FACE );
1566
1567   SMESHDS_SubMesh * botSMDS = botSM->GetSubMeshDS();
1568   SMESHDS_SubMesh * topSMDS = topSM->GetSubMeshDS();
1569
1570   if ( !botSMDS || botSMDS->NbElements() == 0 )
1571   {
1572     _gen->Compute( *myHelper->GetMesh(), botSM->GetSubShape() );
1573     botSMDS = botSM->GetSubMeshDS();
1574     if ( !botSMDS || botSMDS->NbElements() == 0 )
1575       return toSM( error(TCom("No elements on face #") << botSM->GetId() ));
1576   }
1577
1578   bool needProject = !topSM->IsMeshComputed();
1579   if ( !needProject && 
1580        (botSMDS->NbElements() != topSMDS->NbElements() ||
1581         botSMDS->NbNodes()    != topSMDS->NbNodes()))
1582   {
1583     MESSAGE("nb elem bot " << botSMDS->NbElements() <<
1584             " top " << ( topSMDS ? topSMDS->NbElements() : 0 ));
1585     MESSAGE("nb node bot " << botSMDS->NbNodes() <<
1586             " top " << ( topSMDS ? topSMDS->NbNodes() : 0 ));
1587     return toSM( error(TCom("Mesh on faces #") << botSM->GetId()
1588                        <<" and #"<< topSM->GetId() << " seems different" ));
1589   }
1590
1591   if ( 0/*needProject && !myProjectTriangles*/ )
1592     return toSM( error(TCom("Mesh on faces #") << botSM->GetId()
1593                        <<" and #"<< topSM->GetId() << " seems different" ));
1594   ///RETURN_BAD_RESULT("Need to project but not allowed");
1595
1596   if ( needProject )
1597   {
1598     return projectBottomToTop();
1599   }
1600
1601   TopoDS_Face botFace = TopoDS::Face( myBlock.Shape( ID_BOT_FACE ));
1602   TopoDS_Face topFace = TopoDS::Face( myBlock.Shape( ID_TOP_FACE ));
1603   // associate top and bottom faces
1604   TAssocTool::TShapeShapeMap shape2ShapeMap;
1605   if ( !TAssocTool::FindSubShapeAssociation( botFace, myBlock.Mesh(),
1606                                              topFace, myBlock.Mesh(),
1607                                              shape2ShapeMap) )
1608     return toSM( error(TCom("Topology of faces #") << botSM->GetId()
1609                        <<" and #"<< topSM->GetId() << " seems different" ));
1610
1611   // Find matching nodes of top and bottom faces
1612   TNodeNodeMap n2nMap;
1613   if ( ! TAssocTool::FindMatchingNodesOnFaces( botFace, myBlock.Mesh(),
1614                                                topFace, myBlock.Mesh(),
1615                                                shape2ShapeMap, n2nMap ))
1616     return toSM( error(TCom("Mesh on faces #") << botSM->GetId()
1617                        <<" and #"<< topSM->GetId() << " seems different" ));
1618
1619   // Fill myBotToColumnMap
1620
1621   int zSize = myBlock.VerticalSize();
1622   //TNode prevTNode;
1623   TNodeNodeMap::iterator bN_tN = n2nMap.begin();
1624   for ( ; bN_tN != n2nMap.end(); ++bN_tN )
1625   {
1626     const SMDS_MeshNode* botNode = bN_tN->first;
1627     const SMDS_MeshNode* topNode = bN_tN->second;
1628     if ( botNode->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE )
1629       continue; // wall columns are contained in myBlock
1630     // create node column
1631     Prism_3D::TNode bN( botNode );
1632     TNode2ColumnMap::iterator bN_col = 
1633       myBotToColumnMap.insert( make_pair ( bN, TNodeColumn() )).first;
1634     TNodeColumn & column = bN_col->second;
1635     column.resize( zSize );
1636     column.front() = botNode;
1637     column.back()  = topNode;
1638   }
1639   return true;
1640 }
1641
1642 //================================================================================
1643 /*!
1644  * \brief Remove quadrangles from the top face and
1645  * create triangles there by projection from the bottom
1646  * \retval bool - a success or not
1647  */
1648 //================================================================================
1649
1650 bool StdMeshers_Prism_3D::projectBottomToTop()
1651 {
1652   SMESHDS_Mesh*  meshDS = myBlock.MeshDS();
1653   SMESH_subMesh * botSM = myBlock.SubMesh( ID_BOT_FACE );
1654   SMESH_subMesh * topSM = myBlock.SubMesh( ID_TOP_FACE );
1655
1656   SMESHDS_SubMesh * botSMDS = botSM->GetSubMeshDS();
1657   SMESHDS_SubMesh * topSMDS = topSM->GetSubMeshDS();
1658
1659   if ( topSMDS && topSMDS->NbElements() > 0 )
1660     topSM->ComputeStateEngine( SMESH_subMesh::CLEAN );
1661
1662   const TopoDS_Shape& botFace = myBlock.Shape( ID_BOT_FACE ); // oriented within the 3D SHAPE
1663   const TopoDS_Shape& topFace = myBlock.Shape( ID_TOP_FACE);
1664   int topFaceID = meshDS->ShapeToIndex( topFace );
1665
1666   // Fill myBotToColumnMap
1667
1668   int zSize = myBlock.VerticalSize();
1669   Prism_3D::TNode prevTNode;
1670   SMDS_NodeIteratorPtr nIt = botSMDS->GetNodes();
1671   while ( nIt->more() )
1672   {
1673     const SMDS_MeshNode* botNode = nIt->next();
1674     if ( botNode->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE )
1675       continue; // strange
1676     // compute bottom node params
1677     Prism_3D::TNode bN( botNode );
1678     gp_XYZ paramHint(-1,-1,-1);
1679     if ( prevTNode.IsNeighbor( bN ))
1680       paramHint = prevTNode.GetParams();
1681     if ( !myBlock.ComputeParameters( bN.GetCoords(), bN.ChangeParams(),
1682                                      ID_BOT_FACE, paramHint ))
1683       return toSM( error(TCom("Can't compute normalized parameters for node ")
1684                          << botNode->GetID() << " on the face #"<< botSM->GetId() ));
1685     prevTNode = bN;
1686     // compute top node coords
1687     gp_XYZ topXYZ; gp_XY topUV;
1688     if ( !myBlock.FacePoint( ID_TOP_FACE, bN.GetParams(), topXYZ ) ||
1689          !myBlock.FaceUV   ( ID_TOP_FACE, bN.GetParams(), topUV ))
1690       return toSM( error(TCom("Can't compute coordinates "
1691                               "by normalized parameters on the face #")<< topSM->GetId() ));
1692     SMDS_MeshNode * topNode = meshDS->AddNode( topXYZ.X(),topXYZ.Y(),topXYZ.Z() );
1693     meshDS->SetNodeOnFace( topNode, topFaceID, topUV.X(), topUV.Y() );
1694     // create node column
1695     TNode2ColumnMap::iterator bN_col = 
1696       myBotToColumnMap.insert( make_pair ( bN, TNodeColumn() )).first;
1697     TNodeColumn & column = bN_col->second;
1698     column.resize( zSize );
1699     column.front() = botNode;
1700     column.back()  = topNode;
1701   }
1702
1703   // Create top faces
1704
1705   const bool oldSetElemsOnShape = myHelper->SetElementsOnShape( false );
1706
1707   // care of orientation;
1708   // if the bottom faces is orienetd OK then top faces must be reversed
1709   bool reverseTop = true;
1710   if ( myHelper->NbAncestors( botFace, *myBlock.Mesh(), TopAbs_SOLID ) > 1 )
1711     reverseTop = ! myHelper->IsReversedSubMesh( TopoDS::Face( botFace ));
1712   int iFrw, iRev, *iPtr = &( reverseTop ? iRev : iFrw );
1713
1714   // loop on bottom mesh faces
1715   SMDS_ElemIteratorPtr faceIt = botSMDS->GetElements();
1716   vector< const SMDS_MeshNode* > nodes;
1717   while ( faceIt->more() )
1718   {
1719     const SMDS_MeshElement* face = faceIt->next();
1720     if ( !face || face->GetType() != SMDSAbs_Face )
1721       continue;
1722
1723     // find top node in columns for each bottom node
1724     int nbNodes = face->NbCornerNodes();
1725     nodes.resize( nbNodes );
1726     for ( iFrw = 0, iRev = nbNodes-1; iFrw < nbNodes; ++iFrw, --iRev )
1727     {
1728       const SMDS_MeshNode* n = face->GetNode( *iPtr );
1729       if ( n->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE ) {
1730         TNode2ColumnMap::iterator bot_column = myBotToColumnMap.find( n );
1731         if ( bot_column == myBotToColumnMap.end() )
1732           return toSM( error(TCom("No nodes found above node ") << n->GetID() ));
1733         nodes[ iFrw ] = bot_column->second.back();
1734       }
1735       else {
1736         const TNodeColumn* column = myBlock.GetNodeColumn( n );
1737         if ( !column )
1738           return toSM( error(TCom("No side nodes found above node ") << n->GetID() ));
1739         nodes[ iFrw ] = column->back();
1740       }
1741     }
1742     SMDS_MeshElement* newFace = 0;
1743     switch ( nbNodes ) {
1744
1745     case 3: {
1746       newFace = myHelper->AddFace(nodes[0], nodes[1], nodes[2]);
1747       break;
1748       }
1749     case 4: {
1750       newFace = myHelper->AddFace( nodes[0], nodes[1], nodes[2], nodes[3] );
1751       break;
1752       }
1753     default:
1754       newFace = meshDS->AddPolygonalFace( nodes );
1755     }
1756     if ( newFace )
1757       meshDS->SetMeshElementOnShape( newFace, topFaceID );
1758   }
1759
1760   myHelper->SetElementsOnShape( oldSetElemsOnShape );  
1761
1762   return true;
1763 }
1764
1765 //=======================================================================
1766 //function : project2dMesh
1767 //purpose  : Project mesh faces from a source FACE of one prism (theSrcFace)
1768 //           to a source FACE of another prism (theTgtFace)
1769 //=======================================================================
1770
1771 bool StdMeshers_Prism_3D::project2dMesh(const TopoDS_Face& theSrcFace,
1772                                         const TopoDS_Face& theTgtFace)
1773 {
1774   TProjction2dAlgo* projector2D = TProjction2dAlgo::instance( this );
1775   projector2D->myHyp.SetSourceFace( theSrcFace );
1776   bool ok = projector2D->Compute( *myHelper->GetMesh(), theTgtFace );
1777
1778   SMESH_subMesh* tgtSM = myHelper->GetMesh()->GetSubMesh( theTgtFace );
1779   tgtSM->ComputeStateEngine       ( SMESH_subMesh::CHECK_COMPUTE_STATE );
1780   tgtSM->ComputeSubMeshStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1781
1782   return ok;
1783 }
1784
1785 //================================================================================
1786 /*!
1787  * \brief Set projection coordinates of a node to a face and it's sub-shapes
1788  * \param faceID - the face given by in-block ID
1789  * \param params - node normalized parameters
1790  * \retval bool - is a success
1791  */
1792 //================================================================================
1793
1794 bool StdMeshers_Prism_3D::setFaceAndEdgesXYZ( const int faceID, const gp_XYZ& params, int z )
1795 {
1796   // find base and top edges of the face
1797   enum { BASE = 0, TOP, LEFT, RIGHT };
1798   vector< int > edgeVec; // 0-base, 1-top
1799   SMESH_Block::GetFaceEdgesIDs( faceID, edgeVec );
1800
1801   myBlock.EdgePoint( edgeVec[ BASE ], params, myShapeXYZ[ edgeVec[ BASE ]]);
1802   myBlock.EdgePoint( edgeVec[ TOP  ], params, myShapeXYZ[ edgeVec[ TOP ]]);
1803
1804   SHOWYXZ("\nparams ", params);
1805   SHOWYXZ("TOP is " <<edgeVec[ TOP ], myShapeXYZ[ edgeVec[ TOP]]);
1806   SHOWYXZ("BASE is "<<edgeVec[ BASE], myShapeXYZ[ edgeVec[ BASE]]);
1807
1808   if ( faceID == SMESH_Block::ID_Fx0z || faceID == SMESH_Block::ID_Fx1z )
1809   {
1810     myBlock.EdgePoint( edgeVec[ LEFT ], params, myShapeXYZ[ edgeVec[ LEFT ]]);
1811     myBlock.EdgePoint( edgeVec[ RIGHT ], params, myShapeXYZ[ edgeVec[ RIGHT ]]);
1812
1813     SHOWYXZ("VER "<<edgeVec[ LEFT], myShapeXYZ[ edgeVec[ LEFT]]);
1814     SHOWYXZ("VER "<<edgeVec[ RIGHT], myShapeXYZ[ edgeVec[ RIGHT]]);
1815   }
1816   myBlock.FacePoint( faceID, params, myShapeXYZ[ faceID ]);
1817   SHOWYXZ("FacePoint "<<faceID, myShapeXYZ[ faceID]);
1818
1819   return true;
1820 }
1821
1822 //=======================================================================
1823 //function : toSM
1824 //purpose  : If (!isOK), sets the error to a sub-mesh of a current SOLID
1825 //=======================================================================
1826
1827 bool StdMeshers_Prism_3D::toSM( bool isOK )
1828 {
1829   if ( mySetErrorToSM &&
1830        !isOK &&
1831        myHelper &&
1832        !myHelper->GetSubShape().IsNull() &&
1833        myHelper->GetSubShape().ShapeType() == TopAbs_SOLID)
1834   {
1835     SMESH_subMesh* sm = myHelper->GetMesh()->GetSubMesh( myHelper->GetSubShape() );
1836     sm->GetComputeError() = this->GetComputeError();
1837     // clear error in order not to return it twice
1838     _error = COMPERR_OK;
1839     _comment.clear();
1840   }
1841   return isOK;
1842 }
1843
1844 //=======================================================================
1845 //function : shapeID
1846 //purpose  : Return index of a shape
1847 //=======================================================================
1848
1849 int StdMeshers_Prism_3D::shapeID( const TopoDS_Shape& S )
1850 {
1851   if ( S.IsNull() ) return 0;
1852   if ( !myHelper  ) return -3;
1853   return myHelper->GetMeshDS()->ShapeToIndex( S );
1854 }
1855
1856 namespace Prism_3D
1857 {
1858   //================================================================================
1859   /*!
1860    * \brief Return true if this node and other one belong to one face
1861    */
1862   //================================================================================
1863
1864   bool Prism_3D::TNode::IsNeighbor( const Prism_3D::TNode& other ) const
1865   {
1866     if ( !other.myNode || !myNode ) return false;
1867
1868     SMDS_ElemIteratorPtr fIt = other.myNode->GetInverseElementIterator(SMDSAbs_Face);
1869     while ( fIt->more() )
1870       if ( fIt->next()->GetNodeIndex( myNode ) >= 0 )
1871         return true;
1872     return false;
1873   }
1874
1875   //================================================================================
1876   /*!
1877    * \brief Prism initialization
1878    */
1879   //================================================================================
1880
1881   void TPrismTopo::Clear()
1882   {
1883     myShape3D.Nullify();
1884     myTop.Nullify();
1885     myBottom.Nullify();
1886     myWallQuads.clear();
1887     myBottomEdges.clear();
1888     myNbEdgesInWires.clear();
1889     myWallQuads.clear();
1890   }
1891
1892 } // namespace Prism_3D
1893
1894 //================================================================================
1895 /*!
1896  * \brief Constructor. Initialization is needed
1897  */
1898 //================================================================================
1899
1900 StdMeshers_PrismAsBlock::StdMeshers_PrismAsBlock()
1901 {
1902   mySide = 0;
1903 }
1904
1905 StdMeshers_PrismAsBlock::~StdMeshers_PrismAsBlock()
1906 {
1907   Clear();
1908 }
1909 void StdMeshers_PrismAsBlock::Clear()
1910 {
1911   myHelper = 0;
1912   myShapeIDMap.Clear();
1913   myError.reset();
1914
1915   if ( mySide ) {
1916     delete mySide; mySide = 0;
1917   }
1918   myParam2ColumnMaps.clear();
1919   myShapeIndex2ColumnMap.clear();
1920 }
1921
1922 //=======================================================================
1923 //function : initPrism
1924 //purpose  : Analyse shape geometry and mesh.
1925 //           If there are triangles on one of faces, it becomes 'bottom'.
1926 //           thePrism.myBottom can be already set up.
1927 //=======================================================================
1928
1929 bool StdMeshers_Prism_3D::initPrism(Prism_3D::TPrismTopo& thePrism,
1930                                     const TopoDS_Shape&   shape3D)
1931 {
1932   myHelper->SetSubShape( shape3D );
1933
1934   SMESH_subMesh* mainSubMesh = myHelper->GetMesh()->GetSubMeshContaining( shape3D );
1935   if ( !mainSubMesh ) return toSM( error(COMPERR_BAD_INPUT_MESH,"Null submesh of shape3D"));
1936
1937   // detect not-quad FACE sub-meshes of the 3D SHAPE
1938   list< SMESH_subMesh* > notQuadGeomSubMesh;
1939   list< SMESH_subMesh* > notQuadElemSubMesh;
1940   int nbFaces = 0;
1941   //
1942   SMESH_subMesh* anyFaceSM = 0;
1943   SMESH_subMeshIteratorPtr smIt = mainSubMesh->getDependsOnIterator(false,true);
1944   while ( smIt->more() )
1945   {
1946     SMESH_subMesh* sm = smIt->next();
1947     const TopoDS_Shape& face = sm->GetSubShape();
1948     if      ( face.ShapeType() > TopAbs_FACE ) break;
1949     else if ( face.ShapeType() < TopAbs_FACE ) continue;
1950     nbFaces++;
1951     anyFaceSM = sm;
1952
1953     // is quadrangle FACE?
1954     list< TopoDS_Edge > orderedEdges;
1955     list< int >         nbEdgesInWires;
1956     int nbWires = SMESH_Block::GetOrderedEdges( TopoDS::Face( face ), orderedEdges,
1957                                                 nbEdgesInWires );
1958     if ( nbWires != 1 || nbEdgesInWires.front() != 4 )
1959       notQuadGeomSubMesh.push_back( sm );
1960
1961     // look for not quadrangle mesh elements
1962     if ( SMESHDS_SubMesh* smDS = sm->GetSubMeshDS() )
1963       if ( !myHelper->IsSameElemGeometry( smDS, SMDSGeom_QUADRANGLE ))
1964         notQuadElemSubMesh.push_back( sm );
1965   }
1966
1967   int nbNotQuadMeshed = notQuadElemSubMesh.size();
1968   int       nbNotQuad = notQuadGeomSubMesh.size();
1969   bool     hasNotQuad = ( nbNotQuad || nbNotQuadMeshed );
1970
1971   // detect bad cases
1972   if ( nbNotQuadMeshed > 2 )
1973   {
1974     return toSM( error(COMPERR_BAD_INPUT_MESH,
1975                        TCom("More than 2 faces with not quadrangle elements: ")
1976                        <<nbNotQuadMeshed));
1977   }
1978   if ( nbNotQuad > 2 || !thePrism.myBottom.IsNull() )
1979   {
1980     // Issue 0020843 - one of side FACEs is quasi-quadrilateral (not 4 EDGEs).
1981     // Remove from notQuadGeomSubMesh faces meshed with regular grid
1982     int nbQuasiQuads = removeQuasiQuads( notQuadGeomSubMesh, myHelper,
1983                                          TQuadrangleAlgo::instance(this,myHelper) );
1984     nbNotQuad -= nbQuasiQuads;
1985     if ( nbNotQuad > 2 )
1986       return toSM( error(COMPERR_BAD_SHAPE,
1987                          TCom("More than 2 not quadrilateral faces: ") <<nbNotQuad));
1988     hasNotQuad = ( nbNotQuad || nbNotQuadMeshed );
1989   }
1990
1991   // Analyse mesh and topology of FACEs: choose the bottom sub-mesh.
1992   // If there are not quadrangle FACEs, they are top and bottom ones.
1993   // Not quadrangle FACEs must be only on top and bottom.
1994
1995   SMESH_subMesh * botSM = 0;
1996   SMESH_subMesh * topSM = 0;
1997
1998   if ( hasNotQuad ) // can chose a bottom FACE
1999   {
2000     if ( nbNotQuadMeshed > 0 ) botSM = notQuadElemSubMesh.front();
2001     else                       botSM = notQuadGeomSubMesh.front();
2002     if ( nbNotQuadMeshed > 1 ) topSM = notQuadElemSubMesh.back();
2003     else if ( nbNotQuad  > 1 ) topSM = notQuadGeomSubMesh.back();
2004
2005     if ( topSM == botSM ) {
2006       if ( nbNotQuadMeshed > 1 ) topSM = notQuadElemSubMesh.front();
2007       else                       topSM = notQuadGeomSubMesh.front();
2008     }
2009
2010     // detect mesh triangles on wall FACEs
2011     if ( nbNotQuad == 2 && nbNotQuadMeshed > 0 ) {
2012       bool ok = false;
2013       if ( nbNotQuadMeshed == 1 )
2014         ok = ( find( notQuadGeomSubMesh.begin(),
2015                      notQuadGeomSubMesh.end(), botSM ) != notQuadGeomSubMesh.end() );
2016       else
2017         ok = ( notQuadGeomSubMesh == notQuadElemSubMesh );
2018       if ( !ok )
2019         return toSM( error(COMPERR_BAD_INPUT_MESH,
2020                            "Side face meshed with not quadrangle elements"));
2021     }
2022   }
2023
2024   thePrism.myNotQuadOnTop = ( nbNotQuadMeshed > 1 );
2025
2026   // use thePrism.myBottom
2027   if ( !thePrism.myBottom.IsNull() )
2028   {
2029     if ( botSM ) {
2030       if ( ! botSM->GetSubShape().IsSame( thePrism.myBottom )) {
2031         std::swap( botSM, topSM );
2032         if ( ! botSM->GetSubShape().IsSame( thePrism.myBottom ))
2033           return toSM( error( COMPERR_BAD_INPUT_MESH,
2034                               "Incompatible non-structured sub-meshes"));
2035       }
2036     }
2037     else {
2038       botSM = myHelper->GetMesh()->GetSubMesh( thePrism.myBottom );
2039     }
2040   }
2041   else if ( !botSM ) // find a proper bottom
2042   {
2043     // composite walls or not prism shape
2044     for ( TopExp_Explorer f( shape3D, TopAbs_FACE ); f.More(); f.Next() )
2045     {
2046       int minNbFaces = 2 + myHelper->Count( f.Current(), TopAbs_EDGE, false);
2047       if ( nbFaces >= minNbFaces)
2048       {
2049         thePrism.Clear();
2050         thePrism.myBottom = TopoDS::Face( f.Current() );
2051         if ( initPrism( thePrism, shape3D ))
2052           return true;
2053       }
2054       return toSM( error( COMPERR_BAD_SHAPE ));
2055     }
2056   }
2057
2058   // find vertex 000 - the one with smallest coordinates (for easy DEBUG :-)
2059   TopoDS_Vertex V000;
2060   double minVal = DBL_MAX, minX, val;
2061   for ( TopExp_Explorer exp( botSM->GetSubShape(), TopAbs_VERTEX );
2062         exp.More(); exp.Next() )
2063   {
2064     const TopoDS_Vertex& v = TopoDS::Vertex( exp.Current() );
2065     gp_Pnt P = BRep_Tool::Pnt( v );
2066     val = P.X() + P.Y() + P.Z();
2067     if ( val < minVal || ( val == minVal && P.X() < minX )) {
2068       V000 = v;
2069       minVal = val;
2070       minX = P.X();
2071     }
2072   }
2073
2074   thePrism.myShape3D = shape3D;
2075   if ( thePrism.myBottom.IsNull() )
2076     thePrism.myBottom  = TopoDS::Face( botSM->GetSubShape() );
2077   thePrism.myBottom.Orientation( myHelper->GetSubShapeOri( shape3D,
2078                                                            thePrism.myBottom ));
2079   // Get ordered bottom edges
2080   TopoDS_Face reverseBottom = // to have order of top EDGEs as in the top FACE
2081     TopoDS::Face( thePrism.myBottom.Reversed() );
2082   SMESH_Block::GetOrderedEdges( reverseBottom,
2083                                 thePrism.myBottomEdges,
2084                                 thePrism.myNbEdgesInWires, V000 );
2085
2086   // Get Wall faces corresponding to the ordered bottom edges and the top FACE
2087   if ( !getWallFaces( thePrism, nbFaces ))
2088     return false; //toSM( error(COMPERR_BAD_SHAPE, "Can't find side faces"));
2089
2090   if ( topSM )
2091   {
2092     if ( !thePrism.myTop.IsSame( topSM->GetSubShape() ))
2093       return toSM( error
2094                    (notQuadGeomSubMesh.empty() ? COMPERR_BAD_INPUT_MESH : COMPERR_BAD_SHAPE,
2095                     "Non-quadrilateral faces are not opposite"));
2096
2097     // check that the found top and bottom FACEs are opposite
2098     list< TopoDS_Edge >::iterator edge = thePrism.myBottomEdges.begin();
2099     for ( ; edge != thePrism.myBottomEdges.end(); ++edge )
2100       if ( myHelper->IsSubShape( *edge, thePrism.myTop ))
2101         return toSM( error
2102                      (notQuadGeomSubMesh.empty() ? COMPERR_BAD_INPUT_MESH : COMPERR_BAD_SHAPE,
2103                       "Non-quadrilateral faces are not opposite"));
2104   }
2105
2106   return true;
2107 }
2108
2109 //================================================================================
2110 /*!
2111  * \brief Initialization.
2112  * \param helper - helper loaded with mesh and 3D shape
2113  * \param thePrism - a prosm data
2114  * \retval bool - false if a mesh or a shape are KO
2115  */
2116 //================================================================================
2117
2118 bool StdMeshers_PrismAsBlock::Init(SMESH_MesherHelper*         helper,
2119                                    const Prism_3D::TPrismTopo& thePrism)
2120 {
2121   if ( mySide ) {
2122     delete mySide; mySide = 0;
2123   }
2124   vector< TSideFace* >         sideFaces( NB_WALL_FACES, 0 );
2125   vector< pair< double, double> > params( NB_WALL_FACES );
2126   mySide = new TSideFace( sideFaces, params );
2127
2128   myHelper = helper;
2129   SMESHDS_Mesh* meshDS = myHelper->GetMeshDS();
2130
2131   SMESH_Block::init();
2132   myShapeIDMap.Clear();
2133   myShapeIndex2ColumnMap.clear();
2134   
2135   int wallFaceIds[ NB_WALL_FACES ] = { // to walk around a block
2136     SMESH_Block::ID_Fx0z, SMESH_Block::ID_F1yz,
2137     SMESH_Block::ID_Fx1z, SMESH_Block::ID_F0yz
2138   };
2139
2140   myError = SMESH_ComputeError::New();
2141
2142   myNotQuadOnTop = thePrism.myNotQuadOnTop;
2143
2144   // Find columns of wall nodes and calculate edges' lengths
2145   // --------------------------------------------------------
2146
2147   myParam2ColumnMaps.clear();
2148   myParam2ColumnMaps.resize( thePrism.myBottomEdges.size() ); // total nb edges
2149
2150   size_t iE, nbEdges = thePrism.myNbEdgesInWires.front(); // nb outer edges
2151   vector< double >    edgeLength( nbEdges );
2152   multimap< double, int > len2edgeMap;
2153
2154   list< TopoDS_Edge >::const_iterator edgeIt = thePrism.myBottomEdges.begin();
2155   for ( iE = 0; iE < nbEdges; ++iE, ++edgeIt )
2156   {
2157     TParam2ColumnMap & faceColumns = myParam2ColumnMaps[ iE ];
2158
2159     Prism_3D::TQuadList::const_iterator quad = thePrism.myWallQuads[ iE ].begin();
2160     for ( ; quad != thePrism.myWallQuads[ iE ].end(); ++quad )
2161     {
2162       const TopoDS_Edge& quadBot = (*quad)->side[ QUAD_BOTTOM_SIDE ]->Edge( 0 );
2163       if ( !myHelper->LoadNodeColumns( faceColumns, (*quad)->face, quadBot, meshDS ))
2164         return error(COMPERR_BAD_INPUT_MESH, TCom("Can't find regular quadrangle mesh ")
2165                      << "on a side face #" << MeshDS()->ShapeToIndex( (*quad)->face ));
2166     }
2167     SHOWYXZ("\np1 F " <<iE, gpXYZ(faceColumns.begin()->second.front() ));
2168     SHOWYXZ("p2 F "   <<iE, gpXYZ(faceColumns.rbegin()->second.front() ));
2169     SHOWYXZ("V First "<<iE, BRep_Tool::Pnt( TopExp::FirstVertex(*edgeIt,true )));
2170
2171     edgeLength[ iE ] = SMESH_Algo::EdgeLength( *edgeIt );
2172
2173     if ( nbEdges < NB_WALL_FACES ) // fill map used to split faces
2174     {
2175       SMESHDS_SubMesh* smDS = meshDS->MeshElements( *edgeIt);
2176       if ( !smDS )
2177         return error(COMPERR_BAD_INPUT_MESH, TCom("Null submesh on the edge #")
2178                      << MeshDS()->ShapeToIndex( *edgeIt ));
2179       len2edgeMap.insert( make_pair( edgeLength[ iE ], iE ));
2180     }
2181   }
2182   // Load columns of internal edges (forming holes)
2183   // and fill map ShapeIndex to TParam2ColumnMap for them
2184   for ( ; edgeIt != thePrism.myBottomEdges.end() ; ++edgeIt, ++iE )
2185   {
2186     TParam2ColumnMap & faceColumns = myParam2ColumnMaps[ iE ];
2187
2188     Prism_3D::TQuadList::const_iterator quad = thePrism.myWallQuads[ iE ].begin();
2189     for ( ; quad != thePrism.myWallQuads[ iE ].end(); ++quad )
2190     {
2191       const TopoDS_Edge& quadBot = (*quad)->side[ QUAD_BOTTOM_SIDE ]->Edge( 0 );
2192       if ( !myHelper->LoadNodeColumns( faceColumns, (*quad)->face, quadBot, meshDS ))
2193         return error(COMPERR_BAD_INPUT_MESH, TCom("Can't find regular quadrangle mesh ")
2194                      << "on a side face #" << MeshDS()->ShapeToIndex( (*quad)->face ));
2195     }
2196     // edge columns
2197     int id = MeshDS()->ShapeToIndex( *edgeIt );
2198     bool isForward = true; // meaningless for intenal wires
2199     myShapeIndex2ColumnMap[ id ] = make_pair( & faceColumns, isForward );
2200     // columns for vertices
2201     // 1
2202     const SMDS_MeshNode* n0 = faceColumns.begin()->second.front();
2203     id = n0->getshapeId();
2204     myShapeIndex2ColumnMap[ id ] = make_pair( & faceColumns, isForward );
2205     // 2
2206     const SMDS_MeshNode* n1 = faceColumns.rbegin()->second.front();
2207     id = n1->getshapeId();
2208     myShapeIndex2ColumnMap[ id ] = make_pair( & faceColumns, isForward );
2209
2210     // SHOWYXZ("\np1 F " <<iE, gpXYZ(faceColumns.begin()->second.front() ));
2211     // SHOWYXZ("p2 F "   <<iE, gpXYZ(faceColumns.rbegin()->second.front() ));
2212     // SHOWYXZ("V First "<<iE, BRep_Tool::Pnt( TopExp::FirstVertex(*edgeIt,true )));
2213   }
2214
2215   // Create 4 wall faces of a block
2216   // -------------------------------
2217
2218   if ( nbEdges <= NB_WALL_FACES ) // ************* Split faces if necessary
2219   {
2220     map< int, int > iE2nbSplit;
2221     if ( nbEdges != NB_WALL_FACES ) // define how to split
2222     {
2223       if ( len2edgeMap.size() != nbEdges )
2224         RETURN_BAD_RESULT("Uniqueness of edge lengths not assured");
2225
2226       multimap< double, int >::reverse_iterator maxLen_i = len2edgeMap.rbegin();
2227       multimap< double, int >::reverse_iterator midLen_i = ++len2edgeMap.rbegin();
2228
2229       double maxLen = maxLen_i->first;
2230       double midLen = ( len2edgeMap.size() == 1 ) ? 0 : midLen_i->first;
2231       switch ( nbEdges ) {
2232       case 1: // 0-th edge is split into 4 parts
2233         iE2nbSplit.insert( make_pair( 0, 4 )); break;
2234       case 2: // either the longest edge is split into 3 parts, or both edges into halves
2235         if ( maxLen / 3 > midLen / 2 ) {
2236           iE2nbSplit.insert( make_pair( maxLen_i->second, 3 ));
2237         }
2238         else {
2239           iE2nbSplit.insert( make_pair( maxLen_i->second, 2 ));
2240           iE2nbSplit.insert( make_pair( midLen_i->second, 2 ));
2241         }
2242         break;
2243       case 3:
2244         // split longest into halves
2245         iE2nbSplit.insert( make_pair( maxLen_i->second, 2 ));
2246       }
2247     }
2248     // Create TSideFace's
2249     int iSide = 0;
2250     list< TopoDS_Edge >::const_iterator botE = thePrism.myBottomEdges.begin();
2251     for ( iE = 0; iE < nbEdges; ++iE, ++botE )
2252     {
2253       TFaceQuadStructPtr quad = thePrism.myWallQuads[ iE ].front();
2254       // split?
2255       map< int, int >::iterator i_nb = iE2nbSplit.find( iE );
2256       if ( i_nb != iE2nbSplit.end() ) {
2257         // split!
2258         int nbSplit = i_nb->second;
2259         vector< double > params;
2260         splitParams( nbSplit, &myParam2ColumnMaps[ iE ], params );
2261         const bool isForward =
2262           StdMeshers_PrismAsBlock::IsForwardEdge( myHelper->GetMeshDS(),
2263                                                   myParam2ColumnMaps[iE],
2264                                                   *botE, SMESH_Block::ID_Fx0z );
2265         for ( int i = 0; i < nbSplit; ++i ) {
2266           double f = ( isForward ? params[ i ]   : params[ nbSplit - i-1 ]);
2267           double l = ( isForward ? params[ i+1 ] : params[ nbSplit - i ]);
2268           TSideFace* comp = new TSideFace( myHelper, wallFaceIds[ iSide ],
2269                                            thePrism.myWallQuads[ iE ], *botE,
2270                                            &myParam2ColumnMaps[ iE ], f, l );
2271           mySide->SetComponent( iSide++, comp );
2272         }
2273       }
2274       else {
2275         TSideFace* comp = new TSideFace( myHelper, wallFaceIds[ iSide ],
2276                                          thePrism.myWallQuads[ iE ], *botE,
2277                                          &myParam2ColumnMaps[ iE ]);
2278         mySide->SetComponent( iSide++, comp );
2279       }
2280     }
2281   }
2282   else { // **************************** Unite faces
2283
2284     // unite first faces
2285     int nbExraFaces = nbEdges - 3;
2286     int iSide = 0, iE;
2287     double u0 = 0, sumLen = 0;
2288     for ( iE = 0; iE < nbExraFaces; ++iE )
2289       sumLen += edgeLength[ iE ];
2290
2291     vector< TSideFace* >        components( nbExraFaces );
2292     vector< pair< double, double> > params( nbExraFaces );
2293     list< TopoDS_Edge >::const_iterator botE = thePrism.myBottomEdges.begin();
2294     for ( iE = 0; iE < nbExraFaces; ++iE, ++botE )
2295     {
2296       components[ iE ] = new TSideFace( myHelper, wallFaceIds[ iSide ],
2297                                         thePrism.myWallQuads[ iE ], *botE,
2298                                         &myParam2ColumnMaps[ iE ]);
2299       double u1 = u0 + edgeLength[ iE ] / sumLen;
2300       params[ iE ] = make_pair( u0 , u1 );
2301       u0 = u1;
2302     }
2303     mySide->SetComponent( iSide++, new TSideFace( components, params ));
2304
2305     // fill the rest faces
2306     for ( ; iE < nbEdges; ++iE, ++botE )
2307     {
2308       TSideFace* comp = new TSideFace( myHelper, wallFaceIds[ iSide ],
2309                                        thePrism.myWallQuads[ iE ], *botE,
2310                                        &myParam2ColumnMaps[ iE ]);
2311       mySide->SetComponent( iSide++, comp );
2312     }
2313   }
2314
2315
2316   // Fill geometry fields of SMESH_Block
2317   // ------------------------------------
2318
2319   vector< int > botEdgeIdVec;
2320   SMESH_Block::GetFaceEdgesIDs( ID_BOT_FACE, botEdgeIdVec );
2321
2322   bool isForward[NB_WALL_FACES] = { true, true, true, true };
2323   Adaptor2d_Curve2d* botPcurves[NB_WALL_FACES];
2324   Adaptor2d_Curve2d* topPcurves[NB_WALL_FACES];
2325
2326   for ( int iF = 0; iF < NB_WALL_FACES; ++iF )
2327   {
2328     TSideFace * sideFace = mySide->GetComponent( iF );
2329     if ( !sideFace )
2330       RETURN_BAD_RESULT("NULL TSideFace");
2331     int fID = sideFace->FaceID(); // in-block ID
2332
2333     // fill myShapeIDMap
2334     if ( sideFace->InsertSubShapes( myShapeIDMap ) != 8 &&
2335          !sideFace->IsComplex())
2336       MESSAGE( ": Warning : InsertSubShapes() < 8 on side " << iF );
2337
2338     // side faces geometry
2339     Adaptor2d_Curve2d* pcurves[NB_WALL_FACES];
2340     if ( !sideFace->GetPCurves( pcurves ))
2341       RETURN_BAD_RESULT("TSideFace::GetPCurves() failed");
2342
2343     SMESH_Block::TFace& tFace = myFace[ fID - ID_FirstF ];
2344     tFace.Set( fID, sideFace->Surface(), pcurves, isForward );
2345
2346     SHOWYXZ( endl<<"F "<< iF << " id " << fID << " FRW " << sideFace->IsForward(), sideFace->Value(0,0));
2347     // edges 3D geometry
2348     vector< int > edgeIdVec;
2349     SMESH_Block::GetFaceEdgesIDs( fID, edgeIdVec );
2350     for ( int isMax = 0; isMax < 2; ++isMax ) {
2351       {
2352         int eID = edgeIdVec[ isMax ];
2353         SMESH_Block::TEdge& tEdge = myEdge[ eID - ID_FirstE ];
2354         tEdge.Set( eID, sideFace->HorizCurve(isMax), true);
2355         SHOWYXZ(eID<<" HOR"<<isMax<<"(0)", sideFace->HorizCurve(isMax)->Value(0));
2356         SHOWYXZ(eID<<" HOR"<<isMax<<"(1)", sideFace->HorizCurve(isMax)->Value(1));
2357       }
2358       {
2359         int eID = edgeIdVec[ isMax+2 ];
2360         SMESH_Block::TEdge& tEdge = myEdge[ eID - ID_FirstE  ];
2361         tEdge.Set( eID, sideFace->VertiCurve(isMax), true);
2362         SHOWYXZ(eID<<" VER"<<isMax<<"(0)", sideFace->VertiCurve(isMax)->Value(0));
2363         SHOWYXZ(eID<<" VER"<<isMax<<"(1)", sideFace->VertiCurve(isMax)->Value(1));
2364
2365         // corner points
2366         vector< int > vertexIdVec;
2367         SMESH_Block::GetEdgeVertexIDs( eID, vertexIdVec );
2368         myPnt[ vertexIdVec[0] - ID_FirstV ] = tEdge.GetCurve()->Value(0).XYZ();
2369         myPnt[ vertexIdVec[1] - ID_FirstV ] = tEdge.GetCurve()->Value(1).XYZ();
2370       }
2371     }
2372     // pcurves on horizontal faces
2373     for ( iE = 0; iE < NB_WALL_FACES; ++iE ) {
2374       if ( edgeIdVec[ BOTTOM_EDGE ] == botEdgeIdVec[ iE ] ) {
2375         botPcurves[ iE ] = sideFace->HorizPCurve( false, thePrism.myBottom );
2376         topPcurves[ iE ] = sideFace->HorizPCurve( true,  thePrism.myTop );
2377         break;
2378       }
2379     }
2380     //sideFace->dumpNodes( 4 ); // debug
2381   }
2382   // horizontal faces geometry
2383   {
2384     SMESH_Block::TFace& tFace = myFace[ ID_BOT_FACE - ID_FirstF ];
2385     tFace.Set( ID_BOT_FACE, new BRepAdaptor_Surface( thePrism.myBottom ), botPcurves, isForward );
2386     SMESH_Block::Insert( thePrism.myBottom, ID_BOT_FACE, myShapeIDMap );
2387   }
2388   {
2389     SMESH_Block::TFace& tFace = myFace[ ID_TOP_FACE - ID_FirstF ];
2390     tFace.Set( ID_TOP_FACE, new BRepAdaptor_Surface( thePrism.myTop ), topPcurves, isForward );
2391     SMESH_Block::Insert( thePrism.myTop, ID_TOP_FACE, myShapeIDMap );
2392   }
2393
2394   // Fill map ShapeIndex to TParam2ColumnMap
2395   // ----------------------------------------
2396
2397   list< TSideFace* > fList;
2398   list< TSideFace* >::iterator fListIt;
2399   fList.push_back( mySide );
2400   for ( fListIt = fList.begin(); fListIt != fList.end(); ++fListIt)
2401   {
2402     int nb = (*fListIt)->NbComponents();
2403     for ( int i = 0; i < nb; ++i ) {
2404       if ( TSideFace* comp = (*fListIt)->GetComponent( i ))
2405         fList.push_back( comp );
2406     }
2407     if ( TParam2ColumnMap* cols = (*fListIt)->GetColumns()) {
2408       // columns for a base edge
2409       int id = MeshDS()->ShapeToIndex( (*fListIt)->BaseEdge() );
2410       bool isForward = (*fListIt)->IsForward();
2411       myShapeIndex2ColumnMap[ id ] = make_pair( cols, isForward );
2412
2413       // columns for vertices
2414       const SMDS_MeshNode* n0 = cols->begin()->second.front();
2415       id = n0->getshapeId();
2416       myShapeIndex2ColumnMap[ id ] = make_pair( cols, isForward );
2417
2418       const SMDS_MeshNode* n1 = cols->rbegin()->second.front();
2419       id = n1->getshapeId();
2420       myShapeIndex2ColumnMap[ id ] = make_pair( cols, !isForward );
2421     }
2422   }
2423
2424 //   gp_XYZ testPar(0.25, 0.25, 0), testCoord;
2425 //   if ( !FacePoint( ID_BOT_FACE, testPar, testCoord ))
2426 //     RETURN_BAD_RESULT("TEST FacePoint() FAILED");
2427 //   SHOWYXZ("IN TEST PARAM" , testPar);
2428 //   SHOWYXZ("OUT TEST CORD" , testCoord);
2429 //   if ( !ComputeParameters( testCoord, testPar , ID_BOT_FACE))
2430 //     RETURN_BAD_RESULT("TEST ComputeParameters() FAILED");
2431 //   SHOWYXZ("OUT TEST PARAM" , testPar);
2432
2433   return true;
2434 }
2435
2436 //================================================================================
2437 /*!
2438  * \brief Return pointer to column of nodes
2439  * \param node - bottom node from which the returned column goes up
2440  * \retval const TNodeColumn* - the found column
2441  */
2442 //================================================================================
2443
2444 const TNodeColumn* StdMeshers_PrismAsBlock::GetNodeColumn(const SMDS_MeshNode* node) const
2445 {
2446   int sID = node->getshapeId();
2447
2448   map<int, pair< TParam2ColumnMap*, bool > >::const_iterator col_frw =
2449     myShapeIndex2ColumnMap.find( sID );
2450   if ( col_frw != myShapeIndex2ColumnMap.end() ) {
2451     const TParam2ColumnMap* cols = col_frw->second.first;
2452     TParam2ColumnIt u_col = cols->begin();
2453     for ( ; u_col != cols->end(); ++u_col )
2454       if ( u_col->second[ 0 ] == node )
2455         return & u_col->second;
2456   }
2457   return 0;
2458 }
2459
2460 //=======================================================================
2461 //function : GetLayersTransformation
2462 //purpose  : Return transformations to get coordinates of nodes of each layer
2463 //           by nodes of the bottom. Layer is a set of nodes at a certain step
2464 //           from bottom to top.
2465 //=======================================================================
2466
2467 bool StdMeshers_PrismAsBlock::GetLayersTransformation(vector<gp_Trsf> &           trsf,
2468                                                       const Prism_3D::TPrismTopo& prism) const
2469 {
2470   const int zSize = VerticalSize();
2471   if ( zSize < 3 ) return true;
2472   trsf.resize( zSize - 2 );
2473
2474   // Select some node columns by which we will define coordinate system of layers
2475
2476   vector< const TNodeColumn* > columns;
2477   {
2478     bool isReverse;
2479     list< TopoDS_Edge >::const_iterator edgeIt = prism.myBottomEdges.begin();
2480     for ( int iE = 0; iE < prism.myNbEdgesInWires.front(); ++iE, ++edgeIt )
2481     {
2482       if ( BRep_Tool::Degenerated( *edgeIt )) continue;
2483       const TParam2ColumnMap* u2colMap =
2484         GetParam2ColumnMap( MeshDS()->ShapeToIndex( *edgeIt ), isReverse );
2485       if ( !u2colMap ) return false;
2486       double f = u2colMap->begin()->first, l = u2colMap->rbegin()->first;
2487       //isReverse = ( edgeIt->Orientation() == TopAbs_REVERSED );
2488       //if ( isReverse ) swap ( f, l ); -- u2colMap takes orientation into account
2489       const int nbCol = 5;
2490       for ( int i = 0; i < nbCol; ++i )
2491       {
2492         double u = f + i/double(nbCol) * ( l - f );
2493         const TNodeColumn* col = & getColumn( u2colMap, u )->second;
2494         if ( columns.empty() || col != columns.back() )
2495           columns.push_back( col );
2496       }
2497     }
2498   }
2499
2500   // Find tolerance to check transformations
2501
2502   double tol2;
2503   {
2504     Bnd_B3d bndBox;
2505     for ( int i = 0; i < columns.size(); ++i )
2506       bndBox.Add( gpXYZ( columns[i]->front() ));
2507     tol2 = bndBox.SquareExtent() * 1e-5;
2508   }
2509
2510   // Compute transformations
2511
2512   int xCol = -1;
2513   gp_Trsf fromCsZ, toCs0;
2514   gp_Ax3 cs0 = getLayerCoordSys(0, columns, xCol );
2515   //double dist0 = cs0.Location().Distance( gpXYZ( (*columns[0])[0]));
2516   toCs0.SetTransformation( cs0 );
2517   for ( int z = 1; z < zSize-1; ++z )
2518   {
2519     gp_Ax3 csZ = getLayerCoordSys(z, columns, xCol );
2520     //double distZ = csZ.Location().Distance( gpXYZ( (*columns[0])[z]));
2521     fromCsZ.SetTransformation( csZ );
2522     fromCsZ.Invert();
2523     gp_Trsf& t = trsf[ z-1 ];
2524     t = fromCsZ * toCs0;
2525     //t.SetScaleFactor( distZ/dist0 ); - it does not work properly, wrong base point
2526
2527     // check a transformation
2528     for ( int i = 0; i < columns.size(); ++i )
2529     {
2530       gp_Pnt p0 = gpXYZ( (*columns[i])[0] );
2531       gp_Pnt pz = gpXYZ( (*columns[i])[z] );
2532       t.Transforms( p0.ChangeCoord() );
2533       if ( p0.SquareDistance( pz ) > tol2 )
2534         return false;
2535     }
2536   }
2537   return true;
2538 }
2539
2540 //================================================================================
2541 /*!
2542  * \brief Check curve orientation of a bootom edge
2543   * \param meshDS - mesh DS
2544   * \param columnsMap - node columns map of side face
2545   * \param bottomEdge - the bootom edge
2546   * \param sideFaceID - side face in-block ID
2547   * \retval bool - true if orientation coinside with in-block forward orientation
2548  */
2549 //================================================================================
2550
2551 bool StdMeshers_PrismAsBlock::IsForwardEdge(SMESHDS_Mesh*           meshDS,
2552                                             const TParam2ColumnMap& columnsMap,
2553                                             const TopoDS_Edge &     bottomEdge,
2554                                             const int               sideFaceID)
2555 {
2556   bool isForward = false;
2557   if ( SMESH_MesherHelper::IsClosedEdge( bottomEdge ))
2558   {
2559     isForward = ( bottomEdge.Orientation() == TopAbs_FORWARD );
2560   }
2561   else
2562   {
2563     const TNodeColumn&     firstCol = columnsMap.begin()->second;
2564     const SMDS_MeshNode* bottomNode = firstCol[0];
2565     TopoDS_Shape firstVertex = SMESH_MesherHelper::GetSubShapeByNode( bottomNode, meshDS );
2566     isForward = ( firstVertex.IsSame( TopExp::FirstVertex( bottomEdge, true )));
2567   }
2568   // on 2 of 4 sides first vertex is end
2569   if ( sideFaceID == ID_Fx1z || sideFaceID == ID_F0yz )
2570     isForward = !isForward;
2571   return isForward;
2572 }
2573
2574 //================================================================================
2575 /*!
2576  * \brief Constructor
2577   * \param faceID - in-block ID
2578   * \param face - geom FACE
2579   * \param baseEdge - EDGE proreply oriented in the bottom EDGE !!!
2580   * \param columnsMap - map of node columns
2581   * \param first - first normalized param
2582   * \param last - last normalized param
2583  */
2584 //================================================================================
2585
2586 StdMeshers_PrismAsBlock::TSideFace::TSideFace(SMESH_MesherHelper*        helper,
2587                                               const int                  faceID,
2588                                               const Prism_3D::TQuadList& quadList,
2589                                               const TopoDS_Edge&         baseEdge,
2590                                               TParam2ColumnMap*          columnsMap,
2591                                               const double               first,
2592                                               const double               last):
2593   myID( faceID ),
2594   myParamToColumnMap( columnsMap ),
2595   myHelper( helper )
2596 {
2597   myParams.resize( 1 );
2598   myParams[ 0 ] = make_pair( first, last );
2599   mySurface     = PSurface( new BRepAdaptor_Surface( quadList.front()->face ));
2600   myBaseEdge    = baseEdge;
2601   myIsForward   = StdMeshers_PrismAsBlock::IsForwardEdge( myHelper->GetMeshDS(),
2602                                                           *myParamToColumnMap,
2603                                                           myBaseEdge, myID );
2604   if ( quadList.size() > 1 ) // side is vertically composite
2605   {
2606     // fill myShapeID2Surf map to enable finding a right surface by any sub-shape ID
2607
2608     SMESHDS_Mesh* meshDS = myHelper->GetMeshDS();
2609
2610     TopTools_IndexedDataMapOfShapeListOfShape subToFaces;
2611     Prism_3D::TQuadList::const_iterator quad = quadList.begin();
2612     for ( ; quad != quadList.end(); ++quad )
2613     {
2614       const TopoDS_Face& face = (*quad)->face;
2615       TopExp::MapShapesAndAncestors( face, TopAbs_VERTEX, TopAbs_FACE, subToFaces );
2616       TopExp::MapShapesAndAncestors( face, TopAbs_EDGE,   TopAbs_FACE, subToFaces );
2617       myShapeID2Surf.insert( make_pair( meshDS->ShapeToIndex( face ),
2618                                         PSurface( new BRepAdaptor_Surface( face ))));
2619     }
2620     for ( int i = 1; i <= subToFaces.Extent(); ++i )
2621     {
2622       const TopoDS_Shape&     sub = subToFaces.FindKey( i );
2623       TopTools_ListOfShape& faces = subToFaces( i );
2624       int subID  = meshDS->ShapeToIndex( sub );
2625       int faceID = meshDS->ShapeToIndex( faces.First() );
2626       myShapeID2Surf.insert ( make_pair( subID, myShapeID2Surf[ faceID ]));
2627     }
2628   }
2629 }
2630
2631 //================================================================================
2632 /*!
2633  * \brief Constructor of complex side face
2634  */
2635 //================================================================================
2636
2637 StdMeshers_PrismAsBlock::TSideFace::
2638 TSideFace(const vector< TSideFace* >&             components,
2639           const vector< pair< double, double> > & params)
2640   :myID( components[0] ? components[0]->myID : 0 ),
2641    myParamToColumnMap( 0 ),
2642    myParams( params ),
2643    myIsForward( true ),
2644    myComponents( components ),
2645    myHelper( components[0] ? components[0]->myHelper : 0 )
2646 {}
2647 //================================================================================
2648 /*!
2649  * \brief Copy constructor
2650   * \param other - other side
2651  */
2652 //================================================================================
2653
2654 StdMeshers_PrismAsBlock::TSideFace::TSideFace( const TSideFace& other )
2655 {
2656   myID               = other.myID;
2657   mySurface          = other.mySurface;
2658   myBaseEdge         = other.myBaseEdge;
2659   myParams           = other.myParams;
2660   myIsForward        = other.myIsForward;
2661   myHelper           = other.myHelper;
2662   myParamToColumnMap = other.myParamToColumnMap;
2663
2664   myComponents.resize( other.myComponents.size());
2665   for (int i = 0 ; i < myComponents.size(); ++i )
2666     myComponents[ i ] = new TSideFace( *other.myComponents[ i ]);
2667 }
2668
2669 //================================================================================
2670 /*!
2671  * \brief Deletes myComponents
2672  */
2673 //================================================================================
2674
2675 StdMeshers_PrismAsBlock::TSideFace::~TSideFace()
2676 {
2677   for (int i = 0 ; i < myComponents.size(); ++i )
2678     if ( myComponents[ i ] )
2679       delete myComponents[ i ];
2680 }
2681
2682 //================================================================================
2683 /*!
2684  * \brief Return geometry of the vertical curve
2685   * \param isMax - true means curve located closer to (1,1,1) block point
2686   * \retval Adaptor3d_Curve* - curve adaptor
2687  */
2688 //================================================================================
2689
2690 Adaptor3d_Curve* StdMeshers_PrismAsBlock::TSideFace::VertiCurve(const bool isMax) const
2691 {
2692   if ( !myComponents.empty() ) {
2693     if ( isMax )
2694       return myComponents.back()->VertiCurve(isMax);
2695     else
2696       return myComponents.front()->VertiCurve(isMax);
2697   }
2698   double f = myParams[0].first, l = myParams[0].second;
2699   if ( !myIsForward ) std::swap( f, l );
2700   return new TVerticalEdgeAdaptor( myParamToColumnMap, isMax ? l : f );
2701 }
2702
2703 //================================================================================
2704 /*!
2705  * \brief Return geometry of the top or bottom curve
2706   * \param isTop - 
2707   * \retval Adaptor3d_Curve* - 
2708  */
2709 //================================================================================
2710
2711 Adaptor3d_Curve* StdMeshers_PrismAsBlock::TSideFace::HorizCurve(const bool isTop) const
2712 {
2713   return new THorizontalEdgeAdaptor( this, isTop );
2714 }
2715
2716 //================================================================================
2717 /*!
2718  * \brief Return pcurves
2719   * \param pcurv - array of 4 pcurves
2720   * \retval bool - is a success
2721  */
2722 //================================================================================
2723
2724 bool StdMeshers_PrismAsBlock::TSideFace::GetPCurves(Adaptor2d_Curve2d* pcurv[4]) const
2725 {
2726   int iEdge[ 4 ] = { BOTTOM_EDGE, TOP_EDGE, V0_EDGE, V1_EDGE };
2727
2728   for ( int i = 0 ; i < 4 ; ++i ) {
2729     Handle(Geom2d_Line) line;
2730     switch ( iEdge[ i ] ) {
2731     case TOP_EDGE:
2732       line = new Geom2d_Line( gp_Pnt2d( 0, 1 ), gp::DX2d() ); break;
2733     case BOTTOM_EDGE:
2734       line = new Geom2d_Line( gp::Origin2d(), gp::DX2d() ); break;
2735     case V0_EDGE:
2736       line = new Geom2d_Line( gp::Origin2d(), gp::DY2d() ); break;
2737     case V1_EDGE:
2738       line = new Geom2d_Line( gp_Pnt2d( 1, 0 ), gp::DY2d() ); break;
2739     }
2740     pcurv[ i ] = new Geom2dAdaptor_Curve( line, 0, 1 );
2741   }
2742   return true;
2743 }
2744
2745 //================================================================================
2746 /*!
2747  * \brief Returns geometry of pcurve on a horizontal face
2748   * \param isTop - is top or bottom face
2749   * \param horFace - a horizontal face
2750   * \retval Adaptor2d_Curve2d* - curve adaptor
2751  */
2752 //================================================================================
2753
2754 Adaptor2d_Curve2d*
2755 StdMeshers_PrismAsBlock::TSideFace::HorizPCurve(const bool         isTop,
2756                                                 const TopoDS_Face& horFace) const
2757 {
2758   return new TPCurveOnHorFaceAdaptor( this, isTop, horFace );
2759 }
2760
2761 //================================================================================
2762 /*!
2763  * \brief Return a component corresponding to parameter
2764   * \param U - parameter along a horizontal size
2765   * \param localU - parameter along a horizontal size of a component
2766   * \retval TSideFace* - found component
2767  */
2768 //================================================================================
2769
2770 StdMeshers_PrismAsBlock::TSideFace*
2771 StdMeshers_PrismAsBlock::TSideFace::GetComponent(const double U,double & localU) const
2772 {
2773   localU = U;
2774   if ( myComponents.empty() )
2775     return const_cast<TSideFace*>( this );
2776
2777   int i;
2778   for ( i = 0; i < myComponents.size(); ++i )
2779     if ( U < myParams[ i ].second )
2780       break;
2781   if ( i >= myComponents.size() )
2782     i = myComponents.size() - 1;
2783
2784   double f = myParams[ i ].first, l = myParams[ i ].second;
2785   localU = ( U - f ) / ( l - f );
2786   return myComponents[ i ];
2787 }
2788
2789 //================================================================================
2790 /*!
2791  * \brief Find node columns for a parameter
2792   * \param U - parameter along a horizontal edge
2793   * \param col1 - the 1st found column
2794   * \param col2 - the 2nd found column
2795   * \retval r - normalized position of U between the found columns
2796  */
2797 //================================================================================
2798
2799 double StdMeshers_PrismAsBlock::TSideFace::GetColumns(const double      U,
2800                                                       TParam2ColumnIt & col1,
2801                                                       TParam2ColumnIt & col2) const
2802 {
2803   double u = U, r = 0;
2804   if ( !myComponents.empty() ) {
2805     TSideFace * comp = GetComponent(U,u);
2806     return comp->GetColumns( u, col1, col2 );
2807   }
2808
2809   if ( !myIsForward )
2810     u = 1 - u;
2811   double f = myParams[0].first, l = myParams[0].second;
2812   u = f + u * ( l - f );
2813
2814   col1 = col2 = getColumn( myParamToColumnMap, u );
2815   if ( ++col2 == myParamToColumnMap->end() ) {
2816     --col2;
2817     r = 0.5;
2818   }
2819   else {
2820     double uf = col1->first;
2821     double ul = col2->first;
2822     r = ( u - uf ) / ( ul - uf );
2823   }
2824   return r;
2825 }
2826
2827 //================================================================================
2828 /*!
2829  * \brief Return coordinates by normalized params
2830   * \param U - horizontal param
2831   * \param V - vertical param
2832   * \retval gp_Pnt - result point
2833  */
2834 //================================================================================
2835
2836 gp_Pnt StdMeshers_PrismAsBlock::TSideFace::Value(const Standard_Real U,
2837                                                  const Standard_Real V) const
2838 {
2839   if ( !myComponents.empty() ) {
2840     double u;
2841     TSideFace * comp = GetComponent(U,u);
2842     return comp->Value( u, V );
2843   }
2844
2845   TParam2ColumnIt u_col1, u_col2;
2846   double vR, hR = GetColumns( U, u_col1, u_col2 );
2847
2848   const SMDS_MeshNode* nn[4];
2849
2850   // BEGIN issue 0020680: Bad cell created by Radial prism in center of torus
2851   // Workaround for a wrongly located point returned by mySurface.Value() for
2852   // UV located near boundary of BSpline surface.
2853   // To bypass the problem, we take point from 3D curve of EDGE.
2854   // It solves pb of the bloc_fiss_new.py
2855   const double tol = 1e-3;
2856   if ( V < tol || V+tol >= 1. )
2857   {
2858     nn[0] = V < tol ? u_col1->second.front() : u_col1->second.back();
2859     nn[2] = V < tol ? u_col2->second.front() : u_col2->second.back();
2860     TopoDS_Edge edge;
2861     if ( V < tol )
2862     {
2863       edge = myBaseEdge;
2864     }
2865     else
2866     {
2867       TopoDS_Shape s = myHelper->GetSubShapeByNode( nn[0], myHelper->GetMeshDS() );
2868       if ( s.ShapeType() != TopAbs_EDGE )
2869         s = myHelper->GetSubShapeByNode( nn[2], myHelper->GetMeshDS() );
2870       if ( s.ShapeType() == TopAbs_EDGE )
2871         edge = TopoDS::Edge( s );
2872     }
2873     if ( !edge.IsNull() )
2874     {
2875       double u1 = myHelper->GetNodeU( edge, nn[0] );
2876       double u3 = myHelper->GetNodeU( edge, nn[2] );
2877       double u = u1 * ( 1 - hR ) + u3 * hR;
2878       TopLoc_Location loc; double f,l;
2879       Handle(Geom_Curve) curve = BRep_Tool::Curve( edge,loc,f,l );
2880       return curve->Value( u ).Transformed( loc );
2881     }
2882   }
2883   // END issue 0020680: Bad cell created by Radial prism in center of torus
2884
2885   vR = getRAndNodes( & u_col1->second, V, nn[0], nn[1] );
2886   vR = getRAndNodes( & u_col2->second, V, nn[2], nn[3] );
2887
2888   if ( !myShapeID2Surf.empty() ) // side is vertically composite
2889   {
2890     // find a FACE on which the 4 nodes lie
2891     TSideFace* me = (TSideFace*) this;
2892     int notFaceID1 = 0, notFaceID2 = 0;
2893     for ( int i = 0; i < 4; ++i )
2894       if ( nn[i]->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE ) // node on FACE
2895       {
2896         me->mySurface = me->myShapeID2Surf[ nn[i]->getshapeId() ];
2897         notFaceID2 = 0;
2898         break;
2899       }
2900       else if ( notFaceID1 == 0 ) // node on EDGE or VERTEX
2901       {
2902         me->mySurface  = me->myShapeID2Surf[ nn[i]->getshapeId() ];
2903         notFaceID1 = nn[i]->getshapeId();
2904       }
2905       else if ( notFaceID1 != nn[i]->getshapeId() ) // node on other EDGE or VERTEX
2906       {
2907         if ( mySurface != me->myShapeID2Surf[ nn[i]->getshapeId() ])
2908           notFaceID2 = nn[i]->getshapeId();
2909       }
2910     if ( notFaceID2 ) // no nodes of FACE and nodes are on different FACEs
2911     {
2912       SMESHDS_Mesh* meshDS = myHelper->GetMeshDS();
2913       TopoDS_Shape face = myHelper->GetCommonAncestor( meshDS->IndexToShape( notFaceID1 ),
2914                                                        meshDS->IndexToShape( notFaceID2 ),
2915                                                        *myHelper->GetMesh(),
2916                                                        TopAbs_FACE );
2917       if ( face.IsNull() ) 
2918         throw SALOME_Exception("StdMeshers_PrismAsBlock::TSideFace::Value() face.IsNull()");
2919       int faceID = meshDS->ShapeToIndex( face );
2920       me->mySurface = me->myShapeID2Surf[ faceID ];
2921       if ( !mySurface )
2922         throw SALOME_Exception("StdMeshers_PrismAsBlock::TSideFace::Value() !mySurface");
2923     }
2924   }
2925   
2926   gp_XY uv1 = myHelper->GetNodeUV( mySurface->Face(), nn[0], nn[2]);
2927   gp_XY uv2 = myHelper->GetNodeUV( mySurface->Face(), nn[1], nn[3]);
2928   gp_XY uv12 = uv1 * ( 1 - vR ) + uv2 * vR;
2929
2930   gp_XY uv3 = myHelper->GetNodeUV( mySurface->Face(), nn[2], nn[0]);
2931   gp_XY uv4 = myHelper->GetNodeUV( mySurface->Face(), nn[3], nn[1]);
2932   gp_XY uv34 = uv3 * ( 1 - vR ) + uv4 * vR;
2933
2934   gp_XY uv = uv12 * ( 1 - hR ) + uv34 * hR;
2935
2936   gp_Pnt p = mySurface->Value( uv.X(), uv.Y() );
2937   return p;
2938 }
2939
2940
2941 //================================================================================
2942 /*!
2943  * \brief Return boundary edge
2944   * \param edge - edge index
2945   * \retval TopoDS_Edge - found edge
2946  */
2947 //================================================================================
2948
2949 TopoDS_Edge StdMeshers_PrismAsBlock::TSideFace::GetEdge(const int iEdge) const
2950 {
2951   if ( !myComponents.empty() ) {
2952     switch ( iEdge ) {
2953     case V0_EDGE : return myComponents.front()->GetEdge( iEdge );
2954     case V1_EDGE : return myComponents.back() ->GetEdge( iEdge );
2955     default: return TopoDS_Edge();
2956     }
2957   }
2958   TopoDS_Shape edge;
2959   const SMDS_MeshNode* node = 0;
2960   SMESHDS_Mesh * meshDS = myHelper->GetMesh()->GetMeshDS();
2961   TNodeColumn* column;
2962
2963   switch ( iEdge ) {
2964   case TOP_EDGE:
2965   case BOTTOM_EDGE:
2966     column = & (( ++myParamToColumnMap->begin())->second );
2967     node = ( iEdge == TOP_EDGE ) ? column->back() : column->front();
2968     edge = myHelper->GetSubShapeByNode ( node, meshDS );
2969     if ( edge.ShapeType() == TopAbs_VERTEX ) {
2970       column = & ( myParamToColumnMap->begin()->second );
2971       node = ( iEdge == TOP_EDGE ) ? column->back() : column->front();
2972     }
2973     break;
2974   case V0_EDGE:
2975   case V1_EDGE: {
2976     bool back = ( iEdge == V1_EDGE );
2977     if ( !myIsForward ) back = !back;
2978     if ( back )
2979       column = & ( myParamToColumnMap->rbegin()->second );
2980     else
2981       column = & ( myParamToColumnMap->begin()->second );
2982     if ( column->size() > 0 )
2983       edge = myHelper->GetSubShapeByNode( (*column)[ 1 ], meshDS );
2984     if ( edge.IsNull() || edge.ShapeType() == TopAbs_VERTEX )
2985       node = column->front();
2986     break;
2987   }
2988   default:;
2989   }
2990   if ( !edge.IsNull() && edge.ShapeType() == TopAbs_EDGE )
2991     return TopoDS::Edge( edge );
2992
2993   // find edge by 2 vertices
2994   TopoDS_Shape V1 = edge;
2995   TopoDS_Shape V2 = myHelper->GetSubShapeByNode( node, meshDS );
2996   if ( !V2.IsNull() && V2.ShapeType() == TopAbs_VERTEX && !V2.IsSame( V1 ))
2997   {
2998     TopoDS_Shape ancestor = myHelper->GetCommonAncestor( V1, V2, *myHelper->GetMesh(), TopAbs_EDGE);
2999     if ( !ancestor.IsNull() )
3000       return TopoDS::Edge( ancestor );
3001   }
3002   return TopoDS_Edge();
3003 }
3004
3005 //================================================================================
3006 /*!
3007  * \brief Fill block sub-shapes
3008   * \param shapeMap - map to fill in
3009   * \retval int - nb inserted sub-shapes
3010  */
3011 //================================================================================
3012
3013 int StdMeshers_PrismAsBlock::TSideFace::InsertSubShapes(TBlockShapes& shapeMap) const
3014 {
3015   int nbInserted = 0;
3016
3017   // Insert edges
3018   vector< int > edgeIdVec;
3019   SMESH_Block::GetFaceEdgesIDs( myID, edgeIdVec );
3020
3021   for ( int i = BOTTOM_EDGE; i <=V1_EDGE ; ++i ) {
3022     TopoDS_Edge e = GetEdge( i );
3023     if ( !e.IsNull() ) {
3024       nbInserted += SMESH_Block::Insert( e, edgeIdVec[ i ], shapeMap);
3025     }
3026   }
3027
3028   // Insert corner vertices
3029
3030   TParam2ColumnIt col1, col2 ;
3031   vector< int > vertIdVec;
3032
3033   // from V0 column
3034   SMESH_Block::GetEdgeVertexIDs( edgeIdVec[ V0_EDGE ], vertIdVec);
3035   GetColumns(0, col1, col2 );
3036   const SMDS_MeshNode* node0 = col1->second.front();
3037   const SMDS_MeshNode* node1 = col1->second.back();
3038   TopoDS_Shape v0 = myHelper->GetSubShapeByNode( node0, myHelper->GetMeshDS());
3039   TopoDS_Shape v1 = myHelper->GetSubShapeByNode( node1, myHelper->GetMeshDS());
3040   if ( v0.ShapeType() == TopAbs_VERTEX ) {
3041     nbInserted += SMESH_Block::Insert( v0, vertIdVec[ 0 ], shapeMap);
3042   }
3043   if ( v1.ShapeType() == TopAbs_VERTEX ) {
3044     nbInserted += SMESH_Block::Insert( v1, vertIdVec[ 1 ], shapeMap);
3045   }
3046   
3047   // from V1 column
3048   SMESH_Block::GetEdgeVertexIDs( edgeIdVec[ V1_EDGE ], vertIdVec);
3049   GetColumns(1, col1, col2 );
3050   node0 = col2->second.front();
3051   node1 = col2->second.back();
3052   v0 = myHelper->GetSubShapeByNode( node0, myHelper->GetMeshDS());
3053   v1 = myHelper->GetSubShapeByNode( node1, myHelper->GetMeshDS());
3054   if ( v0.ShapeType() == TopAbs_VERTEX ) {
3055     nbInserted += SMESH_Block::Insert( v0, vertIdVec[ 0 ], shapeMap);
3056   }
3057   if ( v1.ShapeType() == TopAbs_VERTEX ) {
3058     nbInserted += SMESH_Block::Insert( v1, vertIdVec[ 1 ], shapeMap);
3059   }
3060
3061 //   TopoDS_Vertex V0, V1, Vcom;
3062 //   TopExp::Vertices( myBaseEdge, V0, V1, true );
3063 //   if ( !myIsForward ) std::swap( V0, V1 );
3064
3065 //   // bottom vertex IDs
3066 //   SMESH_Block::GetEdgeVertexIDs( edgeIdVec[ _u0 ], vertIdVec);
3067 //   SMESH_Block::Insert( V0, vertIdVec[ 0 ], shapeMap);
3068 //   SMESH_Block::Insert( V1, vertIdVec[ 1 ], shapeMap);
3069
3070 //   TopoDS_Edge sideEdge = GetEdge( V0_EDGE );
3071 //   if ( sideEdge.IsNull() || !TopExp::CommonVertex( botEdge, sideEdge, Vcom ))
3072 //     return false;
3073
3074 //   // insert one side edge
3075 //   int edgeID;
3076 //   if ( Vcom.IsSame( V0 )) edgeID = edgeIdVec[ _v0 ];
3077 //   else                    edgeID = edgeIdVec[ _v1 ];
3078 //   SMESH_Block::Insert( sideEdge, edgeID, shapeMap);
3079
3080 //   // top vertex of the side edge
3081 //   SMESH_Block::GetEdgeVertexIDs( edgeID, vertIdVec);
3082 //   TopoDS_Vertex Vtop = TopExp::FirstVertex( sideEdge );
3083 //   if ( Vcom.IsSame( Vtop ))
3084 //     Vtop = TopExp::LastVertex( sideEdge );
3085 //   SMESH_Block::Insert( Vtop, vertIdVec[ 1 ], shapeMap);
3086
3087 //   // other side edge
3088 //   sideEdge = GetEdge( V1_EDGE );
3089 //   if ( sideEdge.IsNull() )
3090 //     return false;
3091 //   if ( edgeID = edgeIdVec[ _v1 ]) edgeID = edgeIdVec[ _v0 ];
3092 //   else                            edgeID = edgeIdVec[ _v1 ];
3093 //   SMESH_Block::Insert( sideEdge, edgeID, shapeMap);
3094   
3095 //   // top edge
3096 //   TopoDS_Edge topEdge = GetEdge( TOP_EDGE );
3097 //   SMESH_Block::Insert( topEdge, edgeIdVec[ _u1 ], shapeMap);
3098
3099 //   // top vertex of the other side edge
3100 //   if ( !TopExp::CommonVertex( topEdge, sideEdge, Vcom ))
3101 //     return false;
3102 //   SMESH_Block::GetEdgeVertexIDs( edgeID, vertIdVec );
3103 //   SMESH_Block::Insert( Vcom, vertIdVec[ 1 ], shapeMap);
3104
3105   return nbInserted;
3106 }
3107
3108 //================================================================================
3109 /*!
3110  * \brief Dump ids of nodes of sides
3111  */
3112 //================================================================================
3113
3114 void StdMeshers_PrismAsBlock::TSideFace::dumpNodes(int nbNodes) const
3115 {
3116 #ifdef _DEBUG_
3117   cout << endl << "NODES OF FACE "; SMESH_Block::DumpShapeID( myID, cout ) << endl;
3118   THorizontalEdgeAdaptor* hSize0 = (THorizontalEdgeAdaptor*) HorizCurve(0);
3119   cout << "Horiz side 0: "; hSize0->dumpNodes(nbNodes); cout << endl;
3120   THorizontalEdgeAdaptor* hSize1 = (THorizontalEdgeAdaptor*) HorizCurve(1);
3121   cout << "Horiz side 1: "; hSize1->dumpNodes(nbNodes); cout << endl;
3122   TVerticalEdgeAdaptor* vSide0 = (TVerticalEdgeAdaptor*) VertiCurve(0);
3123   cout << "Verti side 0: "; vSide0->dumpNodes(nbNodes); cout << endl;
3124   TVerticalEdgeAdaptor* vSide1 = (TVerticalEdgeAdaptor*) VertiCurve(1);
3125   cout << "Verti side 1: "; vSide1->dumpNodes(nbNodes); cout << endl;
3126   delete hSize0; delete hSize1; delete vSide0; delete vSide1;
3127 #endif
3128 }
3129
3130 //================================================================================
3131 /*!
3132  * \brief Creates TVerticalEdgeAdaptor 
3133   * \param columnsMap - node column map
3134   * \param parameter - normalized parameter
3135  */
3136 //================================================================================
3137
3138 StdMeshers_PrismAsBlock::TVerticalEdgeAdaptor::
3139 TVerticalEdgeAdaptor( const TParam2ColumnMap* columnsMap, const double parameter)
3140 {
3141   myNodeColumn = & getColumn( columnsMap, parameter )->second;
3142 }
3143
3144 //================================================================================
3145 /*!
3146  * \brief Return coordinates for the given normalized parameter
3147   * \param U - normalized parameter
3148   * \retval gp_Pnt - coordinates
3149  */
3150 //================================================================================
3151
3152 gp_Pnt StdMeshers_PrismAsBlock::TVerticalEdgeAdaptor::Value(const Standard_Real U) const
3153 {
3154   const SMDS_MeshNode* n1;
3155   const SMDS_MeshNode* n2;
3156   double r = getRAndNodes( myNodeColumn, U, n1, n2 );
3157   return gpXYZ(n1) * ( 1 - r ) + gpXYZ(n2) * r;
3158 }
3159
3160 //================================================================================
3161 /*!
3162  * \brief Dump ids of nodes
3163  */
3164 //================================================================================
3165
3166 void StdMeshers_PrismAsBlock::TVerticalEdgeAdaptor::dumpNodes(int nbNodes) const
3167 {
3168 #ifdef _DEBUG_
3169   for ( int i = 0; i < nbNodes && i < myNodeColumn->size(); ++i )
3170     cout << (*myNodeColumn)[i]->GetID() << " ";
3171   if ( nbNodes < myNodeColumn->size() )
3172     cout << myNodeColumn->back()->GetID();
3173 #endif
3174 }
3175
3176 //================================================================================
3177 /*!
3178  * \brief Return coordinates for the given normalized parameter
3179   * \param U - normalized parameter
3180   * \retval gp_Pnt - coordinates
3181  */
3182 //================================================================================
3183
3184 gp_Pnt StdMeshers_PrismAsBlock::THorizontalEdgeAdaptor::Value(const Standard_Real U) const
3185 {
3186   return mySide->TSideFace::Value( U, myV );
3187 }
3188
3189 //================================================================================
3190 /*!
3191  * \brief Dump ids of <nbNodes> first nodes and the last one
3192  */
3193 //================================================================================
3194
3195 void StdMeshers_PrismAsBlock::THorizontalEdgeAdaptor::dumpNodes(int nbNodes) const
3196 {
3197 #ifdef _DEBUG_
3198   // Not bedugged code. Last node is sometimes incorrect
3199   const TSideFace* side = mySide;
3200   double u = 0;
3201   if ( mySide->IsComplex() )
3202     side = mySide->GetComponent(0,u);
3203
3204   TParam2ColumnIt col, col2;
3205   TParam2ColumnMap* u2cols = side->GetColumns();
3206   side->GetColumns( u , col, col2 );
3207   
3208   int j, i = myV ? mySide->ColumnHeight()-1 : 0;
3209
3210   const SMDS_MeshNode* n = 0;
3211   const SMDS_MeshNode* lastN
3212     = side->IsForward() ? u2cols->rbegin()->second[ i ] : u2cols->begin()->second[ i ];
3213   for ( j = 0; j < nbNodes && n != lastN; ++j )
3214   {
3215     n = col->second[ i ];
3216     cout << n->GetID() << " ";
3217     if ( side->IsForward() )
3218       ++col;
3219     else
3220       --col;
3221   }
3222
3223   // last node
3224   u = 1;
3225   if ( mySide->IsComplex() )
3226     side = mySide->GetComponent(1,u);
3227
3228   side->GetColumns( u , col, col2 );
3229   if ( n != col->second[ i ] )
3230     cout << col->second[ i ]->GetID();
3231 #endif
3232 }
3233 //================================================================================
3234 /*!
3235  * \brief Return UV on pcurve for the given normalized parameter
3236   * \param U - normalized parameter
3237   * \retval gp_Pnt - coordinates
3238  */
3239 //================================================================================
3240
3241 gp_Pnt2d StdMeshers_PrismAsBlock::TPCurveOnHorFaceAdaptor::Value(const Standard_Real U) const
3242 {
3243   TParam2ColumnIt u_col1, u_col2;
3244   double r = mySide->GetColumns( U, u_col1, u_col2 );
3245   gp_XY uv1 = mySide->GetNodeUV( myFace, u_col1->second[ myZ ]);
3246   gp_XY uv2 = mySide->GetNodeUV( myFace, u_col2->second[ myZ ]);
3247   return uv1 * ( 1 - r ) + uv2 * r;
3248 }