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