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