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