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