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