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