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