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