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