Salome HOME
bbfd6c462a538b898ef1c1badd59eb5afbcfb993
[modules/smesh.git] / src / StdMeshers / StdMeshers_Prism_3D.cxx
1 // Copyright (C) 2007-2014  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, or (at your option) any later version.
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 #include <limits>
64
65 using namespace std;
66
67 #define RETURN_BAD_RESULT(msg) { MESSAGE(")-: Error: " << msg); return false; }
68 #define gpXYZ(n) gp_XYZ(n->X(),n->Y(),n->Z())
69 #define SHOWYXZ(msg, xyz) // {\
70 // gp_Pnt p (xyz); \
71 // cout << msg << " ("<< p.X() << "; " <<p.Y() << "; " <<p.Z() << ") " <<endl;\
72 // }
73 #ifdef _DEBUG_
74 #define DBGOUT(msg) //cout << msg << endl;
75 #else
76 #define DBGOUT(msg)
77 #endif
78
79 namespace TAssocTool = StdMeshers_ProjectionUtils;
80
81 typedef SMESH_Comment TCom;
82
83 enum { ID_BOT_FACE = SMESH_Block::ID_Fxy0,
84        ID_TOP_FACE = SMESH_Block::ID_Fxy1,
85        BOTTOM_EDGE = 0, TOP_EDGE, V0_EDGE, V1_EDGE, // edge IDs in face
86        NB_WALL_FACES = 4 }; //
87
88 namespace {
89
90   //=======================================================================
91   /*!
92    * \brief Quadrangle algorithm
93    */
94   struct TQuadrangleAlgo : public StdMeshers_Quadrangle_2D
95   {
96     TQuadrangleAlgo(int studyId, SMESH_Gen* gen)
97       : StdMeshers_Quadrangle_2D( gen->GetANewId(), studyId, gen)
98     {
99     }
100     static StdMeshers_Quadrangle_2D* instance( SMESH_Algo*         fatherAlgo,
101                                                SMESH_MesherHelper* helper=0)
102     {
103       static TQuadrangleAlgo* algo = new TQuadrangleAlgo( fatherAlgo->GetStudyId(),
104                                                           fatherAlgo->GetGen() );
105       if ( helper &&
106            algo->myProxyMesh &&
107            algo->myProxyMesh->GetMesh() != helper->GetMesh() )
108         algo->myProxyMesh.reset( new SMESH_ProxyMesh( *helper->GetMesh() ));
109
110       algo->myQuadList.clear();
111
112       if ( helper )
113         algo->_quadraticMesh = helper->GetIsQuadratic();
114
115       return algo;
116     }
117   };
118   //=======================================================================
119   /*!
120    * \brief Algorithm projecting 1D mesh
121    */
122   struct TProjction1dAlgo : public StdMeshers_Projection_1D
123   {
124     StdMeshers_ProjectionSource1D myHyp;
125
126     TProjction1dAlgo(int studyId, SMESH_Gen* gen)
127       : StdMeshers_Projection_1D( gen->GetANewId(), studyId, gen),
128         myHyp( gen->GetANewId(), studyId, gen)
129     {
130       StdMeshers_Projection_1D::_sourceHypo = & myHyp;
131     }
132     static TProjction1dAlgo* instance( SMESH_Algo* fatherAlgo )
133     {
134       static TProjction1dAlgo* algo = new TProjction1dAlgo( fatherAlgo->GetStudyId(),
135                                                             fatherAlgo->GetGen() );
136       return algo;
137     }
138   };
139   //=======================================================================
140   /*!
141    * \brief Algorithm projecting 2D mesh
142    */
143   struct TProjction2dAlgo : public StdMeshers_Projection_1D2D
144   {
145     StdMeshers_ProjectionSource2D myHyp;
146
147     TProjction2dAlgo(int studyId, SMESH_Gen* gen)
148       : StdMeshers_Projection_1D2D( gen->GetANewId(), studyId, gen),
149         myHyp( gen->GetANewId(), studyId, gen)
150     {
151       StdMeshers_Projection_2D::_sourceHypo = & myHyp;
152     }
153     static TProjction2dAlgo* instance( SMESH_Algo* fatherAlgo )
154     {
155       static TProjction2dAlgo* algo = new TProjction2dAlgo( fatherAlgo->GetStudyId(),
156                                                             fatherAlgo->GetGen() );
157       return algo;
158     }
159   };
160   //=======================================================================
161   /*!
162    * \brief Returns already computed EDGEs
163    */
164   void getPrecomputedEdges( SMESH_MesherHelper&    theHelper,
165                             const TopoDS_Shape&    theShape,
166                             vector< TopoDS_Edge >& theEdges)
167   {
168     theEdges.clear();
169
170     SMESHDS_Mesh* meshDS = theHelper.GetMeshDS();
171     SMESHDS_SubMesh* sm;
172
173     TopTools_IndexedMapOfShape edges;
174     TopExp::MapShapes( theShape, TopAbs_EDGE, edges );
175     for ( int iE = 1; iE <= edges.Extent(); ++iE )
176     {
177       const TopoDS_Shape edge = edges( iE );
178       if (( ! ( sm = meshDS->MeshElements( edge ))) ||
179           ( sm->NbElements() == 0 ))
180         continue;
181
182       // there must not be FACEs meshed with triangles and sharing a computed EDGE
183       // as the precomputed EDGEs are used for propagation other to 'vertical' EDGEs
184       bool faceFound = false;
185       PShapeIteratorPtr faceIt =
186         theHelper.GetAncestors( edge, *theHelper.GetMesh(), TopAbs_FACE );
187       while ( const TopoDS_Shape* face = faceIt->next() )
188
189         if (( sm = meshDS->MeshElements( *face )) &&
190             ( sm->NbElements() > 0 ) &&
191             ( !theHelper.IsSameElemGeometry( sm, SMDSGeom_QUADRANGLE ) ))
192         {
193           faceFound = true;
194           break;
195         }
196       if ( !faceFound )
197         theEdges.push_back( TopoDS::Edge( edge ));
198     }
199   }
200
201   //================================================================================
202   /*!
203    * \brief Make \a botE be the BOTTOM_SIDE of \a quad.
204    *        Return false if the BOTTOM_SIDE is composite
205    */
206   //================================================================================
207
208   bool setBottomEdge( const TopoDS_Edge&   botE,
209                       FaceQuadStruct::Ptr& quad,
210                       const TopoDS_Shape&  face)
211   {
212     quad->side[ QUAD_TOP_SIDE  ].grid->Reverse();
213     quad->side[ QUAD_LEFT_SIDE ].grid->Reverse();
214     int edgeIndex = 0;
215     bool isComposite = false;
216     for ( size_t i = 0; i < quad->side.size(); ++i )
217     {
218       StdMeshers_FaceSidePtr quadSide = quad->side[i];
219       for ( int iE = 0; iE < quadSide->NbEdges(); ++iE )
220         if ( botE.IsSame( quadSide->Edge( iE )))
221         {
222           if ( quadSide->NbEdges() > 1 )
223             isComposite = true; //return false;
224           edgeIndex = i;
225           i = quad->side.size(); // to quit from the outer loop
226           break;
227         }
228     }
229     if ( edgeIndex != QUAD_BOTTOM_SIDE )
230       quad->shift( quad->side.size() - edgeIndex, /*keepUnitOri=*/false );
231
232     quad->face = TopoDS::Face( face );
233
234     return !isComposite;
235   }
236
237   //================================================================================
238   /*!
239    * \brief Return iterator pointing to node column for the given parameter
240    * \param columnsMap - node column map
241    * \param parameter - parameter
242    * \retval TParam2ColumnMap::iterator - result
243    *
244    * it returns closest left column
245    */
246   //================================================================================
247
248   TParam2ColumnIt getColumn( const TParam2ColumnMap* columnsMap,
249                              const double            parameter )
250   {
251     TParam2ColumnIt u_col = columnsMap->upper_bound( parameter );
252     if ( u_col != columnsMap->begin() )
253       --u_col;
254     return u_col; // return left column
255   }
256
257   //================================================================================
258   /*!
259    * \brief Return nodes around given parameter and a ratio
260    * \param column - node column
261    * \param param - parameter
262    * \param node1 - lower node
263    * \param node2 - upper node
264    * \retval double - ratio
265    */
266   //================================================================================
267
268   double getRAndNodes( const TNodeColumn*     column,
269                        const double           param,
270                        const SMDS_MeshNode* & node1,
271                        const SMDS_MeshNode* & node2)
272   {
273     if ( param >= 1.0 || column->size() == 1) {
274       node1 = node2 = column->back();
275       return 0;
276     }
277
278     int i = int( param * ( column->size() - 1 ));
279     double u0 = double( i )/ double( column->size() - 1 );
280     double r = ( param - u0 ) * ( column->size() - 1 );
281
282     node1 = (*column)[ i ];
283     node2 = (*column)[ i + 1];
284     return r;
285   }
286
287   //================================================================================
288   /*!
289    * \brief Compute boundary parameters of face parts
290     * \param nbParts - nb of parts to split columns into
291     * \param columnsMap - node columns of the face to split
292     * \param params - computed parameters
293    */
294   //================================================================================
295
296   void splitParams( const int               nbParts,
297                     const TParam2ColumnMap* columnsMap,
298                     vector< double > &      params)
299   {
300     params.clear();
301     params.reserve( nbParts + 1 );
302     TParam2ColumnIt last_par_col = --columnsMap->end();
303     double par = columnsMap->begin()->first; // 0.
304     double parLast = last_par_col->first;
305     params.push_back( par );
306     for ( int i = 0; i < nbParts - 1; ++ i )
307     {
308       double partSize = ( parLast - par ) / double ( nbParts - i );
309       TParam2ColumnIt par_col = getColumn( columnsMap, par + partSize );
310       if ( par_col->first == par ) {
311         ++par_col;
312         if ( par_col == last_par_col ) {
313           while ( i < nbParts - 1 )
314             params.push_back( par + partSize * i++ );
315           break;
316         }
317       }
318       par = par_col->first;
319       params.push_back( par );
320     }
321     params.push_back( parLast ); // 1.
322   }
323
324   //================================================================================
325   /*!
326    * \brief Return coordinate system for z-th layer of nodes
327    */
328   //================================================================================
329
330   gp_Ax2 getLayerCoordSys(const int                           z,
331                           const vector< const TNodeColumn* >& columns,
332                           int&                                xColumn)
333   {
334     // gravity center of a layer
335     gp_XYZ O(0,0,0);
336     int vertexCol = -1;
337     for ( int i = 0; i < columns.size(); ++i )
338     {
339       O += gpXYZ( (*columns[ i ])[ z ]);
340       if ( vertexCol < 0 &&
341            columns[ i ]->front()->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX )
342         vertexCol = i;
343     }
344     O /= columns.size();
345
346     // Z axis
347     gp_Vec Z(0,0,0);
348     int iPrev = columns.size()-1;
349     for ( int i = 0; i < columns.size(); ++i )
350     {
351       gp_Vec v1( O, gpXYZ( (*columns[ iPrev ])[ z ]));
352       gp_Vec v2( O, gpXYZ( (*columns[ i ]    )[ z ]));
353       Z += v1 ^ v2;
354       iPrev = i;
355     }
356
357     if ( vertexCol >= 0 )
358     {
359       O = gpXYZ( (*columns[ vertexCol ])[ z ]);
360     }
361     if ( xColumn < 0 || xColumn >= columns.size() )
362     {
363       // select a column for X dir
364       double maxDist = 0;
365       for ( int i = 0; i < columns.size(); ++i )
366       {
367         double dist = ( O - gpXYZ((*columns[ i ])[ z ])).SquareModulus();
368         if ( dist > maxDist )
369         {
370           xColumn = i;
371           maxDist = dist;
372         }
373       }
374     }
375
376     // X axis
377     gp_Vec X( O, gpXYZ( (*columns[ xColumn ])[ z ]));
378
379     return gp_Ax2( O, Z, X);
380   }
381
382   //================================================================================
383   /*!
384    * \brief Removes submeshes that are or can be meshed with regular grid from given list
385    *  \retval int - nb of removed submeshes
386    */
387   //================================================================================
388
389   int removeQuasiQuads(list< SMESH_subMesh* >&   notQuadSubMesh,
390                        SMESH_MesherHelper*       helper,
391                        StdMeshers_Quadrangle_2D* quadAlgo)
392   {
393     int nbRemoved = 0;
394     //SMESHDS_Mesh* mesh = notQuadSubMesh.front()->GetFather()->GetMeshDS();
395     list< SMESH_subMesh* >::iterator smIt = notQuadSubMesh.begin();
396     while ( smIt != notQuadSubMesh.end() )
397     {
398       SMESH_subMesh* faceSm = *smIt;
399       SMESHDS_SubMesh* faceSmDS = faceSm->GetSubMeshDS();
400       int nbQuads = faceSmDS ? faceSmDS->NbElements() : 0;
401       bool toRemove;
402       if ( nbQuads > 0 )
403         toRemove = helper->IsStructured( faceSm );
404       else
405         toRemove = quadAlgo->CheckNbEdges( *helper->GetMesh(),
406                                            faceSm->GetSubShape() );
407       nbRemoved += toRemove;
408       if ( toRemove )
409         smIt = notQuadSubMesh.erase( smIt );
410       else
411         ++smIt;
412     }
413
414     return nbRemoved;
415   }
416
417   //================================================================================
418   /*!
419    * \brief Return and angle between two EDGEs
420    *  \return double - the angle normalized so that
421    * >~ 0  -> 2.0
422    *  PI/2 -> 1.0
423    *  PI   -> 0.0
424    * -PI/2 -> -1.0
425    * <~ 0  -> -2.0
426    */
427   //================================================================================
428
429   double normAngle(const TopoDS_Edge & E1, const TopoDS_Edge & E2, const TopoDS_Face & F)
430   {
431     return SMESH_MesherHelper::GetAngle( E1, E2, F ) / ( 0.5 * M_PI );
432   }
433
434   //================================================================================
435   /*!
436    * Consider continuous straight EDGES as one side - mark them to unite
437    */
438   //================================================================================
439
440   int countNbSides( const Prism_3D::TPrismTopo & thePrism,
441                     vector<int> &                nbUnitePerEdge,
442                     vector< double > &           edgeLength)
443   {
444     int nbEdges = thePrism.myNbEdgesInWires.front();  // nb outer edges
445     int nbSides = nbEdges;
446
447     
448     list< TopoDS_Edge >::const_iterator edgeIt = thePrism.myBottomEdges.begin();
449     std::advance( edgeIt, nbEdges-1 );
450     TopoDS_Edge   prevE = *edgeIt;
451     // bool isPrevStraight = SMESH_Algo::IsStraight( prevE );
452     int           iPrev = nbEdges - 1;
453
454     int iUnite = -1; // the first of united EDGEs
455
456     // analyse angles between EDGEs
457     int nbCorners = 0;
458     vector< bool > isCorner( nbEdges );
459     edgeIt = thePrism.myBottomEdges.begin();
460     for ( int iE = 0; iE < nbEdges; ++iE, ++edgeIt )
461     {
462       const TopoDS_Edge&  curE = *edgeIt;
463       edgeLength[ iE ] = SMESH_Algo::EdgeLength( curE );
464
465       // double normAngle = normAngle( prevE, curE, thePrism.myBottom );
466       // isCorner[ iE ] = false;
467       // if ( normAngle < 2.0 )
468       // {
469       //   if ( normAngle < 0.001 ) // straight or obtuse angle
470       //   {
471       //     // unite EDGEs in order not to put a corner of the unit quadrangle at this VERTEX
472       //     if ( iUnite < 0 )
473       //       iUnite = iPrev;
474       //     nbUnitePerEdge[ iUnite ]++;
475       //     nbUnitePerEdge[ iE ] = -1;
476       //     --nbSides;
477       //   }
478       //   else
479       //   {
480       //     isCorner[ iE ] = true;
481       //     nbCorners++;
482       //     iUnite = -1;
483       //   }
484       // }
485       // prevE = curE;
486     }
487
488     if ( nbCorners > 4 )
489     {
490       // define which of corners to put on a side of the unit quadrangle
491     }
492     // edgeIt = thePrism.myBottomEdges.begin();
493     // for ( int iE = 0; iE < nbEdges; ++iE, ++edgeIt )
494     // {
495     //   const TopoDS_Edge&  curE = *edgeIt;
496     //   edgeLength[ iE ] = SMESH_Algo::EdgeLength( curE );
497
498     //   const bool isCurStraight = SMESH_Algo::IsStraight( curE );
499     //   if ( isPrevStraight && isCurStraight && SMESH_Algo::IsContinuous( prevE, curE ))
500     //   {
501     //     if ( iUnite < 0 )
502     //       iUnite = iPrev;
503     //     nbUnitePerEdge[ iUnite ]++;
504     //     nbUnitePerEdge[ iE ] = -1;
505     //     --nbSides;
506     //   }
507     //   else
508     //   {
509     //     iUnite = -1;
510     //   }
511     //   prevE          = curE;
512     //   isPrevStraight = isCurStraight;
513     //   iPrev = iE;
514     // }
515     
516     return nbSides;
517   }
518
519   void pointsToPython(const std::vector<gp_XYZ>& p)
520   {
521 #ifdef _DEBUG_
522     for ( int i = SMESH_Block::ID_V000; i < p.size(); ++i )
523     {
524       cout << "mesh.AddNode( " << p[i].X() << ", "<< p[i].Y() << ", "<< p[i].Z() << ") # " << i <<" " ;
525       SMESH_Block::DumpShapeID( i, cout ) << endl;
526     }
527 #endif
528   }
529 } // namespace
530
531 //=======================================================================
532 //function : StdMeshers_Prism_3D
533 //purpose  : 
534 //=======================================================================
535
536 StdMeshers_Prism_3D::StdMeshers_Prism_3D(int hypId, int studyId, SMESH_Gen* gen)
537   :SMESH_3D_Algo(hypId, studyId, gen)
538 {
539   _name                    = "Prism_3D";
540   _shapeType               = (1 << TopAbs_SOLID); // 1 bit per shape type
541   _onlyUnaryInput          = false; // accept all SOLIDs at once
542   _requireDiscreteBoundary = false; // mesh FACEs and EDGEs by myself
543   _supportSubmeshes        = true;  // "source" FACE must be meshed by other algo
544   _neededLowerHyps[ 1 ]    = true;  // suppress warning on hiding a global 1D algo
545   _neededLowerHyps[ 2 ]    = true;  // suppress warning on hiding a global 2D algo
546
547   //myProjectTriangles       = false;
548   mySetErrorToSM           = true;  // to pass an error to a sub-mesh of a current solid or not
549 }
550
551 //================================================================================
552 /*!
553  * \brief Destructor
554  */
555 //================================================================================
556
557 StdMeshers_Prism_3D::~StdMeshers_Prism_3D()
558 {}
559
560 //=======================================================================
561 //function : CheckHypothesis
562 //purpose  : 
563 //=======================================================================
564
565 bool StdMeshers_Prism_3D::CheckHypothesis(SMESH_Mesh&                          aMesh,
566                                           const TopoDS_Shape&                  aShape,
567                                           SMESH_Hypothesis::Hypothesis_Status& aStatus)
568 {
569   // Check shape geometry
570 /*  PAL16229
571   aStatus = SMESH_Hypothesis::HYP_BAD_GEOMETRY;
572
573   // find not quadrangle faces
574   list< TopoDS_Shape > notQuadFaces;
575   int nbEdge, nbWire, nbFace = 0;
576   TopExp_Explorer exp( aShape, TopAbs_FACE );
577   for ( ; exp.More(); exp.Next() ) {
578     ++nbFace;
579     const TopoDS_Shape& face = exp.Current();
580     nbEdge = TAssocTool::Count( face, TopAbs_EDGE, 0 );
581     nbWire = TAssocTool::Count( face, TopAbs_WIRE, 0 );
582     if (  nbEdge!= 4 || nbWire!= 1 ) {
583       if ( !notQuadFaces.empty() ) {
584         if ( TAssocTool::Count( notQuadFaces.back(), TopAbs_EDGE, 0 ) != nbEdge ||
585              TAssocTool::Count( notQuadFaces.back(), TopAbs_WIRE, 0 ) != nbWire )
586           RETURN_BAD_RESULT("Different not quad faces");
587       }
588       notQuadFaces.push_back( face );
589     }
590   }
591   if ( !notQuadFaces.empty() )
592   {
593     if ( notQuadFaces.size() != 2 )
594       RETURN_BAD_RESULT("Bad nb not quad faces: " << notQuadFaces.size());
595
596     // check total nb faces
597     nbEdge = TAssocTool::Count( notQuadFaces.back(), TopAbs_EDGE, 0 );
598     if ( nbFace != nbEdge + 2 )
599       RETURN_BAD_RESULT("Bad nb of faces: " << nbFace << " but must be " << nbEdge + 2);
600   }
601 */
602   // no hypothesis
603   aStatus = SMESH_Hypothesis::HYP_OK;
604   return true;
605 }
606
607 //=======================================================================
608 //function : Compute
609 //purpose  : Compute mesh on a COMPOUND of SOLIDs
610 //=======================================================================
611
612 bool StdMeshers_Prism_3D::Compute(SMESH_Mesh& theMesh, const TopoDS_Shape& theShape)
613 {
614   SMESH_MesherHelper helper( theMesh );
615   myHelper = &helper;
616
617   int nbSolids = helper.Count( theShape, TopAbs_SOLID, /*skipSame=*/false );
618   if ( nbSolids < 1 )
619     return true;
620
621   TopTools_IndexedDataMapOfShapeListOfShape faceToSolids;
622   TopExp::MapShapesAndAncestors( theShape, TopAbs_FACE, TopAbs_SOLID, faceToSolids );
623
624   // look for meshed FACEs ("source" FACEs) that must be prism bottoms
625   list< TopoDS_Face > meshedFaces, notQuadMeshedFaces, notQuadFaces;
626   const bool meshHasQuads = ( theMesh.NbQuadrangles() > 0 );
627   //StdMeshers_Quadrangle_2D* quadAlgo = TQuadrangleAlgo::instance( this );
628   for ( int iF = 1; iF <= faceToSolids.Extent(); ++iF )
629   {
630     const TopoDS_Face& face = TopoDS::Face( faceToSolids.FindKey( iF ));
631     SMESH_subMesh*   faceSM = theMesh.GetSubMesh( face );
632     if ( !faceSM->IsEmpty() )
633     {
634       if ( !meshHasQuads ||
635            !helper.IsSameElemGeometry( faceSM->GetSubMeshDS(), SMDSGeom_QUADRANGLE ) ||
636            !helper.IsStructured( faceSM )
637            )
638         notQuadMeshedFaces.push_front( face );
639       else if ( myHelper->Count( face, TopAbs_EDGE, /*ignoreSame=*/false ) != 4 )
640         meshedFaces.push_front( face );
641       else
642         meshedFaces.push_back( face );
643     }
644     // not add not quadrilateral FACE as we can't compute it
645     // else if ( !quadAlgo->CheckNbEdges( theMesh, face ))
646     // // not add not quadrilateral FACE as it can be a prism side
647     // // else if ( myHelper->Count( face, TopAbs_EDGE, /*ignoreSame=*/false ) != 4 )
648     // {
649     //   notQuadFaces.push_back( face );
650     // }
651   }
652   // notQuadFaces are of medium priority, put them before ordinary meshed faces
653   meshedFaces.splice( meshedFaces.begin(), notQuadFaces );
654   // notQuadMeshedFaces are of highest priority, put them before notQuadFaces
655   meshedFaces.splice( meshedFaces.begin(), notQuadMeshedFaces );
656
657   Prism_3D::TPrismTopo prism;
658   myPropagChains = 0;
659
660   if ( nbSolids == 1 )
661   {
662     if ( !meshedFaces.empty() )
663       prism.myBottom = meshedFaces.front();
664     return ( initPrism( prism, TopExp_Explorer( theShape, TopAbs_SOLID ).Current() ) &&
665              compute( prism ));
666   }
667
668   // find propagation chains from already computed EDGEs
669   vector< TopoDS_Edge > computedEdges;
670   getPrecomputedEdges( helper, theShape, computedEdges );
671   myPropagChains = new TopTools_IndexedMapOfShape[ computedEdges.size() + 1 ];
672   SMESHUtils::ArrayDeleter< TopTools_IndexedMapOfShape > pcDel( myPropagChains );
673   for ( size_t i = 0, nb = 0; i < computedEdges.size(); ++i )
674   {
675     StdMeshers_ProjectionUtils::GetPropagationEdge( &theMesh, TopoDS_Edge(),
676                                                     computedEdges[i], myPropagChains + nb );
677     if ( myPropagChains[ nb ].Extent() < 2 ) // an empty map is a termination sign
678       myPropagChains[ nb ].Clear();
679     else
680       nb++;
681   }
682
683   TopTools_MapOfShape meshedSolids;
684   list< Prism_3D::TPrismTopo > meshedPrism;
685   TopTools_ListIteratorOfListOfShape solidIt;
686
687   while ( meshedSolids.Extent() < nbSolids )
688   {
689     if ( _computeCanceled )
690       return toSM( error( SMESH_ComputeError::New(COMPERR_CANCELED)));
691
692     // compute prisms having avident computed source FACE
693     while ( !meshedFaces.empty() )
694     {
695       TopoDS_Face face = meshedFaces.front();
696       meshedFaces.pop_front();
697       TopTools_ListOfShape& solidList = faceToSolids.ChangeFromKey( face );
698       while ( !solidList.IsEmpty() )
699       {
700         TopoDS_Shape solid = solidList.First();
701         solidList.RemoveFirst();
702         if ( meshedSolids.Add( solid ))
703         {
704           prism.Clear();
705           prism.myBottom = face;
706           if ( !initPrism( prism, solid ) ||
707                !compute( prism ))
708             return false;
709
710           SMESHDS_SubMesh* smDS = theMesh.GetMeshDS()->MeshElements( prism.myTop );
711           if ( !myHelper->IsSameElemGeometry( smDS, SMDSGeom_QUADRANGLE ))
712           {
713             meshedFaces.push_front( prism.myTop );
714           }
715           meshedPrism.push_back( prism );
716         }
717       }
718     }
719     if ( meshedSolids.Extent() == nbSolids )
720       break;
721
722     // below in the loop we try to find source FACEs somehow
723
724     // project mesh from source FACEs of computed prisms to
725     // prisms sharing wall FACEs
726     list< Prism_3D::TPrismTopo >::iterator prismIt = meshedPrism.begin();
727     for ( ; prismIt != meshedPrism.end(); ++prismIt )
728     {
729       for ( size_t iW = 0; iW < prismIt->myWallQuads.size(); ++iW )
730       {
731         Prism_3D::TQuadList::iterator wQuad = prismIt->myWallQuads[iW].begin();
732         for ( ; wQuad != prismIt->myWallQuads[iW].end(); ++ wQuad )
733         {
734           const TopoDS_Face& wFace = (*wQuad)->face;
735           TopTools_ListOfShape& solidList = faceToSolids.ChangeFromKey( wFace );
736           solidIt.Initialize( solidList );
737           while ( solidIt.More() )
738           {
739             const TopoDS_Shape& solid = solidIt.Value();
740             if ( meshedSolids.Contains( solid )) {
741               solidList.Remove( solidIt );
742               continue; // already computed prism
743             }
744             // find a source FACE of the SOLID: it's a FACE sharing a bottom EDGE with wFace
745             const TopoDS_Edge& wEdge = (*wQuad)->side[ QUAD_TOP_SIDE ].grid->Edge(0);
746             PShapeIteratorPtr faceIt = myHelper->GetAncestors( wEdge, *myHelper->GetMesh(),
747                                                                TopAbs_FACE);
748             while ( const TopoDS_Shape* f = faceIt->next() )
749             {
750               const TopoDS_Face& candidateF = TopoDS::Face( *f );
751               prism.Clear();
752               prism.myBottom  = candidateF;
753               mySetErrorToSM = false;
754               if ( !myHelper->IsSubShape( candidateF, prismIt->myShape3D ) &&
755                    myHelper->IsSubShape( candidateF, solid ) &&
756                    !myHelper->GetMesh()->GetSubMesh( candidateF )->IsMeshComputed() &&
757                    initPrism( prism, solid ) &&
758                    project2dMesh( prismIt->myBottom, candidateF))
759               {
760                 mySetErrorToSM = true;
761                 if ( !compute( prism ))
762                   return false;
763                 SMESHDS_SubMesh* smDS = theMesh.GetMeshDS()->MeshElements( prism.myTop );
764                 if ( !myHelper->IsSameElemGeometry( smDS, SMDSGeom_QUADRANGLE ))
765                 {
766                   meshedFaces.push_front( prism.myTop );
767                   meshedFaces.push_front( prism.myBottom );
768                 }
769                 meshedPrism.push_back( prism );
770                 meshedSolids.Add( solid );
771               }
772               InitComputeError();
773             }
774             mySetErrorToSM = true;
775             InitComputeError();
776             if ( meshedSolids.Contains( solid ))
777               solidList.Remove( solidIt );
778             else
779               solidIt.Next();
780           }
781         }
782       }
783       if ( !meshedFaces.empty() )
784         break; // to compute prisms with avident sources
785     }
786
787     // find FACEs with local 1D hyps, which has to be computed by now,
788     // or at least any computed FACEs
789     for ( int iF = 1; ( meshedFaces.empty() && iF < faceToSolids.Extent() ); ++iF )
790     {
791       const TopoDS_Face&               face = TopoDS::Face( faceToSolids.FindKey( iF ));
792       const TopTools_ListOfShape& solidList = faceToSolids.FindFromKey( face );
793       if ( solidList.IsEmpty() ) continue;
794       SMESH_subMesh*                 faceSM = theMesh.GetSubMesh( face );
795       if ( !faceSM->IsEmpty() )
796       {
797         meshedFaces.push_back( face ); // lower priority
798       }
799       else
800       {
801         bool allSubMeComputed = true;
802         SMESH_subMeshIteratorPtr smIt = faceSM->getDependsOnIterator(false,true);
803         while ( smIt->more() && allSubMeComputed )
804           allSubMeComputed = smIt->next()->IsMeshComputed();
805         if ( allSubMeComputed )
806         {
807           faceSM->ComputeStateEngine( SMESH_subMesh::COMPUTE );
808           if ( !faceSM->IsEmpty() )
809             meshedFaces.push_front( face ); // higher priority
810           else
811             faceSM->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
812         }
813       }
814     }
815
816
817     // TODO. there are other ways to find out the source FACE:
818     // propagation, topological similarity, ect.
819
820     // simply try to mesh all not meshed SOLIDs
821     if ( meshedFaces.empty() )
822     {
823       for ( TopExp_Explorer solid( theShape, TopAbs_SOLID ); solid.More(); solid.Next() )
824       {
825         mySetErrorToSM = false;
826         prism.Clear();
827         if ( !meshedSolids.Contains( solid.Current() ) &&
828              initPrism( prism, solid.Current() ))
829         {
830           mySetErrorToSM = true;
831           if ( !compute( prism ))
832             return false;
833           meshedFaces.push_front( prism.myTop );
834           meshedFaces.push_front( prism.myBottom );
835           meshedPrism.push_back( prism );
836           meshedSolids.Add( solid.Current() );
837         }
838         mySetErrorToSM = true;
839       }
840     }
841
842     if ( meshedFaces.empty() ) // set same error to 10 not-computed solids
843     {
844       SMESH_ComputeErrorPtr err = SMESH_ComputeError::New
845         ( COMPERR_BAD_INPUT_MESH, "No meshed source face found", this );
846
847       const int maxNbErrors = 10; // limit nb errors not to overload the Compute dialog
848       TopExp_Explorer solid( theShape, TopAbs_SOLID );
849       for ( int i = 0; ( i < maxNbErrors && solid.More() ); ++i, solid.Next() )
850         if ( !meshedSolids.Contains( solid.Current() ))
851         {
852           SMESH_subMesh* sm = theMesh.GetSubMesh( solid.Current() );
853           sm->GetComputeError() = err;
854         }
855       return error( err );
856     }
857   }
858   return true;
859 }
860
861 //================================================================================
862 /*!
863  * \brief Find wall faces by bottom edges
864  */
865 //================================================================================
866
867 bool StdMeshers_Prism_3D::getWallFaces( Prism_3D::TPrismTopo & thePrism,
868                                         const int              totalNbFaces)
869 {
870   thePrism.myWallQuads.clear();
871
872   SMESH_Mesh* mesh = myHelper->GetMesh();
873
874   StdMeshers_Quadrangle_2D* quadAlgo = TQuadrangleAlgo::instance( this, myHelper );
875
876   TopTools_MapOfShape faceMap;
877   TopTools_IndexedDataMapOfShapeListOfShape edgeToFaces;   
878   TopExp::MapShapesAndAncestors( thePrism.myShape3D,
879                                  TopAbs_EDGE, TopAbs_FACE, edgeToFaces );
880
881   // ------------------------------
882   // Get the 1st row of wall FACEs
883   // ------------------------------
884
885   list< TopoDS_Edge >::iterator edge = thePrism.myBottomEdges.begin();
886   std::list< int >::iterator     nbE = thePrism.myNbEdgesInWires.begin();
887   int iE = 0;
888   double f,l;
889   while ( edge != thePrism.myBottomEdges.end() )
890   {
891     ++iE;
892     if ( BRep_Tool::Curve( *edge, f,l ).IsNull() )
893     {
894       edge = thePrism.myBottomEdges.erase( edge );
895       --iE;
896       --(*nbE);
897     }
898     else
899     {
900       TopTools_ListIteratorOfListOfShape faceIt( edgeToFaces.FindFromKey( *edge ));
901       for ( ; faceIt.More(); faceIt.Next() )
902       {
903         const TopoDS_Face& face = TopoDS::Face( faceIt.Value() );
904         if ( !thePrism.myBottom.IsSame( face ))
905         {
906           Prism_3D::TQuadList quadList( 1, quadAlgo->CheckNbEdges( *mesh, face ));
907           if ( !quadList.back() )
908             return toSM( error(TCom("Side face #") << shapeID( face )
909                                << " not meshable with quadrangles"));
910           bool isCompositeBase = ! setBottomEdge( *edge, quadList.back(), face );
911           if ( isCompositeBase )
912           {
913             // it's OK if all EDGEs of the bottom side belongs to the bottom FACE
914             StdMeshers_FaceSidePtr botSide = quadList.back()->side[ QUAD_BOTTOM_SIDE ];
915             for ( int iE = 0; iE < botSide->NbEdges(); ++iE )
916               if ( !myHelper->IsSubShape( botSide->Edge(iE), thePrism.myBottom ))
917                 return toSM( error(TCom("Composite 'horizontal' edges are not supported")));
918           }
919           if ( faceMap.Add( face ))
920             thePrism.myWallQuads.push_back( quadList );
921           break;
922         }
923       }
924       ++edge;
925     }
926     if ( iE == *nbE )
927     {
928       iE = 0;
929       ++nbE;
930     }
931   }
932
933   // -------------------------
934   // Find the rest wall FACEs
935   // -------------------------
936
937   // Compose a vector of indixes of right neighbour FACE for each wall FACE
938   // that is not so evident in case of several WIREs in the bottom FACE
939   thePrism.myRightQuadIndex.clear();
940   for ( size_t i = 0; i < thePrism.myWallQuads.size(); ++i )
941     thePrism.myRightQuadIndex.push_back( i+1 );
942   list< int >::iterator nbEinW = thePrism.myNbEdgesInWires.begin();
943   for ( int iLeft = 0; nbEinW != thePrism.myNbEdgesInWires.end(); ++nbEinW )
944   {
945     thePrism.myRightQuadIndex[ iLeft + *nbEinW - 1 ] = iLeft; // 1st EDGE index of a current WIRE
946     iLeft += *nbEinW;
947   }
948
949   while ( totalNbFaces - faceMap.Extent() > 2 )
950   {
951     // find wall FACEs adjacent to each of wallQuads by the right side EDGE
952     int nbKnownFaces;
953     do {
954       nbKnownFaces = faceMap.Extent();
955       StdMeshers_FaceSidePtr rightSide, topSide; // sides of the quad
956       for ( size_t i = 0; i < thePrism.myWallQuads.size(); ++i )
957       {
958         rightSide = thePrism.myWallQuads[i].back()->side[ QUAD_RIGHT_SIDE ];
959         for ( int iE = 0; iE < rightSide->NbEdges(); ++iE ) // rightSide can be composite
960         {
961           const TopoDS_Edge & rightE = rightSide->Edge( iE );
962           TopTools_ListIteratorOfListOfShape face( edgeToFaces.FindFromKey( rightE ));
963           for ( ; face.More(); face.Next() )
964             if ( faceMap.Add( face.Value() ))
965             {
966               // a new wall FACE encountered, store it in thePrism.myWallQuads
967               const int iRight = thePrism.myRightQuadIndex[i];
968               topSide = thePrism.myWallQuads[ iRight ].back()->side[ QUAD_TOP_SIDE ];
969               const TopoDS_Edge&   newBotE = topSide->Edge(0);
970               const TopoDS_Shape& newWallF = face.Value();
971               thePrism.myWallQuads[ iRight ].push_back( quadAlgo->CheckNbEdges( *mesh, newWallF ));
972               if ( !thePrism.myWallQuads[ iRight ].back() )
973                 return toSM( error(TCom("Side face #") << shapeID( newWallF ) <<
974                                    " not meshable with quadrangles"));
975               if ( ! setBottomEdge( newBotE, thePrism.myWallQuads[ iRight ].back(), newWallF ))
976                 return toSM( error(TCom("Composite 'horizontal' edges are not supported")));
977             }
978         }
979       }
980     } while ( nbKnownFaces != faceMap.Extent() );
981
982     // find wall FACEs adjacent to each of thePrism.myWallQuads by the top side EDGE
983     if ( totalNbFaces - faceMap.Extent() > 2 )
984     {
985       for ( size_t i = 0; i < thePrism.myWallQuads.size(); ++i )
986       {
987         StdMeshers_FaceSidePtr topSide = thePrism.myWallQuads[i].back()->side[ QUAD_TOP_SIDE ];
988         const TopoDS_Edge &       topE = topSide->Edge( 0 );
989         if ( topSide->NbEdges() > 1 )
990           return toSM( error(COMPERR_BAD_SHAPE, TCom("Side face #") <<
991                              shapeID( thePrism.myWallQuads[i].back()->face )
992                              << " has a composite top edge"));
993         TopTools_ListIteratorOfListOfShape faceIt( edgeToFaces.FindFromKey( topE ));
994         for ( ; faceIt.More(); faceIt.Next() )
995           if ( faceMap.Add( faceIt.Value() ))
996           {
997             // a new wall FACE encountered, store it in wallQuads
998             thePrism.myWallQuads[ i ].push_back( quadAlgo->CheckNbEdges( *mesh, faceIt.Value() ));
999             if ( !thePrism.myWallQuads[ i ].back() )
1000               return toSM( error(TCom("Side face #") << shapeID( faceIt.Value() ) <<
1001                                  " not meshable with quadrangles"));
1002             if ( ! setBottomEdge( topE, thePrism.myWallQuads[ i ].back(), faceIt.Value() ))
1003               return toSM( error(TCom("Composite 'horizontal' edges are not supported")));
1004             if ( totalNbFaces - faceMap.Extent() == 2 )
1005             {
1006               i = thePrism.myWallQuads.size(); // to quit from the outer loop
1007               break;
1008             }
1009           }
1010       }
1011     }
1012   } // while ( totalNbFaces - faceMap.Extent() > 2 )
1013
1014   // ------------------
1015   // Find the top FACE
1016   // ------------------
1017
1018   if ( thePrism.myTop.IsNull() )
1019   {
1020     // now only top and bottom FACEs are not in the faceMap
1021     faceMap.Add( thePrism.myBottom );
1022     for ( TopExp_Explorer f( thePrism.myShape3D, TopAbs_FACE );f.More(); f.Next() )
1023       if ( !faceMap.Contains( f.Current() )) {
1024         thePrism.myTop = TopoDS::Face( f.Current() );
1025         break;
1026       }
1027     if ( thePrism.myTop.IsNull() )
1028       return toSM( error("Top face not found"));
1029   }
1030
1031   // Check that the top FACE shares all the top EDGEs
1032   for ( size_t i = 0; i < thePrism.myWallQuads.size(); ++i )
1033   {
1034     StdMeshers_FaceSidePtr topSide = thePrism.myWallQuads[i].back()->side[ QUAD_TOP_SIDE ];
1035     const TopoDS_Edge &       topE = topSide->Edge( 0 );
1036     if ( !myHelper->IsSubShape( topE, thePrism.myTop ))
1037       return toSM( error( TCom("Wrong source face (#") << shapeID( thePrism.myBottom )));
1038   }
1039
1040   return true;
1041 }
1042
1043 //=======================================================================
1044 //function : compute
1045 //purpose  : Compute mesh on a SOLID
1046 //=======================================================================
1047
1048 bool StdMeshers_Prism_3D::compute(const Prism_3D::TPrismTopo& thePrism)
1049 {
1050   myHelper->IsQuadraticSubMesh( thePrism.myShape3D );
1051   if ( _computeCanceled )
1052     return toSM( error( SMESH_ComputeError::New(COMPERR_CANCELED)));
1053
1054   // Make all side FACEs of thePrism meshed with quads
1055   if ( !computeWalls( thePrism ))
1056     return false;
1057
1058   // Analyse mesh and geometry to find all block sub-shapes and submeshes
1059   if ( !myBlock.Init( myHelper, thePrism ))
1060     return toSM( error( myBlock.GetError()));
1061
1062   SMESHDS_Mesh* meshDS = myHelper->GetMeshDS();
1063
1064   int volumeID = meshDS->ShapeToIndex( thePrism.myShape3D );
1065
1066   // Try to get gp_Trsf to get all nodes from bottom ones
1067   vector<gp_Trsf> trsf;
1068   gp_Trsf bottomToTopTrsf;
1069   if ( !myBlock.GetLayersTransformation( trsf, thePrism ))
1070     trsf.clear();
1071   else if ( !trsf.empty() )
1072     bottomToTopTrsf = trsf.back();
1073
1074   // To compute coordinates of a node inside a block, it is necessary to know
1075   // 1. normalized parameters of the node by which
1076   // 2. coordinates of node projections on all block sub-shapes are computed
1077
1078   // So we fill projections on vertices at once as they are same for all nodes
1079   myShapeXYZ.resize( myBlock.NbSubShapes() );
1080   for ( int iV = SMESH_Block::ID_FirstV; iV < SMESH_Block::ID_FirstE; ++iV ) {
1081     myBlock.VertexPoint( iV, myShapeXYZ[ iV ]);
1082     SHOWYXZ("V point " <<iV << " ", myShapeXYZ[ iV ]);
1083   }
1084
1085   // Projections on the top and bottom faces are taken from nodes existing
1086   // on these faces; find correspondence between bottom and top nodes
1087   myBotToColumnMap.clear();
1088   if ( !assocOrProjBottom2Top( bottomToTopTrsf, thePrism ) ) // it also fills myBotToColumnMap
1089     return false;
1090
1091
1092   // Create nodes inside the block
1093
1094   // try to use transformation (issue 0020680)
1095   if ( !trsf.empty() )
1096   {
1097     // loop on nodes inside the bottom face
1098     TNode2ColumnMap::iterator bot_column = myBotToColumnMap.begin();
1099     for ( ; bot_column != myBotToColumnMap.end(); ++bot_column )
1100     {
1101       const Prism_3D::TNode& tBotNode = bot_column->first; // bottom TNode
1102       if ( tBotNode.GetPositionType() != SMDS_TOP_FACE )
1103         continue; // node is not inside face 
1104
1105       // column nodes; middle part of the column are zero pointers
1106       TNodeColumn& column = bot_column->second;
1107       TNodeColumn::iterator columnNodes = column.begin();
1108       for ( int z = 0; columnNodes != column.end(); ++columnNodes, ++z)
1109       {
1110         const SMDS_MeshNode* & node = *columnNodes;
1111         if ( node ) continue; // skip bottom or top node
1112
1113         gp_XYZ coords = tBotNode.GetCoords();
1114         trsf[z-1].Transforms( coords );
1115         node = meshDS->AddNode( coords.X(), coords.Y(), coords.Z() );
1116         meshDS->SetNodeInVolume( node, volumeID );
1117       }
1118     } // loop on bottom nodes
1119   }
1120   else // use block approach
1121   {
1122     // loop on nodes inside the bottom face
1123     Prism_3D::TNode prevBNode;
1124     TNode2ColumnMap::iterator bot_column = myBotToColumnMap.begin();
1125     for ( ; bot_column != myBotToColumnMap.end(); ++bot_column )
1126     {
1127       const Prism_3D::TNode& tBotNode = bot_column->first; // bottom TNode
1128       if ( tBotNode.GetPositionType() != SMDS_TOP_FACE )
1129         continue; // node is not inside the FACE 
1130
1131       // column nodes; middle part of the column are zero pointers
1132       TNodeColumn& column = bot_column->second;
1133
1134       gp_XYZ botParams, topParams;
1135       if ( !tBotNode.HasParams() )
1136       {
1137         // compute bottom node parameters
1138         gp_XYZ paramHint(-1,-1,-1);
1139         if ( prevBNode.IsNeighbor( tBotNode ))
1140           paramHint = prevBNode.GetParams();
1141         if ( !myBlock.ComputeParameters( tBotNode.GetCoords(), tBotNode.ChangeParams(),
1142                                          ID_BOT_FACE, paramHint ))
1143           return toSM( error(TCom("Can't compute normalized parameters for node ")
1144                              << tBotNode.myNode->GetID() << " on the face #"
1145                              << myBlock.SubMesh( ID_BOT_FACE )->GetId() ));
1146         prevBNode = tBotNode;
1147
1148         botParams = topParams = tBotNode.GetParams();
1149         topParams.SetZ( 1 );
1150
1151         // compute top node parameters
1152         if ( column.size() > 2 ) {
1153           gp_Pnt topCoords = gpXYZ( column.back() );
1154           if ( !myBlock.ComputeParameters( topCoords, topParams, ID_TOP_FACE, topParams ))
1155             return toSM( error(TCom("Can't compute normalized parameters ")
1156                                << "for node " << column.back()->GetID()
1157                                << " on the face #"<< column.back()->getshapeId() ));
1158         }
1159       }
1160       else // top nodes are created by projection using parameters
1161       {
1162         botParams = topParams = tBotNode.GetParams();
1163         topParams.SetZ( 1 );
1164       }
1165
1166       myShapeXYZ[ ID_BOT_FACE ] = tBotNode.GetCoords();
1167       myShapeXYZ[ ID_TOP_FACE ] = gpXYZ( column.back() );
1168
1169       // vertical loop
1170       TNodeColumn::iterator columnNodes = column.begin();
1171       for ( int z = 0; columnNodes != column.end(); ++columnNodes, ++z)
1172       {
1173         const SMDS_MeshNode* & node = *columnNodes;
1174         if ( node ) continue; // skip bottom or top node
1175
1176         // params of a node to create
1177         double rz = (double) z / (double) ( column.size() - 1 );
1178         gp_XYZ params = botParams * ( 1 - rz ) + topParams * rz;
1179
1180         // set coords on all faces and nodes
1181         const int nbSideFaces = 4;
1182         int sideFaceIDs[nbSideFaces] = { SMESH_Block::ID_Fx0z,
1183                                          SMESH_Block::ID_Fx1z,
1184                                          SMESH_Block::ID_F0yz,
1185                                          SMESH_Block::ID_F1yz };
1186         for ( int iF = 0; iF < nbSideFaces; ++iF )
1187           if ( !setFaceAndEdgesXYZ( sideFaceIDs[ iF ], params, z ))
1188             return false;
1189
1190         // compute coords for a new node
1191         gp_XYZ coords;
1192         if ( !SMESH_Block::ShellPoint( params, myShapeXYZ, coords ))
1193           return toSM( error("Can't compute coordinates by normalized parameters"));
1194
1195         // if ( !meshDS->MeshElements( volumeID ) ||
1196         //      meshDS->MeshElements( volumeID )->NbNodes() == 0 )
1197         //   pointsToPython(myShapeXYZ);
1198         SHOWYXZ("TOPFacePoint ",myShapeXYZ[ ID_TOP_FACE]);
1199         SHOWYXZ("BOT Node "<< tBotNode.myNode->GetID(),gpXYZ(tBotNode.myNode));
1200         SHOWYXZ("ShellPoint ",coords);
1201
1202         // create a node
1203         node = meshDS->AddNode( coords.X(), coords.Y(), coords.Z() );
1204         meshDS->SetNodeInVolume( node, volumeID );
1205       }
1206     } // loop on bottom nodes
1207   }
1208
1209   // Create volumes
1210
1211   SMESHDS_SubMesh* smDS = myBlock.SubMeshDS( ID_BOT_FACE );
1212   if ( !smDS ) return toSM( error(COMPERR_BAD_INPUT_MESH, "Null submesh"));
1213
1214   // loop on bottom mesh faces
1215   SMDS_ElemIteratorPtr faceIt = smDS->GetElements();
1216   while ( faceIt->more() )
1217   {
1218     const SMDS_MeshElement* face = faceIt->next();
1219     if ( !face || face->GetType() != SMDSAbs_Face )
1220       continue;
1221
1222     // find node columns for each node
1223     int nbNodes = face->NbCornerNodes();
1224     vector< const TNodeColumn* > columns( nbNodes );
1225     for ( int i = 0; i < nbNodes; ++i )
1226     {
1227       const SMDS_MeshNode* n = face->GetNode( i );
1228       if ( n->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE ) {
1229         TNode2ColumnMap::iterator bot_column = myBotToColumnMap.find( n );
1230         if ( bot_column == myBotToColumnMap.end() )
1231           return toSM( error(TCom("No nodes found above node ") << n->GetID() ));
1232         columns[ i ] = & bot_column->second;
1233       }
1234       else {
1235         columns[ i ] = myBlock.GetNodeColumn( n );
1236         if ( !columns[ i ] )
1237           return toSM( error(TCom("No side nodes found above node ") << n->GetID() ));
1238       }
1239     }
1240     // create prisms
1241     AddPrisms( columns, myHelper );
1242
1243   } // loop on bottom mesh faces
1244
1245   // clear data
1246   myBotToColumnMap.clear();
1247   myBlock.Clear();
1248         
1249   return true;
1250 }
1251
1252 //=======================================================================
1253 //function : computeWalls
1254 //purpose  : Compute 2D mesh on walls FACEs of a prism
1255 //=======================================================================
1256
1257 bool StdMeshers_Prism_3D::computeWalls(const Prism_3D::TPrismTopo& thePrism)
1258 {
1259   SMESH_Mesh*     mesh = myHelper->GetMesh();
1260   SMESHDS_Mesh* meshDS = myHelper->GetMeshDS();
1261   DBGOUT( endl << "COMPUTE Prism " << meshDS->ShapeToIndex( thePrism.myShape3D ));
1262
1263   TProjction1dAlgo*      projector1D = TProjction1dAlgo::instance( this );
1264   StdMeshers_Quadrangle_2D* quadAlgo = TQuadrangleAlgo::instance( this, myHelper );
1265
1266   // SMESH_HypoFilter hyp1dFilter( SMESH_HypoFilter::IsAlgo(),/*not=*/true);
1267   // hyp1dFilter.And( SMESH_HypoFilter::HasDim( 1 ));
1268   // hyp1dFilter.And( SMESH_HypoFilter::IsMoreLocalThan( thePrism.myShape3D, *mesh ));
1269
1270   // Discretize equally 'vertical' EDGEs
1271   // -----------------------------------
1272   // find source FACE sides for projection: either already computed ones or
1273   // the 'most composite' ones
1274   const size_t nbWalls = thePrism.myWallQuads.size();
1275   vector< int > wgt( nbWalls, 0 ); // "weight" of a wall
1276   for ( size_t iW = 0; iW != nbWalls; ++iW )
1277   {
1278     Prism_3D::TQuadList::const_iterator quad = thePrism.myWallQuads[iW].begin();
1279     for ( ; quad != thePrism.myWallQuads[iW].end(); ++quad )
1280     {
1281       StdMeshers_FaceSidePtr lftSide = (*quad)->side[ QUAD_LEFT_SIDE ];
1282       for ( int i = 0; i < lftSide->NbEdges(); ++i )
1283       {
1284         ++wgt[ iW ];
1285         const TopoDS_Edge& E = lftSide->Edge(i);
1286         if ( mesh->GetSubMesh( E )->IsMeshComputed() )
1287         {
1288           wgt[ iW ] += 100;
1289           wgt[ myHelper->WrapIndex( iW+1, nbWalls)] += 10;
1290           wgt[ myHelper->WrapIndex( iW-1, nbWalls)] += 10;
1291         }
1292         // else if ( mesh->GetHypothesis( E, hyp1dFilter, true )) // local hypothesis!
1293         //   wgt += 100;
1294       }
1295     }
1296     // in quadratic mesh, pass ignoreMediumNodes to quad sides
1297     if ( myHelper->GetIsQuadratic() )
1298     {
1299       quad = thePrism.myWallQuads[iW].begin();
1300       for ( ; quad != thePrism.myWallQuads[iW].end(); ++quad )
1301         for ( int i = 0; i < NB_QUAD_SIDES; ++i )
1302           (*quad)->side[ i ].grid->SetIgnoreMediumNodes( true );
1303     }
1304   }
1305   multimap< int, int > wgt2quad;
1306   for ( size_t iW = 0; iW != nbWalls; ++iW )
1307     wgt2quad.insert( make_pair( wgt[ iW ], iW ));
1308
1309   // Project 'vertical' EDGEs, from left to right
1310   multimap< int, int >::reverse_iterator w2q = wgt2quad.rbegin();
1311   for ( ; w2q != wgt2quad.rend(); ++w2q )
1312   {
1313     const int iW = w2q->second;
1314     const Prism_3D::TQuadList&         quads = thePrism.myWallQuads[ iW ];
1315     Prism_3D::TQuadList::const_iterator quad = quads.begin();
1316     for ( ; quad != quads.end(); ++quad )
1317     {
1318       StdMeshers_FaceSidePtr rgtSide = (*quad)->side[ QUAD_RIGHT_SIDE ]; // tgt
1319       StdMeshers_FaceSidePtr lftSide = (*quad)->side[ QUAD_LEFT_SIDE ];  // src
1320       bool swapLeftRight = ( lftSide->NbSegments( /*update=*/true ) == 0 &&
1321                              rgtSide->NbSegments( /*update=*/true )  > 0 );
1322       if ( swapLeftRight )
1323         std::swap( lftSide, rgtSide );
1324
1325       // assure that all the source (left) EDGEs are meshed
1326       int nbSrcSegments = 0;
1327       for ( int i = 0; i < lftSide->NbEdges(); ++i )
1328       {
1329         const TopoDS_Edge& srcE = lftSide->Edge(i);
1330         SMESH_subMesh*    srcSM = mesh->GetSubMesh( srcE );
1331         if ( !srcSM->IsMeshComputed() ) {
1332           DBGOUT( "COMPUTE V edge " << srcSM->GetId() );
1333           TopoDS_Edge prpgSrcE = findPropagationSource( srcE );
1334           if ( !prpgSrcE.IsNull() ) {
1335             srcSM->ComputeSubMeshStateEngine( SMESH_subMesh::COMPUTE );
1336             projector1D->myHyp.SetSourceEdge( prpgSrcE );
1337             projector1D->Compute( *mesh, srcE );
1338             srcSM->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1339           }
1340           else {
1341             srcSM->ComputeSubMeshStateEngine( SMESH_subMesh::COMPUTE );
1342             srcSM->ComputeStateEngine       ( SMESH_subMesh::COMPUTE );
1343           }
1344           if ( !srcSM->IsMeshComputed() )
1345             return toSM( error( "Can't compute 1D mesh" ));
1346         }
1347         nbSrcSegments += srcSM->GetSubMeshDS()->NbElements();
1348       }
1349       // check target EDGEs
1350       int nbTgtMeshed = 0, nbTgtSegments = 0;
1351       vector< bool > isTgtEdgeComputed( rgtSide->NbEdges() );
1352       for ( int i = 0; i < rgtSide->NbEdges(); ++i )
1353       {
1354         const TopoDS_Edge& tgtE = rgtSide->Edge(i);
1355         SMESH_subMesh*    tgtSM = mesh->GetSubMesh( tgtE );
1356         if ( !( isTgtEdgeComputed[ i ] = tgtSM->IsMeshComputed() )) {
1357           tgtSM->ComputeSubMeshStateEngine( SMESH_subMesh::COMPUTE );
1358           tgtSM->ComputeStateEngine       ( SMESH_subMesh::COMPUTE );
1359         }
1360         if ( tgtSM->IsMeshComputed() ) {
1361           ++nbTgtMeshed;
1362           nbTgtSegments += tgtSM->GetSubMeshDS()->NbElements();
1363         }
1364       }
1365       if ( rgtSide->NbEdges() == nbTgtMeshed ) // all tgt EDGEs meshed
1366       {
1367         if ( nbTgtSegments != nbSrcSegments )
1368         {
1369           bool badMeshRemoved = false;
1370           // remove just computed segments
1371           for ( int i = 0; i < rgtSide->NbEdges(); ++i )
1372             if ( !isTgtEdgeComputed[ i ])
1373             {
1374               const TopoDS_Edge& tgtE = rgtSide->Edge(i);
1375               SMESH_subMesh*    tgtSM = mesh->GetSubMesh( tgtE );
1376               tgtSM->ComputeStateEngine( SMESH_subMesh::CLEAN );
1377               badMeshRemoved = true;
1378               nbTgtMeshed--;
1379             }
1380           if ( !badMeshRemoved )
1381           {
1382             for ( int i = 0; i < lftSide->NbEdges(); ++i )
1383               addBadInputElements( meshDS->MeshElements( lftSide->Edge( i )));
1384             for ( int i = 0; i < rgtSide->NbEdges(); ++i )
1385               addBadInputElements( meshDS->MeshElements( rgtSide->Edge( i )));
1386             return toSM( error( TCom("Different nb of segment on logically vertical edges #")
1387                                 << shapeID( lftSide->Edge(0) ) << " and #"
1388                                 << shapeID( rgtSide->Edge(0) ) << ": "
1389                                 << nbSrcSegments << " != " << nbTgtSegments ));
1390           }
1391         }
1392         else // if ( nbTgtSegments == nbSrcSegments )
1393         {
1394           continue;
1395         }
1396       }
1397       // Compute 'vertical projection'
1398       if ( nbTgtMeshed == 0 )
1399       {
1400         // compute nodes on target VERTEXes
1401         const UVPtStructVec&  srcNodeStr = lftSide->GetUVPtStruct();
1402         if ( srcNodeStr.size() == 0 )
1403           return toSM( error( TCom("Invalid node positions on edge #") <<
1404                               shapeID( lftSide->Edge(0) )));
1405         vector< SMDS_MeshNode* > newNodes( srcNodeStr.size() );
1406         for ( int is2ndV = 0; is2ndV < 2; ++is2ndV )
1407         {
1408           const TopoDS_Edge& E = rgtSide->Edge( is2ndV ? rgtSide->NbEdges()-1 : 0 );
1409           TopoDS_Vertex      v = myHelper->IthVertex( is2ndV, E );
1410           mesh->GetSubMesh( v )->ComputeStateEngine( SMESH_subMesh::COMPUTE );
1411           const SMDS_MeshNode* n = SMESH_Algo::VertexNode( v, meshDS );
1412           newNodes[ is2ndV ? 0 : newNodes.size()-1 ] = (SMDS_MeshNode*) n;
1413         }
1414
1415         // compute nodes on target EDGEs
1416         DBGOUT( "COMPUTE V edge (proj) " << shapeID( lftSide->Edge(0)));
1417         rgtSide->Reverse(); // direct it same as the lftSide
1418         myHelper->SetElementsOnShape( false ); // myHelper holds the prism shape
1419         TopoDS_Edge tgtEdge;
1420         for ( size_t iN = 1; iN < srcNodeStr.size()-1; ++iN ) // add nodes
1421         {
1422           gp_Pnt       p = rgtSide->Value3d  ( srcNodeStr[ iN ].normParam );
1423           double       u = rgtSide->Parameter( srcNodeStr[ iN ].normParam, tgtEdge );
1424           newNodes[ iN ] = meshDS->AddNode( p.X(), p.Y(), p.Z() );
1425           meshDS->SetNodeOnEdge( newNodes[ iN ], tgtEdge, u );
1426         }
1427         for ( size_t iN = 1; iN < srcNodeStr.size(); ++iN ) // add segments
1428         {
1429           // find an EDGE to set a new segment
1430           std::pair<int, TopAbs_ShapeEnum> id2type = 
1431             myHelper->GetMediumPos( newNodes[ iN-1 ], newNodes[ iN ] );
1432           if ( id2type.second != TopAbs_EDGE )
1433           {
1434             // new nodes are on different EDGEs; put one of them on VERTEX
1435             const int      edgeIndex = rgtSide->EdgeIndex( srcNodeStr[ iN-1 ].normParam );
1436             const double vertexParam = rgtSide->LastParameter( edgeIndex );
1437             TopoDS_Vertex     vertex = rgtSide->LastVertex( edgeIndex );
1438             const SMDS_MeshNode*  vn = SMESH_Algo::VertexNode( vertex, meshDS );
1439             const gp_Pnt           p = BRep_Tool::Pnt( vertex );
1440             const int         isPrev = ( Abs( srcNodeStr[ iN-1 ].normParam - vertexParam ) <
1441                                          Abs( srcNodeStr[ iN   ].normParam - vertexParam ));
1442             meshDS->UnSetNodeOnShape( newNodes[ iN-isPrev ] );
1443             meshDS->SetNodeOnVertex ( newNodes[ iN-isPrev ], vertex );
1444             meshDS->MoveNode        ( newNodes[ iN-isPrev ], p.X(), p.Y(), p.Z() );
1445             id2type.first = newNodes[ iN-(1-isPrev) ]->getshapeId();
1446             if ( vn )
1447             {
1448               SMESH_MeshEditor::TListOfListOfNodes lln( 1, list< const SMDS_MeshNode* >() );
1449               lln.back().push_back ( vn );
1450               lln.back().push_front( newNodes[ iN-isPrev ] ); // to keep 
1451               SMESH_MeshEditor( mesh ).MergeNodes( lln );
1452             }
1453           }
1454           SMDS_MeshElement* newEdge = myHelper->AddEdge( newNodes[ iN-1 ], newNodes[ iN ] );
1455           meshDS->SetMeshElementOnShape( newEdge, id2type.first );
1456         }
1457         myHelper->SetElementsOnShape( true );
1458         for ( int i = 0; i < rgtSide->NbEdges(); ++i ) // update state of sub-meshes
1459         {
1460           const TopoDS_Edge& E = rgtSide->Edge( i );
1461           SMESH_subMesh* tgtSM = mesh->GetSubMesh( E );
1462           tgtSM->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1463         }
1464
1465         // to continue projection from the just computed side as a source
1466         if ( !swapLeftRight && rgtSide->NbEdges() > 1 && w2q->second == iW )
1467         {
1468           std::pair<int,int> wgt2quadKeyVal( w2q->first + 1, thePrism.myRightQuadIndex[ iW ]);
1469           wgt2quad.insert( wgt2quadKeyVal ); // it will be skipped by ++w2q
1470           wgt2quad.insert( wgt2quadKeyVal );
1471           w2q = wgt2quad.rbegin();
1472         }
1473       }
1474       else
1475       {
1476         // HOPE assigned hypotheses are OK, so that equal nb of segments will be generated
1477         //return toSM( error("Partial projection not implemented"));
1478       }
1479     } // loop on quads of a composite wall side
1480   } // loop on the ordered wall sides
1481
1482
1483
1484   for ( size_t iW = 0; iW != thePrism.myWallQuads.size(); ++iW )
1485   {
1486     Prism_3D::TQuadList::const_iterator quad = thePrism.myWallQuads[iW].begin();
1487     for ( ; quad != thePrism.myWallQuads[iW].end(); ++quad )
1488     {
1489       const TopoDS_Face& face = (*quad)->face;
1490       SMESH_subMesh* fSM = mesh->GetSubMesh( face );
1491       if ( ! fSM->IsMeshComputed() )
1492       {
1493         // Top EDGEs must be projections from the bottom ones
1494         // to compute stuctured quad mesh on wall FACEs
1495         // ---------------------------------------------------
1496         const TopoDS_Edge& botE = (*quad)->side[ QUAD_BOTTOM_SIDE ].grid->Edge(0);
1497         const TopoDS_Edge& topE = (*quad)->side[ QUAD_TOP_SIDE    ].grid->Edge(0);
1498         SMESH_subMesh*    botSM = mesh->GetSubMesh( botE );
1499         SMESH_subMesh*    topSM = mesh->GetSubMesh( topE );
1500         SMESH_subMesh*    srcSM = botSM;
1501         SMESH_subMesh*    tgtSM = topSM;
1502         if ( !srcSM->IsMeshComputed() && tgtSM->IsMeshComputed() )
1503           std::swap( srcSM, tgtSM );
1504
1505         if ( !srcSM->IsMeshComputed() )
1506         {
1507           DBGOUT( "COMPUTE H edge " << srcSM->GetId());
1508           srcSM->ComputeSubMeshStateEngine( SMESH_subMesh::COMPUTE ); // nodes on VERTEXes
1509           srcSM->ComputeStateEngine( SMESH_subMesh::COMPUTE );        // segments on the EDGE
1510         }
1511         srcSM->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1512
1513         if ( tgtSM->IsMeshComputed() &&
1514              tgtSM->GetSubMeshDS()->NbNodes() != srcSM->GetSubMeshDS()->NbNodes() )
1515         {
1516           // the top EDGE is computed differently than the bottom one,
1517           // try to clear a wrong mesh
1518           bool isAdjFaceMeshed = false;
1519           PShapeIteratorPtr fIt = myHelper->GetAncestors( tgtSM->GetSubShape(),
1520                                                           *mesh, TopAbs_FACE );
1521           while ( const TopoDS_Shape* f = fIt->next() )
1522             if (( isAdjFaceMeshed = mesh->GetSubMesh( *f )->IsMeshComputed() ))
1523               break;
1524           if ( isAdjFaceMeshed )
1525             return toSM( error( TCom("Different nb of segment on logically horizontal edges #")
1526                                 << shapeID( botE ) << " and #"
1527                                 << shapeID( topE ) << ": "
1528                                 << tgtSM->GetSubMeshDS()->NbElements() << " != "
1529                                 << srcSM->GetSubMeshDS()->NbElements() ));
1530           tgtSM->ComputeStateEngine( SMESH_subMesh::CLEAN );
1531         }
1532         if ( !tgtSM->IsMeshComputed() )
1533         {
1534           // compute nodes on VERTEXes
1535           SMESH_subMeshIteratorPtr smIt = tgtSM->getDependsOnIterator(/*includeSelf=*/false);
1536           while ( smIt->more() )
1537             smIt->next()->ComputeStateEngine( SMESH_subMesh::COMPUTE );
1538           // project segments
1539           DBGOUT( "COMPUTE H edge (proj) " << tgtSM->GetId());
1540           projector1D->myHyp.SetSourceEdge( TopoDS::Edge( srcSM->GetSubShape() ));
1541           projector1D->InitComputeError();
1542           bool ok = projector1D->Compute( *mesh, tgtSM->GetSubShape() );
1543           if ( !ok )
1544           {
1545             SMESH_ComputeErrorPtr err = projector1D->GetComputeError();
1546             if ( err->IsOK() ) err->myName = COMPERR_ALGO_FAILED;
1547             tgtSM->GetComputeError() = err;
1548             return false;
1549           }
1550         }
1551         tgtSM->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1552
1553
1554         // Compute quad mesh on wall FACEs
1555         // -------------------------------
1556
1557         // make all EDGES meshed
1558         fSM->ComputeSubMeshStateEngine( SMESH_subMesh::COMPUTE );
1559         if ( !fSM->SubMeshesComputed() )
1560           return toSM( error( COMPERR_BAD_INPUT_MESH,
1561                               "Not all edges have valid algorithm and hypothesis"));
1562         // mesh the <face>
1563         quadAlgo->InitComputeError();
1564         DBGOUT( "COMPUTE Quad face " << fSM->GetId());
1565         bool ok = quadAlgo->Compute( *mesh, face );
1566         fSM->GetComputeError() = quadAlgo->GetComputeError();
1567         if ( !ok )
1568           return false;
1569         fSM->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1570       }
1571       if ( myHelper->GetIsQuadratic() )
1572       {
1573         // fill myHelper with medium nodes built by quadAlgo
1574         SMDS_ElemIteratorPtr fIt = fSM->GetSubMeshDS()->GetElements();
1575         while ( fIt->more() )
1576           myHelper->AddTLinks( dynamic_cast<const SMDS_MeshFace*>( fIt->next() ));
1577       }
1578     }
1579   }
1580
1581   return true;
1582 }
1583
1584 //=======================================================================
1585 /*!
1586  * \brief Returns a source EDGE of propagation to a given EDGE
1587  */
1588 //=======================================================================
1589
1590 TopoDS_Edge StdMeshers_Prism_3D::findPropagationSource( const TopoDS_Edge& E )
1591 {
1592   if ( myPropagChains )
1593     for ( size_t i = 0; !myPropagChains[i].IsEmpty(); ++i )
1594       if ( myPropagChains[i].Contains( E ))
1595         return TopoDS::Edge( myPropagChains[i].FindKey( 1 ));
1596
1597   return TopoDS_Edge();
1598 }
1599
1600 //=======================================================================
1601 //function : Evaluate
1602 //purpose  : 
1603 //=======================================================================
1604
1605 bool StdMeshers_Prism_3D::Evaluate(SMESH_Mesh&         theMesh,
1606                                    const TopoDS_Shape& theShape,
1607                                    MapShapeNbElems&    aResMap)
1608 {
1609   if ( theShape.ShapeType() == TopAbs_COMPOUND )
1610   {
1611     bool ok = true;
1612     for ( TopoDS_Iterator it( theShape ); it.More(); it.Next() )
1613       ok &= Evaluate( theMesh, it.Value(), aResMap );
1614     return ok;
1615   }
1616   SMESH_MesherHelper helper( theMesh );
1617   myHelper = &helper;
1618   myHelper->SetSubShape( theShape );
1619
1620   // find face contains only triangles
1621   vector < SMESH_subMesh * >meshFaces;
1622   TopTools_SequenceOfShape aFaces;
1623   int NumBase = 0, i = 0, NbQFs = 0;
1624   for (TopExp_Explorer exp(theShape, TopAbs_FACE); exp.More(); exp.Next()) {
1625     i++;
1626     aFaces.Append(exp.Current());
1627     SMESH_subMesh *aSubMesh = theMesh.GetSubMesh(exp.Current());
1628     meshFaces.push_back(aSubMesh);
1629     MapShapeNbElemsItr anIt = aResMap.find(meshFaces[i-1]);
1630     if( anIt==aResMap.end() )
1631       return toSM( error( "Submesh can not be evaluated"));
1632
1633     std::vector<int> aVec = (*anIt).second;
1634     int nbtri = Max(aVec[SMDSEntity_Triangle],aVec[SMDSEntity_Quad_Triangle]);
1635     int nbqua = Max(aVec[SMDSEntity_Quadrangle],aVec[SMDSEntity_Quad_Quadrangle]);
1636     if( nbtri==0 && nbqua>0 ) {
1637       NbQFs++;
1638     }
1639     if( nbtri>0 ) {
1640       NumBase = i;
1641     }
1642   }
1643
1644   if(NbQFs<4) {
1645     std::vector<int> aResVec(SMDSEntity_Last);
1646     for(int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aResVec[i] = 0;
1647     SMESH_subMesh * sm = theMesh.GetSubMesh(theShape);
1648     aResMap.insert(std::make_pair(sm,aResVec));
1649     return toSM( error( "Submesh can not be evaluated" ));
1650   }
1651
1652   if(NumBase==0) NumBase = 1; // only quads => set 1 faces as base
1653
1654   // find number of 1d elems for base face
1655   int nb1d = 0;
1656   TopTools_MapOfShape Edges1;
1657   for (TopExp_Explorer exp(aFaces.Value(NumBase), TopAbs_EDGE); exp.More(); exp.Next()) {
1658     Edges1.Add(exp.Current());
1659     SMESH_subMesh *sm = theMesh.GetSubMesh(exp.Current());
1660     if( sm ) {
1661       MapShapeNbElemsItr anIt = aResMap.find(sm);
1662       if( anIt == aResMap.end() ) continue;
1663       std::vector<int> aVec = (*anIt).second;
1664       nb1d += Max(aVec[SMDSEntity_Edge],aVec[SMDSEntity_Quad_Edge]);
1665     }
1666   }
1667   // find face opposite to base face
1668   int OppNum = 0;
1669   for(i=1; i<=6; i++) {
1670     if(i==NumBase) continue;
1671     bool IsOpposite = true;
1672     for(TopExp_Explorer exp(aFaces.Value(i), TopAbs_EDGE); exp.More(); exp.Next()) {
1673       if( Edges1.Contains(exp.Current()) ) {
1674         IsOpposite = false;
1675         break;
1676       }
1677     }
1678     if(IsOpposite) {
1679       OppNum = i;
1680       break;
1681     }
1682   }
1683   // find number of 2d elems on side faces
1684   int nb2d = 0;
1685   for(i=1; i<=6; i++) {
1686     if( i==OppNum || i==NumBase ) continue;
1687     MapShapeNbElemsItr anIt = aResMap.find( meshFaces[i-1] );
1688     if( anIt == aResMap.end() ) continue;
1689     std::vector<int> aVec = (*anIt).second;
1690     nb2d += Max(aVec[SMDSEntity_Quadrangle],aVec[SMDSEntity_Quad_Quadrangle]);
1691   }
1692   
1693   MapShapeNbElemsItr anIt = aResMap.find( meshFaces[NumBase-1] );
1694   std::vector<int> aVec = (*anIt).second;
1695   bool IsQuadratic = (aVec[SMDSEntity_Quad_Triangle]>aVec[SMDSEntity_Triangle]) ||
1696                      (aVec[SMDSEntity_Quad_Quadrangle]>aVec[SMDSEntity_Quadrangle]);
1697   int nb2d_face0_3 = Max(aVec[SMDSEntity_Triangle],aVec[SMDSEntity_Quad_Triangle]);
1698   int nb2d_face0_4 = Max(aVec[SMDSEntity_Quadrangle],aVec[SMDSEntity_Quad_Quadrangle]);
1699   int nb0d_face0 = aVec[SMDSEntity_Node];
1700   int nb1d_face0_int = ( nb2d_face0_3*3 + nb2d_face0_4*4 - nb1d ) / 2;
1701
1702   std::vector<int> aResVec(SMDSEntity_Last);
1703   for(int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aResVec[i] = 0;
1704   if(IsQuadratic) {
1705     aResVec[SMDSEntity_Quad_Penta] = nb2d_face0_3 * ( nb2d/nb1d );
1706     aResVec[SMDSEntity_Quad_Hexa] = nb2d_face0_4 * ( nb2d/nb1d );
1707     aResVec[SMDSEntity_Node] = nb0d_face0 * ( 2*nb2d/nb1d - 1 ) - nb1d_face0_int * nb2d/nb1d;
1708   }
1709   else {
1710     aResVec[SMDSEntity_Node] = nb0d_face0 * ( nb2d/nb1d - 1 );
1711     aResVec[SMDSEntity_Penta] = nb2d_face0_3 * ( nb2d/nb1d );
1712     aResVec[SMDSEntity_Hexa] = nb2d_face0_4 * ( nb2d/nb1d );
1713   }
1714   SMESH_subMesh * sm = theMesh.GetSubMesh(theShape);
1715   aResMap.insert(std::make_pair(sm,aResVec));
1716
1717   return true;
1718 }
1719
1720 //================================================================================
1721 /*!
1722  * \brief Create prisms
1723  * \param columns - columns of nodes generated from nodes of a mesh face
1724  * \param helper - helper initialized by mesh and shape to add prisms to
1725  */
1726 //================================================================================
1727
1728 void StdMeshers_Prism_3D::AddPrisms( vector<const TNodeColumn*> & columns,
1729                                      SMESH_MesherHelper*          helper)
1730 {
1731   int nbNodes = columns.size();
1732   int nbZ     = columns[0]->size();
1733   if ( nbZ < 2 ) return;
1734
1735   // find out orientation
1736   bool isForward = true;
1737   SMDS_VolumeTool vTool;
1738   int z = 1;
1739   switch ( nbNodes ) {
1740   case 3: {
1741     SMDS_VolumeOfNodes tmpPenta ( (*columns[0])[z-1], // bottom
1742                                   (*columns[1])[z-1],
1743                                   (*columns[2])[z-1],
1744                                   (*columns[0])[z],   // top
1745                                   (*columns[1])[z],
1746                                   (*columns[2])[z] );
1747     vTool.Set( &tmpPenta );
1748     isForward  = vTool.IsForward();
1749     break;
1750   }
1751   case 4: {
1752     SMDS_VolumeOfNodes tmpHex( (*columns[0])[z-1], (*columns[1])[z-1], // bottom
1753                                (*columns[2])[z-1], (*columns[3])[z-1],
1754                                (*columns[0])[z],   (*columns[1])[z],   // top
1755                                (*columns[2])[z],   (*columns[3])[z] );
1756     vTool.Set( &tmpHex );
1757     isForward  = vTool.IsForward();
1758     break;
1759   }
1760   default:
1761     const int di = (nbNodes+1) / 3;
1762     SMDS_VolumeOfNodes tmpVol ( (*columns[0]   )[z-1],
1763                                 (*columns[di]  )[z-1],
1764                                 (*columns[2*di])[z-1],
1765                                 (*columns[0]   )[z],
1766                                 (*columns[di]  )[z],
1767                                 (*columns[2*di])[z] );
1768     vTool.Set( &tmpVol );
1769     isForward  = vTool.IsForward();
1770   }
1771
1772   // vertical loop on columns
1773
1774   helper->SetElementsOnShape( true );
1775
1776   switch ( nbNodes ) {
1777
1778   case 3: { // ---------- pentahedra
1779     const int i1 = isForward ? 1 : 2;
1780     const int i2 = isForward ? 2 : 1;
1781     for ( z = 1; z < nbZ; ++z )
1782       helper->AddVolume( (*columns[0 ])[z-1], // bottom
1783                          (*columns[i1])[z-1],
1784                          (*columns[i2])[z-1],
1785                          (*columns[0 ])[z],   // top
1786                          (*columns[i1])[z],
1787                          (*columns[i2])[z] );
1788     break;
1789   }
1790   case 4: { // ---------- hexahedra
1791     const int i1 = isForward ? 1 : 3;
1792     const int i3 = isForward ? 3 : 1;
1793     for ( z = 1; z < nbZ; ++z )
1794       helper->AddVolume( (*columns[0])[z-1], (*columns[i1])[z-1], // bottom
1795                          (*columns[2])[z-1], (*columns[i3])[z-1],
1796                          (*columns[0])[z],   (*columns[i1])[z],     // top
1797                          (*columns[2])[z],   (*columns[i3])[z] );
1798     break;
1799   }
1800   case 6: { // ---------- octahedra
1801     const int iBase1 = isForward ? -1 : 0;
1802     const int iBase2 = isForward ?  0 :-1;
1803     for ( z = 1; z < nbZ; ++z )
1804       helper->AddVolume( (*columns[0])[z+iBase1], (*columns[1])[z+iBase1], // bottom or top
1805                          (*columns[2])[z+iBase1], (*columns[3])[z+iBase1],
1806                          (*columns[4])[z+iBase1], (*columns[5])[z+iBase1],
1807                          (*columns[0])[z+iBase2], (*columns[1])[z+iBase2], // top or bottom
1808                          (*columns[2])[z+iBase2], (*columns[3])[z+iBase2],
1809                          (*columns[4])[z+iBase2], (*columns[5])[z+iBase2] );
1810     break;
1811   }
1812   default: // ---------- polyhedra
1813     vector<int> quantities( 2 + nbNodes, 4 );
1814     quantities[0] = quantities[1] = nbNodes;
1815     columns.resize( nbNodes + 1 );
1816     columns[ nbNodes ] = columns[ 0 ];
1817     const int i1 = isForward ? 1 : 3;
1818     const int i3 = isForward ? 3 : 1;
1819     const int iBase1 = isForward ? -1 : 0;
1820     const int iBase2 = isForward ?  0 :-1;
1821     vector<const SMDS_MeshNode*> nodes( 2*nbNodes + 4*nbNodes);
1822     for ( z = 1; z < nbZ; ++z )
1823     {
1824       for ( int i = 0; i < nbNodes; ++i ) {
1825         nodes[ i             ] = (*columns[ i ])[z+iBase1]; // bottom or top
1826         nodes[ 2*nbNodes-i-1 ] = (*columns[ i ])[z+iBase2]; // top or bottom
1827         // side
1828         int di = 2*nbNodes + 4*i;
1829         nodes[ di+0 ] = (*columns[i  ])[z  ];
1830         nodes[ di+i1] = (*columns[i+1])[z  ];
1831         nodes[ di+2 ] = (*columns[i+1])[z-1];
1832         nodes[ di+i3] = (*columns[i  ])[z-1];
1833       }
1834       helper->AddPolyhedralVolume( nodes, quantities );
1835     }
1836
1837   } // switch ( nbNodes )
1838 }
1839
1840 //================================================================================
1841 /*!
1842  * \brief Find correspondence between bottom and top nodes
1843  *  If elements on the bottom and top faces are topologically different,
1844  *  and projection is possible and allowed, perform the projection
1845  *  \retval bool - is a success or not
1846  */
1847 //================================================================================
1848
1849 bool StdMeshers_Prism_3D::assocOrProjBottom2Top( const gp_Trsf & bottomToTopTrsf,
1850                                                  const Prism_3D::TPrismTopo& thePrism)
1851 {
1852   SMESH_subMesh * botSM = myBlock.SubMesh( ID_BOT_FACE );
1853   SMESH_subMesh * topSM = myBlock.SubMesh( ID_TOP_FACE );
1854
1855   SMESHDS_SubMesh * botSMDS = botSM->GetSubMeshDS();
1856   SMESHDS_SubMesh * topSMDS = topSM->GetSubMeshDS();
1857
1858   if ( !botSMDS || botSMDS->NbElements() == 0 )
1859   {
1860     _gen->Compute( *myHelper->GetMesh(), botSM->GetSubShape() );
1861     botSMDS = botSM->GetSubMeshDS();
1862     if ( !botSMDS || botSMDS->NbElements() == 0 )
1863       return toSM( error(TCom("No elements on face #") << botSM->GetId() ));
1864   }
1865
1866   bool needProject = !topSM->IsMeshComputed();
1867   if ( !needProject &&
1868        (botSMDS->NbElements() != topSMDS->NbElements() ||
1869         botSMDS->NbNodes()    != topSMDS->NbNodes()))
1870   {
1871     MESSAGE("nb elem bot " << botSMDS->NbElements() <<
1872             " top " << ( topSMDS ? topSMDS->NbElements() : 0 ));
1873     MESSAGE("nb node bot " << botSMDS->NbNodes() <<
1874             " top " << ( topSMDS ? topSMDS->NbNodes() : 0 ));
1875     return toSM( error(TCom("Mesh on faces #") << botSM->GetId()
1876                        <<" and #"<< topSM->GetId() << " seems different" ));
1877   }
1878
1879   if ( 0/*needProject && !myProjectTriangles*/ )
1880     return toSM( error(TCom("Mesh on faces #") << botSM->GetId()
1881                        <<" and #"<< topSM->GetId() << " seems different" ));
1882   ///RETURN_BAD_RESULT("Need to project but not allowed");
1883
1884   if ( needProject )
1885   {
1886     return projectBottomToTop( bottomToTopTrsf );
1887   }
1888
1889   TopoDS_Face botFace = TopoDS::Face( myBlock.Shape( ID_BOT_FACE ));
1890   TopoDS_Face topFace = TopoDS::Face( myBlock.Shape( ID_TOP_FACE ));
1891   // associate top and bottom faces
1892   TAssocTool::TShapeShapeMap shape2ShapeMap;
1893   const bool sameTopo = 
1894     TAssocTool::FindSubShapeAssociation( botFace, myBlock.Mesh(),
1895                                          topFace, myBlock.Mesh(),
1896                                          shape2ShapeMap);
1897   if ( !sameTopo )
1898     for ( size_t iQ = 0; iQ < thePrism.myWallQuads.size(); ++iQ )
1899     {
1900       const Prism_3D::TQuadList& quadList = thePrism.myWallQuads[iQ];
1901       StdMeshers_FaceSidePtr      botSide = quadList.front()->side[ QUAD_BOTTOM_SIDE ];
1902       StdMeshers_FaceSidePtr      topSide = quadList.back ()->side[ QUAD_TOP_SIDE ];
1903       if ( botSide->NbEdges() == topSide->NbEdges() )
1904       {
1905         for ( int iE = 0; iE < botSide->NbEdges(); ++iE )
1906         {
1907           TAssocTool::InsertAssociation( botSide->Edge( iE ),
1908                                          topSide->Edge( iE ), shape2ShapeMap );
1909           TAssocTool::InsertAssociation( myHelper->IthVertex( 0, botSide->Edge( iE )),
1910                                          myHelper->IthVertex( 0, topSide->Edge( iE )),
1911                                          shape2ShapeMap );
1912         }
1913       }
1914       else
1915       {
1916         TopoDS_Vertex vb, vt;
1917         StdMeshers_FaceSidePtr sideB, sideT;
1918         vb = myHelper->IthVertex( 0, botSide->Edge( 0 ));
1919         vt = myHelper->IthVertex( 0, topSide->Edge( 0 ));
1920         sideB = quadList.front()->side[ QUAD_LEFT_SIDE ];
1921         sideT = quadList.back ()->side[ QUAD_LEFT_SIDE ];
1922         if ( vb.IsSame( sideB->FirstVertex() ) &&
1923              vt.IsSame( sideT->LastVertex() ))
1924         {
1925           TAssocTool::InsertAssociation( botSide->Edge( 0 ),
1926                                          topSide->Edge( 0 ), shape2ShapeMap );
1927           TAssocTool::InsertAssociation( vb, vt, shape2ShapeMap );
1928         }
1929         vb = myHelper->IthVertex( 1, botSide->Edge( botSide->NbEdges()-1 ));
1930         vt = myHelper->IthVertex( 1, topSide->Edge( topSide->NbEdges()-1 ));
1931         sideB = quadList.front()->side[ QUAD_RIGHT_SIDE ];
1932         sideT = quadList.back ()->side[ QUAD_RIGHT_SIDE ];
1933         if ( vb.IsSame( sideB->FirstVertex() ) &&
1934              vt.IsSame( sideT->LastVertex() ))
1935         {
1936           TAssocTool::InsertAssociation( botSide->Edge( botSide->NbEdges()-1 ),
1937                                          topSide->Edge( topSide->NbEdges()-1 ),
1938                                          shape2ShapeMap );
1939           TAssocTool::InsertAssociation( vb, vt, shape2ShapeMap );
1940         }
1941       }
1942     }
1943
1944   // Find matching nodes of top and bottom faces
1945   TNodeNodeMap n2nMap;
1946   if ( ! TAssocTool::FindMatchingNodesOnFaces( botFace, myBlock.Mesh(),
1947                                                topFace, myBlock.Mesh(),
1948                                                shape2ShapeMap, n2nMap ))
1949   {
1950     if ( sameTopo )
1951       return toSM( error(TCom("Mesh on faces #") << botSM->GetId()
1952                          <<" and #"<< topSM->GetId() << " seems different" ));
1953     else
1954       return toSM( error(TCom("Topology of faces #") << botSM->GetId()
1955                          <<" and #"<< topSM->GetId() << " seems different" ));
1956   }
1957
1958   // Fill myBotToColumnMap
1959
1960   int zSize = myBlock.VerticalSize();
1961   //TNode prevTNode;
1962   TNodeNodeMap::iterator bN_tN = n2nMap.begin();
1963   for ( ; bN_tN != n2nMap.end(); ++bN_tN )
1964   {
1965     const SMDS_MeshNode* botNode = bN_tN->first;
1966     const SMDS_MeshNode* topNode = bN_tN->second;
1967     if ( botNode->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE )
1968       continue; // wall columns are contained in myBlock
1969     // create node column
1970     Prism_3D::TNode bN( botNode );
1971     TNode2ColumnMap::iterator bN_col = 
1972       myBotToColumnMap.insert( make_pair ( bN, TNodeColumn() )).first;
1973     TNodeColumn & column = bN_col->second;
1974     column.resize( zSize );
1975     column.front() = botNode;
1976     column.back()  = topNode;
1977   }
1978   return true;
1979 }
1980
1981 //================================================================================
1982 /*!
1983  * \brief Remove quadrangles from the top face and
1984  * create triangles there by projection from the bottom
1985  * \retval bool - a success or not
1986  */
1987 //================================================================================
1988
1989 bool StdMeshers_Prism_3D::projectBottomToTop( const gp_Trsf & bottomToTopTrsf )
1990 {
1991   SMESHDS_Mesh*  meshDS = myBlock.MeshDS();
1992   SMESH_subMesh * botSM = myBlock.SubMesh( ID_BOT_FACE );
1993   SMESH_subMesh * topSM = myBlock.SubMesh( ID_TOP_FACE );
1994
1995   SMESHDS_SubMesh * botSMDS = botSM->GetSubMeshDS();
1996   SMESHDS_SubMesh * topSMDS = topSM->GetSubMeshDS();
1997
1998   if ( topSMDS && topSMDS->NbElements() > 0 )
1999     topSM->ComputeStateEngine( SMESH_subMesh::CLEAN );
2000
2001   const TopoDS_Face& botFace = TopoDS::Face( myBlock.Shape( ID_BOT_FACE )); // oriented within
2002   const TopoDS_Face& topFace = TopoDS::Face( myBlock.Shape( ID_TOP_FACE )); //    the 3D SHAPE
2003   int topFaceID = meshDS->ShapeToIndex( topFace );
2004
2005   SMESH_MesherHelper botHelper( *myHelper->GetMesh() );
2006   botHelper.SetSubShape( botFace );
2007   botHelper.ToFixNodeParameters( true );
2008   bool checkUV;
2009   SMESH_MesherHelper topHelper( *myHelper->GetMesh() );
2010   topHelper.SetSubShape( topFace );
2011   topHelper.ToFixNodeParameters( true );
2012   double distXYZ[4], fixTol = 10 * topHelper.MaxTolerance( topFace );
2013
2014   // Fill myBotToColumnMap
2015
2016   int zSize = myBlock.VerticalSize();
2017   Prism_3D::TNode prevTNode;
2018   SMDS_NodeIteratorPtr nIt = botSMDS->GetNodes();
2019   while ( nIt->more() )
2020   {
2021     const SMDS_MeshNode* botNode = nIt->next();
2022     const SMDS_MeshNode* topNode = 0;
2023     if ( botNode->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE )
2024       continue; // strange
2025
2026     Prism_3D::TNode bN( botNode );
2027     if ( bottomToTopTrsf.Form() == gp_Identity )
2028     {
2029       // compute bottom node params
2030       gp_XYZ paramHint(-1,-1,-1);
2031       if ( prevTNode.IsNeighbor( bN ))
2032       {
2033         paramHint = prevTNode.GetParams();
2034         // double tol = 1e-2 * ( prevTNode.GetCoords() - bN.GetCoords() ).Modulus();
2035         // myBlock.SetTolerance( Min( myBlock.GetTolerance(), tol ));
2036       }
2037       if ( !myBlock.ComputeParameters( bN.GetCoords(), bN.ChangeParams(),
2038                                        ID_BOT_FACE, paramHint ))
2039         return toSM( error(TCom("Can't compute normalized parameters for node ")
2040                            << botNode->GetID() << " on the face #"<< botSM->GetId() ));
2041       prevTNode = bN;
2042       // compute top node coords
2043       gp_XYZ topXYZ; gp_XY topUV;
2044       if ( !myBlock.FacePoint( ID_TOP_FACE, bN.GetParams(), topXYZ ) ||
2045            !myBlock.FaceUV   ( ID_TOP_FACE, bN.GetParams(), topUV ))
2046         return toSM( error(TCom("Can't compute coordinates "
2047                                 "by normalized parameters on the face #")<< topSM->GetId() ));
2048       topNode = meshDS->AddNode( topXYZ.X(),topXYZ.Y(),topXYZ.Z() );
2049       meshDS->SetNodeOnFace( topNode, topFaceID, topUV.X(), topUV.Y() );
2050     }
2051     else // use bottomToTopTrsf
2052     {
2053       gp_XYZ coords = bN.GetCoords();
2054       bottomToTopTrsf.Transforms( coords );
2055       topNode = meshDS->AddNode( coords.X(), coords.Y(), coords.Z() );
2056       gp_XY topUV = botHelper.GetNodeUV( botFace, botNode, 0, &checkUV );
2057       meshDS->SetNodeOnFace( topNode, topFaceID, topUV.X(), topUV.Y() );
2058       distXYZ[0] = -1;
2059       if ( topHelper.CheckNodeUV( topFace, topNode, topUV, fixTol, /*force=*/false, distXYZ ) &&
2060            distXYZ[0] > fixTol && distXYZ[0] < fixTol * 1e+3 )
2061         meshDS->MoveNode( topNode, distXYZ[1], distXYZ[2], distXYZ[3] ); // transform can be inaccurate
2062     }
2063     // create node column
2064     TNode2ColumnMap::iterator bN_col = 
2065       myBotToColumnMap.insert( make_pair ( bN, TNodeColumn() )).first;
2066     TNodeColumn & column = bN_col->second;
2067     column.resize( zSize );
2068     column.front() = botNode;
2069     column.back()  = topNode;
2070   }
2071
2072   // Create top faces
2073
2074   const bool oldSetElemsOnShape = myHelper->SetElementsOnShape( false );
2075
2076   // care of orientation;
2077   // if the bottom faces is orienetd OK then top faces must be reversed
2078   bool reverseTop = true;
2079   if ( myHelper->NbAncestors( botFace, *myBlock.Mesh(), TopAbs_SOLID ) > 1 )
2080     reverseTop = ! myHelper->IsReversedSubMesh( botFace );
2081   int iFrw, iRev, *iPtr = &( reverseTop ? iRev : iFrw );
2082
2083   // loop on bottom mesh faces
2084   SMDS_ElemIteratorPtr faceIt = botSMDS->GetElements();
2085   vector< const SMDS_MeshNode* > nodes;
2086   while ( faceIt->more() )
2087   {
2088     const SMDS_MeshElement* face = faceIt->next();
2089     if ( !face || face->GetType() != SMDSAbs_Face )
2090       continue;
2091
2092     // find top node in columns for each bottom node
2093     int nbNodes = face->NbCornerNodes();
2094     nodes.resize( nbNodes );
2095     for ( iFrw = 0, iRev = nbNodes-1; iFrw < nbNodes; ++iFrw, --iRev )
2096     {
2097       const SMDS_MeshNode* n = face->GetNode( *iPtr );
2098       if ( n->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE ) {
2099         TNode2ColumnMap::iterator bot_column = myBotToColumnMap.find( n );
2100         if ( bot_column == myBotToColumnMap.end() )
2101           return toSM( error(TCom("No nodes found above node ") << n->GetID() ));
2102         nodes[ iFrw ] = bot_column->second.back();
2103       }
2104       else {
2105         const TNodeColumn* column = myBlock.GetNodeColumn( n );
2106         if ( !column )
2107           return toSM( error(TCom("No side nodes found above node ") << n->GetID() ));
2108         nodes[ iFrw ] = column->back();
2109       }
2110     }
2111     SMDS_MeshElement* newFace = 0;
2112     switch ( nbNodes ) {
2113
2114     case 3: {
2115       newFace = myHelper->AddFace(nodes[0], nodes[1], nodes[2]);
2116       break;
2117       }
2118     case 4: {
2119       newFace = myHelper->AddFace( nodes[0], nodes[1], nodes[2], nodes[3] );
2120       break;
2121       }
2122     default:
2123       newFace = meshDS->AddPolygonalFace( nodes );
2124     }
2125     if ( newFace )
2126       meshDS->SetMeshElementOnShape( newFace, topFaceID );
2127   }
2128
2129   myHelper->SetElementsOnShape( oldSetElemsOnShape );  
2130
2131   return true;
2132 }
2133
2134 //=======================================================================
2135 //function : project2dMesh
2136 //purpose  : Project mesh faces from a source FACE of one prism (theSrcFace)
2137 //           to a source FACE of another prism (theTgtFace)
2138 //=======================================================================
2139
2140 bool StdMeshers_Prism_3D::project2dMesh(const TopoDS_Face& theSrcFace,
2141                                         const TopoDS_Face& theTgtFace)
2142 {
2143   TProjction2dAlgo* projector2D = TProjction2dAlgo::instance( this );
2144   projector2D->myHyp.SetSourceFace( theSrcFace );
2145   bool ok = projector2D->Compute( *myHelper->GetMesh(), theTgtFace );
2146
2147   SMESH_subMesh* tgtSM = myHelper->GetMesh()->GetSubMesh( theTgtFace );
2148   tgtSM->ComputeStateEngine       ( SMESH_subMesh::CHECK_COMPUTE_STATE );
2149   tgtSM->ComputeSubMeshStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
2150
2151   return ok;
2152 }
2153
2154 //================================================================================
2155 /*!
2156  * \brief Set projection coordinates of a node to a face and it's sub-shapes
2157  * \param faceID - the face given by in-block ID
2158  * \param params - node normalized parameters
2159  * \retval bool - is a success
2160  */
2161 //================================================================================
2162
2163 bool StdMeshers_Prism_3D::setFaceAndEdgesXYZ( const int faceID, const gp_XYZ& params, int z )
2164 {
2165   // find base and top edges of the face
2166   enum { BASE = 0, TOP, LEFT, RIGHT };
2167   vector< int > edgeVec; // 0-base, 1-top
2168   SMESH_Block::GetFaceEdgesIDs( faceID, edgeVec );
2169
2170   myBlock.EdgePoint( edgeVec[ BASE ], params, myShapeXYZ[ edgeVec[ BASE ]]);
2171   myBlock.EdgePoint( edgeVec[ TOP  ], params, myShapeXYZ[ edgeVec[ TOP ]]);
2172
2173   SHOWYXZ("\nparams ", params);
2174   SHOWYXZ("TOP is " <<edgeVec[ TOP ], myShapeXYZ[ edgeVec[ TOP]]);
2175   SHOWYXZ("BASE is "<<edgeVec[ BASE], myShapeXYZ[ edgeVec[ BASE]]);
2176
2177   if ( faceID == SMESH_Block::ID_Fx0z || faceID == SMESH_Block::ID_Fx1z )
2178   {
2179     myBlock.EdgePoint( edgeVec[ LEFT ], params, myShapeXYZ[ edgeVec[ LEFT ]]);
2180     myBlock.EdgePoint( edgeVec[ RIGHT ], params, myShapeXYZ[ edgeVec[ RIGHT ]]);
2181
2182     SHOWYXZ("VER "<<edgeVec[ LEFT], myShapeXYZ[ edgeVec[ LEFT]]);
2183     SHOWYXZ("VER "<<edgeVec[ RIGHT], myShapeXYZ[ edgeVec[ RIGHT]]);
2184   }
2185   myBlock.FacePoint( faceID, params, myShapeXYZ[ faceID ]);
2186   SHOWYXZ("FacePoint "<<faceID, myShapeXYZ[ faceID]);
2187
2188   return true;
2189 }
2190
2191 //=======================================================================
2192 //function : toSM
2193 //purpose  : If (!isOK), sets the error to a sub-mesh of a current SOLID
2194 //=======================================================================
2195
2196 bool StdMeshers_Prism_3D::toSM( bool isOK )
2197 {
2198   if ( mySetErrorToSM &&
2199        !isOK &&
2200        myHelper &&
2201        !myHelper->GetSubShape().IsNull() &&
2202        myHelper->GetSubShape().ShapeType() == TopAbs_SOLID)
2203   {
2204     SMESH_subMesh* sm = myHelper->GetMesh()->GetSubMesh( myHelper->GetSubShape() );
2205     sm->GetComputeError() = this->GetComputeError();
2206     // clear error in order not to return it twice
2207     _error = COMPERR_OK;
2208     _comment.clear();
2209   }
2210   return isOK;
2211 }
2212
2213 //=======================================================================
2214 //function : shapeID
2215 //purpose  : Return index of a shape
2216 //=======================================================================
2217
2218 int StdMeshers_Prism_3D::shapeID( const TopoDS_Shape& S )
2219 {
2220   if ( S.IsNull() ) return 0;
2221   if ( !myHelper  ) return -3;
2222   return myHelper->GetMeshDS()->ShapeToIndex( S );
2223 }
2224
2225 namespace // utils used by StdMeshers_Prism_3D::IsApplicable()
2226 {
2227   struct EdgeWithNeighbors
2228   {
2229     TopoDS_Edge _edge;
2230     int         _iL, _iR;
2231     EdgeWithNeighbors(const TopoDS_Edge& E, int iE, int nbE, int shift = 0 ):
2232       _edge( E ),
2233       _iL( SMESH_MesherHelper::WrapIndex( iE-1, nbE ) + shift ),
2234       _iR( SMESH_MesherHelper::WrapIndex( iE+1, nbE ) + shift )
2235     {
2236     }
2237     EdgeWithNeighbors() {}
2238   };
2239   struct PrismSide
2240   {
2241     TopoDS_Face                 _face;
2242     TopTools_IndexedMapOfShape *_faces; // pointer because its copy constructor is private
2243     TopoDS_Edge                 _topEdge;
2244     vector< EdgeWithNeighbors >*_edges;
2245     int                         _iBotEdge;
2246     vector< bool >              _isCheckedEdge;
2247     int                         _nbCheckedEdges; // nb of EDGEs whose location is defined
2248     PrismSide                  *_leftSide;
2249     PrismSide                  *_rightSide;
2250     const TopoDS_Edge& Edge( int i ) const
2251     {
2252       return (*_edges)[ i ]._edge;
2253     }
2254     int FindEdge( const TopoDS_Edge& E ) const
2255     {
2256       for ( size_t i = 0; i < _edges->size(); ++i )
2257         if ( E.IsSame( Edge( i ))) return i;
2258       return -1;
2259     }
2260   };
2261   //--------------------------------------------------------------------------------
2262   /*!
2263    * \brief Return ordered edges of a face
2264    */
2265   bool getEdges( const TopoDS_Face&            face,
2266                  vector< EdgeWithNeighbors > & edges,
2267                  const bool                    noHolesAllowed)
2268   {
2269     list< TopoDS_Edge > ee;
2270     list< int >         nbEdgesInWires;
2271     int nbW = SMESH_Block::GetOrderedEdges( face, ee, nbEdgesInWires );
2272     if ( nbW > 1 && noHolesAllowed )
2273       return false;
2274
2275     int iE, nbTot = 0;
2276     list< TopoDS_Edge >::iterator e = ee.begin();
2277     list< int >::iterator       nbE = nbEdgesInWires.begin();
2278     for ( ; nbE != nbEdgesInWires.end(); ++nbE )
2279       for ( iE = 0; iE < *nbE; ++e, ++iE )
2280         if ( SMESH_Algo::isDegenerated( *e ))
2281         {
2282           ee.erase( e );
2283           --(*nbE);
2284           --iE;
2285         }
2286         else
2287         {
2288           e->Orientation( TopAbs_FORWARD ); // for operator==() to work
2289         }
2290
2291     edges.clear();
2292     e = ee.begin();
2293     for ( nbE = nbEdgesInWires.begin(); nbE != nbEdgesInWires.end(); ++nbE )
2294     {
2295       for ( iE = 0; iE < *nbE; ++e, ++iE )
2296         edges.push_back( EdgeWithNeighbors( *e, iE, *nbE, nbTot ));
2297       nbTot += *nbE;
2298     }
2299     return edges.size();
2300   }
2301   //--------------------------------------------------------------------------------
2302   /*!
2303    * \brief Return another faces sharing an edge
2304    */
2305   const TopoDS_Shape & getAnotherFace( const TopoDS_Face& face,
2306                                        const TopoDS_Edge& edge,
2307                                        TopTools_IndexedDataMapOfShapeListOfShape& facesOfEdge)
2308   {
2309     TopTools_ListIteratorOfListOfShape faceIt( facesOfEdge.FindFromKey( edge ));
2310     for ( ; faceIt.More(); faceIt.Next() )
2311       if ( !face.IsSame( faceIt.Value() ))
2312         return faceIt.Value();
2313     return face;
2314   }
2315 }
2316
2317 //================================================================================
2318 /*!
2319  * \brief Return true if the algorithm can mesh this shape
2320  *  \param [in] aShape - shape to check
2321  *  \param [in] toCheckAll - if true, this check returns OK if all shapes are OK,
2322  *              else, returns OK if at least one shape is OK
2323  */
2324 //================================================================================
2325
2326 bool StdMeshers_Prism_3D::IsApplicable(const TopoDS_Shape & shape, bool toCheckAll)
2327 {
2328   TopExp_Explorer sExp( shape, TopAbs_SOLID );
2329   if ( !sExp.More() )
2330     return false;
2331
2332   for ( ; sExp.More(); sExp.Next() )
2333   {
2334     // check nb shells
2335     TopoDS_Shape shell;
2336     TopExp_Explorer shExp( sExp.Current(), TopAbs_SHELL );
2337     if ( shExp.More() ) {
2338       shell = shExp.Current();
2339       shExp.Next();
2340       if ( shExp.More() )
2341         shell.Nullify();
2342     }
2343     if ( shell.IsNull() ) {
2344       if ( toCheckAll ) return false;
2345       continue;
2346     }
2347     // get all faces
2348     TopTools_IndexedMapOfShape allFaces;
2349     TopExp::MapShapes( shell, TopAbs_FACE, allFaces );
2350     if ( allFaces.Extent() < 3 ) {
2351       if ( toCheckAll ) return false;
2352       continue;
2353     }
2354     // is a box?
2355     if ( allFaces.Extent() == 6 )
2356     {
2357       TopTools_IndexedMapOfOrientedShape map;
2358       bool isBox = SMESH_Block::FindBlockShapes( TopoDS::Shell( shell ),
2359                                                  TopoDS_Vertex(), TopoDS_Vertex(), map );
2360       if ( isBox ) {
2361         if ( !toCheckAll ) return true;
2362         continue;
2363       }
2364     }
2365 #ifdef _DEBUG_
2366     TopTools_IndexedMapOfShape allShapes;
2367     TopExp::MapShapes( shape, allShapes );
2368 #endif
2369
2370     TopTools_IndexedDataMapOfShapeListOfShape facesOfEdge;
2371     TopTools_ListIteratorOfListOfShape faceIt;
2372     TopExp::MapShapesAndAncestors( sExp.Current(), TopAbs_EDGE, TopAbs_FACE , facesOfEdge );
2373     if ( facesOfEdge.IsEmpty() ) {
2374       if ( toCheckAll ) return false;
2375       continue;
2376     }
2377
2378     typedef vector< EdgeWithNeighbors > TEdgeWithNeighborsVec;
2379     vector< TEdgeWithNeighborsVec > faceEdgesVec( allFaces.Extent() + 1 );
2380     TopTools_IndexedMapOfShape* facesOfSide = new TopTools_IndexedMapOfShape[ faceEdgesVec.size() ];
2381     SMESHUtils::ArrayDeleter<TopTools_IndexedMapOfShape> delFacesOfSide( facesOfSide );
2382
2383     // try to use each face as a bottom one
2384     bool prismDetected = false;
2385     for ( int iF = 1; iF < allFaces.Extent() && !prismDetected; ++iF )
2386     {
2387       const TopoDS_Face& botF = TopoDS::Face( allFaces( iF ));
2388
2389       TEdgeWithNeighborsVec& botEdges = faceEdgesVec[ iF ];
2390       if ( botEdges.empty() )
2391       {
2392         if ( !getEdges( botF, botEdges, /*noHoles=*/false ))
2393           break;
2394         if ( allFaces.Extent()-1 <= (int) botEdges.size() )
2395           continue; // all faces are adjacent to botF - no top FACE
2396       }
2397       // init data of side FACEs
2398       vector< PrismSide > sides( botEdges.size() );
2399       for ( int iS = 0; iS < botEdges.size(); ++iS )
2400       {
2401         sides[ iS ]._topEdge = botEdges[ iS ]._edge;
2402         sides[ iS ]._face    = botF;
2403         sides[ iS ]._leftSide  = & sides[ botEdges[ iS ]._iR ];
2404         sides[ iS ]._rightSide = & sides[ botEdges[ iS ]._iL ];
2405         sides[ iS ]._faces = & facesOfSide[ iS ];
2406         sides[ iS ]._faces->Clear();
2407       }
2408
2409       bool isOK = true; // ok for a current botF
2410       bool isAdvanced = true;
2411       int nbFoundSideFaces = 0;
2412       for ( int iLoop = 0; isOK && isAdvanced; ++iLoop )
2413       {
2414         isAdvanced = false;
2415         for ( size_t iS = 0; iS < sides.size() && isOK; ++iS )
2416         {
2417           PrismSide& side = sides[ iS ];
2418           if ( side._face.IsNull() )
2419             continue;
2420           if ( side._topEdge.IsNull() )
2421           {
2422             // find vertical EDGEs --- EGDEs shared with neighbor side FACEs
2423             for ( int is2nd = 0; is2nd < 2 && isOK; ++is2nd ) // 2 adjacent neighbors
2424             {
2425               int di = is2nd ? 1 : -1;
2426               const PrismSide* adjSide = is2nd ? side._rightSide : side._leftSide;
2427               for ( size_t i = 1; i < side._edges->size(); ++i )
2428               {
2429                 int iE = SMESH_MesherHelper::WrapIndex( i*di + side._iBotEdge, side._edges->size());
2430                 if ( side._isCheckedEdge[ iE ] ) continue;
2431                 const TopoDS_Edge&      vertE = side.Edge( iE );
2432                 const TopoDS_Shape& neighborF = getAnotherFace( side._face, vertE, facesOfEdge );
2433                 bool isEdgeShared = adjSide->_faces->Contains( neighborF );
2434                 if ( isEdgeShared )
2435                 {
2436                   isAdvanced = true;
2437                   side._isCheckedEdge[ iE ] = true;
2438                   side._nbCheckedEdges++;
2439                   int nbNotCheckedE = side._edges->size() - side._nbCheckedEdges;
2440                   if ( nbNotCheckedE == 1 )
2441                     break;
2442                 }
2443                 else
2444                 {
2445                   if ( i == 1 && iLoop == 0 ) isOK = false;
2446                   break;
2447                 }
2448               }
2449             }
2450             // find a top EDGE
2451             int nbNotCheckedE = side._edges->size() - side._nbCheckedEdges;
2452             if ( nbNotCheckedE == 1 )
2453             {
2454               vector<bool>::iterator ii = std::find( side._isCheckedEdge.begin(),
2455                                                      side._isCheckedEdge.end(), false );
2456               if ( ii != side._isCheckedEdge.end() )
2457               {
2458                 size_t iE = std::distance( side._isCheckedEdge.begin(), ii );
2459                 side._topEdge = side.Edge( iE );
2460               }
2461             }
2462             isOK = ( nbNotCheckedE >= 1 );
2463           }
2464           else //if ( !side._topEdge.IsNull() )
2465           {
2466             // get a next face of a side
2467             const TopoDS_Shape& f = getAnotherFace( side._face, side._topEdge, facesOfEdge );
2468             side._faces->Add( f );
2469             bool stop = false;
2470             if ( f.IsSame( side._face ) || // _topEdge is a seam
2471                  SMESH_MesherHelper::Count( f, TopAbs_WIRE, false ) != 1 )
2472             {
2473               stop = true;
2474             }
2475             else if ( side._leftSide != & side ) // not closed side face
2476             {
2477               if ( side._leftSide->_faces->Contains( f ))
2478               {
2479                 stop = true;
2480                 side._leftSide->_face.Nullify();
2481                 side._leftSide->_topEdge.Nullify();
2482               }
2483               if ( side._rightSide->_faces->Contains( f ))
2484               {
2485                 stop = true;
2486                 side._rightSide->_face.Nullify();
2487                 side._rightSide->_topEdge.Nullify();
2488               }
2489             }
2490             if ( stop )
2491             {
2492               side._face.Nullify();
2493               side._topEdge.Nullify();
2494               continue;
2495             }
2496             side._face = TopoDS::Face( f );
2497             int faceID = allFaces.FindIndex( side._face );
2498             side._edges = & faceEdgesVec[ faceID ];
2499             if ( side._edges->empty() )
2500               if ( !getEdges( side._face, * side._edges, /*noHoles=*/true ))
2501                 break;
2502             const int nbE = side._edges->size();
2503             if ( nbE >= 4 )
2504             {
2505               isAdvanced = true;
2506               ++nbFoundSideFaces;
2507               side._iBotEdge = side.FindEdge( side._topEdge );
2508               side._isCheckedEdge.clear();
2509               side._isCheckedEdge.resize( nbE, false );
2510               side._isCheckedEdge[ side._iBotEdge ] = true;
2511               side._nbCheckedEdges = 1; // bottom EDGE is known
2512             }
2513             side._topEdge.Nullify();
2514             isOK = ( !side._edges->empty() || side._faces->Extent() > 1 );
2515
2516           } //if ( !side._topEdge.IsNull() )
2517
2518         } // loop on prism sides
2519
2520         if ( nbFoundSideFaces > allFaces.Extent() )
2521         {
2522           isOK = false;
2523         }
2524         if ( iLoop > allFaces.Extent() * 10 )
2525         {
2526           isOK = false;
2527 #ifdef _DEBUG_
2528           cerr << "BUG: infinite loop in StdMeshers_Prism_3D::IsApplicable()" << endl;
2529 #endif
2530         }
2531       } // while isAdvanced
2532
2533       if ( isOK && sides[0]._faces->Extent() > 1 )
2534       {
2535         const int nbFaces = sides[0]._faces->Extent();
2536         if ( botEdges.size() == 1 ) // cylinder
2537         {
2538           prismDetected = ( nbFaces == allFaces.Extent()-1 );
2539         }
2540         else
2541         {
2542           const TopoDS_Shape& topFace = sides[0]._faces->FindKey( nbFaces );
2543           size_t iS;
2544           for ( iS = 1; iS < sides.size(); ++iS )
2545             if ( !sides[ iS ]._faces->Contains( topFace ))
2546               break;
2547           prismDetected = ( iS == sides.size() );
2548         }
2549       }
2550     } // loop on allFaces
2551
2552     if ( !prismDetected && toCheckAll ) return false;
2553     if ( prismDetected && !toCheckAll ) return true;
2554
2555   } // loop on solids
2556
2557   return toCheckAll;
2558 }
2559
2560 namespace Prism_3D
2561 {
2562   //================================================================================
2563   /*!
2564    * \brief Return true if this node and other one belong to one face
2565    */
2566   //================================================================================
2567
2568   bool Prism_3D::TNode::IsNeighbor( const Prism_3D::TNode& other ) const
2569   {
2570     if ( !other.myNode || !myNode ) return false;
2571
2572     SMDS_ElemIteratorPtr fIt = other.myNode->GetInverseElementIterator(SMDSAbs_Face);
2573     while ( fIt->more() )
2574       if ( fIt->next()->GetNodeIndex( myNode ) >= 0 )
2575         return true;
2576     return false;
2577   }
2578
2579   //================================================================================
2580   /*!
2581    * \brief Prism initialization
2582    */
2583   //================================================================================
2584
2585   void TPrismTopo::Clear()
2586   {
2587     myShape3D.Nullify();
2588     myTop.Nullify();
2589     myBottom.Nullify();
2590     myWallQuads.clear();
2591     myBottomEdges.clear();
2592     myNbEdgesInWires.clear();
2593     myWallQuads.clear();
2594   }
2595
2596   //================================================================================
2597   /*!
2598    * \brief Set upside-down
2599    */
2600   //================================================================================
2601
2602   void TPrismTopo::SetUpsideDown()
2603   {
2604     std::swap( myBottom, myTop );
2605     myBottomEdges.clear();
2606     std::reverse( myBottomEdges.begin(), myBottomEdges.end() );
2607     for ( size_t i = 0; i < myWallQuads.size(); ++i )
2608     {
2609       myWallQuads[i].reverse();
2610       TQuadList::iterator q = myWallQuads[i].begin();
2611       for ( ; q != myWallQuads[i].end(); ++q )
2612       {
2613         (*q)->shift( 2, /*keepUnitOri=*/true );
2614       }
2615       myBottomEdges.push_back( myWallQuads[i].front()->side[ QUAD_BOTTOM_SIDE ].grid->Edge(0) );
2616     }
2617   }
2618
2619 } // namespace Prism_3D
2620
2621 //================================================================================
2622 /*!
2623  * \brief Constructor. Initialization is needed
2624  */
2625 //================================================================================
2626
2627 StdMeshers_PrismAsBlock::StdMeshers_PrismAsBlock()
2628 {
2629   mySide = 0;
2630 }
2631
2632 StdMeshers_PrismAsBlock::~StdMeshers_PrismAsBlock()
2633 {
2634   Clear();
2635 }
2636 void StdMeshers_PrismAsBlock::Clear()
2637 {
2638   myHelper = 0;
2639   myShapeIDMap.Clear();
2640   myError.reset();
2641
2642   if ( mySide ) {
2643     delete mySide; mySide = 0;
2644   }
2645   myParam2ColumnMaps.clear();
2646   myShapeIndex2ColumnMap.clear();
2647 }
2648
2649 //=======================================================================
2650 //function : initPrism
2651 //purpose  : Analyse shape geometry and mesh.
2652 //           If there are triangles on one of faces, it becomes 'bottom'.
2653 //           thePrism.myBottom can be already set up.
2654 //=======================================================================
2655
2656 bool StdMeshers_Prism_3D::initPrism(Prism_3D::TPrismTopo& thePrism,
2657                                     const TopoDS_Shape&   shape3D)
2658 {
2659   myHelper->SetSubShape( shape3D );
2660
2661   SMESH_subMesh* mainSubMesh = myHelper->GetMesh()->GetSubMeshContaining( shape3D );
2662   if ( !mainSubMesh ) return toSM( error(COMPERR_BAD_INPUT_MESH,"Null submesh of shape3D"));
2663
2664   // detect not-quad FACE sub-meshes of the 3D SHAPE
2665   list< SMESH_subMesh* > notQuadGeomSubMesh;
2666   list< SMESH_subMesh* > notQuadElemSubMesh;
2667   int nbFaces = 0;
2668   //
2669   SMESH_subMesh* anyFaceSM = 0;
2670   SMESH_subMeshIteratorPtr smIt = mainSubMesh->getDependsOnIterator(false,true);
2671   while ( smIt->more() )
2672   {
2673     SMESH_subMesh* sm = smIt->next();
2674     const TopoDS_Shape& face = sm->GetSubShape();
2675     if      ( face.ShapeType() > TopAbs_FACE ) break;
2676     else if ( face.ShapeType() < TopAbs_FACE ) continue;
2677     nbFaces++;
2678     anyFaceSM = sm;
2679
2680     // is quadrangle FACE?
2681     list< TopoDS_Edge > orderedEdges;
2682     list< int >         nbEdgesInWires;
2683     int nbWires = SMESH_Block::GetOrderedEdges( TopoDS::Face( face ), orderedEdges,
2684                                                 nbEdgesInWires );
2685     if ( nbWires != 1 || nbEdgesInWires.front() != 4 )
2686       notQuadGeomSubMesh.push_back( sm );
2687
2688     // look for not quadrangle mesh elements
2689     if ( SMESHDS_SubMesh* smDS = sm->GetSubMeshDS() )
2690       if ( !myHelper->IsSameElemGeometry( smDS, SMDSGeom_QUADRANGLE ))
2691         notQuadElemSubMesh.push_back( sm );
2692   }
2693
2694   int nbNotQuadMeshed = notQuadElemSubMesh.size();
2695   int       nbNotQuad = notQuadGeomSubMesh.size();
2696   bool     hasNotQuad = ( nbNotQuad || nbNotQuadMeshed );
2697
2698   // detect bad cases
2699   if ( nbNotQuadMeshed > 2 )
2700   {
2701     return toSM( error(COMPERR_BAD_INPUT_MESH,
2702                        TCom("More than 2 faces with not quadrangle elements: ")
2703                        <<nbNotQuadMeshed));
2704   }
2705   if ( nbNotQuad > 2 || !thePrism.myBottom.IsNull() )
2706   {
2707     // Issue 0020843 - one of side FACEs is quasi-quadrilateral (not 4 EDGEs).
2708     // Remove from notQuadGeomSubMesh faces meshed with regular grid
2709     int nbQuasiQuads = removeQuasiQuads( notQuadGeomSubMesh, myHelper,
2710                                          TQuadrangleAlgo::instance(this,myHelper) );
2711     nbNotQuad -= nbQuasiQuads;
2712     if ( nbNotQuad > 2 )
2713       return toSM( error(COMPERR_BAD_SHAPE,
2714                          TCom("More than 2 not quadrilateral faces: ") <<nbNotQuad));
2715     hasNotQuad = ( nbNotQuad || nbNotQuadMeshed );
2716   }
2717
2718   // Analyse mesh and topology of FACEs: choose the bottom sub-mesh.
2719   // If there are not quadrangle FACEs, they are top and bottom ones.
2720   // Not quadrangle FACEs must be only on top and bottom.
2721
2722   SMESH_subMesh * botSM = 0;
2723   SMESH_subMesh * topSM = 0;
2724
2725   if ( hasNotQuad ) // can choose a bottom FACE
2726   {
2727     if ( nbNotQuadMeshed > 0 ) botSM = notQuadElemSubMesh.front();
2728     else                       botSM = notQuadGeomSubMesh.front();
2729     if ( nbNotQuadMeshed > 1 ) topSM = notQuadElemSubMesh.back();
2730     else if ( nbNotQuad  > 1 ) topSM = notQuadGeomSubMesh.back();
2731
2732     if ( topSM == botSM ) {
2733       if ( nbNotQuadMeshed > 1 ) topSM = notQuadElemSubMesh.front();
2734       else                       topSM = notQuadGeomSubMesh.front();
2735     }
2736
2737     // detect mesh triangles on wall FACEs
2738     if ( nbNotQuad == 2 && nbNotQuadMeshed > 0 ) {
2739       bool ok = false;
2740       if ( nbNotQuadMeshed == 1 )
2741         ok = ( find( notQuadGeomSubMesh.begin(),
2742                      notQuadGeomSubMesh.end(), botSM ) != notQuadGeomSubMesh.end() );
2743       else
2744         ok = ( notQuadGeomSubMesh == notQuadElemSubMesh );
2745       if ( !ok )
2746         return toSM( error(COMPERR_BAD_INPUT_MESH,
2747                            "Side face meshed with not quadrangle elements"));
2748     }
2749   }
2750
2751   thePrism.myNotQuadOnTop = ( nbNotQuadMeshed > 1 );
2752
2753   // use thePrism.myBottom
2754   if ( !thePrism.myBottom.IsNull() )
2755   {
2756     if ( botSM ) {
2757       if ( ! botSM->GetSubShape().IsSame( thePrism.myBottom )) {
2758         std::swap( botSM, topSM );
2759         if ( !botSM || ! botSM->GetSubShape().IsSame( thePrism.myBottom ))
2760           return toSM( error( COMPERR_BAD_INPUT_MESH,
2761                               "Incompatible non-structured sub-meshes"));
2762       }
2763     }
2764     else {
2765       botSM = myHelper->GetMesh()->GetSubMesh( thePrism.myBottom );
2766     }
2767   }
2768   else if ( !botSM ) // find a proper bottom
2769   {
2770     // composite walls or not prism shape
2771     for ( TopExp_Explorer f( shape3D, TopAbs_FACE ); f.More(); f.Next() )
2772     {
2773       int minNbFaces = 2 + myHelper->Count( f.Current(), TopAbs_EDGE, false);
2774       if ( nbFaces >= minNbFaces)
2775       {
2776         thePrism.Clear();
2777         thePrism.myBottom = TopoDS::Face( f.Current() );
2778         if ( initPrism( thePrism, shape3D ))
2779           return true;
2780       }
2781       return toSM( error( COMPERR_BAD_SHAPE ));
2782     }
2783   }
2784
2785   // find vertex 000 - the one with smallest coordinates (for easy DEBUG :-)
2786   TopoDS_Vertex V000;
2787   double minVal = DBL_MAX, minX, val;
2788   for ( TopExp_Explorer exp( botSM->GetSubShape(), TopAbs_VERTEX );
2789         exp.More(); exp.Next() )
2790   {
2791     const TopoDS_Vertex& v = TopoDS::Vertex( exp.Current() );
2792     gp_Pnt P = BRep_Tool::Pnt( v );
2793     val = P.X() + P.Y() + P.Z();
2794     if ( val < minVal || ( val == minVal && P.X() < minX )) {
2795       V000 = v;
2796       minVal = val;
2797       minX = P.X();
2798     }
2799   }
2800
2801   thePrism.myShape3D = shape3D;
2802   if ( thePrism.myBottom.IsNull() )
2803     thePrism.myBottom  = TopoDS::Face( botSM->GetSubShape() );
2804   thePrism.myBottom.Orientation( myHelper->GetSubShapeOri( shape3D,
2805                                                            thePrism.myBottom ));
2806   // Get ordered bottom edges
2807   TopoDS_Face reverseBottom = // to have order of top EDGEs as in the top FACE
2808     TopoDS::Face( thePrism.myBottom.Reversed() );
2809   SMESH_Block::GetOrderedEdges( reverseBottom,
2810                                 thePrism.myBottomEdges,
2811                                 thePrism.myNbEdgesInWires, V000 );
2812
2813   // Get Wall faces corresponding to the ordered bottom edges and the top FACE
2814   if ( !getWallFaces( thePrism, nbFaces ))
2815     return false; //toSM( error(COMPERR_BAD_SHAPE, "Can't find side faces"));
2816
2817   if ( topSM )
2818   {
2819     if ( !thePrism.myTop.IsSame( topSM->GetSubShape() ))
2820       return toSM( error
2821                    (notQuadGeomSubMesh.empty() ? COMPERR_BAD_INPUT_MESH : COMPERR_BAD_SHAPE,
2822                     "Non-quadrilateral faces are not opposite"));
2823
2824     // check that the found top and bottom FACEs are opposite
2825     list< TopoDS_Edge >::iterator edge = thePrism.myBottomEdges.begin();
2826     for ( ; edge != thePrism.myBottomEdges.end(); ++edge )
2827       if ( myHelper->IsSubShape( *edge, thePrism.myTop ))
2828         return toSM( error
2829                      (notQuadGeomSubMesh.empty() ? COMPERR_BAD_INPUT_MESH : COMPERR_BAD_SHAPE,
2830                       "Non-quadrilateral faces are not opposite"));
2831   }
2832
2833   if ( thePrism.myBottomEdges.size() > thePrism.myWallQuads.size() )
2834   {
2835     // composite bottom sides => set thePrism upside-down
2836     thePrism.SetUpsideDown();
2837   }
2838
2839   return true;
2840 }
2841
2842 //================================================================================
2843 /*!
2844  * \brief Initialization.
2845  * \param helper - helper loaded with mesh and 3D shape
2846  * \param thePrism - a prism data
2847  * \retval bool - false if a mesh or a shape are KO
2848  */
2849 //================================================================================
2850
2851 bool StdMeshers_PrismAsBlock::Init(SMESH_MesherHelper*         helper,
2852                                    const Prism_3D::TPrismTopo& thePrism)
2853 {
2854   myHelper = helper;
2855   SMESHDS_Mesh* meshDS = myHelper->GetMeshDS();
2856   SMESH_Mesh*     mesh = myHelper->GetMesh();
2857
2858   if ( mySide ) {
2859     delete mySide; mySide = 0;
2860   }
2861   vector< TSideFace* >         sideFaces( NB_WALL_FACES, 0 );
2862   vector< pair< double, double> > params( NB_WALL_FACES );
2863   mySide = new TSideFace( *mesh, sideFaces, params );
2864
2865
2866   SMESH_Block::init();
2867   myShapeIDMap.Clear();
2868   myShapeIndex2ColumnMap.clear();
2869   
2870   int wallFaceIds[ NB_WALL_FACES ] = { // to walk around a block
2871     SMESH_Block::ID_Fx0z, SMESH_Block::ID_F1yz,
2872     SMESH_Block::ID_Fx1z, SMESH_Block::ID_F0yz
2873   };
2874
2875   myError = SMESH_ComputeError::New();
2876
2877   myNotQuadOnTop = thePrism.myNotQuadOnTop;
2878
2879   // Find columns of wall nodes and calculate edges' lengths
2880   // --------------------------------------------------------
2881
2882   myParam2ColumnMaps.clear();
2883   myParam2ColumnMaps.resize( thePrism.myBottomEdges.size() ); // total nb edges
2884
2885   size_t iE, nbEdges = thePrism.myNbEdgesInWires.front(); // nb outer edges
2886   vector< double > edgeLength( nbEdges );
2887   multimap< double, int > len2edgeMap;
2888
2889   // for each EDGE: either split into several parts, or join with several next EDGEs
2890   vector<int> nbSplitPerEdge( nbEdges, 0 );
2891   vector<int> nbUnitePerEdge( nbEdges, 0 ); // -1 means "joined to a previous"
2892
2893   // consider continuous straight EDGEs as one side
2894   const int nbSides = countNbSides( thePrism, nbUnitePerEdge, edgeLength );
2895
2896   list< TopoDS_Edge >::const_iterator edgeIt = thePrism.myBottomEdges.begin();
2897   for ( iE = 0; iE < nbEdges; ++iE, ++edgeIt )
2898   {
2899     TParam2ColumnMap & faceColumns = myParam2ColumnMaps[ iE ];
2900
2901     Prism_3D::TQuadList::const_iterator quad = thePrism.myWallQuads[ iE ].begin();
2902     for ( ; quad != thePrism.myWallQuads[ iE ].end(); ++quad )
2903     {
2904       const TopoDS_Edge& quadBot = (*quad)->side[ QUAD_BOTTOM_SIDE ].grid->Edge( 0 );
2905       if ( !myHelper->LoadNodeColumns( faceColumns, (*quad)->face, quadBot, meshDS ))
2906         return error(COMPERR_BAD_INPUT_MESH, TCom("Can't find regular quadrangle mesh ")
2907                      << "on a side face #" << MeshDS()->ShapeToIndex( (*quad)->face ));
2908     }
2909     SHOWYXZ("\np1 F " <<iE, gpXYZ(faceColumns.begin()->second.front() ));
2910     SHOWYXZ("p2 F "   <<iE, gpXYZ(faceColumns.rbegin()->second.front() ));
2911     SHOWYXZ("V First "<<iE, BRep_Tool::Pnt( TopExp::FirstVertex(*edgeIt,true )));
2912
2913     if ( nbSides < NB_WALL_FACES ) // fill map used to split faces
2914       len2edgeMap.insert( make_pair( edgeLength[ iE ], iE )); // sort edges by length
2915   }
2916   // Load columns of internal edges (forming holes)
2917   // and fill map ShapeIndex to TParam2ColumnMap for them
2918   for ( ; edgeIt != thePrism.myBottomEdges.end() ; ++edgeIt, ++iE )
2919   {
2920     TParam2ColumnMap & faceColumns = myParam2ColumnMaps[ iE ];
2921
2922     Prism_3D::TQuadList::const_iterator quad = thePrism.myWallQuads[ iE ].begin();
2923     for ( ; quad != thePrism.myWallQuads[ iE ].end(); ++quad )
2924     {
2925       const TopoDS_Edge& quadBot = (*quad)->side[ QUAD_BOTTOM_SIDE ].grid->Edge( 0 );
2926       if ( !myHelper->LoadNodeColumns( faceColumns, (*quad)->face, quadBot, meshDS ))
2927         return error(COMPERR_BAD_INPUT_MESH, TCom("Can't find regular quadrangle mesh ")
2928                      << "on a side face #" << MeshDS()->ShapeToIndex( (*quad)->face ));
2929     }
2930     // edge columns
2931     int id = MeshDS()->ShapeToIndex( *edgeIt );
2932     bool isForward = true; // meaningless for intenal wires
2933     myShapeIndex2ColumnMap[ id ] = make_pair( & faceColumns, isForward );
2934     // columns for vertices
2935     // 1
2936     const SMDS_MeshNode* n0 = faceColumns.begin()->second.front();
2937     id = n0->getshapeId();
2938     myShapeIndex2ColumnMap[ id ] = make_pair( & faceColumns, isForward );
2939     // 2
2940     const SMDS_MeshNode* n1 = faceColumns.rbegin()->second.front();
2941     id = n1->getshapeId();
2942     myShapeIndex2ColumnMap[ id ] = make_pair( & faceColumns, isForward );
2943
2944     // SHOWYXZ("\np1 F " <<iE, gpXYZ(faceColumns.begin()->second.front() ));
2945     // SHOWYXZ("p2 F "   <<iE, gpXYZ(faceColumns.rbegin()->second.front() ));
2946     // SHOWYXZ("V First "<<iE, BRep_Tool::Pnt( TopExp::FirstVertex(*edgeIt,true )));
2947   }
2948
2949   // Create 4 wall faces of a block
2950   // -------------------------------
2951
2952   if ( nbSides <= NB_WALL_FACES ) // ************* Split faces if necessary
2953   {
2954     if ( nbSides != NB_WALL_FACES ) // define how to split
2955     {
2956       if ( len2edgeMap.size() != nbEdges )
2957         RETURN_BAD_RESULT("Uniqueness of edge lengths not assured");
2958
2959       multimap< double, int >::reverse_iterator maxLen_i = len2edgeMap.rbegin();
2960       multimap< double, int >::reverse_iterator midLen_i = ++len2edgeMap.rbegin();
2961
2962       double maxLen = maxLen_i->first;
2963       double midLen = ( len2edgeMap.size() == 1 ) ? 0 : midLen_i->first;
2964       switch ( nbEdges ) {
2965       case 1: // 0-th edge is split into 4 parts
2966         nbSplitPerEdge[ 0 ] = 4;
2967         break;
2968       case 2: // either the longest edge is split into 3 parts, or both edges into halves
2969         if ( maxLen / 3 > midLen / 2 ) {
2970           nbSplitPerEdge[ maxLen_i->second ] = 3;
2971         }
2972         else {
2973           nbSplitPerEdge[ maxLen_i->second ] = 2;
2974           nbSplitPerEdge[ midLen_i->second ] = 2;
2975         }
2976         break;
2977       case 3:
2978         if ( nbSides == 2 )
2979           // split longest into 3 parts
2980           nbSplitPerEdge[ maxLen_i->second ] = 3;
2981         else
2982           // split longest into halves
2983           nbSplitPerEdge[ maxLen_i->second ] = 2;
2984       }
2985     }
2986   }
2987   else // **************************** Unite faces
2988   {
2989     int nbExraFaces = nbSides - 4; // nb of faces to fuse
2990     for ( iE = 0; iE < nbEdges; ++iE )
2991     {
2992       if ( nbUnitePerEdge[ iE ] < 0 )
2993         continue;
2994       // look for already united faces
2995       for ( int i = iE; i < iE + nbExraFaces; ++i )
2996       {
2997         if ( nbUnitePerEdge[ i ] > 0 ) // a side including nbUnitePerEdge[i]+1 edge
2998           nbExraFaces += nbUnitePerEdge[ i ];
2999         nbUnitePerEdge[ i ] = -1;
3000       }
3001       nbUnitePerEdge[ iE ] = nbExraFaces;
3002       break;
3003     }
3004   }
3005
3006   // Create TSideFace's
3007   int iSide = 0;
3008   list< TopoDS_Edge >::const_iterator botE = thePrism.myBottomEdges.begin();
3009   for ( iE = 0; iE < nbEdges; ++iE, ++botE )
3010   {
3011     TFaceQuadStructPtr quad = thePrism.myWallQuads[ iE ].front();
3012     const int       nbSplit = nbSplitPerEdge[ iE ];
3013     const int   nbExraFaces = nbUnitePerEdge[ iE ] + 1;
3014     if ( nbSplit > 0 ) // split
3015     {
3016       vector< double > params;
3017       splitParams( nbSplit, &myParam2ColumnMaps[ iE ], params );
3018       const bool isForward =
3019         StdMeshers_PrismAsBlock::IsForwardEdge( myHelper->GetMeshDS(),
3020                                                 myParam2ColumnMaps[iE],
3021                                                 *botE, SMESH_Block::ID_Fx0z );
3022       for ( int i = 0; i < nbSplit; ++i ) {
3023         double f = ( isForward ? params[ i ]   : params[ nbSplit - i-1 ]);
3024         double l = ( isForward ? params[ i+1 ] : params[ nbSplit - i ]);
3025         TSideFace* comp = new TSideFace( *mesh, wallFaceIds[ iSide ],
3026                                          thePrism.myWallQuads[ iE ], *botE,
3027                                          &myParam2ColumnMaps[ iE ], f, l );
3028         mySide->SetComponent( iSide++, comp );
3029       }
3030     }
3031     else if ( nbExraFaces > 1 ) // unite
3032     {
3033       double u0 = 0, sumLen = 0;
3034       for ( int i = iE; i < iE + nbExraFaces; ++i )
3035         sumLen += edgeLength[ i ];
3036
3037       vector< TSideFace* >        components( nbExraFaces );
3038       vector< pair< double, double> > params( nbExraFaces );
3039       bool endReached = false;
3040       for ( int i = 0; i < nbExraFaces; ++i, ++botE, ++iE )
3041       {
3042         if ( iE == nbEdges )
3043         {
3044           endReached = true;
3045           botE = thePrism.myBottomEdges.begin();
3046           iE = 0;
3047         }
3048         components[ i ] = new TSideFace( *mesh, wallFaceIds[ iSide ],
3049                                          thePrism.myWallQuads[ iE ], *botE,
3050                                          &myParam2ColumnMaps[ iE ]);
3051         double u1 = u0 + edgeLength[ iE ] / sumLen;
3052         params[ i ] = make_pair( u0 , u1 );
3053         u0 = u1;
3054       }
3055       TSideFace* comp = new TSideFace( *mesh, components, params );
3056       mySide->SetComponent( iSide++, comp );
3057       if ( endReached )
3058         break;
3059       --iE; // for increment in an external loop on iE
3060       --botE;
3061     }
3062     else if ( nbExraFaces < 0 ) // skip already united face
3063     {
3064     }
3065     else // use as is
3066     {
3067       TSideFace* comp = new TSideFace( *mesh, wallFaceIds[ iSide ],
3068                                        thePrism.myWallQuads[ iE ], *botE,
3069                                        &myParam2ColumnMaps[ iE ]);
3070       mySide->SetComponent( iSide++, comp );
3071     }
3072   }
3073
3074
3075   // Fill geometry fields of SMESH_Block
3076   // ------------------------------------
3077
3078   vector< int > botEdgeIdVec;
3079   SMESH_Block::GetFaceEdgesIDs( ID_BOT_FACE, botEdgeIdVec );
3080
3081   bool isForward[NB_WALL_FACES] = { true, true, true, true };
3082   Adaptor2d_Curve2d* botPcurves[NB_WALL_FACES];
3083   Adaptor2d_Curve2d* topPcurves[NB_WALL_FACES];
3084
3085   for ( int iF = 0; iF < NB_WALL_FACES; ++iF )
3086   {
3087     TSideFace * sideFace = mySide->GetComponent( iF );
3088     if ( !sideFace )
3089       RETURN_BAD_RESULT("NULL TSideFace");
3090     int fID = sideFace->FaceID(); // in-block ID
3091
3092     // fill myShapeIDMap
3093     if ( sideFace->InsertSubShapes( myShapeIDMap ) != 8 &&
3094          !sideFace->IsComplex())
3095       MESSAGE( ": Warning : InsertSubShapes() < 8 on side " << iF );
3096
3097     // side faces geometry
3098     Adaptor2d_Curve2d* pcurves[NB_WALL_FACES];
3099     if ( !sideFace->GetPCurves( pcurves ))
3100       RETURN_BAD_RESULT("TSideFace::GetPCurves() failed");
3101
3102     SMESH_Block::TFace& tFace = myFace[ fID - ID_FirstF ];
3103     tFace.Set( fID, sideFace->Surface(), pcurves, isForward );
3104
3105     SHOWYXZ( endl<<"F "<< iF << " id " << fID << " FRW " << sideFace->IsForward(), sideFace->Value(0,0));
3106     // edges 3D geometry
3107     vector< int > edgeIdVec;
3108     SMESH_Block::GetFaceEdgesIDs( fID, edgeIdVec );
3109     for ( int isMax = 0; isMax < 2; ++isMax ) {
3110       {
3111         int eID = edgeIdVec[ isMax ];
3112         SMESH_Block::TEdge& tEdge = myEdge[ eID - ID_FirstE ];
3113         tEdge.Set( eID, sideFace->HorizCurve(isMax), true);
3114         SHOWYXZ(eID<<" HOR"<<isMax<<"(0)", sideFace->HorizCurve(isMax)->Value(0));
3115         SHOWYXZ(eID<<" HOR"<<isMax<<"(1)", sideFace->HorizCurve(isMax)->Value(1));
3116       }
3117       {
3118         int eID = edgeIdVec[ isMax+2 ];
3119         SMESH_Block::TEdge& tEdge = myEdge[ eID - ID_FirstE  ];
3120         tEdge.Set( eID, sideFace->VertiCurve(isMax), true);
3121         SHOWYXZ(eID<<" VER"<<isMax<<"(0)", sideFace->VertiCurve(isMax)->Value(0));
3122         SHOWYXZ(eID<<" VER"<<isMax<<"(1)", sideFace->VertiCurve(isMax)->Value(1));
3123
3124         // corner points
3125         vector< int > vertexIdVec;
3126         SMESH_Block::GetEdgeVertexIDs( eID, vertexIdVec );
3127         myPnt[ vertexIdVec[0] - ID_FirstV ] = tEdge.GetCurve()->Value(0).XYZ();
3128         myPnt[ vertexIdVec[1] - ID_FirstV ] = tEdge.GetCurve()->Value(1).XYZ();
3129       }
3130     }
3131     // pcurves on horizontal faces
3132     for ( iE = 0; iE < NB_WALL_FACES; ++iE ) {
3133       if ( edgeIdVec[ BOTTOM_EDGE ] == botEdgeIdVec[ iE ] ) {
3134         botPcurves[ iE ] = sideFace->HorizPCurve( false, thePrism.myBottom );
3135         topPcurves[ iE ] = sideFace->HorizPCurve( true,  thePrism.myTop );
3136         break;
3137       }
3138     }
3139     //sideFace->dumpNodes( 4 ); // debug
3140   }
3141   // horizontal faces geometry
3142   {
3143     SMESH_Block::TFace& tFace = myFace[ ID_BOT_FACE - ID_FirstF ];
3144     tFace.Set( ID_BOT_FACE, new BRepAdaptor_Surface( thePrism.myBottom ), botPcurves, isForward );
3145     SMESH_Block::Insert( thePrism.myBottom, ID_BOT_FACE, myShapeIDMap );
3146   }
3147   {
3148     SMESH_Block::TFace& tFace = myFace[ ID_TOP_FACE - ID_FirstF ];
3149     tFace.Set( ID_TOP_FACE, new BRepAdaptor_Surface( thePrism.myTop ), topPcurves, isForward );
3150     SMESH_Block::Insert( thePrism.myTop, ID_TOP_FACE, myShapeIDMap );
3151   }
3152   //faceGridToPythonDump( SMESH_Block::ID_Fxy0, 50 );
3153   //faceGridToPythonDump( SMESH_Block::ID_Fxy1 );
3154
3155   // Fill map ShapeIndex to TParam2ColumnMap
3156   // ----------------------------------------
3157
3158   list< TSideFace* > fList;
3159   list< TSideFace* >::iterator fListIt;
3160   fList.push_back( mySide );
3161   for ( fListIt = fList.begin(); fListIt != fList.end(); ++fListIt)
3162   {
3163     int nb = (*fListIt)->NbComponents();
3164     for ( int i = 0; i < nb; ++i ) {
3165       if ( TSideFace* comp = (*fListIt)->GetComponent( i ))
3166         fList.push_back( comp );
3167     }
3168     if ( TParam2ColumnMap* cols = (*fListIt)->GetColumns()) {
3169       // columns for a base edge
3170       int id = MeshDS()->ShapeToIndex( (*fListIt)->BaseEdge() );
3171       bool isForward = (*fListIt)->IsForward();
3172       myShapeIndex2ColumnMap[ id ] = make_pair( cols, isForward );
3173
3174       // columns for vertices
3175       const SMDS_MeshNode* n0 = cols->begin()->second.front();
3176       id = n0->getshapeId();
3177       myShapeIndex2ColumnMap[ id ] = make_pair( cols, isForward );
3178
3179       const SMDS_MeshNode* n1 = cols->rbegin()->second.front();
3180       id = n1->getshapeId();
3181       myShapeIndex2ColumnMap[ id ] = make_pair( cols, !isForward );
3182     }
3183   }
3184
3185 // #define SHOWYXZ(msg, xyz) {                     \
3186 //     gp_Pnt p (xyz);                                                     \
3187 //     cout << msg << " ("<< p.X() << "; " <<p.Y() << "; " <<p.Z() << ") " <<endl; \
3188 //   }
3189 //   double _u[]={ 0.1, 0.1, 0.9, 0.9 };
3190 //   double _v[]={ 0.1, 0.9, 0.1, 0.9 };
3191 //   for ( int z = 0; z < 2; ++z )
3192 //     for ( int i = 0; i < 4; ++i )
3193 //     {
3194 //       //gp_XYZ testPar(0.25, 0.25, 0), testCoord;
3195 //       int iFace = (z ? ID_TOP_FACE : ID_BOT_FACE);
3196 //       gp_XYZ testPar(_u[i], _v[i], z), testCoord;
3197 //       if ( !FacePoint( iFace, testPar, testCoord ))
3198 //         RETURN_BAD_RESULT("TEST FacePoint() FAILED");
3199 //       SHOWYXZ("IN TEST PARAM" , testPar);
3200 //       SHOWYXZ("OUT TEST CORD" , testCoord);
3201 //       if ( !ComputeParameters( testCoord, testPar , iFace))
3202 //         RETURN_BAD_RESULT("TEST ComputeParameters() FAILED");
3203 //       SHOWYXZ("OUT TEST PARAM" , testPar);
3204 //     }
3205   return true;
3206 }
3207
3208 //================================================================================
3209 /*!
3210  * \brief Return pointer to column of nodes
3211  * \param node - bottom node from which the returned column goes up
3212  * \retval const TNodeColumn* - the found column
3213  */
3214 //================================================================================
3215
3216 const TNodeColumn* StdMeshers_PrismAsBlock::GetNodeColumn(const SMDS_MeshNode* node) const
3217 {
3218   int sID = node->getshapeId();
3219
3220   map<int, pair< TParam2ColumnMap*, bool > >::const_iterator col_frw =
3221     myShapeIndex2ColumnMap.find( sID );
3222   if ( col_frw != myShapeIndex2ColumnMap.end() ) {
3223     const TParam2ColumnMap* cols = col_frw->second.first;
3224     TParam2ColumnIt u_col = cols->begin();
3225     for ( ; u_col != cols->end(); ++u_col )
3226       if ( u_col->second[ 0 ] == node )
3227         return & u_col->second;
3228   }
3229   return 0;
3230 }
3231
3232 //=======================================================================
3233 //function : GetLayersTransformation
3234 //purpose  : Return transformations to get coordinates of nodes of each layer
3235 //           by nodes of the bottom. Layer is a set of nodes at a certain step
3236 //           from bottom to top.
3237 //           Transformation to get top node from bottom ones is computed
3238 //           only if the top FACE is not meshed.
3239 //=======================================================================
3240
3241 bool StdMeshers_PrismAsBlock::GetLayersTransformation(vector<gp_Trsf> &           trsf,
3242                                                       const Prism_3D::TPrismTopo& prism) const
3243 {
3244   const bool itTopMeshed = !SubMesh( ID_BOT_FACE )->IsEmpty();
3245   const int zSize = VerticalSize();
3246   if ( zSize < 3 && !itTopMeshed ) return true;
3247   trsf.resize( zSize - 1 );
3248
3249   // Select some node columns by which we will define coordinate system of layers
3250
3251   vector< const TNodeColumn* > columns;
3252   {
3253     bool isReverse;
3254     list< TopoDS_Edge >::const_iterator edgeIt = prism.myBottomEdges.begin();
3255     for ( int iE = 0; iE < prism.myNbEdgesInWires.front(); ++iE, ++edgeIt )
3256     {
3257       if ( SMESH_Algo::isDegenerated( *edgeIt )) continue;
3258       const TParam2ColumnMap* u2colMap =
3259         GetParam2ColumnMap( MeshDS()->ShapeToIndex( *edgeIt ), isReverse );
3260       if ( !u2colMap ) return false;
3261       double f = u2colMap->begin()->first, l = u2colMap->rbegin()->first;
3262       //isReverse = ( edgeIt->Orientation() == TopAbs_REVERSED );
3263       //if ( isReverse ) swap ( f, l ); -- u2colMap takes orientation into account
3264       const int nbCol = 5;
3265       for ( int i = 0; i < nbCol; ++i )
3266       {
3267         double u = f + i/double(nbCol) * ( l - f );
3268         const TNodeColumn* col = & getColumn( u2colMap, u )->second;
3269         if ( columns.empty() || col != columns.back() )
3270           columns.push_back( col );
3271       }
3272     }
3273   }
3274
3275   // Find tolerance to check transformations
3276
3277   double tol2;
3278   {
3279     Bnd_B3d bndBox;
3280     for ( int i = 0; i < columns.size(); ++i )
3281       bndBox.Add( gpXYZ( columns[i]->front() ));
3282     tol2 = bndBox.SquareExtent() * 1e-5;
3283   }
3284
3285   // Compute transformations
3286
3287   int xCol = -1;
3288   gp_Trsf fromCsZ, toCs0;
3289   gp_Ax3 cs0 = getLayerCoordSys(0, columns, xCol );
3290   //double dist0 = cs0.Location().Distance( gpXYZ( (*columns[0])[0]));
3291   toCs0.SetTransformation( cs0 );
3292   for ( int z = 1; z < zSize; ++z )
3293   {
3294     gp_Ax3 csZ = getLayerCoordSys(z, columns, xCol );
3295     //double distZ = csZ.Location().Distance( gpXYZ( (*columns[0])[z]));
3296     fromCsZ.SetTransformation( csZ );
3297     fromCsZ.Invert();
3298     gp_Trsf& t = trsf[ z-1 ];
3299     t = fromCsZ * toCs0;
3300     //t.SetScaleFactor( distZ/dist0 ); - it does not work properly, wrong base point
3301
3302     // check a transformation
3303     for ( int i = 0; i < columns.size(); ++i )
3304     {
3305       gp_Pnt p0 = gpXYZ( (*columns[i])[0] );
3306       gp_Pnt pz = gpXYZ( (*columns[i])[z] );
3307       t.Transforms( p0.ChangeCoord() );
3308       if ( p0.SquareDistance( pz ) > tol2 )
3309       {
3310         t = gp_Trsf();
3311         return ( z == zSize - 1 ); // OK if fails only botton->top trsf
3312       }
3313     }
3314   }
3315   return true;
3316 }
3317
3318 //================================================================================
3319 /*!
3320  * \brief Check curve orientation of a bootom edge
3321   * \param meshDS - mesh DS
3322   * \param columnsMap - node columns map of side face
3323   * \param bottomEdge - the bootom edge
3324   * \param sideFaceID - side face in-block ID
3325   * \retval bool - true if orientation coinside with in-block forward orientation
3326  */
3327 //================================================================================
3328
3329 bool StdMeshers_PrismAsBlock::IsForwardEdge(SMESHDS_Mesh*           meshDS,
3330                                             const TParam2ColumnMap& columnsMap,
3331                                             const TopoDS_Edge &     bottomEdge,
3332                                             const int               sideFaceID)
3333 {
3334   bool isForward = false;
3335   if ( SMESH_MesherHelper::IsClosedEdge( bottomEdge ))
3336   {
3337     isForward = ( bottomEdge.Orientation() == TopAbs_FORWARD );
3338   }
3339   else
3340   {
3341     const TNodeColumn&     firstCol = columnsMap.begin()->second;
3342     const SMDS_MeshNode* bottomNode = firstCol[0];
3343     TopoDS_Shape firstVertex = SMESH_MesherHelper::GetSubShapeByNode( bottomNode, meshDS );
3344     isForward = ( firstVertex.IsSame( TopExp::FirstVertex( bottomEdge, true )));
3345   }
3346   // on 2 of 4 sides first vertex is end
3347   if ( sideFaceID == ID_Fx1z || sideFaceID == ID_F0yz )
3348     isForward = !isForward;
3349   return isForward;
3350 }
3351
3352 //=======================================================================
3353 //function : faceGridToPythonDump
3354 //purpose  : Prints a script creating a normal grid on the prism side
3355 //=======================================================================
3356
3357 void StdMeshers_PrismAsBlock::faceGridToPythonDump(const SMESH_Block::TShapeID face,
3358                                                    const int                   nb)
3359 {
3360 #ifdef _DEBUG_
3361   gp_XYZ pOnF[6] = { gp_XYZ(0,0,0), gp_XYZ(0,0,1),
3362                      gp_XYZ(0,0,0), gp_XYZ(0,1,0),
3363                      gp_XYZ(0,0,0), gp_XYZ(1,0,0) };
3364   gp_XYZ p2;
3365   cout << "mesh = smesh.Mesh( 'Face " << face << "')" << endl;
3366   SMESH_Block::TFace& f = myFace[ face - ID_FirstF ];
3367   gp_XYZ params = pOnF[ face - ID_FirstF ];
3368   //const int nb = 10; // nb face rows
3369   for ( int j = 0; j <= nb; ++j )
3370   {
3371     params.SetCoord( f.GetVInd(), double( j )/ nb );
3372     for ( int i = 0; i <= nb; ++i )
3373     {
3374       params.SetCoord( f.GetUInd(), double( i )/ nb );
3375       gp_XYZ p = f.Point( params );
3376       gp_XY uv = f.GetUV( params );
3377       cout << "mesh.AddNode( " << p.X() << ", " << p.Y() << ", " << p.Z() << " )"
3378            << " # " << 1 + i + j * ( nb + 1 )
3379            << " ( " << i << ", " << j << " ) "
3380            << " UV( " << uv.X() << ", " << uv.Y() << " )" << endl;
3381       ShellPoint( params, p2 );
3382       double dist = ( p2 - p ).Modulus();
3383       if ( dist > 1e-4 )
3384         cout << "#### dist from ShellPoint " << dist
3385              << " (" << p2.X() << ", " << p2.Y() << ", " << p2.Z() << " ) " << endl;
3386     }
3387   }
3388   for ( int j = 0; j < nb; ++j )
3389     for ( int i = 0; i < nb; ++i )
3390     {
3391       int n = 1 + i + j * ( nb + 1 );
3392       cout << "mesh.AddFace([ "
3393            << n << ", " << n+1 << ", "
3394            << n+nb+2 << ", " << n+nb+1 << "]) " << endl;
3395     }
3396   
3397 #endif
3398 }
3399
3400 //================================================================================
3401 /*!
3402  * \brief Constructor
3403   * \param faceID - in-block ID
3404   * \param face - geom FACE
3405   * \param baseEdge - EDGE proreply oriented in the bottom EDGE !!!
3406   * \param columnsMap - map of node columns
3407   * \param first - first normalized param
3408   * \param last - last normalized param
3409  */
3410 //================================================================================
3411
3412 StdMeshers_PrismAsBlock::TSideFace::TSideFace(SMESH_Mesh&                mesh,
3413                                               const int                  faceID,
3414                                               const Prism_3D::TQuadList& quadList,
3415                                               const TopoDS_Edge&         baseEdge,
3416                                               TParam2ColumnMap*          columnsMap,
3417                                               const double               first,
3418                                               const double               last):
3419   myID( faceID ),
3420   myParamToColumnMap( columnsMap ),
3421   myHelper( mesh )
3422 {
3423   myParams.resize( 1 );
3424   myParams[ 0 ] = make_pair( first, last );
3425   mySurface     = PSurface( new BRepAdaptor_Surface( quadList.front()->face ));
3426   myBaseEdge    = baseEdge;
3427   myIsForward   = StdMeshers_PrismAsBlock::IsForwardEdge( myHelper.GetMeshDS(),
3428                                                           *myParamToColumnMap,
3429                                                           myBaseEdge, myID );
3430   myHelper.SetSubShape( quadList.front()->face );
3431
3432   if ( quadList.size() > 1 ) // side is vertically composite
3433   {
3434     // fill myShapeID2Surf map to enable finding a right surface by any sub-shape ID
3435
3436     SMESHDS_Mesh* meshDS = myHelper.GetMeshDS();
3437
3438     TopTools_IndexedDataMapOfShapeListOfShape subToFaces;
3439     Prism_3D::TQuadList::const_iterator quad = quadList.begin();
3440     for ( ; quad != quadList.end(); ++quad )
3441     {
3442       const TopoDS_Face& face = (*quad)->face;
3443       TopExp::MapShapesAndAncestors( face, TopAbs_VERTEX, TopAbs_FACE, subToFaces );
3444       TopExp::MapShapesAndAncestors( face, TopAbs_EDGE,   TopAbs_FACE, subToFaces );
3445       myShapeID2Surf.insert( make_pair( meshDS->ShapeToIndex( face ),
3446                                         PSurface( new BRepAdaptor_Surface( face ))));
3447     }
3448     for ( int i = 1; i <= subToFaces.Extent(); ++i )
3449     {
3450       const TopoDS_Shape&     sub = subToFaces.FindKey( i );
3451       TopTools_ListOfShape& faces = subToFaces( i );
3452       int subID  = meshDS->ShapeToIndex( sub );
3453       int faceID = meshDS->ShapeToIndex( faces.First() );
3454       myShapeID2Surf.insert ( make_pair( subID, myShapeID2Surf[ faceID ]));
3455     }
3456   }
3457 }
3458
3459 //================================================================================
3460 /*!
3461  * \brief Constructor of a complex side face
3462  */
3463 //================================================================================
3464
3465 StdMeshers_PrismAsBlock::TSideFace::
3466 TSideFace(SMESH_Mesh&                             mesh,
3467           const vector< TSideFace* >&             components,
3468           const vector< pair< double, double> > & params)
3469   :myID( components[0] ? components[0]->myID : 0 ),
3470    myParamToColumnMap( 0 ),
3471    myParams( params ),
3472    myIsForward( true ),
3473    myComponents( components ),
3474    myHelper( mesh )
3475 {
3476   if ( myID == ID_Fx1z || myID == ID_F0yz )
3477   {
3478     // reverse components
3479     std::reverse( myComponents.begin(), myComponents.end() );
3480     std::reverse( myParams.begin(),     myParams.end() );
3481     for ( size_t i = 0; i < myParams.size(); ++i )
3482     {
3483       const double f = myParams[i].first;
3484       const double l = myParams[i].second;
3485       myParams[i] = make_pair( 1. - l, 1. - f );
3486     }
3487   }
3488 }
3489 //================================================================================
3490 /*!
3491  * \brief Copy constructor
3492   * \param other - other side
3493  */
3494 //================================================================================
3495
3496 StdMeshers_PrismAsBlock::TSideFace::TSideFace( const TSideFace& other ):
3497   myID               ( other.myID ),
3498   myParamToColumnMap ( other.myParamToColumnMap ),
3499   mySurface          ( other.mySurface ),
3500   myBaseEdge         ( other.myBaseEdge ),
3501   myShapeID2Surf     ( other.myShapeID2Surf ),
3502   myParams           ( other.myParams ),
3503   myIsForward        ( other.myIsForward ),
3504   myComponents       ( other.myComponents.size() ),
3505   myHelper           ( *other.myHelper.GetMesh() )
3506 {
3507   for (int i = 0 ; i < myComponents.size(); ++i )
3508     myComponents[ i ] = new TSideFace( *other.myComponents[ i ]);
3509 }
3510
3511 //================================================================================
3512 /*!
3513  * \brief Deletes myComponents
3514  */
3515 //================================================================================
3516
3517 StdMeshers_PrismAsBlock::TSideFace::~TSideFace()
3518 {
3519   for (int i = 0 ; i < myComponents.size(); ++i )
3520     if ( myComponents[ i ] )
3521       delete myComponents[ i ];
3522 }
3523
3524 //================================================================================
3525 /*!
3526  * \brief Return geometry of the vertical curve
3527   * \param isMax - true means curve located closer to (1,1,1) block point
3528   * \retval Adaptor3d_Curve* - curve adaptor
3529  */
3530 //================================================================================
3531
3532 Adaptor3d_Curve* StdMeshers_PrismAsBlock::TSideFace::VertiCurve(const bool isMax) const
3533 {
3534   if ( !myComponents.empty() ) {
3535     if ( isMax )
3536       return myComponents.back()->VertiCurve(isMax);
3537     else
3538       return myComponents.front()->VertiCurve(isMax);
3539   }
3540   double f = myParams[0].first, l = myParams[0].second;
3541   if ( !myIsForward ) std::swap( f, l );
3542   return new TVerticalEdgeAdaptor( myParamToColumnMap, isMax ? l : f );
3543 }
3544
3545 //================================================================================
3546 /*!
3547  * \brief Return geometry of the top or bottom curve
3548   * \param isTop - 
3549   * \retval Adaptor3d_Curve* - 
3550  */
3551 //================================================================================
3552
3553 Adaptor3d_Curve* StdMeshers_PrismAsBlock::TSideFace::HorizCurve(const bool isTop) const
3554 {
3555   return new THorizontalEdgeAdaptor( this, isTop );
3556 }
3557
3558 //================================================================================
3559 /*!
3560  * \brief Return pcurves
3561   * \param pcurv - array of 4 pcurves
3562   * \retval bool - is a success
3563  */
3564 //================================================================================
3565
3566 bool StdMeshers_PrismAsBlock::TSideFace::GetPCurves(Adaptor2d_Curve2d* pcurv[4]) const
3567 {
3568   int iEdge[ 4 ] = { BOTTOM_EDGE, TOP_EDGE, V0_EDGE, V1_EDGE };
3569
3570   for ( int i = 0 ; i < 4 ; ++i ) {
3571     Handle(Geom2d_Line) line;
3572     switch ( iEdge[ i ] ) {
3573     case TOP_EDGE:
3574       line = new Geom2d_Line( gp_Pnt2d( 0, 1 ), gp::DX2d() ); break;
3575     case BOTTOM_EDGE:
3576       line = new Geom2d_Line( gp::Origin2d(), gp::DX2d() ); break;
3577     case V0_EDGE:
3578       line = new Geom2d_Line( gp::Origin2d(), gp::DY2d() ); break;
3579     case V1_EDGE:
3580       line = new Geom2d_Line( gp_Pnt2d( 1, 0 ), gp::DY2d() ); break;
3581     }
3582     pcurv[ i ] = new Geom2dAdaptor_Curve( line, 0, 1 );
3583   }
3584   return true;
3585 }
3586
3587 //================================================================================
3588 /*!
3589  * \brief Returns geometry of pcurve on a horizontal face
3590   * \param isTop - is top or bottom face
3591   * \param horFace - a horizontal face
3592   * \retval Adaptor2d_Curve2d* - curve adaptor
3593  */
3594 //================================================================================
3595
3596 Adaptor2d_Curve2d*
3597 StdMeshers_PrismAsBlock::TSideFace::HorizPCurve(const bool         isTop,
3598                                                 const TopoDS_Face& horFace) const
3599 {
3600   return new TPCurveOnHorFaceAdaptor( this, isTop, horFace );
3601 }
3602
3603 //================================================================================
3604 /*!
3605  * \brief Return a component corresponding to parameter
3606   * \param U - parameter along a horizontal size
3607   * \param localU - parameter along a horizontal size of a component
3608   * \retval TSideFace* - found component
3609  */
3610 //================================================================================
3611
3612 StdMeshers_PrismAsBlock::TSideFace*
3613 StdMeshers_PrismAsBlock::TSideFace::GetComponent(const double U,double & localU) const
3614 {
3615   localU = U;
3616   if ( myComponents.empty() )
3617     return const_cast<TSideFace*>( this );
3618
3619   int i;
3620   for ( i = 0; i < myComponents.size(); ++i )
3621     if ( U < myParams[ i ].second )
3622       break;
3623   if ( i >= myComponents.size() )
3624     i = myComponents.size() - 1;
3625
3626   double f = myParams[ i ].first, l = myParams[ i ].second;
3627   localU = ( U - f ) / ( l - f );
3628   return myComponents[ i ];
3629 }
3630
3631 //================================================================================
3632 /*!
3633  * \brief Find node columns for a parameter
3634   * \param U - parameter along a horizontal edge
3635   * \param col1 - the 1st found column
3636   * \param col2 - the 2nd found column
3637   * \retval r - normalized position of U between the found columns
3638  */
3639 //================================================================================
3640
3641 double StdMeshers_PrismAsBlock::TSideFace::GetColumns(const double      U,
3642                                                       TParam2ColumnIt & col1,
3643                                                       TParam2ColumnIt & col2) const
3644 {
3645   double u = U, r = 0;
3646   if ( !myComponents.empty() ) {
3647     TSideFace * comp = GetComponent(U,u);
3648     return comp->GetColumns( u, col1, col2 );
3649   }
3650
3651   if ( !myIsForward )
3652     u = 1 - u;
3653   double f = myParams[0].first, l = myParams[0].second;
3654   u = f + u * ( l - f );
3655
3656   col1 = col2 = getColumn( myParamToColumnMap, u );
3657   if ( ++col2 == myParamToColumnMap->end() ) {
3658     --col2;
3659     r = 0.5;
3660   }
3661   else {
3662     double uf = col1->first;
3663     double ul = col2->first;
3664     r = ( u - uf ) / ( ul - uf );
3665   }
3666   return r;
3667 }
3668
3669 //================================================================================
3670 /*!
3671  * \brief Return all nodes at a given height together with their normalized parameters
3672  *  \param [in] Z - the height of interest
3673  *  \param [out] nodes - map of parameter to node
3674  */
3675 //================================================================================
3676
3677 void StdMeshers_PrismAsBlock::
3678 TSideFace::GetNodesAtZ(const int Z,
3679                        map<double, const SMDS_MeshNode* >& nodes ) const
3680 {
3681   if ( !myComponents.empty() )
3682   {
3683     double u0 = 0.;
3684     for ( size_t i = 0; i < myComponents.size(); ++i )
3685     {
3686       map<double, const SMDS_MeshNode* > nn;
3687       myComponents[i]->GetNodesAtZ( Z, nn );
3688       map<double, const SMDS_MeshNode* >::iterator u2n = nn.begin();
3689       if ( !nodes.empty() && nodes.rbegin()->second == u2n->second )
3690         ++u2n;
3691       const double uRange = myParams[i].second - myParams[i].first;
3692       for ( ; u2n != nn.end(); ++u2n )
3693         nodes.insert( nodes.end(), make_pair( u0 + uRange * u2n->first, u2n->second ));
3694       u0 += uRange;
3695     }
3696   }
3697   else
3698   {
3699     double f = myParams[0].first, l = myParams[0].second;
3700     if ( !myIsForward )
3701       std::swap( f, l );
3702     const double uRange = l - f;
3703     if ( Abs( uRange ) < std::numeric_limits<double>::min() )
3704       return;
3705     TParam2ColumnIt u2col = getColumn( myParamToColumnMap, myParams[0].first + 1e-3 );
3706     for ( ; u2col != myParamToColumnMap->end(); ++u2col )
3707       if ( u2col->first > myParams[0].second + 1e-9 )
3708         break;
3709       else
3710         nodes.insert( nodes.end(),
3711                       make_pair( ( u2col->first - f ) / uRange, u2col->second[ Z ] ));
3712   }
3713 }
3714
3715 //================================================================================
3716 /*!
3717  * \brief Return coordinates by normalized params
3718   * \param U - horizontal param
3719   * \param V - vertical param
3720   * \retval gp_Pnt - result point
3721  */
3722 //================================================================================
3723
3724 gp_Pnt StdMeshers_PrismAsBlock::TSideFace::Value(const Standard_Real U,
3725                                                  const Standard_Real V) const
3726 {
3727   if ( !myComponents.empty() ) {
3728     double u;
3729     TSideFace * comp = GetComponent(U,u);
3730     return comp->Value( u, V );
3731   }
3732
3733   TParam2ColumnIt u_col1, u_col2;
3734   double vR, hR = GetColumns( U, u_col1, u_col2 );
3735
3736   const SMDS_MeshNode* nn[4];
3737
3738   // BEGIN issue 0020680: Bad cell created by Radial prism in center of torus
3739   // Workaround for a wrongly located point returned by mySurface.Value() for
3740   // UV located near boundary of BSpline surface.
3741   // To bypass the problem, we take point from 3D curve of EDGE.
3742   // It solves pb of the bloc_fiss_new.py
3743   const double tol = 1e-3;
3744   if ( V < tol || V+tol >= 1. )
3745   {
3746     nn[0] = V < tol ? u_col1->second.front() : u_col1->second.back();
3747     nn[2] = V < tol ? u_col2->second.front() : u_col2->second.back();
3748     TopoDS_Edge edge;
3749     if ( V < tol )
3750     {
3751       edge = myBaseEdge;
3752     }
3753     else
3754     {
3755       TopoDS_Shape s = myHelper.GetSubShapeByNode( nn[0], myHelper.GetMeshDS() );
3756       if ( s.ShapeType() != TopAbs_EDGE )
3757         s = myHelper.GetSubShapeByNode( nn[2], myHelper.GetMeshDS() );
3758       if ( s.ShapeType() == TopAbs_EDGE )
3759         edge = TopoDS::Edge( s );
3760     }
3761     if ( !edge.IsNull() )
3762     {
3763       double u1 = myHelper.GetNodeU( edge, nn[0] );
3764       double u3 = myHelper.GetNodeU( edge, nn[2] );
3765       double u = u1 * ( 1 - hR ) + u3 * hR;
3766       TopLoc_Location loc; double f,l;
3767       Handle(Geom_Curve) curve = BRep_Tool::Curve( edge,loc,f,l );
3768       return curve->Value( u ).Transformed( loc );
3769     }
3770   }
3771   // END issue 0020680: Bad cell created by Radial prism in center of torus
3772
3773   vR = getRAndNodes( & u_col1->second, V, nn[0], nn[1] );
3774   vR = getRAndNodes( & u_col2->second, V, nn[2], nn[3] );
3775
3776   if ( !myShapeID2Surf.empty() ) // side is vertically composite
3777   {
3778     // find a FACE on which the 4 nodes lie
3779     TSideFace* me = (TSideFace*) this;
3780     int notFaceID1 = 0, notFaceID2 = 0;
3781     for ( int i = 0; i < 4; ++i )
3782       if ( nn[i]->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE ) // node on FACE
3783       {
3784         me->mySurface = me->myShapeID2Surf[ nn[i]->getshapeId() ];
3785         notFaceID2 = 0;
3786         break;
3787       }
3788       else if ( notFaceID1 == 0 ) // node on EDGE or VERTEX
3789       {
3790         me->mySurface  = me->myShapeID2Surf[ nn[i]->getshapeId() ];
3791         notFaceID1 = nn[i]->getshapeId();
3792       }
3793       else if ( notFaceID1 != nn[i]->getshapeId() ) // node on other EDGE or VERTEX
3794       {
3795         if ( mySurface != me->myShapeID2Surf[ nn[i]->getshapeId() ])
3796           notFaceID2 = nn[i]->getshapeId();
3797       }
3798     if ( notFaceID2 ) // no nodes of FACE and nodes are on different FACEs
3799     {
3800       SMESHDS_Mesh* meshDS = myHelper.GetMeshDS();
3801       TopoDS_Shape face = myHelper.GetCommonAncestor( meshDS->IndexToShape( notFaceID1 ),
3802                                                        meshDS->IndexToShape( notFaceID2 ),
3803                                                        *myHelper.GetMesh(),
3804                                                        TopAbs_FACE );
3805       if ( face.IsNull() ) 
3806         throw SALOME_Exception("StdMeshers_PrismAsBlock::TSideFace::Value() face.IsNull()");
3807       int faceID = meshDS->ShapeToIndex( face );
3808       me->mySurface = me->myShapeID2Surf[ faceID ];
3809       if ( !mySurface )
3810         throw SALOME_Exception("StdMeshers_PrismAsBlock::TSideFace::Value() !mySurface");
3811     }
3812   }
3813   ((TSideFace*) this)->myHelper.SetSubShape( mySurface->Face() );
3814
3815   gp_XY uv1 = myHelper.GetNodeUV( mySurface->Face(), nn[0], nn[2]);
3816   gp_XY uv2 = myHelper.GetNodeUV( mySurface->Face(), nn[1], nn[3]);
3817   gp_XY uv12 = uv1 * ( 1 - vR ) + uv2 * vR;
3818
3819   gp_XY uv3 = myHelper.GetNodeUV( mySurface->Face(), nn[2], nn[0]);
3820   gp_XY uv4 = myHelper.GetNodeUV( mySurface->Face(), nn[3], nn[1]);
3821   gp_XY uv34 = uv3 * ( 1 - vR ) + uv4 * vR;
3822
3823   gp_XY uv = uv12 * ( 1 - hR ) + uv34 * hR;
3824
3825   gp_Pnt p = mySurface->Value( uv.X(), uv.Y() );
3826   return p;
3827 }
3828
3829
3830 //================================================================================
3831 /*!
3832  * \brief Return boundary edge
3833   * \param edge - edge index
3834   * \retval TopoDS_Edge - found edge
3835  */
3836 //================================================================================
3837
3838 TopoDS_Edge StdMeshers_PrismAsBlock::TSideFace::GetEdge(const int iEdge) const
3839 {
3840   if ( !myComponents.empty() ) {
3841     switch ( iEdge ) {
3842     case V0_EDGE : return myComponents.front()->GetEdge( iEdge );
3843     case V1_EDGE : return myComponents.back() ->GetEdge( iEdge );
3844     default: return TopoDS_Edge();
3845     }
3846   }
3847   TopoDS_Shape edge;
3848   const SMDS_MeshNode* node = 0;
3849   SMESHDS_Mesh * meshDS = myHelper.GetMesh()->GetMeshDS();
3850   TNodeColumn* column;
3851
3852   switch ( iEdge ) {
3853   case TOP_EDGE:
3854   case BOTTOM_EDGE:
3855     column = & (( ++myParamToColumnMap->begin())->second );
3856     node = ( iEdge == TOP_EDGE ) ? column->back() : column->front();
3857     edge = myHelper.GetSubShapeByNode ( node, meshDS );
3858     if ( edge.ShapeType() == TopAbs_VERTEX ) {
3859       column = & ( myParamToColumnMap->begin()->second );
3860       node = ( iEdge == TOP_EDGE ) ? column->back() : column->front();
3861     }
3862     break;
3863   case V0_EDGE:
3864   case V1_EDGE: {
3865     bool back = ( iEdge == V1_EDGE );
3866     if ( !myIsForward ) back = !back;
3867     if ( back )
3868       column = & ( myParamToColumnMap->rbegin()->second );
3869     else
3870       column = & ( myParamToColumnMap->begin()->second );
3871     if ( column->size() > 0 )
3872       edge = myHelper.GetSubShapeByNode( (*column)[ 1 ], meshDS );
3873     if ( edge.IsNull() || edge.ShapeType() == TopAbs_VERTEX )
3874       node = column->front();
3875     break;
3876   }
3877   default:;
3878   }
3879   if ( !edge.IsNull() && edge.ShapeType() == TopAbs_EDGE )
3880     return TopoDS::Edge( edge );
3881
3882   // find edge by 2 vertices
3883   TopoDS_Shape V1 = edge;
3884   TopoDS_Shape V2 = myHelper.GetSubShapeByNode( node, meshDS );
3885   if ( !V2.IsNull() && V2.ShapeType() == TopAbs_VERTEX && !V2.IsSame( V1 ))
3886   {
3887     TopoDS_Shape ancestor = myHelper.GetCommonAncestor( V1, V2, *myHelper.GetMesh(), TopAbs_EDGE);
3888     if ( !ancestor.IsNull() )
3889       return TopoDS::Edge( ancestor );
3890   }
3891   return TopoDS_Edge();
3892 }
3893
3894 //================================================================================
3895 /*!
3896  * \brief Fill block sub-shapes
3897   * \param shapeMap - map to fill in
3898   * \retval int - nb inserted sub-shapes
3899  */
3900 //================================================================================
3901
3902 int StdMeshers_PrismAsBlock::TSideFace::InsertSubShapes(TBlockShapes& shapeMap) const
3903 {
3904   int nbInserted = 0;
3905
3906   // Insert edges
3907   vector< int > edgeIdVec;
3908   SMESH_Block::GetFaceEdgesIDs( myID, edgeIdVec );
3909
3910   for ( int i = BOTTOM_EDGE; i <=V1_EDGE ; ++i ) {
3911     TopoDS_Edge e = GetEdge( i );
3912     if ( !e.IsNull() ) {
3913       nbInserted += SMESH_Block::Insert( e, edgeIdVec[ i ], shapeMap);
3914     }
3915   }
3916
3917   // Insert corner vertices
3918
3919   TParam2ColumnIt col1, col2 ;
3920   vector< int > vertIdVec;
3921
3922   // from V0 column
3923   SMESH_Block::GetEdgeVertexIDs( edgeIdVec[ V0_EDGE ], vertIdVec);
3924   GetColumns(0, col1, col2 );
3925   const SMDS_MeshNode* node0 = col1->second.front();
3926   const SMDS_MeshNode* node1 = col1->second.back();
3927   TopoDS_Shape v0 = myHelper.GetSubShapeByNode( node0, myHelper.GetMeshDS());
3928   TopoDS_Shape v1 = myHelper.GetSubShapeByNode( node1, myHelper.GetMeshDS());
3929   if ( v0.ShapeType() == TopAbs_VERTEX ) {
3930     nbInserted += SMESH_Block::Insert( v0, vertIdVec[ 0 ], shapeMap);
3931   }
3932   if ( v1.ShapeType() == TopAbs_VERTEX ) {
3933     nbInserted += SMESH_Block::Insert( v1, vertIdVec[ 1 ], shapeMap);
3934   }
3935   
3936   // from V1 column
3937   SMESH_Block::GetEdgeVertexIDs( edgeIdVec[ V1_EDGE ], vertIdVec);
3938   GetColumns(1, col1, col2 );
3939   node0 = col2->second.front();
3940   node1 = col2->second.back();
3941   v0 = myHelper.GetSubShapeByNode( node0, myHelper.GetMeshDS());
3942   v1 = myHelper.GetSubShapeByNode( node1, myHelper.GetMeshDS());
3943   if ( v0.ShapeType() == TopAbs_VERTEX ) {
3944     nbInserted += SMESH_Block::Insert( v0, vertIdVec[ 0 ], shapeMap);
3945   }
3946   if ( v1.ShapeType() == TopAbs_VERTEX ) {
3947     nbInserted += SMESH_Block::Insert( v1, vertIdVec[ 1 ], shapeMap);
3948   }
3949
3950 //   TopoDS_Vertex V0, V1, Vcom;
3951 //   TopExp::Vertices( myBaseEdge, V0, V1, true );
3952 //   if ( !myIsForward ) std::swap( V0, V1 );
3953
3954 //   // bottom vertex IDs
3955 //   SMESH_Block::GetEdgeVertexIDs( edgeIdVec[ _u0 ], vertIdVec);
3956 //   SMESH_Block::Insert( V0, vertIdVec[ 0 ], shapeMap);
3957 //   SMESH_Block::Insert( V1, vertIdVec[ 1 ], shapeMap);
3958
3959 //   TopoDS_Edge sideEdge = GetEdge( V0_EDGE );
3960 //   if ( sideEdge.IsNull() || !TopExp::CommonVertex( botEdge, sideEdge, Vcom ))
3961 //     return false;
3962
3963 //   // insert one side edge
3964 //   int edgeID;
3965 //   if ( Vcom.IsSame( V0 )) edgeID = edgeIdVec[ _v0 ];
3966 //   else                    edgeID = edgeIdVec[ _v1 ];
3967 //   SMESH_Block::Insert( sideEdge, edgeID, shapeMap);
3968
3969 //   // top vertex of the side edge
3970 //   SMESH_Block::GetEdgeVertexIDs( edgeID, vertIdVec);
3971 //   TopoDS_Vertex Vtop = TopExp::FirstVertex( sideEdge );
3972 //   if ( Vcom.IsSame( Vtop ))
3973 //     Vtop = TopExp::LastVertex( sideEdge );
3974 //   SMESH_Block::Insert( Vtop, vertIdVec[ 1 ], shapeMap);
3975
3976 //   // other side edge
3977 //   sideEdge = GetEdge( V1_EDGE );
3978 //   if ( sideEdge.IsNull() )
3979 //     return false;
3980 //   if ( edgeID = edgeIdVec[ _v1 ]) edgeID = edgeIdVec[ _v0 ];
3981 //   else                            edgeID = edgeIdVec[ _v1 ];
3982 //   SMESH_Block::Insert( sideEdge, edgeID, shapeMap);
3983   
3984 //   // top edge
3985 //   TopoDS_Edge topEdge = GetEdge( TOP_EDGE );
3986 //   SMESH_Block::Insert( topEdge, edgeIdVec[ _u1 ], shapeMap);
3987
3988 //   // top vertex of the other side edge
3989 //   if ( !TopExp::CommonVertex( topEdge, sideEdge, Vcom ))
3990 //     return false;
3991 //   SMESH_Block::GetEdgeVertexIDs( edgeID, vertIdVec );
3992 //   SMESH_Block::Insert( Vcom, vertIdVec[ 1 ], shapeMap);
3993
3994   return nbInserted;
3995 }
3996
3997 //================================================================================
3998 /*!
3999  * \brief Dump ids of nodes of sides
4000  */
4001 //================================================================================
4002
4003 void StdMeshers_PrismAsBlock::TSideFace::dumpNodes(int nbNodes) const
4004 {
4005 #ifdef _DEBUG_
4006   cout << endl << "NODES OF FACE "; SMESH_Block::DumpShapeID( myID, cout ) << endl;
4007   THorizontalEdgeAdaptor* hSize0 = (THorizontalEdgeAdaptor*) HorizCurve(0);
4008   cout << "Horiz side 0: "; hSize0->dumpNodes(nbNodes); cout << endl;
4009   THorizontalEdgeAdaptor* hSize1 = (THorizontalEdgeAdaptor*) HorizCurve(1);
4010   cout << "Horiz side 1: "; hSize1->dumpNodes(nbNodes); cout << endl;
4011   TVerticalEdgeAdaptor* vSide0 = (TVerticalEdgeAdaptor*) VertiCurve(0);
4012   cout << "Verti side 0: "; vSide0->dumpNodes(nbNodes); cout << endl;
4013   TVerticalEdgeAdaptor* vSide1 = (TVerticalEdgeAdaptor*) VertiCurve(1);
4014   cout << "Verti side 1: "; vSide1->dumpNodes(nbNodes); cout << endl;
4015   delete hSize0; delete hSize1; delete vSide0; delete vSide1;
4016 #endif
4017 }
4018
4019 //================================================================================
4020 /*!
4021  * \brief Creates TVerticalEdgeAdaptor 
4022   * \param columnsMap - node column map
4023   * \param parameter - normalized parameter
4024  */
4025 //================================================================================
4026
4027 StdMeshers_PrismAsBlock::TVerticalEdgeAdaptor::
4028 TVerticalEdgeAdaptor( const TParam2ColumnMap* columnsMap, const double parameter)
4029 {
4030   myNodeColumn = & getColumn( columnsMap, parameter )->second;
4031 }
4032
4033 //================================================================================
4034 /*!
4035  * \brief Return coordinates for the given normalized parameter
4036   * \param U - normalized parameter
4037   * \retval gp_Pnt - coordinates
4038  */
4039 //================================================================================
4040
4041 gp_Pnt StdMeshers_PrismAsBlock::TVerticalEdgeAdaptor::Value(const Standard_Real U) const
4042 {
4043   const SMDS_MeshNode* n1;
4044   const SMDS_MeshNode* n2;
4045   double r = getRAndNodes( myNodeColumn, U, n1, n2 );
4046   return gpXYZ(n1) * ( 1 - r ) + gpXYZ(n2) * r;
4047 }
4048
4049 //================================================================================
4050 /*!
4051  * \brief Dump ids of nodes
4052  */
4053 //================================================================================
4054
4055 void StdMeshers_PrismAsBlock::TVerticalEdgeAdaptor::dumpNodes(int nbNodes) const
4056 {
4057 #ifdef _DEBUG_
4058   for ( int i = 0; i < nbNodes && i < myNodeColumn->size(); ++i )
4059     cout << (*myNodeColumn)[i]->GetID() << " ";
4060   if ( nbNodes < myNodeColumn->size() )
4061     cout << myNodeColumn->back()->GetID();
4062 #endif
4063 }
4064
4065 //================================================================================
4066 /*!
4067  * \brief Return coordinates for the given normalized parameter
4068   * \param U - normalized parameter
4069   * \retval gp_Pnt - coordinates
4070  */
4071 //================================================================================
4072
4073 gp_Pnt StdMeshers_PrismAsBlock::THorizontalEdgeAdaptor::Value(const Standard_Real U) const
4074 {
4075   return mySide->TSideFace::Value( U, myV );
4076 }
4077
4078 //================================================================================
4079 /*!
4080  * \brief Dump ids of <nbNodes> first nodes and the last one
4081  */
4082 //================================================================================
4083
4084 void StdMeshers_PrismAsBlock::THorizontalEdgeAdaptor::dumpNodes(int nbNodes) const
4085 {
4086 #ifdef _DEBUG_
4087   // Not bedugged code. Last node is sometimes incorrect
4088   const TSideFace* side = mySide;
4089   double u = 0;
4090   if ( mySide->IsComplex() )
4091     side = mySide->GetComponent(0,u);
4092
4093   TParam2ColumnIt col, col2;
4094   TParam2ColumnMap* u2cols = side->GetColumns();
4095   side->GetColumns( u , col, col2 );
4096   
4097   int j, i = myV ? mySide->ColumnHeight()-1 : 0;
4098
4099   const SMDS_MeshNode* n = 0;
4100   const SMDS_MeshNode* lastN
4101     = side->IsForward() ? u2cols->rbegin()->second[ i ] : u2cols->begin()->second[ i ];
4102   for ( j = 0; j < nbNodes && n != lastN; ++j )
4103   {
4104     n = col->second[ i ];
4105     cout << n->GetID() << " ";
4106     if ( side->IsForward() )
4107       ++col;
4108     else
4109       --col;
4110   }
4111
4112   // last node
4113   u = 1;
4114   if ( mySide->IsComplex() )
4115     side = mySide->GetComponent(1,u);
4116
4117   side->GetColumns( u , col, col2 );
4118   if ( n != col->second[ i ] )
4119     cout << col->second[ i ]->GetID();
4120 #endif
4121 }
4122
4123 //================================================================================
4124 /*!
4125  * \brief Costructor of TPCurveOnHorFaceAdaptor fills its map of
4126  * normalized parameter to node UV on a horizontal face
4127  *  \param [in] sideFace - lateral prism side
4128  *  \param [in] isTop - is \a horFace top or bottom of the prism
4129  *  \param [in] horFace - top or bottom face of the prism
4130  */
4131 //================================================================================
4132
4133 StdMeshers_PrismAsBlock::
4134 TPCurveOnHorFaceAdaptor::TPCurveOnHorFaceAdaptor( const TSideFace*   sideFace,
4135                                                   const bool         isTop,
4136                                                   const TopoDS_Face& horFace)
4137 {
4138   if ( sideFace && !horFace.IsNull() )
4139   {
4140     //cout << "\n\t FACE " << sideFace->FaceID() << endl;
4141     const int Z = isTop ? sideFace->ColumnHeight() - 1 : 0;
4142     map<double, const SMDS_MeshNode* > u2nodes;
4143     sideFace->GetNodesAtZ( Z, u2nodes );
4144     if ( u2nodes.empty() )
4145       return;
4146
4147     SMESH_MesherHelper helper( *sideFace->GetMesh() );
4148     helper.SetSubShape( horFace );
4149
4150     bool okUV;
4151     gp_XY uv;
4152     double f,l;
4153     Handle(Geom2d_Curve) C2d;
4154     int edgeID = -1;
4155     const double tol = 10 * helper.MaxTolerance( horFace );
4156     const SMDS_MeshNode* prevNode = u2nodes.rbegin()->second;
4157
4158     map<double, const SMDS_MeshNode* >::iterator u2n = u2nodes.begin();
4159     for ( ; u2n != u2nodes.end(); ++u2n )
4160     {
4161       const SMDS_MeshNode* n = u2n->second;
4162       okUV = false;
4163       if ( n->GetPosition()->GetTypeOfPosition() == SMDS_TOP_EDGE )
4164       {
4165         if ( n->getshapeId() != edgeID )
4166         {
4167           C2d.Nullify();
4168           edgeID = n->getshapeId();
4169           TopoDS_Shape S = helper.GetSubShapeByNode( n, helper.GetMeshDS() );
4170           if ( !S.IsNull() && S.ShapeType() == TopAbs_EDGE )
4171           {
4172             C2d = BRep_Tool::CurveOnSurface( TopoDS::Edge( S ), horFace, f,l );
4173           }
4174         }
4175         if ( !C2d.IsNull() )
4176         {
4177           double u = static_cast< const SMDS_EdgePosition* >( n->GetPosition() )->GetUParameter();
4178           if ( f <= u && u <= l )
4179           {
4180             uv = C2d->Value( u ).XY();
4181             okUV = helper.CheckNodeUV( horFace, n, uv, tol );
4182           }
4183         }
4184       }
4185       if ( !okUV )
4186         uv = helper.GetNodeUV( horFace, n, prevNode, &okUV );
4187
4188       myUVmap.insert( myUVmap.end(), make_pair( u2n->first, uv ));
4189       // cout << n->getshapeId() << " N " << n->GetID()
4190       //      << " \t" << uv.X() << ", " << uv.Y() << " \t" << u2n->first << endl;
4191
4192       prevNode = n;
4193     }
4194   }
4195 }
4196
4197 //================================================================================
4198 /*!
4199  * \brief Return UV on pcurve for the given normalized parameter
4200   * \param U - normalized parameter
4201   * \retval gp_Pnt - coordinates
4202  */
4203 //================================================================================
4204
4205 gp_Pnt2d StdMeshers_PrismAsBlock::TPCurveOnHorFaceAdaptor::Value(const Standard_Real U) const
4206 {
4207   map< double, gp_XY >::const_iterator i1 = myUVmap.upper_bound( U );
4208
4209   if ( i1 == myUVmap.end() )
4210     return myUVmap.empty() ? gp_XY(0,0) : myUVmap.rbegin()->second;
4211
4212   if ( i1 == myUVmap.begin() )
4213     return (*i1).second;
4214
4215   map< double, gp_XY >::const_iterator i2 = i1--;
4216
4217   double r = ( U - i1->first ) / ( i2->first - i1->first );
4218   return i1->second * ( 1 - r ) + i2->second * r;
4219 }