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