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