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