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