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