Salome HOME
Update of CheckDone
[modules/smesh.git] / src / StdMeshers / StdMeshers_Prism_3D.cxx
1 // Copyright (C) 2007-2020  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_MeshEditor.hxx"
37 #include "SMESH_MesherHelper.hxx"
38 #include "StdMeshers_FaceSide.hxx"
39 #include "StdMeshers_ProjectionSource1D.hxx"
40 #include "StdMeshers_ProjectionSource2D.hxx"
41 #include "StdMeshers_ProjectionUtils.hxx"
42 #include "StdMeshers_Projection_1D.hxx"
43 #include "StdMeshers_Projection_1D2D.hxx"
44 #include "StdMeshers_Quadrangle_2D.hxx"
45
46 #include "utilities.h"
47
48 #include <BRepAdaptor_CompCurve.hxx>
49 #include <BRep_Tool.hxx>
50 #include <Bnd_B3d.hxx>
51 #include <Geom2dAdaptor_Curve.hxx>
52 #include <Geom2d_Line.hxx>
53 #include <GeomLib_IsPlanarSurface.hxx>
54 #include <Geom_Curve.hxx>
55 #include <Standard_ErrorHandler.hxx>
56 #include <TopExp.hxx>
57 #include <TopExp_Explorer.hxx>
58 #include <TopTools_ListIteratorOfListOfShape.hxx>
59 #include <TopTools_ListOfShape.hxx>
60 #include <TopTools_MapOfShape.hxx>
61 #include <TopTools_SequenceOfShape.hxx>
62 #include <TopoDS.hxx>
63 #include <gp_Ax2.hxx>
64 #include <gp_Ax3.hxx>
65
66 #include <limits>
67 #include <numeric>
68
69 using namespace std;
70
71 #define RETURN_BAD_RESULT(msg) { MESSAGE(")-: Error: " << msg); return false; }
72 #define gpXYZ(n) SMESH_TNodeXYZ(n)
73
74 #ifdef _DEBUG_
75 #define DBGOUT(msg) //cout << msg << endl;
76 #define SHOWYXZ(msg, xyz)                                               \
77   //{ gp_Pnt p (xyz); cout << msg << " ("<< p.X() << "; " <<p.Y() << "; " <<p.Z() << ") " <<endl; }
78 #else
79 #define DBGOUT(msg)
80 #define SHOWYXZ(msg, xyz)
81 #endif
82
83 namespace NSProjUtils = StdMeshers_ProjectionUtils;
84
85 typedef SMESH_Comment TCom;
86
87 enum { ID_BOT_FACE = SMESH_Block::ID_Fxy0,
88        ID_TOP_FACE = SMESH_Block::ID_Fxy1,
89        BOTTOM_EDGE = 0, TOP_EDGE, V0_EDGE, V1_EDGE, // edge IDs in face
90        NB_WALL_FACES = 4 }; //
91
92 namespace
93 {
94   //=======================================================================
95   /*!
96    * \brief Auxiliary mesh
97    */
98   struct TmpMesh: public SMESH_Mesh
99   {
100     TmpMesh() {
101       _isShapeToMesh = (_id = 0);
102       _myMeshDS  = new SMESHDS_Mesh( _id, true );
103     }
104   };
105   //=======================================================================
106   /*!
107    * \brief Quadrangle algorithm
108    */
109   class TQuadrangleAlgo : public StdMeshers_Quadrangle_2D
110   {
111     typedef NCollection_DataMap< TopoDS_Face, FaceQuadStruct::Ptr > TFace2QuadMap;
112     TFace2QuadMap myFace2QuadMap;
113
114     TQuadrangleAlgo(SMESH_Gen* gen)
115       : StdMeshers_Quadrangle_2D( gen->GetANewId(), gen)
116     {
117     }
118   public:
119
120     //================================================================================
121     // Clear data of TQuadrangleAlgo at destruction
122     struct Cleaner
123     {
124       TQuadrangleAlgo* myAlgo;
125
126       Cleaner(TQuadrangleAlgo* algo): myAlgo( algo ){}
127       ~Cleaner() { myAlgo->reset(); }
128     };
129
130     //================================================================================
131     // Return TQuadrangleAlgo singleton
132     static TQuadrangleAlgo* instance( SMESH_Algo*         fatherAlgo,
133                                       SMESH_MesherHelper* helper=0)
134     {
135       static TQuadrangleAlgo* algo = new TQuadrangleAlgo( fatherAlgo->GetGen() );
136       if ( helper &&
137            algo->myProxyMesh &&
138            algo->myProxyMesh->GetMesh() != helper->GetMesh() )
139         algo->myProxyMesh.reset( new SMESH_ProxyMesh( *helper->GetMesh() ));
140
141       algo->myQuadList.clear();
142       algo->myHelper = 0;
143
144       if ( helper )
145         algo->_quadraticMesh = helper->GetIsQuadratic();
146
147       return algo;
148     }
149
150     //================================================================================
151     // Clear collected data
152     void reset()
153     {
154       StdMeshers_Quadrangle_2D::myQuadList.clear();
155       StdMeshers_Quadrangle_2D::myHelper = nullptr;
156       StdMeshers_Quadrangle_2D::myProxyMesh.reset();
157       myFace2QuadMap.Clear();
158     }
159
160     //================================================================================
161     /*!
162      * \brief Return FaceQuadStruct if a given FACE can be meshed by StdMeshers_Quadrangle_2D
163      */
164     FaceQuadStruct::Ptr CheckNbEdges(SMESH_Mesh&         theMesh,
165                                      const TopoDS_Shape& theShape )
166     {
167       const TopoDS_Face& face = TopoDS::Face( theShape );
168       if ( myFace2QuadMap.IsBound( face ))
169         return myFace2QuadMap.Find( face );
170
171       FaceQuadStruct::Ptr &  resultQuad = * myFace2QuadMap.Bound( face, FaceQuadStruct::Ptr() );
172
173       FaceQuadStruct::Ptr quad =
174         StdMeshers_Quadrangle_2D::CheckNbEdges( theMesh, face, /*considerMesh=*/false, myHelper );
175       if ( quad )
176       {
177         // check if the quadrangle mesh would be valid
178
179         // check existing 1D mesh
180         // int nbSegments[4], i = 0;
181         // for ( FaceQuadStruct::Side & side : quad->side )
182         //   nbSegments[ i++ ] = side.grid->NbSegments();
183         // if ( nbSegments[0] > 0 && nbSegments[2] > 0 && nbSegments[0] != nbSegments[2] ||
184         //      nbSegments[1] > 0 && nbSegments[3] > 0 && nbSegments[1] != nbSegments[3] )
185         //   return resultQuad;
186
187         int nbEdges = 0;
188         for ( FaceQuadStruct::Side & side : quad->side )
189           nbEdges += side.grid->NbEdges();
190         if ( nbEdges == 4 )
191           return resultQuad = quad;
192
193         TmpMesh mesh;
194         mesh.ShapeToMesh( face );
195         SMESHDS_Mesh* meshDS = mesh.GetMeshDS();
196         SMESH_MesherHelper helper( mesh );
197         helper.SetSubShape( face );
198         helper.SetElementsOnShape( true );
199
200         // create nodes on all VERTEX'es
201         for ( TopExp_Explorer vert( face, TopAbs_VERTEX ); vert.More(); vert.Next() )
202           mesh.GetSubMesh( vert.Current() )->ComputeStateEngine( SMESH_subMesh::COMPUTE );
203
204         FaceQuadStruct::Ptr tmpQuad( new FaceQuadStruct() );
205         tmpQuad->side.resize( 4 );
206
207         // divide quad sides into halves at least
208         const SMDS_MeshNode* node;
209         for ( int iDir = 0; iDir < 2; ++iDir )
210         {
211           StdMeshers_FaceSidePtr sides[2] = { quad->side[iDir], quad->side[iDir+2] };
212           std::map< double, const SMDS_MeshNode* > nodes[2];
213           for ( int iS : { 0, 1 } )
214           {
215             node = SMESH_Algo::VertexNode( sides[iS]->FirstVertex(), meshDS );
216             nodes[iS].insert( std::make_pair( 0, node ));
217             double curLen = 0;
218             for ( int iE = 1; iE < sides[iS]->NbEdges(); ++iE )
219             {
220               curLen += sides[iS]->EdgeLength( iE - 1 );
221               double u = curLen / sides[iS]->Length();
222               node = SMESH_Algo::VertexNode( sides[iS]->FirstVertex( iE ), meshDS );
223               nodes[iS  ].insert( std::make_pair( u, node ));
224               nodes[1-iS].insert( std::make_pair( u, nullptr ));
225             }
226             nodes[iS].insert( std::make_pair( 0.5, nullptr ));
227             node = SMESH_Algo::VertexNode( sides[iS]->LastVertex(), meshDS );
228             nodes[iS].insert( std::make_pair( 1, node ));
229           }
230
231           for ( int iS : { 0, 1 } )
232           {
233             UVPtStructVec sideNodes;
234             sideNodes.reserve( nodes[ iS ].size() );
235             for ( auto & u_node : nodes[ iS ])
236             {
237               if ( !u_node.second )
238               {
239                 gp_Pnt p = sides[iS]->Value3d( u_node.first );
240                 u_node.second = meshDS->AddNode( p.X(), p.Y(), p.Z() );
241                 TopoDS_Edge edge;
242                 double param = sides[iS]->Parameter( u_node.first, edge );
243                 meshDS->SetNodeOnEdge( u_node.second, edge, param );
244               }
245               sideNodes.push_back( u_node.second );
246               sideNodes.back().SetUV( helper.GetNodeUV( face, u_node.second ));
247             }
248             tmpQuad->side[ iS ? iDir+2 : iDir ] = StdMeshers_FaceSide::New( sideNodes, face );
249           }
250         }
251         StdMeshers_Quadrangle_2D::myCheckOri = true;
252         StdMeshers_Quadrangle_2D::myQuadList.clear();
253         StdMeshers_Quadrangle_2D::myQuadList.push_back( tmpQuad );
254         StdMeshers_Quadrangle_2D::myHelper = &helper;
255         if ( StdMeshers_Quadrangle_2D::computeQuadDominant( mesh, face, tmpQuad ) &&
256              StdMeshers_Quadrangle_2D::check())
257         {
258           resultQuad = quad;
259         }
260         StdMeshers_Quadrangle_2D::myQuadList.clear();
261         StdMeshers_Quadrangle_2D::myHelper = nullptr;
262       }
263       return resultQuad;
264     }
265   };
266
267   //=======================================================================
268   /*!
269    * \brief Algorithm projecting 1D mesh
270    */
271   struct TProjction1dAlgo : public StdMeshers_Projection_1D
272   {
273     StdMeshers_ProjectionSource1D myHyp;
274
275     TProjction1dAlgo(SMESH_Gen* gen)
276       : StdMeshers_Projection_1D( gen->GetANewId(), gen),
277         myHyp( gen->GetANewId(), gen)
278     {
279       StdMeshers_Projection_1D::_sourceHypo = & myHyp;
280     }
281     static TProjction1dAlgo* instance( SMESH_Algo* fatherAlgo )
282     {
283       static TProjction1dAlgo* algo = new TProjction1dAlgo( fatherAlgo->GetGen() );
284       return algo;
285     }
286   };
287   //=======================================================================
288   /*!
289    * \brief Algorithm projecting 2D mesh
290    */
291   struct TProjction2dAlgo : public StdMeshers_Projection_1D2D
292   {
293     StdMeshers_ProjectionSource2D myHyp;
294
295     TProjction2dAlgo(SMESH_Gen* gen)
296       : StdMeshers_Projection_1D2D( gen->GetANewId(), gen),
297         myHyp( gen->GetANewId(), gen)
298     {
299       StdMeshers_Projection_2D::_sourceHypo = & myHyp;
300     }
301     static TProjction2dAlgo* instance( SMESH_Algo* fatherAlgo )
302     {
303       static TProjction2dAlgo* algo = new TProjction2dAlgo( fatherAlgo->GetGen() );
304       return algo;
305     }
306     const NSProjUtils::TNodeNodeMap& GetNodesMap()
307     {
308       return _src2tgtNodes;
309     }
310     void SetEventListener( SMESH_subMesh* tgtSubMesh )
311     {
312       NSProjUtils::SetEventListener( tgtSubMesh,
313                                      _sourceHypo->GetSourceFace(),
314                                      _sourceHypo->GetSourceMesh() );
315     }
316   };
317   //=======================================================================
318   /*!
319    * \brief Returns already computed EDGEs
320    */
321   void getPrecomputedEdges( SMESH_MesherHelper&    theHelper,
322                             const TopoDS_Shape&    theShape,
323                             vector< TopoDS_Edge >& theEdges)
324   {
325     theEdges.clear();
326
327     SMESHDS_Mesh* meshDS = theHelper.GetMeshDS();
328     SMESHDS_SubMesh* sm;
329
330     TopTools_IndexedMapOfShape edges;
331     TopExp::MapShapes( theShape, TopAbs_EDGE, edges );
332     for ( int iE = 1; iE <= edges.Extent(); ++iE )
333     {
334       const TopoDS_Shape edge = edges( iE );
335       if (( ! ( sm = meshDS->MeshElements( edge ))) ||
336           ( sm->NbElements() == 0 ))
337         continue;
338
339       // there must not be FACEs meshed with triangles and sharing a computed EDGE
340       // as the precomputed EDGEs are used for propagation other to 'vertical' EDGEs
341       bool faceFound = false;
342       PShapeIteratorPtr faceIt =
343         theHelper.GetAncestors( edge, *theHelper.GetMesh(), TopAbs_FACE );
344       while ( const TopoDS_Shape* face = faceIt->next() )
345
346         if (( sm = meshDS->MeshElements( *face )) &&
347             ( sm->NbElements() > 0 ) &&
348             ( !theHelper.IsSameElemGeometry( sm, SMDSGeom_QUADRANGLE ) ))
349         {
350           faceFound = true;
351           break;
352         }
353       if ( !faceFound )
354         theEdges.push_back( TopoDS::Edge( edge ));
355     }
356   }
357
358   //================================================================================
359   /*!
360    * \brief Make \a botE be the BOTTOM_SIDE of \a quad.
361    *        Return false if the BOTTOM_SIDE is composite
362    */
363   //================================================================================
364
365   bool setBottomEdge( const TopoDS_Edge&   botE,
366                       FaceQuadStruct::Ptr& quad,
367                       const TopoDS_Shape&  face)
368   {
369     quad->side[ QUAD_TOP_SIDE  ].grid->Reverse();
370     quad->side[ QUAD_LEFT_SIDE ].grid->Reverse();
371     int edgeIndex = 0;
372     bool isComposite = false;
373     for ( size_t i = 0; i < quad->side.size(); ++i )
374     {
375       StdMeshers_FaceSidePtr quadSide = quad->side[i];
376       for ( int iE = 0; iE < quadSide->NbEdges(); ++iE )
377         if ( botE.IsSame( quadSide->Edge( iE )))
378         {
379           if ( quadSide->NbEdges() > 1 )
380             isComposite = true; //return false;
381           edgeIndex = i;
382           i = quad->side.size(); // to quit from the outer loop
383           break;
384         }
385     }
386     if ( edgeIndex != QUAD_BOTTOM_SIDE )
387       quad->shift( quad->side.size() - edgeIndex, /*keepUnitOri=*/false );
388
389     quad->face = TopoDS::Face( face );
390
391     return !isComposite;
392   }
393
394   //================================================================================
395   /*!
396    * \brief Return iterator pointing to node column for the given parameter
397    * \param columnsMap - node column map
398    * \param parameter - parameter
399    * \retval TParam2ColumnMap::iterator - result
400    *
401    * it returns closest left column
402    */
403   //================================================================================
404
405   TParam2ColumnIt getColumn( const TParam2ColumnMap* columnsMap,
406                              const double            parameter )
407   {
408     TParam2ColumnIt u_col = columnsMap->upper_bound( parameter );
409     if ( u_col != columnsMap->begin() )
410       --u_col;
411     return u_col; // return left column
412   }
413
414   //================================================================================
415   /*!
416    * \brief Return nodes around given parameter and a ratio
417    * \param column - node column
418    * \param param - parameter
419    * \param node1 - lower node
420    * \param node2 - upper node
421    * \retval double - ratio
422    */
423   //================================================================================
424
425   double getRAndNodes( const TNodeColumn*     column,
426                        const double           param,
427                        const SMDS_MeshNode* & node1,
428                        const SMDS_MeshNode* & node2)
429   {
430     if ( param >= 1.0 || column->size() == 1) {
431       node1 = node2 = column->back();
432       return 0;
433     }
434
435     int i = int( param * ( column->size() - 1 ));
436     double u0 = double( i )/ double( column->size() - 1 );
437     double r = ( param - u0 ) * ( column->size() - 1 );
438
439     node1 = (*column)[ i ];
440     node2 = (*column)[ i + 1];
441     return r;
442   }
443
444   //================================================================================
445   /*!
446    * \brief Compute boundary parameters of face parts
447     * \param nbParts - nb of parts to split columns into
448     * \param columnsMap - node columns of the face to split
449     * \param params - computed parameters
450    */
451   //================================================================================
452
453   void splitParams( const int               nbParts,
454                     const TParam2ColumnMap* columnsMap,
455                     vector< double > &      params)
456   {
457     params.clear();
458     params.reserve( nbParts + 1 );
459     TParam2ColumnIt last_par_col = --columnsMap->end();
460     double par = columnsMap->begin()->first; // 0.
461     double parLast = last_par_col->first;
462     params.push_back( par );
463     for ( int i = 0; i < nbParts - 1; ++ i )
464     {
465       double partSize = ( parLast - par ) / double ( nbParts - i );
466       TParam2ColumnIt par_col = getColumn( columnsMap, par + partSize );
467       if ( par_col->first == par ) {
468         ++par_col;
469         if ( par_col == last_par_col ) {
470           while ( i < nbParts - 1 )
471             params.push_back( par + partSize * i++ );
472           break;
473         }
474       }
475       par = par_col->first;
476       params.push_back( par );
477     }
478     params.push_back( parLast ); // 1.
479   }
480
481   //================================================================================
482   /*!
483    * \brief Return coordinate system for z-th layer of nodes
484    */
485   //================================================================================
486
487   gp_Ax2 getLayerCoordSys(const int                           z,
488                           const vector< const TNodeColumn* >& columns,
489                           int&                                xColumn)
490   {
491     // gravity center of a layer
492     gp_XYZ O(0,0,0);
493     int vertexCol = -1;
494     for ( size_t i = 0; i < columns.size(); ++i )
495     {
496       O += gpXYZ( (*columns[ i ])[ z ]);
497       if ( vertexCol < 0 &&
498            columns[ i ]->front()->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX )
499         vertexCol = i;
500     }
501     O /= columns.size();
502
503     // Z axis
504     gp_Vec Z(0,0,0);
505     int iPrev = columns.size()-1;
506     for ( size_t i = 0; i < columns.size(); ++i )
507     {
508       gp_Vec v1( O, gpXYZ( (*columns[ iPrev ])[ z ]));
509       gp_Vec v2( O, gpXYZ( (*columns[ i ]    )[ z ]));
510       Z += v1 ^ v2;
511       iPrev = i;
512     }
513
514     if ( vertexCol >= 0 )
515     {
516       O = gpXYZ( (*columns[ vertexCol ])[ z ]);
517     }
518     if ( xColumn < 0 || xColumn >= (int) columns.size() )
519     {
520       // select a column for X dir
521       double maxDist = 0;
522       for ( size_t i = 0; i < columns.size(); ++i )
523       {
524         double dist = ( O - gpXYZ((*columns[ i ])[ z ])).SquareModulus();
525         if ( dist > maxDist )
526         {
527           xColumn = i;
528           maxDist = dist;
529         }
530       }
531     }
532
533     // X axis
534     gp_Vec X( O, gpXYZ( (*columns[ xColumn ])[ z ]));
535
536     return gp_Ax2( O, Z, X);
537   }
538
539   //================================================================================
540   /*!
541    * \brief Removes submeshes that are or can be meshed with regular grid from given list
542    *  \retval int - nb of removed submeshes
543    */
544   //================================================================================
545
546   int removeQuasiQuads(list< SMESH_subMesh* >&   notQuadSubMesh,
547                        SMESH_MesherHelper*       helper,
548                        TQuadrangleAlgo*          quadAlgo)
549   {
550     int nbRemoved = 0;
551     //SMESHDS_Mesh* mesh = notQuadSubMesh.front()->GetFather()->GetMeshDS();
552     list< SMESH_subMesh* >::iterator smIt = notQuadSubMesh.begin();
553     while ( smIt != notQuadSubMesh.end() )
554     {
555       SMESH_subMesh* faceSm = *smIt;
556       SMESHDS_SubMesh* faceSmDS = faceSm->GetSubMeshDS();
557       int nbQuads = faceSmDS ? faceSmDS->NbElements() : 0;
558       bool toRemove;
559       if ( nbQuads > 0 )
560         toRemove = helper->IsStructured( faceSm );
561       else
562         toRemove = ( quadAlgo->CheckNbEdges( *helper->GetMesh(),
563                                              faceSm->GetSubShape() ) != NULL );
564       nbRemoved += toRemove;
565       if ( toRemove )
566         smIt = notQuadSubMesh.erase( smIt );
567       else
568         ++smIt;
569     }
570
571     return nbRemoved;
572   }
573
574   //================================================================================
575   /*!
576    * \brief Return and angle between two EDGEs
577    *  \return double - the angle normalized so that
578    * >~ 0  -> 2.0
579    *  PI/2 -> 1.0
580    *  PI   -> 0.0
581    * -PI/2 -> -1.0
582    * <~ 0  -> -2.0
583    */
584   //================================================================================
585
586   // double normAngle(const TopoDS_Edge & E1, const TopoDS_Edge & E2, const TopoDS_Face & F)
587   // {
588   //   return SMESH_MesherHelper::GetAngle( E1, E2, F ) / ( 0.5 * M_PI );
589   // }
590
591   //================================================================================
592   /*!
593    * Consider continuous straight EDGES as one side - mark them to unite
594    */
595   //================================================================================
596
597   int countNbSides( const Prism_3D::TPrismTopo & thePrism,
598                     vector<int> &                nbUnitePerEdge,
599                     vector< double > &           edgeLength)
600   {
601     int nbEdges = thePrism.myNbEdgesInWires.front();  // nb outer edges
602     int nbSides = nbEdges;
603
604
605     list< TopoDS_Edge >::const_iterator edgeIt = thePrism.myBottomEdges.begin();
606     std::advance( edgeIt, nbEdges-1 );
607     TopoDS_Edge   prevE = *edgeIt;
608     // bool isPrevStraight = SMESH_Algo::IsStraight( prevE );
609     // int           iPrev = nbEdges - 1;
610
611     // int iUnite = -1; // the first of united EDGEs
612
613     // analyse angles between EDGEs
614     int nbCorners = 0;
615     vector< bool > isCorner( nbEdges );
616     edgeIt = thePrism.myBottomEdges.begin();
617     for ( int iE = 0; iE < nbEdges; ++iE, ++edgeIt )
618     {
619       const TopoDS_Edge&  curE = *edgeIt;
620       edgeLength[ iE ] = SMESH_Algo::EdgeLength( curE );
621
622       // double normAngle = normAngle( prevE, curE, thePrism.myBottom );
623       // isCorner[ iE ] = false;
624       // if ( normAngle < 2.0 )
625       // {
626       //   if ( normAngle < 0.001 ) // straight or obtuse angle
627       //   {
628       //     // unite EDGEs in order not to put a corner of the unit quadrangle at this VERTEX
629       //     if ( iUnite < 0 )
630       //       iUnite = iPrev;
631       //     nbUnitePerEdge[ iUnite ]++;
632       //     nbUnitePerEdge[ iE ] = -1;
633       //     --nbSides;
634       //   }
635       //   else
636       //   {
637       //     isCorner[ iE ] = true;
638       //     nbCorners++;
639       //     iUnite = -1;
640       //   }
641       // }
642       // prevE = curE;
643     }
644
645     if ( nbCorners > 4 )
646     {
647       // define which of corners to put on a side of the unit quadrangle
648     }
649     // edgeIt = thePrism.myBottomEdges.begin();
650     // for ( int iE = 0; iE < nbEdges; ++iE, ++edgeIt )
651     // {
652     //   const TopoDS_Edge&  curE = *edgeIt;
653     //   edgeLength[ iE ] = SMESH_Algo::EdgeLength( curE );
654
655     //   const bool isCurStraight = SMESH_Algo::IsStraight( curE );
656     //   if ( isPrevStraight && isCurStraight && SMESH_Algo::IsContinuous( prevE, curE ))
657     //   {
658     //     if ( iUnite < 0 )
659     //       iUnite = iPrev;
660     //     nbUnitePerEdge[ iUnite ]++;
661     //     nbUnitePerEdge[ iE ] = -1;
662     //     --nbSides;
663     //   }
664     //   else
665     //   {
666     //     iUnite = -1;
667     //   }
668     //   prevE          = curE;
669     //   isPrevStraight = isCurStraight;
670     //   iPrev = iE;
671     // }
672
673     return nbSides;
674   }
675
676   //================================================================================
677   /*!
678    * \brief Count EDGEs ignoring degenerated ones
679    */
680   //================================================================================
681
682   int CountEdges( const TopoDS_Face& face )
683   {
684     int nbE = 0;
685     for ( TopExp_Explorer edgeExp( face, TopAbs_EDGE ); edgeExp.More(); edgeExp.Next() )
686       if ( !SMESH_Algo::isDegenerated( TopoDS::Edge( edgeExp.Current() )))
687         ++nbE;
688
689     return nbE;
690   }
691
692   //================================================================================
693   /*!
694    * \brief Set/get wire index to FaceQuadStruct
695    */
696   //================================================================================
697
698   void setWireIndex( TFaceQuadStructPtr& quad, int iWire )
699   {
700     quad->iSize = iWire;
701   }
702   int getWireIndex( const TFaceQuadStructPtr& quad )
703   {
704     return quad->iSize;
705   }
706
707   //================================================================================
708   /*!
709    * \brief Print Python commands adding given points to a mesh
710    */
711   //================================================================================
712
713   void pointsToPython(const std::vector<gp_XYZ>& p)
714   {
715 #ifdef _DEBUG_
716     for ( size_t i = SMESH_Block::ID_V000; i < p.size(); ++i )
717     {
718       cout << "mesh.AddNode( " << p[i].X() << ", "<< p[i].Y() << ", "<< p[i].Z() << ") # " << i <<" " ;
719       SMESH_Block::DumpShapeID( i, cout ) << endl;
720     }
721 #endif
722   }
723
724 } // namespace
725
726 //=======================================================================
727 //function : StdMeshers_Prism_3D
728 //purpose  :
729 //=======================================================================
730
731 StdMeshers_Prism_3D::StdMeshers_Prism_3D(int hypId, SMESH_Gen* gen)
732   :SMESH_3D_Algo(hypId, gen)
733 {
734   _name                    = "Prism_3D";
735   _shapeType               = (1 << TopAbs_SOLID); // 1 bit per shape type
736   _onlyUnaryInput          = false; // mesh all SOLIDs at once
737   _requireDiscreteBoundary = false; // mesh FACEs and EDGEs by myself
738   _supportSubmeshes        = true;  // "source" FACE must be meshed by other algo
739   _neededLowerHyps[ 1 ]    = true;  // suppress warning on hiding a global 1D algo
740   _neededLowerHyps[ 2 ]    = true;  // suppress warning on hiding a global 2D algo
741
742   //myProjectTriangles       = false;
743   mySetErrorToSM           = true;  // to pass an error to a sub-mesh of a current solid or not
744   myPrevBottomSM           = 0;     // last treated bottom sub-mesh with a suitable algorithm
745 }
746
747 //================================================================================
748 /*!
749  * \brief Destructor
750  */
751 //================================================================================
752
753 StdMeshers_Prism_3D::~StdMeshers_Prism_3D()
754 {
755   pointsToPython( std::vector<gp_XYZ>() ); // avoid warning: pointsToPython defined but not used
756 }
757
758 //=======================================================================
759 //function : CheckHypothesis
760 //purpose  :
761 //=======================================================================
762
763 bool StdMeshers_Prism_3D::CheckHypothesis(SMESH_Mesh&                          aMesh,
764                                           const TopoDS_Shape&                  aShape,
765                                           SMESH_Hypothesis::Hypothesis_Status& aStatus)
766 {
767   // no hypothesis
768   aStatus = SMESH_Hypothesis::HYP_OK;
769   return true;
770 }
771
772 //=======================================================================
773 //function : Compute
774 //purpose  : Compute mesh on a COMPOUND of SOLIDs
775 //=======================================================================
776
777 bool StdMeshers_Prism_3D::Compute(SMESH_Mesh& theMesh, const TopoDS_Shape& theShape)
778 {
779   SMESH_MesherHelper helper( theMesh );
780   myHelper = &helper;
781   myPrevBottomSM = 0;
782   TQuadrangleAlgo::Cleaner quadCleaner( TQuadrangleAlgo::instance( this ));
783
784   int nbSolids = helper.Count( theShape, TopAbs_SOLID, /*skipSame=*/false );
785   if ( nbSolids < 1 )
786     return true;
787
788   TopTools_IndexedDataMapOfShapeListOfShape faceToSolids;
789   TopExp::MapShapesAndAncestors( theShape, TopAbs_FACE, TopAbs_SOLID, faceToSolids );
790
791   // look for meshed FACEs ("source" FACEs) that must be prism bottoms
792   list< TopoDS_Face > meshedFaces, notQuadMeshedFaces, notQuadFaces;
793   const bool meshHasQuads = ( theMesh.NbQuadrangles() > 0 );
794   for ( int iF = 1; iF <= faceToSolids.Extent(); ++iF )
795   {
796     const TopoDS_Face& face = TopoDS::Face( faceToSolids.FindKey( iF ));
797     SMESH_subMesh*   faceSM = theMesh.GetSubMesh( face );
798     if ( !faceSM->IsEmpty() )
799     {
800       if ( !meshHasQuads ||
801            !helper.IsSameElemGeometry( faceSM->GetSubMeshDS(), SMDSGeom_QUADRANGLE ) ||
802            !helper.IsStructured( faceSM )
803            )
804         notQuadMeshedFaces.push_front( face );
805       else if ( myHelper->Count( face, TopAbs_EDGE, /*ignoreSame=*/false ) != 4 )
806         meshedFaces.push_front( face );
807       else
808         meshedFaces.push_back( face );
809     }
810     // not add not quadrilateral FACE as we can't compute it
811     // else if ( !quadAlgo->CheckNbEdges( theMesh, face ))
812     // // not add not quadrilateral FACE as it can be a prism side
813     // // else if ( myHelper->Count( face, TopAbs_EDGE, /*ignoreSame=*/false ) != 4 )
814     // {
815     //   notQuadFaces.push_back( face );
816     // }
817   }
818   // notQuadFaces are of medium priority, put them before ordinary meshed faces
819   meshedFaces.splice( meshedFaces.begin(), notQuadFaces );
820   // notQuadMeshedFaces are of highest priority, put them before notQuadFaces
821   meshedFaces.splice( meshedFaces.begin(), notQuadMeshedFaces );
822
823   Prism_3D::TPrismTopo prism;
824   myPropagChains = 0;
825   bool selectBottom = meshedFaces.empty();
826
827   if ( nbSolids == 1 )
828   {
829     TopoDS_Shape solid = TopExp_Explorer( theShape, TopAbs_SOLID ).Current();
830     if ( !meshedFaces.empty() )
831       prism.myBottom = meshedFaces.front();
832     return ( initPrism( prism, solid, selectBottom ) &&
833              compute( prism ));
834   }
835
836   // find propagation chains from already computed EDGEs
837   vector< TopoDS_Edge > computedEdges;
838   getPrecomputedEdges( helper, theShape, computedEdges );
839   myPropagChains = new TopTools_IndexedMapOfShape[ computedEdges.size() + 1 ];
840   SMESHUtils::ArrayDeleter< TopTools_IndexedMapOfShape > pcDel( myPropagChains );
841   for ( size_t i = 0, nb = 0; i < computedEdges.size(); ++i )
842   {
843     StdMeshers_ProjectionUtils::GetPropagationEdge( &theMesh, TopoDS_Edge(),
844                                                     computedEdges[i], myPropagChains + nb );
845     if ( myPropagChains[ nb ].Extent() < 2 ) // an empty map is a termination sign
846       myPropagChains[ nb ].Clear();
847     else
848       nb++;
849   }
850
851   TopTools_MapOfShape meshedSolids;
852   NCollection_DataMap< TopoDS_Shape, SMESH_subMesh* > meshedFace2AlgoSM;
853   list< Prism_3D::TPrismTopo > meshedPrism;
854   list< TopoDS_Face > suspectSourceFaces;
855   TopTools_ListIteratorOfListOfShape solidIt;
856
857   while ( meshedSolids.Extent() < nbSolids )
858   {
859     if ( _computeCanceled )
860       return toSM( error( SMESH_ComputeError::New(COMPERR_CANCELED)));
861
862     // compute prisms having avident computed source FACE
863     while ( !meshedFaces.empty() )
864     {
865       TopoDS_Face face = meshedFaces.front();
866       meshedFaces.pop_front();
867       TopTools_ListOfShape& solidList = faceToSolids.ChangeFromKey( face );
868       while ( !solidList.IsEmpty() )
869       {
870         TopoDS_Shape solid = solidList.First();
871         solidList.RemoveFirst();
872         if ( meshedSolids.Add( solid ))
873         {
874           prism.Clear();
875           prism.myBottom = face;
876           if ( meshedFace2AlgoSM.IsBound( face ))
877             prism.myAlgoSM = meshedFace2AlgoSM.Find( face );
878           if ( !initPrism( prism, solid, selectBottom ) ||
879                !compute( prism ))
880             return false;
881
882           SMESHDS_SubMesh* smDS = theMesh.GetMeshDS()->MeshElements( prism.myTop );
883           if ( !myHelper->IsSameElemGeometry( smDS, SMDSGeom_QUADRANGLE ) ||
884                !myHelper->IsStructured( theMesh.GetSubMesh( prism.myTop )))
885           {
886             meshedFaces.push_front( prism.myTop );
887             if ( prism.myAlgoSM  && prism.myAlgoSM->GetAlgo() )
888             {
889               meshedFace2AlgoSM.Bind( prism.myTop,    prism.myAlgoSM );
890               meshedFace2AlgoSM.Bind( prism.myBottom, prism.myAlgoSM );
891             }
892           }
893           else
894           {
895             suspectSourceFaces.push_back( prism.myTop );
896           }
897           meshedPrism.push_back( prism );
898         }
899       }
900     }
901     if ( meshedSolids.Extent() == nbSolids )
902       break;
903
904     // below in the loop we try to find source FACEs somehow
905
906     // project mesh from source FACEs of computed prisms to
907     // prisms sharing wall FACEs
908     list< Prism_3D::TPrismTopo >::iterator prismIt = meshedPrism.begin();
909     for ( ; prismIt != meshedPrism.end(); ++prismIt )
910     {
911       for ( size_t iW = 0; iW < prismIt->myWallQuads.size(); ++iW )
912       {
913         Prism_3D::TQuadList::iterator wQuad = prismIt->myWallQuads[iW].begin();
914         for ( ; wQuad != prismIt->myWallQuads[iW].end(); ++ wQuad )
915         {
916           const TopoDS_Face& wFace = (*wQuad)->face;
917           TopTools_ListOfShape& solidList = faceToSolids.ChangeFromKey( wFace );
918           solidIt.Initialize( solidList );
919           while ( solidIt.More() )
920           {
921             const TopoDS_Shape& solid = solidIt.Value();
922             if ( meshedSolids.Contains( solid )) {
923               solidList.Remove( solidIt );
924               continue; // already computed prism
925             }
926             if ( myHelper->IsBlock( solid ))
927             {
928               bool isStructBase = true;
929               if ( prismIt->myAlgoSM )
930                 isStructBase = ( myHelper->IsSameElemGeometry( prismIt->myAlgoSM->GetSubMeshDS(),
931                                                                SMDSGeom_QUADRANGLE ) &&
932                                  myHelper->IsStructured(prismIt->myAlgoSM ));
933               if ( isStructBase )
934               {
935                 solidIt.Next();
936                 continue; // too trivial
937               }
938             }
939             // find a source FACE of the SOLID: it's a FACE sharing a bottom EDGE with wFace
940             const TopoDS_Edge& wEdge = (*wQuad)->side[ QUAD_TOP_SIDE ].grid->Edge(0);
941             PShapeIteratorPtr faceIt = myHelper->GetAncestors( wEdge, *myHelper->GetMesh(),
942                                                                TopAbs_FACE);
943             while ( const TopoDS_Shape* f = faceIt->next() )
944             {
945               const TopoDS_Face& candidateF = TopoDS::Face( *f );
946               if ( candidateF.IsSame( wFace )) continue;
947               // select a source FACE: prismIt->myBottom or prismIt->myTop
948               TopoDS_Face sourceF = prismIt->myBottom;
949               for ( TopExp_Explorer v( prismIt->myTop, TopAbs_VERTEX ); v.More(); v.Next() )
950                 if ( myHelper->IsSubShape( v.Current(), candidateF )) {
951                   sourceF = prismIt->myTop;
952                   break;
953                 }
954               prism.Clear();
955               prism.myBottom = candidateF;
956               prism.myAlgoSM = prismIt->myAlgoSM;
957               mySetErrorToSM = false;
958               if ( !myHelper->IsSubShape( candidateF, prismIt->myShape3D ) &&
959                    myHelper ->IsSubShape( candidateF, solid ) &&
960                    !myHelper->GetMesh()->GetSubMesh( candidateF )->IsMeshComputed() &&
961                    initPrism( prism, solid, /*selectBottom=*/false ) &&
962                    !myHelper->GetMesh()->GetSubMesh( prism.myTop )->IsMeshComputed() &&
963                    !myHelper->GetMesh()->GetSubMesh( prism.myBottom )->IsMeshComputed() )
964               {
965                 if ( project2dMesh( sourceF, prism.myBottom ))
966                 {
967                   mySetErrorToSM = true;
968                   if ( !compute( prism ))
969                     return false;
970                   SMESHDS_SubMesh* smDS = theMesh.GetMeshDS()->MeshElements( prism.myTop );
971                   if ( !myHelper->IsSameElemGeometry( smDS, SMDSGeom_QUADRANGLE ))
972                   {
973                     meshedFaces.push_front( prism.myTop );
974                     meshedFaces.push_front( prism.myBottom );
975                     selectBottom = false;
976                     if ( prism.myAlgoSM  && prism.myAlgoSM->GetAlgo() )
977                     {
978                       meshedFace2AlgoSM.Bind( prism.myTop, prism.myAlgoSM );
979                       meshedFace2AlgoSM.Bind( prism.myBottom, prism.myAlgoSM );
980                     }
981                   }
982                   meshedPrism.push_back( prism );
983                   meshedSolids.Add( solid );
984                 }
985                 else
986                 {
987                   meshedFaces.push_back( prism.myBottom );
988                   if ( prism.myAlgoSM && prism.myAlgoSM->GetAlgo() )
989                     meshedFace2AlgoSM.Bind( prism.myBottom, prism.myAlgoSM );
990                 }
991               }
992               InitComputeError();
993             }
994             mySetErrorToSM = true;
995             InitComputeError();
996             if ( meshedSolids.Contains( solid ))
997               solidList.Remove( solidIt );
998             else
999               solidIt.Next();
1000           }
1001         }
1002       }
1003       if ( !meshedFaces.empty() )
1004         break; // to compute prisms with avident sources
1005     }
1006
1007     if ( meshedFaces.empty() )
1008     {
1009       meshedFaces.splice( meshedFaces.end(), suspectSourceFaces );
1010       selectBottom = true;
1011     }
1012
1013     // find FACEs with local 1D hyps, which has to be computed by now,
1014     // or at least any computed FACEs
1015     if ( meshedFaces.empty() )
1016     {
1017       int prevNbFaces = 0;
1018       for ( int iF = 1; iF <= faceToSolids.Extent(); ++iF )
1019       {
1020         const TopoDS_Face&               face = TopoDS::Face( faceToSolids.FindKey( iF ));
1021         const TopTools_ListOfShape& solidList = faceToSolids.FindFromKey( face );
1022         if ( solidList.IsEmpty() ) continue;
1023         SMESH_subMesh*                 faceSM = theMesh.GetSubMesh( face );
1024         if ( !faceSM->IsEmpty() )
1025         {
1026           int nbFaces = faceSM->GetSubMeshDS()->NbElements();
1027           if ( prevNbFaces < nbFaces )
1028           {
1029             if ( !meshedFaces.empty() ) meshedFaces.pop_back();
1030             meshedFaces.push_back( face ); // lower priority
1031             selectBottom = true;
1032             prevNbFaces = nbFaces;
1033           }
1034         }
1035         else
1036         {
1037           bool allSubMeComputed = true;
1038           SMESH_subMeshIteratorPtr smIt = faceSM->getDependsOnIterator(false,true);
1039           while ( smIt->more() && allSubMeComputed )
1040             allSubMeComputed = smIt->next()->IsMeshComputed();
1041           if ( allSubMeComputed )
1042           {
1043             faceSM->ComputeStateEngine( SMESH_subMesh::COMPUTE_SUBMESH );
1044             if ( !faceSM->IsEmpty() ) {
1045               meshedFaces.push_front( face ); // higher priority
1046               selectBottom = true;
1047               break;
1048             }
1049             else {
1050               faceSM->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1051             }
1052           }
1053         }
1054       }
1055     }
1056
1057
1058     // TODO. there are other ways to find out the source FACE:
1059     // propagation, topological similarity, etc...
1060
1061     // simply try to mesh all not meshed SOLIDs
1062     if ( meshedFaces.empty() )
1063     {
1064       for ( TopExp_Explorer solid( theShape, TopAbs_SOLID ); solid.More(); solid.Next() )
1065       {
1066         mySetErrorToSM = false;
1067         prism.Clear();
1068         if ( !meshedSolids.Contains( solid.Current() ) &&
1069              initPrism( prism, solid.Current() ))
1070         {
1071           mySetErrorToSM = true;
1072           if ( !compute( prism ))
1073             return false;
1074           meshedFaces.push_front( prism.myTop );
1075           meshedFaces.push_front( prism.myBottom );
1076           meshedPrism.push_back( prism );
1077           meshedSolids.Add( solid.Current() );
1078           selectBottom = true;
1079         }
1080         mySetErrorToSM = true;
1081       }
1082     }
1083
1084     if ( meshedFaces.empty() ) // set same error to 10 not-computed solids
1085     {
1086       SMESH_ComputeErrorPtr err = SMESH_ComputeError::New
1087         ( COMPERR_BAD_INPUT_MESH, "No meshed source face found", this );
1088
1089       const int maxNbErrors = 10; // limit nb errors not to overload the Compute dialog
1090       TopExp_Explorer solid( theShape, TopAbs_SOLID );
1091       for ( int i = 0; ( i < maxNbErrors && solid.More() ); ++i, solid.Next() )
1092         if ( !meshedSolids.Contains( solid.Current() ))
1093         {
1094           SMESH_subMesh* sm = theMesh.GetSubMesh( solid.Current() );
1095           sm->GetComputeError() = err;
1096         }
1097       return error( err );
1098     }
1099   }
1100   return error( COMPERR_OK );
1101 }
1102
1103 //================================================================================
1104 /*!
1105  * \brief Find wall faces by bottom edges
1106  */
1107 //================================================================================
1108
1109 bool StdMeshers_Prism_3D::getWallFaces( Prism_3D::TPrismTopo & thePrism,
1110                                         const int              totalNbFaces)
1111 {
1112   thePrism.myWallQuads.clear();
1113
1114   SMESH_Mesh* mesh = myHelper->GetMesh();
1115
1116   TQuadrangleAlgo* quadAlgo = TQuadrangleAlgo::instance( this, myHelper );
1117
1118   TopTools_MapOfShape faceMap;
1119   TopTools_IndexedDataMapOfShapeListOfShape edgeToFaces;
1120   TopExp::MapShapesAndAncestors( thePrism.myShape3D,
1121                                  TopAbs_EDGE, TopAbs_FACE, edgeToFaces );
1122
1123   // ------------------------------
1124   // Get the 1st row of wall FACEs
1125   // ------------------------------
1126
1127   list< TopoDS_Edge >::iterator edge = thePrism.myBottomEdges.begin();
1128   std::list< int >::iterator     nbE = thePrism.myNbEdgesInWires.begin();
1129   std::list< int > nbQuadsPerWire;
1130   int iE = 0, iWire = 0;
1131   while ( edge != thePrism.myBottomEdges.end() )
1132   {
1133     ++iE;
1134     if ( SMESH_Algo::isDegenerated( *edge ))
1135     {
1136       edge = thePrism.myBottomEdges.erase( edge );
1137       --iE;
1138       --(*nbE);
1139     }
1140     else
1141     {
1142       bool hasWallFace = false;
1143       TopTools_ListIteratorOfListOfShape faceIt( edgeToFaces.FindFromKey( *edge ));
1144       for ( ; faceIt.More(); faceIt.Next() )
1145       {
1146         const TopoDS_Face& face = TopoDS::Face( faceIt.Value() );
1147         if ( !thePrism.myBottom.IsSame( face ))
1148         {
1149           hasWallFace = true;
1150           Prism_3D::TQuadList quadList( 1, quadAlgo->CheckNbEdges( *mesh, face ));
1151           if ( !quadList.back() )
1152             return toSM( error(TCom("Side face #") << shapeID( face )
1153                                << " not meshable with quadrangles"));
1154           bool isCompositeBase = ! setBottomEdge( *edge, quadList.back(), face );
1155           if ( isCompositeBase )
1156           {
1157             // it's OK if all EDGEs of the bottom side belongs to the bottom FACE
1158             StdMeshers_FaceSidePtr botSide = quadList.back()->side[ QUAD_BOTTOM_SIDE ];
1159             for ( int iE = 0; iE < botSide->NbEdges(); ++iE )
1160               if ( !myHelper->IsSubShape( botSide->Edge(iE), thePrism.myBottom ))
1161                 return toSM( error(TCom("Composite 'horizontal' edges are not supported")));
1162           }
1163           if ( faceMap.Add( face ))
1164           {
1165             setWireIndex( quadList.back(), iWire ); // for use in makeQuadsForOutInProjection()
1166             thePrism.myWallQuads.push_back( quadList );
1167           }
1168           break;
1169         }
1170       }
1171       if ( hasWallFace )
1172       {
1173         ++edge;
1174       }
1175       else // seam edge (IPAL53561)
1176       {
1177         edge = thePrism.myBottomEdges.erase( edge );
1178         --iE;
1179         --(*nbE);
1180       }
1181     }
1182     if ( iE == *nbE )
1183     {
1184       iE = 0;
1185       ++iWire;
1186       ++nbE;
1187       int nbQuadPrev = std::accumulate( nbQuadsPerWire.begin(), nbQuadsPerWire.end(), 0 );
1188       nbQuadsPerWire.push_back( thePrism.myWallQuads.size() - nbQuadPrev );
1189     }
1190   }
1191
1192   // -------------------------
1193   // Find the rest wall FACEs
1194   // -------------------------
1195
1196   // Compose a vector of indixes of right neighbour FACE for each wall FACE
1197   // that is not so evident in case of several WIREs in the bottom FACE
1198   thePrism.myRightQuadIndex.clear();
1199   for ( size_t i = 0; i < thePrism.myWallQuads.size(); ++i )
1200   {
1201     thePrism.myRightQuadIndex.push_back( i+1 ); // OK for all but the last EDGE of a WIRE
1202   }
1203   list< int >::iterator nbQinW = nbQuadsPerWire.begin();
1204   for ( int iLeft = 0; nbQinW != nbQuadsPerWire.end(); ++nbQinW )
1205   {
1206     thePrism.myRightQuadIndex[ iLeft + *nbQinW - 1 ] = iLeft; // for the last EDGE of a WIRE
1207     iLeft += *nbQinW;
1208   }
1209
1210   while ( totalNbFaces - faceMap.Extent() > 2 )
1211   {
1212     // find wall FACEs adjacent to each of wallQuads by the right side EDGE
1213     int nbKnownFaces;
1214     do {
1215       nbKnownFaces = faceMap.Extent();
1216       StdMeshers_FaceSidePtr rightSide, topSide; // sides of the quad
1217       for ( size_t i = 0; i < thePrism.myWallQuads.size(); ++i )
1218       {
1219         rightSide = thePrism.myWallQuads[i].back()->side[ QUAD_RIGHT_SIDE ];
1220         for ( int iE = 0; iE < rightSide->NbEdges(); ++iE ) // rightSide can be composite
1221         {
1222           const TopoDS_Edge & rightE = rightSide->Edge( iE );
1223           TopTools_ListIteratorOfListOfShape face( edgeToFaces.FindFromKey( rightE ));
1224           for ( ; face.More(); face.Next() )
1225             if ( faceMap.Add( face.Value() ))
1226             {
1227               // a new wall FACE encountered, store it in thePrism.myWallQuads
1228               const int iRight = thePrism.myRightQuadIndex[i];
1229               topSide = thePrism.myWallQuads[ iRight ].back()->side[ QUAD_TOP_SIDE ];
1230               const TopoDS_Edge&   newBotE = topSide->Edge(0);
1231               const TopoDS_Shape& newWallF = face.Value();
1232               thePrism.myWallQuads[ iRight ].push_back( quadAlgo->CheckNbEdges( *mesh, newWallF ));
1233               if ( !thePrism.myWallQuads[ iRight ].back() )
1234                 return toSM( error(TCom("Side face #") << shapeID( newWallF ) <<
1235                                    " not meshable with quadrangles"));
1236               if ( ! setBottomEdge( newBotE, thePrism.myWallQuads[ iRight ].back(), newWallF ))
1237                 return toSM( error(TCom("Composite 'horizontal' edges are not supported")));
1238             }
1239         }
1240       }
1241     } while ( nbKnownFaces != faceMap.Extent() );
1242
1243     // find wall FACEs adjacent to each of thePrism.myWallQuads by the top side EDGE
1244     if ( totalNbFaces - faceMap.Extent() > 2 )
1245     {
1246       const int nbFoundWalls = faceMap.Extent();
1247       for ( size_t i = 0; i < thePrism.myWallQuads.size(); ++i )
1248       {
1249         StdMeshers_FaceSidePtr topSide = thePrism.myWallQuads[i].back()->side[ QUAD_TOP_SIDE ];
1250         const TopoDS_Edge &       topE = topSide->Edge( 0 );
1251         if ( topSide->NbEdges() > 1 )
1252           return toSM( error(COMPERR_BAD_SHAPE, TCom("Side face #") <<
1253                              shapeID( thePrism.myWallQuads[i].back()->face )
1254                              << " has a composite top edge"));
1255         TopTools_ListIteratorOfListOfShape faceIt( edgeToFaces.FindFromKey( topE ));
1256         for ( ; faceIt.More(); faceIt.Next() )
1257           if ( faceMap.Add( faceIt.Value() ))
1258           {
1259             // a new wall FACE encountered, store it in wallQuads
1260             thePrism.myWallQuads[ i ].push_back( quadAlgo->CheckNbEdges( *mesh, faceIt.Value() ));
1261             if ( !thePrism.myWallQuads[ i ].back() )
1262               return toSM( error(TCom("Side face #") << shapeID( faceIt.Value() ) <<
1263                                  " not meshable with quadrangles"));
1264             if ( ! setBottomEdge( topE, thePrism.myWallQuads[ i ].back(), faceIt.Value() ))
1265               return toSM( error(TCom("Composite 'horizontal' edges are not supported")));
1266             if ( totalNbFaces - faceMap.Extent() == 2 )
1267             {
1268               i = thePrism.myWallQuads.size(); // to quit from the outer loop
1269               break;
1270             }
1271           }
1272       }
1273       if ( nbFoundWalls == faceMap.Extent() )
1274         return toSM( error("Failed to find wall faces"));
1275
1276     }
1277   } // while ( totalNbFaces - faceMap.Extent() > 2 )
1278
1279   // ------------------
1280   // Find the top FACE
1281   // ------------------
1282
1283   if ( thePrism.myTop.IsNull() )
1284   {
1285     // now only top and bottom FACEs are not in the faceMap
1286     faceMap.Add( thePrism.myBottom );
1287     for ( TopExp_Explorer f( thePrism.myShape3D, TopAbs_FACE ); f.More(); f.Next() )
1288       if ( !faceMap.Contains( f.Current() )) {
1289         thePrism.myTop = TopoDS::Face( f.Current() );
1290         break;
1291       }
1292     if ( thePrism.myTop.IsNull() )
1293       return toSM( error("Top face not found"));
1294   }
1295
1296   // Check that the top FACE shares all the top EDGEs
1297   for ( size_t i = 0; i < thePrism.myWallQuads.size(); ++i )
1298   {
1299     StdMeshers_FaceSidePtr topSide = thePrism.myWallQuads[i].back()->side[ QUAD_TOP_SIDE ];
1300     const TopoDS_Edge &       topE = topSide->Edge( 0 );
1301     if ( !myHelper->IsSubShape( topE, thePrism.myTop ))
1302       return toSM( error( TCom("Wrong source face: #") << shapeID( thePrism.myBottom )));
1303   }
1304
1305   return true;
1306 }
1307
1308 //=======================================================================
1309 //function : compute
1310 //purpose  : Compute mesh on a SOLID
1311 //=======================================================================
1312
1313 bool StdMeshers_Prism_3D::compute(const Prism_3D::TPrismTopo& thePrism)
1314 {
1315   myHelper->IsQuadraticSubMesh( thePrism.myShape3D );
1316   if ( _computeCanceled )
1317     return toSM( error( SMESH_ComputeError::New(COMPERR_CANCELED)));
1318
1319   // Assure the bottom is meshed
1320   if ( !computeBase( thePrism ))
1321     return false;
1322
1323   // Make all side FACEs of thePrism meshed with quads
1324   if ( !computeWalls( thePrism ))
1325     return false;
1326
1327   // Analyse mesh and geometry to find all block sub-shapes and submeshes
1328   // (after fixing IPAL52499 myBlock is used as a holder of boundary nodes
1329   // and for 2D projection in hard cases where StdMeshers_Projection_2D fails;
1330   // location of internal nodes is usually computed by StdMeshers_Sweeper)
1331   if ( !myBlock.Init( myHelper, thePrism ))
1332     return toSM( error( myBlock.GetError()));
1333
1334   SMESHDS_Mesh* meshDS = myHelper->GetMeshDS();
1335
1336   int volumeID = meshDS->ShapeToIndex( thePrism.myShape3D );
1337
1338   // Try to get gp_Trsf to get all nodes from bottom ones
1339   vector<gp_Trsf> trsf;
1340   gp_Trsf bottomToTopTrsf;
1341   // if ( !myBlock.GetLayersTransformation( trsf, thePrism ))
1342   //   trsf.clear();
1343   // else if ( !trsf.empty() )
1344   //   bottomToTopTrsf = trsf.back();
1345
1346   // To compute coordinates of a node inside a block using "block approach",
1347   // it is necessary to know
1348   // 1. normalized parameters of the node by which
1349   // 2. coordinates of node projections on all block sub-shapes are computed
1350
1351   // So we fill projections on vertices at once as they are same for all nodes
1352   myShapeXYZ.resize( myBlock.NbSubShapes() );
1353   for ( int iV = SMESH_Block::ID_FirstV; iV < SMESH_Block::ID_FirstE; ++iV ) {
1354     myBlock.VertexPoint( iV, myShapeXYZ[ iV ]);
1355     SHOWYXZ("V point " <<iV << " ", myShapeXYZ[ iV ]);
1356   }
1357
1358   // Projections on the top and bottom faces are taken from nodes existing
1359   // on these faces; find correspondence between bottom and top nodes
1360   myUseBlock = false; // is set to true if projection is done using "block approach"
1361   myBotToColumnMap.clear();
1362   if ( !assocOrProjBottom2Top( bottomToTopTrsf, thePrism ) ) // it also fills myBotToColumnMap
1363     return false;
1364
1365   // If all "vertical" EDGEs are straight, then all nodes of an internal node column
1366   // are located on a line connecting the top node and the bottom node.
1367   bool isStrightColunm = allVerticalEdgesStraight( thePrism );
1368   if ( isStrightColunm )
1369     myUseBlock = false;
1370
1371   // Create nodes inside the block
1372
1373   if ( !myUseBlock )
1374   {
1375     // use transformation (issue 0020680, IPAL0052499) or a "straight line" approach
1376     StdMeshers_Sweeper sweeper;
1377     sweeper.myHelper  = myHelper;
1378     sweeper.myBotFace = thePrism.myBottom;
1379     sweeper.myTopFace = thePrism.myTop;
1380
1381     // load boundary nodes into sweeper
1382     bool dummy;
1383     std::set< const SMDS_MeshNode* > usedEndNodes;
1384     list< TopoDS_Edge >::const_iterator edge = thePrism.myBottomEdges.begin();
1385     for ( ; edge != thePrism.myBottomEdges.end(); ++edge )
1386     {
1387       int edgeID = meshDS->ShapeToIndex( *edge );
1388       TParam2ColumnMap* u2col = const_cast<TParam2ColumnMap*>
1389         ( myBlock.GetParam2ColumnMap( edgeID, dummy ));
1390
1391       TParam2ColumnMap::iterator u2colIt = u2col->begin(), u2colEnd = u2col->end();
1392       const SMDS_MeshNode* n0 = u2colIt->second[0];
1393       const SMDS_MeshNode* n1 = u2col->rbegin()->second[0];
1394       if ( !usedEndNodes.insert ( n0 ).second ) ++u2colIt;
1395       if ( !usedEndNodes.insert ( n1 ).second ) --u2colEnd;
1396
1397       for ( ; u2colIt != u2colEnd; ++u2colIt )
1398         sweeper.myBndColumns.push_back( & u2colIt->second );
1399     }
1400     // load node columns inside the bottom FACE
1401     sweeper.myIntColumns.reserve( myBotToColumnMap.size() );
1402     TNode2ColumnMap::iterator bot_column = myBotToColumnMap.begin();
1403     for ( ; bot_column != myBotToColumnMap.end(); ++bot_column )
1404       sweeper.myIntColumns.push_back( & bot_column->second );
1405
1406     myHelper->SetElementsOnShape( true );
1407
1408     if ( !isStrightColunm )
1409     {
1410       double tol = getSweepTolerance( thePrism );
1411       bool allowHighBndError = !isSimpleBottom( thePrism );
1412       myUseBlock = !sweeper.ComputeNodesByTrsf( tol, allowHighBndError );
1413     }
1414     else if ( sweeper.CheckSameZ() )
1415     {
1416       myUseBlock = !sweeper.ComputeNodesOnStraightSameZ();
1417     }
1418     else
1419     {
1420       myUseBlock = !sweeper.ComputeNodesOnStraight();
1421     }
1422     myHelper->SetElementsOnShape( false );
1423   }
1424
1425   if ( myUseBlock ) // use block approach
1426   {
1427     // loop on nodes inside the bottom face
1428     Prism_3D::TNode prevBNode;
1429     TNode2ColumnMap::iterator bot_column = myBotToColumnMap.begin();
1430     for ( ; bot_column != myBotToColumnMap.end(); ++bot_column )
1431     {
1432       const Prism_3D::TNode& tBotNode = bot_column->first; // bottom TNode
1433       if ( tBotNode.GetPositionType() != SMDS_TOP_FACE &&
1434            myBlock.HasNodeColumn( tBotNode.myNode ))
1435         continue; // node is not inside the FACE
1436
1437       // column nodes; middle part of the column are zero pointers
1438       TNodeColumn& column = bot_column->second;
1439
1440       // check if a column is already computed using non-block approach
1441       size_t i;
1442       for ( i = 0; i < column.size(); ++i )
1443         if ( !column[ i ])
1444           break;
1445       if ( i == column.size() )
1446         continue; // all nodes created
1447
1448       gp_XYZ botParams, topParams;
1449       if ( !tBotNode.HasParams() )
1450       {
1451         // compute bottom node parameters
1452         gp_XYZ paramHint(-1,-1,-1);
1453         if ( prevBNode.IsNeighbor( tBotNode ))
1454           paramHint = prevBNode.GetParams();
1455         if ( !myBlock.ComputeParameters( tBotNode.GetCoords(), tBotNode.ChangeParams(),
1456                                          ID_BOT_FACE, paramHint ))
1457           return toSM( error(TCom("Can't compute normalized parameters for node ")
1458                              << tBotNode.myNode->GetID() << " on the face #"
1459                              << myBlock.SubMesh( ID_BOT_FACE )->GetId() ));
1460         prevBNode = tBotNode;
1461
1462         botParams = topParams = tBotNode.GetParams();
1463         topParams.SetZ( 1 );
1464
1465         // compute top node parameters
1466         if ( column.size() > 2 ) {
1467           gp_Pnt topCoords = gpXYZ( column.back() );
1468           if ( !myBlock.ComputeParameters( topCoords, topParams, ID_TOP_FACE, topParams ))
1469             return toSM( error(TCom("Can't compute normalized parameters ")
1470                                << "for node " << column.back()->GetID()
1471                                << " on the face #"<< column.back()->getshapeId() ));
1472         }
1473       }
1474       else // top nodes are created by projection using parameters
1475       {
1476         botParams = topParams = tBotNode.GetParams();
1477         topParams.SetZ( 1 );
1478       }
1479
1480       myShapeXYZ[ ID_BOT_FACE ] = tBotNode.GetCoords();
1481       myShapeXYZ[ ID_TOP_FACE ] = gpXYZ( column.back() );
1482
1483       // vertical loop
1484       TNodeColumn::iterator columnNodes = column.begin();
1485       for ( int z = 0; columnNodes != column.end(); ++columnNodes, ++z)
1486       {
1487         const SMDS_MeshNode* & node = *columnNodes;
1488         if ( node ) continue; // skip bottom or top node
1489
1490         // params of a node to create
1491         double rz = (double) z / (double) ( column.size() - 1 );
1492         gp_XYZ params = botParams * ( 1 - rz ) + topParams * rz;
1493
1494         // set coords on all faces and nodes
1495         const int nbSideFaces = 4;
1496         int sideFaceIDs[nbSideFaces] = { SMESH_Block::ID_Fx0z,
1497                                          SMESH_Block::ID_Fx1z,
1498                                          SMESH_Block::ID_F0yz,
1499                                          SMESH_Block::ID_F1yz };
1500         for ( int iF = 0; iF < nbSideFaces; ++iF )
1501           if ( !setFaceAndEdgesXYZ( sideFaceIDs[ iF ], params, z ))
1502             return false;
1503
1504         // compute coords for a new node
1505         gp_XYZ coords;
1506         if ( !SMESH_Block::ShellPoint( params, myShapeXYZ, coords ))
1507           return toSM( error("Can't compute coordinates by normalized parameters"));
1508
1509         // if ( !meshDS->MeshElements( volumeID ) ||
1510         //      meshDS->MeshElements( volumeID )->NbNodes() == 0 )
1511         //   pointsToPython(myShapeXYZ);
1512         SHOWYXZ("TOPFacePoint ",myShapeXYZ[ ID_TOP_FACE]);
1513         SHOWYXZ("BOT Node "<< tBotNode.myNode->GetID(),gpXYZ(tBotNode.myNode));
1514         SHOWYXZ("ShellPoint ",coords);
1515
1516         // create a node
1517         node = meshDS->AddNode( coords.X(), coords.Y(), coords.Z() );
1518         meshDS->SetNodeInVolume( node, volumeID );
1519
1520         if ( _computeCanceled )
1521           return false;
1522       }
1523     } // loop on bottom nodes
1524   }
1525
1526   // Create volumes
1527
1528   SMESHDS_SubMesh* smDS = myBlock.SubMeshDS( ID_BOT_FACE );
1529   if ( !smDS ) return toSM( error(COMPERR_BAD_INPUT_MESH, "Null submesh"));
1530
1531   // loop on bottom mesh faces
1532   vector< const TNodeColumn* > columns;
1533   SMDS_ElemIteratorPtr faceIt = smDS->GetElements();
1534   while ( faceIt->more() )
1535   {
1536     const SMDS_MeshElement* face = faceIt->next();
1537     if ( !face || face->GetType() != SMDSAbs_Face )
1538       continue;
1539
1540     // find node columns for each node
1541     int nbNodes = face->NbCornerNodes();
1542     columns.resize( nbNodes );
1543     for ( int i = 0; i < nbNodes; ++i )
1544     {
1545       const SMDS_MeshNode* n = face->GetNode( i );
1546       columns[ i ] = NULL;
1547
1548       if ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE )
1549         columns[ i ] = myBlock.GetNodeColumn( n );
1550
1551       if ( !columns[ i ] )
1552       {
1553         TNode2ColumnMap::iterator bot_column = myBotToColumnMap.find( n );
1554         if ( bot_column == myBotToColumnMap.end() )
1555           return toSM( error(TCom("No side nodes found above node ") << n->GetID() ));
1556         columns[ i ] = & bot_column->second;
1557       }
1558     }
1559     // create prisms
1560     if ( !AddPrisms( columns, myHelper ))
1561       return toSM( error("Different 'vertical' discretization"));
1562
1563   } // loop on bottom mesh faces
1564
1565   // clear data
1566   myBotToColumnMap.clear();
1567   myBlock.Clear();
1568
1569   // update state of sub-meshes (mostly in order to erase improper errors)
1570   SMESH_subMesh* sm = myHelper->GetMesh()->GetSubMesh( thePrism.myShape3D );
1571   SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/true);
1572   while ( smIt->more() )
1573   {
1574     sm = smIt->next();
1575     sm->GetComputeError().reset();
1576     sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1577   }
1578
1579   return true;
1580 }
1581
1582 //=======================================================================
1583 //function : computeBase
1584 //purpose  : Compute the base face of a prism
1585 //=======================================================================
1586
1587 bool StdMeshers_Prism_3D::computeBase(const Prism_3D::TPrismTopo& thePrism)
1588 {
1589   SMESH_Mesh*     mesh = myHelper->GetMesh();
1590   SMESH_subMesh* botSM = mesh->GetSubMesh( thePrism.myBottom );
1591   if (( botSM->IsEmpty() ) &&
1592       ( ! botSM->GetAlgo() ||
1593         ! _gen->Compute( *botSM->GetFather(), botSM->GetSubShape(), /*shapeOnly=*/true )))
1594   {
1595     // find any applicable algorithm assigned to any FACE of the main shape
1596     std::vector< TopoDS_Shape > faces;
1597     if ( thePrism.myAlgoSM && thePrism.myAlgoSM->GetAlgo() )
1598       faces.push_back( thePrism.myAlgoSM->GetSubShape() );
1599     if ( myPrevBottomSM && myPrevBottomSM->GetAlgo() )
1600       faces.push_back( myPrevBottomSM->GetSubShape() );
1601
1602     TopExp_Explorer faceIt( mesh->GetShapeToMesh(), TopAbs_FACE );
1603     for ( ; faceIt.More(); faceIt.Next() )
1604       faces.push_back( faceIt.Current() );
1605
1606     faces.push_back( TopoDS_Shape() ); // to try quadrangle algorithm
1607
1608     SMESH_Algo* algo = 0;
1609     for ( size_t i = 0; i < faces.size() &&  botSM->IsEmpty(); ++i )
1610     {
1611       if ( faces[i].IsNull() ) algo = TQuadrangleAlgo::instance( this, myHelper );
1612       else                     algo = mesh->GetSubMesh( faces[i] )->GetAlgo();
1613       if ( algo && algo->IsApplicableToShape( thePrism.myBottom, /*all=*/false ))
1614       {
1615         // try to compute the bottom FACE
1616         if ( algo->NeedDiscreteBoundary() )
1617         {
1618           // compute sub-shapes
1619           SMESH_subMeshIteratorPtr smIt = botSM->getDependsOnIterator(false,false);
1620           bool subOK = true;
1621           while ( smIt->more() && subOK )
1622           {
1623             SMESH_subMesh* sub = smIt->next();
1624             sub->ComputeStateEngine( SMESH_subMesh::COMPUTE_SUBMESH );
1625             subOK = sub->IsMeshComputed();
1626           }
1627           if ( !subOK )
1628             continue;
1629         }
1630         try {
1631           OCC_CATCH_SIGNALS;
1632
1633           Hypothesis_Status status;
1634           algo->CheckHypothesis( *mesh, faces[i], status );
1635           algo->InitComputeError();
1636           if ( algo->Compute( *mesh, botSM->GetSubShape() ))
1637           {
1638             myPrevBottomSM = thePrism.myAlgoSM = mesh->GetSubMesh( faces[i] );
1639             break;
1640           }
1641         }
1642         catch (...) {
1643         }
1644       }
1645     }
1646   }
1647   else
1648   {
1649     myPrevBottomSM = thePrism.myAlgoSM = botSM;
1650   }
1651
1652   if ( botSM->IsEmpty() )
1653     return error( COMPERR_BAD_INPUT_MESH,
1654                   TCom( "No mesher defined to compute the base face #")
1655                   << shapeID( thePrism.myBottom ));
1656
1657   return true;
1658 }
1659
1660 //=======================================================================
1661 //function : computeWalls
1662 //purpose  : Compute 2D mesh on walls FACEs of a prism
1663 //=======================================================================
1664
1665 bool StdMeshers_Prism_3D::computeWalls(const Prism_3D::TPrismTopo& thePrism)
1666 {
1667   SMESH_Mesh*     mesh = myHelper->GetMesh();
1668   SMESHDS_Mesh* meshDS = myHelper->GetMeshDS();
1669   DBGOUT( endl << "COMPUTE Prism " << meshDS->ShapeToIndex( thePrism.myShape3D ));
1670
1671   TProjction1dAlgo* projector1D = TProjction1dAlgo::instance( this );
1672   TQuadrangleAlgo*     quadAlgo = TQuadrangleAlgo::instance( this, myHelper );
1673
1674   // SMESH_HypoFilter hyp1dFilter( SMESH_HypoFilter::IsAlgo(),/*not=*/true);
1675   // hyp1dFilter.And( SMESH_HypoFilter::HasDim( 1 ));
1676   // hyp1dFilter.And( SMESH_HypoFilter::IsMoreLocalThan( thePrism.myShape3D, *mesh ));
1677
1678   // Discretize equally 'vertical' EDGEs
1679   // -----------------------------------
1680   // find source FACE sides for projection: either already computed ones or
1681   // the 'most composite' ones
1682   const size_t nbWalls = thePrism.myWallQuads.size();
1683   vector< int > wgt( nbWalls, 0 ); // "weight" of a wall
1684   for ( size_t iW = 0; iW != nbWalls; ++iW )
1685   {
1686     Prism_3D::TQuadList::const_iterator quad = thePrism.myWallQuads[iW].begin();
1687     for ( ; quad != thePrism.myWallQuads[iW].end(); ++quad )
1688     {
1689       StdMeshers_FaceSidePtr lftSide = (*quad)->side[ QUAD_LEFT_SIDE ];
1690       lftSide->Reverse(); // to go up
1691       for ( int i = 0; i < lftSide->NbEdges(); ++i )
1692       {
1693         ++wgt[ iW ];
1694         const TopoDS_Edge& E = lftSide->Edge(i);
1695         if ( mesh->GetSubMesh( E )->IsMeshComputed() )
1696         {
1697           wgt[ iW ] += 100;
1698           wgt[ myHelper->WrapIndex( iW+1, nbWalls)] += 10;
1699           wgt[ myHelper->WrapIndex( iW-1, nbWalls)] += 10;
1700         }
1701         // else if ( mesh->GetHypothesis( E, hyp1dFilter, true )) // local hypothesis!
1702         //   wgt += 100;
1703       }
1704     }
1705     // in quadratic mesh, pass ignoreMediumNodes to quad sides
1706     if ( myHelper->GetIsQuadratic() )
1707     {
1708       quad = thePrism.myWallQuads[iW].begin();
1709       for ( ; quad != thePrism.myWallQuads[iW].end(); ++quad )
1710         for ( int i = 0; i < NB_QUAD_SIDES; ++i )
1711           (*quad)->side[ i ].grid->SetIgnoreMediumNodes( true );
1712     }
1713   }
1714   multimap< int, int > wgt2quad;
1715   for ( size_t iW = 0; iW != nbWalls; ++iW )
1716     wgt2quad.insert( make_pair( wgt[ iW ], iW ));
1717
1718   // artificial quads to do outer <-> inner wall projection
1719   std::map< int, FaceQuadStruct > iW2oiQuads;
1720   std::map< int, FaceQuadStruct >::iterator w2oiq;
1721   makeQuadsForOutInProjection( thePrism, wgt2quad, iW2oiQuads );
1722
1723   // Project 'vertical' EDGEs, from left to right
1724   multimap< int, int >::reverse_iterator w2q = wgt2quad.rbegin();
1725   for ( ; w2q != wgt2quad.rend(); ++w2q )
1726   {
1727     const int iW = w2q->second;
1728     const Prism_3D::TQuadList&         quads = thePrism.myWallQuads[ iW ];
1729     Prism_3D::TQuadList::const_iterator quad = quads.begin();
1730     for ( ; quad != quads.end(); ++quad )
1731     {
1732       StdMeshers_FaceSidePtr rgtSide = (*quad)->side[ QUAD_RIGHT_SIDE ]; // tgt
1733       StdMeshers_FaceSidePtr lftSide = (*quad)->side[ QUAD_LEFT_SIDE ];  // src
1734       bool swapLeftRight = ( lftSide->NbSegments( /*update=*/true ) == 0 &&
1735                              rgtSide->NbSegments( /*update=*/true )  > 0 );
1736       if ( swapLeftRight )
1737         std::swap( lftSide, rgtSide );
1738
1739       bool isArtificialQuad = (( w2oiq = iW2oiQuads.find( iW )) != iW2oiQuads.end() );
1740       if ( isArtificialQuad )
1741       {
1742         // reset sides to perform the outer <-> inner projection
1743         FaceQuadStruct& oiQuad = w2oiq->second;
1744         rgtSide = oiQuad.side[ QUAD_RIGHT_SIDE ];
1745         lftSide = oiQuad.side[ QUAD_LEFT_SIDE ];
1746         iW2oiQuads.erase( w2oiq );
1747       }
1748
1749       // assure that all the source (left) EDGEs are meshed
1750       int nbSrcSegments = 0;
1751       for ( int i = 0; i < lftSide->NbEdges(); ++i )
1752       {
1753         if ( isArtificialQuad )
1754         {
1755           nbSrcSegments = lftSide->NbPoints()-1;
1756           continue;
1757         }
1758         const TopoDS_Edge& srcE = lftSide->Edge(i);
1759         SMESH_subMesh*    srcSM = mesh->GetSubMesh( srcE );
1760         if ( !srcSM->IsMeshComputed() ) {
1761           DBGOUT( "COMPUTE V edge " << srcSM->GetId() );
1762           TopoDS_Edge prpgSrcE = findPropagationSource( srcE );
1763           if ( !prpgSrcE.IsNull() ) {
1764             srcSM->ComputeSubMeshStateEngine( SMESH_subMesh::COMPUTE );
1765             projector1D->myHyp.SetSourceEdge( prpgSrcE );
1766             projector1D->Compute( *mesh, srcE );
1767             srcSM->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1768           }
1769           else {
1770             srcSM->ComputeSubMeshStateEngine( SMESH_subMesh::COMPUTE );
1771             srcSM->ComputeStateEngine       ( SMESH_subMesh::COMPUTE );
1772           }
1773           if ( !srcSM->IsMeshComputed() )
1774             return toSM( error( "Can't compute 1D mesh" ));
1775         }
1776         nbSrcSegments += srcSM->GetSubMeshDS()->NbElements();
1777       }
1778       // check target EDGEs
1779       int nbTgtMeshed = 0, nbTgtSegments = 0;
1780       vector< bool > isTgtEdgeComputed( rgtSide->NbEdges() );
1781       for ( int i = 0; i < rgtSide->NbEdges(); ++i )
1782       {
1783         const TopoDS_Edge& tgtE = rgtSide->Edge(i);
1784         SMESH_subMesh*    tgtSM = mesh->GetSubMesh( tgtE );
1785         if ( !( isTgtEdgeComputed[ i ] = tgtSM->IsMeshComputed() )) {
1786           tgtSM->ComputeSubMeshStateEngine( SMESH_subMesh::COMPUTE );
1787           tgtSM->ComputeStateEngine       ( SMESH_subMesh::COMPUTE );
1788         }
1789         if ( tgtSM->IsMeshComputed() ) {
1790           ++nbTgtMeshed;
1791           nbTgtSegments += tgtSM->GetSubMeshDS()->NbElements();
1792         }
1793       }
1794       if ( rgtSide->NbEdges() == nbTgtMeshed ) // all tgt EDGEs meshed
1795       {
1796         if ( nbTgtSegments != nbSrcSegments )
1797         {
1798           bool badMeshRemoved = false;
1799           // remove just computed segments
1800           for ( int i = 0; i < rgtSide->NbEdges(); ++i )
1801             if ( !isTgtEdgeComputed[ i ])
1802             {
1803               const TopoDS_Edge& tgtE = rgtSide->Edge(i);
1804               SMESH_subMesh*    tgtSM = mesh->GetSubMesh( tgtE );
1805               tgtSM->ComputeStateEngine( SMESH_subMesh::CLEAN );
1806               badMeshRemoved = true;
1807               nbTgtMeshed--;
1808             }
1809           if ( !badMeshRemoved )
1810           {
1811             for ( int i = 0; i < lftSide->NbEdges(); ++i )
1812               addBadInputElements( meshDS->MeshElements( lftSide->Edge( i )));
1813             for ( int i = 0; i < rgtSide->NbEdges(); ++i )
1814               addBadInputElements( meshDS->MeshElements( rgtSide->Edge( i )));
1815             return toSM( error( TCom("Different nb of segment on logically vertical edges #")
1816                                 << shapeID( lftSide->Edge(0) ) << " and #"
1817                                 << shapeID( rgtSide->Edge(0) ) << ": "
1818                                 << nbSrcSegments << " != " << nbTgtSegments ));
1819           }
1820         }
1821         else // if ( nbTgtSegments == nbSrcSegments )
1822         {
1823           continue;
1824         }
1825       }
1826       // Compute 'vertical projection'
1827       if ( nbTgtMeshed == 0 )
1828       {
1829         // compute nodes on target VERTEXes
1830         const UVPtStructVec&  srcNodeStr = lftSide->GetUVPtStruct();
1831         if ( srcNodeStr.size() == 0 )
1832           return toSM( error( TCom("Invalid node positions on edge #") <<
1833                               lftSide->EdgeID(0) ));
1834         vector< SMDS_MeshNode* > newNodes( srcNodeStr.size() );
1835         for ( int is2ndV = 0; is2ndV < 2; ++is2ndV )
1836         {
1837           const TopoDS_Edge& E = rgtSide->Edge( is2ndV ? rgtSide->NbEdges()-1 : 0 );
1838           TopoDS_Vertex      v = myHelper->IthVertex( is2ndV, E );
1839           mesh->GetSubMesh( v )->ComputeStateEngine( SMESH_subMesh::COMPUTE );
1840           const SMDS_MeshNode* n = SMESH_Algo::VertexNode( v, meshDS );
1841           newNodes[ is2ndV ? newNodes.size()-1 : 0 ] = (SMDS_MeshNode*) n;
1842         }
1843
1844         // compute nodes on target EDGEs
1845         DBGOUT( "COMPUTE V edge (proj) " << shapeID( lftSide->Edge(0)));
1846         //rgtSide->Reverse(); // direct it same as the lftSide
1847         myHelper->SetElementsOnShape( false ); // myHelper holds the prism shape
1848         TopoDS_Edge tgtEdge;
1849         for ( size_t iN = 1; iN < srcNodeStr.size()-1; ++iN ) // add nodes
1850         {
1851           gp_Pnt       p = rgtSide->Value3d  ( srcNodeStr[ iN ].normParam );
1852           double       u = rgtSide->Parameter( srcNodeStr[ iN ].normParam, tgtEdge );
1853           newNodes[ iN ] = meshDS->AddNode( p.X(), p.Y(), p.Z() );
1854           meshDS->SetNodeOnEdge( newNodes[ iN ], tgtEdge, u );
1855         }
1856         for ( size_t iN = 1; iN < srcNodeStr.size(); ++iN ) // add segments
1857         {
1858           // find an EDGE to set a new segment
1859           std::pair<int, TopAbs_ShapeEnum> id2type =
1860             myHelper->GetMediumPos( newNodes[ iN-1 ], newNodes[ iN ] );
1861           if ( id2type.second != TopAbs_EDGE )
1862           {
1863             // new nodes are on different EDGEs; put one of them on VERTEX
1864             const int      edgeIndex = rgtSide->EdgeIndex( srcNodeStr[ iN-1 ].normParam );
1865             const double vertexParam = rgtSide->LastParameter( edgeIndex );
1866             TopoDS_Vertex     vertex = rgtSide->LastVertex( edgeIndex );
1867             const SMDS_MeshNode*  vn = SMESH_Algo::VertexNode( vertex, meshDS );
1868             const gp_Pnt           p = BRep_Tool::Pnt( vertex );
1869             const int         isPrev = ( Abs( srcNodeStr[ iN-1 ].normParam - vertexParam ) <
1870                                          Abs( srcNodeStr[ iN   ].normParam - vertexParam ));
1871             meshDS->UnSetNodeOnShape( newNodes[ iN-isPrev ] );
1872             meshDS->SetNodeOnVertex ( newNodes[ iN-isPrev ], vertex );
1873             meshDS->MoveNode        ( newNodes[ iN-isPrev ], p.X(), p.Y(), p.Z() );
1874             id2type.first = newNodes[ iN-(1-isPrev) ]->getshapeId();
1875             if ( vn )
1876             {
1877               SMESH_MeshEditor::TListOfListOfNodes lln( 1, list< const SMDS_MeshNode* >() );
1878               lln.back().push_back ( vn );
1879               lln.back().push_front( newNodes[ iN-isPrev ] ); // to keep
1880               SMESH_MeshEditor( mesh ).MergeNodes( lln );
1881             }
1882           }
1883           SMDS_MeshElement* newEdge = myHelper->AddEdge( newNodes[ iN-1 ], newNodes[ iN ] );
1884           meshDS->SetMeshElementOnShape( newEdge, id2type.first );
1885         }
1886         myHelper->SetElementsOnShape( true );
1887         for ( int i = 0; i < rgtSide->NbEdges(); ++i ) // update state of sub-meshes
1888         {
1889           const TopoDS_Edge& E = rgtSide->Edge( i );
1890           SMESH_subMesh* tgtSM = mesh->GetSubMesh( E );
1891           tgtSM->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1892         }
1893
1894         // to continue projection from the just computed side as a source
1895         if ( !swapLeftRight && rgtSide->NbEdges() > 1 && w2q->second == iW )
1896         {
1897           std::pair<int,int> wgt2quadKeyVal( w2q->first + 1, thePrism.myRightQuadIndex[ iW ]);
1898           wgt2quad.insert( wgt2quadKeyVal ); // it will be skipped by ++w2q
1899           wgt2quad.insert( wgt2quadKeyVal );
1900           w2q = wgt2quad.rbegin();
1901         }
1902       }
1903       else
1904       {
1905         // HOPE assigned hypotheses are OK, so that equal nb of segments will be generated
1906         //return toSM( error("Partial projection not implemented"));
1907       }
1908     } // loop on quads of a composite wall side
1909   } // loop on the ordered wall sides
1910
1911
1912
1913   for ( size_t iW = 0; iW != thePrism.myWallQuads.size(); ++iW )
1914   {
1915     Prism_3D::TQuadList::const_iterator quad = thePrism.myWallQuads[iW].begin();
1916     for ( ; quad != thePrism.myWallQuads[iW].end(); ++quad )
1917     {
1918       const TopoDS_Face& face = (*quad)->face;
1919       SMESH_subMesh*      fSM = mesh->GetSubMesh( face );
1920       if ( ! fSM->IsMeshComputed() )
1921       {
1922         // Top EDGEs must be projections from the bottom ones
1923         // to compute structured quad mesh on wall FACEs
1924         // ---------------------------------------------------
1925         const TopoDS_Edge& botE = (*quad)->side[ QUAD_BOTTOM_SIDE ].grid->Edge(0);
1926         const TopoDS_Edge& topE = (*quad)->side[ QUAD_TOP_SIDE    ].grid->Edge(0);
1927         SMESH_subMesh*    botSM = mesh->GetSubMesh( botE );
1928         SMESH_subMesh*    topSM = mesh->GetSubMesh( topE );
1929         SMESH_subMesh*    srcSM = botSM;
1930         SMESH_subMesh*    tgtSM = topSM;
1931         srcSM->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1932         tgtSM->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1933         if ( !srcSM->IsMeshComputed() && tgtSM->IsMeshComputed() )
1934           std::swap( srcSM, tgtSM );
1935
1936         if ( !srcSM->IsMeshComputed() )
1937         {
1938           DBGOUT( "COMPUTE H edge " << srcSM->GetId());
1939           srcSM->ComputeSubMeshStateEngine( SMESH_subMesh::COMPUTE ); // nodes on VERTEXes
1940           srcSM->ComputeStateEngine( SMESH_subMesh::COMPUTE );        // segments on the EDGE
1941         }
1942
1943         if ( tgtSM->IsMeshComputed() &&
1944              tgtSM->GetSubMeshDS()->NbNodes() != srcSM->GetSubMeshDS()->NbNodes() )
1945         {
1946           // the top EDGE is computed differently than the bottom one,
1947           // try to clear a wrong mesh
1948           bool isAdjFaceMeshed = false;
1949           PShapeIteratorPtr fIt = myHelper->GetAncestors( tgtSM->GetSubShape(),
1950                                                           *mesh, TopAbs_FACE );
1951           while ( const TopoDS_Shape* f = fIt->next() )
1952             if (( isAdjFaceMeshed = mesh->GetSubMesh( *f )->IsMeshComputed() ))
1953               break;
1954           if ( isAdjFaceMeshed )
1955             return toSM( error( TCom("Different nb of segment on logically horizontal edges #")
1956                                 << shapeID( botE ) << " and #"
1957                                 << shapeID( topE ) << ": "
1958                                 << tgtSM->GetSubMeshDS()->NbElements() << " != "
1959                                 << srcSM->GetSubMeshDS()->NbElements() ));
1960           tgtSM->ComputeStateEngine( SMESH_subMesh::CLEAN );
1961         }
1962         if ( !tgtSM->IsMeshComputed() )
1963         {
1964           // compute nodes on VERTEXes
1965           SMESH_subMeshIteratorPtr smIt = tgtSM->getDependsOnIterator(/*includeSelf=*/false);
1966           while ( smIt->more() )
1967             smIt->next()->ComputeStateEngine( SMESH_subMesh::COMPUTE );
1968           // project segments
1969           DBGOUT( "COMPUTE H edge (proj) " << tgtSM->GetId());
1970           projector1D->myHyp.SetSourceEdge( TopoDS::Edge( srcSM->GetSubShape() ));
1971           projector1D->InitComputeError();
1972           bool ok = projector1D->Compute( *mesh, tgtSM->GetSubShape() );
1973           if ( !ok )
1974           {
1975             SMESH_ComputeErrorPtr err = projector1D->GetComputeError();
1976             if ( err->IsOK() ) err->myName = COMPERR_ALGO_FAILED;
1977             tgtSM->GetComputeError() = err;
1978             return false;
1979           }
1980         }
1981         tgtSM->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1982
1983
1984         // Compute quad mesh on wall FACEs
1985         // -------------------------------
1986
1987         // make all EDGES meshed
1988         fSM->ComputeSubMeshStateEngine( SMESH_subMesh::COMPUTE );
1989         if ( !fSM->SubMeshesComputed() )
1990           return toSM( error( COMPERR_BAD_INPUT_MESH,
1991                               "Not all edges have valid algorithm and hypothesis"));
1992         // mesh the <face>
1993         quadAlgo->InitComputeError();
1994         DBGOUT( "COMPUTE Quad face " << fSM->GetId());
1995         bool ok = quadAlgo->Compute( *mesh, face );
1996         fSM->GetComputeError() = quadAlgo->GetComputeError();
1997         if ( !ok )
1998           return false;
1999         fSM->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
2000       }
2001       if ( myHelper->GetIsQuadratic() )
2002       {
2003         // fill myHelper with medium nodes built by quadAlgo
2004         for ( SMDS_ElemIteratorPtr fIt = fSM->GetSubMeshDS()->GetElements(); fIt->more(); )
2005           myHelper->AddTLinks( SMDS_Mesh::DownCast<SMDS_MeshFace>( fIt->next() ));
2006       }
2007     }
2008   }
2009
2010   return true;
2011 }
2012
2013 //=======================================================================
2014 //function : findPropagationSource
2015 //purpose  : Returns a source EDGE of propagation to a given EDGE
2016 //=======================================================================
2017
2018 TopoDS_Edge StdMeshers_Prism_3D::findPropagationSource( const TopoDS_Edge& E )
2019 {
2020   if ( myPropagChains )
2021     for ( size_t i = 0; !myPropagChains[i].IsEmpty(); ++i )
2022       if ( myPropagChains[i].Contains( E ))
2023         return TopoDS::Edge( myPropagChains[i].FindKey( 1 ));
2024
2025   return TopoDS_Edge();
2026 }
2027
2028 //=======================================================================
2029 //function : makeQuadsForOutInProjection
2030 //purpose  : Create artificial wall quads for vertical projection between
2031 //           the outer and inner walls
2032 //=======================================================================
2033
2034 void StdMeshers_Prism_3D::makeQuadsForOutInProjection( const Prism_3D::TPrismTopo& thePrism,
2035                                                        multimap< int, int >&       wgt2quad,
2036                                                        map< int, FaceQuadStruct >& iQ2oiQuads)
2037 {
2038   if ( thePrism.NbWires() <= 1 )
2039     return;
2040
2041   std::set< int > doneWires; // processed wires
2042
2043   SMESH_Mesh*      mesh = myHelper->GetMesh();
2044   const bool  isForward = true;
2045   const bool skipMedium = myHelper->GetIsQuadratic();
2046
2047   // make a source side for all projections
2048
2049   multimap< int, int >::reverse_iterator w2q = wgt2quad.rbegin();
2050   const int iQuad = w2q->second;
2051   const int iWire = getWireIndex( thePrism.myWallQuads[ iQuad ].front() );
2052   doneWires.insert( iWire );
2053
2054   UVPtStructVec srcNodes;
2055
2056   Prism_3D::TQuadList::const_iterator quad = thePrism.myWallQuads[ iQuad ].begin();
2057   for ( ; quad != thePrism.myWallQuads[ iQuad ].end(); ++quad )
2058   {
2059     StdMeshers_FaceSidePtr lftSide = (*quad)->side[ QUAD_LEFT_SIDE ];
2060
2061     // assure that all the source (left) EDGEs are meshed
2062     for ( int i = 0; i < lftSide->NbEdges(); ++i )
2063     {
2064       const TopoDS_Edge& srcE = lftSide->Edge(i);
2065       SMESH_subMesh*    srcSM = mesh->GetSubMesh( srcE );
2066       if ( !srcSM->IsMeshComputed() ) {
2067         srcSM->ComputeSubMeshStateEngine( SMESH_subMesh::COMPUTE );
2068         srcSM->ComputeStateEngine       ( SMESH_subMesh::COMPUTE );
2069       }
2070       if ( !srcSM->IsMeshComputed() )
2071         return;
2072     }
2073     const UVPtStructVec& subNodes = lftSide->GetUVPtStruct();
2074     UVPtStructVec::const_iterator subBeg = subNodes.begin(), subEnd = subNodes.end();
2075     if ( !srcNodes.empty() ) ++subBeg;
2076     srcNodes.insert( srcNodes.end(), subBeg, subEnd );
2077   }
2078   StdMeshers_FaceSidePtr srcSide = StdMeshers_FaceSide::New( srcNodes );
2079
2080   // make the quads
2081
2082   list< TopoDS_Edge > sideEdges;
2083   TopoDS_Face face;
2084   for ( ++w2q; w2q != wgt2quad.rend(); ++w2q )
2085   {
2086     const int                  iQuad = w2q->second;
2087     const Prism_3D::TQuadList& quads = thePrism.myWallQuads[ iQuad ];
2088     const int                  iWire = getWireIndex( quads.front() );
2089     if ( !doneWires.insert( iWire ).second )
2090       continue;
2091
2092     sideEdges.clear();
2093     for ( quad = quads.begin(); quad != quads.end(); ++quad )
2094     {
2095       StdMeshers_FaceSidePtr lftSide = (*quad)->side[ QUAD_LEFT_SIDE ];
2096       for ( int i = 0; i < lftSide->NbEdges(); ++i )
2097         sideEdges.push_back( lftSide->Edge( i ));
2098       face = lftSide->Face();
2099     }
2100     StdMeshers_FaceSidePtr tgtSide =
2101       StdMeshers_FaceSide::New( face, sideEdges, mesh, isForward, skipMedium, myHelper );
2102
2103     FaceQuadStruct& newQuad = iQ2oiQuads[ iQuad ];
2104     newQuad.side.resize( 4 );
2105     newQuad.side[ QUAD_LEFT_SIDE  ] = srcSide;
2106     newQuad.side[ QUAD_RIGHT_SIDE ] = tgtSide;
2107
2108     wgt2quad.insert( *w2q ); // to process this quad after processing the newQuad
2109   }
2110 }
2111
2112 //=======================================================================
2113 //function : Evaluate
2114 //purpose  :
2115 //=======================================================================
2116
2117 bool StdMeshers_Prism_3D::Evaluate(SMESH_Mesh&         theMesh,
2118                                    const TopoDS_Shape& theShape,
2119                                    MapShapeNbElems&    aResMap)
2120 {
2121   if ( theShape.ShapeType() == TopAbs_COMPOUND )
2122   {
2123     bool ok = true;
2124     for ( TopoDS_Iterator it( theShape ); it.More(); it.Next() )
2125       ok &= Evaluate( theMesh, it.Value(), aResMap );
2126     return ok;
2127   }
2128   SMESH_MesherHelper helper( theMesh );
2129   myHelper = &helper;
2130   myHelper->SetSubShape( theShape );
2131
2132   // find face contains only triangles
2133   vector < SMESH_subMesh * >meshFaces;
2134   TopTools_SequenceOfShape aFaces;
2135   int NumBase = 0, i = 0, NbQFs = 0;
2136   for (TopExp_Explorer exp(theShape, TopAbs_FACE); exp.More(); exp.Next()) {
2137     i++;
2138     aFaces.Append(exp.Current());
2139     SMESH_subMesh *aSubMesh = theMesh.GetSubMesh(exp.Current());
2140     meshFaces.push_back(aSubMesh);
2141     MapShapeNbElemsItr anIt = aResMap.find(meshFaces[i-1]);
2142     if( anIt==aResMap.end() )
2143       return toSM( error( "Submesh can not be evaluated"));
2144
2145     std::vector<int> aVec = (*anIt).second;
2146     int nbtri = Max(aVec[SMDSEntity_Triangle],aVec[SMDSEntity_Quad_Triangle]);
2147     int nbqua = Max(aVec[SMDSEntity_Quadrangle],aVec[SMDSEntity_Quad_Quadrangle]);
2148     if( nbtri==0 && nbqua>0 ) {
2149       NbQFs++;
2150     }
2151     if( nbtri>0 ) {
2152       NumBase = i;
2153     }
2154   }
2155
2156   if(NbQFs<4) {
2157     std::vector<int> aResVec(SMDSEntity_Last);
2158     for(int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aResVec[i] = 0;
2159     SMESH_subMesh * sm = theMesh.GetSubMesh(theShape);
2160     aResMap.insert(std::make_pair(sm,aResVec));
2161     return toSM( error( "Submesh can not be evaluated" ));
2162   }
2163
2164   if(NumBase==0) NumBase = 1; // only quads => set 1 faces as base
2165
2166   // find number of 1d elems for base face
2167   int nb1d = 0;
2168   TopTools_MapOfShape Edges1;
2169   for (TopExp_Explorer exp(aFaces.Value(NumBase), TopAbs_EDGE); exp.More(); exp.Next()) {
2170     Edges1.Add(exp.Current());
2171     SMESH_subMesh *sm = theMesh.GetSubMesh(exp.Current());
2172     if( sm ) {
2173       MapShapeNbElemsItr anIt = aResMap.find(sm);
2174       if( anIt == aResMap.end() ) continue;
2175       std::vector<int> aVec = (*anIt).second;
2176       nb1d += Max(aVec[SMDSEntity_Edge],aVec[SMDSEntity_Quad_Edge]);
2177     }
2178   }
2179   // find face opposite to base face
2180   int OppNum = 0;
2181   for(i=1; i<=6; i++) {
2182     if(i==NumBase) continue;
2183     bool IsOpposite = true;
2184     for(TopExp_Explorer exp(aFaces.Value(i), TopAbs_EDGE); exp.More(); exp.Next()) {
2185       if( Edges1.Contains(exp.Current()) ) {
2186         IsOpposite = false;
2187         break;
2188       }
2189     }
2190     if(IsOpposite) {
2191       OppNum = i;
2192       break;
2193     }
2194   }
2195   // find number of 2d elems on side faces
2196   int nb2d = 0;
2197   for(i=1; i<=6; i++) {
2198     if( i==OppNum || i==NumBase ) continue;
2199     MapShapeNbElemsItr anIt = aResMap.find( meshFaces[i-1] );
2200     if( anIt == aResMap.end() ) continue;
2201     std::vector<int> aVec = (*anIt).second;
2202     nb2d += Max(aVec[SMDSEntity_Quadrangle],aVec[SMDSEntity_Quad_Quadrangle]);
2203   }
2204
2205   MapShapeNbElemsItr anIt = aResMap.find( meshFaces[NumBase-1] );
2206   std::vector<int> aVec = (*anIt).second;
2207   bool IsQuadratic = (aVec[SMDSEntity_Quad_Triangle]>aVec[SMDSEntity_Triangle]) ||
2208                      (aVec[SMDSEntity_Quad_Quadrangle]>aVec[SMDSEntity_Quadrangle]);
2209   int nb2d_face0_3 = Max(aVec[SMDSEntity_Triangle],aVec[SMDSEntity_Quad_Triangle]);
2210   int nb2d_face0_4 = Max(aVec[SMDSEntity_Quadrangle],aVec[SMDSEntity_Quad_Quadrangle]);
2211   int nb0d_face0 = aVec[SMDSEntity_Node];
2212   int nb1d_face0_int = ( nb2d_face0_3*3 + nb2d_face0_4*4 - nb1d ) / 2;
2213
2214   std::vector<int> aResVec(SMDSEntity_Last);
2215   for(int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aResVec[i] = 0;
2216   if(IsQuadratic) {
2217     aResVec[SMDSEntity_Quad_Penta] = nb2d_face0_3 * ( nb2d/nb1d );
2218     aResVec[SMDSEntity_Quad_Hexa] = nb2d_face0_4 * ( nb2d/nb1d );
2219     aResVec[SMDSEntity_Node] = nb0d_face0 * ( 2*nb2d/nb1d - 1 ) - nb1d_face0_int * nb2d/nb1d;
2220   }
2221   else {
2222     aResVec[SMDSEntity_Node] = nb0d_face0 * ( nb2d/nb1d - 1 );
2223     aResVec[SMDSEntity_Penta] = nb2d_face0_3 * ( nb2d/nb1d );
2224     aResVec[SMDSEntity_Hexa] = nb2d_face0_4 * ( nb2d/nb1d );
2225   }
2226   SMESH_subMesh * sm = theMesh.GetSubMesh(theShape);
2227   aResMap.insert(std::make_pair(sm,aResVec));
2228
2229   return true;
2230 }
2231
2232 //================================================================================
2233 /*!
2234  * \brief Create prisms
2235  * \param columns - columns of nodes generated from nodes of a mesh face
2236  * \param helper - helper initialized by mesh and shape to add prisms to
2237  */
2238 //================================================================================
2239
2240 bool StdMeshers_Prism_3D::AddPrisms( vector<const TNodeColumn*> & columns,
2241                                      SMESH_MesherHelper*          helper)
2242 {
2243   size_t nbNodes = columns.size();
2244   size_t nbZ     = columns[0]->size();
2245   if ( nbZ < 2 ) return false;
2246   for ( size_t i = 1; i < nbNodes; ++i )
2247     if ( columns[i]->size() != nbZ )
2248       return false;
2249
2250   // find out orientation
2251   bool isForward = true;
2252   SMDS_VolumeTool vTool;
2253   size_t z = 1;
2254   switch ( nbNodes ) {
2255   case 3: {
2256     SMDS_VolumeOfNodes tmpPenta ( (*columns[0])[z-1], // bottom
2257                                   (*columns[1])[z-1],
2258                                   (*columns[2])[z-1],
2259                                   (*columns[0])[z],   // top
2260                                   (*columns[1])[z],
2261                                   (*columns[2])[z] );
2262     vTool.Set( &tmpPenta );
2263     isForward  = vTool.IsForward();
2264     break;
2265   }
2266   case 4: {
2267     SMDS_VolumeOfNodes tmpHex( (*columns[0])[z-1], (*columns[1])[z-1], // bottom
2268                                (*columns[2])[z-1], (*columns[3])[z-1],
2269                                (*columns[0])[z],   (*columns[1])[z],   // top
2270                                (*columns[2])[z],   (*columns[3])[z] );
2271     vTool.Set( &tmpHex );
2272     isForward  = vTool.IsForward();
2273     break;
2274   }
2275   default:
2276     const int di = (nbNodes+1) / 3;
2277     SMDS_VolumeOfNodes tmpVol ( (*columns[0]   )[z-1],
2278                                 (*columns[di]  )[z-1],
2279                                 (*columns[2*di])[z-1],
2280                                 (*columns[0]   )[z],
2281                                 (*columns[di]  )[z],
2282                                 (*columns[2*di])[z] );
2283     vTool.Set( &tmpVol );
2284     isForward  = vTool.IsForward();
2285   }
2286
2287   // vertical loop on columns
2288
2289   helper->SetElementsOnShape( true );
2290
2291   switch ( nbNodes ) {
2292
2293   case 3: { // ---------- pentahedra
2294     const int i1 = isForward ? 1 : 2;
2295     const int i2 = isForward ? 2 : 1;
2296     for ( z = 1; z < nbZ; ++z )
2297       helper->AddVolume( (*columns[0 ])[z-1], // bottom
2298                          (*columns[i1])[z-1],
2299                          (*columns[i2])[z-1],
2300                          (*columns[0 ])[z],   // top
2301                          (*columns[i1])[z],
2302                          (*columns[i2])[z] );
2303     break;
2304   }
2305   case 4: { // ---------- hexahedra
2306     const int i1 = isForward ? 1 : 3;
2307     const int i3 = isForward ? 3 : 1;
2308     for ( z = 1; z < nbZ; ++z )
2309       helper->AddVolume( (*columns[0])[z-1], (*columns[i1])[z-1], // bottom
2310                          (*columns[2])[z-1], (*columns[i3])[z-1],
2311                          (*columns[0])[z],   (*columns[i1])[z],     // top
2312                          (*columns[2])[z],   (*columns[i3])[z] );
2313     break;
2314   }
2315   case 6: { // ---------- octahedra
2316     const int iBase1 = isForward ? -1 : 0;
2317     const int iBase2 = isForward ?  0 :-1;
2318     for ( z = 1; z < nbZ; ++z )
2319       helper->AddVolume( (*columns[0])[z+iBase1], (*columns[1])[z+iBase1], // bottom or top
2320                          (*columns[2])[z+iBase1], (*columns[3])[z+iBase1],
2321                          (*columns[4])[z+iBase1], (*columns[5])[z+iBase1],
2322                          (*columns[0])[z+iBase2], (*columns[1])[z+iBase2], // top or bottom
2323                          (*columns[2])[z+iBase2], (*columns[3])[z+iBase2],
2324                          (*columns[4])[z+iBase2], (*columns[5])[z+iBase2] );
2325     break;
2326   }
2327   default: // ---------- polyhedra
2328     vector<int> quantities( 2 + nbNodes, 4 );
2329     quantities[0] = quantities[1] = nbNodes;
2330     columns.resize( nbNodes + 1 );
2331     columns[ nbNodes ] = columns[ 0 ];
2332     const int i1 = isForward ? 1 : 3;
2333     const int i3 = isForward ? 3 : 1;
2334     const int iBase1 = isForward ? -1 : 0;
2335     const int iBase2 = isForward ?  0 :-1;
2336     vector<const SMDS_MeshNode*> nodes( 2*nbNodes + 4*nbNodes);
2337     for ( z = 1; z < nbZ; ++z )
2338     {
2339       for ( size_t i = 0; i < nbNodes; ++i ) {
2340         nodes[ i             ] = (*columns[ i ])[z+iBase1]; // bottom or top
2341         nodes[ 2*nbNodes-i-1 ] = (*columns[ i ])[z+iBase2]; // top or bottom
2342         // side
2343         int di = 2*nbNodes + 4*i;
2344         nodes[ di+0 ] = (*columns[i  ])[z  ];
2345         nodes[ di+i1] = (*columns[i+1])[z  ];
2346         nodes[ di+2 ] = (*columns[i+1])[z-1];
2347         nodes[ di+i3] = (*columns[i  ])[z-1];
2348       }
2349       helper->AddPolyhedralVolume( nodes, quantities );
2350     }
2351
2352   } // switch ( nbNodes )
2353
2354   return true;
2355 }
2356
2357 //================================================================================
2358 /*!
2359  * \brief Find correspondence between bottom and top nodes
2360  *  If elements on the bottom and top faces are topologically different,
2361  *  and projection is possible and allowed, perform the projection
2362  *  \retval bool - is a success or not
2363  */
2364 //================================================================================
2365
2366 bool StdMeshers_Prism_3D::assocOrProjBottom2Top( const gp_Trsf & bottomToTopTrsf,
2367                                                  const Prism_3D::TPrismTopo& thePrism)
2368 {
2369   SMESH_subMesh * botSM = myHelper->GetMesh()->GetSubMesh( thePrism.myBottom );
2370   SMESH_subMesh * topSM = myHelper->GetMesh()->GetSubMesh( thePrism.myTop    );
2371
2372   SMESHDS_SubMesh * botSMDS = botSM->GetSubMeshDS();
2373   SMESHDS_SubMesh * topSMDS = topSM->GetSubMeshDS();
2374
2375   if ( !botSMDS || botSMDS->NbElements() == 0 )
2376   {
2377     _gen->Compute( *myHelper->GetMesh(), botSM->GetSubShape(), /*aShapeOnly=*/true );
2378     botSMDS = botSM->GetSubMeshDS();
2379     if ( !botSMDS || botSMDS->NbElements() == 0 )
2380       return toSM( error(TCom("No elements on face #") << botSM->GetId() ));
2381   }
2382
2383   bool needProject = !topSM->IsMeshComputed();
2384   if ( !needProject &&
2385        (botSMDS->NbElements() != topSMDS->NbElements() ||
2386         botSMDS->NbNodes()    != topSMDS->NbNodes()))
2387   {
2388     MESSAGE("nb elem bot " << botSMDS->NbElements() <<
2389             " top " << ( topSMDS ? topSMDS->NbElements() : 0 ));
2390     MESSAGE("nb node bot " << botSMDS->NbNodes() <<
2391             " top " << ( topSMDS ? topSMDS->NbNodes() : 0 ));
2392     return toSM( error(TCom("Mesh on faces #") << botSM->GetId()
2393                        <<" and #"<< topSM->GetId() << " seems different" ));
2394   }
2395
2396   if ( 0/*needProject && !myProjectTriangles*/ )
2397     return toSM( error(TCom("Mesh on faces #") << botSM->GetId()
2398                        <<" and #"<< topSM->GetId() << " seems different" ));
2399   ///RETURN_BAD_RESULT("Need to project but not allowed");
2400
2401   NSProjUtils::TNodeNodeMap n2nMap;
2402   const NSProjUtils::TNodeNodeMap* n2nMapPtr = & n2nMap;
2403   if ( needProject )
2404   {
2405     if ( !projectBottomToTop( bottomToTopTrsf, thePrism ))
2406       return false;
2407     n2nMapPtr = & TProjction2dAlgo::instance( this )->GetNodesMap();
2408   }
2409
2410   if ( !n2nMapPtr || (int) n2nMapPtr->size() < botSMDS->NbNodes() )
2411   {
2412     // associate top and bottom faces
2413     NSProjUtils::TShapeShapeMap shape2ShapeMap;
2414     const bool sameTopo =
2415       NSProjUtils::FindSubShapeAssociation( thePrism.myBottom, myHelper->GetMesh(),
2416                                             thePrism.myTop,    myHelper->GetMesh(),
2417                                             shape2ShapeMap);
2418     if ( !sameTopo )
2419       for ( size_t iQ = 0; iQ < thePrism.myWallQuads.size(); ++iQ )
2420       {
2421         const Prism_3D::TQuadList& quadList = thePrism.myWallQuads[iQ];
2422         StdMeshers_FaceSidePtr      botSide = quadList.front()->side[ QUAD_BOTTOM_SIDE ];
2423         StdMeshers_FaceSidePtr      topSide = quadList.back ()->side[ QUAD_TOP_SIDE ];
2424         if ( botSide->NbEdges() == topSide->NbEdges() )
2425         {
2426           for ( int iE = 0; iE < botSide->NbEdges(); ++iE )
2427           {
2428             NSProjUtils::InsertAssociation( botSide->Edge( iE ),
2429                                             topSide->Edge( iE ), shape2ShapeMap );
2430             NSProjUtils::InsertAssociation( myHelper->IthVertex( 0, botSide->Edge( iE )),
2431                                             myHelper->IthVertex( 0, topSide->Edge( iE )),
2432                                             shape2ShapeMap );
2433           }
2434         }
2435         else
2436         {
2437           TopoDS_Vertex vb, vt;
2438           StdMeshers_FaceSidePtr sideB, sideT;
2439           vb = myHelper->IthVertex( 0, botSide->Edge( 0 ));
2440           vt = myHelper->IthVertex( 0, topSide->Edge( 0 ));
2441           sideB = quadList.front()->side[ QUAD_LEFT_SIDE ];
2442           sideT = quadList.back ()->side[ QUAD_LEFT_SIDE ];
2443           if ( vb.IsSame( sideB->FirstVertex() ) &&
2444                vt.IsSame( sideT->LastVertex() ))
2445           {
2446             NSProjUtils::InsertAssociation( botSide->Edge( 0 ),
2447                                             topSide->Edge( 0 ), shape2ShapeMap );
2448             NSProjUtils::InsertAssociation( vb, vt, shape2ShapeMap );
2449           }
2450           vb = myHelper->IthVertex( 1, botSide->Edge( botSide->NbEdges()-1 ));
2451           vt = myHelper->IthVertex( 1, topSide->Edge( topSide->NbEdges()-1 ));
2452           sideB = quadList.front()->side[ QUAD_RIGHT_SIDE ];
2453           sideT = quadList.back ()->side[ QUAD_RIGHT_SIDE ];
2454           if ( vb.IsSame( sideB->FirstVertex() ) &&
2455                vt.IsSame( sideT->LastVertex() ))
2456           {
2457             NSProjUtils::InsertAssociation( botSide->Edge( botSide->NbEdges()-1 ),
2458                                             topSide->Edge( topSide->NbEdges()-1 ),
2459                                             shape2ShapeMap );
2460             NSProjUtils::InsertAssociation( vb, vt, shape2ShapeMap );
2461           }
2462         }
2463       }
2464
2465     // Find matching nodes of top and bottom faces
2466     n2nMapPtr = & n2nMap;
2467     if ( ! NSProjUtils::FindMatchingNodesOnFaces( thePrism.myBottom, myHelper->GetMesh(),
2468                                                   thePrism.myTop,    myHelper->GetMesh(),
2469                                                   shape2ShapeMap, n2nMap ))
2470     {
2471       if ( sameTopo )
2472         return toSM( error(TCom("Mesh on faces #") << botSM->GetId()
2473                            <<" and #"<< topSM->GetId() << " seems different" ));
2474       else
2475         return toSM( error(TCom("Topology of faces #") << botSM->GetId()
2476                            <<" and #"<< topSM->GetId() << " seems different" ));
2477     }
2478   }
2479
2480   // Fill myBotToColumnMap
2481
2482   int zSize = myBlock.VerticalSize();
2483   TNodeNodeMap::const_iterator bN_tN = n2nMapPtr->begin();
2484   for ( ; bN_tN != n2nMapPtr->end(); ++bN_tN )
2485   {
2486     const SMDS_MeshNode* botNode = bN_tN->first;
2487     const SMDS_MeshNode* topNode = bN_tN->second;
2488     if ( botNode->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE &&
2489          myBlock.HasNodeColumn( botNode ))
2490       continue; // wall columns are contained in myBlock
2491     // create node column
2492     Prism_3D::TNode bN( botNode );
2493     TNode2ColumnMap::iterator bN_col =
2494       myBotToColumnMap.insert( make_pair ( bN, TNodeColumn() )).first;
2495     TNodeColumn & column = bN_col->second;
2496     column.resize( zSize, 0 );
2497     column.front() = botNode;
2498     column.back()  = topNode;
2499   }
2500   return true;
2501 }
2502
2503 //================================================================================
2504 /*!
2505  * \brief Remove faces from the top face and re-create them by projection from the bottom
2506  * \retval bool - a success or not
2507  */
2508 //================================================================================
2509
2510 bool StdMeshers_Prism_3D::projectBottomToTop( const gp_Trsf &             bottomToTopTrsf,
2511                                               const Prism_3D::TPrismTopo& thePrism )
2512 {
2513   if ( project2dMesh( thePrism.myBottom, thePrism.myTop ))
2514   {
2515     return true;
2516   }
2517   NSProjUtils::TNodeNodeMap& n2nMap =
2518     (NSProjUtils::TNodeNodeMap&) TProjction2dAlgo::instance( this )->GetNodesMap();
2519   n2nMap.clear();
2520
2521   myUseBlock = true;
2522
2523   SMESHDS_Mesh*  meshDS = myHelper->GetMeshDS();
2524   SMESH_subMesh * botSM = myHelper->GetMesh()->GetSubMesh( thePrism.myBottom );
2525   SMESH_subMesh * topSM = myHelper->GetMesh()->GetSubMesh( thePrism.myTop );
2526
2527   SMESHDS_SubMesh * botSMDS = botSM->GetSubMeshDS();
2528   SMESHDS_SubMesh * topSMDS = topSM->GetSubMeshDS();
2529
2530   if ( topSMDS && topSMDS->NbElements() > 0 )
2531   {
2532     //topSM->ComputeStateEngine( SMESH_subMesh::CLEAN ); -- avoid propagation of events
2533     for ( SMDS_ElemIteratorPtr eIt = topSMDS->GetElements(); eIt->more(); )
2534       meshDS->RemoveFreeElement( eIt->next(), topSMDS, /*fromGroups=*/false );
2535     for ( SMDS_NodeIteratorPtr nIt = topSMDS->GetNodes(); nIt->more(); )
2536       meshDS->RemoveFreeNode( nIt->next(), topSMDS, /*fromGroups=*/false );
2537   }
2538
2539   const TopoDS_Face& botFace = thePrism.myBottom; // oriented within
2540   const TopoDS_Face& topFace = thePrism.myTop;    //    the 3D SHAPE
2541   int topFaceID = meshDS->ShapeToIndex( thePrism.myTop );
2542
2543   SMESH_MesherHelper botHelper( *myHelper->GetMesh() );
2544   botHelper.SetSubShape( botFace );
2545   botHelper.ToFixNodeParameters( true );
2546   bool checkUV;
2547   SMESH_MesherHelper topHelper( *myHelper->GetMesh() );
2548   topHelper.SetSubShape( topFace );
2549   topHelper.ToFixNodeParameters( true );
2550   double distXYZ[4], fixTol = 10 * topHelper.MaxTolerance( topFace );
2551
2552   // Fill myBotToColumnMap
2553
2554   int zSize = myBlock.VerticalSize();
2555   Prism_3D::TNode prevTNode;
2556   SMDS_NodeIteratorPtr nIt = botSMDS->GetNodes();
2557   while ( nIt->more() )
2558   {
2559     const SMDS_MeshNode* botNode = nIt->next();
2560     const SMDS_MeshNode* topNode = 0;
2561     if ( botNode->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE )
2562       continue; // strange
2563
2564     Prism_3D::TNode bN( botNode );
2565     if ( bottomToTopTrsf.Form() == gp_Identity )
2566     {
2567       // compute bottom node params
2568       gp_XYZ paramHint(-1,-1,-1);
2569       if ( prevTNode.IsNeighbor( bN ))
2570       {
2571         paramHint = prevTNode.GetParams();
2572         // double tol = 1e-2 * ( prevTNode.GetCoords() - bN.GetCoords() ).Modulus();
2573         // myBlock.SetTolerance( Min( myBlock.GetTolerance(), tol ));
2574       }
2575       if ( !myBlock.ComputeParameters( bN.GetCoords(), bN.ChangeParams(),
2576                                        ID_BOT_FACE, paramHint ))
2577         return toSM( error(TCom("Can't compute normalized parameters for node ")
2578                            << botNode->GetID() << " on the face #"<< botSM->GetId() ));
2579       prevTNode = bN;
2580       // compute top node coords
2581       gp_XYZ topXYZ; gp_XY topUV;
2582       if ( !myBlock.FacePoint( ID_TOP_FACE, bN.GetParams(), topXYZ ) ||
2583            !myBlock.FaceUV   ( ID_TOP_FACE, bN.GetParams(), topUV ))
2584         return toSM( error(TCom("Can't compute coordinates "
2585                                 "by normalized parameters on the face #")<< topSM->GetId() ));
2586       topNode = meshDS->AddNode( topXYZ.X(),topXYZ.Y(),topXYZ.Z() );
2587       meshDS->SetNodeOnFace( topNode, topFaceID, topUV.X(), topUV.Y() );
2588     }
2589     else // use bottomToTopTrsf
2590     {
2591       gp_XYZ coords = bN.GetCoords();
2592       bottomToTopTrsf.Transforms( coords );
2593       topNode = meshDS->AddNode( coords.X(), coords.Y(), coords.Z() );
2594       gp_XY topUV = botHelper.GetNodeUV( botFace, botNode, 0, &checkUV );
2595       meshDS->SetNodeOnFace( topNode, topFaceID, topUV.X(), topUV.Y() );
2596       distXYZ[0] = -1;
2597       if ( topHelper.CheckNodeUV( topFace, topNode, topUV, fixTol, /*force=*/false, distXYZ ) &&
2598            distXYZ[0] > fixTol && distXYZ[0] < fixTol * 1e+3 )
2599         meshDS->MoveNode( topNode, distXYZ[1], distXYZ[2], distXYZ[3] ); // transform can be inaccurate
2600     }
2601     // create node column
2602     TNode2ColumnMap::iterator bN_col =
2603       myBotToColumnMap.insert( make_pair ( bN, TNodeColumn() )).first;
2604     TNodeColumn & column = bN_col->second;
2605     column.resize( zSize );
2606     column.front() = botNode;
2607     column.back()  = topNode;
2608
2609     n2nMap.insert( n2nMap.end(), make_pair( botNode, topNode ));
2610
2611     if ( _computeCanceled )
2612       return toSM( error( SMESH_ComputeError::New(COMPERR_CANCELED)));
2613   }
2614
2615   // Create top faces
2616
2617   const bool oldSetElemsOnShape = myHelper->SetElementsOnShape( false );
2618
2619   // care of orientation;
2620   // if the bottom faces is orienetd OK then top faces must be reversed
2621   bool reverseTop = true;
2622   if ( myHelper->NbAncestors( botFace, *myBlock.Mesh(), TopAbs_SOLID ) > 1 )
2623     reverseTop = ! myHelper->IsReversedSubMesh( botFace );
2624   int iFrw, iRev, *iPtr = &( reverseTop ? iRev : iFrw );
2625
2626   // loop on bottom mesh faces
2627   SMDS_ElemIteratorPtr faceIt = botSMDS->GetElements();
2628   vector< const SMDS_MeshNode* > nodes;
2629   while ( faceIt->more() )
2630   {
2631     const SMDS_MeshElement* face = faceIt->next();
2632     if ( !face || face->GetType() != SMDSAbs_Face )
2633       continue;
2634
2635     // find top node in columns for each bottom node
2636     int nbNodes = face->NbCornerNodes();
2637     nodes.resize( nbNodes );
2638     for ( iFrw = 0, iRev = nbNodes-1; iFrw < nbNodes; ++iFrw, --iRev )
2639     {
2640       const SMDS_MeshNode* n = face->GetNode( *iPtr );
2641       if ( n->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE ) {
2642         TNode2ColumnMap::iterator bot_column = myBotToColumnMap.find( n );
2643         if ( bot_column == myBotToColumnMap.end() )
2644           return toSM( error(TCom("No nodes found above node ") << n->GetID() ));
2645         nodes[ iFrw ] = bot_column->second.back();
2646       }
2647       else {
2648         const TNodeColumn* column = myBlock.GetNodeColumn( n );
2649         if ( !column )
2650           return toSM( error(TCom("No side nodes found above node ") << n->GetID() ));
2651         nodes[ iFrw ] = column->back();
2652       }
2653     }
2654     SMDS_MeshElement* newFace = 0;
2655     switch ( nbNodes ) {
2656
2657     case 3: {
2658       newFace = myHelper->AddFace(nodes[0], nodes[1], nodes[2]);
2659       break;
2660     }
2661     case 4: {
2662       newFace = myHelper->AddFace( nodes[0], nodes[1], nodes[2], nodes[3] );
2663       break;
2664     }
2665     default:
2666       newFace = meshDS->AddPolygonalFace( nodes );
2667     }
2668     if ( newFace )
2669       meshDS->SetMeshElementOnShape( newFace, topFaceID );
2670   }
2671
2672   myHelper->SetElementsOnShape( oldSetElemsOnShape );
2673
2674   // Check the projected mesh
2675
2676   if ( thePrism.NbWires() > 1 && // there are holes
2677        topHelper.IsDistorted2D( topSM, /*checkUV=*/false ))
2678   {
2679     SMESH_MeshEditor editor( topHelper.GetMesh() );
2680
2681     // smooth in 2D or 3D?
2682     TopLoc_Location loc;
2683     Handle(Geom_Surface) surface = BRep_Tool::Surface( topFace, loc );
2684     bool isPlanar = GeomLib_IsPlanarSurface( surface ).IsPlanar();
2685
2686     set<const SMDS_MeshNode*> fixedNodes;
2687     TIDSortedElemSet faces;
2688     for ( faceIt = topSMDS->GetElements(); faceIt->more(); )
2689       faces.insert( faces.end(), faceIt->next() );
2690
2691     bool isOk = false;
2692     for ( int isCentroidal = 0; isCentroidal < 2; ++isCentroidal )
2693     {
2694       SMESH_MeshEditor::SmoothMethod algo =
2695         isCentroidal ? SMESH_MeshEditor::CENTROIDAL : SMESH_MeshEditor::LAPLACIAN;
2696
2697       int nbAttempts = isCentroidal ? 1 : 10;
2698       for ( int iAttemp = 0; iAttemp < nbAttempts; ++iAttemp )
2699       {
2700         TIDSortedElemSet workFaces = faces;
2701
2702         // smoothing
2703         editor.Smooth( workFaces, fixedNodes, algo, /*nbIterations=*/ 10,
2704                        /*theTgtAspectRatio=*/1.0, /*the2D=*/!isPlanar);
2705
2706         if (( isOk = !topHelper.IsDistorted2D( topSM, /*checkUV=*/true )) &&
2707             ( !isCentroidal ))
2708           break;
2709       }
2710     }
2711     if ( !isOk )
2712       return toSM( error( TCom("Projection from face #") << botSM->GetId()
2713                           << " to face #" << topSM->GetId()
2714                           << " failed: inverted elements created"));
2715   }
2716
2717   TProjction2dAlgo::instance( this )->SetEventListener( topSM );
2718
2719   return true;
2720 }
2721
2722 //=======================================================================
2723 //function : getSweepTolerance
2724 //purpose  : Compute tolerance to pass to StdMeshers_Sweeper
2725 //=======================================================================
2726
2727 double StdMeshers_Prism_3D::getSweepTolerance( const Prism_3D::TPrismTopo& thePrism )
2728 {
2729   SMESHDS_Mesh*    meshDS = myHelper->GetMeshDS();
2730   SMESHDS_SubMesh * sm[2] = { meshDS->MeshElements( thePrism.myBottom ),
2731                               meshDS->MeshElements( thePrism.myTop )    };
2732   double minDist = 1e100;
2733
2734   vector< SMESH_TNodeXYZ > nodes;
2735   for ( int iSM = 0; iSM < 2; ++iSM )
2736   {
2737     if ( !sm[ iSM ]) continue;
2738
2739     SMDS_ElemIteratorPtr fIt = sm[ iSM ]->GetElements();
2740     while ( fIt->more() )
2741     {
2742       const SMDS_MeshElement* face = fIt->next();
2743       const int            nbNodes = face->NbCornerNodes();
2744       SMDS_ElemIteratorPtr     nIt = face->nodesIterator();
2745
2746       nodes.resize( nbNodes + 1 );
2747       for ( int iN = 0; iN < nbNodes; ++iN )
2748         nodes[ iN ] = nIt->next();
2749       nodes.back() = nodes[0];
2750
2751       // loop on links
2752       double dist2;
2753       for ( int iN = 0; iN < nbNodes; ++iN )
2754       {
2755         if ( nodes[ iN   ]._node->GetPosition()->GetDim() < 2 &&
2756              nodes[ iN+1 ]._node->GetPosition()->GetDim() < 2 )
2757         {
2758           // it's a boundary link; measure distance of other
2759           // nodes to this link
2760           gp_XYZ linkDir = nodes[ iN ] - nodes[ iN+1 ];
2761           double linkLen = linkDir.Modulus();
2762           bool   isDegen = ( linkLen < numeric_limits<double>::min() );
2763           if ( !isDegen ) linkDir /= linkLen;
2764           for ( int iN2 = 0; iN2 < nbNodes; ++iN2 ) // loop on other nodes
2765           {
2766             if ( nodes[ iN2 ] == nodes[ iN ] ||
2767                  nodes[ iN2 ] == nodes[ iN+1 ]) continue;
2768             if ( isDegen )
2769             {
2770               dist2 = ( nodes[ iN ] - nodes[ iN2 ]).SquareModulus();
2771             }
2772             else
2773             {
2774               dist2 = linkDir.CrossSquareMagnitude( nodes[ iN ] - nodes[ iN2 ]);
2775             }
2776             if ( dist2 > numeric_limits<double>::min() )
2777               minDist = Min ( minDist, dist2 );
2778           }
2779         }
2780         // measure length link
2781         else if ( nodes[ iN ]._node < nodes[ iN+1 ]._node ) // not to measure same link twice
2782         {
2783           dist2 = ( nodes[ iN ] - nodes[ iN+1 ]).SquareModulus();
2784           if ( dist2 > numeric_limits<double>::min() )
2785             minDist = Min ( minDist, dist2 );
2786         }
2787       }
2788     }
2789   }
2790   return 0.1 * Sqrt ( minDist );
2791 }
2792
2793 //=======================================================================
2794 //function : isSimpleQuad
2795 //purpose  : check if the bottom FACE is meshable with nice quadrangles,
2796 //           if so the block approach can work rather fast.
2797 //           This is a temporary mean caused by problems in StdMeshers_Sweeper
2798 //=======================================================================
2799
2800 bool StdMeshers_Prism_3D::isSimpleBottom( const Prism_3D::TPrismTopo& thePrism )
2801 {
2802   if ( thePrism.myNbEdgesInWires.front() != 4 )
2803     return false;
2804
2805   // analyse angles between edges
2806   double nbConcaveAng = 0, nbConvexAng = 0;
2807   TopoDS_Face reverseBottom = TopoDS::Face( thePrism.myBottom.Reversed() ); // see initPrism()
2808   TopoDS_Vertex commonV;
2809   const list< TopoDS_Edge >& botEdges = thePrism.myBottomEdges;
2810   list< TopoDS_Edge >::const_iterator edge = botEdges.begin();
2811   while ( edge != botEdges.end() )
2812   {
2813     if ( SMESH_Algo::isDegenerated( *edge ))
2814       return false;
2815     TopoDS_Edge e1 = *edge++;
2816     TopoDS_Edge e2 = ( edge == botEdges.end() ? botEdges.front() : *edge );
2817     if ( ! TopExp::CommonVertex( e1, e2,  commonV ))
2818     {
2819       e2 = botEdges.front();
2820       if ( ! TopExp::CommonVertex( e1, e2,  commonV ))
2821         break;
2822     }
2823     double angle = myHelper->GetAngle( e1, e2, reverseBottom, commonV );
2824     if ( angle < -5 * M_PI/180 )
2825       if ( ++nbConcaveAng > 1 )
2826         return false;
2827     if ( angle > 85 * M_PI/180 )
2828       if ( ++nbConvexAng > 4 )
2829         return false;
2830   }
2831   return true;
2832 }
2833
2834 //=======================================================================
2835 //function : allVerticalEdgesStraight
2836 //purpose  : Defines if all "vertical" EDGEs are straight
2837 //=======================================================================
2838
2839 bool StdMeshers_Prism_3D::allVerticalEdgesStraight( const Prism_3D::TPrismTopo& thePrism )
2840 {
2841   for ( size_t i = 0; i < thePrism.myWallQuads.size(); ++i )
2842   {
2843     const Prism_3D::TQuadList& quads = thePrism.myWallQuads[i];
2844     Prism_3D::TQuadList::const_iterator quadIt = quads.begin();
2845     TopoDS_Edge prevQuadEdge;
2846     for ( ; quadIt != quads.end(); ++quadIt )
2847     {
2848       StdMeshers_FaceSidePtr rightSide = (*quadIt)->side[ QUAD_RIGHT_SIDE ];
2849
2850       if ( !prevQuadEdge.IsNull() &&
2851            !SMESH_Algo::IsContinuous( rightSide->Edge( 0 ), prevQuadEdge ))
2852         return false;
2853
2854       for ( int iE = 0; iE < rightSide->NbEdges(); ++iE )
2855       {
2856         const TopoDS_Edge & rightE = rightSide->Edge( iE );
2857         if ( !SMESH_Algo::IsStraight( rightE, /*degenResult=*/true ))
2858           return false;
2859
2860         if ( iE > 0 &&
2861              !SMESH_Algo::IsContinuous( rightSide->Edge( iE-1 ), rightE ))
2862           return false;
2863
2864         prevQuadEdge = rightE;
2865       }
2866     }
2867   }
2868   return true;
2869 }
2870
2871 //=======================================================================
2872 //function : project2dMesh
2873 //purpose  : Project mesh faces from a source FACE of one prism (theSrcFace)
2874 //           to a source FACE of another prism (theTgtFace)
2875 //=======================================================================
2876
2877 bool StdMeshers_Prism_3D::project2dMesh(const TopoDS_Face& theSrcFace,
2878                                         const TopoDS_Face& theTgtFace)
2879 {
2880   if ( CountEdges( theSrcFace ) != CountEdges( theTgtFace ))
2881     return false;
2882
2883   TProjction2dAlgo* projector2D = TProjction2dAlgo::instance( this );
2884   projector2D->myHyp.SetSourceFace( theSrcFace );
2885   bool ok = projector2D->Compute( *myHelper->GetMesh(), theTgtFace );
2886
2887   SMESH_subMesh* tgtSM = myHelper->GetMesh()->GetSubMesh( theTgtFace );
2888   if ( !ok && tgtSM->GetSubMeshDS() ) {
2889     //tgtSM->ComputeStateEngine( SMESH_subMesh::CLEAN ); -- avoid propagation of events
2890     SMESHDS_Mesh*     meshDS = myHelper->GetMeshDS();
2891     SMESHDS_SubMesh* tgtSMDS = tgtSM->GetSubMeshDS();
2892     for ( SMDS_ElemIteratorPtr eIt = tgtSMDS->GetElements(); eIt->more(); )
2893       meshDS->RemoveFreeElement( eIt->next(), tgtSMDS, /*fromGroups=*/false );
2894     for ( SMDS_NodeIteratorPtr nIt = tgtSMDS->GetNodes(); nIt->more(); )
2895       meshDS->RemoveFreeNode( nIt->next(), tgtSMDS, /*fromGroups=*/false );
2896   }
2897   tgtSM->ComputeStateEngine       ( SMESH_subMesh::CHECK_COMPUTE_STATE );
2898   tgtSM->ComputeSubMeshStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
2899
2900   projector2D->SetEventListener( tgtSM );
2901
2902   return ok;
2903 }
2904
2905 //================================================================================
2906 /*!
2907  * \brief Set projection coordinates of a node to a face and it's sub-shapes
2908  * \param faceID - the face given by in-block ID
2909  * \param params - node normalized parameters
2910  * \retval bool - is a success
2911  */
2912 //================================================================================
2913
2914 bool StdMeshers_Prism_3D::setFaceAndEdgesXYZ( const int faceID, const gp_XYZ& params, int z )
2915 {
2916   // find base and top edges of the face
2917   enum { BASE = 0, TOP, LEFT, RIGHT };
2918   vector< int > edgeVec; // 0-base, 1-top
2919   SMESH_Block::GetFaceEdgesIDs( faceID, edgeVec );
2920
2921   myBlock.EdgePoint( edgeVec[ BASE ], params, myShapeXYZ[ edgeVec[ BASE ]]);
2922   myBlock.EdgePoint( edgeVec[ TOP  ], params, myShapeXYZ[ edgeVec[ TOP ]]);
2923
2924   SHOWYXZ("\nparams ", params);
2925   SHOWYXZ("TOP is " <<edgeVec[ TOP ], myShapeXYZ[ edgeVec[ TOP]]);
2926   SHOWYXZ("BASE is "<<edgeVec[ BASE], myShapeXYZ[ edgeVec[ BASE]]);
2927
2928   if ( faceID == SMESH_Block::ID_Fx0z || faceID == SMESH_Block::ID_Fx1z )
2929   {
2930     myBlock.EdgePoint( edgeVec[ LEFT ], params, myShapeXYZ[ edgeVec[ LEFT ]]);
2931     myBlock.EdgePoint( edgeVec[ RIGHT ], params, myShapeXYZ[ edgeVec[ RIGHT ]]);
2932
2933     SHOWYXZ("VER "<<edgeVec[ LEFT], myShapeXYZ[ edgeVec[ LEFT]]);
2934     SHOWYXZ("VER "<<edgeVec[ RIGHT], myShapeXYZ[ edgeVec[ RIGHT]]);
2935   }
2936   myBlock.FacePoint( faceID, params, myShapeXYZ[ faceID ]);
2937   SHOWYXZ("FacePoint "<<faceID, myShapeXYZ[ faceID]);
2938
2939   return true;
2940 }
2941
2942 //=======================================================================
2943 //function : toSM
2944 //purpose  : If (!isOK), sets the error to a sub-mesh of a current SOLID
2945 //=======================================================================
2946
2947 bool StdMeshers_Prism_3D::toSM( bool isOK )
2948 {
2949   if ( mySetErrorToSM &&
2950        !isOK &&
2951        myHelper &&
2952        !myHelper->GetSubShape().IsNull() &&
2953        myHelper->GetSubShape().ShapeType() == TopAbs_SOLID)
2954   {
2955     SMESH_subMesh* sm = myHelper->GetMesh()->GetSubMesh( myHelper->GetSubShape() );
2956     sm->GetComputeError() = this->GetComputeError();
2957     // clear error in order not to return it twice
2958     _error = COMPERR_OK;
2959     _comment.clear();
2960   }
2961   return isOK;
2962 }
2963
2964 //=======================================================================
2965 //function : shapeID
2966 //purpose  : Return index of a shape
2967 //=======================================================================
2968
2969 int StdMeshers_Prism_3D::shapeID( const TopoDS_Shape& S )
2970 {
2971   if ( S.IsNull() ) return 0;
2972   if ( !myHelper  ) return -3;
2973   return myHelper->GetMeshDS()->ShapeToIndex( S );
2974 }
2975
2976 namespace // utils used by StdMeshers_Prism_3D::IsApplicable()
2977 {
2978   struct EdgeWithNeighbors
2979   {
2980     TopoDS_Edge   _edge;
2981     int           _iBase;     // index in a WIRE with non-base EDGEs excluded
2982     int           _iL, _iR;   // used to connect PrismSide's
2983     int           _iE;        // index in a WIRE
2984     int           _iLE, _iRE; // used to connect EdgeWithNeighbors's
2985     bool          _isBase;    // is used in a base FACE
2986     TopoDS_Vertex _vv[2];     // end VERTEXes
2987     EdgeWithNeighbors(const TopoDS_Edge& E,
2988                       int iE,  int nbE,  int shift,
2989                       int iEE, int nbEE, int shiftE,
2990                       bool isBase, bool setVV ):
2991       _edge( E ),
2992       _iBase( iE + shift ),
2993       _iL ( SMESH_MesherHelper::WrapIndex( iE-1,  Max( 1, nbE  )) + shift ),
2994       _iR ( SMESH_MesherHelper::WrapIndex( iE+1,  Max( 1, nbE  )) + shift ),
2995       _iE ( iEE + shiftE ),
2996       _iLE( SMESH_MesherHelper::WrapIndex( iEE-1, Max( 1, nbEE )) + shiftE ),
2997       _iRE( SMESH_MesherHelper::WrapIndex( iEE+1, Max( 1, nbEE )) + shiftE ),
2998       _isBase( isBase )
2999     {
3000       if ( setVV )
3001       {
3002         Vertex( 0 );
3003         Vertex( 1 );
3004       }
3005     }
3006     EdgeWithNeighbors() {}
3007     bool IsInternal() const { return !_edge.IsNull() && _edge.Orientation() == TopAbs_INTERNAL; }
3008     bool IsConnected( const EdgeWithNeighbors& edge, int iEnd ) const
3009     {
3010       return (( _vv[ iEnd ].IsSame( edge._vv[ 1 - iEnd ])) ||
3011               ( IsInternal() && _vv[ iEnd ].IsSame( edge._vv[ iEnd ])));
3012     }
3013     bool IsConnected( const std::vector< EdgeWithNeighbors > & edges, int iEnd ) const
3014     {
3015       int iEdge = iEnd ? _iRE : _iLE;
3016       return iEdge == _iE ? false : IsConnected( edges[ iEdge ], iEnd );
3017     }
3018     const TopoDS_Vertex& Vertex( int iEnd )
3019     {
3020       if ( _vv[ iEnd ].IsNull() )
3021         _vv[ iEnd ] = SMESH_MesherHelper::IthVertex( iEnd, _edge );
3022       return _vv[ iEnd ];
3023     }
3024   };
3025   // PrismSide contains all FACEs linking a bottom EDGE with a top one.
3026   struct PrismSide
3027   {
3028     TopoDS_Face                 _face;    // a currently treated upper FACE
3029     TopTools_IndexedMapOfShape *_faces;   // all FACEs (pointer because of a private copy constructor)
3030     TopoDS_Edge                 _topEdge; // a current top EDGE
3031     vector< EdgeWithNeighbors >*_edges;   // all EDGEs of _face
3032     int                         _iBotEdge;       // index of _topEdge within _edges
3033     vector< bool >              _isCheckedEdge;  // mark EDGEs whose two owner FACEs found
3034     int                         _nbCheckedEdges; // nb of EDGEs whose location is defined
3035     PrismSide                  *_leftSide;       // neighbor sides
3036     PrismSide                  *_rightSide;
3037     bool                        _isInternal; // whether this side raises from an INTERNAL EDGE
3038     //void SetExcluded() { _leftSide = _rightSide = NULL; }
3039     //bool IsExcluded() const { return !_leftSide; }
3040     const TopoDS_Edge& Edge( int i ) const
3041     {
3042       return (*_edges)[ i ]._edge;
3043     }
3044     int FindEdge( const TopoDS_Edge& E ) const
3045     {
3046       for ( size_t i = 0; i < _edges->size(); ++i )
3047         if ( E.IsSame( Edge( i ))) return i;
3048       return -1;
3049     }
3050     const TopoDS_Vertex& Vertex( int iE, int iEnd ) const
3051     {
3052       return (*_edges)[ iE ].Vertex( iEnd );
3053     }
3054     bool HasVertex( const TopoDS_Vertex& V ) const
3055     {
3056       for ( size_t i = 0; i < _edges->size(); ++i )
3057         if ( V.IsSame( Vertex( i, 0 ))) return true;
3058       return false;
3059     }
3060     bool IsSideFace( const TopTools_ListOfShape& faces,
3061                      const TopoDS_Face&          avoidFace,
3062                      const bool                  checkNeighbors ) const
3063     {
3064       TopTools_ListIteratorOfListOfShape faceIt( faces );
3065       for ( ; faceIt.More(); faceIt.Next() )
3066       {
3067         const TopoDS_Shape& face = faceIt.Value();
3068         if ( !face.IsSame( avoidFace ))
3069         {
3070           if ( _faces->Contains( face )) // avoid returning true for a prism top FACE
3071             return ( !_face.IsNull() || !( face.IsSame( _faces->FindKey( _faces->Extent() ))));
3072         }
3073       }
3074       if ( checkNeighbors )
3075         return (( _leftSide  && _leftSide->IsSideFace ( faces, avoidFace, false )) ||
3076                 ( _rightSide && _rightSide->IsSideFace( faces, avoidFace, false )));
3077
3078       return false;
3079     }
3080   };
3081   //--------------------------------------------------------------------------------
3082   /*!
3083    * \brief Return another faces sharing an edge
3084    */
3085   const TopoDS_Face & getAnotherFace( const TopoDS_Face& face,
3086                                       const TopTools_ListOfShape& faces)
3087   {
3088     TopTools_ListIteratorOfListOfShape faceIt( faces );
3089     for ( ; faceIt.More(); faceIt.Next() )
3090       if ( !face.IsSame( faceIt.Value() ))
3091         return TopoDS::Face( faceIt.Value() );
3092     return face;
3093   }
3094   //--------------------------------------------------------------------------------
3095   /*!
3096    * \brief Return another faces sharing an edge
3097    */
3098   const TopoDS_Face & getAnotherFace( const TopoDS_Face& face,
3099                                       const TopoDS_Edge& edge,
3100                                       TopTools_IndexedDataMapOfShapeListOfShape& facesOfEdge)
3101   {
3102     return getAnotherFace( face, facesOfEdge.FindFromKey( edge ));
3103   }
3104
3105   //--------------------------------------------------------------------------------
3106   /*!
3107    * \brief Return ordered edges of a face
3108    */
3109   //================================================================================
3110   /*!
3111    * \brief Return ordered edges of a face
3112    *  \param [in] face - the face
3113    *  \param [out] edges - return edge (edges from which no vertical faces raise excluded)
3114    *  \param [in] facesOfEdge - faces of each edge
3115    *  \param [in] noHolesAllowed - are multiple wires allowed
3116    */
3117   //================================================================================
3118
3119   bool getEdges( const TopoDS_Face&                         face,
3120                  vector< EdgeWithNeighbors > &              edges,
3121                  TopTools_IndexedDataMapOfShapeListOfShape& facesOfEdge,
3122                  const bool                                 noHolesAllowed)
3123   {
3124     TopoDS_Face f = face;
3125     if ( f.Orientation() != TopAbs_FORWARD &&
3126          f.Orientation() != TopAbs_REVERSED )
3127       f.Orientation( TopAbs_FORWARD );
3128     list< TopoDS_Edge > ee;
3129     list< int >         nbEdgesInWires;
3130     int nbW = SMESH_Block::GetOrderedEdges( f, ee, nbEdgesInWires );
3131     if ( nbW > 1 && noHolesAllowed )
3132       return false;
3133
3134     list< TopoDS_Edge >::iterator   e = ee.begin();
3135     list< int         >::iterator nbE = nbEdgesInWires.begin();
3136     for ( ; nbE != nbEdgesInWires.end(); ++nbE )
3137       for ( int iE = 0; iE < *nbE; ++e, ++iE )
3138         if ( SMESH_Algo::isDegenerated( *e )) // degenerated EDGE is never used
3139         {
3140           e = --ee.erase( e );
3141           --(*nbE);
3142           --iE;
3143         }
3144
3145     int iE, nbTot = 0, iBase, nbBase, nbTotBase = 0;
3146     vector<int> isBase;
3147     edges.clear();
3148     e = ee.begin();
3149     for ( nbE = nbEdgesInWires.begin(); nbE != nbEdgesInWires.end(); ++nbE )
3150     {
3151       nbBase = 0;
3152       isBase.resize( *nbE );
3153       list< TopoDS_Edge >::iterator eIt = e;
3154       for ( iE = 0; iE < *nbE; ++eIt, ++iE )
3155       {
3156         isBase[ iE ] = ( getAnotherFace( face, *eIt, facesOfEdge ) != face );
3157         nbBase += isBase[ iE ];
3158       }
3159       for ( iBase = 0, iE = 0; iE < *nbE; ++e, ++iE )
3160       {
3161         edges.push_back( EdgeWithNeighbors( *e,
3162                                             iBase, nbBase, nbTotBase,
3163                                             iE,    *nbE,   nbTot,
3164                                             isBase[ iE ], nbW > 1 ));
3165         iBase += isBase[ iE ];
3166       }
3167       nbTot     += *nbE;
3168       nbTotBase += nbBase;
3169     }
3170     if ( nbTotBase == 0 )
3171       return false;
3172
3173     // IPAL53099, 54416. Set correct neighbors to INTERNAL EDGEs
3174     if ( nbW > 1 )
3175     {
3176       int iFirst = 0, iLast;
3177       for ( nbE = nbEdgesInWires.begin(); nbE != nbEdgesInWires.end(); ++nbE )
3178       {
3179         iLast = iFirst + *nbE - 1;
3180         bool isConnectOk = ( edges[ iFirst ].IsConnected( edges, 0 ) &&
3181                              edges[ iFirst ].IsConnected( edges, 1 ));
3182         if ( !isConnectOk )
3183         {
3184           for ( iE = iFirst; iE <= iLast; ++iE )
3185           {
3186             if ( !edges[ iE ]._isBase )
3187               continue;
3188             int* iNei[] = { & edges[ iE ]._iL,
3189                             & edges[ iE ]._iR };
3190             for ( int iV = 0; iV < 2; ++iV )
3191             {
3192               if ( edges[ iE ].IsConnected( edges, iV ))
3193                 continue; // Ok - connected to a neighbor EDGE
3194
3195               // look for a connected EDGE
3196               bool found = false;
3197               for ( int iE2 = 0, nbE = edges.size(); iE2 < nbE &&   !found; ++iE2 )
3198                 if (( iE2 != iE ) &&
3199                     ( found = edges[ iE ].IsConnected( edges[ iE2 ], iV )))
3200                 {
3201                   *iNei[ iV ] = edges[ iE2 ]._iBase;
3202                 }
3203               if ( !found )
3204                 *iNei[ iV ] = edges[ iE ]._iBase; // connect to self
3205             }
3206           }
3207         }
3208         iFirst += *nbE;
3209       }
3210     }
3211     return edges.size();
3212   }
3213
3214   //--------------------------------------------------------------------------------
3215   /*!
3216    * \brief Return number of faces sharing given edges
3217    */
3218   // int nbAdjacentFaces( const std::vector< EdgeWithNeighbors >&          edges,
3219   //                      const TopTools_IndexedDataMapOfShapeListOfShape& facesOfEdge )
3220   // {
3221   //   TopTools_MapOfShape adjFaces;
3222
3223   //   for ( size_t i = 0; i < edges.size(); ++i )
3224   //   {
3225   //     TopTools_ListIteratorOfListOfShape faceIt( facesOfEdge.FindFromKey( edges[i]._edge ));
3226   //     for ( ; faceIt.More(); faceIt.Next() )
3227   //       adjFaces.Add( faceIt.Value() );
3228   //   }
3229   //   return adjFaces.Extent();
3230   // }
3231 }
3232
3233 //================================================================================
3234 /*!
3235  * \brief Return true if the algorithm can mesh this shape
3236  *  \param [in] aShape - shape to check
3237  *  \param [in] toCheckAll - if true, this check returns OK if all shapes are OK,
3238  *              else, returns OK if at least one shape is OK
3239  */
3240 //================================================================================
3241
3242 bool StdMeshers_Prism_3D::IsApplicable(const TopoDS_Shape & shape, bool toCheckAll)
3243 {
3244   TopExp_Explorer sExp( shape, TopAbs_SOLID );
3245   if ( !sExp.More() )
3246     return false;
3247
3248   for ( ; sExp.More(); sExp.Next() )
3249   {
3250     // check nb shells
3251     TopoDS_Shape shell;
3252     TopExp_Explorer shExp( sExp.Current(), TopAbs_SHELL );
3253     while ( shExp.More() ) {
3254       shell = shExp.Current();
3255       shExp.Next();
3256       if ( shExp.More() && BRep_Tool::IsClosed( shExp.Current() ))
3257         shell.Nullify();
3258     }
3259     if ( shell.IsNull() ) {
3260       if ( toCheckAll ) return false;
3261       continue;
3262     }
3263     // get all faces
3264     TopTools_IndexedMapOfShape allFaces;
3265     TopExp::MapShapes( sExp.Current(), TopAbs_FACE, allFaces );
3266     if ( allFaces.Extent() < 3 ) {
3267       if ( toCheckAll ) return false;
3268       continue;
3269     }
3270     // is a box?
3271     if ( allFaces.Extent() == 6 )
3272     {
3273       TopTools_IndexedMapOfOrientedShape map;
3274       bool isBox = SMESH_Block::FindBlockShapes( TopoDS::Shell( shell ),
3275                                                  TopoDS_Vertex(), TopoDS_Vertex(), map );
3276       if ( isBox ) {
3277         if ( !toCheckAll ) return true;
3278         continue;
3279       }
3280     }
3281 #ifdef _DEBUG_
3282     TopTools_IndexedMapOfShape allShapes; // usage: allShapes.FindIndex( s )
3283     TopExp::MapShapes( shape, allShapes );
3284 #endif
3285
3286     TopTools_IndexedDataMapOfShapeListOfShape facesOfEdge;
3287     TopTools_ListIteratorOfListOfShape faceIt;
3288     TopExp::MapShapesAndAncestors( sExp.Current(), TopAbs_EDGE, TopAbs_FACE , facesOfEdge );
3289     if ( facesOfEdge.IsEmpty() ) {
3290       if ( toCheckAll ) return false;
3291       continue;
3292     }
3293
3294     typedef vector< EdgeWithNeighbors > TEdgeWithNeighborsVec;
3295     vector< TEdgeWithNeighborsVec > faceEdgesVec( allFaces.Extent() + 1 );
3296     const size_t nbEdgesMax = facesOfEdge.Extent() * 2; // there can be seam EDGEs
3297     TopTools_IndexedMapOfShape* facesOfSide = new TopTools_IndexedMapOfShape[ nbEdgesMax ];
3298     SMESHUtils::ArrayDeleter<TopTools_IndexedMapOfShape> delFacesOfSide( facesOfSide );
3299
3300     // try to use each face as a bottom one
3301     bool prismDetected = false;
3302     vector< PrismSide > sides;
3303     for ( int iF = 1; iF < allFaces.Extent() && !prismDetected; ++iF )
3304     {
3305       const TopoDS_Face& botF = TopoDS::Face( allFaces( iF ));
3306
3307       TEdgeWithNeighborsVec& botEdges = faceEdgesVec[ iF ];
3308       if ( botEdges.empty() )
3309         if ( !getEdges( botF, botEdges, facesOfEdge, /*noHoles=*/false ))
3310           break;
3311
3312       int nbBase = 0;
3313       for ( size_t iS = 0; iS < botEdges.size(); ++iS )
3314         nbBase += botEdges[ iS ]._isBase;
3315
3316       if ( allFaces.Extent()-1 <= nbBase )
3317         continue; // all faces are adjacent to botF - no top FACE
3318
3319       // init data of side FACEs
3320       sides.clear();
3321       sides.resize( nbBase );
3322       size_t iS = 0;
3323       for ( size_t iE = 0; iE < botEdges.size(); ++iE )
3324       {
3325         if ( !botEdges[ iE ]._isBase )
3326           continue;
3327         sides[ iS ]._topEdge    = botEdges[ iE ]._edge;
3328         sides[ iS ]._face       = botF;
3329         sides[ iS ]._leftSide   = & sides[ botEdges[ iE ]._iR ];
3330         sides[ iS ]._rightSide  = & sides[ botEdges[ iE ]._iL ];
3331         sides[ iS ]._isInternal = botEdges[ iE ].IsInternal();
3332         sides[ iS ]._faces      = & facesOfSide[ iS ];
3333         sides[ iS ]._faces->Clear();
3334         ++iS;
3335       }
3336
3337       bool isOK = true; // ok for a current botF
3338       bool hasAdvanced = true; // is new data found in a current loop
3339       int  nbFoundSideFaces = 0;
3340       for ( int iLoop = 0; isOK && hasAdvanced; ++iLoop )
3341       {
3342         hasAdvanced = false;
3343         for ( size_t iS = 0; iS < sides.size() && isOK; ++iS )
3344         {
3345           PrismSide& side = sides[ iS ];
3346           if ( side._face.IsNull() )
3347             continue; // probably the prism top face is the last of side._faces
3348
3349           if ( side._topEdge.IsNull() )
3350           {
3351             // find vertical EDGEs --- EDGEs shared with neighbor side FACEs
3352             for ( int is2nd = 0; is2nd < 2 && isOK; ++is2nd ) // 2 adjacent neighbors
3353             {
3354               const PrismSide* adjSide = is2nd ? side._rightSide : side._leftSide;
3355               if ( side._isInternal )
3356               {
3357                 const TopoDS_Vertex& V = side.Vertex( side._iBotEdge, is2nd );
3358                 bool lHasV = side._leftSide ->HasVertex( V );
3359                 bool rHasV = side._rightSide->HasVertex( V );
3360                 if ( lHasV == rHasV )
3361                   adjSide = ( &side == side._leftSide ) ? side._rightSide : side._leftSide;
3362                 else
3363                   adjSide = ( rHasV ) ? side._rightSide : side._leftSide;
3364               }
3365               int di = is2nd ? 1 : -1;
3366               for ( size_t i = 1; i < side._edges->size(); ++i )
3367               {
3368                 int iE = SMESH_MesherHelper::WrapIndex( i*di + side._iBotEdge, side._edges->size());
3369                 if ( side._isCheckedEdge[ iE ] ) continue;
3370                 const TopoDS_Edge&               vertE = side.Edge( iE );
3371                 const TopTools_ListOfShape& neighborFF = facesOfEdge.FindFromKey( vertE );
3372                 bool isEdgeShared = (( adjSide->IsSideFace( neighborFF, side._face,
3373                                                             side._isInternal )) ||
3374                                      ( adjSide == &side &&
3375                                        side._face.IsSame( getAnotherFace( side._face,
3376                                                                           neighborFF ))));
3377                 if ( isEdgeShared ) // vertE is shared with adjSide
3378                 {
3379                   hasAdvanced = true;
3380                   side._isCheckedEdge[ iE ] = true;
3381                   side._nbCheckedEdges++;
3382                   int nbNotCheckedE = side._edges->size() - side._nbCheckedEdges;
3383                   if ( nbNotCheckedE == 1 )
3384                     break;
3385                 }
3386                 else
3387                 {
3388                   if ( i == 1 && iLoop == 0 ) isOK = false;
3389                   break;
3390                 }
3391               }
3392             }
3393             // find a top EDGE
3394             int nbNotCheckedE = side._edges->size() - side._nbCheckedEdges;
3395             if ( nbNotCheckedE == 1 )
3396             {
3397               vector<bool>::iterator ii = std::find( side._isCheckedEdge.begin(),
3398                                                      side._isCheckedEdge.end(), false );
3399               if ( ii != side._isCheckedEdge.end() )
3400               {
3401                 size_t iE = std::distance( side._isCheckedEdge.begin(), ii );
3402                 side._topEdge = side.Edge( iE );
3403               }
3404             }
3405             isOK = ( nbNotCheckedE >= 1 );
3406           }
3407           else //if ( !side._topEdge.IsNull() )
3408           {
3409             // get a next face of a side
3410             const TopoDS_Shape& f = getAnotherFace( side._face, side._topEdge, facesOfEdge );
3411             side._faces->Add( f );
3412             bool stop = false;
3413             if ( f.IsSame( side._face ) || // _topEdge is a seam
3414                  SMESH_MesherHelper::Count( f, TopAbs_WIRE, false ) != 1 )
3415             {
3416               stop = true;
3417             }
3418             else if ( side._leftSide != & side && // not closed side face
3419                       side._leftSide->_faces->Contains( f ))
3420             {
3421               stop = true; // probably f is the prism top face
3422               side._leftSide->_face.Nullify();
3423               side._leftSide->_topEdge.Nullify();
3424             }
3425             else if ( side._rightSide != & side &&
3426                       side._rightSide->_faces->Contains( f ))
3427             {
3428               stop = true; // probably f is the prism top face
3429               side._rightSide->_face.Nullify();
3430               side._rightSide->_topEdge.Nullify();
3431             }
3432             if ( stop )
3433             {
3434               side._face.Nullify();
3435               side._topEdge.Nullify();
3436               continue;
3437             }
3438             side._face  = TopoDS::Face( f );
3439             int faceID  = allFaces.FindIndex( side._face );
3440             side._edges = & faceEdgesVec[ faceID ];
3441             if ( side._edges->empty() )
3442               if ( !getEdges( side._face, * side._edges, facesOfEdge, /*noHoles=*/true ))
3443                 break;
3444             const int nbE = side._edges->size();
3445             if ( nbE >= 4 )
3446             {
3447               hasAdvanced = true;
3448               ++nbFoundSideFaces;
3449               side._iBotEdge = side.FindEdge( side._topEdge );
3450               side._isCheckedEdge.clear();
3451               side._isCheckedEdge.resize( nbE, false );
3452               side._isCheckedEdge[ side._iBotEdge ] = true;
3453               side._nbCheckedEdges = 1; // bottom EDGE is known
3454             }
3455             else // probably a triangular top face found
3456             {
3457               side._face.Nullify();
3458             }
3459             side._topEdge.Nullify();
3460             isOK = ( !side._edges->empty() || side._faces->Extent() > 1 );
3461
3462           } //if ( !side._topEdge.IsNull() )
3463
3464         } // loop on prism sides
3465
3466         if ( nbFoundSideFaces > allFaces.Extent() )
3467         {
3468           isOK = false;
3469         }
3470         if ( iLoop > allFaces.Extent() * 10 )
3471         {
3472           isOK = false;
3473 #ifdef _DEBUG_
3474           cerr << "BUG: infinite loop in StdMeshers_Prism_3D::IsApplicable()" << endl;
3475 #endif
3476         }
3477       } // while hasAdvanced
3478
3479       if ( isOK && sides[0]._faces->Extent() > 1 )
3480       {
3481         const int nbFaces = sides[0]._faces->Extent();
3482         if ( botEdges.size() == 1 ) // cylinder
3483         {
3484           prismDetected = ( nbFaces == allFaces.Extent()-1 );
3485         }
3486         else
3487         {
3488           // check that all face columns end up at the same top face
3489           const TopoDS_Shape& topFace = sides[0]._faces->FindKey( nbFaces );
3490           size_t iS;
3491           for ( iS = 1; iS < sides.size(); ++iS )
3492             if ( ! sides[ iS ]._faces->Contains( topFace ))
3493               break;
3494           if (( prismDetected = ( iS == sides.size() )))
3495           {
3496             // check that bottom and top faces has equal nb of edges
3497             TEdgeWithNeighborsVec& topEdges = faceEdgesVec[ allFaces.FindIndex( topFace )];
3498             if ( topEdges.empty() )
3499               getEdges( TopoDS::Face( topFace ), topEdges, facesOfEdge, /*noHoles=*/false );
3500             prismDetected = ( botEdges.size() == topEdges.size() );
3501           }
3502         }
3503       }
3504     } // loop on allFaces
3505
3506     if ( !prismDetected && toCheckAll ) return false;
3507     if ( prismDetected && !toCheckAll ) return true;
3508
3509   } // loop on solids
3510
3511   return toCheckAll;
3512 }
3513
3514 namespace Prism_3D
3515 {
3516   //================================================================================
3517   /*!
3518    * \brief Return true if this node and other one belong to one face
3519    */
3520   //================================================================================
3521
3522   bool Prism_3D::TNode::IsNeighbor( const Prism_3D::TNode& other ) const
3523   {
3524     if ( !other.myNode || !myNode ) return false;
3525
3526     SMDS_ElemIteratorPtr fIt = other.myNode->GetInverseElementIterator(SMDSAbs_Face);
3527     while ( fIt->more() )
3528       if ( fIt->next()->GetNodeIndex( myNode ) >= 0 )
3529         return true;
3530     return false;
3531   }
3532
3533   //================================================================================
3534   /*!
3535    * \brief Prism initialization
3536    */
3537   //================================================================================
3538
3539   void TPrismTopo::Clear()
3540   {
3541     myShape3D.Nullify();
3542     myTop.Nullify();
3543     myBottom.Nullify();
3544     myWallQuads.clear();
3545     myBottomEdges.clear();
3546     myNbEdgesInWires.clear();
3547     myWallQuads.clear();
3548     myAlgoSM = nullptr;
3549   }
3550
3551   //================================================================================
3552   /*!
3553    * \brief Set upside-down
3554    */
3555   //================================================================================
3556
3557   void TPrismTopo::SetUpsideDown()
3558   {
3559     std::swap( myBottom, myTop );
3560     myBottomEdges.clear();
3561     std::reverse( myBottomEdges.begin(), myBottomEdges.end() );
3562     for ( size_t i = 0; i < myWallQuads.size(); ++i )
3563     {
3564       myWallQuads[i].reverse();
3565       TQuadList::iterator q = myWallQuads[i].begin();
3566       for ( ; q != myWallQuads[i].end(); ++q )
3567       {
3568         (*q)->shift( 2, /*keepUnitOri=*/true );
3569       }
3570       myBottomEdges.push_back( myWallQuads[i].front()->side[ QUAD_BOTTOM_SIDE ].grid->Edge(0) );
3571     }
3572   }
3573
3574 } // namespace Prism_3D
3575
3576 //================================================================================
3577 /*!
3578  * \brief Constructor. Initialization is needed
3579  */
3580 //================================================================================
3581
3582 StdMeshers_PrismAsBlock::StdMeshers_PrismAsBlock()
3583 {
3584   mySide = 0;
3585 }
3586
3587 StdMeshers_PrismAsBlock::~StdMeshers_PrismAsBlock()
3588 {
3589   Clear();
3590 }
3591 void StdMeshers_PrismAsBlock::Clear()
3592 {
3593   myHelper = 0;
3594   myShapeIDMap.Clear();
3595   myError.reset();
3596
3597   if ( mySide ) {
3598     delete mySide; mySide = 0;
3599   }
3600   myParam2ColumnMaps.clear();
3601   myShapeIndex2ColumnMap.clear();
3602 }
3603
3604 //=======================================================================
3605 //function : initPrism
3606 //purpose  : Analyse shape geometry and mesh.
3607 //           If there are triangles on one of faces, it becomes 'bottom'.
3608 //           thePrism.myBottom can be already set up.
3609 //=======================================================================
3610
3611 bool StdMeshers_Prism_3D::initPrism(Prism_3D::TPrismTopo& thePrism,
3612                                     const TopoDS_Shape&   theShape3D,
3613                                     const bool            selectBottom)
3614 {
3615   myHelper->SetSubShape( theShape3D );
3616
3617   SMESH_subMesh* mainSubMesh = myHelper->GetMesh()->GetSubMeshContaining( theShape3D );
3618   if ( !mainSubMesh ) return toSM( error(COMPERR_BAD_INPUT_MESH,"Null submesh of shape3D"));
3619
3620   // detect not-quad FACE sub-meshes of the 3D SHAPE
3621   list< SMESH_subMesh* > notQuadGeomSubMesh;
3622   list< SMESH_subMesh* > notQuadElemSubMesh;
3623   list< SMESH_subMesh* > meshedSubMesh;
3624   int nbFaces = 0;
3625   //
3626   SMESH_subMeshIteratorPtr smIt = mainSubMesh->getDependsOnIterator(false,true);
3627   while ( smIt->more() )
3628   {
3629     SMESH_subMesh* sm = smIt->next();
3630     const TopoDS_Shape& face = sm->GetSubShape();
3631     if      ( face.ShapeType() > TopAbs_FACE ) break;
3632     else if ( face.ShapeType() < TopAbs_FACE ) continue;
3633     nbFaces++;
3634
3635     // is quadrangle FACE?
3636     list< TopoDS_Edge > orderedEdges;
3637     list< int >         nbEdgesInWires;
3638     int nbWires = SMESH_Block::GetOrderedEdges( TopoDS::Face( face ), orderedEdges,
3639                                                 nbEdgesInWires );
3640     if ( nbWires != 1 || nbEdgesInWires.front() != 4 )
3641       notQuadGeomSubMesh.push_back( sm );
3642
3643     // look for a not structured sub-mesh
3644     if ( !sm->IsEmpty() )
3645     {
3646       meshedSubMesh.push_back( sm );
3647       if ( !myHelper->IsSameElemGeometry( sm->GetSubMeshDS(), SMDSGeom_QUADRANGLE ) ||
3648            !myHelper->IsStructured      ( sm ))
3649         notQuadElemSubMesh.push_back( sm );
3650     }
3651   }
3652
3653   int nbNotQuadMeshed = notQuadElemSubMesh.size();
3654   int       nbNotQuad = notQuadGeomSubMesh.size();
3655   bool     hasNotQuad = ( nbNotQuad || nbNotQuadMeshed );
3656
3657   // detect bad cases
3658   if ( nbNotQuadMeshed > 2 )
3659   {
3660     return toSM( error(COMPERR_BAD_INPUT_MESH,
3661                        TCom("More than 2 faces with not quadrangle elements: ")
3662                        <<nbNotQuadMeshed));
3663   }
3664   if ( nbNotQuad > 2 || !thePrism.myBottom.IsNull() )
3665   {
3666     // Issue 0020843 - one of side FACEs is quasi-quadrilateral (not 4 EDGEs).
3667     // Remove from notQuadGeomSubMesh faces meshed with regular grid
3668     int nbQuasiQuads = removeQuasiQuads( notQuadGeomSubMesh, myHelper,
3669                                          TQuadrangleAlgo::instance(this,myHelper) );
3670     nbNotQuad -= nbQuasiQuads;
3671     if ( nbNotQuad > 2 )
3672       return toSM( error(COMPERR_BAD_SHAPE,
3673                          TCom("More than 2 not quadrilateral faces: ") <<nbNotQuad));
3674     hasNotQuad = ( nbNotQuad || nbNotQuadMeshed );
3675   }
3676
3677   // Analyse mesh and topology of FACEs: choose the bottom sub-mesh.
3678   // If there are not quadrangle FACEs, they are top and bottom ones.
3679   // Not quadrangle FACEs must be only on top and bottom.
3680
3681   SMESH_subMesh * botSM = 0;
3682   SMESH_subMesh * topSM = 0;
3683
3684   if ( hasNotQuad ) // can choose a bottom FACE
3685   {
3686     if ( nbNotQuadMeshed > 0 ) botSM = notQuadElemSubMesh.front();
3687     else                       botSM = notQuadGeomSubMesh.front();
3688     if ( nbNotQuadMeshed > 1 ) topSM = notQuadElemSubMesh.back();
3689     else if ( nbNotQuad  > 1 ) topSM = notQuadGeomSubMesh.back();
3690
3691     if ( topSM == botSM ) {
3692       if ( nbNotQuadMeshed > 1 ) topSM = notQuadElemSubMesh.front();
3693       else                       topSM = notQuadGeomSubMesh.front();
3694     }
3695
3696     // detect mesh triangles on wall FACEs
3697     if ( nbNotQuad == 2 && nbNotQuadMeshed > 0 ) {
3698       bool ok = false;
3699       if ( nbNotQuadMeshed == 1 )
3700         ok = ( find( notQuadGeomSubMesh.begin(),
3701                      notQuadGeomSubMesh.end(), botSM ) != notQuadGeomSubMesh.end() );
3702       else
3703         ok = ( notQuadGeomSubMesh == notQuadElemSubMesh );
3704       if ( !ok )
3705         return toSM( error(COMPERR_BAD_INPUT_MESH,
3706                            "Side face meshed with not quadrangle elements"));
3707     }
3708   }
3709
3710   thePrism.myNotQuadOnTop = ( nbNotQuadMeshed > 1 );
3711
3712   // use thePrism.myBottom
3713   if ( !thePrism.myBottom.IsNull() )
3714   {
3715     if ( botSM ) { // <-- not quad geom or mesh on botSM
3716       if ( ! botSM->GetSubShape().IsSame( thePrism.myBottom )) {
3717         std::swap( botSM, topSM );
3718         if ( !botSM || ! botSM->GetSubShape().IsSame( thePrism.myBottom )) {
3719           if ( !selectBottom )
3720             return toSM( error( COMPERR_BAD_INPUT_MESH,
3721                                 "Incompatible non-structured sub-meshes"));
3722           std::swap( botSM, topSM );
3723           thePrism.myBottom = TopoDS::Face( botSM->GetSubShape() );
3724         }
3725       }
3726     }
3727     else if ( !selectBottom ) {
3728       botSM = myHelper->GetMesh()->GetSubMesh( thePrism.myBottom );
3729     }
3730   }
3731   if ( !botSM ) // find a proper bottom
3732   {
3733     bool savedSetErrorToSM = mySetErrorToSM;
3734     mySetErrorToSM = false; // ignore errors in initPrism()
3735
3736     // search among meshed FACEs
3737     list< SMESH_subMesh* >::iterator sm = meshedSubMesh.begin();
3738     for ( ; !botSM && sm != meshedSubMesh.end(); ++sm )
3739     {
3740       thePrism.Clear();
3741       botSM             = *sm;
3742       thePrism.myBottom = TopoDS::Face( botSM->GetSubShape() );
3743       if ( !initPrism( thePrism, theShape3D, /*selectBottom=*/false ))
3744         botSM = NULL;
3745     }
3746     // search among all FACEs
3747     for ( TopExp_Explorer f( theShape3D, TopAbs_FACE ); !botSM && f.More(); f.Next() )
3748     {
3749       int minNbFaces = 2 + myHelper->Count( f.Current(), TopAbs_EDGE, false);
3750       if ( nbFaces < minNbFaces) continue;
3751       thePrism.Clear();
3752       thePrism.myBottom = TopoDS::Face( f.Current() );
3753       botSM             = myHelper->GetMesh()->GetSubMesh( thePrism.myBottom );
3754       if ( !initPrism( thePrism, theShape3D, /*selectBottom=*/false ))
3755         botSM = NULL;
3756     }
3757     mySetErrorToSM = savedSetErrorToSM;
3758     return botSM ? true : toSM( error( COMPERR_BAD_SHAPE ));
3759   }
3760
3761   // find vertex 000 - the one with smallest coordinates (for easy DEBUG :-)
3762   TopoDS_Vertex V000;
3763   double minVal = DBL_MAX, minX = 0, val;
3764   for ( TopExp_Explorer exp( botSM->GetSubShape(), TopAbs_VERTEX );
3765         exp.More(); exp.Next() )
3766   {
3767     const TopoDS_Vertex& v = TopoDS::Vertex( exp.Current() );
3768     gp_Pnt P = BRep_Tool::Pnt( v );
3769     val = P.X() + P.Y() + P.Z();
3770     if ( val < minVal || ( val == minVal && P.X() < minX )) {
3771       V000 = v;
3772       minVal = val;
3773       minX = P.X();
3774     }
3775   }
3776
3777   thePrism.myShape3D = theShape3D;
3778   if ( thePrism.myBottom.IsNull() )
3779     thePrism.myBottom  = TopoDS::Face( botSM->GetSubShape() );
3780   thePrism.myBottom.Orientation( myHelper->GetSubShapeOri( theShape3D, thePrism.myBottom ));
3781   thePrism.myTop.   Orientation( myHelper->GetSubShapeOri( theShape3D, thePrism.myTop ));
3782
3783   // Get ordered bottom edges
3784   TopoDS_Face reverseBottom = // to have order of top EDGEs as in the top FACE
3785     TopoDS::Face( thePrism.myBottom.Reversed() );
3786   SMESH_Block::GetOrderedEdges( reverseBottom,
3787                                 thePrism.myBottomEdges,
3788                                 thePrism.myNbEdgesInWires, V000 );
3789
3790   // Get Wall faces corresponding to the ordered bottom edges and the top FACE
3791   if ( !getWallFaces( thePrism, nbFaces )) // it also sets thePrism.myTop
3792     return false; //toSM( error(COMPERR_BAD_SHAPE, "Can't find side faces"));
3793
3794   if ( topSM )
3795   {
3796     if ( !thePrism.myTop.IsSame( topSM->GetSubShape() ))
3797       return toSM( error
3798                    (notQuadGeomSubMesh.empty() ? COMPERR_BAD_INPUT_MESH : COMPERR_BAD_SHAPE,
3799                     "Non-quadrilateral faces are not opposite"));
3800
3801     // check that the found top and bottom FACEs are opposite
3802     TopTools_IndexedMapOfShape topEdgesMap( thePrism.myBottomEdges.size() );
3803     TopExp::MapShapes( thePrism.myTop, topEdgesMap );
3804     list< TopoDS_Edge >::iterator edge = thePrism.myBottomEdges.begin();
3805     for ( ; edge != thePrism.myBottomEdges.end(); ++edge )
3806       if ( topEdgesMap.Contains( *edge ))
3807         return toSM( error
3808                      (notQuadGeomSubMesh.empty() ? COMPERR_BAD_INPUT_MESH : COMPERR_BAD_SHAPE,
3809                       "Non-quadrilateral faces are not opposite"));
3810   }
3811
3812   if ( thePrism.myBottomEdges.size() > thePrism.myWallQuads.size() )
3813   {
3814     // composite bottom sides => set thePrism upside-down
3815     thePrism.SetUpsideDown();
3816   }
3817
3818   return true;
3819 }
3820
3821 //================================================================================
3822 /*!
3823  * \brief Initialization.
3824  * \param helper - helper loaded with mesh and 3D shape
3825  * \param thePrism - a prism data
3826  * \retval bool - false if a mesh or a shape are KO
3827  */
3828 //================================================================================
3829
3830 bool StdMeshers_PrismAsBlock::Init(SMESH_MesherHelper*         helper,
3831                                    const Prism_3D::TPrismTopo& thePrism)
3832 {
3833   myHelper = helper;
3834   SMESHDS_Mesh* meshDS = myHelper->GetMeshDS();
3835   SMESH_Mesh*     mesh = myHelper->GetMesh();
3836
3837   if ( mySide ) {
3838     delete mySide; mySide = 0;
3839   }
3840   vector< TSideFace* >         sideFaces( NB_WALL_FACES, 0 );
3841   vector< pair< double, double> > params( NB_WALL_FACES );
3842   mySide = new TSideFace( *mesh, sideFaces, params );
3843
3844
3845   SMESH_Block::init();
3846   myShapeIDMap.Clear();
3847   myShapeIndex2ColumnMap.clear();
3848
3849   int wallFaceIds[ NB_WALL_FACES ] = { // to walk around a block
3850     SMESH_Block::ID_Fx0z, SMESH_Block::ID_F1yz,
3851     SMESH_Block::ID_Fx1z, SMESH_Block::ID_F0yz
3852   };
3853
3854   myError = SMESH_ComputeError::New();
3855
3856   myNotQuadOnTop = thePrism.myNotQuadOnTop;
3857
3858   // Find columns of wall nodes and calculate edges' lengths
3859   // --------------------------------------------------------
3860
3861   myParam2ColumnMaps.clear();
3862   myParam2ColumnMaps.resize( thePrism.myBottomEdges.size() ); // total nb edges
3863
3864   size_t iE, nbEdges = thePrism.myNbEdgesInWires.front(); // nb outer edges
3865   vector< double > edgeLength( nbEdges );
3866   multimap< double, int > len2edgeMap;
3867
3868   // for each EDGE: either split into several parts, or join with several next EDGEs
3869   vector<int> nbSplitPerEdge( nbEdges, 0 );
3870   vector<int> nbUnitePerEdge( nbEdges, 0 ); // -1 means "joined to a previous"
3871
3872   // consider continuous straight EDGEs as one side
3873   const int nbSides = countNbSides( thePrism, nbUnitePerEdge, edgeLength );
3874
3875   list< TopoDS_Edge >::const_iterator edgeIt = thePrism.myBottomEdges.begin();
3876   for ( iE = 0; iE < nbEdges; ++iE, ++edgeIt )
3877   {
3878     TParam2ColumnMap & faceColumns = myParam2ColumnMaps[ iE ];
3879
3880     Prism_3D::TQuadList::const_iterator quad = thePrism.myWallQuads[ iE ].begin();
3881     for ( ; quad != thePrism.myWallQuads[ iE ].end(); ++quad )
3882     {
3883       const TopoDS_Edge& quadBot = (*quad)->side[ QUAD_BOTTOM_SIDE ].grid->Edge( 0 );
3884       if ( !myHelper->LoadNodeColumns( faceColumns, (*quad)->face, quadBot, meshDS ))
3885         return error(COMPERR_BAD_INPUT_MESH, TCom("Can't find regular quadrangle mesh ")
3886                      << "on a side face #" << MeshDS()->ShapeToIndex( (*quad)->face ));
3887     }
3888     SHOWYXZ("\np1 F " <<iE, gpXYZ(faceColumns.begin()->second.front() ));
3889     SHOWYXZ("p2 F "   <<iE, gpXYZ(faceColumns.rbegin()->second.front() ));
3890     SHOWYXZ("V First "<<iE, BRep_Tool::Pnt( TopExp::FirstVertex(*edgeIt,true )));
3891
3892     if ( nbSides < NB_WALL_FACES ) // fill map used to split faces
3893       len2edgeMap.insert( make_pair( edgeLength[ iE ], iE )); // sort edges by length
3894   }
3895   // Load columns of internal edges (forming holes)
3896   // and fill map ShapeIndex to TParam2ColumnMap for them
3897   for ( ; edgeIt != thePrism.myBottomEdges.end() ; ++edgeIt, ++iE )
3898   {
3899     TParam2ColumnMap & faceColumns = myParam2ColumnMaps[ iE ];
3900
3901     Prism_3D::TQuadList::const_iterator quad = thePrism.myWallQuads[ iE ].begin();
3902     for ( ; quad != thePrism.myWallQuads[ iE ].end(); ++quad )
3903     {
3904       const TopoDS_Edge& quadBot = (*quad)->side[ QUAD_BOTTOM_SIDE ].grid->Edge( 0 );
3905       if ( !myHelper->LoadNodeColumns( faceColumns, (*quad)->face, quadBot, meshDS ))
3906         return error(COMPERR_BAD_INPUT_MESH, TCom("Can't find regular quadrangle mesh ")
3907                      << "on a side face #" << MeshDS()->ShapeToIndex( (*quad)->face ));
3908     }
3909     if ( !faceColumns.empty() && (int)faceColumns.begin()->second.size() != VerticalSize() )
3910       return error(COMPERR_BAD_INPUT_MESH, "Different 'vertical' discretization");
3911
3912     // edge columns
3913     int id = MeshDS()->ShapeToIndex( *edgeIt );
3914     bool isForward = true; // meaningless for intenal wires
3915     myShapeIndex2ColumnMap[ id ] = make_pair( & faceColumns, isForward );
3916     // columns for vertices
3917     // 1
3918     const SMDS_MeshNode* n0 = faceColumns.begin()->second.front();
3919     id = n0->getshapeId();
3920     myShapeIndex2ColumnMap[ id ] = make_pair( & faceColumns, isForward );
3921     // 2
3922     const SMDS_MeshNode* n1 = faceColumns.rbegin()->second.front();
3923     id = n1->getshapeId();
3924     myShapeIndex2ColumnMap[ id ] = make_pair( & faceColumns, isForward );
3925
3926     // SHOWYXZ("\np1 F " <<iE, gpXYZ(faceColumns.begin()->second.front() ));
3927     // SHOWYXZ("p2 F "   <<iE, gpXYZ(faceColumns.rbegin()->second.front() ));
3928     // SHOWYXZ("V First "<<iE, BRep_Tool::Pnt( TopExp::FirstVertex(*edgeIt,true )));
3929   }
3930
3931   // Create 4 wall faces of a block
3932   // -------------------------------
3933
3934   if ( nbSides <= NB_WALL_FACES ) // ************* Split faces if necessary
3935   {
3936     if ( nbSides != NB_WALL_FACES ) // define how to split
3937     {
3938       if ( len2edgeMap.size() != nbEdges )
3939         RETURN_BAD_RESULT("Uniqueness of edge lengths not assured");
3940
3941       multimap< double, int >::reverse_iterator maxLen_i = len2edgeMap.rbegin();
3942       multimap< double, int >::reverse_iterator midLen_i = ++len2edgeMap.rbegin();
3943
3944       double maxLen = maxLen_i->first;
3945       double midLen = ( len2edgeMap.size() == 1 ) ? 0 : midLen_i->first;
3946       switch ( nbEdges ) {
3947       case 1: // 0-th edge is split into 4 parts
3948         nbSplitPerEdge[ 0 ] = 4;
3949         break;
3950       case 2: // either the longest edge is split into 3 parts, or both edges into halves
3951         if ( maxLen / 3 > midLen / 2 ) {
3952           nbSplitPerEdge[ maxLen_i->second ] = 3;
3953         }
3954         else {
3955           nbSplitPerEdge[ maxLen_i->second ] = 2;
3956           nbSplitPerEdge[ midLen_i->second ] = 2;
3957         }
3958         break;
3959       case 3:
3960         if ( nbSides == 2 )
3961           // split longest into 3 parts
3962           nbSplitPerEdge[ maxLen_i->second ] = 3;
3963         else
3964           // split longest into halves
3965           nbSplitPerEdge[ maxLen_i->second ] = 2;
3966       }
3967     }
3968   }
3969   else // **************************** Unite faces
3970   {
3971     int nbExraFaces = nbSides - 4; // nb of faces to fuse
3972     for ( iE = 0; iE < nbEdges; ++iE )
3973     {
3974       if ( nbUnitePerEdge[ iE ] < 0 )
3975         continue;
3976       // look for already united faces
3977       for ( size_t i = iE; i < iE + nbExraFaces; ++i )
3978       {
3979         if ( nbUnitePerEdge[ i ] > 0 ) // a side including nbUnitePerEdge[i]+1 edge
3980           nbExraFaces += nbUnitePerEdge[ i ];
3981         nbUnitePerEdge[ i ] = -1;
3982       }
3983       nbUnitePerEdge[ iE ] = nbExraFaces;
3984       break;
3985     }
3986   }
3987
3988   // Create TSideFace's
3989   int iSide = 0;
3990   list< TopoDS_Edge >::const_iterator botE = thePrism.myBottomEdges.begin();
3991   for ( iE = 0; iE < nbEdges; ++iE, ++botE )
3992   {
3993     TFaceQuadStructPtr quad = thePrism.myWallQuads[ iE ].front();
3994     const int       nbSplit = nbSplitPerEdge[ iE ];
3995     const int   nbExraFaces = nbUnitePerEdge[ iE ] + 1;
3996     if ( nbSplit > 0 ) // split
3997     {
3998       vector< double > params;
3999       splitParams( nbSplit, &myParam2ColumnMaps[ iE ], params );
4000       const bool isForward =
4001         StdMeshers_PrismAsBlock::IsForwardEdge( myHelper->GetMeshDS(),
4002                                                 myParam2ColumnMaps[iE],
4003                                                 *botE, SMESH_Block::ID_Fx0z );
4004       for ( int i = 0; i < nbSplit; ++i ) {
4005         double f = ( isForward ? params[ i ]   : params[ nbSplit - i-1 ]);
4006         double l = ( isForward ? params[ i+1 ] : params[ nbSplit - i ]);
4007         TSideFace* comp = new TSideFace( *mesh, wallFaceIds[ iSide ],
4008                                          thePrism.myWallQuads[ iE ], *botE,
4009                                          &myParam2ColumnMaps[ iE ], f, l );
4010         mySide->SetComponent( iSide++, comp );
4011       }
4012     }
4013     else if ( nbExraFaces > 1 ) // unite
4014     {
4015       double u0 = 0, sumLen = 0;
4016       for ( size_t i = iE; i < iE + nbExraFaces; ++i )
4017         sumLen += edgeLength[ i ];
4018
4019       vector< TSideFace* >        components( nbExraFaces );
4020       vector< pair< double, double> > params( nbExraFaces );
4021       bool endReached = false;
4022       for ( int i = 0; i < nbExraFaces; ++i, ++botE, ++iE )
4023       {
4024         if ( iE == nbEdges )
4025         {
4026           endReached = true;
4027           botE = thePrism.myBottomEdges.begin();
4028           iE = 0;
4029         }
4030         components[ i ] = new TSideFace( *mesh, wallFaceIds[ iSide ],
4031                                          thePrism.myWallQuads[ iE ], *botE,
4032                                          &myParam2ColumnMaps[ iE ]);
4033         double u1 = u0 + edgeLength[ iE ] / sumLen;
4034         params[ i ] = make_pair( u0 , u1 );
4035         u0 = u1;
4036       }
4037       TSideFace* comp = new TSideFace( *mesh, components, params );
4038       mySide->SetComponent( iSide++, comp );
4039       if ( endReached )
4040         break;
4041       --iE; // for increment in an external loop on iE
4042       --botE;
4043     }
4044     else if ( nbExraFaces < 0 ) // skip already united face
4045     {
4046     }
4047     else // use as is
4048     {
4049       TSideFace* comp = new TSideFace( *mesh, wallFaceIds[ iSide ],
4050                                        thePrism.myWallQuads[ iE ], *botE,
4051                                        &myParam2ColumnMaps[ iE ]);
4052       mySide->SetComponent( iSide++, comp );
4053     }
4054   }
4055
4056
4057   // Fill geometry fields of SMESH_Block
4058   // ------------------------------------
4059
4060   vector< int > botEdgeIdVec;
4061   SMESH_Block::GetFaceEdgesIDs( ID_BOT_FACE, botEdgeIdVec );
4062
4063   bool isForward[NB_WALL_FACES] = { true, true, true, true };
4064   Adaptor2d_Curve2d* botPcurves[NB_WALL_FACES];
4065   Adaptor2d_Curve2d* topPcurves[NB_WALL_FACES];
4066
4067   for ( int iF = 0; iF < NB_WALL_FACES; ++iF )
4068   {
4069     TSideFace * sideFace = mySide->GetComponent( iF );
4070     if ( !sideFace )
4071       RETURN_BAD_RESULT("NULL TSideFace");
4072     int fID = sideFace->FaceID(); // in-block ID
4073
4074     // fill myShapeIDMap
4075     if ( sideFace->InsertSubShapes( myShapeIDMap ) != 8 &&
4076          !sideFace->IsComplex())
4077       MESSAGE( ": Warning : InsertSubShapes() < 8 on side " << iF );
4078
4079     // side faces geometry
4080     Adaptor2d_Curve2d* pcurves[NB_WALL_FACES];
4081     if ( !sideFace->GetPCurves( pcurves ))
4082       RETURN_BAD_RESULT("TSideFace::GetPCurves() failed");
4083
4084     SMESH_Block::TFace& tFace = myFace[ fID - ID_FirstF ];
4085     tFace.Set( fID, sideFace->Surface(), pcurves, isForward );
4086
4087     SHOWYXZ( endl<<"F "<< iF << " id " << fID << " FRW " << sideFace->IsForward(), sideFace->Value(0,0));
4088     // edges 3D geometry
4089     vector< int > edgeIdVec;
4090     SMESH_Block::GetFaceEdgesIDs( fID, edgeIdVec );
4091     for ( int isMax = 0; isMax < 2; ++isMax ) {
4092       {
4093         int eID = edgeIdVec[ isMax ];
4094         SMESH_Block::TEdge& tEdge = myEdge[ eID - ID_FirstE ];
4095         tEdge.Set( eID, sideFace->HorizCurve(isMax), true);
4096         SHOWYXZ(eID<<" HOR"<<isMax<<"(0)", sideFace->HorizCurve(isMax)->Value(0));
4097         SHOWYXZ(eID<<" HOR"<<isMax<<"(1)", sideFace->HorizCurve(isMax)->Value(1));
4098       }
4099       {
4100         int eID = edgeIdVec[ isMax+2 ];
4101         SMESH_Block::TEdge& tEdge = myEdge[ eID - ID_FirstE  ];
4102         tEdge.Set( eID, sideFace->VertiCurve(isMax), true);
4103         SHOWYXZ(eID<<" VER"<<isMax<<"(0)", sideFace->VertiCurve(isMax)->Value(0));
4104         SHOWYXZ(eID<<" VER"<<isMax<<"(1)", sideFace->VertiCurve(isMax)->Value(1));
4105
4106         // corner points
4107         vector< int > vertexIdVec;
4108         SMESH_Block::GetEdgeVertexIDs( eID, vertexIdVec );
4109         myPnt[ vertexIdVec[0] - ID_FirstV ] = tEdge.GetCurve()->Value(0).XYZ();
4110         myPnt[ vertexIdVec[1] - ID_FirstV ] = tEdge.GetCurve()->Value(1).XYZ();
4111       }
4112     }
4113     // pcurves on horizontal faces
4114     for ( iE = 0; iE < NB_WALL_FACES; ++iE ) {
4115       if ( edgeIdVec[ BOTTOM_EDGE ] == botEdgeIdVec[ iE ] ) {
4116         botPcurves[ iE ] = sideFace->HorizPCurve( false, thePrism.myBottom );
4117         topPcurves[ iE ] = sideFace->HorizPCurve( true,  thePrism.myTop );
4118         break;
4119       }
4120     }
4121     //sideFace->dumpNodes( 4 ); // debug
4122   }
4123   // horizontal faces geometry
4124   {
4125     SMESH_Block::TFace& tFace = myFace[ ID_BOT_FACE - ID_FirstF ];
4126     tFace.Set( ID_BOT_FACE, new BRepAdaptor_Surface( thePrism.myBottom ), botPcurves, isForward );
4127     SMESH_Block::Insert( thePrism.myBottom, ID_BOT_FACE, myShapeIDMap );
4128   }
4129   {
4130     SMESH_Block::TFace& tFace = myFace[ ID_TOP_FACE - ID_FirstF ];
4131     tFace.Set( ID_TOP_FACE, new BRepAdaptor_Surface( thePrism.myTop ), topPcurves, isForward );
4132     SMESH_Block::Insert( thePrism.myTop, ID_TOP_FACE, myShapeIDMap );
4133   }
4134   //faceGridToPythonDump( SMESH_Block::ID_Fxy0, 50 );
4135   //faceGridToPythonDump( SMESH_Block::ID_Fxy1 );
4136
4137   // Fill map ShapeIndex to TParam2ColumnMap
4138   // ----------------------------------------
4139
4140   list< TSideFace* > fList;
4141   list< TSideFace* >::iterator fListIt;
4142   fList.push_back( mySide );
4143   for ( fListIt = fList.begin(); fListIt != fList.end(); ++fListIt)
4144   {
4145     int nb = (*fListIt)->NbComponents();
4146     for ( int i = 0; i < nb; ++i ) {
4147       if ( TSideFace* comp = (*fListIt)->GetComponent( i ))
4148         fList.push_back( comp );
4149     }
4150     if ( TParam2ColumnMap* cols = (*fListIt)->GetColumns()) {
4151       // columns for a base edge
4152       int id = MeshDS()->ShapeToIndex( (*fListIt)->BaseEdge() );
4153       bool isForward = (*fListIt)->IsForward();
4154       myShapeIndex2ColumnMap[ id ] = make_pair( cols, isForward );
4155
4156       // columns for vertices
4157       const SMDS_MeshNode* n0 = cols->begin()->second.front();
4158       id = n0->getshapeId();
4159       myShapeIndex2ColumnMap[ id ] = make_pair( cols, isForward );
4160
4161       const SMDS_MeshNode* n1 = cols->rbegin()->second.front();
4162       id = n1->getshapeId();
4163       myShapeIndex2ColumnMap[ id ] = make_pair( cols, !isForward );
4164     }
4165   }
4166
4167 // #define SHOWYXZ(msg, xyz) { gp_Pnt p(xyz); cout << msg << " ("<< p.X() << "; " <<p.Y() << "; " <<p.Z() << ") " <<endl; }
4168
4169 //   double _u[]={ 0.1, 0.1, 0.9, 0.9 };
4170 //   double _v[]={ 0.1, 0.9, 0.1, 0.9 };
4171 //   for ( int z = 0; z < 2; ++z )
4172 //     for ( int i = 0; i < 4; ++i )
4173 //     {
4174 //       //gp_XYZ testPar(0.25, 0.25, 0), testCoord;
4175 //       int iFace = (z ? ID_TOP_FACE : ID_BOT_FACE);
4176 //       gp_XYZ testPar(_u[i], _v[i], z), testCoord;
4177 //       if ( !FacePoint( iFace, testPar, testCoord ))
4178 //         RETURN_BAD_RESULT("TEST FacePoint() FAILED");
4179 //       SHOWYXZ("IN TEST PARAM" , testPar);
4180 //       SHOWYXZ("OUT TEST CORD" , testCoord);
4181 //       if ( !ComputeParameters( testCoord, testPar , iFace))
4182 //         RETURN_BAD_RESULT("TEST ComputeParameters() FAILED");
4183 //       SHOWYXZ("OUT TEST PARAM" , testPar);
4184 //     }
4185   return true;
4186 }
4187
4188 //================================================================================
4189 /*!
4190  * \brief Return pointer to column of nodes
4191  * \param node - bottom node from which the returned column goes up
4192  * \retval const TNodeColumn* - the found column
4193  */
4194 //================================================================================
4195
4196 const TNodeColumn* StdMeshers_PrismAsBlock::GetNodeColumn(const SMDS_MeshNode* node) const
4197 {
4198   int sID = node->getshapeId();
4199
4200   map<int, pair< TParam2ColumnMap*, bool > >::const_iterator col_frw =
4201     myShapeIndex2ColumnMap.find( sID );
4202   if ( col_frw != myShapeIndex2ColumnMap.end() ) {
4203     const TParam2ColumnMap* cols = col_frw->second.first;
4204     TParam2ColumnIt u_col = cols->begin();
4205     for ( ; u_col != cols->end(); ++u_col )
4206       if ( u_col->second[ 0 ] == node )
4207         return & u_col->second;
4208   }
4209   return 0;
4210 }
4211
4212 //=======================================================================
4213 //function : GetLayersTransformation
4214 //purpose  : Return transformations to get coordinates of nodes of each layer
4215 //           by nodes of the bottom. Layer is a set of nodes at a certain step
4216 //           from bottom to top.
4217 //           Transformation to get top node from bottom ones is computed
4218 //           only if the top FACE is not meshed.
4219 //=======================================================================
4220
4221 bool StdMeshers_PrismAsBlock::GetLayersTransformation(vector<gp_Trsf> &           trsf,
4222                                                       const Prism_3D::TPrismTopo& prism) const
4223 {
4224   const bool itTopMeshed = !SubMesh( ID_BOT_FACE )->IsEmpty();
4225   const int zSize = VerticalSize();
4226   if ( zSize < 3 && !itTopMeshed ) return true;
4227   trsf.resize( zSize - 1 );
4228
4229   // Select some node columns by which we will define coordinate system of layers
4230
4231   vector< const TNodeColumn* > columns;
4232   {
4233     bool isReverse;
4234     list< TopoDS_Edge >::const_iterator edgeIt = prism.myBottomEdges.begin();
4235     for ( int iE = 0; iE < prism.myNbEdgesInWires.front(); ++iE, ++edgeIt )
4236     {
4237       if ( SMESH_Algo::isDegenerated( *edgeIt )) continue;
4238       const TParam2ColumnMap* u2colMap =
4239         GetParam2ColumnMap( MeshDS()->ShapeToIndex( *edgeIt ), isReverse );
4240       if ( !u2colMap ) return false;
4241       double f = u2colMap->begin()->first, l = u2colMap->rbegin()->first;
4242       //isReverse = ( edgeIt->Orientation() == TopAbs_REVERSED );
4243       //if ( isReverse ) swap ( f, l ); -- u2colMap takes orientation into account
4244       const int nbCol = 5;
4245       for ( int i = 0; i < nbCol; ++i )
4246       {
4247         double u = f + i/double(nbCol) * ( l - f );
4248         const TNodeColumn* col = & getColumn( u2colMap, u )->second;
4249         if ( columns.empty() || col != columns.back() )
4250           columns.push_back( col );
4251       }
4252     }
4253   }
4254
4255   // Find tolerance to check transformations
4256
4257   double tol2;
4258   {
4259     Bnd_B3d bndBox;
4260     for ( size_t i = 0; i < columns.size(); ++i )
4261       bndBox.Add( gpXYZ( columns[i]->front() ));
4262     tol2 = bndBox.SquareExtent() * 1e-5;
4263   }
4264
4265   // Compute transformations
4266
4267   int xCol = -1;
4268   gp_Trsf fromCsZ, toCs0;
4269   gp_Ax3 cs0 = getLayerCoordSys(0, columns, xCol );
4270   //double dist0 = cs0.Location().Distance( gpXYZ( (*columns[0])[0]));
4271   toCs0.SetTransformation( cs0 );
4272   for ( int z = 1; z < zSize; ++z )
4273   {
4274     gp_Ax3 csZ = getLayerCoordSys(z, columns, xCol );
4275     //double distZ = csZ.Location().Distance( gpXYZ( (*columns[0])[z]));
4276     fromCsZ.SetTransformation( csZ );
4277     fromCsZ.Invert();
4278     gp_Trsf& t = trsf[ z-1 ];
4279     t = fromCsZ * toCs0;
4280     //t.SetScaleFactor( distZ/dist0 ); - it does not work properly, wrong base point
4281
4282     // check a transformation
4283     for ( size_t i = 0; i < columns.size(); ++i )
4284     {
4285       gp_Pnt p0 = gpXYZ( (*columns[i])[0] );
4286       gp_Pnt pz = gpXYZ( (*columns[i])[z] );
4287       t.Transforms( p0.ChangeCoord() );
4288       if ( p0.SquareDistance( pz ) > tol2 )
4289       {
4290         t = gp_Trsf();
4291         return ( z == zSize - 1 ); // OK if fails only bottom->top trsf
4292       }
4293     }
4294   }
4295   return true;
4296 }
4297
4298 //================================================================================
4299 /*!
4300  * \brief Check curve orientation of a bottom edge
4301   * \param meshDS - mesh DS
4302   * \param columnsMap - node columns map of side face
4303   * \param bottomEdge - the bottom edge
4304   * \param sideFaceID - side face in-block ID
4305   * \retval bool - true if orientation coincide with in-block forward orientation
4306  */
4307 //================================================================================
4308
4309 bool StdMeshers_PrismAsBlock::IsForwardEdge(SMESHDS_Mesh*           meshDS,
4310                                             const TParam2ColumnMap& columnsMap,
4311                                             const TopoDS_Edge &     bottomEdge,
4312                                             const int               sideFaceID)
4313 {
4314   bool isForward = false;
4315   if ( SMESH_MesherHelper::IsClosedEdge( bottomEdge ))
4316   {
4317     isForward = ( bottomEdge.Orientation() == TopAbs_FORWARD );
4318   }
4319   else
4320   {
4321     const TNodeColumn&     firstCol = columnsMap.begin()->second;
4322     const SMDS_MeshNode* bottomNode = firstCol[0];
4323     TopoDS_Shape firstVertex = SMESH_MesherHelper::GetSubShapeByNode( bottomNode, meshDS );
4324     isForward = ( firstVertex.IsSame( TopExp::FirstVertex( bottomEdge, true )));
4325   }
4326   // on 2 of 4 sides first vertex is end
4327   if ( sideFaceID == ID_Fx1z || sideFaceID == ID_F0yz )
4328     isForward = !isForward;
4329   return isForward;
4330 }
4331
4332 //=======================================================================
4333 //function : faceGridToPythonDump
4334 //purpose  : Prints a script creating a normal grid on the prism side
4335 //=======================================================================
4336
4337 void StdMeshers_PrismAsBlock::faceGridToPythonDump(const SMESH_Block::TShapeID face,
4338                                                    const int                   nb)
4339 {
4340 #ifdef _DEBUG_
4341   gp_XYZ pOnF[6] = { gp_XYZ(0,0,0), gp_XYZ(0,0,1),
4342                      gp_XYZ(0,0,0), gp_XYZ(0,1,0),
4343                      gp_XYZ(0,0,0), gp_XYZ(1,0,0) };
4344   gp_XYZ p2;
4345   cout << "mesh = smesh.Mesh( 'Face " << face << "')" << endl;
4346   SMESH_Block::TFace& f = myFace[ face - ID_FirstF ];
4347   gp_XYZ params = pOnF[ face - ID_FirstF ];
4348   //const int nb = 10; // nb face rows
4349   for ( int j = 0; j <= nb; ++j )
4350   {
4351     params.SetCoord( f.GetVInd(), double( j )/ nb );
4352     for ( int i = 0; i <= nb; ++i )
4353     {
4354       params.SetCoord( f.GetUInd(), double( i )/ nb );
4355       gp_XYZ p = f.Point( params );
4356       gp_XY uv = f.GetUV( params );
4357       cout << "mesh.AddNode( " << p.X() << ", " << p.Y() << ", " << p.Z() << " )"
4358            << " # " << 1 + i + j * ( nb + 1 )
4359            << " ( " << i << ", " << j << " ) "
4360            << " UV( " << uv.X() << ", " << uv.Y() << " )" << endl;
4361       ShellPoint( params, p2 );
4362       double dist = ( p2 - p ).Modulus();
4363       if ( dist > 1e-4 )
4364         cout << "#### dist from ShellPoint " << dist
4365              << " (" << p2.X() << ", " << p2.Y() << ", " << p2.Z() << " ) " << endl;
4366     }
4367   }
4368   for ( int j = 0; j < nb; ++j )
4369     for ( int i = 0; i < nb; ++i )
4370     {
4371       int n = 1 + i + j * ( nb + 1 );
4372       cout << "mesh.AddFace([ "
4373            << n << ", " << n+1 << ", "
4374            << n+nb+2 << ", " << n+nb+1 << "]) " << endl;
4375     }
4376
4377 #endif
4378 }
4379
4380 //================================================================================
4381 /*!
4382  * \brief Constructor
4383   * \param faceID - in-block ID
4384   * \param face - geom FACE
4385   * \param baseEdge - EDGE proreply oriented in the bottom EDGE !!!
4386   * \param columnsMap - map of node columns
4387   * \param first - first normalized param
4388   * \param last - last normalized param
4389  */
4390 //================================================================================
4391
4392 StdMeshers_PrismAsBlock::TSideFace::TSideFace(SMESH_Mesh&                mesh,
4393                                               const int                  faceID,
4394                                               const Prism_3D::TQuadList& quadList,
4395                                               const TopoDS_Edge&         baseEdge,
4396                                               TParam2ColumnMap*          columnsMap,
4397                                               const double               first,
4398                                               const double               last):
4399   myID( faceID ),
4400   myParamToColumnMap( columnsMap ),
4401   myHelper( mesh )
4402 {
4403   myParams.resize( 1 );
4404   myParams[ 0 ] = make_pair( first, last );
4405   mySurface     = PSurface( new BRepAdaptor_Surface( quadList.front()->face ));
4406   myBaseEdge    = baseEdge;
4407   myIsForward   = StdMeshers_PrismAsBlock::IsForwardEdge( myHelper.GetMeshDS(),
4408                                                           *myParamToColumnMap,
4409                                                           myBaseEdge, myID );
4410   myHelper.SetSubShape( quadList.front()->face );
4411
4412   if ( quadList.size() > 1 ) // side is vertically composite
4413   {
4414     // fill myShapeID2Surf map to enable finding a right surface by any sub-shape ID
4415
4416     SMESHDS_Mesh* meshDS = myHelper.GetMeshDS();
4417
4418     TopTools_IndexedDataMapOfShapeListOfShape subToFaces;
4419     Prism_3D::TQuadList::const_iterator quad = quadList.begin();
4420     for ( ; quad != quadList.end(); ++quad )
4421     {
4422       const TopoDS_Face& face = (*quad)->face;
4423       TopExp::MapShapesAndAncestors( face, TopAbs_VERTEX, TopAbs_FACE, subToFaces );
4424       TopExp::MapShapesAndAncestors( face, TopAbs_EDGE,   TopAbs_FACE, subToFaces );
4425       myShapeID2Surf.insert( make_pair( meshDS->ShapeToIndex( face ),
4426                                         PSurface( new BRepAdaptor_Surface( face ))));
4427     }
4428     for ( int i = 1; i <= subToFaces.Extent(); ++i )
4429     {
4430       const TopoDS_Shape&     sub = subToFaces.FindKey( i );
4431       TopTools_ListOfShape& faces = subToFaces( i );
4432       int subID  = meshDS->ShapeToIndex( sub );
4433       int faceID = meshDS->ShapeToIndex( faces.First() );
4434       myShapeID2Surf.insert ( make_pair( subID, myShapeID2Surf[ faceID ]));
4435     }
4436   }
4437 }
4438
4439 //================================================================================
4440 /*!
4441  * \brief Constructor of a complex side face
4442  */
4443 //================================================================================
4444
4445 StdMeshers_PrismAsBlock::TSideFace::
4446 TSideFace(SMESH_Mesh&                             mesh,
4447           const vector< TSideFace* >&             components,
4448           const vector< pair< double, double> > & params)
4449   :myID( components[0] ? components[0]->myID : 0 ),
4450    myParamToColumnMap( 0 ),
4451    myParams( params ),
4452    myIsForward( true ),
4453    myComponents( components ),
4454    myHelper( mesh )
4455 {
4456   if ( myID == ID_Fx1z || myID == ID_F0yz )
4457   {
4458     // reverse components
4459     std::reverse( myComponents.begin(), myComponents.end() );
4460     std::reverse( myParams.begin(),     myParams.end() );
4461     for ( size_t i = 0; i < myParams.size(); ++i )
4462     {
4463       const double f = myParams[i].first;
4464       const double l = myParams[i].second;
4465       myParams[i] = make_pair( 1. - l, 1. - f );
4466     }
4467   }
4468 }
4469 //================================================================================
4470 /*!
4471  * \brief Copy constructor
4472   * \param other - other side
4473  */
4474 //================================================================================
4475
4476 StdMeshers_PrismAsBlock::TSideFace::TSideFace( const TSideFace& other ):
4477   myID               ( other.myID ),
4478   myParamToColumnMap ( other.myParamToColumnMap ),
4479   mySurface          ( other.mySurface ),
4480   myBaseEdge         ( other.myBaseEdge ),
4481   myShapeID2Surf     ( other.myShapeID2Surf ),
4482   myParams           ( other.myParams ),
4483   myIsForward        ( other.myIsForward ),
4484   myComponents       ( other.myComponents.size() ),
4485   myHelper           ( *other.myHelper.GetMesh() )
4486 {
4487   for ( size_t i = 0 ; i < myComponents.size(); ++i )
4488     myComponents[ i ] = new TSideFace( *other.myComponents[ i ]);
4489 }
4490
4491 //================================================================================
4492 /*!
4493  * \brief Deletes myComponents
4494  */
4495 //================================================================================
4496
4497 StdMeshers_PrismAsBlock::TSideFace::~TSideFace()
4498 {
4499   for ( size_t i = 0 ; i < myComponents.size(); ++i )
4500     if ( myComponents[ i ] )
4501       delete myComponents[ i ];
4502 }
4503
4504 //================================================================================
4505 /*!
4506  * \brief Return geometry of the vertical curve
4507   * \param isMax - true means curve located closer to (1,1,1) block point
4508   * \retval Adaptor3d_Curve* - curve adaptor
4509  */
4510 //================================================================================
4511
4512 Adaptor3d_Curve* StdMeshers_PrismAsBlock::TSideFace::VertiCurve(const bool isMax) const
4513 {
4514   if ( !myComponents.empty() ) {
4515     if ( isMax )
4516       return myComponents.back()->VertiCurve(isMax);
4517     else
4518       return myComponents.front()->VertiCurve(isMax);
4519   }
4520   double f = myParams[0].first, l = myParams[0].second;
4521   if ( !myIsForward ) std::swap( f, l );
4522   return new TVerticalEdgeAdaptor( myParamToColumnMap, isMax ? l : f );
4523 }
4524
4525 //================================================================================
4526 /*!
4527  * \brief Return geometry of the top or bottom curve
4528   * \param isTop -
4529   * \retval Adaptor3d_Curve* -
4530  */
4531 //================================================================================
4532
4533 Adaptor3d_Curve* StdMeshers_PrismAsBlock::TSideFace::HorizCurve(const bool isTop) const
4534 {
4535   return new THorizontalEdgeAdaptor( this, isTop );
4536 }
4537
4538 //================================================================================
4539 /*!
4540  * \brief Return pcurves
4541   * \param pcurv - array of 4 pcurves
4542   * \retval bool - is a success
4543  */
4544 //================================================================================
4545
4546 bool StdMeshers_PrismAsBlock::TSideFace::GetPCurves(Adaptor2d_Curve2d* pcurv[4]) const
4547 {
4548   int iEdge[ 4 ] = { BOTTOM_EDGE, TOP_EDGE, V0_EDGE, V1_EDGE };
4549
4550   for ( int i = 0 ; i < 4 ; ++i ) {
4551     Handle(Geom2d_Line) line;
4552     switch ( iEdge[ i ] ) {
4553     case TOP_EDGE:
4554       line = new Geom2d_Line( gp_Pnt2d( 0, 1 ), gp::DX2d() ); break;
4555     case BOTTOM_EDGE:
4556       line = new Geom2d_Line( gp::Origin2d(), gp::DX2d() ); break;
4557     case V0_EDGE:
4558       line = new Geom2d_Line( gp::Origin2d(), gp::DY2d() ); break;
4559     case V1_EDGE:
4560       line = new Geom2d_Line( gp_Pnt2d( 1, 0 ), gp::DY2d() ); break;
4561     }
4562     pcurv[ i ] = new Geom2dAdaptor_Curve( line, 0, 1 );
4563   }
4564   return true;
4565 }
4566
4567 //================================================================================
4568 /*!
4569  * \brief Returns geometry of pcurve on a horizontal face
4570   * \param isTop - is top or bottom face
4571   * \param horFace - a horizontal face
4572   * \retval Adaptor2d_Curve2d* - curve adaptor
4573  */
4574 //================================================================================
4575
4576 Adaptor2d_Curve2d*
4577 StdMeshers_PrismAsBlock::TSideFace::HorizPCurve(const bool         isTop,
4578                                                 const TopoDS_Face& horFace) const
4579 {
4580   return new TPCurveOnHorFaceAdaptor( this, isTop, horFace );
4581 }
4582
4583 //================================================================================
4584 /*!
4585  * \brief Return a component corresponding to parameter
4586   * \param U - parameter along a horizontal size
4587   * \param localU - parameter along a horizontal size of a component
4588   * \retval TSideFace* - found component
4589  */
4590 //================================================================================
4591
4592 StdMeshers_PrismAsBlock::TSideFace*
4593 StdMeshers_PrismAsBlock::TSideFace::GetComponent(const double U,double & localU) const
4594 {
4595   localU = U;
4596   if ( myComponents.empty() )
4597     return const_cast<TSideFace*>( this );
4598
4599   size_t i;
4600   for ( i = 0; i < myComponents.size(); ++i )
4601     if ( U < myParams[ i ].second )
4602       break;
4603   if ( i >= myComponents.size() )
4604     i = myComponents.size() - 1;
4605
4606   double f = myParams[ i ].first, l = myParams[ i ].second;
4607   localU = ( U - f ) / ( l - f );
4608   return myComponents[ i ];
4609 }
4610
4611 //================================================================================
4612 /*!
4613  * \brief Find node columns for a parameter
4614   * \param U - parameter along a horizontal edge
4615   * \param col1 - the 1st found column
4616   * \param col2 - the 2nd found column
4617   * \retval r - normalized position of U between the found columns
4618  */
4619 //================================================================================
4620
4621 double StdMeshers_PrismAsBlock::TSideFace::GetColumns(const double      U,
4622                                                       TParam2ColumnIt & col1,
4623                                                       TParam2ColumnIt & col2) const
4624 {
4625   double u = U, r = 0;
4626   if ( !myComponents.empty() ) {
4627     TSideFace * comp = GetComponent(U,u);
4628     return comp->GetColumns( u, col1, col2 );
4629   }
4630
4631   if ( !myIsForward )
4632     u = 1 - u;
4633   double f = myParams[0].first, l = myParams[0].second;
4634   u = f + u * ( l - f );
4635
4636   col1 = col2 = getColumn( myParamToColumnMap, u );
4637   if ( ++col2 == myParamToColumnMap->end() ) {
4638     --col2;
4639     r = 0.5;
4640   }
4641   else {
4642     double uf = col1->first;
4643     double ul = col2->first;
4644     r = ( u - uf ) / ( ul - uf );
4645   }
4646   return r;
4647 }
4648
4649 //================================================================================
4650 /*!
4651  * \brief Return all nodes at a given height together with their normalized parameters
4652  *  \param [in] Z - the height of interest
4653  *  \param [out] nodes - map of parameter to node
4654  */
4655 //================================================================================
4656
4657 void StdMeshers_PrismAsBlock::
4658 TSideFace::GetNodesAtZ(const int Z,
4659                        map<double, const SMDS_MeshNode* >& nodes ) const
4660 {
4661   if ( !myComponents.empty() )
4662   {
4663     double u0 = 0.;
4664     for ( size_t i = 0; i < myComponents.size(); ++i )
4665     {
4666       map<double, const SMDS_MeshNode* > nn;
4667       myComponents[i]->GetNodesAtZ( Z, nn );
4668       map<double, const SMDS_MeshNode* >::iterator u2n = nn.begin();
4669       if ( !nodes.empty() && nodes.rbegin()->second == u2n->second )
4670         ++u2n;
4671       const double uRange = myParams[i].second - myParams[i].first;
4672       for ( ; u2n != nn.end(); ++u2n )
4673         nodes.insert( nodes.end(), make_pair( u0 + uRange * u2n->first, u2n->second ));
4674       u0 += uRange;
4675     }
4676   }
4677   else
4678   {
4679     double f = myParams[0].first, l = myParams[0].second;
4680     if ( !myIsForward )
4681       std::swap( f, l );
4682     const double uRange = l - f;
4683     if ( Abs( uRange ) < std::numeric_limits<double>::min() )
4684       return;
4685     TParam2ColumnIt u2col = getColumn( myParamToColumnMap, myParams[0].first + 1e-3 );
4686     for ( ; u2col != myParamToColumnMap->end(); ++u2col )
4687       if ( u2col->first > myParams[0].second + 1e-9 )
4688         break;
4689       else
4690         nodes.insert( nodes.end(),
4691                       make_pair( ( u2col->first - f ) / uRange, u2col->second[ Z ] ));
4692   }
4693 }
4694
4695 //================================================================================
4696 /*!
4697  * \brief Return coordinates by normalized params
4698   * \param U - horizontal param
4699   * \param V - vertical param
4700   * \retval gp_Pnt - result point
4701  */
4702 //================================================================================
4703
4704 gp_Pnt StdMeshers_PrismAsBlock::TSideFace::Value(const Standard_Real U,
4705                                                  const Standard_Real V) const
4706 {
4707   if ( !myComponents.empty() ) {
4708     double u;
4709     TSideFace * comp = GetComponent(U,u);
4710     return comp->Value( u, V );
4711   }
4712
4713   TParam2ColumnIt u_col1, u_col2;
4714   double vR, hR = GetColumns( U, u_col1, u_col2 );
4715
4716   const SMDS_MeshNode* nn[4];
4717
4718   // BEGIN issue 0020680: Bad cell created by Radial prism in center of torus
4719   // Workaround for a wrongly located point returned by mySurface.Value() for
4720   // UV located near boundary of BSpline surface.
4721   // To bypass the problem, we take point from 3D curve of EDGE.
4722   // It solves pb of the bloc_fiss_new.py
4723   const double tol = 1e-3;
4724   if ( V < tol || V+tol >= 1. )
4725   {
4726     nn[0] = V < tol ? u_col1->second.front() : u_col1->second.back();
4727     nn[2] = V < tol ? u_col2->second.front() : u_col2->second.back();
4728     TopoDS_Edge edge;
4729     if ( V < tol )
4730     {
4731       edge = myBaseEdge;
4732     }
4733     else
4734     {
4735       TopoDS_Shape s = myHelper.GetSubShapeByNode( nn[0], myHelper.GetMeshDS() );
4736       if ( s.ShapeType() != TopAbs_EDGE )
4737         s = myHelper.GetSubShapeByNode( nn[2], myHelper.GetMeshDS() );
4738       if ( !s.IsNull() && s.ShapeType() == TopAbs_EDGE )
4739         edge = TopoDS::Edge( s );
4740     }
4741     if ( !edge.IsNull() )
4742     {
4743       double u1 = myHelper.GetNodeU( edge, nn[0], nn[2] );
4744       double u3 = myHelper.GetNodeU( edge, nn[2], nn[0] );
4745       double u = u1 * ( 1 - hR ) + u3 * hR;
4746       TopLoc_Location loc; double f,l;
4747       Handle(Geom_Curve) curve = BRep_Tool::Curve( edge,loc,f,l );
4748       return curve->Value( u ).Transformed( loc );
4749     }
4750   }
4751   // END issue 0020680: Bad cell created by Radial prism in center of torus
4752
4753   vR = getRAndNodes( & u_col1->second, V, nn[0], nn[1] );
4754   vR = getRAndNodes( & u_col2->second, V, nn[2], nn[3] );
4755
4756   if ( !myShapeID2Surf.empty() ) // side is vertically composite
4757   {
4758     // find a FACE on which the 4 nodes lie
4759     TSideFace* me = (TSideFace*) this;
4760     int notFaceID1 = 0, notFaceID2 = 0;
4761     for ( int i = 0; i < 4; ++i )
4762       if ( nn[i]->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE ) // node on FACE
4763       {
4764         me->mySurface = me->myShapeID2Surf[ nn[i]->getshapeId() ];
4765         notFaceID2 = 0;
4766         break;
4767       }
4768       else if ( notFaceID1 == 0 ) // node on EDGE or VERTEX
4769       {
4770         me->mySurface  = me->myShapeID2Surf[ nn[i]->getshapeId() ];
4771         notFaceID1 = nn[i]->getshapeId();
4772       }
4773       else if ( notFaceID1 != nn[i]->getshapeId() ) // node on other EDGE or VERTEX
4774       {
4775         if ( mySurface != me->myShapeID2Surf[ nn[i]->getshapeId() ])
4776           notFaceID2 = nn[i]->getshapeId();
4777       }
4778     if ( notFaceID2 ) // no nodes of FACE and nodes are on different FACEs
4779     {
4780       SMESHDS_Mesh* meshDS = myHelper.GetMeshDS();
4781       TopoDS_Shape face = myHelper.GetCommonAncestor( meshDS->IndexToShape( notFaceID1 ),
4782                                                        meshDS->IndexToShape( notFaceID2 ),
4783                                                        *myHelper.GetMesh(),
4784                                                        TopAbs_FACE );
4785       if ( face.IsNull() )
4786         throw SALOME_Exception("StdMeshers_PrismAsBlock::TSideFace::Value() face.IsNull()");
4787       int faceID = meshDS->ShapeToIndex( face );
4788       me->mySurface = me->myShapeID2Surf[ faceID ];
4789       if ( !mySurface )
4790         throw SALOME_Exception("StdMeshers_PrismAsBlock::TSideFace::Value() !mySurface");
4791     }
4792   }
4793   ((TSideFace*) this)->myHelper.SetSubShape( mySurface->Face() );
4794
4795   gp_XY uv1 = myHelper.GetNodeUV( mySurface->Face(), nn[0], nn[2]);
4796   gp_XY uv2 = myHelper.GetNodeUV( mySurface->Face(), nn[1], nn[3]);
4797   gp_XY uv12 = uv1 * ( 1 - vR ) + uv2 * vR;
4798
4799   gp_XY uv3 = myHelper.GetNodeUV( mySurface->Face(), nn[2], nn[0]);
4800   gp_XY uv4 = myHelper.GetNodeUV( mySurface->Face(), nn[3], nn[1]);
4801   gp_XY uv34 = uv3 * ( 1 - vR ) + uv4 * vR;
4802
4803   gp_XY uv = uv12 * ( 1 - hR ) + uv34 * hR;
4804
4805   gp_Pnt p = mySurface->Value( uv.X(), uv.Y() );
4806   return p;
4807 }
4808
4809
4810 //================================================================================
4811 /*!
4812  * \brief Return boundary edge
4813   * \param edge - edge index
4814   * \retval TopoDS_Edge - found edge
4815  */
4816 //================================================================================
4817
4818 TopoDS_Edge StdMeshers_PrismAsBlock::TSideFace::GetEdge(const int iEdge) const
4819 {
4820   if ( !myComponents.empty() ) {
4821     switch ( iEdge ) {
4822     case V0_EDGE : return myComponents.front()->GetEdge( iEdge );
4823     case V1_EDGE : return myComponents.back() ->GetEdge( iEdge );
4824     default: return TopoDS_Edge();
4825     }
4826   }
4827   TopoDS_Shape edge;
4828   const SMDS_MeshNode* node = 0;
4829   SMESHDS_Mesh * meshDS = myHelper.GetMesh()->GetMeshDS();
4830   TNodeColumn* column;
4831
4832   switch ( iEdge ) {
4833   case TOP_EDGE:
4834   case BOTTOM_EDGE:
4835     column = & (( ++myParamToColumnMap->begin())->second );
4836     node = ( iEdge == TOP_EDGE ) ? column->back() : column->front();
4837     edge = myHelper.GetSubShapeByNode ( node, meshDS );
4838     if ( edge.ShapeType() == TopAbs_VERTEX ) {
4839       column = & ( myParamToColumnMap->begin()->second );
4840       node = ( iEdge == TOP_EDGE ) ? column->back() : column->front();
4841     }
4842     break;
4843   case V0_EDGE:
4844   case V1_EDGE: {
4845     bool back = ( iEdge == V1_EDGE );
4846     if ( !myIsForward ) back = !back;
4847     if ( back )
4848       column = & ( myParamToColumnMap->rbegin()->second );
4849     else
4850       column = & ( myParamToColumnMap->begin()->second );
4851     if ( column->size() > 1 )
4852       edge = myHelper.GetSubShapeByNode( (*column)[ 1 ], meshDS );
4853     if ( edge.IsNull() || edge.ShapeType() == TopAbs_VERTEX )
4854       node = column->front();
4855     break;
4856   }
4857   default:;
4858   }
4859   if ( !edge.IsNull() && edge.ShapeType() == TopAbs_EDGE )
4860     return TopoDS::Edge( edge );
4861
4862   // find edge by 2 vertices
4863   TopoDS_Shape V1 = edge;
4864   TopoDS_Shape V2 = myHelper.GetSubShapeByNode( node, meshDS );
4865   if ( !V2.IsNull() && V2.ShapeType() == TopAbs_VERTEX && !V2.IsSame( V1 ))
4866   {
4867     TopoDS_Shape ancestor = myHelper.GetCommonAncestor( V1, V2, *myHelper.GetMesh(), TopAbs_EDGE);
4868     if ( !ancestor.IsNull() )
4869       return TopoDS::Edge( ancestor );
4870   }
4871   return TopoDS_Edge();
4872 }
4873
4874 //================================================================================
4875 /*!
4876  * \brief Fill block sub-shapes
4877   * \param shapeMap - map to fill in
4878   * \retval int - nb inserted sub-shapes
4879  */
4880 //================================================================================
4881
4882 int StdMeshers_PrismAsBlock::TSideFace::InsertSubShapes(TBlockShapes& shapeMap) const
4883 {
4884   int nbInserted = 0;
4885
4886   // Insert edges
4887   vector< int > edgeIdVec;
4888   SMESH_Block::GetFaceEdgesIDs( myID, edgeIdVec );
4889
4890   for ( int i = BOTTOM_EDGE; i <=V1_EDGE ; ++i ) {
4891     TopoDS_Edge e = GetEdge( i );
4892     if ( !e.IsNull() ) {
4893       nbInserted += SMESH_Block::Insert( e, edgeIdVec[ i ], shapeMap);
4894     }
4895   }
4896
4897   // Insert corner vertices
4898
4899   TParam2ColumnIt col1, col2 ;
4900   vector< int > vertIdVec;
4901
4902   // from V0 column
4903   SMESH_Block::GetEdgeVertexIDs( edgeIdVec[ V0_EDGE ], vertIdVec);
4904   GetColumns(0, col1, col2 );
4905   const SMDS_MeshNode* node0 = col1->second.front();
4906   const SMDS_MeshNode* node1 = col1->second.back();
4907   TopoDS_Shape v0 = myHelper.GetSubShapeByNode( node0, myHelper.GetMeshDS());
4908   TopoDS_Shape v1 = myHelper.GetSubShapeByNode( node1, myHelper.GetMeshDS());
4909   if ( v0.ShapeType() == TopAbs_VERTEX ) {
4910     nbInserted += SMESH_Block::Insert( v0, vertIdVec[ 0 ], shapeMap);
4911   }
4912   if ( v1.ShapeType() == TopAbs_VERTEX ) {
4913     nbInserted += SMESH_Block::Insert( v1, vertIdVec[ 1 ], shapeMap);
4914   }
4915
4916   // from V1 column
4917   SMESH_Block::GetEdgeVertexIDs( edgeIdVec[ V1_EDGE ], vertIdVec);
4918   GetColumns(1, col1, col2 );
4919   node0 = col2->second.front();
4920   node1 = col2->second.back();
4921   v0 = myHelper.GetSubShapeByNode( node0, myHelper.GetMeshDS());
4922   v1 = myHelper.GetSubShapeByNode( node1, myHelper.GetMeshDS());
4923   if ( v0.ShapeType() == TopAbs_VERTEX ) {
4924     nbInserted += SMESH_Block::Insert( v0, vertIdVec[ 0 ], shapeMap);
4925   }
4926   if ( v1.ShapeType() == TopAbs_VERTEX ) {
4927     nbInserted += SMESH_Block::Insert( v1, vertIdVec[ 1 ], shapeMap);
4928   }
4929
4930 //   TopoDS_Vertex V0, V1, Vcom;
4931 //   TopExp::Vertices( myBaseEdge, V0, V1, true );
4932 //   if ( !myIsForward ) std::swap( V0, V1 );
4933
4934 //   // bottom vertex IDs
4935 //   SMESH_Block::GetEdgeVertexIDs( edgeIdVec[ _u0 ], vertIdVec);
4936 //   SMESH_Block::Insert( V0, vertIdVec[ 0 ], shapeMap);
4937 //   SMESH_Block::Insert( V1, vertIdVec[ 1 ], shapeMap);
4938
4939 //   TopoDS_Edge sideEdge = GetEdge( V0_EDGE );
4940 //   if ( sideEdge.IsNull() || !TopExp::CommonVertex( botEdge, sideEdge, Vcom ))
4941 //     return false;
4942
4943 //   // insert one side edge
4944 //   int edgeID;
4945 //   if ( Vcom.IsSame( V0 )) edgeID = edgeIdVec[ _v0 ];
4946 //   else                    edgeID = edgeIdVec[ _v1 ];
4947 //   SMESH_Block::Insert( sideEdge, edgeID, shapeMap);
4948
4949 //   // top vertex of the side edge
4950 //   SMESH_Block::GetEdgeVertexIDs( edgeID, vertIdVec);
4951 //   TopoDS_Vertex Vtop = TopExp::FirstVertex( sideEdge );
4952 //   if ( Vcom.IsSame( Vtop ))
4953 //     Vtop = TopExp::LastVertex( sideEdge );
4954 //   SMESH_Block::Insert( Vtop, vertIdVec[ 1 ], shapeMap);
4955
4956 //   // other side edge
4957 //   sideEdge = GetEdge( V1_EDGE );
4958 //   if ( sideEdge.IsNull() )
4959 //     return false;
4960 //   if ( edgeID = edgeIdVec[ _v1 ]) edgeID = edgeIdVec[ _v0 ];
4961 //   else                            edgeID = edgeIdVec[ _v1 ];
4962 //   SMESH_Block::Insert( sideEdge, edgeID, shapeMap);
4963
4964 //   // top edge
4965 //   TopoDS_Edge topEdge = GetEdge( TOP_EDGE );
4966 //   SMESH_Block::Insert( topEdge, edgeIdVec[ _u1 ], shapeMap);
4967
4968 //   // top vertex of the other side edge
4969 //   if ( !TopExp::CommonVertex( topEdge, sideEdge, Vcom ))
4970 //     return false;
4971 //   SMESH_Block::GetEdgeVertexIDs( edgeID, vertIdVec );
4972 //   SMESH_Block::Insert( Vcom, vertIdVec[ 1 ], shapeMap);
4973
4974   return nbInserted;
4975 }
4976
4977 //================================================================================
4978 /*!
4979  * \brief Dump ids of nodes of sides
4980  */
4981 //================================================================================
4982
4983 void StdMeshers_PrismAsBlock::TSideFace::dumpNodes(int nbNodes) const
4984 {
4985 #ifdef _DEBUG_
4986   cout << endl << "NODES OF FACE "; SMESH_Block::DumpShapeID( myID, cout ) << endl;
4987   THorizontalEdgeAdaptor* hSize0 = (THorizontalEdgeAdaptor*) HorizCurve(0);
4988   cout << "Horiz side 0: "; hSize0->dumpNodes(nbNodes); cout << endl;
4989   THorizontalEdgeAdaptor* hSize1 = (THorizontalEdgeAdaptor*) HorizCurve(1);
4990   cout << "Horiz side 1: "; hSize1->dumpNodes(nbNodes); cout << endl;
4991   TVerticalEdgeAdaptor* vSide0 = (TVerticalEdgeAdaptor*) VertiCurve(0);
4992   cout << "Verti side 0: "; vSide0->dumpNodes(nbNodes); cout << endl;
4993   TVerticalEdgeAdaptor* vSide1 = (TVerticalEdgeAdaptor*) VertiCurve(1);
4994   cout << "Verti side 1: "; vSide1->dumpNodes(nbNodes); cout << endl;
4995   delete hSize0; delete hSize1; delete vSide0; delete vSide1;
4996 #endif
4997 }
4998
4999 //================================================================================
5000 /*!
5001  * \brief Creates TVerticalEdgeAdaptor
5002   * \param columnsMap - node column map
5003   * \param parameter - normalized parameter
5004  */
5005 //================================================================================
5006
5007 StdMeshers_PrismAsBlock::TVerticalEdgeAdaptor::
5008 TVerticalEdgeAdaptor( const TParam2ColumnMap* columnsMap, const double parameter)
5009 {
5010   myNodeColumn = & getColumn( columnsMap, parameter )->second;
5011 }
5012
5013 //================================================================================
5014 /*!
5015  * \brief Return coordinates for the given normalized parameter
5016   * \param U - normalized parameter
5017   * \retval gp_Pnt - coordinates
5018  */
5019 //================================================================================
5020
5021 gp_Pnt StdMeshers_PrismAsBlock::TVerticalEdgeAdaptor::Value(const Standard_Real U) const
5022 {
5023   const SMDS_MeshNode* n1;
5024   const SMDS_MeshNode* n2;
5025   double r = getRAndNodes( myNodeColumn, U, n1, n2 );
5026   return gpXYZ(n1) * ( 1 - r ) + gpXYZ(n2) * r;
5027 }
5028
5029 //================================================================================
5030 /*!
5031  * \brief Dump ids of nodes
5032  */
5033 //================================================================================
5034
5035 void StdMeshers_PrismAsBlock::TVerticalEdgeAdaptor::dumpNodes(int nbNodes) const
5036 {
5037 #ifdef _DEBUG_
5038   for ( int i = 0; i < nbNodes && i < (int)myNodeColumn->size(); ++i )
5039     cout << (*myNodeColumn)[i]->GetID() << " ";
5040   if ( nbNodes < (int) myNodeColumn->size() )
5041     cout << myNodeColumn->back()->GetID();
5042 #endif
5043 }
5044
5045 //================================================================================
5046 /*!
5047  * \brief Return coordinates for the given normalized parameter
5048   * \param U - normalized parameter
5049   * \retval gp_Pnt - coordinates
5050  */
5051 //================================================================================
5052
5053 gp_Pnt StdMeshers_PrismAsBlock::THorizontalEdgeAdaptor::Value(const Standard_Real U) const
5054 {
5055   return mySide->TSideFace::Value( U, myV );
5056 }
5057
5058 //================================================================================
5059 /*!
5060  * \brief Dump ids of <nbNodes> first nodes and the last one
5061  */
5062 //================================================================================
5063
5064 void StdMeshers_PrismAsBlock::THorizontalEdgeAdaptor::dumpNodes(int nbNodes) const
5065 {
5066 #ifdef _DEBUG_
5067   // Not bedugged code. Last node is sometimes incorrect
5068   const TSideFace* side = mySide;
5069   double u = 0;
5070   if ( mySide->IsComplex() )
5071     side = mySide->GetComponent(0,u);
5072
5073   TParam2ColumnIt col, col2;
5074   TParam2ColumnMap* u2cols = side->GetColumns();
5075   side->GetColumns( u , col, col2 );
5076
5077   int j, i = myV ? mySide->ColumnHeight()-1 : 0;
5078
5079   const SMDS_MeshNode* n = 0;
5080   const SMDS_MeshNode* lastN
5081     = side->IsForward() ? u2cols->rbegin()->second[ i ] : u2cols->begin()->second[ i ];
5082   for ( j = 0; j < nbNodes && n != lastN; ++j )
5083   {
5084     n = col->second[ i ];
5085     cout << n->GetID() << " ";
5086     if ( side->IsForward() )
5087       ++col;
5088     else
5089       --col;
5090   }
5091
5092   // last node
5093   u = 1;
5094   if ( mySide->IsComplex() )
5095     side = mySide->GetComponent(1,u);
5096
5097   side->GetColumns( u , col, col2 );
5098   if ( n != col->second[ i ] )
5099     cout << col->second[ i ]->GetID();
5100 #endif
5101 }
5102
5103 //================================================================================
5104 /*!
5105  * \brief Constructor of TPCurveOnHorFaceAdaptor fills its map of
5106  * normalized parameter to node UV on a horizontal face
5107  *  \param [in] sideFace - lateral prism side
5108  *  \param [in] isTop - is \a horFace top or bottom of the prism
5109  *  \param [in] horFace - top or bottom face of the prism
5110  */
5111 //================================================================================
5112
5113 StdMeshers_PrismAsBlock::
5114 TPCurveOnHorFaceAdaptor::TPCurveOnHorFaceAdaptor( const TSideFace*   sideFace,
5115                                                   const bool         isTop,
5116                                                   const TopoDS_Face& horFace)
5117 {
5118   if ( sideFace && !horFace.IsNull() )
5119   {
5120     //cout << "\n\t FACE " << sideFace->FaceID() << endl;
5121     const int Z = isTop ? sideFace->ColumnHeight() - 1 : 0;
5122     map<double, const SMDS_MeshNode* > u2nodes;
5123     sideFace->GetNodesAtZ( Z, u2nodes );
5124     if ( u2nodes.empty() )
5125       return;
5126
5127     SMESH_MesherHelper helper( *sideFace->GetMesh() );
5128     helper.SetSubShape( horFace );
5129
5130     bool okUV;
5131     gp_XY uv;
5132     double f,l;
5133     Handle(Geom2d_Curve) C2d;
5134     int edgeID = -1;
5135     const double tol = 10 * helper.MaxTolerance( horFace );
5136     const SMDS_MeshNode* prevNode = u2nodes.rbegin()->second;
5137
5138     map<double, const SMDS_MeshNode* >::iterator u2n = u2nodes.begin();
5139     for ( ; u2n != u2nodes.end(); ++u2n )
5140     {
5141       const SMDS_MeshNode* n = u2n->second;
5142       okUV = false;
5143       if ( n->GetPosition()->GetTypeOfPosition() == SMDS_TOP_EDGE )
5144       {
5145         if ( n->getshapeId() != edgeID )
5146         {
5147           C2d.Nullify();
5148           edgeID = n->getshapeId();
5149           TopoDS_Shape S = helper.GetSubShapeByNode( n, helper.GetMeshDS() );
5150           if ( !S.IsNull() && S.ShapeType() == TopAbs_EDGE )
5151           {
5152             C2d = BRep_Tool::CurveOnSurface( TopoDS::Edge( S ), horFace, f,l );
5153           }
5154         }
5155         if ( !C2d.IsNull() )
5156         {
5157           double u = SMDS_EdgePositionPtr( n->GetPosition() )->GetUParameter();
5158           if ( f <= u && u <= l )
5159           {
5160             uv = C2d->Value( u ).XY();
5161             okUV = helper.CheckNodeUV( horFace, n, uv, tol );
5162           }
5163         }
5164       }
5165       if ( !okUV )
5166         uv = helper.GetNodeUV( horFace, n, prevNode, &okUV );
5167
5168       myUVmap.insert( myUVmap.end(), make_pair( u2n->first, uv ));
5169       // cout << n->getshapeId() << " N " << n->GetID()
5170       //      << " \t" << uv.X() << ", " << uv.Y() << " \t" << u2n->first << endl;
5171
5172       prevNode = n;
5173     }
5174   }
5175 }
5176
5177 //================================================================================
5178 /*!
5179  * \brief Return UV on pcurve for the given normalized parameter
5180   * \param U - normalized parameter
5181   * \retval gp_Pnt - coordinates
5182  */
5183 //================================================================================
5184
5185 gp_Pnt2d StdMeshers_PrismAsBlock::TPCurveOnHorFaceAdaptor::Value(const Standard_Real U) const
5186 {
5187   map< double, gp_XY >::const_iterator i1 = myUVmap.upper_bound( U );
5188
5189   if ( i1 == myUVmap.end() )
5190     return myUVmap.empty() ? gp_XY(0,0) : myUVmap.rbegin()->second;
5191
5192   if ( i1 == myUVmap.begin() )
5193     return (*i1).second;
5194
5195   map< double, gp_XY >::const_iterator i2 = i1--;
5196
5197   double r = ( U - i1->first ) / ( i2->first - i1->first );
5198   return i1->second * ( 1 - r ) + i2->second * r;
5199 }
5200
5201 //================================================================================
5202 /*!
5203  * \brief Projects internal nodes using transformation found by boundary nodes
5204  */
5205 //================================================================================
5206
5207 bool StdMeshers_Sweeper::projectIntPoints(const vector< gp_XYZ >&    fromBndPoints,
5208                                           const vector< gp_XYZ >&    toBndPoints,
5209                                           const vector< gp_XYZ >&    fromIntPoints,
5210                                           vector< gp_XYZ >&          toIntPoints,
5211                                           const double               r,
5212                                           NSProjUtils::TrsfFinder3D& trsf,
5213                                           vector< gp_XYZ > *         bndError)
5214 {
5215   // find transformation
5216   if ( trsf.IsIdentity() && !trsf.Solve( fromBndPoints, toBndPoints ))
5217     return false;
5218
5219   // compute internal points using the found trsf
5220   for ( size_t iP = 0; iP < fromIntPoints.size(); ++iP )
5221   {
5222     toIntPoints[ iP ] = trsf.Transform( fromIntPoints[ iP ]);
5223   }
5224
5225   // compute boundary error
5226   if ( bndError )
5227   {
5228     bndError->resize( fromBndPoints.size() );
5229     gp_XYZ fromTrsf;
5230     for ( size_t iP = 0; iP < fromBndPoints.size(); ++iP )
5231     {
5232       fromTrsf = trsf.Transform( fromBndPoints[ iP ] );
5233       (*bndError)[ iP ]  = toBndPoints[ iP ] - fromTrsf;
5234     }
5235   }
5236
5237   // apply boundary error
5238   if ( bndError && toIntPoints.size() == myTopBotTriangles.size() )
5239   {
5240     for ( size_t iP = 0; iP < toIntPoints.size(); ++iP )
5241     {
5242       const TopBotTriangles& tbTrias = myTopBotTriangles[ iP ];
5243       for ( int i = 0; i < 3; ++i ) // boundary errors at 3 triangle nodes
5244       {
5245         toIntPoints[ iP ] +=
5246           ( (*bndError)[ tbTrias.myBotTriaNodes[i] ] * tbTrias.myBotBC[i] * ( 1 - r ) +
5247             (*bndError)[ tbTrias.myTopTriaNodes[i] ] * tbTrias.myTopBC[i] * ( r     ));
5248       }
5249     }
5250   }
5251
5252   return true;
5253 }
5254
5255 //================================================================================
5256 /*!
5257  * \brief Create internal nodes of the prism by computing an affine transformation
5258  *        from layer to layer
5259  */
5260 //================================================================================
5261
5262 bool StdMeshers_Sweeper::ComputeNodesByTrsf( const double tol,
5263                                              const bool   allowHighBndError)
5264 {
5265   const size_t zSize = myBndColumns[0]->size();
5266   const size_t zSrc = 0, zTgt = zSize-1;
5267   if ( zSize < 3 ) return true;
5268
5269   vector< vector< gp_XYZ > > intPntsOfLayer( zSize ); // node coordinates to compute
5270   // set coordinates of src and tgt nodes
5271   for ( size_t z = 0; z < intPntsOfLayer.size(); ++z )
5272     intPntsOfLayer[ z ].resize( myIntColumns.size() );
5273   for ( size_t iP = 0; iP < myIntColumns.size(); ++iP )
5274   {
5275     intPntsOfLayer[ zSrc ][ iP ] = intPoint( iP, zSrc );
5276     intPntsOfLayer[ zTgt ][ iP ] = intPoint( iP, zTgt );
5277   }
5278
5279   // for each internal column find boundary nodes whose error to use for correction
5280   prepareTopBotDelaunay();
5281   bool isErrorCorrectable = findDelaunayTriangles();
5282
5283   // compute coordinates of internal nodes by projecting (transforming) src and tgt
5284   // nodes towards the central layer
5285
5286   vector< NSProjUtils::TrsfFinder3D > trsfOfLayer( zSize );
5287   vector< vector< gp_XYZ > >          bndError( zSize );
5288
5289   // boundary points used to compute an affine transformation from a layer to a next one
5290   vector< gp_XYZ > fromSrcBndPnts( myBndColumns.size() ), fromTgtBndPnts( myBndColumns.size() );
5291   vector< gp_XYZ > toSrcBndPnts  ( myBndColumns.size() ), toTgtBndPnts  ( myBndColumns.size() );
5292   for ( size_t iP = 0; iP < myBndColumns.size(); ++iP )
5293   {
5294     fromSrcBndPnts[ iP ] = bndPoint( iP, zSrc );
5295     fromTgtBndPnts[ iP ] = bndPoint( iP, zTgt );
5296   }
5297
5298   size_t zS = zSrc + 1;
5299   size_t zT = zTgt - 1;
5300   for ( ; zS < zT; ++zS, --zT ) // vertical loop on layers
5301   {
5302     for ( size_t iP = 0; iP < myBndColumns.size(); ++iP )
5303     {
5304       toSrcBndPnts[ iP ] = bndPoint( iP, zS );
5305       toTgtBndPnts[ iP ] = bndPoint( iP, zT );
5306     }
5307     if (! projectIntPoints( fromSrcBndPnts, toSrcBndPnts,
5308                             intPntsOfLayer[ zS-1 ], intPntsOfLayer[ zS ],
5309                             zS / ( zSize - 1.),
5310                             trsfOfLayer   [ zS-1 ], & bndError[ zS-1 ]))
5311       return false;
5312     if (! projectIntPoints( fromTgtBndPnts, toTgtBndPnts,
5313                             intPntsOfLayer[ zT+1 ], intPntsOfLayer[ zT ],
5314                             zT / ( zSize - 1.),
5315                             trsfOfLayer   [ zT+1 ], & bndError[ zT+1 ]))
5316       return false;
5317
5318     // if ( zT == zTgt - 1 )
5319     // {
5320     //   for ( size_t iP = 0; iP < myBndColumns.size(); ++iP )
5321     //   {
5322     //     gp_XYZ fromTrsf = trsfOfLayer   [ zT+1].Transform( fromTgtBndPnts[ iP ] );
5323     //     cout << "mesh.AddNode( "
5324     //          << fromTrsf.X() << ", "
5325     //          << fromTrsf.Y() << ", "
5326     //          << fromTrsf.Z() << ") " << endl;
5327     //   }
5328     //   for ( size_t iP = 0; iP < myIntColumns.size(); ++iP )
5329     //     cout << "mesh.AddNode( "
5330     //          << intPntsOfLayer[ zT ][ iP ].X() << ", "
5331     //          << intPntsOfLayer[ zT ][ iP ].Y() << ", "
5332     //          << intPntsOfLayer[ zT ][ iP ].Z() << ") " << endl;
5333     // }
5334
5335     fromTgtBndPnts.swap( toTgtBndPnts );
5336     fromSrcBndPnts.swap( toSrcBndPnts );
5337   }
5338
5339   // Evaluate an error of boundary points
5340
5341   if ( !isErrorCorrectable && !allowHighBndError )
5342   {
5343     for ( size_t iP = 0; iP < myBndColumns.size(); ++iP )
5344     {
5345       double sumError = 0;
5346       for ( size_t z = 1; z < zS; ++z ) // loop on layers
5347         sumError += ( bndError[ z-1     ][ iP ].Modulus() +
5348                       bndError[ zSize-z ][ iP ].Modulus() );
5349
5350       if ( sumError > tol )
5351         return false;
5352     }
5353   }
5354
5355   // Compute two projections of internal points to the central layer
5356   // in order to evaluate an error of internal points
5357
5358   bool centerIntErrorIsSmall;
5359   vector< gp_XYZ > centerSrcIntPnts( myIntColumns.size() );
5360   vector< gp_XYZ > centerTgtIntPnts( myIntColumns.size() );
5361
5362   for ( size_t iP = 0; iP < myBndColumns.size(); ++iP )
5363   {
5364     toSrcBndPnts[ iP ] = bndPoint( iP, zS );
5365     toTgtBndPnts[ iP ] = bndPoint( iP, zT );
5366   }
5367   if (! projectIntPoints( fromSrcBndPnts, toSrcBndPnts,
5368                           intPntsOfLayer[ zS-1 ], centerSrcIntPnts,
5369                           zS / ( zSize - 1.),
5370                           trsfOfLayer   [ zS-1 ], & bndError[ zS-1 ]))
5371     return false;
5372   if (! projectIntPoints( fromTgtBndPnts, toTgtBndPnts,
5373                           intPntsOfLayer[ zT+1 ], centerTgtIntPnts,
5374                           zT / ( zSize - 1.),
5375                           trsfOfLayer   [ zT+1 ], & bndError[ zT+1 ]))
5376     return false;
5377
5378   // evaluate an error of internal points on the central layer
5379   centerIntErrorIsSmall = true;
5380   if ( zS == zT ) // odd zSize
5381   {
5382     for ( size_t iP = 0; ( iP < myIntColumns.size() && centerIntErrorIsSmall ); ++iP )
5383       centerIntErrorIsSmall =
5384         (centerSrcIntPnts[ iP ] - centerTgtIntPnts[ iP ]).SquareModulus() < tol*tol;
5385   }
5386   else // even zSize
5387   {
5388     for ( size_t iP = 0; ( iP < myIntColumns.size() && centerIntErrorIsSmall ); ++iP )
5389       centerIntErrorIsSmall =
5390         (intPntsOfLayer[ zS-1 ][ iP ] - centerTgtIntPnts[ iP ]).SquareModulus() < tol*tol;
5391   }
5392
5393   // compute final points on the central layer
5394   double r = zS / ( zSize - 1.);
5395   if ( zS == zT )
5396   {
5397     for ( size_t iP = 0; iP < myIntColumns.size(); ++iP )
5398     {
5399       intPntsOfLayer[ zS ][ iP ] =
5400         ( 1 - r ) * centerSrcIntPnts[ iP ] + r * centerTgtIntPnts[ iP ];
5401     }
5402   }
5403   else
5404   {
5405     for ( size_t iP = 0; iP < myIntColumns.size(); ++iP )
5406     {
5407       intPntsOfLayer[ zS ][ iP ] =
5408         r * intPntsOfLayer[ zS ][ iP ] + ( 1 - r ) * centerSrcIntPnts[ iP ];
5409       intPntsOfLayer[ zT ][ iP ] =
5410         r * intPntsOfLayer[ zT ][ iP ] + ( 1 - r ) * centerTgtIntPnts[ iP ];
5411     }
5412   }
5413
5414   if ( !centerIntErrorIsSmall )
5415   {
5416     // Compensate the central error; continue adding projection
5417     // by going from central layer to the source and target ones
5418
5419     vector< gp_XYZ >& fromSrcIntPnts = centerSrcIntPnts;
5420     vector< gp_XYZ >& fromTgtIntPnts = centerTgtIntPnts;
5421     vector< gp_XYZ >  toSrcIntPnts( myIntColumns.size() );
5422     vector< gp_XYZ >  toTgtIntPnts( myIntColumns.size() );
5423     vector< gp_XYZ >  srcBndError( myBndColumns.size() );
5424     vector< gp_XYZ >  tgtBndError( myBndColumns.size() );
5425
5426     fromTgtBndPnts.swap( toTgtBndPnts );
5427     fromSrcBndPnts.swap( toSrcBndPnts );
5428
5429     for ( ++zS, --zT; zS < zTgt; ++zS, --zT ) // vertical loop on layers
5430     {
5431       // invert transformation
5432       //if ( !trsfOfLayer[ zS+1 ].Invert() )
5433       trsfOfLayer[ zS+1 ] = NSProjUtils::TrsfFinder3D(); // to recompute
5434       //if ( !trsfOfLayer[ zT-1 ].Invert() )
5435       trsfOfLayer[ zT-1 ] = NSProjUtils::TrsfFinder3D();
5436
5437       // project internal nodes and compute bnd error
5438       for ( size_t iP = 0; iP < myBndColumns.size(); ++iP )
5439       {
5440         toSrcBndPnts[ iP ] = bndPoint( iP, zS );
5441         toTgtBndPnts[ iP ] = bndPoint( iP, zT );
5442       }
5443       projectIntPoints( fromSrcBndPnts, toSrcBndPnts,
5444                         fromSrcIntPnts, toSrcIntPnts,
5445                         zS / ( zSize - 1.),
5446                         trsfOfLayer[ zS+1 ], & srcBndError );
5447       projectIntPoints( fromTgtBndPnts, toTgtBndPnts,
5448                         fromTgtIntPnts, toTgtIntPnts,
5449                         zT / ( zSize - 1.),
5450                         trsfOfLayer[ zT-1 ], & tgtBndError );
5451
5452       // if ( zS == zTgt - 1 )
5453       // {
5454       //   cout << "mesh2 = smesh.Mesh()" << endl;
5455       //   for ( size_t iP = 0; iP < myBndColumns.size(); ++iP )
5456       //   {
5457       //     gp_XYZ fromTrsf = trsfOfLayer   [ zS+1].Transform( fromSrcBndPnts[ iP ] );
5458       //     cout << "mesh2.AddNode( "
5459       //          << fromTrsf.X() << ", "
5460       //          << fromTrsf.Y() << ", "
5461       //          << fromTrsf.Z() << ") " << endl;
5462       //   }
5463       //   for ( size_t iP = 0; iP < myIntColumns.size(); ++iP )
5464       //     cout << "mesh2.AddNode( "
5465       //          << toSrcIntPnts[ iP ].X() << ", "
5466       //          << toSrcIntPnts[ iP ].Y() << ", "
5467       //          << toSrcIntPnts[ iP ].Z() << ") " << endl;
5468       // }
5469
5470       // sum up 2 projections
5471       r = zS / ( zSize - 1.);
5472       vector< gp_XYZ >& zSIntPnts = intPntsOfLayer[ zS ];
5473       vector< gp_XYZ >& zTIntPnts = intPntsOfLayer[ zT ];
5474       for ( size_t iP = 0; iP < myIntColumns.size(); ++iP )
5475       {
5476         zSIntPnts[ iP ] = r * zSIntPnts[ iP ]  +  ( 1 - r ) * toSrcIntPnts[ iP ];
5477         zTIntPnts[ iP ] = r * zTIntPnts[ iP ]  +  ( 1 - r ) * toTgtIntPnts[ iP ];
5478       }
5479
5480       fromSrcBndPnts.swap( toSrcBndPnts );
5481       fromSrcIntPnts.swap( toSrcIntPnts );
5482       fromTgtBndPnts.swap( toTgtBndPnts );
5483       fromTgtIntPnts.swap( toTgtIntPnts );
5484     }
5485   }  // if ( !centerIntErrorIsSmall )
5486
5487
5488   //cout << "centerIntErrorIsSmall = " << centerIntErrorIsSmall<< endl;
5489
5490   // Create nodes
5491   for ( size_t iP = 0; iP < myIntColumns.size(); ++iP )
5492   {
5493     vector< const SMDS_MeshNode* > & nodeCol = *myIntColumns[ iP ];
5494     for ( size_t z = zSrc + 1; z < zTgt; ++z ) // vertical loop on layers
5495     {
5496       const gp_XYZ & xyz = intPntsOfLayer[ z ][ iP ];
5497       if ( !( nodeCol[ z ] = myHelper->AddNode( xyz.X(), xyz.Y(), xyz.Z() )))
5498         return false;
5499     }
5500   }
5501
5502   return true;
5503 }
5504
5505 //================================================================================
5506 /*!
5507  * \brief Check if all nodes of each layers have same logical Z
5508  */
5509 //================================================================================
5510
5511 bool StdMeshers_Sweeper::CheckSameZ()
5512 {
5513   myZColumns.resize( myBndColumns.size() );
5514   fillZColumn( myZColumns[0], *myBndColumns[0] );
5515
5516   bool sameZ = true;
5517   const double tol = 0.1 * 1./ myBndColumns[0]->size();
5518
5519   // check columns based on VERTEXes
5520
5521   vector< int > vertexIndex;
5522   vertexIndex.push_back( 0 );
5523   for ( size_t iC = 1; iC < myBndColumns.size() &&  sameZ; ++iC )
5524   {
5525     if ( myBndColumns[iC]->front()->GetPosition()->GetDim() > 0 )
5526       continue; // not on VERTEX
5527
5528     vertexIndex.push_back( iC );
5529     fillZColumn( myZColumns[iC], *myBndColumns[iC] );
5530
5531     for ( size_t iZ = 0; iZ < myZColumns[0].size() &&  sameZ; ++iZ )
5532       sameZ = ( Abs( myZColumns[0][iZ] - myZColumns[iC][iZ]) < tol );
5533   }
5534
5535   // check columns based on EDGEs, one per EDGE
5536
5537   for ( size_t i = 1; i < vertexIndex.size() &&  sameZ; ++i )
5538   {
5539     if ( vertexIndex[i] - vertexIndex[i-1] < 2 )
5540       continue;
5541
5542     int iC = ( vertexIndex[i] + vertexIndex[i-1] ) / 2;
5543     fillZColumn( myZColumns[iC], *myBndColumns[iC] );
5544
5545     for ( size_t iZ = 0; iZ < myZColumns[0].size() &&  sameZ; ++iZ )
5546       sameZ = ( Abs( myZColumns[0][iZ] - myZColumns[iC][iZ]) < tol );
5547   }
5548
5549   if ( sameZ )
5550   {
5551     myZColumns.resize(1);
5552   }
5553   else
5554   {
5555     for ( size_t iC = 1; iC < myBndColumns.size(); ++iC )
5556       fillZColumn( myZColumns[iC], *myBndColumns[iC] );
5557   }
5558
5559   return sameZ;
5560 }
5561
5562 //================================================================================
5563 /*!
5564  * \brief Create internal nodes of the prism all located on straight lines with
5565  *        the same distribution along the lines.
5566  */
5567 //================================================================================
5568
5569 bool StdMeshers_Sweeper::ComputeNodesOnStraightSameZ()
5570 {
5571   TZColumn& z = myZColumns[0];
5572
5573   for ( size_t i = 0; i < myIntColumns.size(); ++i )
5574   {
5575     TNodeColumn& nodes = *myIntColumns[i];
5576     SMESH_NodeXYZ n0( nodes[0] ), n1( nodes.back() );
5577
5578     for ( size_t iZ = 0; iZ < z.size(); ++iZ )
5579     {
5580       gp_XYZ p = n0 * ( 1 - z[iZ] ) + n1 * z[iZ];
5581       nodes[ iZ+1 ] = myHelper->AddNode( p.X(), p.Y(), p.Z() );
5582     }
5583   }
5584
5585   return true;
5586 }
5587
5588 //================================================================================
5589 /*!
5590  * \brief Create internal nodes of the prism all located on straight lines with
5591  *        different distributions along the lines.
5592  */
5593 //================================================================================
5594
5595 bool StdMeshers_Sweeper::ComputeNodesOnStraight()
5596 {
5597   prepareTopBotDelaunay();
5598
5599   const SMDS_MeshNode     *botNode, *topNode;
5600   const BRepMesh_Triangle *topTria;
5601   double botBC[3], topBC[3]; // barycentric coordinates
5602   int    botTriaNodes[3], topTriaNodes[3];
5603   bool   checkUV = true;
5604
5605   int nbInternalNodes = myIntColumns.size();
5606   myBotDelaunay->InitTraversal( nbInternalNodes );
5607
5608   while (( botNode = myBotDelaunay->NextNode( botBC, botTriaNodes )))
5609   {
5610     TNodeColumn* column = myIntColumns[ myNodeID2ColID( botNode->GetID() )];
5611
5612     // find a Delaunay triangle containing the topNode
5613     topNode = column->back();
5614     gp_XY topUV = myHelper->GetNodeUV( myTopFace, topNode, NULL, &checkUV );
5615     // get a starting triangle basing on that top and bot boundary nodes have same index
5616     topTria = myTopDelaunay->GetTriangleNear( botTriaNodes[0] );
5617     topTria = myTopDelaunay->FindTriangle( topUV, topTria, topBC, topTriaNodes );
5618     if ( !topTria )
5619       return false;
5620
5621     // create nodes along a line
5622     SMESH_NodeXYZ botP( botNode ), topP( topNode );
5623     for ( size_t iZ = 0; iZ < myZColumns[0].size(); ++iZ )
5624     {
5625       // use barycentric coordinates as weight of Z of boundary columns
5626       double botZ = 0, topZ = 0;
5627       for ( int i = 0; i < 3; ++i )
5628       {
5629         botZ += botBC[i] * myZColumns[ botTriaNodes[i] ][ iZ ];
5630         topZ += topBC[i] * myZColumns[ topTriaNodes[i] ][ iZ ];
5631       }
5632       double rZ = double( iZ + 1 ) / ( myZColumns[0].size() + 1 );
5633       double z = botZ * ( 1 - rZ ) + topZ * rZ;
5634       gp_XYZ p = botP * ( 1 - z  ) + topP * z;
5635       (*column)[ iZ+1 ] = myHelper->AddNode( p.X(), p.Y(), p.Z() );
5636     }
5637   }
5638
5639   return myBotDelaunay->NbVisitedNodes() == nbInternalNodes;
5640 }
5641
5642 //================================================================================
5643 /*!
5644  * \brief Compute Z of nodes of a straight column
5645  */
5646 //================================================================================
5647
5648 void StdMeshers_Sweeper::fillZColumn( TZColumn&    zColumn,
5649                                       TNodeColumn& nodes )
5650 {
5651   if ( zColumn.size() == nodes.size() - 2 )
5652     return;
5653
5654   gp_Pnt p0 = SMESH_NodeXYZ( nodes[0] );
5655   gp_Vec line( p0, SMESH_NodeXYZ( nodes.back() ));
5656   double len2 = line.SquareMagnitude();
5657
5658   zColumn.resize( nodes.size() - 2 );
5659   for ( size_t i = 0; i < zColumn.size(); ++i )
5660   {
5661     gp_Vec vec( p0, SMESH_NodeXYZ( nodes[ i+1] ));
5662     zColumn[i] = ( line * vec ) / len2; // param [0,1] on the line
5663   }
5664 }
5665
5666 //================================================================================
5667 /*!
5668  * \brief Initialize *Delaunay members
5669  */
5670 //================================================================================
5671
5672 void StdMeshers_Sweeper::prepareTopBotDelaunay()
5673 {
5674   SMESH_MesherHelper* helper[2] = { myHelper, myHelper };
5675   SMESH_MesherHelper botHelper( *myHelper->GetMesh() );
5676   SMESH_MesherHelper topHelper( *myHelper->GetMesh() );
5677   const SMDS_MeshNode* intBotNode = 0;
5678   const SMDS_MeshNode* intTopNode = 0;
5679   if ( myHelper->HasSeam() || myHelper->HasDegeneratedEdges() ) // use individual helpers
5680   {
5681     botHelper.SetSubShape( myBotFace );
5682     topHelper.SetSubShape( myTopFace );
5683     helper[0] = & botHelper;
5684     helper[1] = & topHelper;
5685     if ( !myIntColumns.empty() )
5686     {
5687       TNodeColumn& nodes = *myIntColumns[ myIntColumns.size()/2 ];
5688       intBotNode = nodes[0];
5689       intTopNode = nodes.back();
5690     }
5691   }
5692
5693   UVPtStructVec botUV( myBndColumns.size() );
5694   UVPtStructVec topUV( myBndColumns.size() );
5695   for ( size_t i = 0; i < myBndColumns.size(); ++i )
5696   {
5697     TNodeColumn& nodes = *myBndColumns[i];
5698     botUV[i].node = nodes[0];
5699     botUV[i].SetUV( helper[0]->GetNodeUV( myBotFace, nodes[0], intBotNode ));
5700     topUV[i].node = nodes.back();
5701     topUV[i].SetUV( helper[1]->GetNodeUV( myTopFace, nodes.back(), intTopNode ));
5702     botUV[i].node->setIsMarked( true );
5703   }
5704   TopoDS_Edge dummyE;
5705   SMESH_Mesh* mesh = myHelper->GetMesh();
5706   TSideVector botWires( 1, StdMeshers_FaceSide::New( botUV, myBotFace, dummyE, mesh ));
5707   TSideVector topWires( 1, StdMeshers_FaceSide::New( topUV, myTopFace, dummyE, mesh ));
5708
5709   // Delaunay mesh on the FACEs.
5710   bool checkUV = false;
5711   myBotDelaunay.reset( new NSProjUtils::Delaunay( botWires, checkUV ));
5712   myTopDelaunay.reset( new NSProjUtils::Delaunay( topWires, checkUV ));
5713
5714   if ( myHelper->GetIsQuadratic() )
5715   {
5716     // mark all medium nodes of faces on botFace to avoid their treating
5717     SMESHDS_SubMesh* smDS = myHelper->GetMeshDS()->MeshElements( myBotFace );
5718     SMDS_ElemIteratorPtr eIt = smDS->GetElements();
5719     while ( eIt->more() )
5720     {
5721       const SMDS_MeshElement* e = eIt->next();
5722       for ( int i = e->NbCornerNodes(), nb = e->NbNodes(); i < nb; ++i )
5723         e->GetNode( i )->setIsMarked( true );
5724     }
5725   }
5726
5727   // map to get a node column by a bottom node
5728   myNodeID2ColID.Clear(/*doReleaseMemory=*/false);
5729   myNodeID2ColID.ReSize( myIntColumns.size() );
5730
5731   // un-mark nodes to treat (internal bottom nodes) to be returned by myBotDelaunay
5732   for ( size_t i = 0; i < myIntColumns.size(); ++i )
5733   {
5734     const SMDS_MeshNode* botNode = myIntColumns[i]->front();
5735     botNode->setIsMarked( false );
5736     myNodeID2ColID.Bind( botNode->GetID(), i );
5737   }
5738 }
5739
5740 //================================================================================
5741 /*!
5742  * \brief For each internal node column, find Delaunay triangles including it
5743  *        and Barycentric Coordinates within the triangles. Fill in myTopBotTriangles
5744  */
5745 //================================================================================
5746
5747 bool StdMeshers_Sweeper::findDelaunayTriangles()
5748 {
5749   const SMDS_MeshNode     *botNode, *topNode;
5750   const BRepMesh_Triangle *topTria;
5751   TopBotTriangles          tbTrias;
5752   bool  checkUV = true;
5753
5754   int nbInternalNodes = myIntColumns.size();
5755   myTopBotTriangles.resize( nbInternalNodes );
5756
5757   myBotDelaunay->InitTraversal( nbInternalNodes );
5758
5759   while (( botNode = myBotDelaunay->NextNode( tbTrias.myBotBC, tbTrias.myBotTriaNodes )))
5760   {
5761     int colID = myNodeID2ColID( botNode->GetID() );
5762     TNodeColumn* column = myIntColumns[ colID ];
5763
5764     // find a Delaunay triangle containing the topNode
5765     topNode = column->back();
5766     gp_XY topUV = myHelper->GetNodeUV( myTopFace, topNode, NULL, &checkUV );
5767     // get a starting triangle basing on that top and bot boundary nodes have same index
5768     topTria = myTopDelaunay->GetTriangleNear( tbTrias.myBotTriaNodes[0] );
5769     topTria = myTopDelaunay->FindTriangle( topUV, topTria,
5770                                            tbTrias.myTopBC, tbTrias.myTopTriaNodes );
5771     if ( !topTria )
5772       tbTrias.SetTopByBottom();
5773
5774     myTopBotTriangles[ colID ] = tbTrias;
5775   }
5776
5777   if ( myBotDelaunay->NbVisitedNodes() < nbInternalNodes )
5778   {
5779     myTopBotTriangles.clear();
5780     return false;
5781   }
5782
5783   myBotDelaunay.reset();
5784   myTopDelaunay.reset();
5785   myNodeID2ColID.Clear();
5786
5787   return true;
5788 }
5789
5790 //================================================================================
5791 /*!
5792  * \brief Initialize fields
5793  */
5794 //================================================================================
5795
5796 StdMeshers_Sweeper::TopBotTriangles::TopBotTriangles()
5797 {
5798   myBotBC[0] = myBotBC[1] = myBotBC[2] = myTopBC[0] = myTopBC[1] = myTopBC[2] = 0.;
5799   myBotTriaNodes[0] = myBotTriaNodes[1] = myBotTriaNodes[2] = 0;
5800   myTopTriaNodes[0] = myTopTriaNodes[1] = myTopTriaNodes[2] = 0;
5801 }
5802
5803 //================================================================================
5804 /*!
5805  * \brief Set top data equal to bottom data
5806  */
5807 //================================================================================
5808
5809 void StdMeshers_Sweeper::TopBotTriangles::SetTopByBottom()
5810 {
5811   for ( int i = 0; i < 3; ++i )
5812   {
5813     myTopBC[i]        = myBotBC[i];
5814     myTopTriaNodes[i] = myBotTriaNodes[0];
5815   }
5816 }