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