Salome HOME
Increment version: 7.5.0
[modules/smesh.git] / src / StdMeshers / StdMeshers_Prism_3D.cxx
1 // Copyright (C) 2007-2014  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, or (at your option) any later version.
10 //
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 // Lesser General Public License for more details.
15 //
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
19 //
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 //
22
23 // File      : StdMeshers_Prism_3D.cxx
24 // Module    : SMESH
25 // Created   : Fri Oct 20 11:37:07 2006
26 // Author    : Edward AGAPOV (eap)
27 //
28 #include "StdMeshers_Prism_3D.hxx"
29
30 #include "SMDS_EdgePosition.hxx"
31 #include "SMDS_VolumeOfNodes.hxx"
32 #include "SMDS_VolumeTool.hxx"
33 #include "SMESH_Comment.hxx"
34 #include "SMESH_Gen.hxx"
35 #include "SMESH_HypoFilter.hxx"
36 #include "SMESH_MesherHelper.hxx"
37 #include "StdMeshers_FaceSide.hxx"
38 #include "StdMeshers_ProjectionSource1D.hxx"
39 #include "StdMeshers_ProjectionSource2D.hxx"
40 #include "StdMeshers_ProjectionUtils.hxx"
41 #include "StdMeshers_Projection_1D.hxx"
42 #include "StdMeshers_Projection_1D2D.hxx"
43 #include "StdMeshers_Quadrangle_2D.hxx"
44
45 #include "utilities.h"
46
47 #include <BRepAdaptor_CompCurve.hxx>
48 #include <BRep_Tool.hxx>
49 #include <Bnd_B3d.hxx>
50 #include <Geom2dAdaptor_Curve.hxx>
51 #include <Geom2d_Line.hxx>
52 #include <Geom_Curve.hxx>
53 #include <TopExp.hxx>
54 #include <TopExp_Explorer.hxx>
55 #include <TopTools_ListIteratorOfListOfShape.hxx>
56 #include <TopTools_ListOfShape.hxx>
57 #include <TopTools_MapOfShape.hxx>
58 #include <TopTools_SequenceOfShape.hxx>
59 #include <TopoDS.hxx>
60 #include <gp_Ax2.hxx>
61 #include <gp_Ax3.hxx>
62
63 #include <limits>
64
65 using namespace std;
66
67 #define RETURN_BAD_RESULT(msg) { MESSAGE(")-: Error: " << msg); return false; }
68 #define gpXYZ(n) SMESH_TNodeXYZ(n)
69
70 #ifdef _DEBUG_
71 #define DBGOUT(msg) //cout << msg << endl;
72 #define SHOWYXZ(msg, xyz)                                               \
73   // { gp_Pnt p (xyz);                                                     \
74   //   cout << msg << " ("<< p.X() << "; " <<p.Y() << "; " <<p.Z() << ") " <<endl; }
75 #else
76 #define DBGOUT(msg)
77 #define SHOWYXZ(msg, xyz)
78 #endif
79
80 namespace NSProjUtils = StdMeshers_ProjectionUtils;
81
82 typedef SMESH_Comment TCom;
83
84 enum { ID_BOT_FACE = SMESH_Block::ID_Fxy0,
85        ID_TOP_FACE = SMESH_Block::ID_Fxy1,
86        BOTTOM_EDGE = 0, TOP_EDGE, V0_EDGE, V1_EDGE, // edge IDs in face
87        NB_WALL_FACES = 4 }; //
88
89 namespace {
90
91   //=======================================================================
92   /*!
93    * \brief Quadrangle algorithm
94    */
95   struct TQuadrangleAlgo : public StdMeshers_Quadrangle_2D
96   {
97     TQuadrangleAlgo(int studyId, SMESH_Gen* gen)
98       : StdMeshers_Quadrangle_2D( gen->GetANewId(), studyId, gen)
99     {
100     }
101     static StdMeshers_Quadrangle_2D* instance( SMESH_Algo*         fatherAlgo,
102                                                SMESH_MesherHelper* helper=0)
103     {
104       static TQuadrangleAlgo* algo = new TQuadrangleAlgo( fatherAlgo->GetStudyId(),
105                                                           fatherAlgo->GetGen() );
106       if ( helper &&
107            algo->myProxyMesh &&
108            algo->myProxyMesh->GetMesh() != helper->GetMesh() )
109         algo->myProxyMesh.reset( new SMESH_ProxyMesh( *helper->GetMesh() ));
110
111       algo->myQuadList.clear();
112
113       if ( helper )
114         algo->_quadraticMesh = helper->GetIsQuadratic();
115
116       return algo;
117     }
118   };
119   //=======================================================================
120   /*!
121    * \brief Algorithm projecting 1D mesh
122    */
123   struct TProjction1dAlgo : public StdMeshers_Projection_1D
124   {
125     StdMeshers_ProjectionSource1D myHyp;
126
127     TProjction1dAlgo(int studyId, SMESH_Gen* gen)
128       : StdMeshers_Projection_1D( gen->GetANewId(), studyId, gen),
129         myHyp( gen->GetANewId(), studyId, gen)
130     {
131       StdMeshers_Projection_1D::_sourceHypo = & myHyp;
132     }
133     static TProjction1dAlgo* instance( SMESH_Algo* fatherAlgo )
134     {
135       static TProjction1dAlgo* algo = new TProjction1dAlgo( fatherAlgo->GetStudyId(),
136                                                             fatherAlgo->GetGen() );
137       return algo;
138     }
139   };
140   //=======================================================================
141   /*!
142    * \brief Algorithm projecting 2D mesh
143    */
144   struct TProjction2dAlgo : public StdMeshers_Projection_1D2D
145   {
146     StdMeshers_ProjectionSource2D myHyp;
147
148     TProjction2dAlgo(int studyId, SMESH_Gen* gen)
149       : StdMeshers_Projection_1D2D( gen->GetANewId(), studyId, gen),
150         myHyp( gen->GetANewId(), studyId, gen)
151     {
152       StdMeshers_Projection_2D::_sourceHypo = & myHyp;
153     }
154     static TProjction2dAlgo* instance( SMESH_Algo* fatherAlgo )
155     {
156       static TProjction2dAlgo* algo = new TProjction2dAlgo( fatherAlgo->GetStudyId(),
157                                                             fatherAlgo->GetGen() );
158       return algo;
159     }
160     const NSProjUtils::TNodeNodeMap& GetNodesMap()
161     {
162       return _src2tgtNodes;
163     }
164   };
165   //=======================================================================
166   /*!
167    * \brief Returns already computed EDGEs
168    */
169   void getPrecomputedEdges( SMESH_MesherHelper&    theHelper,
170                             const TopoDS_Shape&    theShape,
171                             vector< TopoDS_Edge >& theEdges)
172   {
173     theEdges.clear();
174
175     SMESHDS_Mesh* meshDS = theHelper.GetMeshDS();
176     SMESHDS_SubMesh* sm;
177
178     TopTools_IndexedMapOfShape edges;
179     TopExp::MapShapes( theShape, TopAbs_EDGE, edges );
180     for ( int iE = 1; iE <= edges.Extent(); ++iE )
181     {
182       const TopoDS_Shape edge = edges( iE );
183       if (( ! ( sm = meshDS->MeshElements( edge ))) ||
184           ( sm->NbElements() == 0 ))
185         continue;
186
187       // there must not be FACEs meshed with triangles and sharing a computed EDGE
188       // as the precomputed EDGEs are used for propagation other to 'vertical' EDGEs
189       bool faceFound = false;
190       PShapeIteratorPtr faceIt =
191         theHelper.GetAncestors( edge, *theHelper.GetMesh(), TopAbs_FACE );
192       while ( const TopoDS_Shape* face = faceIt->next() )
193
194         if (( sm = meshDS->MeshElements( *face )) &&
195             ( sm->NbElements() > 0 ) &&
196             ( !theHelper.IsSameElemGeometry( sm, SMDSGeom_QUADRANGLE ) ))
197         {
198           faceFound = true;
199           break;
200         }
201       if ( !faceFound )
202         theEdges.push_back( TopoDS::Edge( edge ));
203     }
204   }
205
206   //================================================================================
207   /*!
208    * \brief Make \a botE be the BOTTOM_SIDE of \a quad.
209    *        Return false if the BOTTOM_SIDE is composite
210    */
211   //================================================================================
212
213   bool setBottomEdge( const TopoDS_Edge&   botE,
214                       FaceQuadStruct::Ptr& quad,
215                       const TopoDS_Shape&  face)
216   {
217     quad->side[ QUAD_TOP_SIDE  ].grid->Reverse();
218     quad->side[ QUAD_LEFT_SIDE ].grid->Reverse();
219     int edgeIndex = 0;
220     bool isComposite = false;
221     for ( size_t i = 0; i < quad->side.size(); ++i )
222     {
223       StdMeshers_FaceSidePtr quadSide = quad->side[i];
224       for ( int iE = 0; iE < quadSide->NbEdges(); ++iE )
225         if ( botE.IsSame( quadSide->Edge( iE )))
226         {
227           if ( quadSide->NbEdges() > 1 )
228             isComposite = true; //return false;
229           edgeIndex = i;
230           i = quad->side.size(); // to quit from the outer loop
231           break;
232         }
233     }
234     if ( edgeIndex != QUAD_BOTTOM_SIDE )
235       quad->shift( quad->side.size() - edgeIndex, /*keepUnitOri=*/false );
236
237     quad->face = TopoDS::Face( face );
238
239     return !isComposite;
240   }
241
242   //================================================================================
243   /*!
244    * \brief Return iterator pointing to node column for the given parameter
245    * \param columnsMap - node column map
246    * \param parameter - parameter
247    * \retval TParam2ColumnMap::iterator - result
248    *
249    * it returns closest left column
250    */
251   //================================================================================
252
253   TParam2ColumnIt getColumn( const TParam2ColumnMap* columnsMap,
254                              const double            parameter )
255   {
256     TParam2ColumnIt u_col = columnsMap->upper_bound( parameter );
257     if ( u_col != columnsMap->begin() )
258       --u_col;
259     return u_col; // return left column
260   }
261
262   //================================================================================
263   /*!
264    * \brief Return nodes around given parameter and a ratio
265    * \param column - node column
266    * \param param - parameter
267    * \param node1 - lower node
268    * \param node2 - upper node
269    * \retval double - ratio
270    */
271   //================================================================================
272
273   double getRAndNodes( const TNodeColumn*     column,
274                        const double           param,
275                        const SMDS_MeshNode* & node1,
276                        const SMDS_MeshNode* & node2)
277   {
278     if ( param >= 1.0 || column->size() == 1) {
279       node1 = node2 = column->back();
280       return 0;
281     }
282
283     int i = int( param * ( column->size() - 1 ));
284     double u0 = double( i )/ double( column->size() - 1 );
285     double r = ( param - u0 ) * ( column->size() - 1 );
286
287     node1 = (*column)[ i ];
288     node2 = (*column)[ i + 1];
289     return r;
290   }
291
292   //================================================================================
293   /*!
294    * \brief Compute boundary parameters of face parts
295     * \param nbParts - nb of parts to split columns into
296     * \param columnsMap - node columns of the face to split
297     * \param params - computed parameters
298    */
299   //================================================================================
300
301   void splitParams( const int               nbParts,
302                     const TParam2ColumnMap* columnsMap,
303                     vector< double > &      params)
304   {
305     params.clear();
306     params.reserve( nbParts + 1 );
307     TParam2ColumnIt last_par_col = --columnsMap->end();
308     double par = columnsMap->begin()->first; // 0.
309     double parLast = last_par_col->first;
310     params.push_back( par );
311     for ( int i = 0; i < nbParts - 1; ++ i )
312     {
313       double partSize = ( parLast - par ) / double ( nbParts - i );
314       TParam2ColumnIt par_col = getColumn( columnsMap, par + partSize );
315       if ( par_col->first == par ) {
316         ++par_col;
317         if ( par_col == last_par_col ) {
318           while ( i < nbParts - 1 )
319             params.push_back( par + partSize * i++ );
320           break;
321         }
322       }
323       par = par_col->first;
324       params.push_back( par );
325     }
326     params.push_back( parLast ); // 1.
327   }
328
329   //================================================================================
330   /*!
331    * \brief Return coordinate system for z-th layer of nodes
332    */
333   //================================================================================
334
335   gp_Ax2 getLayerCoordSys(const int                           z,
336                           const vector< const TNodeColumn* >& columns,
337                           int&                                xColumn)
338   {
339     // gravity center of a layer
340     gp_XYZ O(0,0,0);
341     int vertexCol = -1;
342     for ( int i = 0; i < columns.size(); ++i )
343     {
344       O += gpXYZ( (*columns[ i ])[ z ]);
345       if ( vertexCol < 0 &&
346            columns[ i ]->front()->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX )
347         vertexCol = i;
348     }
349     O /= columns.size();
350
351     // Z axis
352     gp_Vec Z(0,0,0);
353     int iPrev = columns.size()-1;
354     for ( int i = 0; i < columns.size(); ++i )
355     {
356       gp_Vec v1( O, gpXYZ( (*columns[ iPrev ])[ z ]));
357       gp_Vec v2( O, gpXYZ( (*columns[ i ]    )[ z ]));
358       Z += v1 ^ v2;
359       iPrev = i;
360     }
361
362     if ( vertexCol >= 0 )
363     {
364       O = gpXYZ( (*columns[ vertexCol ])[ z ]);
365     }
366     if ( xColumn < 0 || xColumn >= columns.size() )
367     {
368       // select a column for X dir
369       double maxDist = 0;
370       for ( int i = 0; i < columns.size(); ++i )
371       {
372         double dist = ( O - gpXYZ((*columns[ i ])[ z ])).SquareModulus();
373         if ( dist > maxDist )
374         {
375           xColumn = i;
376           maxDist = dist;
377         }
378       }
379     }
380
381     // X axis
382     gp_Vec X( O, gpXYZ( (*columns[ xColumn ])[ z ]));
383
384     return gp_Ax2( O, Z, X);
385   }
386
387   //================================================================================
388   /*!
389    * \brief Removes submeshes that are or can be meshed with regular grid from given list
390    *  \retval int - nb of removed submeshes
391    */
392   //================================================================================
393
394   int removeQuasiQuads(list< SMESH_subMesh* >&   notQuadSubMesh,
395                        SMESH_MesherHelper*       helper,
396                        StdMeshers_Quadrangle_2D* quadAlgo)
397   {
398     int nbRemoved = 0;
399     //SMESHDS_Mesh* mesh = notQuadSubMesh.front()->GetFather()->GetMeshDS();
400     list< SMESH_subMesh* >::iterator smIt = notQuadSubMesh.begin();
401     while ( smIt != notQuadSubMesh.end() )
402     {
403       SMESH_subMesh* faceSm = *smIt;
404       SMESHDS_SubMesh* faceSmDS = faceSm->GetSubMeshDS();
405       int nbQuads = faceSmDS ? faceSmDS->NbElements() : 0;
406       bool toRemove;
407       if ( nbQuads > 0 )
408         toRemove = helper->IsStructured( faceSm );
409       else
410         toRemove = quadAlgo->CheckNbEdges( *helper->GetMesh(),
411                                            faceSm->GetSubShape() );
412       nbRemoved += toRemove;
413       if ( toRemove )
414         smIt = notQuadSubMesh.erase( smIt );
415       else
416         ++smIt;
417     }
418
419     return nbRemoved;
420   }
421
422   //================================================================================
423   /*!
424    * \brief Return and angle between two EDGEs
425    *  \return double - the angle normalized so that
426    * >~ 0  -> 2.0
427    *  PI/2 -> 1.0
428    *  PI   -> 0.0
429    * -PI/2 -> -1.0
430    * <~ 0  -> -2.0
431    */
432   //================================================================================
433
434   // double normAngle(const TopoDS_Edge & E1, const TopoDS_Edge & E2, const TopoDS_Face & F)
435   // {
436   //   return SMESH_MesherHelper::GetAngle( E1, E2, F ) / ( 0.5 * M_PI );
437   // }
438
439   //================================================================================
440   /*!
441    * Consider continuous straight EDGES as one side - mark them to unite
442    */
443   //================================================================================
444
445   int countNbSides( const Prism_3D::TPrismTopo & thePrism,
446                     vector<int> &                nbUnitePerEdge,
447                     vector< double > &           edgeLength)
448   {
449     int nbEdges = thePrism.myNbEdgesInWires.front();  // nb outer edges
450     int nbSides = nbEdges;
451
452     
453     list< TopoDS_Edge >::const_iterator edgeIt = thePrism.myBottomEdges.begin();
454     std::advance( edgeIt, nbEdges-1 );
455     TopoDS_Edge   prevE = *edgeIt;
456     // bool isPrevStraight = SMESH_Algo::IsStraight( prevE );
457     int           iPrev = nbEdges - 1;
458
459     int iUnite = -1; // the first of united EDGEs
460
461     // analyse angles between EDGEs
462     int nbCorners = 0;
463     vector< bool > isCorner( nbEdges );
464     edgeIt = thePrism.myBottomEdges.begin();
465     for ( int iE = 0; iE < nbEdges; ++iE, ++edgeIt )
466     {
467       const TopoDS_Edge&  curE = *edgeIt;
468       edgeLength[ iE ] = SMESH_Algo::EdgeLength( curE );
469
470       // double normAngle = normAngle( prevE, curE, thePrism.myBottom );
471       // isCorner[ iE ] = false;
472       // if ( normAngle < 2.0 )
473       // {
474       //   if ( normAngle < 0.001 ) // straight or obtuse angle
475       //   {
476       //     // unite EDGEs in order not to put a corner of the unit quadrangle at this VERTEX
477       //     if ( iUnite < 0 )
478       //       iUnite = iPrev;
479       //     nbUnitePerEdge[ iUnite ]++;
480       //     nbUnitePerEdge[ iE ] = -1;
481       //     --nbSides;
482       //   }
483       //   else
484       //   {
485       //     isCorner[ iE ] = true;
486       //     nbCorners++;
487       //     iUnite = -1;
488       //   }
489       // }
490       // prevE = curE;
491     }
492
493     if ( nbCorners > 4 )
494     {
495       // define which of corners to put on a side of the unit quadrangle
496     }
497     // edgeIt = thePrism.myBottomEdges.begin();
498     // for ( int iE = 0; iE < nbEdges; ++iE, ++edgeIt )
499     // {
500     //   const TopoDS_Edge&  curE = *edgeIt;
501     //   edgeLength[ iE ] = SMESH_Algo::EdgeLength( curE );
502
503     //   const bool isCurStraight = SMESH_Algo::IsStraight( curE );
504     //   if ( isPrevStraight && isCurStraight && SMESH_Algo::IsContinuous( prevE, curE ))
505     //   {
506     //     if ( iUnite < 0 )
507     //       iUnite = iPrev;
508     //     nbUnitePerEdge[ iUnite ]++;
509     //     nbUnitePerEdge[ iE ] = -1;
510     //     --nbSides;
511     //   }
512     //   else
513     //   {
514     //     iUnite = -1;
515     //   }
516     //   prevE          = curE;
517     //   isPrevStraight = isCurStraight;
518     //   iPrev = iE;
519     // }
520     
521     return nbSides;
522   }
523
524   void pointsToPython(const std::vector<gp_XYZ>& p)
525   {
526 #ifdef _DEBUG_
527     for ( int i = SMESH_Block::ID_V000; i < p.size(); ++i )
528     {
529       cout << "mesh.AddNode( " << p[i].X() << ", "<< p[i].Y() << ", "<< p[i].Z() << ") # " << i <<" " ;
530       SMESH_Block::DumpShapeID( i, cout ) << endl;
531     }
532 #endif
533   }
534 } // namespace
535
536 //=======================================================================
537 //function : StdMeshers_Prism_3D
538 //purpose  : 
539 //=======================================================================
540
541 StdMeshers_Prism_3D::StdMeshers_Prism_3D(int hypId, int studyId, SMESH_Gen* gen)
542   :SMESH_3D_Algo(hypId, studyId, gen)
543 {
544   _name                    = "Prism_3D";
545   _shapeType               = (1 << TopAbs_SOLID); // 1 bit per shape type
546   _onlyUnaryInput          = false; // mesh all SOLIDs at once
547   _requireDiscreteBoundary = false; // mesh FACEs and EDGEs by myself
548   _supportSubmeshes        = true;  // "source" FACE must be meshed by other algo
549   _neededLowerHyps[ 1 ]    = true;  // suppress warning on hiding a global 1D algo
550   _neededLowerHyps[ 2 ]    = true;  // suppress warning on hiding a global 2D algo
551
552   //myProjectTriangles       = false;
553   mySetErrorToSM           = true;  // to pass an error to a sub-mesh of a current solid or not
554 }
555
556 //================================================================================
557 /*!
558  * \brief Destructor
559  */
560 //================================================================================
561
562 StdMeshers_Prism_3D::~StdMeshers_Prism_3D()
563 {}
564
565 //=======================================================================
566 //function : CheckHypothesis
567 //purpose  : 
568 //=======================================================================
569
570 bool StdMeshers_Prism_3D::CheckHypothesis(SMESH_Mesh&                          aMesh,
571                                           const TopoDS_Shape&                  aShape,
572                                           SMESH_Hypothesis::Hypothesis_Status& aStatus)
573 {
574   // Check shape geometry
575 /*  PAL16229
576   aStatus = SMESH_Hypothesis::HYP_BAD_GEOMETRY;
577
578   // find not quadrangle faces
579   list< TopoDS_Shape > notQuadFaces;
580   int nbEdge, nbWire, nbFace = 0;
581   TopExp_Explorer exp( aShape, TopAbs_FACE );
582   for ( ; exp.More(); exp.Next() ) {
583     ++nbFace;
584     const TopoDS_Shape& face = exp.Current();
585     nbEdge = NSProjUtils::Count( face, TopAbs_EDGE, 0 );
586     nbWire = NSProjUtils::Count( face, TopAbs_WIRE, 0 );
587     if (  nbEdge!= 4 || nbWire!= 1 ) {
588       if ( !notQuadFaces.empty() ) {
589         if ( NSProjUtils::Count( notQuadFaces.back(), TopAbs_EDGE, 0 ) != nbEdge ||
590              NSProjUtils::Count( notQuadFaces.back(), TopAbs_WIRE, 0 ) != nbWire )
591           RETURN_BAD_RESULT("Different not quad faces");
592       }
593       notQuadFaces.push_back( face );
594     }
595   }
596   if ( !notQuadFaces.empty() )
597   {
598     if ( notQuadFaces.size() != 2 )
599       RETURN_BAD_RESULT("Bad nb not quad faces: " << notQuadFaces.size());
600
601     // check total nb faces
602     nbEdge = NSProjUtils::Count( notQuadFaces.back(), TopAbs_EDGE, 0 );
603     if ( nbFace != nbEdge + 2 )
604       RETURN_BAD_RESULT("Bad nb of faces: " << nbFace << " but must be " << nbEdge + 2);
605   }
606 */
607   // no hypothesis
608   aStatus = SMESH_Hypothesis::HYP_OK;
609   return true;
610 }
611
612 //=======================================================================
613 //function : Compute
614 //purpose  : Compute mesh on a COMPOUND of SOLIDs
615 //=======================================================================
616
617 bool StdMeshers_Prism_3D::Compute(SMESH_Mesh& theMesh, const TopoDS_Shape& theShape)
618 {
619   SMESH_MesherHelper helper( theMesh );
620   myHelper = &helper;
621
622   int nbSolids = helper.Count( theShape, TopAbs_SOLID, /*skipSame=*/false );
623   if ( nbSolids < 1 )
624     return true;
625
626   TopTools_IndexedDataMapOfShapeListOfShape faceToSolids;
627   TopExp::MapShapesAndAncestors( theShape, TopAbs_FACE, TopAbs_SOLID, faceToSolids );
628
629   // look for meshed FACEs ("source" FACEs) that must be prism bottoms
630   list< TopoDS_Face > meshedFaces, notQuadMeshedFaces, notQuadFaces;
631   const bool meshHasQuads = ( theMesh.NbQuadrangles() > 0 );
632   //StdMeshers_Quadrangle_2D* quadAlgo = TQuadrangleAlgo::instance( this );
633   for ( int iF = 1; iF <= faceToSolids.Extent(); ++iF )
634   {
635     const TopoDS_Face& face = TopoDS::Face( faceToSolids.FindKey( iF ));
636     SMESH_subMesh*   faceSM = theMesh.GetSubMesh( face );
637     if ( !faceSM->IsEmpty() )
638     {
639       if ( !meshHasQuads ||
640            !helper.IsSameElemGeometry( faceSM->GetSubMeshDS(), SMDSGeom_QUADRANGLE ) ||
641            !helper.IsStructured( faceSM )
642            )
643         notQuadMeshedFaces.push_front( face );
644       else if ( myHelper->Count( face, TopAbs_EDGE, /*ignoreSame=*/false ) != 4 )
645         meshedFaces.push_front( face );
646       else
647         meshedFaces.push_back( face );
648     }
649     // not add not quadrilateral FACE as we can't compute it
650     // else if ( !quadAlgo->CheckNbEdges( theMesh, face ))
651     // // not add not quadrilateral FACE as it can be a prism side
652     // // else if ( myHelper->Count( face, TopAbs_EDGE, /*ignoreSame=*/false ) != 4 )
653     // {
654     //   notQuadFaces.push_back( face );
655     // }
656   }
657   // notQuadFaces are of medium priority, put them before ordinary meshed faces
658   meshedFaces.splice( meshedFaces.begin(), notQuadFaces );
659   // notQuadMeshedFaces are of highest priority, put them before notQuadFaces
660   meshedFaces.splice( meshedFaces.begin(), notQuadMeshedFaces );
661
662   Prism_3D::TPrismTopo prism;
663   myPropagChains = 0;
664
665   if ( nbSolids == 1 )
666   {
667     if ( !meshedFaces.empty() )
668       prism.myBottom = meshedFaces.front();
669     return ( initPrism( prism, TopExp_Explorer( theShape, TopAbs_SOLID ).Current() ) &&
670              compute( prism ));
671   }
672
673   // find propagation chains from already computed EDGEs
674   vector< TopoDS_Edge > computedEdges;
675   getPrecomputedEdges( helper, theShape, computedEdges );
676   myPropagChains = new TopTools_IndexedMapOfShape[ computedEdges.size() + 1 ];
677   SMESHUtils::ArrayDeleter< TopTools_IndexedMapOfShape > pcDel( myPropagChains );
678   for ( size_t i = 0, nb = 0; i < computedEdges.size(); ++i )
679   {
680     StdMeshers_ProjectionUtils::GetPropagationEdge( &theMesh, TopoDS_Edge(),
681                                                     computedEdges[i], myPropagChains + nb );
682     if ( myPropagChains[ nb ].Extent() < 2 ) // an empty map is a termination sign
683       myPropagChains[ nb ].Clear();
684     else
685       nb++;
686   }
687
688   TopTools_MapOfShape meshedSolids;
689   list< Prism_3D::TPrismTopo > meshedPrism;
690   TopTools_ListIteratorOfListOfShape solidIt;
691
692   while ( meshedSolids.Extent() < nbSolids )
693   {
694     if ( _computeCanceled )
695       return toSM( error( SMESH_ComputeError::New(COMPERR_CANCELED)));
696
697     // compute prisms having avident computed source FACE
698     while ( !meshedFaces.empty() )
699     {
700       TopoDS_Face face = meshedFaces.front();
701       meshedFaces.pop_front();
702       TopTools_ListOfShape& solidList = faceToSolids.ChangeFromKey( face );
703       while ( !solidList.IsEmpty() )
704       {
705         TopoDS_Shape solid = solidList.First();
706         solidList.RemoveFirst();
707         if ( meshedSolids.Add( solid ))
708         {
709           prism.Clear();
710           prism.myBottom = face;
711           if ( !initPrism( prism, solid ) ||
712                !compute( prism ))
713             return false;
714
715           SMESHDS_SubMesh* smDS = theMesh.GetMeshDS()->MeshElements( prism.myTop );
716           if ( !myHelper->IsSameElemGeometry( smDS, SMDSGeom_QUADRANGLE ))
717           {
718             meshedFaces.push_front( prism.myTop );
719           }
720           meshedPrism.push_back( prism );
721         }
722       }
723     }
724     if ( meshedSolids.Extent() == nbSolids )
725       break;
726
727     // below in the loop we try to find source FACEs somehow
728
729     // project mesh from source FACEs of computed prisms to
730     // prisms sharing wall FACEs
731     list< Prism_3D::TPrismTopo >::iterator prismIt = meshedPrism.begin();
732     for ( ; prismIt != meshedPrism.end(); ++prismIt )
733     {
734       for ( size_t iW = 0; iW < prismIt->myWallQuads.size(); ++iW )
735       {
736         Prism_3D::TQuadList::iterator wQuad = prismIt->myWallQuads[iW].begin();
737         for ( ; wQuad != prismIt->myWallQuads[iW].end(); ++ wQuad )
738         {
739           const TopoDS_Face& wFace = (*wQuad)->face;
740           TopTools_ListOfShape& solidList = faceToSolids.ChangeFromKey( wFace );
741           solidIt.Initialize( solidList );
742           while ( solidIt.More() )
743           {
744             const TopoDS_Shape& solid = solidIt.Value();
745             if ( meshedSolids.Contains( solid )) {
746               solidList.Remove( solidIt );
747               continue; // already computed prism
748             }
749             // find a source FACE of the SOLID: it's a FACE sharing a bottom EDGE with wFace
750             const TopoDS_Edge& wEdge = (*wQuad)->side[ QUAD_TOP_SIDE ].grid->Edge(0);
751             PShapeIteratorPtr faceIt = myHelper->GetAncestors( wEdge, *myHelper->GetMesh(),
752                                                                TopAbs_FACE);
753             while ( const TopoDS_Shape* f = faceIt->next() )
754             {
755               const TopoDS_Face& candidateF = TopoDS::Face( *f );
756               prism.Clear();
757               prism.myBottom  = candidateF;
758               mySetErrorToSM = false;
759               if ( !myHelper->IsSubShape( candidateF, prismIt->myShape3D ) &&
760                    myHelper->IsSubShape( candidateF, solid ) &&
761                    !myHelper->GetMesh()->GetSubMesh( candidateF )->IsMeshComputed() &&
762                    initPrism( prism, solid ) &&
763                    project2dMesh( prismIt->myBottom, candidateF))
764               {
765                 mySetErrorToSM = true;
766                 if ( !compute( prism ))
767                   return false;
768                 SMESHDS_SubMesh* smDS = theMesh.GetMeshDS()->MeshElements( prism.myTop );
769                 if ( !myHelper->IsSameElemGeometry( smDS, SMDSGeom_QUADRANGLE ))
770                 {
771                   meshedFaces.push_front( prism.myTop );
772                   meshedFaces.push_front( prism.myBottom );
773                 }
774                 meshedPrism.push_back( prism );
775                 meshedSolids.Add( solid );
776               }
777               InitComputeError();
778             }
779             mySetErrorToSM = true;
780             InitComputeError();
781             if ( meshedSolids.Contains( solid ))
782               solidList.Remove( solidIt );
783             else
784               solidIt.Next();
785           }
786         }
787       }
788       if ( !meshedFaces.empty() )
789         break; // to compute prisms with avident sources
790     }
791
792     // find FACEs with local 1D hyps, which has to be computed by now,
793     // or at least any computed FACEs
794     for ( int iF = 1; ( meshedFaces.empty() && iF < faceToSolids.Extent() ); ++iF )
795     {
796       const TopoDS_Face&               face = TopoDS::Face( faceToSolids.FindKey( iF ));
797       const TopTools_ListOfShape& solidList = faceToSolids.FindFromKey( face );
798       if ( solidList.IsEmpty() ) continue;
799       SMESH_subMesh*                 faceSM = theMesh.GetSubMesh( face );
800       if ( !faceSM->IsEmpty() )
801       {
802         meshedFaces.push_back( face ); // lower priority
803       }
804       else
805       {
806         bool allSubMeComputed = true;
807         SMESH_subMeshIteratorPtr smIt = faceSM->getDependsOnIterator(false,true);
808         while ( smIt->more() && allSubMeComputed )
809           allSubMeComputed = smIt->next()->IsMeshComputed();
810         if ( allSubMeComputed )
811         {
812           faceSM->ComputeStateEngine( SMESH_subMesh::COMPUTE );
813           if ( !faceSM->IsEmpty() )
814             meshedFaces.push_front( face ); // higher priority
815           else
816             faceSM->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
817         }
818       }
819     }
820
821
822     // TODO. there are other ways to find out the source FACE:
823     // propagation, topological similarity, ect.
824
825     // simply try to mesh all not meshed SOLIDs
826     if ( meshedFaces.empty() )
827     {
828       for ( TopExp_Explorer solid( theShape, TopAbs_SOLID ); solid.More(); solid.Next() )
829       {
830         mySetErrorToSM = false;
831         prism.Clear();
832         if ( !meshedSolids.Contains( solid.Current() ) &&
833              initPrism( prism, solid.Current() ))
834         {
835           mySetErrorToSM = true;
836           if ( !compute( prism ))
837             return false;
838           meshedFaces.push_front( prism.myTop );
839           meshedFaces.push_front( prism.myBottom );
840           meshedPrism.push_back( prism );
841           meshedSolids.Add( solid.Current() );
842         }
843         mySetErrorToSM = true;
844       }
845     }
846
847     if ( meshedFaces.empty() ) // set same error to 10 not-computed solids
848     {
849       SMESH_ComputeErrorPtr err = SMESH_ComputeError::New
850         ( COMPERR_BAD_INPUT_MESH, "No meshed source face found", this );
851
852       const int maxNbErrors = 10; // limit nb errors not to overload the Compute dialog
853       TopExp_Explorer solid( theShape, TopAbs_SOLID );
854       for ( int i = 0; ( i < maxNbErrors && solid.More() ); ++i, solid.Next() )
855         if ( !meshedSolids.Contains( solid.Current() ))
856         {
857           SMESH_subMesh* sm = theMesh.GetSubMesh( solid.Current() );
858           sm->GetComputeError() = err;
859         }
860       return error( err );
861     }
862   }
863   return true;
864 }
865
866 //================================================================================
867 /*!
868  * \brief Find wall faces by bottom edges
869  */
870 //================================================================================
871
872 bool StdMeshers_Prism_3D::getWallFaces( Prism_3D::TPrismTopo & thePrism,
873                                         const int              totalNbFaces)
874 {
875   thePrism.myWallQuads.clear();
876
877   SMESH_Mesh* mesh = myHelper->GetMesh();
878
879   StdMeshers_Quadrangle_2D* quadAlgo = TQuadrangleAlgo::instance( this, myHelper );
880
881   TopTools_MapOfShape faceMap;
882   TopTools_IndexedDataMapOfShapeListOfShape edgeToFaces;   
883   TopExp::MapShapesAndAncestors( thePrism.myShape3D,
884                                  TopAbs_EDGE, TopAbs_FACE, edgeToFaces );
885
886   // ------------------------------
887   // Get the 1st row of wall FACEs
888   // ------------------------------
889
890   list< TopoDS_Edge >::iterator edge = thePrism.myBottomEdges.begin();
891   std::list< int >::iterator     nbE = thePrism.myNbEdgesInWires.begin();
892   int iE = 0;
893   double f,l;
894   while ( edge != thePrism.myBottomEdges.end() )
895   {
896     ++iE;
897     if ( BRep_Tool::Curve( *edge, f,l ).IsNull() )
898     {
899       edge = thePrism.myBottomEdges.erase( edge );
900       --iE;
901       --(*nbE);
902     }
903     else
904     {
905       TopTools_ListIteratorOfListOfShape faceIt( edgeToFaces.FindFromKey( *edge ));
906       for ( ; faceIt.More(); faceIt.Next() )
907       {
908         const TopoDS_Face& face = TopoDS::Face( faceIt.Value() );
909         if ( !thePrism.myBottom.IsSame( face ))
910         {
911           Prism_3D::TQuadList quadList( 1, quadAlgo->CheckNbEdges( *mesh, face ));
912           if ( !quadList.back() )
913             return toSM( error(TCom("Side face #") << shapeID( face )
914                                << " not meshable with quadrangles"));
915           bool isCompositeBase = ! setBottomEdge( *edge, quadList.back(), face );
916           if ( isCompositeBase )
917           {
918             // it's OK if all EDGEs of the bottom side belongs to the bottom FACE
919             StdMeshers_FaceSidePtr botSide = quadList.back()->side[ QUAD_BOTTOM_SIDE ];
920             for ( int iE = 0; iE < botSide->NbEdges(); ++iE )
921               if ( !myHelper->IsSubShape( botSide->Edge(iE), thePrism.myBottom ))
922                 return toSM( error(TCom("Composite 'horizontal' edges are not supported")));
923           }
924           if ( faceMap.Add( face ))
925             thePrism.myWallQuads.push_back( quadList );
926           break;
927         }
928       }
929       ++edge;
930     }
931     if ( iE == *nbE )
932     {
933       iE = 0;
934       ++nbE;
935     }
936   }
937
938   // -------------------------
939   // Find the rest wall FACEs
940   // -------------------------
941
942   // Compose a vector of indixes of right neighbour FACE for each wall FACE
943   // that is not so evident in case of several WIREs in the bottom FACE
944   thePrism.myRightQuadIndex.clear();
945   for ( size_t i = 0; i < thePrism.myWallQuads.size(); ++i )
946     thePrism.myRightQuadIndex.push_back( i+1 );
947   list< int >::iterator nbEinW = thePrism.myNbEdgesInWires.begin();
948   for ( int iLeft = 0; nbEinW != thePrism.myNbEdgesInWires.end(); ++nbEinW )
949   {
950     thePrism.myRightQuadIndex[ iLeft + *nbEinW - 1 ] = iLeft; // 1st EDGE index of a current WIRE
951     iLeft += *nbEinW;
952   }
953
954   while ( totalNbFaces - faceMap.Extent() > 2 )
955   {
956     // find wall FACEs adjacent to each of wallQuads by the right side EDGE
957     int nbKnownFaces;
958     do {
959       nbKnownFaces = faceMap.Extent();
960       StdMeshers_FaceSidePtr rightSide, topSide; // sides of the quad
961       for ( size_t i = 0; i < thePrism.myWallQuads.size(); ++i )
962       {
963         rightSide = thePrism.myWallQuads[i].back()->side[ QUAD_RIGHT_SIDE ];
964         for ( int iE = 0; iE < rightSide->NbEdges(); ++iE ) // rightSide can be composite
965         {
966           const TopoDS_Edge & rightE = rightSide->Edge( iE );
967           TopTools_ListIteratorOfListOfShape face( edgeToFaces.FindFromKey( rightE ));
968           for ( ; face.More(); face.Next() )
969             if ( faceMap.Add( face.Value() ))
970             {
971               // a new wall FACE encountered, store it in thePrism.myWallQuads
972               const int iRight = thePrism.myRightQuadIndex[i];
973               topSide = thePrism.myWallQuads[ iRight ].back()->side[ QUAD_TOP_SIDE ];
974               const TopoDS_Edge&   newBotE = topSide->Edge(0);
975               const TopoDS_Shape& newWallF = face.Value();
976               thePrism.myWallQuads[ iRight ].push_back( quadAlgo->CheckNbEdges( *mesh, newWallF ));
977               if ( !thePrism.myWallQuads[ iRight ].back() )
978                 return toSM( error(TCom("Side face #") << shapeID( newWallF ) <<
979                                    " not meshable with quadrangles"));
980               if ( ! setBottomEdge( newBotE, thePrism.myWallQuads[ iRight ].back(), newWallF ))
981                 return toSM( error(TCom("Composite 'horizontal' edges are not supported")));
982             }
983         }
984       }
985     } while ( nbKnownFaces != faceMap.Extent() );
986
987     // find wall FACEs adjacent to each of thePrism.myWallQuads by the top side EDGE
988     if ( totalNbFaces - faceMap.Extent() > 2 )
989     {
990       const int nbFoundWalls = faceMap.Extent();
991       for ( size_t i = 0; i < thePrism.myWallQuads.size(); ++i )
992       {
993         StdMeshers_FaceSidePtr topSide = thePrism.myWallQuads[i].back()->side[ QUAD_TOP_SIDE ];
994         const TopoDS_Edge &       topE = topSide->Edge( 0 );
995         if ( topSide->NbEdges() > 1 )
996           return toSM( error(COMPERR_BAD_SHAPE, TCom("Side face #") <<
997                              shapeID( thePrism.myWallQuads[i].back()->face )
998                              << " has a composite top edge"));
999         TopTools_ListIteratorOfListOfShape faceIt( edgeToFaces.FindFromKey( topE ));
1000         for ( ; faceIt.More(); faceIt.Next() )
1001           if ( faceMap.Add( faceIt.Value() ))
1002           {
1003             // a new wall FACE encountered, store it in wallQuads
1004             thePrism.myWallQuads[ i ].push_back( quadAlgo->CheckNbEdges( *mesh, faceIt.Value() ));
1005             if ( !thePrism.myWallQuads[ i ].back() )
1006               return toSM( error(TCom("Side face #") << shapeID( faceIt.Value() ) <<
1007                                  " not meshable with quadrangles"));
1008             if ( ! setBottomEdge( topE, thePrism.myWallQuads[ i ].back(), faceIt.Value() ))
1009               return toSM( error(TCom("Composite 'horizontal' edges are not supported")));
1010             if ( totalNbFaces - faceMap.Extent() == 2 )
1011             {
1012               i = thePrism.myWallQuads.size(); // to quit from the outer loop
1013               break;
1014             }
1015           }
1016       }
1017       if ( nbFoundWalls == faceMap.Extent() )
1018         return toSM( error("Failed to find wall faces"));
1019
1020     }
1021   } // while ( totalNbFaces - faceMap.Extent() > 2 )
1022
1023   // ------------------
1024   // Find the top FACE
1025   // ------------------
1026
1027   if ( thePrism.myTop.IsNull() )
1028   {
1029     // now only top and bottom FACEs are not in the faceMap
1030     faceMap.Add( thePrism.myBottom );
1031     for ( TopExp_Explorer f( thePrism.myShape3D, TopAbs_FACE );f.More(); f.Next() )
1032       if ( !faceMap.Contains( f.Current() )) {
1033         thePrism.myTop = TopoDS::Face( f.Current() );
1034         break;
1035       }
1036     if ( thePrism.myTop.IsNull() )
1037       return toSM( error("Top face not found"));
1038   }
1039
1040   // Check that the top FACE shares all the top EDGEs
1041   for ( size_t i = 0; i < thePrism.myWallQuads.size(); ++i )
1042   {
1043     StdMeshers_FaceSidePtr topSide = thePrism.myWallQuads[i].back()->side[ QUAD_TOP_SIDE ];
1044     const TopoDS_Edge &       topE = topSide->Edge( 0 );
1045     if ( !myHelper->IsSubShape( topE, thePrism.myTop ))
1046       return toSM( error( TCom("Wrong source face (#") << shapeID( thePrism.myBottom )));
1047   }
1048
1049   return true;
1050 }
1051
1052 //=======================================================================
1053 //function : compute
1054 //purpose  : Compute mesh on a SOLID
1055 //=======================================================================
1056
1057 bool StdMeshers_Prism_3D::compute(const Prism_3D::TPrismTopo& thePrism)
1058 {
1059   myHelper->IsQuadraticSubMesh( thePrism.myShape3D );
1060   if ( _computeCanceled )
1061     return toSM( error( SMESH_ComputeError::New(COMPERR_CANCELED)));
1062
1063   // Make all side FACEs of thePrism meshed with quads
1064   if ( !computeWalls( thePrism ))
1065     return false;
1066
1067   // Analyse mesh and geometry to find all block sub-shapes and submeshes
1068   // (after fixing IPAL52499 myBlock is used only as a holder of boundary nodes
1069   // and location of internal nodes is computed by StdMeshers_Sweeper)
1070   if ( !myBlock.Init( myHelper, thePrism ))
1071     return toSM( error( myBlock.GetError()));
1072
1073   SMESHDS_Mesh* meshDS = myHelper->GetMeshDS();
1074
1075   int volumeID = meshDS->ShapeToIndex( thePrism.myShape3D );
1076
1077   // Try to get gp_Trsf to get all nodes from bottom ones
1078   vector<gp_Trsf> trsf;
1079   gp_Trsf bottomToTopTrsf;
1080   // if ( !myBlock.GetLayersTransformation( trsf, thePrism ))
1081   //   trsf.clear();
1082   // else if ( !trsf.empty() )
1083   //   bottomToTopTrsf = trsf.back();
1084
1085   // To compute coordinates of a node inside a block, it is necessary to know
1086   // 1. normalized parameters of the node by which
1087   // 2. coordinates of node projections on all block sub-shapes are computed
1088
1089   // So we fill projections on vertices at once as they are same for all nodes
1090   myShapeXYZ.resize( myBlock.NbSubShapes() );
1091   for ( int iV = SMESH_Block::ID_FirstV; iV < SMESH_Block::ID_FirstE; ++iV ) {
1092     myBlock.VertexPoint( iV, myShapeXYZ[ iV ]);
1093     SHOWYXZ("V point " <<iV << " ", myShapeXYZ[ iV ]);
1094   }
1095
1096   // Projections on the top and bottom faces are taken from nodes existing
1097   // on these faces; find correspondence between bottom and top nodes
1098   myBotToColumnMap.clear();
1099   if ( !assocOrProjBottom2Top( bottomToTopTrsf, thePrism ) ) // it also fills myBotToColumnMap
1100     return false;
1101
1102
1103   // Create nodes inside the block
1104
1105   // use transformation (issue 0020680, IPAL0052499)
1106   StdMeshers_Sweeper sweeper;
1107
1108   // load boundary nodes
1109   bool dummy;
1110   list< TopoDS_Edge >::const_iterator edge = thePrism.myBottomEdges.begin();
1111   for ( ; edge != thePrism.myBottomEdges.end(); ++edge )
1112   {
1113     int edgeID = meshDS->ShapeToIndex( *edge );
1114     TParam2ColumnMap* u2col = const_cast<TParam2ColumnMap*>
1115       ( myBlock.GetParam2ColumnMap( edgeID, dummy ));
1116     TParam2ColumnMap::iterator u2colIt = u2col->begin();
1117     for ( ; u2colIt != u2col->end(); ++u2colIt )
1118       sweeper.myBndColumns.push_back( & u2colIt->second );
1119   }
1120   // load node columns inside the bottom face
1121   TNode2ColumnMap::iterator bot_column = myBotToColumnMap.begin();
1122   for ( ; bot_column != myBotToColumnMap.end(); ++bot_column )
1123     sweeper.myIntColumns.push_back( & bot_column->second );
1124
1125   const double tol = getSweepTolerance( thePrism );
1126
1127   if ( sweeper.ComputeNodes( *myHelper, tol ))
1128   {
1129   }
1130   else // use block approach
1131   {
1132     // loop on nodes inside the bottom face
1133     Prism_3D::TNode prevBNode;
1134     TNode2ColumnMap::iterator bot_column = myBotToColumnMap.begin();
1135     for ( ; bot_column != myBotToColumnMap.end(); ++bot_column )
1136     {
1137       const Prism_3D::TNode& tBotNode = bot_column->first; // bottom TNode
1138       if ( tBotNode.GetPositionType() != SMDS_TOP_FACE )
1139         continue; // node is not inside the FACE
1140
1141       // column nodes; middle part of the column are zero pointers
1142       TNodeColumn& column = bot_column->second;
1143
1144       gp_XYZ botParams, topParams;
1145       if ( !tBotNode.HasParams() )
1146       {
1147         // compute bottom node parameters
1148         gp_XYZ paramHint(-1,-1,-1);
1149         if ( prevBNode.IsNeighbor( tBotNode ))
1150           paramHint = prevBNode.GetParams();
1151         if ( !myBlock.ComputeParameters( tBotNode.GetCoords(), tBotNode.ChangeParams(),
1152                                          ID_BOT_FACE, paramHint ))
1153           return toSM( error(TCom("Can't compute normalized parameters for node ")
1154                              << tBotNode.myNode->GetID() << " on the face #"
1155                              << myBlock.SubMesh( ID_BOT_FACE )->GetId() ));
1156         prevBNode = tBotNode;
1157
1158         botParams = topParams = tBotNode.GetParams();
1159         topParams.SetZ( 1 );
1160
1161         // compute top node parameters
1162         if ( column.size() > 2 ) {
1163           gp_Pnt topCoords = gpXYZ( column.back() );
1164           if ( !myBlock.ComputeParameters( topCoords, topParams, ID_TOP_FACE, topParams ))
1165             return toSM( error(TCom("Can't compute normalized parameters ")
1166                                << "for node " << column.back()->GetID()
1167                                << " on the face #"<< column.back()->getshapeId() ));
1168         }
1169       }
1170       else // top nodes are created by projection using parameters
1171       {
1172         botParams = topParams = tBotNode.GetParams();
1173         topParams.SetZ( 1 );
1174       }
1175
1176       myShapeXYZ[ ID_BOT_FACE ] = tBotNode.GetCoords();
1177       myShapeXYZ[ ID_TOP_FACE ] = gpXYZ( column.back() );
1178
1179       // vertical loop
1180       TNodeColumn::iterator columnNodes = column.begin();
1181       for ( int z = 0; columnNodes != column.end(); ++columnNodes, ++z)
1182       {
1183         const SMDS_MeshNode* & node = *columnNodes;
1184         if ( node ) continue; // skip bottom or top node
1185
1186         // params of a node to create
1187         double rz = (double) z / (double) ( column.size() - 1 );
1188         gp_XYZ params = botParams * ( 1 - rz ) + topParams * rz;
1189
1190         // set coords on all faces and nodes
1191         const int nbSideFaces = 4;
1192         int sideFaceIDs[nbSideFaces] = { SMESH_Block::ID_Fx0z,
1193                                          SMESH_Block::ID_Fx1z,
1194                                          SMESH_Block::ID_F0yz,
1195                                          SMESH_Block::ID_F1yz };
1196         for ( int iF = 0; iF < nbSideFaces; ++iF )
1197           if ( !setFaceAndEdgesXYZ( sideFaceIDs[ iF ], params, z ))
1198             return false;
1199
1200         // compute coords for a new node
1201         gp_XYZ coords;
1202         if ( !SMESH_Block::ShellPoint( params, myShapeXYZ, coords ))
1203           return toSM( error("Can't compute coordinates by normalized parameters"));
1204
1205         // if ( !meshDS->MeshElements( volumeID ) ||
1206         //      meshDS->MeshElements( volumeID )->NbNodes() == 0 )
1207         //   pointsToPython(myShapeXYZ);
1208         SHOWYXZ("TOPFacePoint ",myShapeXYZ[ ID_TOP_FACE]);
1209         SHOWYXZ("BOT Node "<< tBotNode.myNode->GetID(),gpXYZ(tBotNode.myNode));
1210         SHOWYXZ("ShellPoint ",coords);
1211
1212         // create a node
1213         node = meshDS->AddNode( coords.X(), coords.Y(), coords.Z() );
1214         meshDS->SetNodeInVolume( node, volumeID );
1215
1216         if ( _computeCanceled )
1217           return false;
1218       }
1219     } // loop on bottom nodes
1220   }
1221
1222   // Create volumes
1223
1224   SMESHDS_SubMesh* smDS = myBlock.SubMeshDS( ID_BOT_FACE );
1225   if ( !smDS ) return toSM( error(COMPERR_BAD_INPUT_MESH, "Null submesh"));
1226
1227   // loop on bottom mesh faces
1228   SMDS_ElemIteratorPtr faceIt = smDS->GetElements();
1229   while ( faceIt->more() )
1230   {
1231     const SMDS_MeshElement* face = faceIt->next();
1232     if ( !face || face->GetType() != SMDSAbs_Face )
1233       continue;
1234
1235     // find node columns for each node
1236     int nbNodes = face->NbCornerNodes();
1237     vector< const TNodeColumn* > columns( nbNodes );
1238     for ( int i = 0; i < nbNodes; ++i )
1239     {
1240       const SMDS_MeshNode* n = face->GetNode( i );
1241       if ( n->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE ) {
1242         TNode2ColumnMap::iterator bot_column = myBotToColumnMap.find( n );
1243         if ( bot_column == myBotToColumnMap.end() )
1244           return toSM( error(TCom("No nodes found above node ") << n->GetID() ));
1245         columns[ i ] = & bot_column->second;
1246       }
1247       else {
1248         columns[ i ] = myBlock.GetNodeColumn( n );
1249         if ( !columns[ i ] )
1250           return toSM( error(TCom("No side nodes found above node ") << n->GetID() ));
1251       }
1252     }
1253     // create prisms
1254     AddPrisms( columns, myHelper );
1255
1256   } // loop on bottom mesh faces
1257
1258   // clear data
1259   myBotToColumnMap.clear();
1260   myBlock.Clear();
1261         
1262   return true;
1263 }
1264
1265 //=======================================================================
1266 //function : computeWalls
1267 //purpose  : Compute 2D mesh on walls FACEs of a prism
1268 //=======================================================================
1269
1270 bool StdMeshers_Prism_3D::computeWalls(const Prism_3D::TPrismTopo& thePrism)
1271 {
1272   SMESH_Mesh*     mesh = myHelper->GetMesh();
1273   SMESHDS_Mesh* meshDS = myHelper->GetMeshDS();
1274   DBGOUT( endl << "COMPUTE Prism " << meshDS->ShapeToIndex( thePrism.myShape3D ));
1275
1276   TProjction1dAlgo*      projector1D = TProjction1dAlgo::instance( this );
1277   StdMeshers_Quadrangle_2D* quadAlgo = TQuadrangleAlgo::instance( this, myHelper );
1278
1279   // SMESH_HypoFilter hyp1dFilter( SMESH_HypoFilter::IsAlgo(),/*not=*/true);
1280   // hyp1dFilter.And( SMESH_HypoFilter::HasDim( 1 ));
1281   // hyp1dFilter.And( SMESH_HypoFilter::IsMoreLocalThan( thePrism.myShape3D, *mesh ));
1282
1283   // Discretize equally 'vertical' EDGEs
1284   // -----------------------------------
1285   // find source FACE sides for projection: either already computed ones or
1286   // the 'most composite' ones
1287   const size_t nbWalls = thePrism.myWallQuads.size();
1288   vector< int > wgt( nbWalls, 0 ); // "weight" of a wall
1289   for ( size_t iW = 0; iW != nbWalls; ++iW )
1290   {
1291     Prism_3D::TQuadList::const_iterator quad = thePrism.myWallQuads[iW].begin();
1292     for ( ; quad != thePrism.myWallQuads[iW].end(); ++quad )
1293     {
1294       StdMeshers_FaceSidePtr lftSide = (*quad)->side[ QUAD_LEFT_SIDE ];
1295       for ( int i = 0; i < lftSide->NbEdges(); ++i )
1296       {
1297         ++wgt[ iW ];
1298         const TopoDS_Edge& E = lftSide->Edge(i);
1299         if ( mesh->GetSubMesh( E )->IsMeshComputed() )
1300         {
1301           wgt[ iW ] += 100;
1302           wgt[ myHelper->WrapIndex( iW+1, nbWalls)] += 10;
1303           wgt[ myHelper->WrapIndex( iW-1, nbWalls)] += 10;
1304         }
1305         // else if ( mesh->GetHypothesis( E, hyp1dFilter, true )) // local hypothesis!
1306         //   wgt += 100;
1307       }
1308     }
1309     // in quadratic mesh, pass ignoreMediumNodes to quad sides
1310     if ( myHelper->GetIsQuadratic() )
1311     {
1312       quad = thePrism.myWallQuads[iW].begin();
1313       for ( ; quad != thePrism.myWallQuads[iW].end(); ++quad )
1314         for ( int i = 0; i < NB_QUAD_SIDES; ++i )
1315           (*quad)->side[ i ].grid->SetIgnoreMediumNodes( true );
1316     }
1317   }
1318   multimap< int, int > wgt2quad;
1319   for ( size_t iW = 0; iW != nbWalls; ++iW )
1320     wgt2quad.insert( make_pair( wgt[ iW ], iW ));
1321
1322   // Project 'vertical' EDGEs, from left to right
1323   multimap< int, int >::reverse_iterator w2q = wgt2quad.rbegin();
1324   for ( ; w2q != wgt2quad.rend(); ++w2q )
1325   {
1326     const int iW = w2q->second;
1327     const Prism_3D::TQuadList&         quads = thePrism.myWallQuads[ iW ];
1328     Prism_3D::TQuadList::const_iterator quad = quads.begin();
1329     for ( ; quad != quads.end(); ++quad )
1330     {
1331       StdMeshers_FaceSidePtr rgtSide = (*quad)->side[ QUAD_RIGHT_SIDE ]; // tgt
1332       StdMeshers_FaceSidePtr lftSide = (*quad)->side[ QUAD_LEFT_SIDE ];  // src
1333       bool swapLeftRight = ( lftSide->NbSegments( /*update=*/true ) == 0 &&
1334                              rgtSide->NbSegments( /*update=*/true )  > 0 );
1335       if ( swapLeftRight )
1336         std::swap( lftSide, rgtSide );
1337
1338       // assure that all the source (left) EDGEs are meshed
1339       int nbSrcSegments = 0;
1340       for ( int i = 0; i < lftSide->NbEdges(); ++i )
1341       {
1342         const TopoDS_Edge& srcE = lftSide->Edge(i);
1343         SMESH_subMesh*    srcSM = mesh->GetSubMesh( srcE );
1344         if ( !srcSM->IsMeshComputed() ) {
1345           DBGOUT( "COMPUTE V edge " << srcSM->GetId() );
1346           TopoDS_Edge prpgSrcE = findPropagationSource( srcE );
1347           if ( !prpgSrcE.IsNull() ) {
1348             srcSM->ComputeSubMeshStateEngine( SMESH_subMesh::COMPUTE );
1349             projector1D->myHyp.SetSourceEdge( prpgSrcE );
1350             projector1D->Compute( *mesh, srcE );
1351             srcSM->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1352           }
1353           else {
1354             srcSM->ComputeSubMeshStateEngine( SMESH_subMesh::COMPUTE );
1355             srcSM->ComputeStateEngine       ( SMESH_subMesh::COMPUTE );
1356           }
1357           if ( !srcSM->IsMeshComputed() )
1358             return toSM( error( "Can't compute 1D mesh" ));
1359         }
1360         nbSrcSegments += srcSM->GetSubMeshDS()->NbElements();
1361       }
1362       // check target EDGEs
1363       int nbTgtMeshed = 0, nbTgtSegments = 0;
1364       vector< bool > isTgtEdgeComputed( rgtSide->NbEdges() );
1365       for ( int i = 0; i < rgtSide->NbEdges(); ++i )
1366       {
1367         const TopoDS_Edge& tgtE = rgtSide->Edge(i);
1368         SMESH_subMesh*    tgtSM = mesh->GetSubMesh( tgtE );
1369         if ( !( isTgtEdgeComputed[ i ] = tgtSM->IsMeshComputed() )) {
1370           tgtSM->ComputeSubMeshStateEngine( SMESH_subMesh::COMPUTE );
1371           tgtSM->ComputeStateEngine       ( SMESH_subMesh::COMPUTE );
1372         }
1373         if ( tgtSM->IsMeshComputed() ) {
1374           ++nbTgtMeshed;
1375           nbTgtSegments += tgtSM->GetSubMeshDS()->NbElements();
1376         }
1377       }
1378       if ( rgtSide->NbEdges() == nbTgtMeshed ) // all tgt EDGEs meshed
1379       {
1380         if ( nbTgtSegments != nbSrcSegments )
1381         {
1382           bool badMeshRemoved = false;
1383           // remove just computed segments
1384           for ( int i = 0; i < rgtSide->NbEdges(); ++i )
1385             if ( !isTgtEdgeComputed[ i ])
1386             {
1387               const TopoDS_Edge& tgtE = rgtSide->Edge(i);
1388               SMESH_subMesh*    tgtSM = mesh->GetSubMesh( tgtE );
1389               tgtSM->ComputeStateEngine( SMESH_subMesh::CLEAN );
1390               badMeshRemoved = true;
1391               nbTgtMeshed--;
1392             }
1393           if ( !badMeshRemoved )
1394           {
1395             for ( int i = 0; i < lftSide->NbEdges(); ++i )
1396               addBadInputElements( meshDS->MeshElements( lftSide->Edge( i )));
1397             for ( int i = 0; i < rgtSide->NbEdges(); ++i )
1398               addBadInputElements( meshDS->MeshElements( rgtSide->Edge( i )));
1399             return toSM( error( TCom("Different nb of segment on logically vertical edges #")
1400                                 << shapeID( lftSide->Edge(0) ) << " and #"
1401                                 << shapeID( rgtSide->Edge(0) ) << ": "
1402                                 << nbSrcSegments << " != " << nbTgtSegments ));
1403           }
1404         }
1405         else // if ( nbTgtSegments == nbSrcSegments )
1406         {
1407           continue;
1408         }
1409       }
1410       // Compute 'vertical projection'
1411       if ( nbTgtMeshed == 0 )
1412       {
1413         // compute nodes on target VERTEXes
1414         const UVPtStructVec&  srcNodeStr = lftSide->GetUVPtStruct();
1415         if ( srcNodeStr.size() == 0 )
1416           return toSM( error( TCom("Invalid node positions on edge #") <<
1417                               shapeID( lftSide->Edge(0) )));
1418         vector< SMDS_MeshNode* > newNodes( srcNodeStr.size() );
1419         for ( int is2ndV = 0; is2ndV < 2; ++is2ndV )
1420         {
1421           const TopoDS_Edge& E = rgtSide->Edge( is2ndV ? rgtSide->NbEdges()-1 : 0 );
1422           TopoDS_Vertex      v = myHelper->IthVertex( is2ndV, E );
1423           mesh->GetSubMesh( v )->ComputeStateEngine( SMESH_subMesh::COMPUTE );
1424           const SMDS_MeshNode* n = SMESH_Algo::VertexNode( v, meshDS );
1425           newNodes[ is2ndV ? 0 : newNodes.size()-1 ] = (SMDS_MeshNode*) n;
1426         }
1427
1428         // compute nodes on target EDGEs
1429         DBGOUT( "COMPUTE V edge (proj) " << shapeID( lftSide->Edge(0)));
1430         rgtSide->Reverse(); // direct it same as the lftSide
1431         myHelper->SetElementsOnShape( false ); // myHelper holds the prism shape
1432         TopoDS_Edge tgtEdge;
1433         for ( size_t iN = 1; iN < srcNodeStr.size()-1; ++iN ) // add nodes
1434         {
1435           gp_Pnt       p = rgtSide->Value3d  ( srcNodeStr[ iN ].normParam );
1436           double       u = rgtSide->Parameter( srcNodeStr[ iN ].normParam, tgtEdge );
1437           newNodes[ iN ] = meshDS->AddNode( p.X(), p.Y(), p.Z() );
1438           meshDS->SetNodeOnEdge( newNodes[ iN ], tgtEdge, u );
1439         }
1440         for ( size_t iN = 1; iN < srcNodeStr.size(); ++iN ) // add segments
1441         {
1442           // find an EDGE to set a new segment
1443           std::pair<int, TopAbs_ShapeEnum> id2type = 
1444             myHelper->GetMediumPos( newNodes[ iN-1 ], newNodes[ iN ] );
1445           if ( id2type.second != TopAbs_EDGE )
1446           {
1447             // new nodes are on different EDGEs; put one of them on VERTEX
1448             const int      edgeIndex = rgtSide->EdgeIndex( srcNodeStr[ iN-1 ].normParam );
1449             const double vertexParam = rgtSide->LastParameter( edgeIndex );
1450             TopoDS_Vertex     vertex = rgtSide->LastVertex( edgeIndex );
1451             const SMDS_MeshNode*  vn = SMESH_Algo::VertexNode( vertex, meshDS );
1452             const gp_Pnt           p = BRep_Tool::Pnt( vertex );
1453             const int         isPrev = ( Abs( srcNodeStr[ iN-1 ].normParam - vertexParam ) <
1454                                          Abs( srcNodeStr[ iN   ].normParam - vertexParam ));
1455             meshDS->UnSetNodeOnShape( newNodes[ iN-isPrev ] );
1456             meshDS->SetNodeOnVertex ( newNodes[ iN-isPrev ], vertex );
1457             meshDS->MoveNode        ( newNodes[ iN-isPrev ], p.X(), p.Y(), p.Z() );
1458             id2type.first = newNodes[ iN-(1-isPrev) ]->getshapeId();
1459             if ( vn )
1460             {
1461               SMESH_MeshEditor::TListOfListOfNodes lln( 1, list< const SMDS_MeshNode* >() );
1462               lln.back().push_back ( vn );
1463               lln.back().push_front( newNodes[ iN-isPrev ] ); // to keep 
1464               SMESH_MeshEditor( mesh ).MergeNodes( lln );
1465             }
1466           }
1467           SMDS_MeshElement* newEdge = myHelper->AddEdge( newNodes[ iN-1 ], newNodes[ iN ] );
1468           meshDS->SetMeshElementOnShape( newEdge, id2type.first );
1469         }
1470         myHelper->SetElementsOnShape( true );
1471         for ( int i = 0; i < rgtSide->NbEdges(); ++i ) // update state of sub-meshes
1472         {
1473           const TopoDS_Edge& E = rgtSide->Edge( i );
1474           SMESH_subMesh* tgtSM = mesh->GetSubMesh( E );
1475           tgtSM->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1476         }
1477
1478         // to continue projection from the just computed side as a source
1479         if ( !swapLeftRight && rgtSide->NbEdges() > 1 && w2q->second == iW )
1480         {
1481           std::pair<int,int> wgt2quadKeyVal( w2q->first + 1, thePrism.myRightQuadIndex[ iW ]);
1482           wgt2quad.insert( wgt2quadKeyVal ); // it will be skipped by ++w2q
1483           wgt2quad.insert( wgt2quadKeyVal );
1484           w2q = wgt2quad.rbegin();
1485         }
1486       }
1487       else
1488       {
1489         // HOPE assigned hypotheses are OK, so that equal nb of segments will be generated
1490         //return toSM( error("Partial projection not implemented"));
1491       }
1492     } // loop on quads of a composite wall side
1493   } // loop on the ordered wall sides
1494
1495
1496
1497   for ( size_t iW = 0; iW != thePrism.myWallQuads.size(); ++iW )
1498   {
1499     Prism_3D::TQuadList::const_iterator quad = thePrism.myWallQuads[iW].begin();
1500     for ( ; quad != thePrism.myWallQuads[iW].end(); ++quad )
1501     {
1502       const TopoDS_Face& face = (*quad)->face;
1503       SMESH_subMesh* fSM = mesh->GetSubMesh( face );
1504       if ( ! fSM->IsMeshComputed() )
1505       {
1506         // Top EDGEs must be projections from the bottom ones
1507         // to compute stuctured quad mesh on wall FACEs
1508         // ---------------------------------------------------
1509         const TopoDS_Edge& botE = (*quad)->side[ QUAD_BOTTOM_SIDE ].grid->Edge(0);
1510         const TopoDS_Edge& topE = (*quad)->side[ QUAD_TOP_SIDE    ].grid->Edge(0);
1511         SMESH_subMesh*    botSM = mesh->GetSubMesh( botE );
1512         SMESH_subMesh*    topSM = mesh->GetSubMesh( topE );
1513         SMESH_subMesh*    srcSM = botSM;
1514         SMESH_subMesh*    tgtSM = topSM;
1515         if ( !srcSM->IsMeshComputed() && tgtSM->IsMeshComputed() )
1516           std::swap( srcSM, tgtSM );
1517
1518         if ( !srcSM->IsMeshComputed() )
1519         {
1520           DBGOUT( "COMPUTE H edge " << srcSM->GetId());
1521           srcSM->ComputeSubMeshStateEngine( SMESH_subMesh::COMPUTE ); // nodes on VERTEXes
1522           srcSM->ComputeStateEngine( SMESH_subMesh::COMPUTE );        // segments on the EDGE
1523         }
1524         srcSM->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1525
1526         if ( tgtSM->IsMeshComputed() &&
1527              tgtSM->GetSubMeshDS()->NbNodes() != srcSM->GetSubMeshDS()->NbNodes() )
1528         {
1529           // the top EDGE is computed differently than the bottom one,
1530           // try to clear a wrong mesh
1531           bool isAdjFaceMeshed = false;
1532           PShapeIteratorPtr fIt = myHelper->GetAncestors( tgtSM->GetSubShape(),
1533                                                           *mesh, TopAbs_FACE );
1534           while ( const TopoDS_Shape* f = fIt->next() )
1535             if (( isAdjFaceMeshed = mesh->GetSubMesh( *f )->IsMeshComputed() ))
1536               break;
1537           if ( isAdjFaceMeshed )
1538             return toSM( error( TCom("Different nb of segment on logically horizontal edges #")
1539                                 << shapeID( botE ) << " and #"
1540                                 << shapeID( topE ) << ": "
1541                                 << tgtSM->GetSubMeshDS()->NbElements() << " != "
1542                                 << srcSM->GetSubMeshDS()->NbElements() ));
1543           tgtSM->ComputeStateEngine( SMESH_subMesh::CLEAN );
1544         }
1545         if ( !tgtSM->IsMeshComputed() )
1546         {
1547           // compute nodes on VERTEXes
1548           SMESH_subMeshIteratorPtr smIt = tgtSM->getDependsOnIterator(/*includeSelf=*/false);
1549           while ( smIt->more() )
1550             smIt->next()->ComputeStateEngine( SMESH_subMesh::COMPUTE );
1551           // project segments
1552           DBGOUT( "COMPUTE H edge (proj) " << tgtSM->GetId());
1553           projector1D->myHyp.SetSourceEdge( TopoDS::Edge( srcSM->GetSubShape() ));
1554           projector1D->InitComputeError();
1555           bool ok = projector1D->Compute( *mesh, tgtSM->GetSubShape() );
1556           if ( !ok )
1557           {
1558             SMESH_ComputeErrorPtr err = projector1D->GetComputeError();
1559             if ( err->IsOK() ) err->myName = COMPERR_ALGO_FAILED;
1560             tgtSM->GetComputeError() = err;
1561             return false;
1562           }
1563         }
1564         tgtSM->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1565
1566
1567         // Compute quad mesh on wall FACEs
1568         // -------------------------------
1569
1570         // make all EDGES meshed
1571         fSM->ComputeSubMeshStateEngine( SMESH_subMesh::COMPUTE );
1572         if ( !fSM->SubMeshesComputed() )
1573           return toSM( error( COMPERR_BAD_INPUT_MESH,
1574                               "Not all edges have valid algorithm and hypothesis"));
1575         // mesh the <face>
1576         quadAlgo->InitComputeError();
1577         DBGOUT( "COMPUTE Quad face " << fSM->GetId());
1578         bool ok = quadAlgo->Compute( *mesh, face );
1579         fSM->GetComputeError() = quadAlgo->GetComputeError();
1580         if ( !ok )
1581           return false;
1582         fSM->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1583       }
1584       if ( myHelper->GetIsQuadratic() )
1585       {
1586         // fill myHelper with medium nodes built by quadAlgo
1587         SMDS_ElemIteratorPtr fIt = fSM->GetSubMeshDS()->GetElements();
1588         while ( fIt->more() )
1589           myHelper->AddTLinks( dynamic_cast<const SMDS_MeshFace*>( fIt->next() ));
1590       }
1591     }
1592   }
1593
1594   return true;
1595 }
1596
1597 //=======================================================================
1598 /*!
1599  * \brief Returns a source EDGE of propagation to a given EDGE
1600  */
1601 //=======================================================================
1602
1603 TopoDS_Edge StdMeshers_Prism_3D::findPropagationSource( const TopoDS_Edge& E )
1604 {
1605   if ( myPropagChains )
1606     for ( size_t i = 0; !myPropagChains[i].IsEmpty(); ++i )
1607       if ( myPropagChains[i].Contains( E ))
1608         return TopoDS::Edge( myPropagChains[i].FindKey( 1 ));
1609
1610   return TopoDS_Edge();
1611 }
1612
1613 //=======================================================================
1614 //function : Evaluate
1615 //purpose  : 
1616 //=======================================================================
1617
1618 bool StdMeshers_Prism_3D::Evaluate(SMESH_Mesh&         theMesh,
1619                                    const TopoDS_Shape& theShape,
1620                                    MapShapeNbElems&    aResMap)
1621 {
1622   if ( theShape.ShapeType() == TopAbs_COMPOUND )
1623   {
1624     bool ok = true;
1625     for ( TopoDS_Iterator it( theShape ); it.More(); it.Next() )
1626       ok &= Evaluate( theMesh, it.Value(), aResMap );
1627     return ok;
1628   }
1629   SMESH_MesherHelper helper( theMesh );
1630   myHelper = &helper;
1631   myHelper->SetSubShape( theShape );
1632
1633   // find face contains only triangles
1634   vector < SMESH_subMesh * >meshFaces;
1635   TopTools_SequenceOfShape aFaces;
1636   int NumBase = 0, i = 0, NbQFs = 0;
1637   for (TopExp_Explorer exp(theShape, TopAbs_FACE); exp.More(); exp.Next()) {
1638     i++;
1639     aFaces.Append(exp.Current());
1640     SMESH_subMesh *aSubMesh = theMesh.GetSubMesh(exp.Current());
1641     meshFaces.push_back(aSubMesh);
1642     MapShapeNbElemsItr anIt = aResMap.find(meshFaces[i-1]);
1643     if( anIt==aResMap.end() )
1644       return toSM( error( "Submesh can not be evaluated"));
1645
1646     std::vector<int> aVec = (*anIt).second;
1647     int nbtri = Max(aVec[SMDSEntity_Triangle],aVec[SMDSEntity_Quad_Triangle]);
1648     int nbqua = Max(aVec[SMDSEntity_Quadrangle],aVec[SMDSEntity_Quad_Quadrangle]);
1649     if( nbtri==0 && nbqua>0 ) {
1650       NbQFs++;
1651     }
1652     if( nbtri>0 ) {
1653       NumBase = i;
1654     }
1655   }
1656
1657   if(NbQFs<4) {
1658     std::vector<int> aResVec(SMDSEntity_Last);
1659     for(int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aResVec[i] = 0;
1660     SMESH_subMesh * sm = theMesh.GetSubMesh(theShape);
1661     aResMap.insert(std::make_pair(sm,aResVec));
1662     return toSM( error( "Submesh can not be evaluated" ));
1663   }
1664
1665   if(NumBase==0) NumBase = 1; // only quads => set 1 faces as base
1666
1667   // find number of 1d elems for base face
1668   int nb1d = 0;
1669   TopTools_MapOfShape Edges1;
1670   for (TopExp_Explorer exp(aFaces.Value(NumBase), TopAbs_EDGE); exp.More(); exp.Next()) {
1671     Edges1.Add(exp.Current());
1672     SMESH_subMesh *sm = theMesh.GetSubMesh(exp.Current());
1673     if( sm ) {
1674       MapShapeNbElemsItr anIt = aResMap.find(sm);
1675       if( anIt == aResMap.end() ) continue;
1676       std::vector<int> aVec = (*anIt).second;
1677       nb1d += Max(aVec[SMDSEntity_Edge],aVec[SMDSEntity_Quad_Edge]);
1678     }
1679   }
1680   // find face opposite to base face
1681   int OppNum = 0;
1682   for(i=1; i<=6; i++) {
1683     if(i==NumBase) continue;
1684     bool IsOpposite = true;
1685     for(TopExp_Explorer exp(aFaces.Value(i), TopAbs_EDGE); exp.More(); exp.Next()) {
1686       if( Edges1.Contains(exp.Current()) ) {
1687         IsOpposite = false;
1688         break;
1689       }
1690     }
1691     if(IsOpposite) {
1692       OppNum = i;
1693       break;
1694     }
1695   }
1696   // find number of 2d elems on side faces
1697   int nb2d = 0;
1698   for(i=1; i<=6; i++) {
1699     if( i==OppNum || i==NumBase ) continue;
1700     MapShapeNbElemsItr anIt = aResMap.find( meshFaces[i-1] );
1701     if( anIt == aResMap.end() ) continue;
1702     std::vector<int> aVec = (*anIt).second;
1703     nb2d += Max(aVec[SMDSEntity_Quadrangle],aVec[SMDSEntity_Quad_Quadrangle]);
1704   }
1705   
1706   MapShapeNbElemsItr anIt = aResMap.find( meshFaces[NumBase-1] );
1707   std::vector<int> aVec = (*anIt).second;
1708   bool IsQuadratic = (aVec[SMDSEntity_Quad_Triangle]>aVec[SMDSEntity_Triangle]) ||
1709                      (aVec[SMDSEntity_Quad_Quadrangle]>aVec[SMDSEntity_Quadrangle]);
1710   int nb2d_face0_3 = Max(aVec[SMDSEntity_Triangle],aVec[SMDSEntity_Quad_Triangle]);
1711   int nb2d_face0_4 = Max(aVec[SMDSEntity_Quadrangle],aVec[SMDSEntity_Quad_Quadrangle]);
1712   int nb0d_face0 = aVec[SMDSEntity_Node];
1713   int nb1d_face0_int = ( nb2d_face0_3*3 + nb2d_face0_4*4 - nb1d ) / 2;
1714
1715   std::vector<int> aResVec(SMDSEntity_Last);
1716   for(int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aResVec[i] = 0;
1717   if(IsQuadratic) {
1718     aResVec[SMDSEntity_Quad_Penta] = nb2d_face0_3 * ( nb2d/nb1d );
1719     aResVec[SMDSEntity_Quad_Hexa] = nb2d_face0_4 * ( nb2d/nb1d );
1720     aResVec[SMDSEntity_Node] = nb0d_face0 * ( 2*nb2d/nb1d - 1 ) - nb1d_face0_int * nb2d/nb1d;
1721   }
1722   else {
1723     aResVec[SMDSEntity_Node] = nb0d_face0 * ( nb2d/nb1d - 1 );
1724     aResVec[SMDSEntity_Penta] = nb2d_face0_3 * ( nb2d/nb1d );
1725     aResVec[SMDSEntity_Hexa] = nb2d_face0_4 * ( nb2d/nb1d );
1726   }
1727   SMESH_subMesh * sm = theMesh.GetSubMesh(theShape);
1728   aResMap.insert(std::make_pair(sm,aResVec));
1729
1730   return true;
1731 }
1732
1733 //================================================================================
1734 /*!
1735  * \brief Create prisms
1736  * \param columns - columns of nodes generated from nodes of a mesh face
1737  * \param helper - helper initialized by mesh and shape to add prisms to
1738  */
1739 //================================================================================
1740
1741 void StdMeshers_Prism_3D::AddPrisms( vector<const TNodeColumn*> & columns,
1742                                      SMESH_MesherHelper*          helper)
1743 {
1744   int nbNodes = columns.size();
1745   int nbZ     = columns[0]->size();
1746   if ( nbZ < 2 ) return;
1747
1748   // find out orientation
1749   bool isForward = true;
1750   SMDS_VolumeTool vTool;
1751   int z = 1;
1752   switch ( nbNodes ) {
1753   case 3: {
1754     SMDS_VolumeOfNodes tmpPenta ( (*columns[0])[z-1], // bottom
1755                                   (*columns[1])[z-1],
1756                                   (*columns[2])[z-1],
1757                                   (*columns[0])[z],   // top
1758                                   (*columns[1])[z],
1759                                   (*columns[2])[z] );
1760     vTool.Set( &tmpPenta );
1761     isForward  = vTool.IsForward();
1762     break;
1763   }
1764   case 4: {
1765     SMDS_VolumeOfNodes tmpHex( (*columns[0])[z-1], (*columns[1])[z-1], // bottom
1766                                (*columns[2])[z-1], (*columns[3])[z-1],
1767                                (*columns[0])[z],   (*columns[1])[z],   // top
1768                                (*columns[2])[z],   (*columns[3])[z] );
1769     vTool.Set( &tmpHex );
1770     isForward  = vTool.IsForward();
1771     break;
1772   }
1773   default:
1774     const int di = (nbNodes+1) / 3;
1775     SMDS_VolumeOfNodes tmpVol ( (*columns[0]   )[z-1],
1776                                 (*columns[di]  )[z-1],
1777                                 (*columns[2*di])[z-1],
1778                                 (*columns[0]   )[z],
1779                                 (*columns[di]  )[z],
1780                                 (*columns[2*di])[z] );
1781     vTool.Set( &tmpVol );
1782     isForward  = vTool.IsForward();
1783   }
1784
1785   // vertical loop on columns
1786
1787   helper->SetElementsOnShape( true );
1788
1789   switch ( nbNodes ) {
1790
1791   case 3: { // ---------- pentahedra
1792     const int i1 = isForward ? 1 : 2;
1793     const int i2 = isForward ? 2 : 1;
1794     for ( z = 1; z < nbZ; ++z )
1795       helper->AddVolume( (*columns[0 ])[z-1], // bottom
1796                          (*columns[i1])[z-1],
1797                          (*columns[i2])[z-1],
1798                          (*columns[0 ])[z],   // top
1799                          (*columns[i1])[z],
1800                          (*columns[i2])[z] );
1801     break;
1802   }
1803   case 4: { // ---------- hexahedra
1804     const int i1 = isForward ? 1 : 3;
1805     const int i3 = isForward ? 3 : 1;
1806     for ( z = 1; z < nbZ; ++z )
1807       helper->AddVolume( (*columns[0])[z-1], (*columns[i1])[z-1], // bottom
1808                          (*columns[2])[z-1], (*columns[i3])[z-1],
1809                          (*columns[0])[z],   (*columns[i1])[z],     // top
1810                          (*columns[2])[z],   (*columns[i3])[z] );
1811     break;
1812   }
1813   case 6: { // ---------- octahedra
1814     const int iBase1 = isForward ? -1 : 0;
1815     const int iBase2 = isForward ?  0 :-1;
1816     for ( z = 1; z < nbZ; ++z )
1817       helper->AddVolume( (*columns[0])[z+iBase1], (*columns[1])[z+iBase1], // bottom or top
1818                          (*columns[2])[z+iBase1], (*columns[3])[z+iBase1],
1819                          (*columns[4])[z+iBase1], (*columns[5])[z+iBase1],
1820                          (*columns[0])[z+iBase2], (*columns[1])[z+iBase2], // top or bottom
1821                          (*columns[2])[z+iBase2], (*columns[3])[z+iBase2],
1822                          (*columns[4])[z+iBase2], (*columns[5])[z+iBase2] );
1823     break;
1824   }
1825   default: // ---------- polyhedra
1826     vector<int> quantities( 2 + nbNodes, 4 );
1827     quantities[0] = quantities[1] = nbNodes;
1828     columns.resize( nbNodes + 1 );
1829     columns[ nbNodes ] = columns[ 0 ];
1830     const int i1 = isForward ? 1 : 3;
1831     const int i3 = isForward ? 3 : 1;
1832     const int iBase1 = isForward ? -1 : 0;
1833     const int iBase2 = isForward ?  0 :-1;
1834     vector<const SMDS_MeshNode*> nodes( 2*nbNodes + 4*nbNodes);
1835     for ( z = 1; z < nbZ; ++z )
1836     {
1837       for ( int i = 0; i < nbNodes; ++i ) {
1838         nodes[ i             ] = (*columns[ i ])[z+iBase1]; // bottom or top
1839         nodes[ 2*nbNodes-i-1 ] = (*columns[ i ])[z+iBase2]; // top or bottom
1840         // side
1841         int di = 2*nbNodes + 4*i;
1842         nodes[ di+0 ] = (*columns[i  ])[z  ];
1843         nodes[ di+i1] = (*columns[i+1])[z  ];
1844         nodes[ di+2 ] = (*columns[i+1])[z-1];
1845         nodes[ di+i3] = (*columns[i  ])[z-1];
1846       }
1847       helper->AddPolyhedralVolume( nodes, quantities );
1848     }
1849
1850   } // switch ( nbNodes )
1851 }
1852
1853 //================================================================================
1854 /*!
1855  * \brief Find correspondence between bottom and top nodes
1856  *  If elements on the bottom and top faces are topologically different,
1857  *  and projection is possible and allowed, perform the projection
1858  *  \retval bool - is a success or not
1859  */
1860 //================================================================================
1861
1862 bool StdMeshers_Prism_3D::assocOrProjBottom2Top( const gp_Trsf & bottomToTopTrsf,
1863                                                  const Prism_3D::TPrismTopo& thePrism)
1864 {
1865   SMESH_subMesh * botSM = myHelper->GetMesh()->GetSubMesh( thePrism.myBottom );
1866   SMESH_subMesh * topSM = myHelper->GetMesh()->GetSubMesh( thePrism.myTop    );
1867
1868   SMESHDS_SubMesh * botSMDS = botSM->GetSubMeshDS();
1869   SMESHDS_SubMesh * topSMDS = topSM->GetSubMeshDS();
1870
1871   if ( !botSMDS || botSMDS->NbElements() == 0 )
1872   {
1873     _gen->Compute( *myHelper->GetMesh(), botSM->GetSubShape(), /*aShapeOnly=*/true );
1874     botSMDS = botSM->GetSubMeshDS();
1875     if ( !botSMDS || botSMDS->NbElements() == 0 )
1876       return toSM( error(TCom("No elements on face #") << botSM->GetId() ));
1877   }
1878
1879   bool needProject = !topSM->IsMeshComputed();
1880   if ( !needProject &&
1881        (botSMDS->NbElements() != topSMDS->NbElements() ||
1882         botSMDS->NbNodes()    != topSMDS->NbNodes()))
1883   {
1884     MESSAGE("nb elem bot " << botSMDS->NbElements() <<
1885             " top " << ( topSMDS ? topSMDS->NbElements() : 0 ));
1886     MESSAGE("nb node bot " << botSMDS->NbNodes() <<
1887             " top " << ( topSMDS ? topSMDS->NbNodes() : 0 ));
1888     return toSM( error(TCom("Mesh on faces #") << botSM->GetId()
1889                        <<" and #"<< topSM->GetId() << " seems different" ));
1890   }
1891
1892   if ( 0/*needProject && !myProjectTriangles*/ )
1893     return toSM( error(TCom("Mesh on faces #") << botSM->GetId()
1894                        <<" and #"<< topSM->GetId() << " seems different" ));
1895   ///RETURN_BAD_RESULT("Need to project but not allowed");
1896
1897   NSProjUtils::TNodeNodeMap n2nMap;
1898   const NSProjUtils::TNodeNodeMap* n2nMapPtr = & n2nMap;
1899   if ( needProject )
1900   {
1901     if ( !projectBottomToTop( bottomToTopTrsf, thePrism ))
1902       return false;
1903     n2nMapPtr = & TProjction2dAlgo::instance( this )->GetNodesMap();
1904   }
1905
1906   if ( !n2nMapPtr || n2nMapPtr->size() < botSMDS->NbNodes() )
1907   {
1908     // associate top and bottom faces
1909     NSProjUtils::TShapeShapeMap shape2ShapeMap;
1910     const bool sameTopo =
1911       NSProjUtils::FindSubShapeAssociation( thePrism.myBottom, myHelper->GetMesh(),
1912                                            thePrism.myTop,    myHelper->GetMesh(),
1913                                            shape2ShapeMap);
1914     if ( !sameTopo )
1915       for ( size_t iQ = 0; iQ < thePrism.myWallQuads.size(); ++iQ )
1916       {
1917         const Prism_3D::TQuadList& quadList = thePrism.myWallQuads[iQ];
1918         StdMeshers_FaceSidePtr      botSide = quadList.front()->side[ QUAD_BOTTOM_SIDE ];
1919         StdMeshers_FaceSidePtr      topSide = quadList.back ()->side[ QUAD_TOP_SIDE ];
1920         if ( botSide->NbEdges() == topSide->NbEdges() )
1921         {
1922           for ( int iE = 0; iE < botSide->NbEdges(); ++iE )
1923           {
1924             NSProjUtils::InsertAssociation( botSide->Edge( iE ),
1925                                            topSide->Edge( iE ), shape2ShapeMap );
1926             NSProjUtils::InsertAssociation( myHelper->IthVertex( 0, botSide->Edge( iE )),
1927                                            myHelper->IthVertex( 0, topSide->Edge( iE )),
1928                                            shape2ShapeMap );
1929           }
1930         }
1931         else
1932         {
1933           TopoDS_Vertex vb, vt;
1934           StdMeshers_FaceSidePtr sideB, sideT;
1935           vb = myHelper->IthVertex( 0, botSide->Edge( 0 ));
1936           vt = myHelper->IthVertex( 0, topSide->Edge( 0 ));
1937           sideB = quadList.front()->side[ QUAD_LEFT_SIDE ];
1938           sideT = quadList.back ()->side[ QUAD_LEFT_SIDE ];
1939           if ( vb.IsSame( sideB->FirstVertex() ) &&
1940                vt.IsSame( sideT->LastVertex() ))
1941           {
1942             NSProjUtils::InsertAssociation( botSide->Edge( 0 ),
1943                                            topSide->Edge( 0 ), shape2ShapeMap );
1944             NSProjUtils::InsertAssociation( vb, vt, shape2ShapeMap );
1945           }
1946           vb = myHelper->IthVertex( 1, botSide->Edge( botSide->NbEdges()-1 ));
1947           vt = myHelper->IthVertex( 1, topSide->Edge( topSide->NbEdges()-1 ));
1948           sideB = quadList.front()->side[ QUAD_RIGHT_SIDE ];
1949           sideT = quadList.back ()->side[ QUAD_RIGHT_SIDE ];
1950           if ( vb.IsSame( sideB->FirstVertex() ) &&
1951                vt.IsSame( sideT->LastVertex() ))
1952           {
1953             NSProjUtils::InsertAssociation( botSide->Edge( botSide->NbEdges()-1 ),
1954                                            topSide->Edge( topSide->NbEdges()-1 ),
1955                                            shape2ShapeMap );
1956             NSProjUtils::InsertAssociation( vb, vt, shape2ShapeMap );
1957           }
1958         }
1959       }
1960
1961     // Find matching nodes of top and bottom faces
1962     n2nMapPtr = & n2nMap;
1963     if ( ! NSProjUtils::FindMatchingNodesOnFaces( thePrism.myBottom, myHelper->GetMesh(),
1964                                                  thePrism.myTop,    myHelper->GetMesh(),
1965                                                  shape2ShapeMap, n2nMap ))
1966     {
1967       if ( sameTopo )
1968         return toSM( error(TCom("Mesh on faces #") << botSM->GetId()
1969                            <<" and #"<< topSM->GetId() << " seems different" ));
1970       else
1971         return toSM( error(TCom("Topology of faces #") << botSM->GetId()
1972                            <<" and #"<< topSM->GetId() << " seems different" ));
1973     }
1974   }
1975
1976   // Fill myBotToColumnMap
1977
1978   int zSize = myBlock.VerticalSize();
1979   TNodeNodeMap::const_iterator bN_tN = n2nMapPtr->begin();
1980   for ( ; bN_tN != n2nMapPtr->end(); ++bN_tN )
1981   {
1982     const SMDS_MeshNode* botNode = bN_tN->first;
1983     const SMDS_MeshNode* topNode = bN_tN->second;
1984     if ( botNode->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE )
1985       continue; // wall columns are contained in myBlock
1986     // create node column
1987     Prism_3D::TNode bN( botNode );
1988     TNode2ColumnMap::iterator bN_col = 
1989       myBotToColumnMap.insert( make_pair ( bN, TNodeColumn() )).first;
1990     TNodeColumn & column = bN_col->second;
1991     column.resize( zSize );
1992     column.front() = botNode;
1993     column.back()  = topNode;
1994   }
1995   return true;
1996 }
1997
1998 //================================================================================
1999 /*!
2000  * \brief Remove faces from the top face and re-create them by projection from the bottom
2001  * \retval bool - a success or not
2002  */
2003 //================================================================================
2004
2005 bool StdMeshers_Prism_3D::projectBottomToTop( const gp_Trsf &             bottomToTopTrsf,
2006                                               const Prism_3D::TPrismTopo& thePrism )
2007 {
2008   if ( project2dMesh( thePrism.myBottom, thePrism.myTop ))
2009   {
2010     return true;
2011   }
2012
2013   SMESHDS_Mesh*  meshDS = myHelper->GetMeshDS();
2014   SMESH_subMesh * botSM = myHelper->GetMesh()->GetSubMesh( thePrism.myBottom );
2015   SMESH_subMesh * topSM = myHelper->GetMesh()->GetSubMesh( thePrism.myTop );
2016
2017   SMESHDS_SubMesh * botSMDS = botSM->GetSubMeshDS();
2018   SMESHDS_SubMesh * topSMDS = topSM->GetSubMeshDS();
2019
2020   if ( topSMDS && topSMDS->NbElements() > 0 )
2021     topSM->ComputeStateEngine( SMESH_subMesh::CLEAN );
2022
2023   const TopoDS_Face& botFace = thePrism.myBottom; // oriented within
2024   const TopoDS_Face& topFace = thePrism.myTop;    //    the 3D SHAPE
2025   int topFaceID = meshDS->ShapeToIndex( thePrism.myTop );
2026
2027   SMESH_MesherHelper botHelper( *myHelper->GetMesh() );
2028   botHelper.SetSubShape( botFace );
2029   botHelper.ToFixNodeParameters( true );
2030   bool checkUV;
2031   SMESH_MesherHelper topHelper( *myHelper->GetMesh() );
2032   topHelper.SetSubShape( topFace );
2033   topHelper.ToFixNodeParameters( true );
2034   double distXYZ[4], fixTol = 10 * topHelper.MaxTolerance( topFace );
2035
2036   // Fill myBotToColumnMap
2037
2038   int zSize = myBlock.VerticalSize();
2039   Prism_3D::TNode prevTNode;
2040   SMDS_NodeIteratorPtr nIt = botSMDS->GetNodes();
2041   while ( nIt->more() )
2042   {
2043     const SMDS_MeshNode* botNode = nIt->next();
2044     const SMDS_MeshNode* topNode = 0;
2045     if ( botNode->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE )
2046       continue; // strange
2047
2048     Prism_3D::TNode bN( botNode );
2049     if ( bottomToTopTrsf.Form() == gp_Identity )
2050     {
2051       // compute bottom node params
2052       gp_XYZ paramHint(-1,-1,-1);
2053       if ( prevTNode.IsNeighbor( bN ))
2054       {
2055         paramHint = prevTNode.GetParams();
2056         // double tol = 1e-2 * ( prevTNode.GetCoords() - bN.GetCoords() ).Modulus();
2057         // myBlock.SetTolerance( Min( myBlock.GetTolerance(), tol ));
2058       }
2059       if ( !myBlock.ComputeParameters( bN.GetCoords(), bN.ChangeParams(),
2060                                        ID_BOT_FACE, paramHint ))
2061         return toSM( error(TCom("Can't compute normalized parameters for node ")
2062                            << botNode->GetID() << " on the face #"<< botSM->GetId() ));
2063       prevTNode = bN;
2064       // compute top node coords
2065       gp_XYZ topXYZ; gp_XY topUV;
2066       if ( !myBlock.FacePoint( ID_TOP_FACE, bN.GetParams(), topXYZ ) ||
2067            !myBlock.FaceUV   ( ID_TOP_FACE, bN.GetParams(), topUV ))
2068         return toSM( error(TCom("Can't compute coordinates "
2069                                 "by normalized parameters on the face #")<< topSM->GetId() ));
2070       topNode = meshDS->AddNode( topXYZ.X(),topXYZ.Y(),topXYZ.Z() );
2071       meshDS->SetNodeOnFace( topNode, topFaceID, topUV.X(), topUV.Y() );
2072     }
2073     else // use bottomToTopTrsf
2074     {
2075       gp_XYZ coords = bN.GetCoords();
2076       bottomToTopTrsf.Transforms( coords );
2077       topNode = meshDS->AddNode( coords.X(), coords.Y(), coords.Z() );
2078       gp_XY topUV = botHelper.GetNodeUV( botFace, botNode, 0, &checkUV );
2079       meshDS->SetNodeOnFace( topNode, topFaceID, topUV.X(), topUV.Y() );
2080       distXYZ[0] = -1;
2081       if ( topHelper.CheckNodeUV( topFace, topNode, topUV, fixTol, /*force=*/false, distXYZ ) &&
2082            distXYZ[0] > fixTol && distXYZ[0] < fixTol * 1e+3 )
2083         meshDS->MoveNode( topNode, distXYZ[1], distXYZ[2], distXYZ[3] ); // transform can be inaccurate
2084     }
2085     // create node column
2086     TNode2ColumnMap::iterator bN_col = 
2087       myBotToColumnMap.insert( make_pair ( bN, TNodeColumn() )).first;
2088     TNodeColumn & column = bN_col->second;
2089     column.resize( zSize );
2090     column.front() = botNode;
2091     column.back()  = topNode;
2092
2093     if ( _computeCanceled )
2094       return toSM( error( SMESH_ComputeError::New(COMPERR_CANCELED)));
2095   }
2096
2097   // Create top faces
2098
2099   const bool oldSetElemsOnShape = myHelper->SetElementsOnShape( false );
2100
2101   // care of orientation;
2102   // if the bottom faces is orienetd OK then top faces must be reversed
2103   bool reverseTop = true;
2104   if ( myHelper->NbAncestors( botFace, *myBlock.Mesh(), TopAbs_SOLID ) > 1 )
2105     reverseTop = ! myHelper->IsReversedSubMesh( botFace );
2106   int iFrw, iRev, *iPtr = &( reverseTop ? iRev : iFrw );
2107
2108   // loop on bottom mesh faces
2109   SMDS_ElemIteratorPtr faceIt = botSMDS->GetElements();
2110   vector< const SMDS_MeshNode* > nodes;
2111   while ( faceIt->more() )
2112   {
2113     const SMDS_MeshElement* face = faceIt->next();
2114     if ( !face || face->GetType() != SMDSAbs_Face )
2115       continue;
2116
2117     // find top node in columns for each bottom node
2118     int nbNodes = face->NbCornerNodes();
2119     nodes.resize( nbNodes );
2120     for ( iFrw = 0, iRev = nbNodes-1; iFrw < nbNodes; ++iFrw, --iRev )
2121     {
2122       const SMDS_MeshNode* n = face->GetNode( *iPtr );
2123       if ( n->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE ) {
2124         TNode2ColumnMap::iterator bot_column = myBotToColumnMap.find( n );
2125         if ( bot_column == myBotToColumnMap.end() )
2126           return toSM( error(TCom("No nodes found above node ") << n->GetID() ));
2127         nodes[ iFrw ] = bot_column->second.back();
2128       }
2129       else {
2130         const TNodeColumn* column = myBlock.GetNodeColumn( n );
2131         if ( !column )
2132           return toSM( error(TCom("No side nodes found above node ") << n->GetID() ));
2133         nodes[ iFrw ] = column->back();
2134       }
2135     }
2136     SMDS_MeshElement* newFace = 0;
2137     switch ( nbNodes ) {
2138
2139     case 3: {
2140       newFace = myHelper->AddFace(nodes[0], nodes[1], nodes[2]);
2141       break;
2142       }
2143     case 4: {
2144       newFace = myHelper->AddFace( nodes[0], nodes[1], nodes[2], nodes[3] );
2145       break;
2146       }
2147     default:
2148       newFace = meshDS->AddPolygonalFace( nodes );
2149     }
2150     if ( newFace )
2151       meshDS->SetMeshElementOnShape( newFace, topFaceID );
2152   }
2153
2154   myHelper->SetElementsOnShape( oldSetElemsOnShape );  
2155
2156   return true;
2157 }
2158
2159 //=======================================================================
2160 //function : getSweepTolerance
2161 //purpose  : Compute tolerance to pass to StdMeshers_Sweeper
2162 //=======================================================================
2163
2164 double StdMeshers_Prism_3D::getSweepTolerance( const Prism_3D::TPrismTopo& thePrism )
2165 {
2166   SMESHDS_Mesh*    meshDS = myHelper->GetMeshDS();
2167   SMESHDS_SubMesh * sm[2] = { meshDS->MeshElements( thePrism.myBottom ),
2168                               meshDS->MeshElements( thePrism.myTop )    };
2169   double minDist = 1e100;
2170
2171   vector< SMESH_TNodeXYZ > nodes;
2172   for ( int iSM = 0; iSM < 2; ++iSM )
2173   {
2174     if ( !sm[ iSM ]) continue;
2175
2176     SMDS_ElemIteratorPtr fIt = sm[ iSM ]->GetElements();
2177     while ( fIt->more() )
2178     {
2179       const SMDS_MeshElement* face = fIt->next();
2180       const int            nbNodes = face->NbCornerNodes();
2181       SMDS_ElemIteratorPtr     nIt = face->nodesIterator();
2182
2183       nodes.resize( nbNodes + 1 );
2184       for ( int iN = 0; iN < nbNodes; ++iN )
2185         nodes[ iN ] = nIt->next();
2186       nodes.back() = nodes[0];
2187       
2188       // loop on links
2189       double dist2;
2190       for ( int iN = 0; iN < nbNodes; ++iN )
2191       {
2192         if ( nodes[ iN   ]._node->GetPosition()->GetDim() < 2 &&
2193              nodes[ iN+1 ]._node->GetPosition()->GetDim() < 2 )
2194         {
2195           // it's a boundary link; measure distance of other
2196           // nodes to this link
2197           gp_XYZ linkDir = nodes[ iN ] - nodes[ iN+1 ];
2198           double linkLen = linkDir.Modulus();
2199           bool   isDegen = ( linkLen < numeric_limits<double>::min() );
2200           if ( !isDegen ) linkDir /= linkLen;
2201           for ( int iN2 = 0; iN2 < nbNodes; ++iN2 ) // loop on other nodes
2202           {
2203             if ( nodes[ iN2 ] == nodes[ iN ] ||
2204                  nodes[ iN2 ] == nodes[ iN+1 ]) continue;
2205             if ( isDegen )
2206             {
2207               dist2 = ( nodes[ iN ] - nodes[ iN2 ]).SquareModulus();
2208             }
2209             else
2210             {
2211               dist2 = linkDir.CrossSquareMagnitude( nodes[ iN ] - nodes[ iN2 ]);
2212             }
2213             if ( dist2 > numeric_limits<double>::min() )
2214               minDist = Min ( minDist, dist2 );
2215           }
2216         }
2217         // measure length link
2218         else if ( nodes[ iN ]._node < nodes[ iN+1 ]._node ) // not to measure same link twice
2219         {
2220           dist2 = ( nodes[ iN ] - nodes[ iN+1 ]).SquareModulus();
2221           if ( dist2 > numeric_limits<double>::min() )
2222             minDist = Min ( minDist, dist2 );
2223         }
2224       }
2225     }
2226   }
2227   return 0.1 * Sqrt ( minDist );
2228 }
2229
2230 //=======================================================================
2231 //function : project2dMesh
2232 //purpose  : Project mesh faces from a source FACE of one prism (theSrcFace)
2233 //           to a source FACE of another prism (theTgtFace)
2234 //=======================================================================
2235
2236 bool StdMeshers_Prism_3D::project2dMesh(const TopoDS_Face& theSrcFace,
2237                                         const TopoDS_Face& theTgtFace)
2238 {
2239   TProjction2dAlgo* projector2D = TProjction2dAlgo::instance( this );
2240   projector2D->myHyp.SetSourceFace( theSrcFace );
2241   bool ok = projector2D->Compute( *myHelper->GetMesh(), theTgtFace );
2242
2243   SMESH_subMesh* tgtSM = myHelper->GetMesh()->GetSubMesh( theTgtFace );
2244   tgtSM->ComputeStateEngine       ( SMESH_subMesh::CHECK_COMPUTE_STATE );
2245   tgtSM->ComputeSubMeshStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
2246
2247   return ok;
2248 }
2249
2250 //================================================================================
2251 /*!
2252  * \brief Set projection coordinates of a node to a face and it's sub-shapes
2253  * \param faceID - the face given by in-block ID
2254  * \param params - node normalized parameters
2255  * \retval bool - is a success
2256  */
2257 //================================================================================
2258
2259 bool StdMeshers_Prism_3D::setFaceAndEdgesXYZ( const int faceID, const gp_XYZ& params, int z )
2260 {
2261   // find base and top edges of the face
2262   enum { BASE = 0, TOP, LEFT, RIGHT };
2263   vector< int > edgeVec; // 0-base, 1-top
2264   SMESH_Block::GetFaceEdgesIDs( faceID, edgeVec );
2265
2266   myBlock.EdgePoint( edgeVec[ BASE ], params, myShapeXYZ[ edgeVec[ BASE ]]);
2267   myBlock.EdgePoint( edgeVec[ TOP  ], params, myShapeXYZ[ edgeVec[ TOP ]]);
2268
2269   SHOWYXZ("\nparams ", params);
2270   SHOWYXZ("TOP is " <<edgeVec[ TOP ], myShapeXYZ[ edgeVec[ TOP]]);
2271   SHOWYXZ("BASE is "<<edgeVec[ BASE], myShapeXYZ[ edgeVec[ BASE]]);
2272
2273   if ( faceID == SMESH_Block::ID_Fx0z || faceID == SMESH_Block::ID_Fx1z )
2274   {
2275     myBlock.EdgePoint( edgeVec[ LEFT ], params, myShapeXYZ[ edgeVec[ LEFT ]]);
2276     myBlock.EdgePoint( edgeVec[ RIGHT ], params, myShapeXYZ[ edgeVec[ RIGHT ]]);
2277
2278     SHOWYXZ("VER "<<edgeVec[ LEFT], myShapeXYZ[ edgeVec[ LEFT]]);
2279     SHOWYXZ("VER "<<edgeVec[ RIGHT], myShapeXYZ[ edgeVec[ RIGHT]]);
2280   }
2281   myBlock.FacePoint( faceID, params, myShapeXYZ[ faceID ]);
2282   SHOWYXZ("FacePoint "<<faceID, myShapeXYZ[ faceID]);
2283
2284   return true;
2285 }
2286
2287 //=======================================================================
2288 //function : toSM
2289 //purpose  : If (!isOK), sets the error to a sub-mesh of a current SOLID
2290 //=======================================================================
2291
2292 bool StdMeshers_Prism_3D::toSM( bool isOK )
2293 {
2294   if ( mySetErrorToSM &&
2295        !isOK &&
2296        myHelper &&
2297        !myHelper->GetSubShape().IsNull() &&
2298        myHelper->GetSubShape().ShapeType() == TopAbs_SOLID)
2299   {
2300     SMESH_subMesh* sm = myHelper->GetMesh()->GetSubMesh( myHelper->GetSubShape() );
2301     sm->GetComputeError() = this->GetComputeError();
2302     // clear error in order not to return it twice
2303     _error = COMPERR_OK;
2304     _comment.clear();
2305   }
2306   return isOK;
2307 }
2308
2309 //=======================================================================
2310 //function : shapeID
2311 //purpose  : Return index of a shape
2312 //=======================================================================
2313
2314 int StdMeshers_Prism_3D::shapeID( const TopoDS_Shape& S )
2315 {
2316   if ( S.IsNull() ) return 0;
2317   if ( !myHelper  ) return -3;
2318   return myHelper->GetMeshDS()->ShapeToIndex( S );
2319 }
2320
2321 namespace // utils used by StdMeshers_Prism_3D::IsApplicable()
2322 {
2323   struct EdgeWithNeighbors
2324   {
2325     TopoDS_Edge _edge;
2326     int         _iL, _iR;
2327     EdgeWithNeighbors(const TopoDS_Edge& E, int iE, int nbE, int shift = 0 ):
2328       _edge( E ),
2329       _iL( SMESH_MesherHelper::WrapIndex( iE-1, nbE ) + shift ),
2330       _iR( SMESH_MesherHelper::WrapIndex( iE+1, nbE ) + shift )
2331     {
2332     }
2333     EdgeWithNeighbors() {}
2334   };
2335   struct PrismSide
2336   {
2337     TopoDS_Face                 _face;
2338     TopTools_IndexedMapOfShape *_faces; // pointer because its copy constructor is private
2339     TopoDS_Edge                 _topEdge;
2340     vector< EdgeWithNeighbors >*_edges;
2341     int                         _iBotEdge;
2342     vector< bool >              _isCheckedEdge;
2343     int                         _nbCheckedEdges; // nb of EDGEs whose location is defined
2344     PrismSide                  *_leftSide;
2345     PrismSide                  *_rightSide;
2346     const TopoDS_Edge& Edge( int i ) const
2347     {
2348       return (*_edges)[ i ]._edge;
2349     }
2350     int FindEdge( const TopoDS_Edge& E ) const
2351     {
2352       for ( size_t i = 0; i < _edges->size(); ++i )
2353         if ( E.IsSame( Edge( i ))) return i;
2354       return -1;
2355     }
2356     bool IsSideFace( const TopoDS_Shape& face ) const
2357     {
2358       if ( _faces->Contains( face )) // avoid returning true for a prism top FACE
2359         return ( !_face.IsNull() || !( face.IsSame( _faces->FindKey( _faces->Extent() ))));
2360       return false;
2361     }
2362   };
2363   //--------------------------------------------------------------------------------
2364   /*!
2365    * \brief Return ordered edges of a face
2366    */
2367   bool getEdges( const TopoDS_Face&            face,
2368                  vector< EdgeWithNeighbors > & edges,
2369                  const bool                    noHolesAllowed)
2370   {
2371     list< TopoDS_Edge > ee;
2372     list< int >         nbEdgesInWires;
2373     int nbW = SMESH_Block::GetOrderedEdges( face, ee, nbEdgesInWires );
2374     if ( nbW > 1 && noHolesAllowed )
2375       return false;
2376
2377     int iE, nbTot = 0;
2378     list< TopoDS_Edge >::iterator e = ee.begin();
2379     list< int >::iterator       nbE = nbEdgesInWires.begin();
2380     for ( ; nbE != nbEdgesInWires.end(); ++nbE )
2381       for ( iE = 0; iE < *nbE; ++e, ++iE )
2382         if ( SMESH_Algo::isDegenerated( *e ))
2383         {
2384           ee.erase( e );
2385           --(*nbE);
2386           --iE;
2387         }
2388         else
2389         {
2390           e->Orientation( TopAbs_FORWARD ); // for operator==() to work
2391         }
2392
2393     edges.clear();
2394     e = ee.begin();
2395     for ( nbE = nbEdgesInWires.begin(); nbE != nbEdgesInWires.end(); ++nbE )
2396     {
2397       for ( iE = 0; iE < *nbE; ++e, ++iE )
2398         edges.push_back( EdgeWithNeighbors( *e, iE, *nbE, nbTot ));
2399       nbTot += *nbE;
2400     }
2401     return edges.size();
2402   }
2403   //--------------------------------------------------------------------------------
2404   /*!
2405    * \brief Return another faces sharing an edge
2406    */
2407   const TopoDS_Shape & getAnotherFace( const TopoDS_Face& face,
2408                                        const TopoDS_Edge& edge,
2409                                        TopTools_IndexedDataMapOfShapeListOfShape& facesOfEdge)
2410   {
2411     TopTools_ListIteratorOfListOfShape faceIt( facesOfEdge.FindFromKey( edge ));
2412     for ( ; faceIt.More(); faceIt.Next() )
2413       if ( !face.IsSame( faceIt.Value() ))
2414         return faceIt.Value();
2415     return face;
2416   }
2417 }
2418
2419 //================================================================================
2420 /*!
2421  * \brief Return true if the algorithm can mesh this shape
2422  *  \param [in] aShape - shape to check
2423  *  \param [in] toCheckAll - if true, this check returns OK if all shapes are OK,
2424  *              else, returns OK if at least one shape is OK
2425  */
2426 //================================================================================
2427
2428 bool StdMeshers_Prism_3D::IsApplicable(const TopoDS_Shape & shape, bool toCheckAll)
2429 {
2430   TopExp_Explorer sExp( shape, TopAbs_SOLID );
2431   if ( !sExp.More() )
2432     return false;
2433
2434   for ( ; sExp.More(); sExp.Next() )
2435   {
2436     // check nb shells
2437     TopoDS_Shape shell;
2438     TopExp_Explorer shExp( sExp.Current(), TopAbs_SHELL );
2439     if ( shExp.More() ) {
2440       shell = shExp.Current();
2441       shExp.Next();
2442       if ( shExp.More() )
2443         shell.Nullify();
2444     }
2445     if ( shell.IsNull() ) {
2446       if ( toCheckAll ) return false;
2447       continue;
2448     }
2449     // get all faces
2450     TopTools_IndexedMapOfShape allFaces;
2451     TopExp::MapShapes( shell, TopAbs_FACE, allFaces );
2452     if ( allFaces.Extent() < 3 ) {
2453       if ( toCheckAll ) return false;
2454       continue;
2455     }
2456     // is a box?
2457     if ( allFaces.Extent() == 6 )
2458     {
2459       TopTools_IndexedMapOfOrientedShape map;
2460       bool isBox = SMESH_Block::FindBlockShapes( TopoDS::Shell( shell ),
2461                                                  TopoDS_Vertex(), TopoDS_Vertex(), map );
2462       if ( isBox ) {
2463         if ( !toCheckAll ) return true;
2464         continue;
2465       }
2466     }
2467 #ifdef _DEBUG_
2468     TopTools_IndexedMapOfShape allShapes;
2469     TopExp::MapShapes( shape, allShapes );
2470 #endif
2471
2472     TopTools_IndexedDataMapOfShapeListOfShape facesOfEdge;
2473     TopTools_ListIteratorOfListOfShape faceIt;
2474     TopExp::MapShapesAndAncestors( sExp.Current(), TopAbs_EDGE, TopAbs_FACE , facesOfEdge );
2475     if ( facesOfEdge.IsEmpty() ) {
2476       if ( toCheckAll ) return false;
2477       continue;
2478     }
2479
2480     typedef vector< EdgeWithNeighbors > TEdgeWithNeighborsVec;
2481     vector< TEdgeWithNeighborsVec > faceEdgesVec( allFaces.Extent() + 1 );
2482     TopTools_IndexedMapOfShape* facesOfSide = new TopTools_IndexedMapOfShape[ faceEdgesVec.size() ];
2483     SMESHUtils::ArrayDeleter<TopTools_IndexedMapOfShape> delFacesOfSide( facesOfSide );
2484
2485     // try to use each face as a bottom one
2486     bool prismDetected = false;
2487     for ( int iF = 1; iF < allFaces.Extent() && !prismDetected; ++iF )
2488     {
2489       const TopoDS_Face& botF = TopoDS::Face( allFaces( iF ));
2490
2491       TEdgeWithNeighborsVec& botEdges = faceEdgesVec[ iF ];
2492       if ( botEdges.empty() )
2493         if ( !getEdges( botF, botEdges, /*noHoles=*/false ))
2494           break;
2495       if ( allFaces.Extent()-1 <= (int) botEdges.size() )
2496         continue; // all faces are adjacent to botF - no top FACE
2497
2498       // init data of side FACEs
2499       vector< PrismSide > sides( botEdges.size() );
2500       for ( int iS = 0; iS < botEdges.size(); ++iS )
2501       {
2502         sides[ iS ]._topEdge = botEdges[ iS ]._edge;
2503         sides[ iS ]._face    = botF;
2504         sides[ iS ]._leftSide  = & sides[ botEdges[ iS ]._iR ];
2505         sides[ iS ]._rightSide = & sides[ botEdges[ iS ]._iL ];
2506         sides[ iS ]._faces = & facesOfSide[ iS ];
2507         sides[ iS ]._faces->Clear();
2508       }
2509
2510       bool isOK = true; // ok for a current botF
2511       bool isAdvanced = true; // is new data found in a current loop
2512       int  nbFoundSideFaces = 0;
2513       for ( int iLoop = 0; isOK && isAdvanced; ++iLoop )
2514       {
2515         isAdvanced = false;
2516         for ( size_t iS = 0; iS < sides.size() && isOK; ++iS )
2517         {
2518           PrismSide& side = sides[ iS ];
2519           if ( side._face.IsNull() )
2520             continue; // probably the prism top face is the last of side._faces
2521
2522           if ( side._topEdge.IsNull() )
2523           {
2524             // find vertical EDGEs --- EGDEs shared with neighbor side FACEs
2525             for ( int is2nd = 0; is2nd < 2 && isOK; ++is2nd ) // 2 adjacent neighbors
2526             {
2527               int di = is2nd ? 1 : -1;
2528               const PrismSide* adjSide = is2nd ? side._rightSide : side._leftSide;
2529               for ( size_t i = 1; i < side._edges->size(); ++i )
2530               {
2531                 int iE = SMESH_MesherHelper::WrapIndex( i*di + side._iBotEdge, side._edges->size());
2532                 if ( side._isCheckedEdge[ iE ] ) continue;
2533                 const TopoDS_Edge&      vertE = side.Edge( iE );
2534                 const TopoDS_Shape& neighborF = getAnotherFace( side._face, vertE, facesOfEdge );
2535                 bool isEdgeShared = adjSide->IsSideFace( neighborF );
2536                 if ( isEdgeShared )
2537                 {
2538                   isAdvanced = true;
2539                   side._isCheckedEdge[ iE ] = true;
2540                   side._nbCheckedEdges++;
2541                   int nbNotCheckedE = side._edges->size() - side._nbCheckedEdges;
2542                   if ( nbNotCheckedE == 1 )
2543                     break;
2544                 }
2545                 else
2546                 {
2547                   if ( i == 1 && iLoop == 0 ) isOK = false;
2548                   break;
2549                 }
2550               }
2551             }
2552             // find a top EDGE
2553             int nbNotCheckedE = side._edges->size() - side._nbCheckedEdges;
2554             if ( nbNotCheckedE == 1 )
2555             {
2556               vector<bool>::iterator ii = std::find( side._isCheckedEdge.begin(),
2557                                                      side._isCheckedEdge.end(), false );
2558               if ( ii != side._isCheckedEdge.end() )
2559               {
2560                 size_t iE = std::distance( side._isCheckedEdge.begin(), ii );
2561                 side._topEdge = side.Edge( iE );
2562               }
2563             }
2564             isOK = ( nbNotCheckedE >= 1 );
2565           }
2566           else //if ( !side._topEdge.IsNull() )
2567           {
2568             // get a next face of a side
2569             const TopoDS_Shape& f = getAnotherFace( side._face, side._topEdge, facesOfEdge );
2570             side._faces->Add( f );
2571             bool stop = false;
2572             if ( f.IsSame( side._face ) || // _topEdge is a seam
2573                  SMESH_MesherHelper::Count( f, TopAbs_WIRE, false ) != 1 )
2574             {
2575               stop = true;
2576             }
2577             else if ( side._leftSide != & side ) // not closed side face
2578             {
2579               if ( side._leftSide->_faces->Contains( f ))
2580               {
2581                 stop = true; // probably f is the prism top face
2582                 side._leftSide->_face.Nullify();
2583                 side._leftSide->_topEdge.Nullify();
2584               }
2585               if ( side._rightSide->_faces->Contains( f ))
2586               {
2587                 stop = true; // probably f is the prism top face
2588                 side._rightSide->_face.Nullify();
2589                 side._rightSide->_topEdge.Nullify();
2590               }
2591             }
2592             if ( stop )
2593             {
2594               side._face.Nullify();
2595               side._topEdge.Nullify();
2596               continue;
2597             }
2598             side._face  = TopoDS::Face( f );
2599             int faceID  = allFaces.FindIndex( side._face );
2600             side._edges = & faceEdgesVec[ faceID ];
2601             if ( side._edges->empty() )
2602               if ( !getEdges( side._face, * side._edges, /*noHoles=*/true ))
2603                 break;
2604             const int nbE = side._edges->size();
2605             if ( nbE >= 4 )
2606             {
2607               isAdvanced = true;
2608               ++nbFoundSideFaces;
2609               side._iBotEdge = side.FindEdge( side._topEdge );
2610               side._isCheckedEdge.clear();
2611               side._isCheckedEdge.resize( nbE, false );
2612               side._isCheckedEdge[ side._iBotEdge ] = true;
2613               side._nbCheckedEdges = 1; // bottom EDGE is known
2614             }
2615             side._topEdge.Nullify();
2616             isOK = ( !side._edges->empty() || side._faces->Extent() > 1 );
2617
2618           } //if ( !side._topEdge.IsNull() )
2619
2620         } // loop on prism sides
2621
2622         if ( nbFoundSideFaces > allFaces.Extent() )
2623         {
2624           isOK = false;
2625         }
2626         if ( iLoop > allFaces.Extent() * 10 )
2627         {
2628           isOK = false;
2629 #ifdef _DEBUG_
2630           cerr << "BUG: infinite loop in StdMeshers_Prism_3D::IsApplicable()" << endl;
2631 #endif
2632         }
2633       } // while isAdvanced
2634
2635       if ( isOK && sides[0]._faces->Extent() > 1 )
2636       {
2637         const int nbFaces = sides[0]._faces->Extent();
2638         if ( botEdges.size() == 1 ) // cylinder
2639         {
2640           prismDetected = ( nbFaces == allFaces.Extent()-1 );
2641         }
2642         else
2643         {
2644           const TopoDS_Shape& topFace = sides[0]._faces->FindKey( nbFaces );
2645           size_t iS;
2646           for ( iS = 1; iS < sides.size(); ++iS )
2647             if ( !sides[ iS ]._faces->Contains( topFace ))
2648               break;
2649           prismDetected = ( iS == sides.size() );
2650         }
2651       }
2652     } // loop on allFaces
2653
2654     if ( !prismDetected && toCheckAll ) return false;
2655     if ( prismDetected && !toCheckAll ) return true;
2656
2657   } // loop on solids
2658
2659   return toCheckAll;
2660 }
2661
2662 namespace Prism_3D
2663 {
2664   //================================================================================
2665   /*!
2666    * \brief Return true if this node and other one belong to one face
2667    */
2668   //================================================================================
2669
2670   bool Prism_3D::TNode::IsNeighbor( const Prism_3D::TNode& other ) const
2671   {
2672     if ( !other.myNode || !myNode ) return false;
2673
2674     SMDS_ElemIteratorPtr fIt = other.myNode->GetInverseElementIterator(SMDSAbs_Face);
2675     while ( fIt->more() )
2676       if ( fIt->next()->GetNodeIndex( myNode ) >= 0 )
2677         return true;
2678     return false;
2679   }
2680
2681   //================================================================================
2682   /*!
2683    * \brief Prism initialization
2684    */
2685   //================================================================================
2686
2687   void TPrismTopo::Clear()
2688   {
2689     myShape3D.Nullify();
2690     myTop.Nullify();
2691     myBottom.Nullify();
2692     myWallQuads.clear();
2693     myBottomEdges.clear();
2694     myNbEdgesInWires.clear();
2695     myWallQuads.clear();
2696   }
2697
2698   //================================================================================
2699   /*!
2700    * \brief Set upside-down
2701    */
2702   //================================================================================
2703
2704   void TPrismTopo::SetUpsideDown()
2705   {
2706     std::swap( myBottom, myTop );
2707     myBottomEdges.clear();
2708     std::reverse( myBottomEdges.begin(), myBottomEdges.end() );
2709     for ( size_t i = 0; i < myWallQuads.size(); ++i )
2710     {
2711       myWallQuads[i].reverse();
2712       TQuadList::iterator q = myWallQuads[i].begin();
2713       for ( ; q != myWallQuads[i].end(); ++q )
2714       {
2715         (*q)->shift( 2, /*keepUnitOri=*/true );
2716       }
2717       myBottomEdges.push_back( myWallQuads[i].front()->side[ QUAD_BOTTOM_SIDE ].grid->Edge(0) );
2718     }
2719   }
2720
2721 } // namespace Prism_3D
2722
2723 //================================================================================
2724 /*!
2725  * \brief Constructor. Initialization is needed
2726  */
2727 //================================================================================
2728
2729 StdMeshers_PrismAsBlock::StdMeshers_PrismAsBlock()
2730 {
2731   mySide = 0;
2732 }
2733
2734 StdMeshers_PrismAsBlock::~StdMeshers_PrismAsBlock()
2735 {
2736   Clear();
2737 }
2738 void StdMeshers_PrismAsBlock::Clear()
2739 {
2740   myHelper = 0;
2741   myShapeIDMap.Clear();
2742   myError.reset();
2743
2744   if ( mySide ) {
2745     delete mySide; mySide = 0;
2746   }
2747   myParam2ColumnMaps.clear();
2748   myShapeIndex2ColumnMap.clear();
2749 }
2750
2751 //=======================================================================
2752 //function : initPrism
2753 //purpose  : Analyse shape geometry and mesh.
2754 //           If there are triangles on one of faces, it becomes 'bottom'.
2755 //           thePrism.myBottom can be already set up.
2756 //=======================================================================
2757
2758 bool StdMeshers_Prism_3D::initPrism(Prism_3D::TPrismTopo& thePrism,
2759                                     const TopoDS_Shape&   shape3D)
2760 {
2761   myHelper->SetSubShape( shape3D );
2762
2763   SMESH_subMesh* mainSubMesh = myHelper->GetMesh()->GetSubMeshContaining( shape3D );
2764   if ( !mainSubMesh ) return toSM( error(COMPERR_BAD_INPUT_MESH,"Null submesh of shape3D"));
2765
2766   // detect not-quad FACE sub-meshes of the 3D SHAPE
2767   list< SMESH_subMesh* > notQuadGeomSubMesh;
2768   list< SMESH_subMesh* > notQuadElemSubMesh;
2769   int nbFaces = 0;
2770   //
2771   SMESH_subMesh* anyFaceSM = 0;
2772   SMESH_subMeshIteratorPtr smIt = mainSubMesh->getDependsOnIterator(false,true);
2773   while ( smIt->more() )
2774   {
2775     SMESH_subMesh* sm = smIt->next();
2776     const TopoDS_Shape& face = sm->GetSubShape();
2777     if      ( face.ShapeType() > TopAbs_FACE ) break;
2778     else if ( face.ShapeType() < TopAbs_FACE ) continue;
2779     nbFaces++;
2780     anyFaceSM = sm;
2781
2782     // is quadrangle FACE?
2783     list< TopoDS_Edge > orderedEdges;
2784     list< int >         nbEdgesInWires;
2785     int nbWires = SMESH_Block::GetOrderedEdges( TopoDS::Face( face ), orderedEdges,
2786                                                 nbEdgesInWires );
2787     if ( nbWires != 1 || nbEdgesInWires.front() != 4 )
2788       notQuadGeomSubMesh.push_back( sm );
2789
2790     // look for not quadrangle mesh elements
2791     if ( SMESHDS_SubMesh* smDS = sm->GetSubMeshDS() )
2792       if ( !myHelper->IsSameElemGeometry( smDS, SMDSGeom_QUADRANGLE ))
2793         notQuadElemSubMesh.push_back( sm );
2794   }
2795
2796   int nbNotQuadMeshed = notQuadElemSubMesh.size();
2797   int       nbNotQuad = notQuadGeomSubMesh.size();
2798   bool     hasNotQuad = ( nbNotQuad || nbNotQuadMeshed );
2799
2800   // detect bad cases
2801   if ( nbNotQuadMeshed > 2 )
2802   {
2803     return toSM( error(COMPERR_BAD_INPUT_MESH,
2804                        TCom("More than 2 faces with not quadrangle elements: ")
2805                        <<nbNotQuadMeshed));
2806   }
2807   if ( nbNotQuad > 2 || !thePrism.myBottom.IsNull() )
2808   {
2809     // Issue 0020843 - one of side FACEs is quasi-quadrilateral (not 4 EDGEs).
2810     // Remove from notQuadGeomSubMesh faces meshed with regular grid
2811     int nbQuasiQuads = removeQuasiQuads( notQuadGeomSubMesh, myHelper,
2812                                          TQuadrangleAlgo::instance(this,myHelper) );
2813     nbNotQuad -= nbQuasiQuads;
2814     if ( nbNotQuad > 2 )
2815       return toSM( error(COMPERR_BAD_SHAPE,
2816                          TCom("More than 2 not quadrilateral faces: ") <<nbNotQuad));
2817     hasNotQuad = ( nbNotQuad || nbNotQuadMeshed );
2818   }
2819
2820   // Analyse mesh and topology of FACEs: choose the bottom sub-mesh.
2821   // If there are not quadrangle FACEs, they are top and bottom ones.
2822   // Not quadrangle FACEs must be only on top and bottom.
2823
2824   SMESH_subMesh * botSM = 0;
2825   SMESH_subMesh * topSM = 0;
2826
2827   if ( hasNotQuad ) // can choose a bottom FACE
2828   {
2829     if ( nbNotQuadMeshed > 0 ) botSM = notQuadElemSubMesh.front();
2830     else                       botSM = notQuadGeomSubMesh.front();
2831     if ( nbNotQuadMeshed > 1 ) topSM = notQuadElemSubMesh.back();
2832     else if ( nbNotQuad  > 1 ) topSM = notQuadGeomSubMesh.back();
2833
2834     if ( topSM == botSM ) {
2835       if ( nbNotQuadMeshed > 1 ) topSM = notQuadElemSubMesh.front();
2836       else                       topSM = notQuadGeomSubMesh.front();
2837     }
2838
2839     // detect mesh triangles on wall FACEs
2840     if ( nbNotQuad == 2 && nbNotQuadMeshed > 0 ) {
2841       bool ok = false;
2842       if ( nbNotQuadMeshed == 1 )
2843         ok = ( find( notQuadGeomSubMesh.begin(),
2844                      notQuadGeomSubMesh.end(), botSM ) != notQuadGeomSubMesh.end() );
2845       else
2846         ok = ( notQuadGeomSubMesh == notQuadElemSubMesh );
2847       if ( !ok )
2848         return toSM( error(COMPERR_BAD_INPUT_MESH,
2849                            "Side face meshed with not quadrangle elements"));
2850     }
2851   }
2852
2853   thePrism.myNotQuadOnTop = ( nbNotQuadMeshed > 1 );
2854
2855   // use thePrism.myBottom
2856   if ( !thePrism.myBottom.IsNull() )
2857   {
2858     if ( botSM ) {
2859       if ( ! botSM->GetSubShape().IsSame( thePrism.myBottom )) {
2860         std::swap( botSM, topSM );
2861         if ( !botSM || ! botSM->GetSubShape().IsSame( thePrism.myBottom ))
2862           return toSM( error( COMPERR_BAD_INPUT_MESH,
2863                               "Incompatible non-structured sub-meshes"));
2864       }
2865     }
2866     else {
2867       botSM = myHelper->GetMesh()->GetSubMesh( thePrism.myBottom );
2868     }
2869   }
2870   else if ( !botSM ) // find a proper bottom
2871   {
2872     // composite walls or not prism shape
2873     for ( TopExp_Explorer f( shape3D, TopAbs_FACE ); f.More(); f.Next() )
2874     {
2875       int minNbFaces = 2 + myHelper->Count( f.Current(), TopAbs_EDGE, false);
2876       if ( nbFaces >= minNbFaces)
2877       {
2878         thePrism.Clear();
2879         thePrism.myBottom = TopoDS::Face( f.Current() );
2880         if ( initPrism( thePrism, shape3D ))
2881           return true;
2882       }
2883       return toSM( error( COMPERR_BAD_SHAPE ));
2884     }
2885   }
2886
2887   // find vertex 000 - the one with smallest coordinates (for easy DEBUG :-)
2888   TopoDS_Vertex V000;
2889   double minVal = DBL_MAX, minX, val;
2890   for ( TopExp_Explorer exp( botSM->GetSubShape(), TopAbs_VERTEX );
2891         exp.More(); exp.Next() )
2892   {
2893     const TopoDS_Vertex& v = TopoDS::Vertex( exp.Current() );
2894     gp_Pnt P = BRep_Tool::Pnt( v );
2895     val = P.X() + P.Y() + P.Z();
2896     if ( val < minVal || ( val == minVal && P.X() < minX )) {
2897       V000 = v;
2898       minVal = val;
2899       minX = P.X();
2900     }
2901   }
2902
2903   thePrism.myShape3D = shape3D;
2904   if ( thePrism.myBottom.IsNull() )
2905     thePrism.myBottom  = TopoDS::Face( botSM->GetSubShape() );
2906   thePrism.myBottom.Orientation( myHelper->GetSubShapeOri( shape3D, thePrism.myBottom ));
2907   thePrism.myTop.   Orientation( myHelper->GetSubShapeOri( shape3D, thePrism.myTop ));
2908
2909   // Get ordered bottom edges
2910   TopoDS_Face reverseBottom = // to have order of top EDGEs as in the top FACE
2911     TopoDS::Face( thePrism.myBottom.Reversed() );
2912   SMESH_Block::GetOrderedEdges( reverseBottom,
2913                                 thePrism.myBottomEdges,
2914                                 thePrism.myNbEdgesInWires, V000 );
2915
2916   // Get Wall faces corresponding to the ordered bottom edges and the top FACE
2917   if ( !getWallFaces( thePrism, nbFaces ))
2918     return false; //toSM( error(COMPERR_BAD_SHAPE, "Can't find side faces"));
2919
2920   if ( topSM )
2921   {
2922     if ( !thePrism.myTop.IsSame( topSM->GetSubShape() ))
2923       return toSM( error
2924                    (notQuadGeomSubMesh.empty() ? COMPERR_BAD_INPUT_MESH : COMPERR_BAD_SHAPE,
2925                     "Non-quadrilateral faces are not opposite"));
2926
2927     // check that the found top and bottom FACEs are opposite
2928     list< TopoDS_Edge >::iterator edge = thePrism.myBottomEdges.begin();
2929     for ( ; edge != thePrism.myBottomEdges.end(); ++edge )
2930       if ( myHelper->IsSubShape( *edge, thePrism.myTop ))
2931         return toSM( error
2932                      (notQuadGeomSubMesh.empty() ? COMPERR_BAD_INPUT_MESH : COMPERR_BAD_SHAPE,
2933                       "Non-quadrilateral faces are not opposite"));
2934   }
2935
2936   if ( thePrism.myBottomEdges.size() > thePrism.myWallQuads.size() )
2937   {
2938     // composite bottom sides => set thePrism upside-down
2939     thePrism.SetUpsideDown();
2940   }
2941
2942   return true;
2943 }
2944
2945 //================================================================================
2946 /*!
2947  * \brief Initialization.
2948  * \param helper - helper loaded with mesh and 3D shape
2949  * \param thePrism - a prism data
2950  * \retval bool - false if a mesh or a shape are KO
2951  */
2952 //================================================================================
2953
2954 bool StdMeshers_PrismAsBlock::Init(SMESH_MesherHelper*         helper,
2955                                    const Prism_3D::TPrismTopo& thePrism)
2956 {
2957   myHelper = helper;
2958   SMESHDS_Mesh* meshDS = myHelper->GetMeshDS();
2959   SMESH_Mesh*     mesh = myHelper->GetMesh();
2960
2961   if ( mySide ) {
2962     delete mySide; mySide = 0;
2963   }
2964   vector< TSideFace* >         sideFaces( NB_WALL_FACES, 0 );
2965   vector< pair< double, double> > params( NB_WALL_FACES );
2966   mySide = new TSideFace( *mesh, sideFaces, params );
2967
2968
2969   SMESH_Block::init();
2970   myShapeIDMap.Clear();
2971   myShapeIndex2ColumnMap.clear();
2972   
2973   int wallFaceIds[ NB_WALL_FACES ] = { // to walk around a block
2974     SMESH_Block::ID_Fx0z, SMESH_Block::ID_F1yz,
2975     SMESH_Block::ID_Fx1z, SMESH_Block::ID_F0yz
2976   };
2977
2978   myError = SMESH_ComputeError::New();
2979
2980   myNotQuadOnTop = thePrism.myNotQuadOnTop;
2981
2982   // Find columns of wall nodes and calculate edges' lengths
2983   // --------------------------------------------------------
2984
2985   myParam2ColumnMaps.clear();
2986   myParam2ColumnMaps.resize( thePrism.myBottomEdges.size() ); // total nb edges
2987
2988   size_t iE, nbEdges = thePrism.myNbEdgesInWires.front(); // nb outer edges
2989   vector< double > edgeLength( nbEdges );
2990   multimap< double, int > len2edgeMap;
2991
2992   // for each EDGE: either split into several parts, or join with several next EDGEs
2993   vector<int> nbSplitPerEdge( nbEdges, 0 );
2994   vector<int> nbUnitePerEdge( nbEdges, 0 ); // -1 means "joined to a previous"
2995
2996   // consider continuous straight EDGEs as one side
2997   const int nbSides = countNbSides( thePrism, nbUnitePerEdge, edgeLength );
2998
2999   list< TopoDS_Edge >::const_iterator edgeIt = thePrism.myBottomEdges.begin();
3000   for ( iE = 0; iE < nbEdges; ++iE, ++edgeIt )
3001   {
3002     TParam2ColumnMap & faceColumns = myParam2ColumnMaps[ iE ];
3003
3004     Prism_3D::TQuadList::const_iterator quad = thePrism.myWallQuads[ iE ].begin();
3005     for ( ; quad != thePrism.myWallQuads[ iE ].end(); ++quad )
3006     {
3007       const TopoDS_Edge& quadBot = (*quad)->side[ QUAD_BOTTOM_SIDE ].grid->Edge( 0 );
3008       if ( !myHelper->LoadNodeColumns( faceColumns, (*quad)->face, quadBot, meshDS ))
3009         return error(COMPERR_BAD_INPUT_MESH, TCom("Can't find regular quadrangle mesh ")
3010                      << "on a side face #" << MeshDS()->ShapeToIndex( (*quad)->face ));
3011     }
3012     SHOWYXZ("\np1 F " <<iE, gpXYZ(faceColumns.begin()->second.front() ));
3013     SHOWYXZ("p2 F "   <<iE, gpXYZ(faceColumns.rbegin()->second.front() ));
3014     SHOWYXZ("V First "<<iE, BRep_Tool::Pnt( TopExp::FirstVertex(*edgeIt,true )));
3015
3016     if ( nbSides < NB_WALL_FACES ) // fill map used to split faces
3017       len2edgeMap.insert( make_pair( edgeLength[ iE ], iE )); // sort edges by length
3018   }
3019   // Load columns of internal edges (forming holes)
3020   // and fill map ShapeIndex to TParam2ColumnMap for them
3021   for ( ; edgeIt != thePrism.myBottomEdges.end() ; ++edgeIt, ++iE )
3022   {
3023     TParam2ColumnMap & faceColumns = myParam2ColumnMaps[ iE ];
3024
3025     Prism_3D::TQuadList::const_iterator quad = thePrism.myWallQuads[ iE ].begin();
3026     for ( ; quad != thePrism.myWallQuads[ iE ].end(); ++quad )
3027     {
3028       const TopoDS_Edge& quadBot = (*quad)->side[ QUAD_BOTTOM_SIDE ].grid->Edge( 0 );
3029       if ( !myHelper->LoadNodeColumns( faceColumns, (*quad)->face, quadBot, meshDS ))
3030         return error(COMPERR_BAD_INPUT_MESH, TCom("Can't find regular quadrangle mesh ")
3031                      << "on a side face #" << MeshDS()->ShapeToIndex( (*quad)->face ));
3032     }
3033     // edge columns
3034     int id = MeshDS()->ShapeToIndex( *edgeIt );
3035     bool isForward = true; // meaningless for intenal wires
3036     myShapeIndex2ColumnMap[ id ] = make_pair( & faceColumns, isForward );
3037     // columns for vertices
3038     // 1
3039     const SMDS_MeshNode* n0 = faceColumns.begin()->second.front();
3040     id = n0->getshapeId();
3041     myShapeIndex2ColumnMap[ id ] = make_pair( & faceColumns, isForward );
3042     // 2
3043     const SMDS_MeshNode* n1 = faceColumns.rbegin()->second.front();
3044     id = n1->getshapeId();
3045     myShapeIndex2ColumnMap[ id ] = make_pair( & faceColumns, isForward );
3046
3047     // SHOWYXZ("\np1 F " <<iE, gpXYZ(faceColumns.begin()->second.front() ));
3048     // SHOWYXZ("p2 F "   <<iE, gpXYZ(faceColumns.rbegin()->second.front() ));
3049     // SHOWYXZ("V First "<<iE, BRep_Tool::Pnt( TopExp::FirstVertex(*edgeIt,true )));
3050   }
3051
3052   // Create 4 wall faces of a block
3053   // -------------------------------
3054
3055   if ( nbSides <= NB_WALL_FACES ) // ************* Split faces if necessary
3056   {
3057     if ( nbSides != NB_WALL_FACES ) // define how to split
3058     {
3059       if ( len2edgeMap.size() != nbEdges )
3060         RETURN_BAD_RESULT("Uniqueness of edge lengths not assured");
3061
3062       multimap< double, int >::reverse_iterator maxLen_i = len2edgeMap.rbegin();
3063       multimap< double, int >::reverse_iterator midLen_i = ++len2edgeMap.rbegin();
3064
3065       double maxLen = maxLen_i->first;
3066       double midLen = ( len2edgeMap.size() == 1 ) ? 0 : midLen_i->first;
3067       switch ( nbEdges ) {
3068       case 1: // 0-th edge is split into 4 parts
3069         nbSplitPerEdge[ 0 ] = 4;
3070         break;
3071       case 2: // either the longest edge is split into 3 parts, or both edges into halves
3072         if ( maxLen / 3 > midLen / 2 ) {
3073           nbSplitPerEdge[ maxLen_i->second ] = 3;
3074         }
3075         else {
3076           nbSplitPerEdge[ maxLen_i->second ] = 2;
3077           nbSplitPerEdge[ midLen_i->second ] = 2;
3078         }
3079         break;
3080       case 3:
3081         if ( nbSides == 2 )
3082           // split longest into 3 parts
3083           nbSplitPerEdge[ maxLen_i->second ] = 3;
3084         else
3085           // split longest into halves
3086           nbSplitPerEdge[ maxLen_i->second ] = 2;
3087       }
3088     }
3089   }
3090   else // **************************** Unite faces
3091   {
3092     int nbExraFaces = nbSides - 4; // nb of faces to fuse
3093     for ( iE = 0; iE < nbEdges; ++iE )
3094     {
3095       if ( nbUnitePerEdge[ iE ] < 0 )
3096         continue;
3097       // look for already united faces
3098       for ( int i = iE; i < iE + nbExraFaces; ++i )
3099       {
3100         if ( nbUnitePerEdge[ i ] > 0 ) // a side including nbUnitePerEdge[i]+1 edge
3101           nbExraFaces += nbUnitePerEdge[ i ];
3102         nbUnitePerEdge[ i ] = -1;
3103       }
3104       nbUnitePerEdge[ iE ] = nbExraFaces;
3105       break;
3106     }
3107   }
3108
3109   // Create TSideFace's
3110   int iSide = 0;
3111   list< TopoDS_Edge >::const_iterator botE = thePrism.myBottomEdges.begin();
3112   for ( iE = 0; iE < nbEdges; ++iE, ++botE )
3113   {
3114     TFaceQuadStructPtr quad = thePrism.myWallQuads[ iE ].front();
3115     const int       nbSplit = nbSplitPerEdge[ iE ];
3116     const int   nbExraFaces = nbUnitePerEdge[ iE ] + 1;
3117     if ( nbSplit > 0 ) // split
3118     {
3119       vector< double > params;
3120       splitParams( nbSplit, &myParam2ColumnMaps[ iE ], params );
3121       const bool isForward =
3122         StdMeshers_PrismAsBlock::IsForwardEdge( myHelper->GetMeshDS(),
3123                                                 myParam2ColumnMaps[iE],
3124                                                 *botE, SMESH_Block::ID_Fx0z );
3125       for ( int i = 0; i < nbSplit; ++i ) {
3126         double f = ( isForward ? params[ i ]   : params[ nbSplit - i-1 ]);
3127         double l = ( isForward ? params[ i+1 ] : params[ nbSplit - i ]);
3128         TSideFace* comp = new TSideFace( *mesh, wallFaceIds[ iSide ],
3129                                          thePrism.myWallQuads[ iE ], *botE,
3130                                          &myParam2ColumnMaps[ iE ], f, l );
3131         mySide->SetComponent( iSide++, comp );
3132       }
3133     }
3134     else if ( nbExraFaces > 1 ) // unite
3135     {
3136       double u0 = 0, sumLen = 0;
3137       for ( int i = iE; i < iE + nbExraFaces; ++i )
3138         sumLen += edgeLength[ i ];
3139
3140       vector< TSideFace* >        components( nbExraFaces );
3141       vector< pair< double, double> > params( nbExraFaces );
3142       bool endReached = false;
3143       for ( int i = 0; i < nbExraFaces; ++i, ++botE, ++iE )
3144       {
3145         if ( iE == nbEdges )
3146         {
3147           endReached = true;
3148           botE = thePrism.myBottomEdges.begin();
3149           iE = 0;
3150         }
3151         components[ i ] = new TSideFace( *mesh, wallFaceIds[ iSide ],
3152                                          thePrism.myWallQuads[ iE ], *botE,
3153                                          &myParam2ColumnMaps[ iE ]);
3154         double u1 = u0 + edgeLength[ iE ] / sumLen;
3155         params[ i ] = make_pair( u0 , u1 );
3156         u0 = u1;
3157       }
3158       TSideFace* comp = new TSideFace( *mesh, components, params );
3159       mySide->SetComponent( iSide++, comp );
3160       if ( endReached )
3161         break;
3162       --iE; // for increment in an external loop on iE
3163       --botE;
3164     }
3165     else if ( nbExraFaces < 0 ) // skip already united face
3166     {
3167     }
3168     else // use as is
3169     {
3170       TSideFace* comp = new TSideFace( *mesh, wallFaceIds[ iSide ],
3171                                        thePrism.myWallQuads[ iE ], *botE,
3172                                        &myParam2ColumnMaps[ iE ]);
3173       mySide->SetComponent( iSide++, comp );
3174     }
3175   }
3176
3177
3178   // Fill geometry fields of SMESH_Block
3179   // ------------------------------------
3180
3181   vector< int > botEdgeIdVec;
3182   SMESH_Block::GetFaceEdgesIDs( ID_BOT_FACE, botEdgeIdVec );
3183
3184   bool isForward[NB_WALL_FACES] = { true, true, true, true };
3185   Adaptor2d_Curve2d* botPcurves[NB_WALL_FACES];
3186   Adaptor2d_Curve2d* topPcurves[NB_WALL_FACES];
3187
3188   for ( int iF = 0; iF < NB_WALL_FACES; ++iF )
3189   {
3190     TSideFace * sideFace = mySide->GetComponent( iF );
3191     if ( !sideFace )
3192       RETURN_BAD_RESULT("NULL TSideFace");
3193     int fID = sideFace->FaceID(); // in-block ID
3194
3195     // fill myShapeIDMap
3196     if ( sideFace->InsertSubShapes( myShapeIDMap ) != 8 &&
3197          !sideFace->IsComplex())
3198       MESSAGE( ": Warning : InsertSubShapes() < 8 on side " << iF );
3199
3200     // side faces geometry
3201     Adaptor2d_Curve2d* pcurves[NB_WALL_FACES];
3202     if ( !sideFace->GetPCurves( pcurves ))
3203       RETURN_BAD_RESULT("TSideFace::GetPCurves() failed");
3204
3205     SMESH_Block::TFace& tFace = myFace[ fID - ID_FirstF ];
3206     tFace.Set( fID, sideFace->Surface(), pcurves, isForward );
3207
3208     SHOWYXZ( endl<<"F "<< iF << " id " << fID << " FRW " << sideFace->IsForward(), sideFace->Value(0,0));
3209     // edges 3D geometry
3210     vector< int > edgeIdVec;
3211     SMESH_Block::GetFaceEdgesIDs( fID, edgeIdVec );
3212     for ( int isMax = 0; isMax < 2; ++isMax ) {
3213       {
3214         int eID = edgeIdVec[ isMax ];
3215         SMESH_Block::TEdge& tEdge = myEdge[ eID - ID_FirstE ];
3216         tEdge.Set( eID, sideFace->HorizCurve(isMax), true);
3217         SHOWYXZ(eID<<" HOR"<<isMax<<"(0)", sideFace->HorizCurve(isMax)->Value(0));
3218         SHOWYXZ(eID<<" HOR"<<isMax<<"(1)", sideFace->HorizCurve(isMax)->Value(1));
3219       }
3220       {
3221         int eID = edgeIdVec[ isMax+2 ];
3222         SMESH_Block::TEdge& tEdge = myEdge[ eID - ID_FirstE  ];
3223         tEdge.Set( eID, sideFace->VertiCurve(isMax), true);
3224         SHOWYXZ(eID<<" VER"<<isMax<<"(0)", sideFace->VertiCurve(isMax)->Value(0));
3225         SHOWYXZ(eID<<" VER"<<isMax<<"(1)", sideFace->VertiCurve(isMax)->Value(1));
3226
3227         // corner points
3228         vector< int > vertexIdVec;
3229         SMESH_Block::GetEdgeVertexIDs( eID, vertexIdVec );
3230         myPnt[ vertexIdVec[0] - ID_FirstV ] = tEdge.GetCurve()->Value(0).XYZ();
3231         myPnt[ vertexIdVec[1] - ID_FirstV ] = tEdge.GetCurve()->Value(1).XYZ();
3232       }
3233     }
3234     // pcurves on horizontal faces
3235     for ( iE = 0; iE < NB_WALL_FACES; ++iE ) {
3236       if ( edgeIdVec[ BOTTOM_EDGE ] == botEdgeIdVec[ iE ] ) {
3237         botPcurves[ iE ] = sideFace->HorizPCurve( false, thePrism.myBottom );
3238         topPcurves[ iE ] = sideFace->HorizPCurve( true,  thePrism.myTop );
3239         break;
3240       }
3241     }
3242     //sideFace->dumpNodes( 4 ); // debug
3243   }
3244   // horizontal faces geometry
3245   {
3246     SMESH_Block::TFace& tFace = myFace[ ID_BOT_FACE - ID_FirstF ];
3247     tFace.Set( ID_BOT_FACE, new BRepAdaptor_Surface( thePrism.myBottom ), botPcurves, isForward );
3248     SMESH_Block::Insert( thePrism.myBottom, ID_BOT_FACE, myShapeIDMap );
3249   }
3250   {
3251     SMESH_Block::TFace& tFace = myFace[ ID_TOP_FACE - ID_FirstF ];
3252     tFace.Set( ID_TOP_FACE, new BRepAdaptor_Surface( thePrism.myTop ), topPcurves, isForward );
3253     SMESH_Block::Insert( thePrism.myTop, ID_TOP_FACE, myShapeIDMap );
3254   }
3255   //faceGridToPythonDump( SMESH_Block::ID_Fxy0, 50 );
3256   //faceGridToPythonDump( SMESH_Block::ID_Fxy1 );
3257
3258   // Fill map ShapeIndex to TParam2ColumnMap
3259   // ----------------------------------------
3260
3261   list< TSideFace* > fList;
3262   list< TSideFace* >::iterator fListIt;
3263   fList.push_back( mySide );
3264   for ( fListIt = fList.begin(); fListIt != fList.end(); ++fListIt)
3265   {
3266     int nb = (*fListIt)->NbComponents();
3267     for ( int i = 0; i < nb; ++i ) {
3268       if ( TSideFace* comp = (*fListIt)->GetComponent( i ))
3269         fList.push_back( comp );
3270     }
3271     if ( TParam2ColumnMap* cols = (*fListIt)->GetColumns()) {
3272       // columns for a base edge
3273       int id = MeshDS()->ShapeToIndex( (*fListIt)->BaseEdge() );
3274       bool isForward = (*fListIt)->IsForward();
3275       myShapeIndex2ColumnMap[ id ] = make_pair( cols, isForward );
3276
3277       // columns for vertices
3278       const SMDS_MeshNode* n0 = cols->begin()->second.front();
3279       id = n0->getshapeId();
3280       myShapeIndex2ColumnMap[ id ] = make_pair( cols, isForward );
3281
3282       const SMDS_MeshNode* n1 = cols->rbegin()->second.front();
3283       id = n1->getshapeId();
3284       myShapeIndex2ColumnMap[ id ] = make_pair( cols, !isForward );
3285     }
3286   }
3287
3288 // #define SHOWYXZ(msg, xyz) {                     \
3289 //     gp_Pnt p (xyz);                                                     \
3290 //     cout << msg << " ("<< p.X() << "; " <<p.Y() << "; " <<p.Z() << ") " <<endl; \
3291 //   }
3292 //   double _u[]={ 0.1, 0.1, 0.9, 0.9 };
3293 //   double _v[]={ 0.1, 0.9, 0.1, 0.9 };
3294 //   for ( int z = 0; z < 2; ++z )
3295 //     for ( int i = 0; i < 4; ++i )
3296 //     {
3297 //       //gp_XYZ testPar(0.25, 0.25, 0), testCoord;
3298 //       int iFace = (z ? ID_TOP_FACE : ID_BOT_FACE);
3299 //       gp_XYZ testPar(_u[i], _v[i], z), testCoord;
3300 //       if ( !FacePoint( iFace, testPar, testCoord ))
3301 //         RETURN_BAD_RESULT("TEST FacePoint() FAILED");
3302 //       SHOWYXZ("IN TEST PARAM" , testPar);
3303 //       SHOWYXZ("OUT TEST CORD" , testCoord);
3304 //       if ( !ComputeParameters( testCoord, testPar , iFace))
3305 //         RETURN_BAD_RESULT("TEST ComputeParameters() FAILED");
3306 //       SHOWYXZ("OUT TEST PARAM" , testPar);
3307 //     }
3308   return true;
3309 }
3310
3311 //================================================================================
3312 /*!
3313  * \brief Return pointer to column of nodes
3314  * \param node - bottom node from which the returned column goes up
3315  * \retval const TNodeColumn* - the found column
3316  */
3317 //================================================================================
3318
3319 const TNodeColumn* StdMeshers_PrismAsBlock::GetNodeColumn(const SMDS_MeshNode* node) const
3320 {
3321   int sID = node->getshapeId();
3322
3323   map<int, pair< TParam2ColumnMap*, bool > >::const_iterator col_frw =
3324     myShapeIndex2ColumnMap.find( sID );
3325   if ( col_frw != myShapeIndex2ColumnMap.end() ) {
3326     const TParam2ColumnMap* cols = col_frw->second.first;
3327     TParam2ColumnIt u_col = cols->begin();
3328     for ( ; u_col != cols->end(); ++u_col )
3329       if ( u_col->second[ 0 ] == node )
3330         return & u_col->second;
3331   }
3332   return 0;
3333 }
3334
3335 //=======================================================================
3336 //function : GetLayersTransformation
3337 //purpose  : Return transformations to get coordinates of nodes of each layer
3338 //           by nodes of the bottom. Layer is a set of nodes at a certain step
3339 //           from bottom to top.
3340 //           Transformation to get top node from bottom ones is computed
3341 //           only if the top FACE is not meshed.
3342 //=======================================================================
3343
3344 bool StdMeshers_PrismAsBlock::GetLayersTransformation(vector<gp_Trsf> &           trsf,
3345                                                       const Prism_3D::TPrismTopo& prism) const
3346 {
3347   const bool itTopMeshed = !SubMesh( ID_BOT_FACE )->IsEmpty();
3348   const int zSize = VerticalSize();
3349   if ( zSize < 3 && !itTopMeshed ) return true;
3350   trsf.resize( zSize - 1 );
3351
3352   // Select some node columns by which we will define coordinate system of layers
3353
3354   vector< const TNodeColumn* > columns;
3355   {
3356     bool isReverse;
3357     list< TopoDS_Edge >::const_iterator edgeIt = prism.myBottomEdges.begin();
3358     for ( int iE = 0; iE < prism.myNbEdgesInWires.front(); ++iE, ++edgeIt )
3359     {
3360       if ( SMESH_Algo::isDegenerated( *edgeIt )) continue;
3361       const TParam2ColumnMap* u2colMap =
3362         GetParam2ColumnMap( MeshDS()->ShapeToIndex( *edgeIt ), isReverse );
3363       if ( !u2colMap ) return false;
3364       double f = u2colMap->begin()->first, l = u2colMap->rbegin()->first;
3365       //isReverse = ( edgeIt->Orientation() == TopAbs_REVERSED );
3366       //if ( isReverse ) swap ( f, l ); -- u2colMap takes orientation into account
3367       const int nbCol = 5;
3368       for ( int i = 0; i < nbCol; ++i )
3369       {
3370         double u = f + i/double(nbCol) * ( l - f );
3371         const TNodeColumn* col = & getColumn( u2colMap, u )->second;
3372         if ( columns.empty() || col != columns.back() )
3373           columns.push_back( col );
3374       }
3375     }
3376   }
3377
3378   // Find tolerance to check transformations
3379
3380   double tol2;
3381   {
3382     Bnd_B3d bndBox;
3383     for ( int i = 0; i < columns.size(); ++i )
3384       bndBox.Add( gpXYZ( columns[i]->front() ));
3385     tol2 = bndBox.SquareExtent() * 1e-5;
3386   }
3387
3388   // Compute transformations
3389
3390   int xCol = -1;
3391   gp_Trsf fromCsZ, toCs0;
3392   gp_Ax3 cs0 = getLayerCoordSys(0, columns, xCol );
3393   //double dist0 = cs0.Location().Distance( gpXYZ( (*columns[0])[0]));
3394   toCs0.SetTransformation( cs0 );
3395   for ( int z = 1; z < zSize; ++z )
3396   {
3397     gp_Ax3 csZ = getLayerCoordSys(z, columns, xCol );
3398     //double distZ = csZ.Location().Distance( gpXYZ( (*columns[0])[z]));
3399     fromCsZ.SetTransformation( csZ );
3400     fromCsZ.Invert();
3401     gp_Trsf& t = trsf[ z-1 ];
3402     t = fromCsZ * toCs0;
3403     //t.SetScaleFactor( distZ/dist0 ); - it does not work properly, wrong base point
3404
3405     // check a transformation
3406     for ( int i = 0; i < columns.size(); ++i )
3407     {
3408       gp_Pnt p0 = gpXYZ( (*columns[i])[0] );
3409       gp_Pnt pz = gpXYZ( (*columns[i])[z] );
3410       t.Transforms( p0.ChangeCoord() );
3411       if ( p0.SquareDistance( pz ) > tol2 )
3412       {
3413         t = gp_Trsf();
3414         return ( z == zSize - 1 ); // OK if fails only botton->top trsf
3415       }
3416     }
3417   }
3418   return true;
3419 }
3420
3421 //================================================================================
3422 /*!
3423  * \brief Check curve orientation of a bootom edge
3424   * \param meshDS - mesh DS
3425   * \param columnsMap - node columns map of side face
3426   * \param bottomEdge - the bootom edge
3427   * \param sideFaceID - side face in-block ID
3428   * \retval bool - true if orientation coinside with in-block forward orientation
3429  */
3430 //================================================================================
3431
3432 bool StdMeshers_PrismAsBlock::IsForwardEdge(SMESHDS_Mesh*           meshDS,
3433                                             const TParam2ColumnMap& columnsMap,
3434                                             const TopoDS_Edge &     bottomEdge,
3435                                             const int               sideFaceID)
3436 {
3437   bool isForward = false;
3438   if ( SMESH_MesherHelper::IsClosedEdge( bottomEdge ))
3439   {
3440     isForward = ( bottomEdge.Orientation() == TopAbs_FORWARD );
3441   }
3442   else
3443   {
3444     const TNodeColumn&     firstCol = columnsMap.begin()->second;
3445     const SMDS_MeshNode* bottomNode = firstCol[0];
3446     TopoDS_Shape firstVertex = SMESH_MesherHelper::GetSubShapeByNode( bottomNode, meshDS );
3447     isForward = ( firstVertex.IsSame( TopExp::FirstVertex( bottomEdge, true )));
3448   }
3449   // on 2 of 4 sides first vertex is end
3450   if ( sideFaceID == ID_Fx1z || sideFaceID == ID_F0yz )
3451     isForward = !isForward;
3452   return isForward;
3453 }
3454
3455 //=======================================================================
3456 //function : faceGridToPythonDump
3457 //purpose  : Prints a script creating a normal grid on the prism side
3458 //=======================================================================
3459
3460 void StdMeshers_PrismAsBlock::faceGridToPythonDump(const SMESH_Block::TShapeID face,
3461                                                    const int                   nb)
3462 {
3463 #ifdef _DEBUG_
3464   gp_XYZ pOnF[6] = { gp_XYZ(0,0,0), gp_XYZ(0,0,1),
3465                      gp_XYZ(0,0,0), gp_XYZ(0,1,0),
3466                      gp_XYZ(0,0,0), gp_XYZ(1,0,0) };
3467   gp_XYZ p2;
3468   cout << "mesh = smesh.Mesh( 'Face " << face << "')" << endl;
3469   SMESH_Block::TFace& f = myFace[ face - ID_FirstF ];
3470   gp_XYZ params = pOnF[ face - ID_FirstF ];
3471   //const int nb = 10; // nb face rows
3472   for ( int j = 0; j <= nb; ++j )
3473   {
3474     params.SetCoord( f.GetVInd(), double( j )/ nb );
3475     for ( int i = 0; i <= nb; ++i )
3476     {
3477       params.SetCoord( f.GetUInd(), double( i )/ nb );
3478       gp_XYZ p = f.Point( params );
3479       gp_XY uv = f.GetUV( params );
3480       cout << "mesh.AddNode( " << p.X() << ", " << p.Y() << ", " << p.Z() << " )"
3481            << " # " << 1 + i + j * ( nb + 1 )
3482            << " ( " << i << ", " << j << " ) "
3483            << " UV( " << uv.X() << ", " << uv.Y() << " )" << endl;
3484       ShellPoint( params, p2 );
3485       double dist = ( p2 - p ).Modulus();
3486       if ( dist > 1e-4 )
3487         cout << "#### dist from ShellPoint " << dist
3488              << " (" << p2.X() << ", " << p2.Y() << ", " << p2.Z() << " ) " << endl;
3489     }
3490   }
3491   for ( int j = 0; j < nb; ++j )
3492     for ( int i = 0; i < nb; ++i )
3493     {
3494       int n = 1 + i + j * ( nb + 1 );
3495       cout << "mesh.AddFace([ "
3496            << n << ", " << n+1 << ", "
3497            << n+nb+2 << ", " << n+nb+1 << "]) " << endl;
3498     }
3499   
3500 #endif
3501 }
3502
3503 //================================================================================
3504 /*!
3505  * \brief Constructor
3506   * \param faceID - in-block ID
3507   * \param face - geom FACE
3508   * \param baseEdge - EDGE proreply oriented in the bottom EDGE !!!
3509   * \param columnsMap - map of node columns
3510   * \param first - first normalized param
3511   * \param last - last normalized param
3512  */
3513 //================================================================================
3514
3515 StdMeshers_PrismAsBlock::TSideFace::TSideFace(SMESH_Mesh&                mesh,
3516                                               const int                  faceID,
3517                                               const Prism_3D::TQuadList& quadList,
3518                                               const TopoDS_Edge&         baseEdge,
3519                                               TParam2ColumnMap*          columnsMap,
3520                                               const double               first,
3521                                               const double               last):
3522   myID( faceID ),
3523   myParamToColumnMap( columnsMap ),
3524   myHelper( mesh )
3525 {
3526   myParams.resize( 1 );
3527   myParams[ 0 ] = make_pair( first, last );
3528   mySurface     = PSurface( new BRepAdaptor_Surface( quadList.front()->face ));
3529   myBaseEdge    = baseEdge;
3530   myIsForward   = StdMeshers_PrismAsBlock::IsForwardEdge( myHelper.GetMeshDS(),
3531                                                           *myParamToColumnMap,
3532                                                           myBaseEdge, myID );
3533   myHelper.SetSubShape( quadList.front()->face );
3534
3535   if ( quadList.size() > 1 ) // side is vertically composite
3536   {
3537     // fill myShapeID2Surf map to enable finding a right surface by any sub-shape ID
3538
3539     SMESHDS_Mesh* meshDS = myHelper.GetMeshDS();
3540
3541     TopTools_IndexedDataMapOfShapeListOfShape subToFaces;
3542     Prism_3D::TQuadList::const_iterator quad = quadList.begin();
3543     for ( ; quad != quadList.end(); ++quad )
3544     {
3545       const TopoDS_Face& face = (*quad)->face;
3546       TopExp::MapShapesAndAncestors( face, TopAbs_VERTEX, TopAbs_FACE, subToFaces );
3547       TopExp::MapShapesAndAncestors( face, TopAbs_EDGE,   TopAbs_FACE, subToFaces );
3548       myShapeID2Surf.insert( make_pair( meshDS->ShapeToIndex( face ),
3549                                         PSurface( new BRepAdaptor_Surface( face ))));
3550     }
3551     for ( int i = 1; i <= subToFaces.Extent(); ++i )
3552     {
3553       const TopoDS_Shape&     sub = subToFaces.FindKey( i );
3554       TopTools_ListOfShape& faces = subToFaces( i );
3555       int subID  = meshDS->ShapeToIndex( sub );
3556       int faceID = meshDS->ShapeToIndex( faces.First() );
3557       myShapeID2Surf.insert ( make_pair( subID, myShapeID2Surf[ faceID ]));
3558     }
3559   }
3560 }
3561
3562 //================================================================================
3563 /*!
3564  * \brief Constructor of a complex side face
3565  */
3566 //================================================================================
3567
3568 StdMeshers_PrismAsBlock::TSideFace::
3569 TSideFace(SMESH_Mesh&                             mesh,
3570           const vector< TSideFace* >&             components,
3571           const vector< pair< double, double> > & params)
3572   :myID( components[0] ? components[0]->myID : 0 ),
3573    myParamToColumnMap( 0 ),
3574    myParams( params ),
3575    myIsForward( true ),
3576    myComponents( components ),
3577    myHelper( mesh )
3578 {
3579   if ( myID == ID_Fx1z || myID == ID_F0yz )
3580   {
3581     // reverse components
3582     std::reverse( myComponents.begin(), myComponents.end() );
3583     std::reverse( myParams.begin(),     myParams.end() );
3584     for ( size_t i = 0; i < myParams.size(); ++i )
3585     {
3586       const double f = myParams[i].first;
3587       const double l = myParams[i].second;
3588       myParams[i] = make_pair( 1. - l, 1. - f );
3589     }
3590   }
3591 }
3592 //================================================================================
3593 /*!
3594  * \brief Copy constructor
3595   * \param other - other side
3596  */
3597 //================================================================================
3598
3599 StdMeshers_PrismAsBlock::TSideFace::TSideFace( const TSideFace& other ):
3600   myID               ( other.myID ),
3601   myParamToColumnMap ( other.myParamToColumnMap ),
3602   mySurface          ( other.mySurface ),
3603   myBaseEdge         ( other.myBaseEdge ),
3604   myShapeID2Surf     ( other.myShapeID2Surf ),
3605   myParams           ( other.myParams ),
3606   myIsForward        ( other.myIsForward ),
3607   myComponents       ( other.myComponents.size() ),
3608   myHelper           ( *other.myHelper.GetMesh() )
3609 {
3610   for (int i = 0 ; i < myComponents.size(); ++i )
3611     myComponents[ i ] = new TSideFace( *other.myComponents[ i ]);
3612 }
3613
3614 //================================================================================
3615 /*!
3616  * \brief Deletes myComponents
3617  */
3618 //================================================================================
3619
3620 StdMeshers_PrismAsBlock::TSideFace::~TSideFace()
3621 {
3622   for (int i = 0 ; i < myComponents.size(); ++i )
3623     if ( myComponents[ i ] )
3624       delete myComponents[ i ];
3625 }
3626
3627 //================================================================================
3628 /*!
3629  * \brief Return geometry of the vertical curve
3630   * \param isMax - true means curve located closer to (1,1,1) block point
3631   * \retval Adaptor3d_Curve* - curve adaptor
3632  */
3633 //================================================================================
3634
3635 Adaptor3d_Curve* StdMeshers_PrismAsBlock::TSideFace::VertiCurve(const bool isMax) const
3636 {
3637   if ( !myComponents.empty() ) {
3638     if ( isMax )
3639       return myComponents.back()->VertiCurve(isMax);
3640     else
3641       return myComponents.front()->VertiCurve(isMax);
3642   }
3643   double f = myParams[0].first, l = myParams[0].second;
3644   if ( !myIsForward ) std::swap( f, l );
3645   return new TVerticalEdgeAdaptor( myParamToColumnMap, isMax ? l : f );
3646 }
3647
3648 //================================================================================
3649 /*!
3650  * \brief Return geometry of the top or bottom curve
3651   * \param isTop - 
3652   * \retval Adaptor3d_Curve* - 
3653  */
3654 //================================================================================
3655
3656 Adaptor3d_Curve* StdMeshers_PrismAsBlock::TSideFace::HorizCurve(const bool isTop) const
3657 {
3658   return new THorizontalEdgeAdaptor( this, isTop );
3659 }
3660
3661 //================================================================================
3662 /*!
3663  * \brief Return pcurves
3664   * \param pcurv - array of 4 pcurves
3665   * \retval bool - is a success
3666  */
3667 //================================================================================
3668
3669 bool StdMeshers_PrismAsBlock::TSideFace::GetPCurves(Adaptor2d_Curve2d* pcurv[4]) const
3670 {
3671   int iEdge[ 4 ] = { BOTTOM_EDGE, TOP_EDGE, V0_EDGE, V1_EDGE };
3672
3673   for ( int i = 0 ; i < 4 ; ++i ) {
3674     Handle(Geom2d_Line) line;
3675     switch ( iEdge[ i ] ) {
3676     case TOP_EDGE:
3677       line = new Geom2d_Line( gp_Pnt2d( 0, 1 ), gp::DX2d() ); break;
3678     case BOTTOM_EDGE:
3679       line = new Geom2d_Line( gp::Origin2d(), gp::DX2d() ); break;
3680     case V0_EDGE:
3681       line = new Geom2d_Line( gp::Origin2d(), gp::DY2d() ); break;
3682     case V1_EDGE:
3683       line = new Geom2d_Line( gp_Pnt2d( 1, 0 ), gp::DY2d() ); break;
3684     }
3685     pcurv[ i ] = new Geom2dAdaptor_Curve( line, 0, 1 );
3686   }
3687   return true;
3688 }
3689
3690 //================================================================================
3691 /*!
3692  * \brief Returns geometry of pcurve on a horizontal face
3693   * \param isTop - is top or bottom face
3694   * \param horFace - a horizontal face
3695   * \retval Adaptor2d_Curve2d* - curve adaptor
3696  */
3697 //================================================================================
3698
3699 Adaptor2d_Curve2d*
3700 StdMeshers_PrismAsBlock::TSideFace::HorizPCurve(const bool         isTop,
3701                                                 const TopoDS_Face& horFace) const
3702 {
3703   return new TPCurveOnHorFaceAdaptor( this, isTop, horFace );
3704 }
3705
3706 //================================================================================
3707 /*!
3708  * \brief Return a component corresponding to parameter
3709   * \param U - parameter along a horizontal size
3710   * \param localU - parameter along a horizontal size of a component
3711   * \retval TSideFace* - found component
3712  */
3713 //================================================================================
3714
3715 StdMeshers_PrismAsBlock::TSideFace*
3716 StdMeshers_PrismAsBlock::TSideFace::GetComponent(const double U,double & localU) const
3717 {
3718   localU = U;
3719   if ( myComponents.empty() )
3720     return const_cast<TSideFace*>( this );
3721
3722   int i;
3723   for ( i = 0; i < myComponents.size(); ++i )
3724     if ( U < myParams[ i ].second )
3725       break;
3726   if ( i >= myComponents.size() )
3727     i = myComponents.size() - 1;
3728
3729   double f = myParams[ i ].first, l = myParams[ i ].second;
3730   localU = ( U - f ) / ( l - f );
3731   return myComponents[ i ];
3732 }
3733
3734 //================================================================================
3735 /*!
3736  * \brief Find node columns for a parameter
3737   * \param U - parameter along a horizontal edge
3738   * \param col1 - the 1st found column
3739   * \param col2 - the 2nd found column
3740   * \retval r - normalized position of U between the found columns
3741  */
3742 //================================================================================
3743
3744 double StdMeshers_PrismAsBlock::TSideFace::GetColumns(const double      U,
3745                                                       TParam2ColumnIt & col1,
3746                                                       TParam2ColumnIt & col2) const
3747 {
3748   double u = U, r = 0;
3749   if ( !myComponents.empty() ) {
3750     TSideFace * comp = GetComponent(U,u);
3751     return comp->GetColumns( u, col1, col2 );
3752   }
3753
3754   if ( !myIsForward )
3755     u = 1 - u;
3756   double f = myParams[0].first, l = myParams[0].second;
3757   u = f + u * ( l - f );
3758
3759   col1 = col2 = getColumn( myParamToColumnMap, u );
3760   if ( ++col2 == myParamToColumnMap->end() ) {
3761     --col2;
3762     r = 0.5;
3763   }
3764   else {
3765     double uf = col1->first;
3766     double ul = col2->first;
3767     r = ( u - uf ) / ( ul - uf );
3768   }
3769   return r;
3770 }
3771
3772 //================================================================================
3773 /*!
3774  * \brief Return all nodes at a given height together with their normalized parameters
3775  *  \param [in] Z - the height of interest
3776  *  \param [out] nodes - map of parameter to node
3777  */
3778 //================================================================================
3779
3780 void StdMeshers_PrismAsBlock::
3781 TSideFace::GetNodesAtZ(const int Z,
3782                        map<double, const SMDS_MeshNode* >& nodes ) const
3783 {
3784   if ( !myComponents.empty() )
3785   {
3786     double u0 = 0.;
3787     for ( size_t i = 0; i < myComponents.size(); ++i )
3788     {
3789       map<double, const SMDS_MeshNode* > nn;
3790       myComponents[i]->GetNodesAtZ( Z, nn );
3791       map<double, const SMDS_MeshNode* >::iterator u2n = nn.begin();
3792       if ( !nodes.empty() && nodes.rbegin()->second == u2n->second )
3793         ++u2n;
3794       const double uRange = myParams[i].second - myParams[i].first;
3795       for ( ; u2n != nn.end(); ++u2n )
3796         nodes.insert( nodes.end(), make_pair( u0 + uRange * u2n->first, u2n->second ));
3797       u0 += uRange;
3798     }
3799   }
3800   else
3801   {
3802     double f = myParams[0].first, l = myParams[0].second;
3803     if ( !myIsForward )
3804       std::swap( f, l );
3805     const double uRange = l - f;
3806     if ( Abs( uRange ) < std::numeric_limits<double>::min() )
3807       return;
3808     TParam2ColumnIt u2col = getColumn( myParamToColumnMap, myParams[0].first + 1e-3 );
3809     for ( ; u2col != myParamToColumnMap->end(); ++u2col )
3810       if ( u2col->first > myParams[0].second + 1e-9 )
3811         break;
3812       else
3813         nodes.insert( nodes.end(),
3814                       make_pair( ( u2col->first - f ) / uRange, u2col->second[ Z ] ));
3815   }
3816 }
3817
3818 //================================================================================
3819 /*!
3820  * \brief Return coordinates by normalized params
3821   * \param U - horizontal param
3822   * \param V - vertical param
3823   * \retval gp_Pnt - result point
3824  */
3825 //================================================================================
3826
3827 gp_Pnt StdMeshers_PrismAsBlock::TSideFace::Value(const Standard_Real U,
3828                                                  const Standard_Real V) const
3829 {
3830   if ( !myComponents.empty() ) {
3831     double u;
3832     TSideFace * comp = GetComponent(U,u);
3833     return comp->Value( u, V );
3834   }
3835
3836   TParam2ColumnIt u_col1, u_col2;
3837   double vR, hR = GetColumns( U, u_col1, u_col2 );
3838
3839   const SMDS_MeshNode* nn[4];
3840
3841   // BEGIN issue 0020680: Bad cell created by Radial prism in center of torus
3842   // Workaround for a wrongly located point returned by mySurface.Value() for
3843   // UV located near boundary of BSpline surface.
3844   // To bypass the problem, we take point from 3D curve of EDGE.
3845   // It solves pb of the bloc_fiss_new.py
3846   const double tol = 1e-3;
3847   if ( V < tol || V+tol >= 1. )
3848   {
3849     nn[0] = V < tol ? u_col1->second.front() : u_col1->second.back();
3850     nn[2] = V < tol ? u_col2->second.front() : u_col2->second.back();
3851     TopoDS_Edge edge;
3852     if ( V < tol )
3853     {
3854       edge = myBaseEdge;
3855     }
3856     else
3857     {
3858       TopoDS_Shape s = myHelper.GetSubShapeByNode( nn[0], myHelper.GetMeshDS() );
3859       if ( s.ShapeType() != TopAbs_EDGE )
3860         s = myHelper.GetSubShapeByNode( nn[2], myHelper.GetMeshDS() );
3861       if ( s.ShapeType() == TopAbs_EDGE )
3862         edge = TopoDS::Edge( s );
3863     }
3864     if ( !edge.IsNull() )
3865     {
3866       double u1 = myHelper.GetNodeU( edge, nn[0], nn[2] );
3867       double u3 = myHelper.GetNodeU( edge, nn[2], nn[0] );
3868       double u = u1 * ( 1 - hR ) + u3 * hR;
3869       TopLoc_Location loc; double f,l;
3870       Handle(Geom_Curve) curve = BRep_Tool::Curve( edge,loc,f,l );
3871       return curve->Value( u ).Transformed( loc );
3872     }
3873   }
3874   // END issue 0020680: Bad cell created by Radial prism in center of torus
3875
3876   vR = getRAndNodes( & u_col1->second, V, nn[0], nn[1] );
3877   vR = getRAndNodes( & u_col2->second, V, nn[2], nn[3] );
3878
3879   if ( !myShapeID2Surf.empty() ) // side is vertically composite
3880   {
3881     // find a FACE on which the 4 nodes lie
3882     TSideFace* me = (TSideFace*) this;
3883     int notFaceID1 = 0, notFaceID2 = 0;
3884     for ( int i = 0; i < 4; ++i )
3885       if ( nn[i]->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE ) // node on FACE
3886       {
3887         me->mySurface = me->myShapeID2Surf[ nn[i]->getshapeId() ];
3888         notFaceID2 = 0;
3889         break;
3890       }
3891       else if ( notFaceID1 == 0 ) // node on EDGE or VERTEX
3892       {
3893         me->mySurface  = me->myShapeID2Surf[ nn[i]->getshapeId() ];
3894         notFaceID1 = nn[i]->getshapeId();
3895       }
3896       else if ( notFaceID1 != nn[i]->getshapeId() ) // node on other EDGE or VERTEX
3897       {
3898         if ( mySurface != me->myShapeID2Surf[ nn[i]->getshapeId() ])
3899           notFaceID2 = nn[i]->getshapeId();
3900       }
3901     if ( notFaceID2 ) // no nodes of FACE and nodes are on different FACEs
3902     {
3903       SMESHDS_Mesh* meshDS = myHelper.GetMeshDS();
3904       TopoDS_Shape face = myHelper.GetCommonAncestor( meshDS->IndexToShape( notFaceID1 ),
3905                                                        meshDS->IndexToShape( notFaceID2 ),
3906                                                        *myHelper.GetMesh(),
3907                                                        TopAbs_FACE );
3908       if ( face.IsNull() ) 
3909         throw SALOME_Exception("StdMeshers_PrismAsBlock::TSideFace::Value() face.IsNull()");
3910       int faceID = meshDS->ShapeToIndex( face );
3911       me->mySurface = me->myShapeID2Surf[ faceID ];
3912       if ( !mySurface )
3913         throw SALOME_Exception("StdMeshers_PrismAsBlock::TSideFace::Value() !mySurface");
3914     }
3915   }
3916   ((TSideFace*) this)->myHelper.SetSubShape( mySurface->Face() );
3917
3918   gp_XY uv1 = myHelper.GetNodeUV( mySurface->Face(), nn[0], nn[2]);
3919   gp_XY uv2 = myHelper.GetNodeUV( mySurface->Face(), nn[1], nn[3]);
3920   gp_XY uv12 = uv1 * ( 1 - vR ) + uv2 * vR;
3921
3922   gp_XY uv3 = myHelper.GetNodeUV( mySurface->Face(), nn[2], nn[0]);
3923   gp_XY uv4 = myHelper.GetNodeUV( mySurface->Face(), nn[3], nn[1]);
3924   gp_XY uv34 = uv3 * ( 1 - vR ) + uv4 * vR;
3925
3926   gp_XY uv = uv12 * ( 1 - hR ) + uv34 * hR;
3927
3928   gp_Pnt p = mySurface->Value( uv.X(), uv.Y() );
3929   return p;
3930 }
3931
3932
3933 //================================================================================
3934 /*!
3935  * \brief Return boundary edge
3936   * \param edge - edge index
3937   * \retval TopoDS_Edge - found edge
3938  */
3939 //================================================================================
3940
3941 TopoDS_Edge StdMeshers_PrismAsBlock::TSideFace::GetEdge(const int iEdge) const
3942 {
3943   if ( !myComponents.empty() ) {
3944     switch ( iEdge ) {
3945     case V0_EDGE : return myComponents.front()->GetEdge( iEdge );
3946     case V1_EDGE : return myComponents.back() ->GetEdge( iEdge );
3947     default: return TopoDS_Edge();
3948     }
3949   }
3950   TopoDS_Shape edge;
3951   const SMDS_MeshNode* node = 0;
3952   SMESHDS_Mesh * meshDS = myHelper.GetMesh()->GetMeshDS();
3953   TNodeColumn* column;
3954
3955   switch ( iEdge ) {
3956   case TOP_EDGE:
3957   case BOTTOM_EDGE:
3958     column = & (( ++myParamToColumnMap->begin())->second );
3959     node = ( iEdge == TOP_EDGE ) ? column->back() : column->front();
3960     edge = myHelper.GetSubShapeByNode ( node, meshDS );
3961     if ( edge.ShapeType() == TopAbs_VERTEX ) {
3962       column = & ( myParamToColumnMap->begin()->second );
3963       node = ( iEdge == TOP_EDGE ) ? column->back() : column->front();
3964     }
3965     break;
3966   case V0_EDGE:
3967   case V1_EDGE: {
3968     bool back = ( iEdge == V1_EDGE );
3969     if ( !myIsForward ) back = !back;
3970     if ( back )
3971       column = & ( myParamToColumnMap->rbegin()->second );
3972     else
3973       column = & ( myParamToColumnMap->begin()->second );
3974     if ( column->size() > 0 )
3975       edge = myHelper.GetSubShapeByNode( (*column)[ 1 ], meshDS );
3976     if ( edge.IsNull() || edge.ShapeType() == TopAbs_VERTEX )
3977       node = column->front();
3978     break;
3979   }
3980   default:;
3981   }
3982   if ( !edge.IsNull() && edge.ShapeType() == TopAbs_EDGE )
3983     return TopoDS::Edge( edge );
3984
3985   // find edge by 2 vertices
3986   TopoDS_Shape V1 = edge;
3987   TopoDS_Shape V2 = myHelper.GetSubShapeByNode( node, meshDS );
3988   if ( !V2.IsNull() && V2.ShapeType() == TopAbs_VERTEX && !V2.IsSame( V1 ))
3989   {
3990     TopoDS_Shape ancestor = myHelper.GetCommonAncestor( V1, V2, *myHelper.GetMesh(), TopAbs_EDGE);
3991     if ( !ancestor.IsNull() )
3992       return TopoDS::Edge( ancestor );
3993   }
3994   return TopoDS_Edge();
3995 }
3996
3997 //================================================================================
3998 /*!
3999  * \brief Fill block sub-shapes
4000   * \param shapeMap - map to fill in
4001   * \retval int - nb inserted sub-shapes
4002  */
4003 //================================================================================
4004
4005 int StdMeshers_PrismAsBlock::TSideFace::InsertSubShapes(TBlockShapes& shapeMap) const
4006 {
4007   int nbInserted = 0;
4008
4009   // Insert edges
4010   vector< int > edgeIdVec;
4011   SMESH_Block::GetFaceEdgesIDs( myID, edgeIdVec );
4012
4013   for ( int i = BOTTOM_EDGE; i <=V1_EDGE ; ++i ) {
4014     TopoDS_Edge e = GetEdge( i );
4015     if ( !e.IsNull() ) {
4016       nbInserted += SMESH_Block::Insert( e, edgeIdVec[ i ], shapeMap);
4017     }
4018   }
4019
4020   // Insert corner vertices
4021
4022   TParam2ColumnIt col1, col2 ;
4023   vector< int > vertIdVec;
4024
4025   // from V0 column
4026   SMESH_Block::GetEdgeVertexIDs( edgeIdVec[ V0_EDGE ], vertIdVec);
4027   GetColumns(0, col1, col2 );
4028   const SMDS_MeshNode* node0 = col1->second.front();
4029   const SMDS_MeshNode* node1 = col1->second.back();
4030   TopoDS_Shape v0 = myHelper.GetSubShapeByNode( node0, myHelper.GetMeshDS());
4031   TopoDS_Shape v1 = myHelper.GetSubShapeByNode( node1, myHelper.GetMeshDS());
4032   if ( v0.ShapeType() == TopAbs_VERTEX ) {
4033     nbInserted += SMESH_Block::Insert( v0, vertIdVec[ 0 ], shapeMap);
4034   }
4035   if ( v1.ShapeType() == TopAbs_VERTEX ) {
4036     nbInserted += SMESH_Block::Insert( v1, vertIdVec[ 1 ], shapeMap);
4037   }
4038   
4039   // from V1 column
4040   SMESH_Block::GetEdgeVertexIDs( edgeIdVec[ V1_EDGE ], vertIdVec);
4041   GetColumns(1, col1, col2 );
4042   node0 = col2->second.front();
4043   node1 = col2->second.back();
4044   v0 = myHelper.GetSubShapeByNode( node0, myHelper.GetMeshDS());
4045   v1 = myHelper.GetSubShapeByNode( node1, myHelper.GetMeshDS());
4046   if ( v0.ShapeType() == TopAbs_VERTEX ) {
4047     nbInserted += SMESH_Block::Insert( v0, vertIdVec[ 0 ], shapeMap);
4048   }
4049   if ( v1.ShapeType() == TopAbs_VERTEX ) {
4050     nbInserted += SMESH_Block::Insert( v1, vertIdVec[ 1 ], shapeMap);
4051   }
4052
4053 //   TopoDS_Vertex V0, V1, Vcom;
4054 //   TopExp::Vertices( myBaseEdge, V0, V1, true );
4055 //   if ( !myIsForward ) std::swap( V0, V1 );
4056
4057 //   // bottom vertex IDs
4058 //   SMESH_Block::GetEdgeVertexIDs( edgeIdVec[ _u0 ], vertIdVec);
4059 //   SMESH_Block::Insert( V0, vertIdVec[ 0 ], shapeMap);
4060 //   SMESH_Block::Insert( V1, vertIdVec[ 1 ], shapeMap);
4061
4062 //   TopoDS_Edge sideEdge = GetEdge( V0_EDGE );
4063 //   if ( sideEdge.IsNull() || !TopExp::CommonVertex( botEdge, sideEdge, Vcom ))
4064 //     return false;
4065
4066 //   // insert one side edge
4067 //   int edgeID;
4068 //   if ( Vcom.IsSame( V0 )) edgeID = edgeIdVec[ _v0 ];
4069 //   else                    edgeID = edgeIdVec[ _v1 ];
4070 //   SMESH_Block::Insert( sideEdge, edgeID, shapeMap);
4071
4072 //   // top vertex of the side edge
4073 //   SMESH_Block::GetEdgeVertexIDs( edgeID, vertIdVec);
4074 //   TopoDS_Vertex Vtop = TopExp::FirstVertex( sideEdge );
4075 //   if ( Vcom.IsSame( Vtop ))
4076 //     Vtop = TopExp::LastVertex( sideEdge );
4077 //   SMESH_Block::Insert( Vtop, vertIdVec[ 1 ], shapeMap);
4078
4079 //   // other side edge
4080 //   sideEdge = GetEdge( V1_EDGE );
4081 //   if ( sideEdge.IsNull() )
4082 //     return false;
4083 //   if ( edgeID = edgeIdVec[ _v1 ]) edgeID = edgeIdVec[ _v0 ];
4084 //   else                            edgeID = edgeIdVec[ _v1 ];
4085 //   SMESH_Block::Insert( sideEdge, edgeID, shapeMap);
4086   
4087 //   // top edge
4088 //   TopoDS_Edge topEdge = GetEdge( TOP_EDGE );
4089 //   SMESH_Block::Insert( topEdge, edgeIdVec[ _u1 ], shapeMap);
4090
4091 //   // top vertex of the other side edge
4092 //   if ( !TopExp::CommonVertex( topEdge, sideEdge, Vcom ))
4093 //     return false;
4094 //   SMESH_Block::GetEdgeVertexIDs( edgeID, vertIdVec );
4095 //   SMESH_Block::Insert( Vcom, vertIdVec[ 1 ], shapeMap);
4096
4097   return nbInserted;
4098 }
4099
4100 //================================================================================
4101 /*!
4102  * \brief Dump ids of nodes of sides
4103  */
4104 //================================================================================
4105
4106 void StdMeshers_PrismAsBlock::TSideFace::dumpNodes(int nbNodes) const
4107 {
4108 #ifdef _DEBUG_
4109   cout << endl << "NODES OF FACE "; SMESH_Block::DumpShapeID( myID, cout ) << endl;
4110   THorizontalEdgeAdaptor* hSize0 = (THorizontalEdgeAdaptor*) HorizCurve(0);
4111   cout << "Horiz side 0: "; hSize0->dumpNodes(nbNodes); cout << endl;
4112   THorizontalEdgeAdaptor* hSize1 = (THorizontalEdgeAdaptor*) HorizCurve(1);
4113   cout << "Horiz side 1: "; hSize1->dumpNodes(nbNodes); cout << endl;
4114   TVerticalEdgeAdaptor* vSide0 = (TVerticalEdgeAdaptor*) VertiCurve(0);
4115   cout << "Verti side 0: "; vSide0->dumpNodes(nbNodes); cout << endl;
4116   TVerticalEdgeAdaptor* vSide1 = (TVerticalEdgeAdaptor*) VertiCurve(1);
4117   cout << "Verti side 1: "; vSide1->dumpNodes(nbNodes); cout << endl;
4118   delete hSize0; delete hSize1; delete vSide0; delete vSide1;
4119 #endif
4120 }
4121
4122 //================================================================================
4123 /*!
4124  * \brief Creates TVerticalEdgeAdaptor 
4125   * \param columnsMap - node column map
4126   * \param parameter - normalized parameter
4127  */
4128 //================================================================================
4129
4130 StdMeshers_PrismAsBlock::TVerticalEdgeAdaptor::
4131 TVerticalEdgeAdaptor( const TParam2ColumnMap* columnsMap, const double parameter)
4132 {
4133   myNodeColumn = & getColumn( columnsMap, parameter )->second;
4134 }
4135
4136 //================================================================================
4137 /*!
4138  * \brief Return coordinates for the given normalized parameter
4139   * \param U - normalized parameter
4140   * \retval gp_Pnt - coordinates
4141  */
4142 //================================================================================
4143
4144 gp_Pnt StdMeshers_PrismAsBlock::TVerticalEdgeAdaptor::Value(const Standard_Real U) const
4145 {
4146   const SMDS_MeshNode* n1;
4147   const SMDS_MeshNode* n2;
4148   double r = getRAndNodes( myNodeColumn, U, n1, n2 );
4149   return gpXYZ(n1) * ( 1 - r ) + gpXYZ(n2) * r;
4150 }
4151
4152 //================================================================================
4153 /*!
4154  * \brief Dump ids of nodes
4155  */
4156 //================================================================================
4157
4158 void StdMeshers_PrismAsBlock::TVerticalEdgeAdaptor::dumpNodes(int nbNodes) const
4159 {
4160 #ifdef _DEBUG_
4161   for ( int i = 0; i < nbNodes && i < myNodeColumn->size(); ++i )
4162     cout << (*myNodeColumn)[i]->GetID() << " ";
4163   if ( nbNodes < myNodeColumn->size() )
4164     cout << myNodeColumn->back()->GetID();
4165 #endif
4166 }
4167
4168 //================================================================================
4169 /*!
4170  * \brief Return coordinates for the given normalized parameter
4171   * \param U - normalized parameter
4172   * \retval gp_Pnt - coordinates
4173  */
4174 //================================================================================
4175
4176 gp_Pnt StdMeshers_PrismAsBlock::THorizontalEdgeAdaptor::Value(const Standard_Real U) const
4177 {
4178   return mySide->TSideFace::Value( U, myV );
4179 }
4180
4181 //================================================================================
4182 /*!
4183  * \brief Dump ids of <nbNodes> first nodes and the last one
4184  */
4185 //================================================================================
4186
4187 void StdMeshers_PrismAsBlock::THorizontalEdgeAdaptor::dumpNodes(int nbNodes) const
4188 {
4189 #ifdef _DEBUG_
4190   // Not bedugged code. Last node is sometimes incorrect
4191   const TSideFace* side = mySide;
4192   double u = 0;
4193   if ( mySide->IsComplex() )
4194     side = mySide->GetComponent(0,u);
4195
4196   TParam2ColumnIt col, col2;
4197   TParam2ColumnMap* u2cols = side->GetColumns();
4198   side->GetColumns( u , col, col2 );
4199   
4200   int j, i = myV ? mySide->ColumnHeight()-1 : 0;
4201
4202   const SMDS_MeshNode* n = 0;
4203   const SMDS_MeshNode* lastN
4204     = side->IsForward() ? u2cols->rbegin()->second[ i ] : u2cols->begin()->second[ i ];
4205   for ( j = 0; j < nbNodes && n != lastN; ++j )
4206   {
4207     n = col->second[ i ];
4208     cout << n->GetID() << " ";
4209     if ( side->IsForward() )
4210       ++col;
4211     else
4212       --col;
4213   }
4214
4215   // last node
4216   u = 1;
4217   if ( mySide->IsComplex() )
4218     side = mySide->GetComponent(1,u);
4219
4220   side->GetColumns( u , col, col2 );
4221   if ( n != col->second[ i ] )
4222     cout << col->second[ i ]->GetID();
4223 #endif
4224 }
4225
4226 //================================================================================
4227 /*!
4228  * \brief Costructor of TPCurveOnHorFaceAdaptor fills its map of
4229  * normalized parameter to node UV on a horizontal face
4230  *  \param [in] sideFace - lateral prism side
4231  *  \param [in] isTop - is \a horFace top or bottom of the prism
4232  *  \param [in] horFace - top or bottom face of the prism
4233  */
4234 //================================================================================
4235
4236 StdMeshers_PrismAsBlock::
4237 TPCurveOnHorFaceAdaptor::TPCurveOnHorFaceAdaptor( const TSideFace*   sideFace,
4238                                                   const bool         isTop,
4239                                                   const TopoDS_Face& horFace)
4240 {
4241   if ( sideFace && !horFace.IsNull() )
4242   {
4243     //cout << "\n\t FACE " << sideFace->FaceID() << endl;
4244     const int Z = isTop ? sideFace->ColumnHeight() - 1 : 0;
4245     map<double, const SMDS_MeshNode* > u2nodes;
4246     sideFace->GetNodesAtZ( Z, u2nodes );
4247     if ( u2nodes.empty() )
4248       return;
4249
4250     SMESH_MesherHelper helper( *sideFace->GetMesh() );
4251     helper.SetSubShape( horFace );
4252
4253     bool okUV;
4254     gp_XY uv;
4255     double f,l;
4256     Handle(Geom2d_Curve) C2d;
4257     int edgeID = -1;
4258     const double tol = 10 * helper.MaxTolerance( horFace );
4259     const SMDS_MeshNode* prevNode = u2nodes.rbegin()->second;
4260
4261     map<double, const SMDS_MeshNode* >::iterator u2n = u2nodes.begin();
4262     for ( ; u2n != u2nodes.end(); ++u2n )
4263     {
4264       const SMDS_MeshNode* n = u2n->second;
4265       okUV = false;
4266       if ( n->GetPosition()->GetTypeOfPosition() == SMDS_TOP_EDGE )
4267       {
4268         if ( n->getshapeId() != edgeID )
4269         {
4270           C2d.Nullify();
4271           edgeID = n->getshapeId();
4272           TopoDS_Shape S = helper.GetSubShapeByNode( n, helper.GetMeshDS() );
4273           if ( !S.IsNull() && S.ShapeType() == TopAbs_EDGE )
4274           {
4275             C2d = BRep_Tool::CurveOnSurface( TopoDS::Edge( S ), horFace, f,l );
4276           }
4277         }
4278         if ( !C2d.IsNull() )
4279         {
4280           double u = static_cast< const SMDS_EdgePosition* >( n->GetPosition() )->GetUParameter();
4281           if ( f <= u && u <= l )
4282           {
4283             uv = C2d->Value( u ).XY();
4284             okUV = helper.CheckNodeUV( horFace, n, uv, tol );
4285           }
4286         }
4287       }
4288       if ( !okUV )
4289         uv = helper.GetNodeUV( horFace, n, prevNode, &okUV );
4290
4291       myUVmap.insert( myUVmap.end(), make_pair( u2n->first, uv ));
4292       // cout << n->getshapeId() << " N " << n->GetID()
4293       //      << " \t" << uv.X() << ", " << uv.Y() << " \t" << u2n->first << endl;
4294
4295       prevNode = n;
4296     }
4297   }
4298 }
4299
4300 //================================================================================
4301 /*!
4302  * \brief Return UV on pcurve for the given normalized parameter
4303   * \param U - normalized parameter
4304   * \retval gp_Pnt - coordinates
4305  */
4306 //================================================================================
4307
4308 gp_Pnt2d StdMeshers_PrismAsBlock::TPCurveOnHorFaceAdaptor::Value(const Standard_Real U) const
4309 {
4310   map< double, gp_XY >::const_iterator i1 = myUVmap.upper_bound( U );
4311
4312   if ( i1 == myUVmap.end() )
4313     return myUVmap.empty() ? gp_XY(0,0) : myUVmap.rbegin()->second;
4314
4315   if ( i1 == myUVmap.begin() )
4316     return (*i1).second;
4317
4318   map< double, gp_XY >::const_iterator i2 = i1--;
4319
4320   double r = ( U - i1->first ) / ( i2->first - i1->first );
4321   return i1->second * ( 1 - r ) + i2->second * r;
4322 }
4323
4324 //================================================================================
4325 /*!
4326  * \brief Projects internal nodes using transformation found by boundary nodes
4327  */
4328 //================================================================================
4329
4330 bool StdMeshers_Sweeper::projectIntPoints(const vector< gp_XYZ >&    fromBndPoints,
4331                                           const vector< gp_XYZ >&    toBndPoints,
4332                                           const vector< gp_XYZ >&    fromIntPoints,
4333                                           vector< gp_XYZ >&          toIntPoints,
4334                                           NSProjUtils::TrsfFinder3D& trsf,
4335                                           vector< gp_XYZ > *         bndError)
4336 {
4337   // find transformation
4338   if ( trsf.IsIdentity() && !trsf.Solve( fromBndPoints, toBndPoints ))
4339     return false;
4340
4341   // compute internal points using the found trsf
4342   for ( size_t iP = 0; iP < fromIntPoints.size(); ++iP )
4343   {
4344     toIntPoints[ iP ] = trsf.Transform( fromIntPoints[ iP ]);
4345   }
4346
4347   // compute boundary error
4348   if ( bndError )
4349   {
4350     bndError->resize( fromBndPoints.size() );
4351     gp_XYZ fromTrsf;
4352     for ( size_t iP = 0; iP < fromBndPoints.size(); ++iP )
4353     {
4354       fromTrsf = trsf.Transform( fromBndPoints[ iP ] );
4355       (*bndError)[ iP ]  = toBndPoints[ iP ] - fromTrsf;
4356     }
4357   }
4358   return true;
4359 }
4360
4361 //================================================================================
4362 /*!
4363  * \brief Add boundary error to ineternal points
4364  */
4365 //================================================================================
4366
4367 void StdMeshers_Sweeper::applyBoundaryError(const vector< gp_XYZ >& bndPoints,
4368                                             const vector< gp_XYZ >& bndError1,
4369                                             const vector< gp_XYZ >& bndError2,
4370                                             const double            r,
4371                                             vector< gp_XYZ >&       intPoints,
4372                                             vector< double >&       int2BndDist)
4373 {
4374   // fix each internal point
4375   const double eps = 1e-100;
4376   for ( size_t iP = 0; iP < intPoints.size(); ++iP )
4377   {
4378     gp_XYZ & intPnt = intPoints[ iP ];
4379
4380     // compute distance from intPnt to each boundary node
4381     double int2BndDistSum = 0;
4382     for ( size_t iBnd = 0; iBnd < bndPoints.size(); ++iBnd )
4383     {
4384       int2BndDist[ iBnd ] = 1 / (( intPnt - bndPoints[ iBnd ]).SquareModulus() + eps );
4385       int2BndDistSum += int2BndDist[ iBnd ];
4386     }
4387
4388     // apply bndError
4389     for ( size_t iBnd = 0; iBnd < bndPoints.size(); ++iBnd )
4390     {
4391       intPnt += bndError1[ iBnd ] * ( 1 - r ) * int2BndDist[ iBnd ] / int2BndDistSum;
4392       intPnt += bndError2[ iBnd ] * r         * int2BndDist[ iBnd ] / int2BndDistSum;
4393     }
4394   }
4395 }
4396
4397 //================================================================================
4398 /*!
4399  * \brief Creates internal nodes of the prism
4400  */
4401 //================================================================================
4402
4403 bool StdMeshers_Sweeper::ComputeNodes( SMESH_MesherHelper& helper,
4404                                        const double        tol)
4405 {
4406   const size_t zSize = myBndColumns[0]->size();
4407   const size_t zSrc = 0, zTgt = zSize-1;
4408   if ( zSize < 3 ) return true;
4409
4410   vector< vector< gp_XYZ > > intPntsOfLayer( zSize ); // node coodinates to compute
4411   // set coordinates of src and tgt nodes
4412   for ( size_t z = 0; z < intPntsOfLayer.size(); ++z )
4413     intPntsOfLayer[ z ].resize( myIntColumns.size() );
4414   for ( size_t iP = 0; iP < myIntColumns.size(); ++iP )
4415   {
4416     intPntsOfLayer[ zSrc ][ iP ] = intPoint( iP, zSrc );
4417     intPntsOfLayer[ zTgt ][ iP ] = intPoint( iP, zTgt );
4418   }
4419
4420   // compute coordinates of internal nodes by projecting (transfroming) src and tgt
4421   // nodes towards the central layer
4422
4423   vector< NSProjUtils::TrsfFinder3D > trsfOfLayer( zSize );
4424   vector< vector< gp_XYZ > >          bndError( zSize );
4425
4426   // boundary points used to compute an affine transformation from a layer to a next one
4427   vector< gp_XYZ > fromSrcBndPnts( myBndColumns.size() ), fromTgtBndPnts( myBndColumns.size() );
4428   vector< gp_XYZ > toSrcBndPnts  ( myBndColumns.size() ), toTgtBndPnts  ( myBndColumns.size() );
4429   for ( size_t iP = 0; iP < myBndColumns.size(); ++iP )
4430   {
4431     fromSrcBndPnts[ iP ] = bndPoint( iP, zSrc );
4432     fromTgtBndPnts[ iP ] = bndPoint( iP, zTgt );
4433   }
4434
4435   size_t zS = zSrc + 1;
4436   size_t zT = zTgt - 1;
4437   for ( ; zS < zT; ++zS, --zT ) // vertical loop on layers
4438   {
4439     for ( size_t iP = 0; iP < myBndColumns.size(); ++iP )
4440     {
4441       toSrcBndPnts[ iP ] = bndPoint( iP, zS );
4442       toTgtBndPnts[ iP ] = bndPoint( iP, zT );
4443     }
4444     if (! projectIntPoints( fromSrcBndPnts, toSrcBndPnts,
4445                             intPntsOfLayer[ zS-1 ], intPntsOfLayer[ zS ],
4446                             trsfOfLayer   [ zS-1 ], & bndError[ zS-1 ]))
4447       return false;
4448     if (! projectIntPoints( fromTgtBndPnts, toTgtBndPnts,
4449                             intPntsOfLayer[ zT+1 ], intPntsOfLayer[ zT ],
4450                             trsfOfLayer   [ zT+1 ], & bndError[ zT+1 ]))
4451       return false;
4452
4453     // if ( zT == zTgt - 1 )
4454     // {
4455     //   for ( size_t iP = 0; iP < myBndColumns.size(); ++iP )
4456     //   {
4457     //     gp_XYZ fromTrsf = trsfOfLayer   [ zT+1].Transform( fromTgtBndPnts[ iP ] );
4458     //     cout << "mesh.AddNode( "
4459     //          << fromTrsf.X() << ", "
4460     //          << fromTrsf.Y() << ", "
4461     //          << fromTrsf.Z() << ") " << endl;
4462     //   }
4463     //   for ( size_t iP = 0; iP < myIntColumns.size(); ++iP )
4464     //     cout << "mesh.AddNode( "
4465     //          << intPntsOfLayer[ zT ][ iP ].X() << ", "
4466     //          << intPntsOfLayer[ zT ][ iP ].Y() << ", "
4467     //          << intPntsOfLayer[ zT ][ iP ].Z() << ") " << endl;
4468     // }
4469
4470     fromTgtBndPnts.swap( toTgtBndPnts );
4471     fromSrcBndPnts.swap( toSrcBndPnts );
4472   }
4473
4474   // Compute two projections of internal points to the central layer
4475   // in order to evaluate an error of internal points
4476
4477   bool centerIntErrorIsSmall;
4478   vector< gp_XYZ > centerSrcIntPnts( myIntColumns.size() );
4479   vector< gp_XYZ > centerTgtIntPnts( myIntColumns.size() );
4480
4481   for ( size_t iP = 0; iP < myBndColumns.size(); ++iP )
4482   {
4483     toSrcBndPnts[ iP ] = bndPoint( iP, zS );
4484     toTgtBndPnts[ iP ] = bndPoint( iP, zT );
4485   }
4486   if (! projectIntPoints( fromSrcBndPnts, toSrcBndPnts,
4487                           intPntsOfLayer[ zS-1 ], centerSrcIntPnts,
4488                           trsfOfLayer   [ zS-1 ], & bndError[ zS-1 ]))
4489     return false;
4490   if (! projectIntPoints( fromTgtBndPnts, toTgtBndPnts,
4491                           intPntsOfLayer[ zT+1 ], centerTgtIntPnts,
4492                           trsfOfLayer   [ zT+1 ], & bndError[ zT+1 ]))
4493     return false;
4494
4495   // evaluate an error of internal points on the central layer
4496   centerIntErrorIsSmall = true;
4497   if ( zS == zT ) // odd zSize
4498   {
4499     for ( size_t iP = 0; ( iP < myIntColumns.size() && centerIntErrorIsSmall ); ++iP )
4500       centerIntErrorIsSmall =
4501         (centerSrcIntPnts[ iP ] - centerTgtIntPnts[ iP ]).SquareModulus() < tol*tol;
4502   }
4503   else // even zSize
4504   {
4505     for ( size_t iP = 0; ( iP < myIntColumns.size() && centerIntErrorIsSmall ); ++iP )
4506       centerIntErrorIsSmall =
4507         (intPntsOfLayer[ zS-1 ][ iP ] - centerTgtIntPnts[ iP ]).SquareModulus() < tol*tol;
4508   }
4509
4510   // Evaluate an error of boundary points
4511
4512   bool bndErrorIsSmall = true;
4513   for ( size_t iP = 0; ( iP < myBndColumns.size() && bndErrorIsSmall ); ++iP )
4514   {
4515     double sumError = 0;
4516     for ( size_t z = 1; z < zS; ++z ) // loop on layers
4517       sumError += ( bndError[ z-1     ][ iP ].Modulus() +
4518                     bndError[ zSize-z ][ iP ].Modulus() );
4519
4520     bndErrorIsSmall = ( sumError < tol );
4521   }
4522
4523   // compute final points on the central layer
4524   std::vector< double > int2BndDist( myBndColumns.size() ); // work array of applyBoundaryError()
4525   double r = zS / ( zSize - 1.);
4526   if ( zS == zT )
4527   {
4528     for ( size_t iP = 0; iP < myIntColumns.size(); ++iP )
4529     {
4530       intPntsOfLayer[ zS ][ iP ] =
4531         ( 1 - r ) * centerSrcIntPnts[ iP ] + r * centerTgtIntPnts[ iP ];
4532     }
4533     if ( !bndErrorIsSmall )
4534     {
4535       applyBoundaryError( toSrcBndPnts, bndError[ zS-1 ], bndError[ zS+1 ], r,
4536                           intPntsOfLayer[ zS ], int2BndDist );
4537     }
4538   }
4539   else
4540   {
4541     for ( size_t iP = 0; iP < myIntColumns.size(); ++iP )
4542     {
4543       intPntsOfLayer[ zS ][ iP ] =
4544         r * intPntsOfLayer[ zS ][ iP ] + ( 1 - r ) * centerSrcIntPnts[ iP ];
4545       intPntsOfLayer[ zT ][ iP ] =
4546         r * intPntsOfLayer[ zT ][ iP ] + ( 1 - r ) * centerTgtIntPnts[ iP ];
4547     }
4548     if ( !bndErrorIsSmall )
4549     {
4550       applyBoundaryError( toSrcBndPnts, bndError[ zS-1 ], bndError[ zS+1 ], r,
4551                           intPntsOfLayer[ zS ], int2BndDist );
4552       applyBoundaryError( toTgtBndPnts, bndError[ zT+1 ], bndError[ zT-1 ], r,
4553                           intPntsOfLayer[ zT ], int2BndDist );
4554     }
4555   }
4556
4557   //centerIntErrorIsSmall = true;
4558   //bndErrorIsSmall = true;
4559   if ( !centerIntErrorIsSmall )
4560   {
4561     // Compensate the central error; continue adding projection
4562     // by going from central layer to the source and target ones
4563
4564     vector< gp_XYZ >& fromSrcIntPnts = centerSrcIntPnts;
4565     vector< gp_XYZ >& fromTgtIntPnts = centerTgtIntPnts;
4566     vector< gp_XYZ >  toSrcIntPnts( myIntColumns.size() );
4567     vector< gp_XYZ >  toTgtIntPnts( myIntColumns.size() );
4568     vector< gp_XYZ >  srcBndError( myBndColumns.size() );
4569     vector< gp_XYZ >  tgtBndError( myBndColumns.size() );
4570
4571     fromTgtBndPnts.swap( toTgtBndPnts );
4572     fromSrcBndPnts.swap( toSrcBndPnts );
4573
4574     for ( ++zS, --zT; zS < zTgt; ++zS, --zT ) // vertical loop on layers
4575     {
4576       // invert transformation
4577       if ( !trsfOfLayer[ zS+1 ].Invert() )
4578         trsfOfLayer[ zS+1 ] = NSProjUtils::TrsfFinder3D(); // to recompute
4579       if ( !trsfOfLayer[ zT-1 ].Invert() )
4580         trsfOfLayer[ zT-1 ] = NSProjUtils::TrsfFinder3D();
4581
4582       // project internal nodes and compute bnd error
4583       for ( size_t iP = 0; iP < myBndColumns.size(); ++iP )
4584       {
4585         toSrcBndPnts[ iP ] = bndPoint( iP, zS );
4586         toTgtBndPnts[ iP ] = bndPoint( iP, zT );
4587       }
4588       projectIntPoints( fromSrcBndPnts, toSrcBndPnts,
4589                         fromSrcIntPnts, toSrcIntPnts,
4590                         trsfOfLayer[ zS+1 ], & srcBndError );
4591       projectIntPoints( fromTgtBndPnts, toTgtBndPnts,
4592                         fromTgtIntPnts, toTgtIntPnts,
4593                         trsfOfLayer[ zT-1 ], & tgtBndError );
4594
4595       // if ( zS == zTgt - 1 )
4596       // {
4597       //   cout << "mesh2 = smesh.Mesh()" << endl;
4598       //   for ( size_t iP = 0; iP < myBndColumns.size(); ++iP )
4599       //   {
4600       //     gp_XYZ fromTrsf = trsfOfLayer   [ zS+1].Transform( fromSrcBndPnts[ iP ] );
4601       //     cout << "mesh2.AddNode( "
4602       //          << fromTrsf.X() << ", "
4603       //          << fromTrsf.Y() << ", "
4604       //          << fromTrsf.Z() << ") " << endl;
4605       //   }
4606       //   for ( size_t iP = 0; iP < myIntColumns.size(); ++iP )
4607       //     cout << "mesh2.AddNode( "
4608       //          << toSrcIntPnts[ iP ].X() << ", "
4609       //          << toSrcIntPnts[ iP ].Y() << ", "
4610       //          << toSrcIntPnts[ iP ].Z() << ") " << endl;
4611       // }
4612
4613       // sum up 2 projections
4614       r = zS / ( zSize - 1.);
4615       vector< gp_XYZ >& zSIntPnts = intPntsOfLayer[ zS ];
4616       vector< gp_XYZ >& zTIntPnts = intPntsOfLayer[ zT ];
4617       for ( size_t iP = 0; iP < myIntColumns.size(); ++iP )
4618       {
4619         zSIntPnts[ iP ] = r * zSIntPnts[ iP ]  +  ( 1 - r ) * toSrcIntPnts[ iP ];
4620         zTIntPnts[ iP ] = r * zTIntPnts[ iP ]  +  ( 1 - r ) * toTgtIntPnts[ iP ];
4621       }
4622
4623       // compensate bnd error
4624       if ( !bndErrorIsSmall )
4625       {
4626         applyBoundaryError( toSrcBndPnts, srcBndError, bndError[ zS+1 ], r,
4627                             intPntsOfLayer[ zS ], int2BndDist );
4628         applyBoundaryError( toTgtBndPnts, tgtBndError, bndError[ zT-1 ], r,
4629                             intPntsOfLayer[ zT ], int2BndDist );
4630       }
4631
4632       fromSrcBndPnts.swap( toSrcBndPnts );
4633       fromSrcIntPnts.swap( toSrcIntPnts );
4634       fromTgtBndPnts.swap( toTgtBndPnts );
4635       fromTgtIntPnts.swap( toTgtIntPnts );
4636     }
4637   }  // if ( !centerIntErrorIsSmall )
4638
4639   else if ( !bndErrorIsSmall )
4640   {
4641     zS = zSrc + 1;
4642     zT = zTgt - 1;
4643     for ( ; zS < zT; ++zS, --zT ) // vertical loop on layers
4644     {
4645       for ( size_t iP = 0; iP < myBndColumns.size(); ++iP )
4646       {
4647         toSrcBndPnts[ iP ] = bndPoint( iP, zS );
4648         toTgtBndPnts[ iP ] = bndPoint( iP, zT );
4649       }
4650       // compensate bnd error
4651       applyBoundaryError( toSrcBndPnts, bndError[ zS-1 ], bndError[ zS-1 ], 0.5,
4652                           intPntsOfLayer[ zS ], int2BndDist );
4653       applyBoundaryError( toTgtBndPnts, bndError[ zT+1 ], bndError[ zT+1 ], 0.5,
4654                           intPntsOfLayer[ zT ], int2BndDist );
4655     }
4656   }
4657
4658   // cout << "centerIntErrorIsSmall = " << centerIntErrorIsSmall<< endl;
4659   // cout << "bndErrorIsSmall = " << bndErrorIsSmall<< endl;
4660
4661   // Create nodes
4662   for ( size_t iP = 0; iP < myIntColumns.size(); ++iP )
4663   {
4664     vector< const SMDS_MeshNode* > & nodeCol = *myIntColumns[ iP ];
4665     for ( size_t z = zSrc + 1; z < zTgt; ++z ) // vertical loop on layers
4666     {
4667       const gp_XYZ & xyz = intPntsOfLayer[ z ][ iP ];
4668       if ( !( nodeCol[ z ] = helper.AddNode( xyz.X(), xyz.Y(), xyz.Z() )))
4669         return false;
4670     }
4671   }
4672
4673   return true;
4674 }