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