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