Back to index

salome-smesh  6.5.0
StdMeshers_ViscousLayers.cxx
Go to the documentation of this file.
00001 // Copyright (C) 2007-2012  CEA/DEN, EDF R&D, OPEN CASCADE
00002 //
00003 // This library is free software; you can redistribute it and/or
00004 // modify it under the terms of the GNU Lesser General Public
00005 // License as published by the Free Software Foundation; either
00006 // version 2.1 of the License.
00007 //
00008 // This library is distributed in the hope that it will be useful,
00009 // but WITHOUT ANY WARRANTY; without even the implied warranty of
00010 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00011 // Lesser General Public License for more details.
00012 //
00013 // You should have received a copy of the GNU Lesser General Public
00014 // License along with this library; if not, write to the Free Software
00015 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
00016 //
00017 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
00018 //
00019 
00020 // File      : StdMeshers_ViscousLayers.cxx
00021 // Created   : Wed Dec  1 15:15:34 2010
00022 // Author    : Edward AGAPOV (eap)
00023 
00024 #include "StdMeshers_ViscousLayers.hxx"
00025 
00026 #include "SMDS_EdgePosition.hxx"
00027 #include "SMDS_FaceOfNodes.hxx"
00028 #include "SMDS_FacePosition.hxx"
00029 #include "SMDS_MeshNode.hxx"
00030 #include "SMDS_SetIterator.hxx"
00031 #include "SMESHDS_Group.hxx"
00032 #include "SMESHDS_Hypothesis.hxx"
00033 #include "SMESH_Algo.hxx"
00034 #include "SMESH_ComputeError.hxx"
00035 #include "SMESH_ControlsDef.hxx"
00036 #include "SMESH_Gen.hxx"
00037 #include "SMESH_Group.hxx"
00038 #include "SMESH_Mesh.hxx"
00039 #include "SMESH_MesherHelper.hxx"
00040 #include "SMESH_ProxyMesh.hxx"
00041 #include "SMESH_subMesh.hxx"
00042 #include "SMESH_subMeshEventListener.hxx"
00043 
00044 #include "utilities.h"
00045 
00046 #include <BRepAdaptor_Curve2d.hxx>
00047 #include <BRep_Tool.hxx>
00048 #include <Bnd_B2d.hxx>
00049 #include <Bnd_B3d.hxx>
00050 #include <ElCLib.hxx>
00051 #include <GCPnts_AbscissaPoint.hxx>
00052 #include <Geom2d_Circle.hxx>
00053 #include <Geom2d_Line.hxx>
00054 #include <Geom2d_TrimmedCurve.hxx>
00055 #include <GeomAdaptor_Curve.hxx>
00056 #include <Geom_Circle.hxx>
00057 #include <Geom_Curve.hxx>
00058 #include <Geom_Line.hxx>
00059 #include <Geom_TrimmedCurve.hxx>
00060 #include <Precision.hxx>
00061 #include <Standard_ErrorHandler.hxx>
00062 #include <TColStd_Array1OfReal.hxx>
00063 #include <TopExp.hxx>
00064 #include <TopExp_Explorer.hxx>
00065 #include <TopTools_IndexedMapOfShape.hxx>
00066 #include <TopTools_MapOfShape.hxx>
00067 #include <TopoDS.hxx>
00068 #include <TopoDS_Edge.hxx>
00069 #include <TopoDS_Face.hxx>
00070 #include <TopoDS_Vertex.hxx>
00071 #include <gp_Ax1.hxx>
00072 #include <gp_Vec.hxx>
00073 #include <gp_XY.hxx>
00074 
00075 #include <list>
00076 #include <string>
00077 #include <cmath>
00078 #include <limits>
00079 
00080 //#define __myDEBUG
00081 
00082 using namespace std;
00083 
00084 //================================================================================
00085 namespace VISCOUS
00086 {
00087   typedef int TGeomID;
00088 
00089   enum UIndex { U_TGT = 1, U_SRC, LEN_TGT };
00090 
00095   struct _MeshOfSolid : public SMESH_ProxyMesh,
00096                         public SMESH_subMeshEventListenerData
00097   {
00098     bool _n2nMapComputed;
00099 
00100     _MeshOfSolid( SMESH_Mesh* mesh)
00101       :SMESH_subMeshEventListenerData( /*isDeletable=*/true),_n2nMapComputed(false)
00102     {
00103       SMESH_ProxyMesh::setMesh( *mesh );
00104     }
00105 
00106     // returns submesh for a geom face
00107     SMESH_ProxyMesh::SubMesh* getFaceSubM(const TopoDS_Face& F, bool create=false)
00108     {
00109       TGeomID i = SMESH_ProxyMesh::shapeIndex(F);
00110       return create ? SMESH_ProxyMesh::getProxySubMesh(i) : findProxySubMesh(i);
00111     }
00112     void setNode2Node(const SMDS_MeshNode*                 srcNode,
00113                       const SMDS_MeshNode*                 proxyNode,
00114                       const SMESH_ProxyMesh::SubMesh* subMesh)
00115     {
00116       SMESH_ProxyMesh::setNode2Node( srcNode,proxyNode,subMesh);
00117     }
00118   };
00119   //--------------------------------------------------------------------------------
00124   class _SrinkShapeListener : SMESH_subMeshEventListener
00125   {
00126     _SrinkShapeListener()
00127       : SMESH_subMeshEventListener(/*isDeletable=*/false,
00128                                    "StdMeshers_ViscousLayers::_SrinkShapeListener") {}
00129     static SMESH_subMeshEventListener* Get() { static _SrinkShapeListener l; return &l; }
00130   public:
00131     virtual void ProcessEvent(const int                       event,
00132                               const int                       eventType,
00133                               SMESH_subMesh*                  solidSM,
00134                               SMESH_subMeshEventListenerData* data,
00135                               const SMESH_Hypothesis*         hyp)
00136     {
00137       if ( SMESH_subMesh::COMPUTE_EVENT == eventType && solidSM->IsEmpty() && data )
00138       {
00139         SMESH_subMeshEventListener::ProcessEvent(event,eventType,solidSM,data,hyp);
00140       }
00141     }
00142     static void ToClearSubMeshWithSolid( SMESH_subMesh*      sm,
00143                                          const TopoDS_Shape& solid)
00144     {
00145       SMESH_subMesh* solidSM = sm->GetFather()->GetSubMesh( solid );
00146       SMESH_subMeshEventListenerData* data = solidSM->GetEventListenerData( Get());
00147       if ( data )
00148       {
00149         if ( find( data->mySubMeshes.begin(), data->mySubMeshes.end(), sm ) ==
00150              data->mySubMeshes.end())
00151           data->mySubMeshes.push_back( sm );
00152       }
00153       else
00154       {
00155         data = SMESH_subMeshEventListenerData::MakeData( /*dependent=*/sm );
00156         sm->SetEventListener( Get(), data, /*whereToListenTo=*/solidSM );
00157       }
00158     }
00159   };
00160   //--------------------------------------------------------------------------------
00166   class _ViscousListener : SMESH_subMeshEventListener
00167   {
00168     _ViscousListener():
00169       SMESH_subMeshEventListener(/*isDeletable=*/false,
00170                                  "StdMeshers_ViscousLayers::_ViscousListener") {}
00171     static SMESH_subMeshEventListener* Get() { static _ViscousListener l; return &l; }
00172   public:
00173     virtual void ProcessEvent(const int                       event,
00174                               const int                       eventType,
00175                               SMESH_subMesh*                  subMesh,
00176                               SMESH_subMeshEventListenerData* data,
00177                               const SMESH_Hypothesis*         hyp)
00178     {
00179       if ( SMESH_subMesh::COMPUTE_EVENT == eventType )
00180       {
00181         // delete SMESH_ProxyMesh containing temporary faces
00182         subMesh->DeleteEventListener( this );
00183       }
00184     }
00185     // Finds or creates proxy mesh of the solid
00186     static _MeshOfSolid* GetSolidMesh(SMESH_Mesh*         mesh,
00187                                       const TopoDS_Shape& solid,
00188                                       bool                toCreate=false)
00189     {
00190       if ( !mesh ) return 0;
00191       SMESH_subMesh* sm = mesh->GetSubMesh(solid);
00192       _MeshOfSolid* data = (_MeshOfSolid*) sm->GetEventListenerData( Get() );
00193       if ( !data && toCreate )
00194       {
00195         data = new _MeshOfSolid(mesh);
00196         data->mySubMeshes.push_back( sm ); // to find SOLID by _MeshOfSolid
00197         sm->SetEventListener( Get(), data, sm );
00198       }
00199       return data;
00200     }
00201     // Removes proxy mesh of the solid
00202     static void RemoveSolidMesh(SMESH_Mesh* mesh, const TopoDS_Shape& solid)
00203     {
00204       mesh->GetSubMesh(solid)->DeleteEventListener( _ViscousListener::Get() );
00205     }
00206   };
00207   
00208   //--------------------------------------------------------------------------------
00215   struct _Simplex
00216   {
00217     const SMDS_MeshNode *_nPrev, *_nNext; // nodes on a smoothed mesh surface
00218     _Simplex(const SMDS_MeshNode* nPrev=0, const SMDS_MeshNode* nNext=0)
00219       : _nPrev(nPrev), _nNext(nNext) {}
00220     bool IsForward(const SMDS_MeshNode* nSrc, const gp_XYZ* pntTgt) const
00221     {
00222       const double M[3][3] =
00223         {{ _nNext->X() - nSrc->X(), _nNext->Y() - nSrc->Y(), _nNext->Z() - nSrc->Z() },
00224          { pntTgt->X() - nSrc->X(), pntTgt->Y() - nSrc->Y(), pntTgt->Z() - nSrc->Z() },
00225          { _nPrev->X() - nSrc->X(), _nPrev->Y() - nSrc->Y(), _nPrev->Z() - nSrc->Z() }};
00226       double determinant = ( + M[0][0]*M[1][1]*M[2][2]
00227                              + M[0][1]*M[1][2]*M[2][0]
00228                              + M[0][2]*M[1][0]*M[2][1]
00229                              - M[0][0]*M[1][2]*M[2][1]
00230                              - M[0][1]*M[1][0]*M[2][2]
00231                              - M[0][2]*M[1][1]*M[2][0]);
00232       return determinant > 1e-100;
00233     }
00234     bool IsForward(const gp_XY&         tgtUV,
00235                    const SMDS_MeshNode* smoothedNode,
00236                    const TopoDS_Face&   face,
00237                    SMESH_MesherHelper&  helper,
00238                    const double         refSign) const
00239     {
00240       gp_XY prevUV = helper.GetNodeUV( face, _nPrev, smoothedNode );
00241       gp_XY nextUV = helper.GetNodeUV( face, _nNext, smoothedNode );
00242       gp_Vec2d v1( tgtUV, prevUV ), v2( tgtUV, nextUV );
00243       double d = v1 ^ v2;
00244       return d*refSign > 1e-100;
00245     }
00246     bool IsNeighbour(const _Simplex& other) const
00247     {
00248       return _nPrev == other._nNext || _nNext == other._nPrev;
00249     }
00250   };
00251   //--------------------------------------------------------------------------------
00255   struct _Curvature
00256   {
00257     double _r; // radius
00258     double _k; // factor to correct node smoothed position
00259   public:
00260     static _Curvature* New( double avgNormProj, double avgDist )
00261     {
00262       _Curvature* c = 0;
00263       if ( fabs( avgNormProj / avgDist ) > 1./200 )
00264       {
00265         c = new _Curvature;
00266         c->_r = avgDist * avgDist / avgNormProj;
00267         c->_k = avgDist * avgDist / c->_r / c->_r;
00268         c->_k *= ( c->_r < 0 ? 1/1.1 : 1.1 ); // not to be too restrictive
00269       }
00270       return c;
00271     }
00272     double lenDelta(double len) const { return _k * ( _r + len ); }
00273   };
00274   struct _LayerEdge;
00275   //--------------------------------------------------------------------------------
00279   struct _2NearEdges
00280   {
00281     // target nodes of 2 neighbour _LayerEdge's based on the same EDGE
00282     const SMDS_MeshNode* _nodes[2];
00283     // vectors from source nodes of 2 _LayerEdge's to the source node of master _LayerEdge
00284     //gp_XYZ               _vec[2];
00285     double               _wgt[2]; // weights of _nodes
00286     _LayerEdge*          _edges[2];
00287 
00288      // normal to plane passing through _LayerEdge._normal and tangent of EDGE
00289     gp_XYZ*              _plnNorm;
00290 
00291     _2NearEdges() { _nodes[0]=_nodes[1]=0; _plnNorm = 0; }
00292     void reverse() {
00293       std::swap( _nodes[0], _nodes[1] );
00294       std::swap( _wgt[0], _wgt[1] );
00295     }
00296   };
00297   //--------------------------------------------------------------------------------
00302   struct _LayerEdge
00303   {
00304     vector< const SMDS_MeshNode*> _nodes;
00305 
00306     gp_XYZ              _normal; // to solid surface
00307     vector<gp_XYZ>      _pos; // points computed during inflation
00308     double              _len; // length achived with the last step
00309     double              _cosin; // of angle (_normal ^ surface)
00310     double              _lenFactor; // to compute _len taking _cosin into account
00311 
00312     // face or edge w/o layer along or near which _LayerEdge is inflated
00313     TopoDS_Shape        _sWOL;
00314     // simplices connected to the source node (_nodes[0]);
00315     // used for smoothing and quality check of _LayerEdge's based on the FACE
00316     vector<_Simplex>    _simplices;
00317     // data for smoothing of _LayerEdge's based on the EDGE
00318     _2NearEdges*        _2neibors;
00319 
00320     _Curvature*         _curvature;
00321     // TODO:: detele _Curvature, _plnNorm
00322 
00323     void SetNewLength( double len, SMESH_MesherHelper& helper );
00324     bool SetNewLength2d( Handle(Geom_Surface)& surface,
00325                          const TopoDS_Face&    F,
00326                          SMESH_MesherHelper&   helper );
00327     void SetDataByNeighbors( const SMDS_MeshNode* n1,
00328                              const SMDS_MeshNode* n2,
00329                              SMESH_MesherHelper&  helper);
00330     void InvalidateStep( int curStep );
00331     bool Smooth(int& badNb);
00332     bool SmoothOnEdge(Handle(Geom_Surface)& surface,
00333                       const TopoDS_Face&    F,
00334                       SMESH_MesherHelper&   helper);
00335     bool FindIntersection( SMESH_ElementSearcher&   searcher,
00336                            double &                 distance,
00337                            const double&            epsilon,
00338                            const SMDS_MeshElement** face = 0);
00339     bool SegTriaInter( const gp_Ax1&        lastSegment,
00340                        const SMDS_MeshNode* n0,
00341                        const SMDS_MeshNode* n1,
00342                        const SMDS_MeshNode* n2,
00343                        double&              dist,
00344                        const double&        epsilon) const;
00345     gp_Ax1 LastSegment(double& segLen) const;
00346     bool IsOnEdge() const { return _2neibors; }
00347     void Copy( _LayerEdge& other, SMESH_MesherHelper& helper );
00348     void SetCosin( double cosin );
00349   };
00350   struct _LayerEdgeCmp
00351   {
00352     bool operator () (const _LayerEdge* e1, const _LayerEdge* e2) const
00353     {
00354       const bool cmpNodes = ( e1 && e2 && e1->_nodes.size() && e2->_nodes.size() );
00355       return cmpNodes ? ( e1->_nodes[0]->GetID() < e2->_nodes[0]->GetID()) : ( e1 < e2 );
00356     }
00357   };
00358   //--------------------------------------------------------------------------------
00359 
00360   typedef map< const SMDS_MeshNode*, _LayerEdge*, TIDCompare > TNode2Edge;
00361   
00362   //--------------------------------------------------------------------------------
00366   struct _SolidData
00367   {
00368     TopoDS_Shape                    _solid;
00369     const StdMeshers_ViscousLayers* _hyp;
00370     _MeshOfSolid*                   _proxyMesh;
00371     set<TGeomID>                    _reversedFaceIds;
00372 
00373     double                          _stepSize, _stepSizeCoeff;
00374     const SMDS_MeshNode*            _stepSizeNodes[2];
00375 
00376     TNode2Edge                      _n2eMap;
00377     // edges of _n2eMap. We keep same data in two containers because
00378     // iteration over the map is 5 time longer than over the vector
00379     vector< _LayerEdge* >           _edges;
00380 
00381     // key: an id of shape (EDGE or VERTEX) shared by a FACE with
00382     // layers and a FACE w/o layers
00383     // value: the shape (FACE or EDGE) to shrink mesh on.
00384     // _LayerEdge's basing on nodes on key shape are inflated along the value shape
00385     map< TGeomID, TopoDS_Shape >     _shrinkShape2Shape;
00386 
00387     // FACE's WOL, srink on which is forbiden due to algo on the adjacent SOLID
00388     set< TGeomID >                   _noShrinkFaces;
00389 
00390     // <EDGE to smooth on> to <it's curve>
00391     map< TGeomID,Handle(Geom_Curve)> _edge2curve;
00392 
00393     // end indices in _edges of _LayerEdge on one shape to smooth
00394     vector< int >                    _endEdgeToSmooth;
00395 
00396     double                           _epsilon; // precision for SegTriaInter()
00397 
00398     int                              _index; // for debug
00399 
00400     _SolidData(const TopoDS_Shape&             s=TopoDS_Shape(),
00401                const StdMeshers_ViscousLayers* h=0,
00402                _MeshOfSolid*                   m=0) :_solid(s), _hyp(h), _proxyMesh(m) {}
00403     ~_SolidData();
00404 
00405     Handle(Geom_Curve) CurveForSmooth( const TopoDS_Edge&    E,
00406                                        const int             iFrom,
00407                                        const int             iTo,
00408                                        Handle(Geom_Surface)& surface,
00409                                        const TopoDS_Face&    F,
00410                                        SMESH_MesherHelper&   helper);
00411   };
00412   //--------------------------------------------------------------------------------
00416   struct _SmoothNode
00417   {
00418     const SMDS_MeshNode*         _node;
00419     //vector<const SMDS_MeshNode*> _nodesAround;
00420     vector<_Simplex>             _simplices; // for quality check
00421 
00422     bool Smooth(int&                  badNb,
00423                 Handle(Geom_Surface)& surface,
00424                 SMESH_MesherHelper&   helper,
00425                 const double          refSign,
00426                 bool                  isCentroidal,
00427                 bool                  set3D);
00428   };
00429   //--------------------------------------------------------------------------------
00433   class _ViscousBuilder
00434   {
00435   public:
00436     _ViscousBuilder();
00437     // does it's job
00438     SMESH_ComputeErrorPtr Compute(SMESH_Mesh&         mesh,
00439                                   const TopoDS_Shape& shape);
00440 
00441     // restore event listeners used to clear an inferior dim sub-mesh modified by viscous layers
00442     void RestoreListeners();
00443 
00444     // computes SMESH_ProxyMesh::SubMesh::_n2n;
00445     bool MakeN2NMap( _MeshOfSolid* pm );
00446 
00447   private:
00448 
00449     bool findSolidsWithLayers();
00450     bool findFacesWithLayers();
00451     bool makeLayer(_SolidData& data);
00452     bool setEdgeData(_LayerEdge& edge, const set<TGeomID>& subIds,
00453                      SMESH_MesherHelper& helper, _SolidData& data);
00454     bool findNeiborsOnEdge(const _LayerEdge*     edge,
00455                            const SMDS_MeshNode*& n1,
00456                            const SMDS_MeshNode*& n2,
00457                            _SolidData&           data);
00458     void getSimplices( const SMDS_MeshNode* node, vector<_Simplex>& simplices,
00459                        const set<TGeomID>& ingnoreShapes,
00460                        const _SolidData*   dataToCheckOri = 0,
00461                        const bool          toSort = false);
00462     bool sortEdges( _SolidData&                    data,
00463                     vector< vector<_LayerEdge*> >& edgesByGeom);
00464     void limitStepSize( _SolidData&             data,
00465                         const SMDS_MeshElement* face,
00466                         const double            cosin);
00467     void limitStepSize( _SolidData& data, const double minSize);
00468     bool inflate(_SolidData& data);
00469     bool smoothAndCheck(_SolidData& data, const int nbSteps, double & distToIntersection);
00470     bool smoothAnalyticEdge( _SolidData&           data,
00471                              const int             iFrom,
00472                              const int             iTo,
00473                              Handle(Geom_Surface)& surface,
00474                              const TopoDS_Face&    F,
00475                              SMESH_MesherHelper&   helper);
00476     bool updateNormals( _SolidData& data, SMESH_MesherHelper& helper );
00477     bool refine(_SolidData& data);
00478     bool shrink();
00479     bool prepareEdgeToShrink( _LayerEdge& edge, const TopoDS_Face& F,
00480                               SMESH_MesherHelper& helper,
00481                               const SMESHDS_SubMesh* faceSubMesh );
00482     void fixBadFaces(const TopoDS_Face& F, SMESH_MesherHelper& helper);
00483     bool addBoundaryElements();
00484 
00485     bool error( const string& text, int solidID=-1 );
00486     SMESHDS_Mesh* getMeshDS() { return _mesh->GetMeshDS(); }
00487 
00488     // debug
00489     void makeGroupOfLE();
00490 
00491     SMESH_Mesh*           _mesh;
00492     SMESH_ComputeErrorPtr _error;
00493 
00494     vector< _SolidData >  _sdVec;
00495     set<TGeomID>          _ignoreShapeIds;
00496     int                   _tmpFaceID;
00497   };
00498   //--------------------------------------------------------------------------------
00502   class _Shrinker1D
00503   {
00504     vector<double>                _initU;
00505     vector<double>                _normPar;
00506     vector<const SMDS_MeshNode*>  _nodes;
00507     const _LayerEdge*             _edges[2];
00508     bool                          _done;
00509   public:
00510     void AddEdge( const _LayerEdge* e, SMESH_MesherHelper& helper );
00511     void Compute(bool set3D, SMESH_MesherHelper& helper);
00512     void RestoreParams();
00513     void SwapSrcTgtNodes(SMESHDS_Mesh* mesh);
00514   };
00515   //--------------------------------------------------------------------------------
00521   struct TmpMeshFace : public SMDS_MeshElement
00522   {
00523     vector<const SMDS_MeshNode* > _nn;
00524     TmpMeshFace( const vector<const SMDS_MeshNode*>& nodes, int id):
00525       SMDS_MeshElement(id), _nn(nodes) {}
00526     virtual const SMDS_MeshNode* GetNode(const int ind) const { return _nn[ind]; }
00527     virtual SMDSAbs_ElementType  GetType() const              { return SMDSAbs_Face; }
00528     virtual vtkIdType GetVtkType() const                      { return -1; }
00529     virtual SMDSAbs_EntityType   GetEntityType() const        { return SMDSEntity_Last; }
00530     virtual SMDS_ElemIteratorPtr elementsIterator(SMDSAbs_ElementType type) const
00531     { return SMDS_ElemIteratorPtr( new SMDS_NodeVectorElemIterator( _nn.begin(), _nn.end()));}
00532   };
00533   //--------------------------------------------------------------------------------
00537   struct TmpMeshFaceOnEdge : public TmpMeshFace
00538   {
00539     _LayerEdge *_le1, *_le2;
00540     TmpMeshFaceOnEdge( _LayerEdge* le1, _LayerEdge* le2, int ID ):
00541       TmpMeshFace( vector<const SMDS_MeshNode*>(4), ID ), _le1(le1), _le2(le2)
00542     {
00543       _nn[0]=_le1->_nodes[0];
00544       _nn[1]=_le1->_nodes.back();
00545       _nn[2]=_le2->_nodes.back();
00546       _nn[3]=_le2->_nodes[0];
00547     }
00548   };
00549 } // namespace VISCOUS
00550 
00551 //================================================================================
00552 // StdMeshers_ViscousLayers hypothesis
00553 //
00554 StdMeshers_ViscousLayers::StdMeshers_ViscousLayers(int hypId, int studyId, SMESH_Gen* gen)
00555   :SMESH_Hypothesis(hypId, studyId, gen),
00556    _nbLayers(1), _thickness(1), _stretchFactor(1)
00557 {
00558   _name = StdMeshers_ViscousLayers::GetHypType();
00559   _param_algo_dim = -3; // auxiliary hyp used by 3D algos
00560 } // --------------------------------------------------------------------------------
00561 void StdMeshers_ViscousLayers::SetIgnoreFaces(const std::vector<int>& faceIds)
00562 {
00563   if ( faceIds != _ignoreFaceIds )
00564     _ignoreFaceIds = faceIds, NotifySubMeshesHypothesisModification();
00565 } // --------------------------------------------------------------------------------
00566 void StdMeshers_ViscousLayers::SetTotalThickness(double thickness)
00567 {
00568   if ( thickness != _thickness )
00569     _thickness = thickness, NotifySubMeshesHypothesisModification();
00570 } // --------------------------------------------------------------------------------
00571 void StdMeshers_ViscousLayers::SetNumberLayers(int nb)
00572 {
00573   if ( _nbLayers != nb )
00574     _nbLayers = nb, NotifySubMeshesHypothesisModification();
00575 } // --------------------------------------------------------------------------------
00576 void StdMeshers_ViscousLayers::SetStretchFactor(double factor)
00577 {
00578   if ( _stretchFactor != factor )
00579     _stretchFactor = factor, NotifySubMeshesHypothesisModification();
00580 } // --------------------------------------------------------------------------------
00581 SMESH_ProxyMesh::Ptr
00582 StdMeshers_ViscousLayers::Compute(SMESH_Mesh&         theMesh,
00583                                   const TopoDS_Shape& theShape,
00584                                   const bool          toMakeN2NMap) const
00585 {
00586   using namespace VISCOUS;
00587   _ViscousBuilder bulder;
00588   SMESH_ComputeErrorPtr err = bulder.Compute( theMesh, theShape );
00589   if ( err && !err->IsOK() )
00590     return SMESH_ProxyMesh::Ptr();
00591 
00592   vector<SMESH_ProxyMesh::Ptr> components;
00593   TopExp_Explorer exp( theShape, TopAbs_SOLID );
00594   for ( ; exp.More(); exp.Next() )
00595   {
00596     if ( _MeshOfSolid* pm =
00597          _ViscousListener::GetSolidMesh( &theMesh, exp.Current(), /*toCreate=*/false))
00598     {
00599       if ( toMakeN2NMap && !pm->_n2nMapComputed )
00600         if ( !bulder.MakeN2NMap( pm ))
00601           return SMESH_ProxyMesh::Ptr();
00602       components.push_back( SMESH_ProxyMesh::Ptr( pm ));
00603       pm->myIsDeletable = false; // it will de deleted by boost::shared_ptr
00604     }
00605     _ViscousListener::RemoveSolidMesh ( &theMesh, exp.Current() );
00606   }
00607   switch ( components.size() )
00608   {
00609   case 0: break;
00610 
00611   case 1: return components[0];
00612 
00613   default: return SMESH_ProxyMesh::Ptr( new SMESH_ProxyMesh( components ));
00614   }
00615   return SMESH_ProxyMesh::Ptr();
00616 } // --------------------------------------------------------------------------------
00617 std::ostream & StdMeshers_ViscousLayers::SaveTo(std::ostream & save)
00618 {
00619   save << " " << _nbLayers
00620        << " " << _thickness
00621        << " " << _stretchFactor
00622        << " " << _ignoreFaceIds.size();
00623   for ( unsigned i = 0; i < _ignoreFaceIds.size(); ++i )
00624     save << " " << _ignoreFaceIds[i];
00625   return save;
00626 } // --------------------------------------------------------------------------------
00627 std::istream & StdMeshers_ViscousLayers::LoadFrom(std::istream & load)
00628 {
00629   int nbFaces, faceID;
00630   load >> _nbLayers >> _thickness >> _stretchFactor >> nbFaces;
00631   while ( _ignoreFaceIds.size() < nbFaces && load >> faceID )
00632     _ignoreFaceIds.push_back( faceID );
00633   return load;
00634 } // --------------------------------------------------------------------------------
00635 bool StdMeshers_ViscousLayers::SetParametersByMesh(const SMESH_Mesh*   theMesh,
00636                                                    const TopoDS_Shape& theShape)
00637 {
00638   // TODO
00639   return false;
00640 }
00641 // END StdMeshers_ViscousLayers hypothesis
00642 //================================================================================
00643 
00644 namespace
00645 {
00646   gp_XYZ getEdgeDir( const TopoDS_Edge& E, const TopoDS_Vertex& fromV )
00647   {
00648     gp_Vec dir;
00649     double f,l;
00650     Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
00651     gp_Pnt p = BRep_Tool::Pnt( fromV );
00652     double distF = p.SquareDistance( c->Value( f ));
00653     double distL = p.SquareDistance( c->Value( l ));
00654     c->D1(( distF < distL ? f : l), p, dir );
00655     if ( distL < distF ) dir.Reverse();
00656     return dir.XYZ();
00657   }
00658   //--------------------------------------------------------------------------------
00659   gp_XYZ getEdgeDir( const TopoDS_Edge& E, const SMDS_MeshNode* atNode,
00660                      SMESH_MesherHelper& helper)
00661   {
00662     gp_Vec dir;
00663     double f,l; gp_Pnt p;
00664     Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
00665     double u = helper.GetNodeU( E, atNode );
00666     c->D1( u, p, dir );
00667     return dir.XYZ();
00668   }
00669   //--------------------------------------------------------------------------------
00670   gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Edge& fromE,
00671                      const SMDS_MeshNode* node, SMESH_MesherHelper& helper, bool& ok)
00672   {
00673     gp_XY uv = helper.GetNodeUV( F, node, 0, &ok );
00674     Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
00675     gp_Pnt p; gp_Vec du, dv, norm;
00676     surface->D1( uv.X(),uv.Y(), p, du,dv );
00677     norm = du ^ dv;
00678 
00679     double f,l;
00680     Handle(Geom_Curve) c = BRep_Tool::Curve( fromE, f, l );
00681     double u = helper.GetNodeU( fromE, node, 0, &ok );
00682     c->D1( u, p, du );
00683     TopAbs_Orientation o = helper.GetSubShapeOri( F.Oriented(TopAbs_FORWARD), fromE);
00684     if ( o == TopAbs_REVERSED )
00685       du.Reverse();
00686 
00687     gp_Vec dir = norm ^ du;
00688 
00689     if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX &&
00690          helper.IsClosedEdge( fromE ))
00691     {
00692       if ( fabs(u-f) < fabs(u-l )) c->D1( l, p, dv );
00693       else                         c->D1( f, p, dv );
00694       if ( o == TopAbs_REVERSED )
00695         dv.Reverse();
00696       gp_Vec dir2 = norm ^ dv;
00697       dir = dir.Normalized() + dir2.Normalized();
00698     }
00699     return dir.XYZ();
00700   }
00701   //--------------------------------------------------------------------------------
00702   gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Vertex& fromV,
00703                      const SMDS_MeshNode* node, SMESH_MesherHelper& helper,
00704                      bool& ok, double* cosin=0)
00705   {
00706     double f,l; TopLoc_Location loc;
00707     vector< TopoDS_Edge > edges; // sharing a vertex
00708     PShapeIteratorPtr eIt = helper.GetAncestors( fromV, *helper.GetMesh(), TopAbs_EDGE);
00709     while ( eIt->more())
00710     {
00711       const TopoDS_Edge* e = static_cast<const TopoDS_Edge*>( eIt->next() );
00712       if ( helper.IsSubShape( *e, F ) && !BRep_Tool::Curve( *e, loc,f,l).IsNull() )
00713         edges.push_back( *e );
00714     }
00715     gp_XYZ dir(0,0,0);
00716     if ( !( ok = ( edges.size() > 0 ))) return dir;
00717     // get average dir of edges going fromV
00718     gp_Vec edgeDir;
00719     for ( unsigned i = 0; i < edges.size(); ++i )
00720     {
00721       edgeDir = getEdgeDir( edges[i], fromV );
00722       double size2 = edgeDir.SquareMagnitude();
00723       if ( size2 > numeric_limits<double>::min() )
00724         edgeDir /= sqrt( size2 );
00725       else
00726         ok = false;
00727       dir += edgeDir.XYZ();
00728     }
00729     gp_XYZ fromEdgeDir = getFaceDir( F, edges[0], node, helper, ok );
00730     if ( edges.size() == 1 || dir.SquareModulus() < 1e-10)
00731       dir = fromEdgeDir;
00732     else if ( dir * fromEdgeDir < 0 )
00733       dir *= -1;
00734     if ( ok )
00735     {
00736       //dir /= edges.size();
00737       if ( cosin ) {
00738         double angle = edgeDir.Angle( dir );
00739         *cosin = cos( angle );
00740       }
00741     }
00742     return dir;
00743   }
00744   //================================================================================
00748   //================================================================================
00749 
00750   bool isConcave( const TopoDS_Face& F, SMESH_MesherHelper& helper )
00751   {
00752     gp_Vec2d drv1, drv2;
00753     gp_Pnt2d p;
00754     TopExp_Explorer eExp( F.Oriented( TopAbs_FORWARD ), TopAbs_EDGE );
00755     for ( ; eExp.More(); eExp.Next() )
00756     {
00757       const TopoDS_Edge& E = TopoDS::Edge( eExp.Current() );
00758       if ( BRep_Tool::Degenerated( E )) continue;
00759       // check if 2D curve is concave
00760       BRepAdaptor_Curve2d curve( E, F );
00761       const int nbIntervals = curve.NbIntervals( GeomAbs_C2 );
00762       TColStd_Array1OfReal intervals(1, nbIntervals + 1 );
00763       curve.Intervals( intervals, GeomAbs_C2 );
00764       bool isConvex = true;
00765       for ( int i = 1; i <= nbIntervals && isConvex; ++i )
00766       {
00767         double u1 = intervals( i );
00768         double u2 = intervals( i+1 );
00769         curve.D2( 0.5*( u1+u2 ), p, drv1, drv2 );
00770         double cross = drv2 ^ drv1;
00771         if ( E.Orientation() == TopAbs_REVERSED )
00772           cross = -cross;
00773         isConvex = ( cross < 1e-9 );
00774       }
00775       // check if concavity is strong enough to care about it
00776       //const double maxAngle = 5 * Standard_PI180;
00777       if ( !isConvex )
00778       {
00779         //cout << "Concave FACE " << helper.GetMeshDS()->ShapeToIndex( F ) << endl;
00780         return true;
00781         // map< double, const SMDS_MeshNode* > u2nodes;
00782         // if ( !SMESH_Algo::GetSortedNodesOnEdge( helper.GetMeshDS(), E,
00783         //                                         /*ignoreMedium=*/true, u2nodes))
00784         //   continue;
00785         // map< double, const SMDS_MeshNode* >::iterator u2n = u2nodes.begin();
00786         // gp_Pnt2d uvPrev = helper.GetNodeUV( F, u2n->second );
00787         // double    uPrev = u2n->first;
00788         // for ( ++u2n; u2n != u2nodes.end(); ++u2n )
00789         // {
00790         //   gp_Pnt2d uv = helper.GetNodeUV( F, u2n->second );
00791         //   gp_Vec2d segmentDir( uvPrev, uv );
00792         //   curve.D1( uPrev, p, drv1 );
00793         //   try {
00794         //     if ( fabs( segmentDir.Angle( drv1 )) > maxAngle )
00795         //       return true;
00796         //   }
00797         //   catch ( ... ) {}
00798         //   uvPrev = uv;
00799         //   uPrev = u2n->first;
00800         // }
00801       }
00802     }
00803     return false;
00804   }
00805   //--------------------------------------------------------------------------------
00806   // DEBUG. Dump intermediate node positions into a python script
00807 #ifdef __myDEBUG
00808   ofstream* py;
00809   struct PyDump {
00810     PyDump() {
00811       const char* fname = "/tmp/viscous.py";
00812       cout << "execfile('"<<fname<<"')"<<endl;
00813       py = new ofstream(fname);
00814       *py << "from smesh import *" << endl
00815           << "meshSO = GetCurrentStudy().FindObjectID('0:1:2:3')" << endl
00816           << "mesh = Mesh( meshSO.GetObject() )"<<endl;
00817     }
00818     void Finish() {
00819       if (py)
00820         *py << "mesh.MakeGroup('Viscous Prisms',VOLUME,FT_ElemGeomType,'=',Geom_PENTA)"<<endl;
00821       delete py; py=0;
00822     }
00823     ~PyDump() { Finish(); }
00824   };
00825 #define dumpFunction(f) { _dumpFunction(f, __LINE__);}
00826 #define dumpMove(n)     { _dumpMove(n, __LINE__);}
00827 #define dumpCmd(txt)    { _dumpCmd(txt, __LINE__);}
00828   void _dumpFunction(const string& fun, int ln)
00829   { if (py) *py<< "def "<<fun<<"(): # "<< ln <<endl; cout<<fun<<"()"<<endl;}
00830   void _dumpMove(const SMDS_MeshNode* n, int ln)
00831   { if (py) *py<< "  mesh.MoveNode( "<<n->GetID()<< ", "<< n->X()
00832                << ", "<<n->Y()<<", "<< n->Z()<< ")\t\t # "<< ln <<endl; }
00833   void _dumpCmd(const string& txt, int ln)
00834   { if (py) *py<< "  "<<txt<<" # "<< ln <<endl; }
00835   void dumpFunctionEnd()
00836   { if (py) *py<< "  return"<< endl; }
00837   void dumpChangeNodes( const SMDS_MeshElement* f )
00838   { if (py) { *py<< "  mesh.ChangeElemNodes( " << f->GetID()<<", [";
00839       for ( int i=1; i < f->NbNodes(); ++i ) *py << f->GetNode(i-1)->GetID()<<", ";
00840       *py << f->GetNode( f->NbNodes()-1 )->GetID() << " ])"<< endl; }}
00841 #else
00842   struct PyDump { void Finish() {} };
00843 #define dumpFunction(f) f
00844 #define dumpMove(n)
00845 #define dumpCmd(txt)
00846 #define dumpFunctionEnd()
00847 #define dumpChangeNodes(f)
00848 #endif
00849 }
00850 
00851 using namespace VISCOUS;
00852 
00853 //================================================================================
00857 //================================================================================
00858 
00859 _ViscousBuilder::_ViscousBuilder()
00860 {
00861   _error = SMESH_ComputeError::New(COMPERR_OK);
00862   _tmpFaceID = 0;
00863 }
00864 
00865 //================================================================================
00869 //================================================================================
00870 
00871 bool _ViscousBuilder::error(const string& text, int solidId )
00872 {
00873   _error->myName    = COMPERR_ALGO_FAILED;
00874   _error->myComment = string("Viscous layers builder: ") + text;
00875   if ( _mesh )
00876   {
00877     SMESH_subMesh* sm = _mesh->GetSubMeshContaining( solidId );
00878     if ( !sm && !_sdVec.empty() )
00879       sm = _mesh->GetSubMeshContaining( _sdVec[0]._index );
00880     if ( sm && sm->GetSubShape().ShapeType() == TopAbs_SOLID )
00881     {
00882       SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
00883       if ( smError && smError->myAlgo )
00884         _error->myAlgo = smError->myAlgo;
00885       smError = _error;
00886     }
00887   }
00888   makeGroupOfLE(); // debug
00889 
00890   return false;
00891 }
00892 
00893 //================================================================================
00898 //================================================================================
00899 
00900 void _ViscousBuilder::RestoreListeners()
00901 {
00902   // TODO
00903 }
00904 
00905 //================================================================================
00909 //================================================================================
00910 
00911 bool _ViscousBuilder::MakeN2NMap( _MeshOfSolid* pm )
00912 {
00913   SMESH_subMesh* solidSM = pm->mySubMeshes.front();
00914   TopExp_Explorer fExp( solidSM->GetSubShape(), TopAbs_FACE );
00915   for ( ; fExp.More(); fExp.Next() )
00916   {
00917     SMESHDS_SubMesh* srcSmDS = pm->GetMeshDS()->MeshElements( fExp.Current() );
00918     const SMESH_ProxyMesh::SubMesh* prxSmDS = pm->GetProxySubMesh( fExp.Current() );
00919 
00920     if ( !srcSmDS || !prxSmDS || !srcSmDS->NbElements() || !prxSmDS->NbElements() )
00921       continue;
00922     if ( srcSmDS->GetElements()->next() == prxSmDS->GetElements()->next())
00923       continue;
00924 
00925     if ( srcSmDS->NbElements() != prxSmDS->NbElements() )
00926       return error( "Different nb elements in a source and a proxy sub-mesh", solidSM->GetId());
00927 
00928     SMDS_ElemIteratorPtr srcIt = srcSmDS->GetElements();
00929     SMDS_ElemIteratorPtr prxIt = prxSmDS->GetElements();
00930     while( prxIt->more() )
00931     {
00932       const SMDS_MeshElement* fSrc = srcIt->next();
00933       const SMDS_MeshElement* fPrx = prxIt->next();
00934       if ( fSrc->NbNodes() != fPrx->NbNodes())
00935         return error( "Different elements in a source and a proxy sub-mesh", solidSM->GetId());
00936       for ( int i = 0 ; i < fPrx->NbNodes(); ++i )
00937         pm->setNode2Node( fSrc->GetNode(i), fPrx->GetNode(i), prxSmDS );
00938     }
00939   }
00940   pm->_n2nMapComputed = true;
00941   return true;
00942 }
00943 
00944 //================================================================================
00948 //================================================================================
00949 
00950 SMESH_ComputeErrorPtr _ViscousBuilder::Compute(SMESH_Mesh&         theMesh,
00951                                                const TopoDS_Shape& theShape)
00952 {
00953   // TODO: set priority of solids during Gen::Compute()
00954 
00955   _mesh = & theMesh;
00956 
00957   // check if proxy mesh already computed
00958   TopExp_Explorer exp( theShape, TopAbs_SOLID );
00959   if ( !exp.More() )
00960     return error("No SOLID's in theShape"), _error;
00961 
00962   if ( _ViscousListener::GetSolidMesh( _mesh, exp.Current(), /*toCreate=*/false))
00963     return SMESH_ComputeErrorPtr(); // everything already computed
00964 
00965   PyDump debugDump;
00966 
00967   // TODO: ignore already computed SOLIDs 
00968   if ( !findSolidsWithLayers())
00969     return _error;
00970 
00971   if ( !findFacesWithLayers() )
00972     return _error;
00973 
00974   for ( unsigned i = 0; i < _sdVec.size(); ++i )
00975   {
00976     if ( ! makeLayer(_sdVec[i]) )
00977       return _error;
00978     
00979     if ( ! inflate(_sdVec[i]) )
00980       return _error;
00981 
00982     if ( ! refine(_sdVec[i]) )
00983       return _error;
00984   }
00985   if ( !shrink() )
00986     return _error;
00987 
00988   addBoundaryElements();
00989 
00990   makeGroupOfLE(); // debug
00991   debugDump.Finish();
00992 
00993   return _error;
00994 }
00995 
00996 //================================================================================
01000 //================================================================================
01001 
01002 bool _ViscousBuilder::findSolidsWithLayers()
01003 {
01004   // get all solids
01005   TopTools_IndexedMapOfShape allSolids;
01006   TopExp::MapShapes( _mesh->GetShapeToMesh(), TopAbs_SOLID, allSolids );
01007   _sdVec.reserve( allSolids.Extent());
01008 
01009   SMESH_Gen* gen = _mesh->GetGen();
01010   for ( int i = 1; i <= allSolids.Extent(); ++i )
01011   {
01012     // find StdMeshers_ViscousLayers hyp assigned to the i-th solid
01013     SMESH_Algo* algo = gen->GetAlgo( *_mesh, allSolids(i) );
01014     if ( !algo ) continue;
01015     // TODO: check if algo is hidden
01016     const list <const SMESHDS_Hypothesis *> & allHyps =
01017       algo->GetUsedHypothesis(*_mesh, allSolids(i), /*ignoreAuxiliary=*/false);
01018     list< const SMESHDS_Hypothesis *>::const_iterator hyp = allHyps.begin();
01019     const StdMeshers_ViscousLayers* viscHyp = 0;
01020     for ( ; hyp != allHyps.end() && !viscHyp; ++hyp )
01021       viscHyp = dynamic_cast<const StdMeshers_ViscousLayers*>( *hyp );
01022     if ( viscHyp )
01023     {
01024       _MeshOfSolid* proxyMesh = _ViscousListener::GetSolidMesh( _mesh,
01025                                                                 allSolids(i),
01026                                                                 /*toCreate=*/true);
01027       _sdVec.push_back( _SolidData( allSolids(i), viscHyp, proxyMesh ));
01028       _sdVec.back()._index = getMeshDS()->ShapeToIndex( allSolids(i));
01029     }
01030   }
01031   if ( _sdVec.empty() )
01032     return error
01033       ( SMESH_Comment(StdMeshers_ViscousLayers::GetHypType()) << " hypothesis not found",0);
01034 
01035   return true;
01036 }
01037 
01038 //================================================================================
01042 //================================================================================
01043 
01044 bool _ViscousBuilder::findFacesWithLayers()
01045 {
01046   // collect all faces to ignore defined by hyp
01047   vector<TopoDS_Shape> ignoreFaces;
01048   for ( unsigned i = 0; i < _sdVec.size(); ++i )
01049   {
01050     vector<TGeomID> ids = _sdVec[i]._hyp->GetIgnoreFaces();
01051     for ( unsigned i = 0; i < ids.size(); ++i )
01052     {
01053       const TopoDS_Shape& s = getMeshDS()->IndexToShape( ids[i] );
01054       if ( !s.IsNull() && s.ShapeType() == TopAbs_FACE )
01055       {
01056         _ignoreShapeIds.insert( ids[i] );
01057         ignoreFaces.push_back( s );
01058       }
01059     }
01060   }
01061 
01062   // ignore internal faces
01063   SMESH_MesherHelper helper( *_mesh );
01064   TopExp_Explorer exp;
01065   for ( unsigned i = 0; i < _sdVec.size(); ++i )
01066   {
01067     exp.Init( _sdVec[i]._solid.Oriented( TopAbs_FORWARD ), TopAbs_FACE );
01068     for ( ; exp.More(); exp.Next() )
01069     {
01070       TGeomID faceInd = getMeshDS()->ShapeToIndex( exp.Current() );
01071       if ( helper.NbAncestors( exp.Current(), *_mesh, TopAbs_SOLID ) > 1 )
01072       {     
01073         _ignoreShapeIds.insert( faceInd );
01074         ignoreFaces.push_back( exp.Current() );
01075         if ( SMESH_Algo::IsReversedSubMesh( TopoDS::Face( exp.Current() ), getMeshDS()))
01076           _sdVec[i]._reversedFaceIds.insert( faceInd );
01077       }
01078     }
01079   }
01080 
01081   // Find faces to shrink mesh on (solution 2 in issue 0020832);
01082   TopTools_IndexedMapOfShape shapes;
01083   for ( unsigned i = 0; i < _sdVec.size(); ++i )
01084   {
01085     shapes.Clear();
01086     TopExp::MapShapes(_sdVec[i]._solid, TopAbs_EDGE, shapes);
01087     for ( int iE = 1; iE <= shapes.Extent(); ++iE )
01088     {
01089       const TopoDS_Shape& edge = shapes(iE);
01090       // find 2 faces sharing an edge
01091       TopoDS_Shape FF[2];
01092       PShapeIteratorPtr fIt = helper.GetAncestors(edge, *_mesh, TopAbs_FACE);
01093       while ( fIt->more())
01094       {
01095         const TopoDS_Shape* f = fIt->next();
01096         if ( helper.IsSubShape( *f, _sdVec[i]._solid))
01097           FF[ int( !FF[0].IsNull()) ] = *f;
01098       }
01099       if( FF[1].IsNull() ) continue; // seam edge can be shared by 1 FACE only
01100       // check presence of layers on them
01101       int ignore[2];
01102       for ( int j = 0; j < 2; ++j )
01103         ignore[j] = _ignoreShapeIds.count ( getMeshDS()->ShapeToIndex( FF[j] ));
01104       if ( ignore[0] == ignore[1] ) continue; // nothing interesting
01105       TopoDS_Shape fWOL = FF[ ignore[0] ? 0 : 1 ];
01106       // add edge to maps
01107       TGeomID edgeInd = getMeshDS()->ShapeToIndex( edge );
01108       _sdVec[i]._shrinkShape2Shape.insert( make_pair( edgeInd, fWOL ));
01109     }
01110   }
01111   // Exclude from _shrinkShape2Shape FACE's that can't be shrinked since
01112   // the algo of the SOLID sharing the FACE does not support it
01113   set< string > notSupportAlgos; notSupportAlgos.insert("Hexa_3D");
01114   for ( unsigned i = 0; i < _sdVec.size(); ++i )
01115   {
01116     TopTools_MapOfShape noShrinkVertices;
01117     map< TGeomID, TopoDS_Shape >::iterator e2f = _sdVec[i]._shrinkShape2Shape.begin();
01118     for ( ; e2f != _sdVec[i]._shrinkShape2Shape.end(); ++e2f )
01119     {
01120       const TopoDS_Shape& fWOL = e2f->second;
01121       TGeomID           edgeID = e2f->first;
01122       bool notShrinkFace = false;
01123       PShapeIteratorPtr soIt = helper.GetAncestors(fWOL, *_mesh, TopAbs_SOLID);
01124       while ( soIt->more())
01125       {
01126         const TopoDS_Shape* solid = soIt->next();
01127         if ( _sdVec[i]._solid.IsSame( *solid )) continue;
01128         SMESH_Algo* algo = _mesh->GetGen()->GetAlgo( *_mesh, *solid );
01129         if ( !algo || !notSupportAlgos.count( algo->GetName() )) continue;
01130         notShrinkFace = true;
01131         for ( unsigned j = 0; j < _sdVec.size(); ++j )
01132         {
01133           if ( _sdVec[j]._solid.IsSame( *solid ) )
01134             if ( _sdVec[j]._shrinkShape2Shape.count( edgeID ))
01135               notShrinkFace = false;
01136         }
01137       }
01138       if ( notShrinkFace )
01139       {
01140         _sdVec[i]._noShrinkFaces.insert( getMeshDS()->ShapeToIndex( fWOL ));
01141         for ( TopExp_Explorer vExp( fWOL, TopAbs_VERTEX ); vExp.More(); vExp.Next() )
01142           noShrinkVertices.Add( vExp.Current() );
01143       }
01144     }
01145     // erase from _shrinkShape2Shape all srink EDGE's of a SOLID connected
01146     // to the found not shrinked fWOL's
01147     e2f = _sdVec[i]._shrinkShape2Shape.begin();
01148     for ( ; e2f != _sdVec[i]._shrinkShape2Shape.end(); )
01149     {
01150       TGeomID edgeID = e2f->first;
01151       TopoDS_Vertex VV[2];
01152       TopExp::Vertices( TopoDS::Edge( getMeshDS()->IndexToShape( edgeID )),VV[0],VV[1]);
01153       if ( noShrinkVertices.Contains( VV[0] ) || noShrinkVertices.Contains( VV[1] ))
01154       {
01155         _sdVec[i]._noShrinkFaces.insert( getMeshDS()->ShapeToIndex( e2f->second ));
01156         _sdVec[i]._shrinkShape2Shape.erase( e2f++ );
01157       }
01158       else
01159       {
01160         e2f++;
01161       }
01162     }
01163   }
01164       
01165   // Find the SHAPE along which to inflate _LayerEdge based on VERTEX
01166 
01167   for ( unsigned i = 0; i < _sdVec.size(); ++i )
01168   {
01169     shapes.Clear();
01170     TopExp::MapShapes(_sdVec[i]._solid, TopAbs_VERTEX, shapes);
01171     for ( int iV = 1; iV <= shapes.Extent(); ++iV )
01172     {
01173       const TopoDS_Shape& vertex = shapes(iV);
01174       // find faces WOL sharing the vertex
01175       vector< TopoDS_Shape > facesWOL;
01176       int totalNbFaces = 0;
01177       PShapeIteratorPtr fIt = helper.GetAncestors(vertex, *_mesh, TopAbs_FACE);
01178       while ( fIt->more())
01179       {
01180         const TopoDS_Shape* f = fIt->next();
01181         const int         fID = getMeshDS()->ShapeToIndex( *f );
01182         if ( helper.IsSubShape( *f, _sdVec[i]._solid ) )
01183         {
01184           totalNbFaces++;
01185           if ( _ignoreShapeIds.count ( fID ) && ! _sdVec[i]._noShrinkFaces.count( fID ))
01186             facesWOL.push_back( *f );
01187         }
01188       }
01189       if ( facesWOL.size() == totalNbFaces || facesWOL.empty() )
01190         continue; // no layers at this vertex or no WOL
01191       TGeomID vInd = getMeshDS()->ShapeToIndex( vertex );
01192       switch ( facesWOL.size() )
01193       {
01194       case 1:
01195         {
01196           helper.SetSubShape( facesWOL[0] );
01197           if ( helper.IsRealSeam( vInd )) // inflate along a seam edge?
01198           {
01199             TopoDS_Shape seamEdge;
01200             PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
01201             while ( eIt->more() && seamEdge.IsNull() )
01202             {
01203               const TopoDS_Shape* e = eIt->next();
01204               if ( helper.IsRealSeam( *e ) )
01205                 seamEdge = *e;
01206             }
01207             if ( !seamEdge.IsNull() )
01208             {
01209               _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, seamEdge ));
01210               break;
01211             }
01212           }
01213           _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, facesWOL[0] ));
01214           break;
01215         }
01216       case 2:
01217         {
01218           // find an edge shared by 2 faces
01219           PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
01220           while ( eIt->more())
01221           {
01222             const TopoDS_Shape* e = eIt->next();
01223             if ( helper.IsSubShape( *e, facesWOL[0]) &&
01224                  helper.IsSubShape( *e, facesWOL[1]))
01225             {
01226               _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, *e )); break;
01227             }
01228           }
01229           break;
01230         }
01231       default:
01232         return error("Not yet supported case", _sdVec[i]._index);
01233       }
01234     }
01235   }
01236 
01237   return true;
01238 }
01239 
01240 //================================================================================
01244 //================================================================================
01245 
01246 bool _ViscousBuilder::makeLayer(_SolidData& data)
01247 {
01248   // get all sub-shapes to make layers on
01249   set<TGeomID> subIds, faceIds;
01250   subIds = data._noShrinkFaces;
01251   TopExp_Explorer exp( data._solid, TopAbs_FACE );
01252   for ( ; exp.More(); exp.Next() )
01253     if ( ! _ignoreShapeIds.count( getMeshDS()->ShapeToIndex( exp.Current() )))
01254     {
01255       SMESH_subMesh* fSubM = _mesh->GetSubMesh( exp.Current() );
01256       faceIds.insert( fSubM->GetId() );
01257       SMESH_subMeshIteratorPtr subIt =
01258         fSubM->getDependsOnIterator(/*includeSelf=*/true, /*complexShapeFirst=*/false);
01259       while ( subIt->more() )
01260         subIds.insert( subIt->next()->GetId() );
01261     }
01262 
01263   // make a map to find new nodes on sub-shapes shared with other SOLID
01264   map< TGeomID, TNode2Edge* > s2neMap;
01265   map< TGeomID, TNode2Edge* >::iterator s2ne;
01266   map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
01267   for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
01268   {
01269     TGeomID shapeInd = s2s->first;
01270     for ( unsigned i = 0; i < _sdVec.size(); ++i )
01271     {
01272       if ( _sdVec[i]._index == data._index ) continue;
01273       map< TGeomID, TopoDS_Shape >::iterator s2s2 = _sdVec[i]._shrinkShape2Shape.find( shapeInd );
01274       if ( s2s2 != _sdVec[i]._shrinkShape2Shape.end() &&
01275            *s2s == *s2s2 && !_sdVec[i]._n2eMap.empty() )
01276       {
01277         s2neMap.insert( make_pair( shapeInd, &_sdVec[i]._n2eMap ));
01278         break;
01279       }
01280     }
01281   }
01282 
01283   // Create temporary faces and _LayerEdge's
01284 
01285   dumpFunction(SMESH_Comment("makeLayers_")<<data._index); 
01286 
01287   data._stepSize = Precision::Infinite();
01288   data._stepSizeNodes[0] = 0;
01289 
01290   SMESH_MesherHelper helper( *_mesh );
01291   helper.SetSubShape( data._solid );
01292   helper.SetElementsOnShape(true);
01293 
01294   vector< const SMDS_MeshNode*> newNodes; // of a mesh face
01295   TNode2Edge::iterator n2e2;
01296 
01297   // collect _LayerEdge's of shapes they are based on
01298   const int nbShapes = getMeshDS()->MaxShapeIndex();
01299   vector< vector<_LayerEdge*> > edgesByGeom( nbShapes+1 );
01300 
01301   for ( set<TGeomID>::iterator id = faceIds.begin(); id != faceIds.end(); ++id )
01302   {
01303     SMESHDS_SubMesh* smDS = getMeshDS()->MeshElements( *id );
01304     if ( !smDS ) return error(SMESH_Comment("Not meshed face ") << *id, data._index );
01305 
01306     const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( *id ));
01307     SMESH_ProxyMesh::SubMesh* proxySub =
01308       data._proxyMesh->getFaceSubM( F, /*create=*/true);
01309 
01310     SMDS_ElemIteratorPtr eIt = smDS->GetElements();
01311     while ( eIt->more() )
01312     {
01313       const SMDS_MeshElement* face = eIt->next();
01314       newNodes.resize( face->NbCornerNodes() );
01315       double faceMaxCosin = -1;
01316       for ( int i = 0 ; i < face->NbCornerNodes(); ++i )
01317       {
01318         const SMDS_MeshNode* n = face->GetNode(i);
01319         TNode2Edge::iterator n2e = data._n2eMap.insert( make_pair( n, (_LayerEdge*)0 )).first;
01320         if ( !(*n2e).second )
01321         {
01322           // add a _LayerEdge
01323           _LayerEdge* edge = new _LayerEdge();
01324           n2e->second = edge;
01325           edge->_nodes.push_back( n );
01326           const int shapeID = n->getshapeId();
01327           edgesByGeom[ shapeID ].push_back( edge );
01328 
01329           // set edge data or find already refined _LayerEdge and get data from it
01330           if ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE &&
01331                ( s2ne = s2neMap.find( shapeID )) != s2neMap.end() &&
01332                ( n2e2 = (*s2ne).second->find( n )) != s2ne->second->end())
01333           {
01334             _LayerEdge* foundEdge = (*n2e2).second;
01335             edge->Copy( *foundEdge, helper );
01336             // location of the last node is modified but we can restore
01337             // it by node position on _sWOL stored by the node
01338             const_cast< SMDS_MeshNode* >
01339               ( edge->_nodes.back() )->setXYZ( n->X(), n->Y(), n->Z() );
01340           }
01341           else
01342           {
01343             edge->_nodes.push_back( helper.AddNode( n->X(), n->Y(), n->Z() ));
01344             if ( !setEdgeData( *edge, subIds, helper, data ))
01345               return false;
01346           }
01347           dumpMove(edge->_nodes.back());
01348           if ( edge->_cosin > 0.01 )
01349           {
01350             if ( edge->_cosin > faceMaxCosin )
01351               faceMaxCosin = edge->_cosin;
01352           }
01353         }
01354         newNodes[ i ] = n2e->second->_nodes.back();
01355       }
01356       // create a temporary face
01357       const SMDS_MeshElement* newFace = new TmpMeshFace( newNodes, --_tmpFaceID );
01358       proxySub->AddElement( newFace );
01359 
01360       // compute inflation step size by min size of element on a convex surface
01361       if ( faceMaxCosin > 0.1 )
01362         limitStepSize( data, face, faceMaxCosin );
01363     } // loop on 2D elements on a FACE
01364   } // loop on FACEs of a SOLID
01365 
01366   data._epsilon = 1e-7;
01367   if ( data._stepSize < 1. )
01368     data._epsilon *= data._stepSize;
01369 
01370   // Put _LayerEdge's into a vector
01371 
01372   if ( !sortEdges( data, edgesByGeom ))
01373     return false;
01374 
01375   // Set target nodes into _Simplex and _2NearEdges
01376   TNode2Edge::iterator n2e;
01377   for ( unsigned i = 0; i < data._edges.size(); ++i )
01378   {
01379     if ( data._edges[i]->IsOnEdge())
01380       for ( int j = 0; j < 2; ++j )
01381       {
01382         if ( data._edges[i]->_nodes.back()->NbInverseElements(SMDSAbs_Volume) > 0 )
01383           break; // _LayerEdge is shared by two _SolidData's
01384         const SMDS_MeshNode* & n = data._edges[i]->_2neibors->_nodes[j];
01385         if (( n2e = data._n2eMap.find( n )) == data._n2eMap.end() )
01386           return error("_LayerEdge not found by src node", data._index);
01387         n = (*n2e).second->_nodes.back();
01388         data._edges[i]->_2neibors->_edges[j] = n2e->second;
01389       }
01390     else
01391       for ( unsigned j = 0; j < data._edges[i]->_simplices.size(); ++j )
01392       {
01393         _Simplex& s = data._edges[i]->_simplices[j];
01394         s._nNext = data._n2eMap[ s._nNext ]->_nodes.back();
01395         s._nPrev = data._n2eMap[ s._nPrev ]->_nodes.back();
01396       }
01397   }
01398 
01399   dumpFunctionEnd();
01400   return true;
01401 }
01402 
01403 //================================================================================
01407 //================================================================================
01408 
01409 void _ViscousBuilder::limitStepSize( _SolidData&             data,
01410                                      const SMDS_MeshElement* face,
01411                                      const double            cosin)
01412 {
01413   int iN = 0;
01414   double minSize = 10 * data._stepSize;
01415   const int nbNodes = face->NbCornerNodes();
01416   for ( int i = 0; i < nbNodes; ++i )
01417   {
01418     const SMDS_MeshNode* nextN = face->GetNode( SMESH_MesherHelper::WrapIndex( i+1, nbNodes ));
01419     const SMDS_MeshNode* curN = face->GetNode( i );
01420     if ( nextN->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE ||
01421          curN->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE )
01422     {
01423       double dist = SMESH_TNodeXYZ( face->GetNode(i)).Distance( nextN );
01424       if ( dist < minSize )
01425         minSize = dist, iN = i;
01426     }
01427   }
01428   double newStep = 0.8 * minSize / cosin;
01429   if ( newStep < data._stepSize )
01430   {
01431     data._stepSize = newStep;
01432     data._stepSizeCoeff = 0.8 / cosin;
01433     data._stepSizeNodes[0] = face->GetNode( iN );
01434     data._stepSizeNodes[1] = face->GetNode( SMESH_MesherHelper::WrapIndex( iN+1, nbNodes ));
01435   }
01436 }
01437 
01438 //================================================================================
01442 //================================================================================
01443 
01444 void _ViscousBuilder::limitStepSize( _SolidData& data, const double minSize)
01445 {
01446   if ( minSize < data._stepSize )
01447   {
01448     data._stepSize = minSize;
01449     if ( data._stepSizeNodes[0] )
01450     {
01451       double dist =
01452         SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
01453       data._stepSizeCoeff = data._stepSize / dist;
01454     }
01455   }
01456 }
01457 
01458 //================================================================================
01462 //================================================================================
01463 
01464 bool _ViscousBuilder::sortEdges( _SolidData&                    data,
01465                                  vector< vector<_LayerEdge*> >& edgesByGeom)
01466 {
01467   // Find shapes needing smoothing; such a shape has _LayerEdge._normal on it's
01468   // boundry inclined at a sharp angle to the shape
01469 
01470   list< TGeomID > shapesToSmooth;
01471   
01472   SMESH_MesherHelper helper( *_mesh );
01473   bool ok = true;
01474 
01475   for ( unsigned iS = 0; iS < edgesByGeom.size(); ++iS )
01476   {
01477     vector<_LayerEdge*>& eS = edgesByGeom[iS];
01478     if ( eS.empty() ) continue;
01479     TopoDS_Shape S = getMeshDS()->IndexToShape( iS );
01480     bool needSmooth = false;
01481     switch ( S.ShapeType() )
01482     {
01483     case TopAbs_EDGE: {
01484 
01485       bool isShrinkEdge = !eS[0]->_sWOL.IsNull();
01486       for ( TopoDS_Iterator vIt( S ); vIt.More() && !needSmooth; vIt.Next() )
01487       {
01488         TGeomID iV = getMeshDS()->ShapeToIndex( vIt.Value() );
01489         vector<_LayerEdge*>& eV = edgesByGeom[ iV ];
01490         if ( eV.empty() ) continue;
01491         double cosin = eV[0]->_cosin;
01492         bool badCosin =
01493           ( !eV[0]->_sWOL.IsNull() && ( eV[0]->_sWOL.ShapeType() == TopAbs_EDGE || !isShrinkEdge));
01494         if ( badCosin )
01495         {
01496           gp_Vec dir1, dir2;
01497           if ( eV[0]->_sWOL.ShapeType() == TopAbs_EDGE )
01498             dir1 = getEdgeDir( TopoDS::Edge( eV[0]->_sWOL ), TopoDS::Vertex( vIt.Value() ));
01499           else
01500             dir1 = getFaceDir( TopoDS::Face( eV[0]->_sWOL ), TopoDS::Vertex( vIt.Value() ),
01501                                eV[0]->_nodes[0], helper, ok);
01502           dir2 = getEdgeDir( TopoDS::Edge( S ), TopoDS::Vertex( vIt.Value() ));
01503           double angle = dir1.Angle( dir2 );
01504           cosin = cos( angle );
01505         }
01506         needSmooth = ( cosin > 0.1 );
01507       }
01508       break;
01509     }
01510     case TopAbs_FACE: {
01511 
01512       for ( TopExp_Explorer eExp( S, TopAbs_EDGE ); eExp.More() && !needSmooth; eExp.Next() )
01513       {
01514         TGeomID iE = getMeshDS()->ShapeToIndex( eExp.Current() );
01515         vector<_LayerEdge*>& eE = edgesByGeom[ iE ];
01516         if ( eE.empty() ) continue;
01517         if ( eE[0]->_sWOL.IsNull() )
01518         {
01519           for ( unsigned i = 0; i < eE.size() && !needSmooth; ++i )
01520             needSmooth = ( eE[i]->_cosin > 0.1 );
01521         }
01522         else
01523         {
01524           const TopoDS_Face& F1 = TopoDS::Face( S );
01525           const TopoDS_Face& F2 = TopoDS::Face( eE[0]->_sWOL );
01526           const TopoDS_Edge& E  = TopoDS::Edge( eExp.Current() );
01527           for ( unsigned i = 0; i < eE.size() && !needSmooth; ++i )
01528           {
01529             gp_Vec dir1 = getFaceDir( F1, E, eE[i]->_nodes[0], helper, ok );
01530             gp_Vec dir2 = getFaceDir( F2, E, eE[i]->_nodes[0], helper, ok );
01531             double angle = dir1.Angle( dir2 );
01532             double cosin = cos( angle );
01533             needSmooth = ( cosin > 0.1 );
01534           }
01535         }
01536       }
01537       break;
01538     }
01539     case TopAbs_VERTEX:
01540       continue;
01541     default:;
01542     }
01543     if ( needSmooth )
01544     {
01545       if ( S.ShapeType() == TopAbs_EDGE ) shapesToSmooth.push_front( iS );
01546       else                                shapesToSmooth.push_back ( iS );
01547     }
01548 
01549   } // loop on edgesByGeom
01550 
01551   data._edges.reserve( data._n2eMap.size() );
01552   data._endEdgeToSmooth.clear();
01553 
01554   // first we put _LayerEdge's on shapes to smooth
01555   list< TGeomID >::iterator gIt = shapesToSmooth.begin();
01556   for ( ; gIt != shapesToSmooth.end(); ++gIt )
01557   {
01558     vector<_LayerEdge*>& eVec = edgesByGeom[ *gIt ];
01559     if ( eVec.empty() ) continue;
01560     data._edges.insert( data._edges.end(), eVec.begin(), eVec.end() );
01561     data._endEdgeToSmooth.push_back( data._edges.size() );
01562     eVec.clear();
01563   }
01564 
01565   // then the rest _LayerEdge's
01566   for ( unsigned iS = 0; iS < edgesByGeom.size(); ++iS )
01567   {
01568     vector<_LayerEdge*>& eVec = edgesByGeom[iS];
01569     data._edges.insert( data._edges.end(), eVec.begin(), eVec.end() );
01570     eVec.clear();
01571   }
01572 
01573   return ok;
01574 }
01575 
01576 //================================================================================
01581 //================================================================================
01582 
01583 bool _ViscousBuilder::setEdgeData(_LayerEdge&         edge,
01584                                   const set<TGeomID>& subIds,
01585                                   SMESH_MesherHelper& helper,
01586                                   _SolidData&         data)
01587 {
01588   SMESH_MeshEditor editor(_mesh);
01589 
01590   const SMDS_MeshNode* node = edge._nodes[0]; // source node
01591   SMDS_TypeOfPosition posType = node->GetPosition()->GetTypeOfPosition();
01592 
01593   edge._len = 0;
01594   edge._2neibors = 0;
01595   edge._curvature = 0;
01596 
01597   // --------------------------
01598   // Compute _normal and _cosin
01599   // --------------------------
01600 
01601   edge._cosin = 0;
01602   edge._normal.SetCoord(0,0,0);
01603 
01604   int totalNbFaces = 0;
01605   gp_Pnt p;
01606   gp_Vec du, dv, geomNorm;
01607   bool normOK = true;
01608 
01609   TGeomID shapeInd = node->getshapeId();
01610   map< TGeomID, TopoDS_Shape >::const_iterator s2s = data._shrinkShape2Shape.find( shapeInd );
01611   bool onShrinkShape ( s2s != data._shrinkShape2Shape.end() );
01612   TopoDS_Shape vertEdge;
01613 
01614   if ( onShrinkShape ) // one of faces the node is on has no layers
01615   {
01616     vertEdge = getMeshDS()->IndexToShape( s2s->first ); // vertex or edge
01617     if ( s2s->second.ShapeType() == TopAbs_EDGE )
01618     {
01619       // inflate from VERTEX along EDGE
01620       edge._normal = getEdgeDir( TopoDS::Edge( s2s->second ), TopoDS::Vertex( vertEdge ));
01621     }
01622     else if ( vertEdge.ShapeType() == TopAbs_VERTEX )
01623     {
01624       // inflate from VERTEX along FACE
01625       edge._normal = getFaceDir( TopoDS::Face( s2s->second ), TopoDS::Vertex( vertEdge ),
01626                                  node, helper, normOK, &edge._cosin);
01627     }
01628     else
01629     {
01630       // inflate from EDGE along FACE
01631       edge._normal = getFaceDir( TopoDS::Face( s2s->second ), TopoDS::Edge( vertEdge ),
01632                                  node, helper, normOK);
01633     }
01634   }
01635   else // layers are on all faces of SOLID the node is on
01636   {
01637     // find indices of geom faces the node lies on
01638     set<TGeomID> faceIds;
01639     if  ( posType == SMDS_TOP_FACE )
01640     {
01641       faceIds.insert( node->getshapeId() );
01642     }
01643     else
01644     {
01645       SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
01646       while ( fIt->more() )
01647         faceIds.insert( editor.FindShape(fIt->next()));
01648     }
01649 
01650     set<TGeomID>::iterator id = faceIds.begin();
01651     TopoDS_Face F;
01652     for ( ; id != faceIds.end(); ++id )
01653     {
01654       const TopoDS_Shape& s = getMeshDS()->IndexToShape( *id );
01655       if ( s.IsNull() || s.ShapeType() != TopAbs_FACE || !subIds.count( *id ))
01656         continue;
01657       totalNbFaces++;
01658       //nbLayerFaces += subIds.count( *id );
01659       F = TopoDS::Face( s );
01660 
01661       gp_XY uv = helper.GetNodeUV( F, node, 0, &normOK );
01662       Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
01663       surface->D1( uv.X(),uv.Y(), p, du,dv );
01664       geomNorm = du ^ dv;
01665       double size2 = geomNorm.SquareMagnitude();
01666       if ( size2 > numeric_limits<double>::min() )
01667         geomNorm /= sqrt( size2 );
01668       else
01669         normOK = false;
01670       if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
01671         geomNorm.Reverse();
01672       edge._normal += geomNorm.XYZ();
01673     }
01674     if ( totalNbFaces == 0 )
01675       return error(SMESH_Comment("Can't get normal to node ") << node->GetID(), data._index);
01676 
01677     edge._normal /= totalNbFaces;
01678 
01679     switch ( posType )
01680     {
01681     case SMDS_TOP_FACE:
01682       edge._cosin = 0; break;
01683 
01684     case SMDS_TOP_EDGE: {
01685       TopoDS_Edge E = TopoDS::Edge( helper.GetSubShapeByNode( node, getMeshDS()));
01686       gp_Vec inFaceDir = getFaceDir( F, E, node, helper, normOK);
01687       double angle = inFaceDir.Angle( edge._normal ); // [0,PI]
01688       edge._cosin = cos( angle );
01689       //cout << "Cosin on EDGE " << edge._cosin << " node " << node->GetID() << endl;
01690       break;
01691     }
01692     case SMDS_TOP_VERTEX: {
01693       TopoDS_Vertex V = TopoDS::Vertex( helper.GetSubShapeByNode( node, getMeshDS()));
01694       gp_Vec inFaceDir = getFaceDir( F, V, node, helper, normOK);
01695       double angle = inFaceDir.Angle( edge._normal ); // [0,PI]
01696       edge._cosin = cos( angle );
01697       //cout << "Cosin on VERTEX " << edge._cosin << " node " << node->GetID() << endl;
01698       break;
01699     }
01700     default:
01701       return error(SMESH_Comment("Invalid shape position of node ")<<node, data._index);
01702     }
01703   }
01704 
01705   double normSize = edge._normal.SquareModulus();
01706   if ( normSize < numeric_limits<double>::min() )
01707     return error(SMESH_Comment("Bad normal at node ")<< node->GetID(), data._index );
01708 
01709   edge._normal /= sqrt( normSize );
01710 
01711   // TODO: if ( !normOK ) then get normal by mesh faces
01712 
01713   // Set the rest data
01714   // --------------------
01715   if ( onShrinkShape )
01716   {
01717     edge._sWOL = (*s2s).second;
01718 
01719     SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edge._nodes.back() );
01720     if ( SMESHDS_SubMesh* sm = getMeshDS()->MeshElements( data._solid ))
01721       sm->RemoveNode( tgtNode , /*isNodeDeleted=*/false );
01722 
01723     // set initial position which is parameters on _sWOL in this case
01724     if ( edge._sWOL.ShapeType() == TopAbs_EDGE )
01725     {
01726       double u = helper.GetNodeU( TopoDS::Edge( edge._sWOL ), node, 0, &normOK );
01727       edge._pos.push_back( gp_XYZ( u, 0, 0));
01728       getMeshDS()->SetNodeOnEdge( tgtNode, TopoDS::Edge( edge._sWOL ), u );
01729     }
01730     else // TopAbs_FACE
01731     {
01732       gp_XY uv = helper.GetNodeUV( TopoDS::Face( edge._sWOL ), node, 0, &normOK );
01733       edge._pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
01734       getMeshDS()->SetNodeOnFace( tgtNode, TopoDS::Face( edge._sWOL ), uv.X(), uv.Y() );
01735     }
01736   }
01737   else
01738   {
01739     edge._pos.push_back( SMESH_TNodeXYZ( node ));
01740 
01741     if ( posType == SMDS_TOP_FACE )
01742     {
01743       getSimplices( node, edge._simplices, _ignoreShapeIds, &data );
01744       double avgNormProj = 0, avgLen = 0;
01745       for ( unsigned i = 0; i < edge._simplices.size(); ++i )
01746       {
01747         gp_XYZ vec = edge._pos.back() - SMESH_TNodeXYZ( edge._simplices[i]._nPrev );
01748         avgNormProj += edge._normal * vec;
01749         avgLen += vec.Modulus();
01750       }
01751       avgNormProj /= edge._simplices.size();
01752       avgLen /= edge._simplices.size();
01753       edge._curvature = _Curvature::New( avgNormProj, avgLen );
01754     }
01755   }
01756 
01757   // Set neighbour nodes for a _LayerEdge based on EDGE
01758 
01759   if ( posType == SMDS_TOP_EDGE /*||
01760        ( onShrinkShape && posType == SMDS_TOP_VERTEX && fabs( edge._cosin ) < 1e-10 )*/)
01761   {
01762     edge._2neibors = new _2NearEdges;
01763     // target node instead of source ones will be set later
01764     if ( ! findNeiborsOnEdge( &edge,
01765                               edge._2neibors->_nodes[0],
01766                               edge._2neibors->_nodes[1],
01767                               data))
01768       return false;
01769     edge.SetDataByNeighbors( edge._2neibors->_nodes[0],
01770                              edge._2neibors->_nodes[1],
01771                              helper);
01772   }
01773 
01774   edge.SetCosin( edge._cosin ); // to update edge._lenFactor
01775 
01776   return true;
01777 }
01778 
01779 //================================================================================
01783 //================================================================================
01784 
01785 bool _ViscousBuilder::findNeiborsOnEdge(const _LayerEdge*     edge,
01786                                         const SMDS_MeshNode*& n1,
01787                                         const SMDS_MeshNode*& n2,
01788                                         _SolidData&           data)
01789 {
01790   const SMDS_MeshNode* node = edge->_nodes[0];
01791   const int shapeInd = node->getshapeId();
01792   SMESHDS_SubMesh* edgeSM = 0;
01793   if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_EDGE )
01794   {
01795     
01796     edgeSM = getMeshDS()->MeshElements( shapeInd );
01797     if ( !edgeSM || edgeSM->NbElements() == 0 )
01798       return error(SMESH_Comment("Not meshed EDGE ") << shapeInd, data._index);
01799   }
01800   int iN = 0;
01801   n2 = 0;
01802   SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator(SMDSAbs_Edge);
01803   while ( eIt->more() && !n2 )
01804   {
01805     const SMDS_MeshElement* e = eIt->next();
01806     const SMDS_MeshNode*   nNeibor = e->GetNode( 0 );
01807     if ( nNeibor == node ) nNeibor = e->GetNode( 1 );
01808     if ( edgeSM )
01809     {
01810       if (!edgeSM->Contains(e)) continue;
01811     }
01812     else
01813     {
01814       TopoDS_Shape s = SMESH_MesherHelper::GetSubShapeByNode(nNeibor, getMeshDS() );
01815       if ( !SMESH_MesherHelper::IsSubShape( s, edge->_sWOL )) continue;
01816     }
01817     ( iN++ ? n2 : n1 ) = nNeibor;
01818   }
01819   if ( !n2 )
01820     return error(SMESH_Comment("Wrongly meshed EDGE ") << shapeInd, data._index);
01821   return true;
01822 }
01823 
01824 //================================================================================
01828 //================================================================================
01829 
01830 void _LayerEdge::SetDataByNeighbors( const SMDS_MeshNode* n1,
01831                                      const SMDS_MeshNode* n2,
01832                                      SMESH_MesherHelper&  helper)
01833 {
01834   if ( _nodes[0]->GetPosition()->GetTypeOfPosition() != SMDS_TOP_EDGE )
01835     return;
01836 
01837   gp_XYZ pos = SMESH_TNodeXYZ( _nodes[0] );
01838   gp_XYZ vec1 = pos - SMESH_TNodeXYZ( n1 );
01839   gp_XYZ vec2 = pos - SMESH_TNodeXYZ( n2 );
01840 
01841   // Set _curvature
01842 
01843   double sumLen = vec1.Modulus() + vec2.Modulus();
01844   _2neibors->_wgt[0] = 1 - vec1.Modulus() / sumLen;
01845   _2neibors->_wgt[1] = 1 - vec2.Modulus() / sumLen;
01846   double avgNormProj = 0.5 * ( _normal * vec1 + _normal * vec2 );
01847   double avgLen = 0.5 * ( vec1.Modulus() + vec2.Modulus() );
01848   if ( _curvature ) delete _curvature;
01849   _curvature = _Curvature::New( avgNormProj, avgLen );
01850 #ifdef __myDEBUG
01851 //     if ( _curvature )
01852 //       cout << _nodes[0]->GetID()
01853 //            << " CURV r,k: " << _curvature->_r<<","<<_curvature->_k
01854 //            << " proj = "<<avgNormProj<< " len = " << avgLen << "| lenDelta(0) = "
01855 //            << _curvature->lenDelta(0) << endl;
01856 #endif
01857 
01858   // Set _plnNorm
01859 
01860   if ( _sWOL.IsNull() )
01861   {
01862     TopoDS_Shape S = helper.GetSubShapeByNode( _nodes[0], helper.GetMeshDS() );
01863     gp_XYZ dirE = getEdgeDir( TopoDS::Edge( S ), _nodes[0], helper );
01864     gp_XYZ plnNorm = dirE ^ _normal;
01865     double proj0 = plnNorm * vec1;
01866     double proj1 = plnNorm * vec2;
01867     if ( fabs( proj0 ) > 1e-10 || fabs( proj1 ) > 1e-10 )
01868     {
01869       if ( _2neibors->_plnNorm ) delete _2neibors->_plnNorm;
01870       _2neibors->_plnNorm = new gp_XYZ( plnNorm.Normalized() );
01871     }
01872   }
01873 }
01874 
01875 //================================================================================
01880 //================================================================================
01881 
01882 void _LayerEdge::Copy( _LayerEdge& other, SMESH_MesherHelper& helper )
01883 {
01884   _nodes     = other._nodes;
01885   _normal    = other._normal;
01886   _len       = 0;
01887   _lenFactor = other._lenFactor;
01888   _cosin     = other._cosin;
01889   _sWOL      = other._sWOL;
01890   _2neibors  = other._2neibors;
01891   _curvature = 0; std::swap( _curvature, other._curvature );
01892   _2neibors  = 0; std::swap( _2neibors,  other._2neibors );
01893 
01894   if ( _sWOL.ShapeType() == TopAbs_EDGE )
01895   {
01896     double u = helper.GetNodeU( TopoDS::Edge( _sWOL ), _nodes[0] );
01897     _pos.push_back( gp_XYZ( u, 0, 0));
01898   }
01899   else // TopAbs_FACE
01900   {
01901     gp_XY uv = helper.GetNodeUV( TopoDS::Face( _sWOL ), _nodes[0]);
01902     _pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
01903   }
01904 }
01905 
01906 //================================================================================
01910 //================================================================================
01911 
01912 void _LayerEdge::SetCosin( double cosin )
01913 {
01914   _cosin = cosin;
01915   _lenFactor = ( _cosin > 0.1 ) ?  1./sqrt(1-_cosin*_cosin) : 1.0;
01916 }
01917 
01918 //================================================================================
01922 //================================================================================
01923 
01924 void _ViscousBuilder::getSimplices( const SMDS_MeshNode* node,
01925                                     vector<_Simplex>&    simplices,
01926                                     const set<TGeomID>&  ingnoreShapes,
01927                                     const _SolidData*    dataToCheckOri,
01928                                     const bool           toSort)
01929 {
01930   SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
01931   while ( fIt->more() )
01932   {
01933     const SMDS_MeshElement* f = fIt->next();
01934     const TGeomID shapeInd = f->getshapeId();
01935     if ( ingnoreShapes.count( shapeInd )) continue;
01936     const int nbNodes = f->NbCornerNodes();
01937     int srcInd = f->GetNodeIndex( node );
01938     const SMDS_MeshNode* nPrev = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd-1, nbNodes ));
01939     const SMDS_MeshNode* nNext = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+1, nbNodes ));
01940     if ( dataToCheckOri && dataToCheckOri->_reversedFaceIds.count( shapeInd ))
01941       std::swap( nPrev, nNext );
01942     simplices.push_back( _Simplex( nPrev, nNext ));
01943   }
01944 
01945   if ( toSort )
01946   {
01947     vector<_Simplex> sortedSimplices( simplices.size() );
01948     sortedSimplices[0] = simplices[0];
01949     int nbFound = 0;
01950     for ( size_t i = 1; i < simplices.size(); ++i )
01951     {
01952       for ( size_t j = 1; j < simplices.size(); ++j )
01953         if ( sortedSimplices[i-1]._nNext == simplices[j]._nPrev )
01954         {
01955           sortedSimplices[i] = simplices[j];
01956           nbFound++;
01957           break;
01958         }
01959     }
01960     if ( nbFound == simplices.size() - 1 )
01961       simplices.swap( sortedSimplices );
01962   }
01963 }
01964 
01965 //================================================================================
01969 //================================================================================
01970 
01971 void _ViscousBuilder::makeGroupOfLE()
01972 {
01973 #ifdef _DEBUG_
01974   for ( unsigned i = 0 ; i < _sdVec.size(); ++i )
01975   {
01976     if ( _sdVec[i]._edges.empty() ) continue;
01977 //     string name = SMESH_Comment("_LayerEdge's_") << i;
01978 //     int id;
01979 //     SMESH_Group* g = _mesh->AddGroup(SMDSAbs_Edge, name.c_str(), id );
01980 //     SMESHDS_Group* gDS = (SMESHDS_Group*)g->GetGroupDS();
01981 //     SMESHDS_Mesh* mDS = _mesh->GetMeshDS();
01982 
01983     dumpFunction( SMESH_Comment("make_LayerEdge_") << i );
01984     for ( unsigned j = 0 ; j < _sdVec[i]._edges.size(); ++j )
01985     {
01986       _LayerEdge* le = _sdVec[i]._edges[j];
01987       for ( unsigned iN = 1; iN < le->_nodes.size(); ++iN )
01988         dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<le->_nodes[iN-1]->GetID()
01989                 << ", " << le->_nodes[iN]->GetID() <<"])");
01990       //gDS->SMDSGroup().Add( mDS->AddEdge( le->_nodes[iN-1], le->_nodes[iN]));
01991     }
01992     dumpFunctionEnd();
01993 
01994     dumpFunction( SMESH_Comment("makeNormals") << i );
01995     for ( unsigned j = 0 ; j < _sdVec[i]._edges.size(); ++j )
01996     {
01997       _LayerEdge& edge = *_sdVec[i]._edges[j];
01998       SMESH_TNodeXYZ nXYZ( edge._nodes[0] );
01999       nXYZ += edge._normal * _sdVec[i]._stepSize;
02000       dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<edge._nodes[0]->GetID()
02001               << ", mesh.AddNode( " << nXYZ.X()<<","<< nXYZ.Y()<<","<< nXYZ.Z()<<")])");
02002     }
02003     dumpFunctionEnd();
02004 
02005 //     name = SMESH_Comment("tmp_faces ") << i;
02006 //     g = _mesh->AddGroup(SMDSAbs_Face, name.c_str(), id );
02007 //     gDS = (SMESHDS_Group*)g->GetGroupDS();
02008 //     SMESH_MeshEditor editor( _mesh );
02009     dumpFunction( SMESH_Comment("makeTmpFaces_") << i );
02010     TopExp_Explorer fExp( _sdVec[i]._solid, TopAbs_FACE );
02011     for ( ; fExp.More(); fExp.Next() )
02012     {
02013       if (const SMESHDS_SubMesh* sm = _sdVec[i]._proxyMesh->GetProxySubMesh( fExp.Current()))
02014       {
02015         SMDS_ElemIteratorPtr fIt = sm->GetElements();
02016         while ( fIt->more())
02017         {
02018           const SMDS_MeshElement* e = fIt->next();
02019           SMESH_Comment cmd("mesh.AddFace([");
02020           for ( int j=0; j < e->NbCornerNodes(); ++j )
02021             cmd << e->GetNode(j)->GetID() << (j+1<e->NbCornerNodes() ? ",": "])");
02022           dumpCmd( cmd );
02023           //vector<const SMDS_MeshNode*> nodes( e->begin_nodes(), e->end_nodes() );
02024           //gDS->SMDSGroup().Add( editor.AddElement( nodes, e->GetType(), e->IsPoly()));
02025         }
02026       }
02027     }
02028     dumpFunctionEnd();
02029   }
02030 #endif
02031 }
02032 
02033 //================================================================================
02037 //================================================================================
02038 
02039 bool _ViscousBuilder::inflate(_SolidData& data)
02040 {
02041   SMESH_MesherHelper helper( *_mesh );
02042 
02043   // Limit inflation step size by geometry size found by itersecting
02044   // normals of _LayerEdge's with mesh faces
02045   double geomSize = Precision::Infinite(), intersecDist;
02046   SMESH_MeshEditor editor( _mesh );
02047   auto_ptr<SMESH_ElementSearcher> searcher
02048     ( editor.GetElementSearcher( data._proxyMesh->GetFaces( data._solid )) );
02049   for ( unsigned i = 0; i < data._edges.size(); ++i )
02050   {
02051     if ( data._edges[i]->IsOnEdge() ) continue;
02052     data._edges[i]->FindIntersection( *searcher, intersecDist, data._epsilon );
02053     if ( geomSize > intersecDist )
02054       geomSize = intersecDist;
02055   }
02056   if ( data._stepSize > 0.3 * geomSize )
02057     limitStepSize( data, 0.3 * geomSize );
02058 
02059   const double tgtThick = data._hyp->GetTotalThickness();
02060   if ( data._stepSize > tgtThick )
02061     limitStepSize( data, tgtThick );
02062 
02063   if ( data._stepSize < 1. )
02064     data._epsilon = data._stepSize * 1e-7;
02065 
02066 #ifdef __myDEBUG
02067   cout << "-- geomSize = " << geomSize << ", stepSize = " << data._stepSize << endl;
02068 #endif
02069 
02070   double avgThick = 0, curThick = 0, distToIntersection = Precision::Infinite();
02071   int nbSteps = 0, nbRepeats = 0;
02072   while ( 1.01 * avgThick < tgtThick )
02073   {
02074     // new target length
02075     curThick += data._stepSize;
02076     if ( curThick > tgtThick )
02077     {
02078       curThick = tgtThick + ( tgtThick-avgThick ) * nbRepeats;
02079       nbRepeats++;
02080     }
02081 
02082     // Elongate _LayerEdge's
02083     dumpFunction(SMESH_Comment("inflate")<<data._index<<"_step"<<nbSteps); // debug
02084     for ( unsigned i = 0; i < data._edges.size(); ++i )
02085     {
02086       data._edges[i]->SetNewLength( curThick, helper );
02087     }
02088     dumpFunctionEnd();
02089 
02090     if ( !nbSteps )
02091       if ( !updateNormals( data, helper ) )
02092         return false;
02093 
02094     // Improve and check quality
02095     if ( !smoothAndCheck( data, nbSteps, distToIntersection ))
02096     {
02097       if ( nbSteps > 0 )
02098       {
02099         dumpFunction(SMESH_Comment("invalidate")<<data._index<<"_step"<<nbSteps); // debug
02100         for ( unsigned i = 0; i < data._edges.size(); ++i )
02101         {
02102           data._edges[i]->InvalidateStep( nbSteps+1 );
02103         }
02104         dumpFunctionEnd();
02105       }
02106       break; // no more inflating possible
02107     }
02108     nbSteps++;
02109 
02110     // Evaluate achieved thickness
02111     avgThick = 0;
02112     for ( unsigned i = 0; i < data._edges.size(); ++i )
02113       avgThick += data._edges[i]->_len;
02114     avgThick /= data._edges.size();
02115 #ifdef __myDEBUG
02116     cout << "-- Thickness " << avgThick << " reached" << endl;
02117 #endif
02118 
02119     if ( distToIntersection < avgThick*1.5 )
02120     {
02121 #ifdef __myDEBUG
02122       cout << "-- Stop inflation since distToIntersection( "<<distToIntersection<<" ) < avgThick( "
02123            << avgThick << " ) * 1.5" << endl;
02124 #endif
02125       break;
02126     }
02127     // new step size
02128     limitStepSize( data, 0.25 * distToIntersection );
02129     if ( data._stepSizeNodes[0] )
02130       data._stepSize = data._stepSizeCoeff *
02131         SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
02132   }
02133 
02134   if (nbSteps == 0 )
02135     return error("failed at the very first inflation step", data._index);
02136 
02137   return true;
02138 }
02139 
02140 //================================================================================
02144 //================================================================================
02145 
02146 bool _ViscousBuilder::smoothAndCheck(_SolidData& data,
02147                                      const int   nbSteps,
02148                                      double &    distToIntersection)
02149 {
02150   if ( data._endEdgeToSmooth.empty() )
02151     return true; // no shapes needing smoothing
02152 
02153   bool moved, improved;
02154 
02155   SMESH_MesherHelper helper(*_mesh);
02156   Handle(Geom_Surface) surface;
02157   TopoDS_Face F;
02158 
02159   int iBeg, iEnd = 0;
02160   for ( unsigned iS = 0; iS < data._endEdgeToSmooth.size(); ++iS )
02161   {
02162     iBeg = iEnd;
02163     iEnd = data._endEdgeToSmooth[ iS ];
02164 
02165     if ( !data._edges[ iBeg ]->_sWOL.IsNull() &&
02166          data._edges[ iBeg ]->_sWOL.ShapeType() == TopAbs_FACE )
02167     {
02168       if ( !F.IsSame( data._edges[ iBeg ]->_sWOL )) {
02169         F = TopoDS::Face( data._edges[ iBeg ]->_sWOL );
02170         helper.SetSubShape( F );
02171         surface = BRep_Tool::Surface( F );
02172       }
02173     }
02174     else
02175     {
02176       F.Nullify(); surface.Nullify();
02177     }
02178     TGeomID sInd = data._edges[ iBeg ]->_nodes[0]->getshapeId();
02179 
02180     if ( data._edges[ iBeg ]->IsOnEdge() )
02181     { 
02182       dumpFunction(SMESH_Comment("smooth")<<data._index << "_Ed"<<sInd <<"_InfStep"<<nbSteps);
02183 
02184       // try a simple solution on an analytic EDGE
02185       if ( !smoothAnalyticEdge( data, iBeg, iEnd, surface, F, helper ))
02186       {
02187         // smooth on EDGE's
02188         int step = 0;
02189         do {
02190           moved = false;
02191           for ( int i = iBeg; i < iEnd; ++i )
02192           {
02193             moved |= data._edges[i]->SmoothOnEdge(surface, F, helper);
02194           }
02195           dumpCmd( SMESH_Comment("# end step ")<<step);
02196         }
02197         while ( moved && step++ < 5 );
02198         //cout << " NB STEPS: " << step << endl;
02199       }
02200       dumpFunctionEnd();
02201     }
02202     else
02203     {
02204       // smooth on FACE's
02205       int step = 0, badNb = 0; moved = true;
02206       while (( ++step <= 5 && moved ) || improved )
02207       {
02208         dumpFunction(SMESH_Comment("smooth")<<data._index<<"_Fa"<<sInd
02209                      <<"_InfStep"<<nbSteps<<"_"<<step); // debug
02210         int oldBadNb = badNb;
02211         badNb = 0;
02212         moved = false;
02213         for ( int i = iBeg; i < iEnd; ++i )
02214           moved |= data._edges[i]->Smooth(badNb);
02215         improved = ( badNb < oldBadNb );
02216 
02217         dumpFunctionEnd();
02218       }
02219       if ( badNb > 0 )
02220       {
02221 #ifdef __myDEBUG
02222         for ( int i = iBeg; i < iEnd; ++i )
02223         {
02224           _LayerEdge* edge = data._edges[i];
02225           SMESH_TNodeXYZ tgtXYZ( edge->_nodes.back() );
02226           for ( unsigned j = 0; j < edge->_simplices.size(); ++j )
02227             if ( !edge->_simplices[j].IsForward( edge->_nodes[0], &tgtXYZ ))
02228             {
02229               cout << "Bad simplex ( " << edge->_nodes[0]->GetID()<< " "<< tgtXYZ._node->GetID()
02230                    << " "<< edge->_simplices[j]._nPrev->GetID()
02231                    << " "<< edge->_simplices[j]._nNext->GetID() << " )" << endl;
02232               return false;
02233             }
02234         }
02235 #endif
02236         return false;
02237       }
02238     }
02239   } // loop on shapes to smooth
02240 
02241   // Check if the last segments of _LayerEdge intersects 2D elements;
02242   // checked elements are either temporary faces or faces on surfaces w/o the layers
02243 
02244   SMESH_MeshEditor editor( _mesh );
02245   auto_ptr<SMESH_ElementSearcher> searcher
02246     ( editor.GetElementSearcher( data._proxyMesh->GetFaces( data._solid )) );
02247 
02248   distToIntersection = Precision::Infinite();
02249   double dist;
02250   const SMDS_MeshElement* intFace = 0;
02251 #ifdef __myDEBUG
02252   const SMDS_MeshElement* closestFace = 0;
02253   int iLE = 0;
02254 #endif
02255   for ( unsigned i = 0; i < data._edges.size(); ++i )
02256   {
02257     if ( data._edges[i]->FindIntersection( *searcher, dist, data._epsilon, &intFace ))
02258       return false;
02259     if ( distToIntersection > dist )
02260     {
02261       distToIntersection = dist;
02262 #ifdef __myDEBUG
02263       iLE = i;
02264       closestFace = intFace;
02265 #endif
02266     }
02267   }
02268 #ifdef __myDEBUG
02269   if ( closestFace )
02270   {
02271     SMDS_MeshElement::iterator nIt = closestFace->begin_nodes();
02272     cout << "Shortest distance: _LayerEdge nodes: tgt " << data._edges[iLE]->_nodes.back()->GetID()
02273          << " src " << data._edges[iLE]->_nodes[0]->GetID()<< ", intersection with face ("
02274          << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
02275          << ") distance = " << distToIntersection<< endl;
02276   }
02277 #endif
02278 
02279   return true;
02280 }
02281 
02282 //================================================================================
02287 //================================================================================
02288 
02289 Handle(Geom_Curve) _SolidData::CurveForSmooth( const TopoDS_Edge&    E,
02290                                                const int             iFrom,
02291                                                const int             iTo,
02292                                                Handle(Geom_Surface)& surface,
02293                                                const TopoDS_Face&    F,
02294                                                SMESH_MesherHelper&   helper)
02295 {
02296   TGeomID eIndex = helper.GetMeshDS()->ShapeToIndex( E );
02297 
02298   map< TGeomID, Handle(Geom_Curve)>::iterator i2curve = _edge2curve.find( eIndex );
02299 
02300   if ( i2curve == _edge2curve.end() )
02301   {
02302     // sort _LayerEdge's by position on the EDGE
02303     {
02304       map< double, _LayerEdge* > u2edge;
02305       for ( int i = iFrom; i < iTo; ++i )
02306         u2edge.insert( make_pair( helper.GetNodeU( E, _edges[i]->_nodes[0] ), _edges[i] ));
02307 
02308       ASSERT( u2edge.size() == iTo - iFrom );
02309       map< double, _LayerEdge* >::iterator u2e = u2edge.begin();
02310       for ( int i = iFrom; i < iTo; ++i, ++u2e )
02311         _edges[i] = u2e->second;
02312 
02313       // set _2neibors according to the new order
02314       for ( int i = iFrom; i < iTo-1; ++i )
02315         if ( _edges[i]->_2neibors->_nodes[1] != _edges[i+1]->_nodes.back() )
02316           _edges[i]->_2neibors->reverse();
02317       if ( u2edge.size() > 1 &&
02318            _edges[iTo-1]->_2neibors->_nodes[0] != _edges[iTo-2]->_nodes.back() )
02319         _edges[iTo-1]->_2neibors->reverse();
02320     }
02321 
02322     SMESHDS_SubMesh* smDS = helper.GetMeshDS()->MeshElements( eIndex );
02323 
02324     TopLoc_Location loc; double f,l;
02325 
02326     Handle(Geom_Line)   line;
02327     Handle(Geom_Circle) circle;
02328     bool isLine, isCirc;
02329     if ( F.IsNull() ) // 3D case
02330     {
02331       // check if the EDGE is a line
02332       Handle(Geom_Curve) curve = BRep_Tool::Curve( E, loc, f, l);
02333       if ( curve->IsKind( STANDARD_TYPE( Geom_TrimmedCurve )))
02334         curve = Handle(Geom_TrimmedCurve)::DownCast( curve )->BasisCurve();
02335 
02336       line   = Handle(Geom_Line)::DownCast( curve );
02337       circle = Handle(Geom_Circle)::DownCast( curve );
02338       isLine = (!line.IsNull());
02339       isCirc = (!circle.IsNull());
02340 
02341       if ( !isLine && !isCirc ) // Check if the EDGE is close to a line
02342       {
02343         Bnd_B3d bndBox;
02344         SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
02345         while ( nIt->more() )
02346           bndBox.Add( SMESH_TNodeXYZ( nIt->next() ));
02347         gp_XYZ size = bndBox.CornerMax() - bndBox.CornerMin();
02348 
02349         SMESH_TNodeXYZ p0( _edges[iFrom]->_2neibors->_nodes[0] );
02350         SMESH_TNodeXYZ p1( _edges[iFrom]->_2neibors->_nodes[1] );
02351         const double lineTol = 1e-2 * ( p0 - p1 ).Modulus();
02352         for ( int i = 0; i < 3 && !isLine; ++i )
02353           isLine = ( size.Coord( i+1 ) <= lineTol );
02354       }
02355       if ( !isLine && !isCirc && iTo-iFrom > 2) // Check if the EDGE is close to a circle
02356       {
02357         // TODO
02358       }
02359     }
02360     else // 2D case
02361     {
02362       // check if the EDGE is a line
02363       Handle(Geom2d_Curve) curve = BRep_Tool::CurveOnSurface( E, F, f, l);
02364       if ( curve->IsKind( STANDARD_TYPE( Geom2d_TrimmedCurve )))
02365         curve = Handle(Geom2d_TrimmedCurve)::DownCast( curve )->BasisCurve();
02366 
02367       Handle(Geom2d_Line)   line2d   = Handle(Geom2d_Line)::DownCast( curve );
02368       Handle(Geom2d_Circle) circle2d = Handle(Geom2d_Circle)::DownCast( curve );
02369       isLine = (!line2d.IsNull());
02370       isCirc = (!circle2d.IsNull());
02371 
02372       if ( !isLine && !isCirc) // Check if the EDGE is close to a line
02373       {
02374         Bnd_B2d bndBox;
02375         SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
02376         while ( nIt->more() )
02377           bndBox.Add( helper.GetNodeUV( F, nIt->next() ));
02378         gp_XY size = bndBox.CornerMax() - bndBox.CornerMin();
02379 
02380         const double lineTol = 1e-2 * sqrt( bndBox.SquareExtent() );
02381         for ( int i = 0; i < 2 && !isLine; ++i )
02382           isLine = ( size.Coord( i+1 ) <= lineTol );
02383       }
02384       if ( !isLine && !isCirc && iTo-iFrom > 2) // Check if the EDGE is close to a circle
02385       {
02386         // TODO
02387       }
02388       if ( isLine )
02389       {
02390         line = new Geom_Line( gp::OX() ); // only type does matter
02391       }
02392       else if ( isCirc )
02393       {
02394         gp_Pnt2d p = circle2d->Location();
02395         gp_Ax2 ax( gp_Pnt( p.X(), p.Y(), 0), gp::DX());
02396         circle = new Geom_Circle( ax, 1.); // only center position does matter
02397       }
02398     }
02399 
02400     Handle(Geom_Curve)& res = _edge2curve[ eIndex ];
02401     if ( isLine )
02402       res = line;
02403     else if ( isCirc )
02404       res = circle;
02405 
02406     return res;
02407   }
02408   return i2curve->second;
02409 }
02410 
02411 //================================================================================
02415 //================================================================================
02416 
02417 bool _ViscousBuilder::smoothAnalyticEdge( _SolidData&           data,
02418                                           const int             iFrom,
02419                                           const int             iTo,
02420                                           Handle(Geom_Surface)& surface,
02421                                           const TopoDS_Face&    F,
02422                                           SMESH_MesherHelper&   helper)
02423 {
02424   TopoDS_Shape S = helper.GetSubShapeByNode( data._edges[ iFrom ]->_nodes[0],
02425                                              helper.GetMeshDS());
02426   TopoDS_Edge E = TopoDS::Edge( S );
02427 
02428   Handle(Geom_Curve) curve = data.CurveForSmooth( E, iFrom, iTo, surface, F, helper );
02429   if ( curve.IsNull() ) return false;
02430 
02431   // compute a relative length of segments
02432   vector< double > len( iTo-iFrom+1 );
02433   {
02434     double curLen, prevLen = len[0] = 1.0;
02435     for ( int i = iFrom; i < iTo; ++i )
02436     {
02437       curLen = prevLen * data._edges[i]->_2neibors->_wgt[0] / data._edges[i]->_2neibors->_wgt[1];
02438       len[i-iFrom+1] = len[i-iFrom] + curLen;
02439       prevLen = curLen;
02440     }
02441   }
02442 
02443   if ( curve->IsKind( STANDARD_TYPE( Geom_Line )))
02444   {
02445     if ( F.IsNull() ) // 3D
02446     {
02447       SMESH_TNodeXYZ p0( data._edges[iFrom]->_2neibors->_nodes[0]);
02448       SMESH_TNodeXYZ p1( data._edges[iTo-1]->_2neibors->_nodes[1]);
02449       for ( int i = iFrom; i < iTo; ++i )
02450       {
02451         double r = len[i-iFrom] / len.back();
02452         gp_XYZ newPos = p0 * ( 1. - r ) + p1 * r;
02453         data._edges[i]->_pos.back() = newPos;
02454         SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( data._edges[i]->_nodes.back() );
02455         tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
02456         dumpMove( tgtNode );
02457       }
02458     }
02459     else
02460     {
02461       gp_XY uv0 = helper.GetNodeUV( F, data._edges[iFrom]->_2neibors->_nodes[0]);
02462       gp_XY uv1 = helper.GetNodeUV( F, data._edges[iTo-1]->_2neibors->_nodes[1]);
02463       if ( data._edges[iFrom]->_2neibors->_nodes[0] ==
02464            data._edges[iTo-1]->_2neibors->_nodes[1] ) // closed edge
02465       {
02466         int iPeriodic = helper.GetPeriodicIndex();
02467         if ( iPeriodic == 1 || iPeriodic == 2 )
02468         {
02469           uv1.SetCoord( iPeriodic, helper.GetOtherParam( uv1.Coord( iPeriodic )));
02470           if ( uv0.Coord( iPeriodic ) > uv1.Coord( iPeriodic ))
02471             std::swap( uv0, uv1 );
02472         }
02473       }
02474       const gp_XY rangeUV = uv1 - uv0;
02475       for ( int i = iFrom; i < iTo; ++i )
02476       {
02477         double r = len[i-iFrom] / len.back();
02478         gp_XY newUV = uv0 + r * rangeUV;
02479         data._edges[i]->_pos.back().SetCoord( newUV.X(), newUV.Y(), 0 );
02480 
02481         gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
02482         SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( data._edges[i]->_nodes.back() );
02483         tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
02484         dumpMove( tgtNode );
02485 
02486         SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
02487         pos->SetUParameter( newUV.X() );
02488         pos->SetVParameter( newUV.Y() );
02489       }
02490     }
02491     return true;
02492   }
02493 
02494   if ( curve->IsKind( STANDARD_TYPE( Geom_Circle )))
02495   {
02496     Handle(Geom_Circle) circle = Handle(Geom_Circle)::DownCast( curve );
02497     gp_Pnt center3D = circle->Location();
02498 
02499     if ( F.IsNull() ) // 3D
02500     {
02501       return false; // TODO ???
02502     }
02503     else // 2D
02504     {
02505       const gp_XY center( center3D.X(), center3D.Y() );
02506       
02507       gp_XY uv0 = helper.GetNodeUV( F, data._edges[iFrom]->_2neibors->_nodes[0]);
02508       gp_XY uvM = helper.GetNodeUV( F, data._edges[iFrom]->_nodes.back());
02509       gp_XY uv1 = helper.GetNodeUV( F, data._edges[iTo-1]->_2neibors->_nodes[1]);
02510       gp_Vec2d vec0( center, uv0 );
02511       gp_Vec2d vecM( center, uvM);
02512       gp_Vec2d vec1( center, uv1 );
02513       double uLast = vec0.Angle( vec1 ); // -PI - +PI
02514       double uMidl = vec0.Angle( vecM );
02515       if ( uLast < 0 ) uLast += 2.*M_PI; // 0.0 - 2*PI
02516       if ( uMidl < 0 ) uMidl += 2.*M_PI;
02517       const bool sense = ( uMidl < uLast );
02518       const double radius = 0.5 * ( vec0.Magnitude() + vec1.Magnitude() );
02519 
02520       gp_Ax2d axis( center, vec0 );
02521       gp_Circ2d circ ( axis, radius, sense );
02522       for ( int i = iFrom; i < iTo; ++i )
02523       {
02524         double    newU = uLast * len[i-iFrom] / len.back();
02525         gp_Pnt2d newUV = ElCLib::Value( newU, circ );
02526         data._edges[i]->_pos.back().SetCoord( newUV.X(), newUV.Y(), 0 );
02527 
02528         gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
02529         SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( data._edges[i]->_nodes.back() );
02530         tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
02531         dumpMove( tgtNode );
02532 
02533         SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
02534         pos->SetUParameter( newUV.X() );
02535         pos->SetVParameter( newUV.Y() );
02536       }
02537     }
02538     return true;
02539   }
02540 
02541   return false;
02542 }
02543 
02544 //================================================================================
02549 //================================================================================
02550 
02551 bool _ViscousBuilder::updateNormals( _SolidData&         data,
02552                                      SMESH_MesherHelper& helper )
02553 {
02554   // make temporary quadrangles got by extrusion of
02555   // mesh edges along _LayerEdge._normal's
02556 
02557   vector< const SMDS_MeshElement* > tmpFaces;
02558   {
02559     set< SMESH_TLink > extrudedLinks; // contains target nodes
02560     vector< const SMDS_MeshNode*> nodes(4); // of a tmp mesh face
02561 
02562     dumpFunction(SMESH_Comment("makeTmpFacesOnEdges")<<data._index);
02563     for ( unsigned i = 0; i < data._edges.size(); ++i )
02564     {
02565       _LayerEdge* edge = data._edges[i];
02566       if ( !edge->IsOnEdge() || !edge->_sWOL.IsNull() ) continue;
02567       const SMDS_MeshNode* tgt1 = edge->_nodes.back();
02568       for ( int j = 0; j < 2; ++j ) // loop on _2NearEdges
02569       {
02570         const SMDS_MeshNode* tgt2 = edge->_2neibors->_nodes[j];
02571         pair< set< SMESH_TLink >::iterator, bool > link_isnew =
02572           extrudedLinks.insert( SMESH_TLink( tgt1, tgt2 ));
02573         if ( !link_isnew.second )
02574         {
02575           extrudedLinks.erase( link_isnew.first );
02576           continue; // already extruded and will no more encounter
02577         }
02578         // look for a _LayerEdge containg tgt2
02579 //         _LayerEdge* neiborEdge = 0;
02580 //         unsigned di = 0; // check _edges[i+di] and _edges[i-di]
02581 //         while ( !neiborEdge && ++di <= data._edges.size() )
02582 //         {
02583 //           if ( i+di < data._edges.size() && data._edges[i+di]->_nodes.back() == tgt2 )
02584 //             neiborEdge = data._edges[i+di];
02585 //           else if ( di <= i && data._edges[i-di]->_nodes.back() == tgt2 )
02586 //             neiborEdge = data._edges[i-di];
02587 //         }
02588 //         if ( !neiborEdge )
02589 //           return error("updateNormals(): neighbor _LayerEdge not found", data._index);
02590         _LayerEdge* neiborEdge = edge->_2neibors->_edges[j];
02591 
02592         TmpMeshFaceOnEdge* f = new TmpMeshFaceOnEdge( edge, neiborEdge, --_tmpFaceID );
02593         tmpFaces.push_back( f );
02594 
02595         dumpCmd(SMESH_Comment("mesh.AddFace([ ")
02596                 <<f->_nn[0]->GetID()<<", "<<f->_nn[1]->GetID()<<", "
02597                 <<f->_nn[2]->GetID()<<", "<<f->_nn[3]->GetID()<<" ])");
02598       }
02599     }
02600     dumpFunctionEnd();
02601   }
02602   // Check if _LayerEdge's based on EDGE's intersects tmpFaces.
02603   // Perform two loops on _LayerEdge on EDGE's:
02604   // 1) to find and fix intersection
02605   // 2) to check that no new intersection appears as result of 1)
02606 
02607   SMESH_MeshEditor editor( _mesh );
02608   SMDS_ElemIteratorPtr fIt( new SMDS_ElementVectorIterator( tmpFaces.begin(),
02609                                                             tmpFaces.end()));
02610   auto_ptr<SMESH_ElementSearcher> searcher ( editor.GetElementSearcher( fIt ));
02611 
02612   // 1) Find intersections
02613   double dist;
02614   const SMDS_MeshElement* face;
02615   typedef map< _LayerEdge*, set< _LayerEdge*, _LayerEdgeCmp >, _LayerEdgeCmp > TLEdge2LEdgeSet;
02616   TLEdge2LEdgeSet edge2CloseEdge;
02617 
02618   const double eps = data._epsilon * data._epsilon;
02619   for ( unsigned i = 0; i < data._edges.size(); ++i )
02620   {
02621     _LayerEdge* edge = data._edges[i];
02622     if ( !edge->IsOnEdge() || !edge->_sWOL.IsNull() ) continue;
02623     if ( edge->FindIntersection( *searcher, dist, eps, &face ))
02624     {
02625       const TmpMeshFaceOnEdge* f = (const TmpMeshFaceOnEdge*) face;
02626       set< _LayerEdge*, _LayerEdgeCmp > & ee = edge2CloseEdge[ edge ];
02627       ee.insert( f->_le1 );
02628       ee.insert( f->_le2 );
02629       if ( f->_le1->IsOnEdge() && f->_le1->_sWOL.IsNull() ) 
02630         edge2CloseEdge[ f->_le1 ].insert( edge );
02631       if ( f->_le2->IsOnEdge() && f->_le2->_sWOL.IsNull() ) 
02632         edge2CloseEdge[ f->_le2 ].insert( edge );
02633     }
02634   }
02635 
02636   // Set _LayerEdge._normal
02637 
02638   if ( !edge2CloseEdge.empty() )
02639   {
02640     dumpFunction(SMESH_Comment("updateNormals")<<data._index);
02641 
02642     TLEdge2LEdgeSet::iterator e2ee = edge2CloseEdge.begin();
02643     for ( ; e2ee != edge2CloseEdge.end(); ++e2ee )
02644     {
02645       _LayerEdge* edge1       = e2ee->first;
02646       _LayerEdge* edge2       = 0;
02647       set< _LayerEdge*, _LayerEdgeCmp >& ee  = e2ee->second;
02648 
02649       // find EDGEs the edges reside
02650       TopoDS_Edge E1, E2;
02651       TopoDS_Shape S = helper.GetSubShapeByNode( edge1->_nodes[0], getMeshDS() );
02652       if ( S.ShapeType() != TopAbs_EDGE )
02653         continue; // TODO: find EDGE by VERTEX
02654       E1 = TopoDS::Edge( S );
02655       set< _LayerEdge*, _LayerEdgeCmp >::iterator eIt = ee.begin();
02656       while ( E2.IsNull() && eIt != ee.end())
02657       {
02658         _LayerEdge* e2 = *eIt++;
02659         TopoDS_Shape S = helper.GetSubShapeByNode( e2->_nodes[0], getMeshDS() );
02660         if ( S.ShapeType() == TopAbs_EDGE )
02661           E2 = TopoDS::Edge( S ), edge2 = e2;
02662       }
02663       if ( E2.IsNull() ) continue; // TODO: find EDGE by VERTEX
02664 
02665       // find 3 FACEs sharing 2 EDGEs
02666 
02667       TopoDS_Face FF1[2], FF2[2];
02668       PShapeIteratorPtr fIt = helper.GetAncestors(E1, *_mesh, TopAbs_FACE);
02669       while ( fIt->more() && FF1[1].IsNull())
02670       {
02671         const TopoDS_Face *F = (const TopoDS_Face*) fIt->next();
02672         if ( helper.IsSubShape( *F, data._solid))
02673           FF1[ FF1[0].IsNull() ? 0 : 1 ] = *F;
02674       }
02675       fIt = helper.GetAncestors(E2, *_mesh, TopAbs_FACE);
02676       while ( fIt->more() && FF2[1].IsNull())
02677       {
02678         const TopoDS_Face *F = (const TopoDS_Face*) fIt->next();
02679         if ( helper.IsSubShape( *F, data._solid))
02680           FF2[ FF2[0].IsNull() ? 0 : 1 ] = *F;
02681       }
02682       // exclude a FACE common to E1 and E2 (put it at [1] in FF* )
02683       if ( FF1[0].IsSame( FF2[0]) || FF1[0].IsSame( FF2[1]))
02684         std::swap( FF1[0], FF1[1] );
02685       if ( FF2[0].IsSame( FF1[0]) )
02686         std::swap( FF2[0], FF2[1] );
02687       if ( FF1[0].IsNull() || FF2[0].IsNull() )
02688         continue;
02689 
02690 //       // get a new normal for edge1
02691       bool ok;
02692       gp_Vec dir1 = edge1->_normal, dir2 = edge2->_normal;
02693       if ( edge1->_cosin < 0 )
02694         dir1 = getFaceDir( FF1[0], E1, edge1->_nodes[0], helper, ok ).Normalized();
02695       if ( edge2->_cosin < 0 )
02696         dir2 = getFaceDir( FF2[0], E2, edge2->_nodes[0], helper, ok ).Normalized();
02697       //      gp_Vec dir1 = getFaceDir( FF1[0], E1, edge1->_nodes[0], helper, ok );
02698 //       gp_Vec dir2 = getFaceDir( FF2[0], E2, edge2->_nodes[0], helper, ok2 );
02699 //       double wgt1 = ( edge1->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
02700 //       double wgt2 = ( edge2->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
02701 //       gp_Vec newNorm = wgt1 * dir1 + wgt2 * dir2;
02702 //       newNorm.Normalize();
02703 
02704       double wgt1 = ( edge1->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
02705       double wgt2 = ( edge2->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
02706       gp_Vec newNorm = wgt1 * dir1 + wgt2 * dir2;
02707       newNorm.Normalize();
02708 
02709       edge1->_normal = newNorm.XYZ();
02710 
02711       // update data of edge1 depending on _normal
02712       const SMDS_MeshNode *n1, *n2;
02713       n1 = edge1->_2neibors->_edges[0]->_nodes[0];
02714       n2 = edge1->_2neibors->_edges[1]->_nodes[0];
02715       //if ( !findNeiborsOnEdge( edge1, n1, n2, data ))
02716       //continue;
02717       edge1->SetDataByNeighbors( n1, n2, helper );
02718       gp_Vec dirInFace;
02719       if ( edge1->_cosin < 0 )
02720         dirInFace = dir1;
02721       else
02722         getFaceDir( FF1[0], E1, edge1->_nodes[0], helper, ok );
02723       double angle = dir1.Angle( edge1->_normal ); // [0,PI]
02724       edge1->SetCosin( cos( angle ));
02725 
02726       // limit data._stepSize
02727       if ( edge1->_cosin > 0.1 )
02728       {
02729         SMDS_ElemIteratorPtr fIt = edge1->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
02730         while ( fIt->more() )
02731           limitStepSize( data, fIt->next(), edge1->_cosin );
02732       }
02733       // set new XYZ of target node
02734       edge1->InvalidateStep( 1 );
02735       edge1->_len = 0;
02736       edge1->SetNewLength( data._stepSize, helper );
02737     }
02738 
02739     // Update normals and other dependent data of not intersecting _LayerEdge's
02740     // neighboring the intersecting ones
02741 
02742     for ( e2ee = edge2CloseEdge.begin(); e2ee != edge2CloseEdge.end(); ++e2ee )
02743     {
02744       _LayerEdge* edge1 = e2ee->first;
02745       if ( !edge1->_2neibors )
02746         continue;
02747       for ( int j = 0; j < 2; ++j ) // loop on 2 neighbors
02748       {
02749         _LayerEdge* neighbor = edge1->_2neibors->_edges[j];
02750         if ( edge2CloseEdge.count ( neighbor ))
02751           continue; // j-th neighbor is also intersected
02752         _LayerEdge* prevEdge = edge1;
02753         const int nbSteps = 6;
02754         for ( int step = nbSteps; step; --step ) // step from edge1 in j-th direction
02755         {
02756           if ( !neighbor->_2neibors )
02757             break; // neighbor is on VERTEX
02758           int iNext = 0;
02759           _LayerEdge* nextEdge = neighbor->_2neibors->_edges[iNext];
02760           if ( nextEdge == prevEdge )
02761             nextEdge = neighbor->_2neibors->_edges[ ++iNext ];
02762 //           const double&  wgtPrev = neighbor->_2neibors->_wgt[1-iNext];
02763 //           const double&  wgtNext = neighbor->_2neibors->_wgt[iNext];
02764           double r = double(step-1)/nbSteps;
02765           if ( !nextEdge->_2neibors )
02766             r = 0.5;
02767 
02768           gp_XYZ newNorm = prevEdge->_normal * r + nextEdge->_normal * (1-r);
02769           newNorm.Normalize();
02770 
02771           neighbor->_normal = newNorm;
02772           neighbor->SetCosin( prevEdge->_cosin * r + nextEdge->_cosin * (1-r) );
02773           neighbor->SetDataByNeighbors( prevEdge->_nodes[0], nextEdge->_nodes[0], helper );
02774 
02775           neighbor->InvalidateStep( 1 );
02776           neighbor->_len = 0;
02777           neighbor->SetNewLength( data._stepSize, helper );
02778 
02779           // goto the next neighbor
02780           prevEdge = neighbor;
02781           neighbor = nextEdge;
02782         }
02783       }
02784     }
02785     dumpFunctionEnd();
02786   }
02787   // 2) Check absence of intersections
02788   // TODO?
02789 
02790   for ( unsigned i = 0 ; i < tmpFaces.size(); ++i )
02791     delete tmpFaces[i];
02792 
02793   return true;
02794 }
02795 
02796 //================================================================================
02801 //================================================================================
02802 
02803 bool _LayerEdge::FindIntersection( SMESH_ElementSearcher&   searcher,
02804                                    double &                 distance,
02805                                    const double&            epsilon,
02806                                    const SMDS_MeshElement** face)
02807 {
02808   vector< const SMDS_MeshElement* > suspectFaces;
02809   double segLen;
02810   gp_Ax1 lastSegment = LastSegment(segLen);
02811   searcher.GetElementsNearLine( lastSegment, SMDSAbs_Face, suspectFaces );
02812 
02813   bool segmentIntersected = false;
02814   distance = Precision::Infinite();
02815   int iFace = -1; // intersected face
02816   for ( unsigned j = 0 ; j < suspectFaces.size() && !segmentIntersected; ++j )
02817   {
02818     const SMDS_MeshElement* face = suspectFaces[j];
02819     if ( face->GetNodeIndex( _nodes.back() ) >= 0 ||
02820          face->GetNodeIndex( _nodes[0]     ) >= 0 )
02821       continue; // face sharing _LayerEdge node
02822     const int nbNodes = face->NbCornerNodes();
02823     bool intFound = false;
02824     double dist;
02825     SMDS_MeshElement::iterator nIt = face->begin_nodes();
02826     if ( nbNodes == 3 )
02827     {
02828       intFound = SegTriaInter( lastSegment, *nIt++, *nIt++, *nIt++, dist, epsilon );
02829     }
02830     else
02831     {
02832       const SMDS_MeshNode* tria[3];
02833       tria[0] = *nIt++;
02834       tria[1] = *nIt++;;
02835       for ( int n2 = 2; n2 < nbNodes && !intFound; ++n2 )
02836       {
02837         tria[2] = *nIt++;
02838         intFound = SegTriaInter(lastSegment, tria[0], tria[1], tria[2], dist, epsilon );
02839         tria[1] = tria[2];
02840       }
02841     }
02842     if ( intFound )
02843     {
02844       if ( dist < segLen*(1.01))
02845         segmentIntersected = true;
02846       if ( distance > dist )
02847         distance = dist, iFace = j;
02848     }
02849   }
02850   if ( iFace != -1 && face ) *face = suspectFaces[iFace];
02851 //   if ( distance && iFace > -1 )
02852 //   {
02853 //     // distance is used to limit size of inflation step which depends on
02854 //     // whether the intersected face bears viscous layers or not
02855 //     bool faceHasVL = suspectFaces[iFace]->GetID() < 1;
02856 //     if ( faceHasVL )
02857 //       *distance /= 2;
02858 //   }
02859   if ( segmentIntersected )
02860   {
02861 #ifdef __myDEBUG
02862     SMDS_MeshElement::iterator nIt = suspectFaces[iFace]->begin_nodes();
02863     gp_XYZ intP( lastSegment.Location().XYZ() + lastSegment.Direction().XYZ() * distance );
02864     cout << "nodes: tgt " << _nodes.back()->GetID() << " src " << _nodes[0]->GetID()
02865          << ", intersection with face ("
02866          << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
02867          << ") at point (" << intP.X() << ", " << intP.Y() << ", " << intP.Z()
02868          << ") distance = " << distance - segLen<< endl;
02869 #endif
02870   }
02871 
02872   distance -= segLen;
02873 
02874   return segmentIntersected;
02875 }
02876 
02877 //================================================================================
02881 //================================================================================
02882 
02883 gp_Ax1 _LayerEdge::LastSegment(double& segLen) const
02884 {
02885   // find two non-coincident positions
02886   gp_XYZ orig = _pos.back();
02887   gp_XYZ dir;
02888   int iPrev = _pos.size() - 2;
02889   while ( iPrev >= 0 )
02890   {
02891     dir = orig - _pos[iPrev];
02892     if ( dir.SquareModulus() > 1e-100 )
02893       break;
02894     else
02895       iPrev--;
02896   }
02897 
02898   // make gp_Ax1
02899   gp_Ax1 segDir;
02900   if ( iPrev < 0 )
02901   {
02902     segDir.SetLocation( SMESH_TNodeXYZ( _nodes[0] ));
02903     segDir.SetDirection( _normal );
02904     segLen = 0;
02905   }
02906   else
02907   {
02908     gp_Pnt pPrev = _pos[ iPrev ];
02909     if ( !_sWOL.IsNull() )
02910     {
02911       TopLoc_Location loc;
02912       if ( _sWOL.ShapeType() == TopAbs_EDGE )
02913       {
02914         double f,l;
02915         Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( _sWOL ), loc, f,l);
02916         pPrev = curve->Value( pPrev.X() ).Transformed( loc );
02917       }
02918       else
02919       {
02920         Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face(_sWOL), loc );
02921         pPrev = surface->Value( pPrev.X(), pPrev.Y() ).Transformed( loc );
02922       }
02923       dir = SMESH_TNodeXYZ( _nodes.back() ) - pPrev.XYZ();
02924     }
02925     segDir.SetLocation( pPrev );
02926     segDir.SetDirection( dir );
02927     segLen = dir.Modulus();
02928   }
02929 
02930   return segDir;
02931 }
02932 
02933 //================================================================================
02939 //================================================================================
02940 
02941 bool _LayerEdge::SegTriaInter( const gp_Ax1&        lastSegment,
02942                                const SMDS_MeshNode* n0,
02943                                const SMDS_MeshNode* n1,
02944                                const SMDS_MeshNode* n2,
02945                                double&              t,
02946                                const double&        EPSILON) const
02947 {
02948   //const double EPSILON = 1e-6;
02949 
02950   gp_XYZ orig = lastSegment.Location().XYZ();
02951   gp_XYZ dir  = lastSegment.Direction().XYZ();
02952 
02953   SMESH_TNodeXYZ vert0( n0 );
02954   SMESH_TNodeXYZ vert1( n1 );
02955   SMESH_TNodeXYZ vert2( n2 );
02956 
02957   /* calculate distance from vert0 to ray origin */
02958   gp_XYZ tvec = orig - vert0;
02959 
02960   if ( tvec * dir > EPSILON )
02961     // intersected face is at back side of the temporary face this _LayerEdge belongs to
02962     return false;
02963 
02964   gp_XYZ edge1 = vert1 - vert0;
02965   gp_XYZ edge2 = vert2 - vert0;
02966 
02967   /* begin calculating determinant - also used to calculate U parameter */
02968   gp_XYZ pvec = dir ^ edge2;
02969 
02970   /* if determinant is near zero, ray lies in plane of triangle */
02971   double det = edge1 * pvec;
02972 
02973   if (det > -EPSILON && det < EPSILON)
02974     return 0;
02975   double inv_det = 1.0 / det;
02976 
02977   /* calculate U parameter and test bounds */
02978   double u = ( tvec * pvec ) * inv_det;
02979   if (u < 0.0 || u > 1.0)
02980     return 0;
02981 
02982   /* prepare to test V parameter */
02983   gp_XYZ qvec = tvec ^ edge1;
02984 
02985   /* calculate V parameter and test bounds */
02986   double v = (dir * qvec) * inv_det;
02987   if ( v < 0.0 || u + v > 1.0 )
02988     return 0;
02989 
02990   /* calculate t, ray intersects triangle */
02991   t = (edge2 * qvec) * inv_det;
02992 
02993   //   if (det < EPSILON)
02994   //     return false;
02995 
02996   //   /* calculate distance from vert0 to ray origin */
02997   //   gp_XYZ tvec = orig - vert0;
02998 
02999   //   /* calculate U parameter and test bounds */
03000   //   double u = tvec * pvec;
03001   //   if (u < 0.0 || u > det)
03002 //     return 0;
03003 
03004 //   /* prepare to test V parameter */
03005 //   gp_XYZ qvec = tvec ^ edge1;
03006 
03007 //   /* calculate V parameter and test bounds */
03008 //   double v = dir * qvec;
03009 //   if (v < 0.0 || u + v > det)
03010 //     return 0;
03011 
03012 //   /* calculate t, scale parameters, ray intersects triangle */
03013 //   double t = edge2 * qvec;
03014 //   double inv_det = 1.0 / det;
03015 //   t *= inv_det;
03016 //   //u *= inv_det;
03017 //   //v *= inv_det;
03018 
03019   return true;
03020 }
03021 
03022 //================================================================================
03027 //================================================================================
03028 
03029 bool _LayerEdge::SmoothOnEdge(Handle(Geom_Surface)& surface,
03030                               const TopoDS_Face&    F,
03031                               SMESH_MesherHelper&   helper)
03032 {
03033   ASSERT( IsOnEdge() );
03034 
03035   SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _nodes.back() );
03036   SMESH_TNodeXYZ oldPos( tgtNode );
03037   double dist01, distNewOld;
03038   
03039   SMESH_TNodeXYZ p0( _2neibors->_nodes[0]);
03040   SMESH_TNodeXYZ p1( _2neibors->_nodes[1]);
03041   dist01 = p0.Distance( _2neibors->_nodes[1] );
03042 
03043   gp_Pnt newPos = p0 * _2neibors->_wgt[0] + p1 * _2neibors->_wgt[1];
03044   double lenDelta = 0;
03045   if ( _curvature )
03046   {
03047     lenDelta = _curvature->lenDelta( _len );
03048     newPos.ChangeCoord() += _normal * lenDelta;
03049   }
03050 
03051   distNewOld = newPos.Distance( oldPos );
03052 
03053   if ( F.IsNull() )
03054   {
03055     if ( _2neibors->_plnNorm )
03056     {
03057       // put newPos on the plane defined by source node and _plnNorm
03058       gp_XYZ new2src = SMESH_TNodeXYZ( _nodes[0] ) - newPos.XYZ();
03059       double new2srcProj = (*_2neibors->_plnNorm) * new2src;
03060       newPos.ChangeCoord() += (*_2neibors->_plnNorm) * new2srcProj;
03061     }
03062     tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
03063     _pos.back() = newPos.XYZ();
03064   }
03065   else
03066   {
03067     tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
03068     gp_XY uv( Precision::Infinite(), 0 );
03069     helper.CheckNodeUV( F, tgtNode, uv, 1e-10, /*force=*/true );
03070     _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
03071 
03072     newPos = surface->Value( uv.X(), uv.Y() );
03073     tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
03074   }
03075 
03076   if ( _curvature && lenDelta < 0 )
03077   {
03078     gp_Pnt prevPos( _pos[ _pos.size()-2 ]);
03079     _len -= prevPos.Distance( oldPos );
03080     _len += prevPos.Distance( newPos );
03081   }
03082   bool moved = distNewOld > dist01/50;
03083   //if ( moved )
03084   dumpMove( tgtNode ); // debug
03085 
03086   return moved;
03087 }
03088 
03089 //================================================================================
03094 //================================================================================
03095 
03096 bool _LayerEdge::Smooth(int& badNb)
03097 {
03098   if ( _simplices.size() < 2 )
03099     return false; // _LayerEdge inflated along EDGE or FACE
03100 
03101   // compute new position for the last _pos
03102   gp_XYZ newPos (0,0,0);
03103   for ( unsigned i = 0; i < _simplices.size(); ++i )
03104     newPos += SMESH_TNodeXYZ( _simplices[i]._nPrev );
03105   newPos /= _simplices.size();
03106 
03107   if ( _curvature )
03108     newPos += _normal * _curvature->lenDelta( _len );
03109 
03110   gp_Pnt prevPos( _pos[ _pos.size()-2 ]);
03111 //   if ( _cosin < -0.1)
03112 //   {
03113 //     // Avoid decreasing length of edge on concave surface
03114 //     //gp_Vec oldMove( _pos[ _pos.size()-2 ], _pos.back() );
03115 //     gp_Vec newMove( prevPos, newPos );
03116 //     newPos = _pos.back() + newMove.XYZ();
03117 //   }
03118 //   else if ( _cosin > 0.3 )
03119 //   {
03120 //     // Avoid increasing length of edge too much
03121 
03122 //   }
03123   // count quality metrics (orientation) of tetras around _tgtNode
03124   int nbOkBefore = 0;
03125   SMESH_TNodeXYZ tgtXYZ( _nodes.back() );
03126   for ( unsigned i = 0; i < _simplices.size(); ++i )
03127     nbOkBefore += _simplices[i].IsForward( _nodes[0], &tgtXYZ );
03128 
03129   int nbOkAfter = 0;
03130   for ( unsigned i = 0; i < _simplices.size(); ++i )
03131     nbOkAfter += _simplices[i].IsForward( _nodes[0], &newPos );
03132 
03133   if ( nbOkAfter < nbOkBefore )
03134     return false;
03135 
03136   SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
03137 
03138   _len -= prevPos.Distance(SMESH_TNodeXYZ( n ));
03139   _len += prevPos.Distance(newPos);
03140 
03141   n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
03142   _pos.back() = newPos;
03143 
03144   badNb += _simplices.size() - nbOkAfter;
03145 
03146   dumpMove( n );
03147 
03148   return true;
03149 }
03150 
03151 //================================================================================
03155 //================================================================================
03156 
03157 void _LayerEdge::SetNewLength( double len, SMESH_MesherHelper& helper )
03158 {
03159   if ( _len - len > -1e-6 )
03160   {
03161     _pos.push_back( _pos.back() );
03162     return;
03163   }
03164 
03165   SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
03166   SMESH_TNodeXYZ oldXYZ( n );
03167   gp_XYZ nXYZ = oldXYZ + _normal * ( len - _len ) * _lenFactor;
03168   n->setXYZ( nXYZ.X(), nXYZ.Y(), nXYZ.Z() );
03169 
03170   _pos.push_back( nXYZ );
03171   _len = len;
03172   if ( !_sWOL.IsNull() )
03173   {
03174     double distXYZ[4];
03175     if ( _sWOL.ShapeType() == TopAbs_EDGE )
03176     {
03177       double u = Precision::Infinite(); // to force projection w/o distance check
03178       helper.CheckNodeU( TopoDS::Edge( _sWOL ), n, u, 1e-10, /*force=*/true, distXYZ );
03179       _pos.back().SetCoord( u, 0, 0 );
03180       SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( n->GetPosition() );
03181       pos->SetUParameter( u );
03182     }
03183     else //  TopAbs_FACE
03184     {
03185       gp_XY uv( Precision::Infinite(), 0 );
03186       helper.CheckNodeUV( TopoDS::Face( _sWOL ), n, uv, 1e-10, /*force=*/true, distXYZ );
03187       _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
03188       SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( n->GetPosition() );
03189       pos->SetUParameter( uv.X() );
03190       pos->SetVParameter( uv.Y() );
03191     }
03192     n->setXYZ( distXYZ[1], distXYZ[2], distXYZ[3]);
03193   }
03194   dumpMove( n ); //debug
03195 }
03196 
03197 //================================================================================
03201 //================================================================================
03202 
03203 void _LayerEdge::InvalidateStep( int curStep )
03204 {
03205   if ( _pos.size() > curStep )
03206   {
03207     _pos.resize( curStep );
03208     gp_Pnt nXYZ = _pos.back();
03209     SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
03210     if ( !_sWOL.IsNull() )
03211     {
03212       TopLoc_Location loc;
03213       if ( _sWOL.ShapeType() == TopAbs_EDGE )
03214       {
03215         SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( n->GetPosition() );
03216         pos->SetUParameter( nXYZ.X() );
03217         double f,l;
03218         Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( _sWOL ), loc, f,l);
03219         nXYZ = curve->Value( nXYZ.X() ).Transformed( loc );
03220       }
03221       else
03222       {
03223         SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( n->GetPosition() );
03224         pos->SetUParameter( nXYZ.X() );
03225         pos->SetVParameter( nXYZ.Y() );
03226         Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face(_sWOL), loc );
03227         nXYZ = surface->Value( nXYZ.X(), nXYZ.Y() ).Transformed( loc );
03228       }
03229     }
03230     n->setXYZ( nXYZ.X(), nXYZ.Y(), nXYZ.Z() );
03231     dumpMove( n );
03232   }
03233 }
03234 
03235 //================================================================================
03239 //================================================================================
03240 
03241 bool _ViscousBuilder::refine(_SolidData& data)
03242 {
03243   SMESH_MesherHelper helper( *_mesh );
03244   helper.SetSubShape( data._solid );
03245   helper.SetElementsOnShape(false);
03246 
03247   Handle(Geom_Curve) curve;
03248   Handle(Geom_Surface) surface;
03249   TopoDS_Edge geomEdge;
03250   TopoDS_Face geomFace;
03251   TopLoc_Location loc;
03252   double f,l, u/*, distXYZ[4]*/;
03253   gp_XY uv;
03254   bool isOnEdge;
03255 
03256   for ( unsigned i = 0; i < data._edges.size(); ++i )
03257   {
03258     _LayerEdge& edge = *data._edges[i];
03259 
03260     // get accumulated length of segments
03261     vector< double > segLen( edge._pos.size() );
03262     segLen[0] = 0.0;
03263     for ( unsigned j = 1; j < edge._pos.size(); ++j )
03264       segLen[j] = segLen[j-1] + (edge._pos[j-1] - edge._pos[j] ).Modulus();
03265 
03266     // allocate memory for new nodes if it is not yet refined
03267     const SMDS_MeshNode* tgtNode = edge._nodes.back();
03268     if ( edge._nodes.size() == 2 )
03269     {
03270       edge._nodes.resize( data._hyp->GetNumberLayers() + 1, 0 );
03271       edge._nodes[1] = 0;
03272       edge._nodes.back() = tgtNode;
03273     }
03274     if ( !edge._sWOL.IsNull() )
03275     {
03276       isOnEdge = ( edge._sWOL.ShapeType() == TopAbs_EDGE );
03277       // restore position of the last node
03278 //       gp_Pnt p;
03279       if ( isOnEdge )
03280       {
03281         geomEdge = TopoDS::Edge( edge._sWOL );
03282         curve = BRep_Tool::Curve( geomEdge, loc, f,l);
03283 //         double u = helper.GetNodeU( tgtNode );
03284 //         p = curve->Value( u );
03285       }
03286       else
03287       {
03288         geomFace = TopoDS::Face( edge._sWOL );
03289         surface = BRep_Tool::Surface( geomFace, loc );
03290 //         gp_XY uv = helper.GetNodeUV( tgtNode );
03291 //         p = surface->Value( uv.X(), uv.Y() );
03292       }
03293 //       p.Transform( loc );
03294 //       const_cast< SMDS_MeshNode* >( tgtNode )->setXYZ( p.X(), p.Y(), p.Z() );
03295     }
03296     // calculate height of the first layer
03297     double h0;
03298     const double T = segLen.back(); //data._hyp.GetTotalThickness();
03299     const double f = data._hyp->GetStretchFactor();
03300     const int    N = data._hyp->GetNumberLayers();
03301     const double fPowN = pow( f, N );
03302     if ( fPowN - 1 <= numeric_limits<double>::min() )
03303       h0 = T / N;
03304     else
03305       h0 = T * ( f - 1 )/( fPowN - 1 );
03306 
03307     const double zeroLen = std::numeric_limits<double>::min();
03308 
03309     // create intermediate nodes
03310     double hSum = 0, hi = h0/f;
03311     unsigned iSeg = 1;
03312     for ( unsigned iStep = 1; iStep < edge._nodes.size(); ++iStep )
03313     {
03314       // compute an intermediate position
03315       hi *= f;
03316       hSum += hi;
03317       while ( hSum > segLen[iSeg] && iSeg < segLen.size()-1)
03318         ++iSeg;
03319       int iPrevSeg = iSeg-1;
03320       while ( fabs( segLen[iPrevSeg] - segLen[iSeg]) <= zeroLen && iPrevSeg > 0 )
03321         --iPrevSeg;
03322       double r = ( segLen[iSeg] - hSum ) / ( segLen[iSeg] - segLen[iPrevSeg] );
03323       gp_Pnt pos = r * edge._pos[iPrevSeg] + (1-r) * edge._pos[iSeg];
03324 
03325       SMDS_MeshNode*& node = const_cast< SMDS_MeshNode*& >(edge._nodes[ iStep ]);
03326       if ( !edge._sWOL.IsNull() )
03327       {
03328         // compute XYZ by parameters <pos>
03329         if ( isOnEdge )
03330         {
03331           u = pos.X();
03332           pos = curve->Value( u ).Transformed(loc);
03333         }
03334         else
03335         {
03336           uv.SetCoord( pos.X(), pos.Y() );
03337           pos = surface->Value( pos.X(), pos.Y() ).Transformed(loc);
03338         }
03339       }
03340       // create or update the node
03341       if ( !node )
03342       {
03343         node = helper.AddNode( pos.X(), pos.Y(), pos.Z());
03344         if ( !edge._sWOL.IsNull() )
03345         {
03346           if ( isOnEdge )
03347             getMeshDS()->SetNodeOnEdge( node, geomEdge, u );
03348           else
03349             getMeshDS()->SetNodeOnFace( node, geomFace, uv.X(), uv.Y() );
03350         }
03351         else
03352         {
03353           getMeshDS()->SetNodeInVolume( node, helper.GetSubShapeID() );
03354         }
03355       }
03356       else
03357       {
03358         if ( !edge._sWOL.IsNull() )
03359         {
03360           // make average pos from new and current parameters
03361           if ( isOnEdge )
03362           {
03363             u = 0.5 * ( u + helper.GetNodeU( geomEdge, node ));
03364             pos = curve->Value( u ).Transformed(loc);
03365           }
03366           else
03367           {
03368             uv = 0.5 * ( uv + helper.GetNodeUV( geomFace, node ));
03369             pos = surface->Value( uv.X(), uv.Y()).Transformed(loc);
03370           }
03371         }
03372         node->setXYZ( pos.X(), pos.Y(), pos.Z() );
03373       }
03374     }
03375   }
03376 
03377   // TODO: make quadratic prisms and polyhedrons(?)
03378 
03379   helper.SetElementsOnShape(true);
03380 
03381   TopExp_Explorer exp( data._solid, TopAbs_FACE );
03382   for ( ; exp.More(); exp.Next() )
03383   {
03384     if ( _ignoreShapeIds.count( getMeshDS()->ShapeToIndex( exp.Current() )))
03385       continue;
03386     SMESHDS_SubMesh* fSubM = getMeshDS()->MeshElements( exp.Current() );
03387     SMDS_ElemIteratorPtr fIt = fSubM->GetElements();
03388     vector< vector<const SMDS_MeshNode*>* > nnVec;
03389     while ( fIt->more() )
03390     {
03391       const SMDS_MeshElement* face = fIt->next();
03392       int nbNodes = face->NbCornerNodes();
03393       nnVec.resize( nbNodes );
03394       SMDS_ElemIteratorPtr nIt = face->nodesIterator();
03395       for ( int iN = 0; iN < nbNodes; ++iN )
03396       {
03397         const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
03398         nnVec[ iN ] = & data._n2eMap[ n ]->_nodes;
03399       }
03400 
03401       int nbZ = nnVec[0]->size();
03402       switch ( nbNodes )
03403       {
03404       case 3:
03405         for ( int iZ = 1; iZ < nbZ; ++iZ )
03406           helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1], (*nnVec[2])[iZ-1],
03407                             (*nnVec[0])[iZ],   (*nnVec[1])[iZ],   (*nnVec[2])[iZ]);
03408         break;
03409       case 4:
03410         for ( int iZ = 1; iZ < nbZ; ++iZ )
03411           helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1],
03412                             (*nnVec[2])[iZ-1], (*nnVec[3])[iZ-1],
03413                             (*nnVec[0])[iZ],   (*nnVec[1])[iZ],
03414                             (*nnVec[2])[iZ],   (*nnVec[3])[iZ]);
03415         break;
03416       default:
03417         return error("Not supported type of element", data._index);
03418       }
03419     }
03420   }
03421   return true;
03422 }
03423 
03424 //================================================================================
03428 //================================================================================
03429 
03430 bool _ViscousBuilder::shrink()
03431 {
03432   // make map of (ids of FACEs to shrink mesh on) to (_SolidData containing _LayerEdge's
03433   // inflated along FACE or EDGE)
03434   map< TGeomID, _SolidData* > f2sdMap;
03435   for ( unsigned i = 0 ; i < _sdVec.size(); ++i )
03436   {
03437     _SolidData& data = _sdVec[i];
03438     TopTools_MapOfShape FFMap;
03439     map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
03440     for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
03441       if ( s2s->second.ShapeType() == TopAbs_FACE )
03442       {
03443         f2sdMap.insert( make_pair( getMeshDS()->ShapeToIndex( s2s->second ), &data ));
03444 
03445         if ( FFMap.Add( (*s2s).second ))
03446           // Put mesh faces on the shrinked FACE to the proxy sub-mesh to avoid
03447           // usage of mesh faces made in addBoundaryElements() by the 3D algo or
03448           // by StdMeshers_QuadToTriaAdaptor
03449           if ( SMESHDS_SubMesh* smDS = getMeshDS()->MeshElements( s2s->second ))
03450           {
03451             SMESH_ProxyMesh::SubMesh* proxySub =
03452               data._proxyMesh->getFaceSubM( TopoDS::Face( s2s->second ), /*create=*/true);
03453             SMDS_ElemIteratorPtr fIt = smDS->GetElements();
03454             while ( fIt->more() )
03455               proxySub->AddElement( fIt->next() );
03456             // as a result 3D algo will use elements from proxySub and not from smDS
03457           }
03458       }
03459   }
03460 
03461   SMESH_MesherHelper helper( *_mesh );
03462 
03463   // EDGE's to shrink
03464   map< int, _Shrinker1D > e2shrMap;
03465 
03466   // loop on FACES to srink mesh on
03467   map< TGeomID, _SolidData* >::iterator f2sd = f2sdMap.begin();
03468   for ( ; f2sd != f2sdMap.end(); ++f2sd )
03469   {
03470     _SolidData&     data = *f2sd->second;
03471     TNode2Edge&   n2eMap = data._n2eMap;
03472     const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( f2sd->first ));
03473 
03474     Handle(Geom_Surface) surface = BRep_Tool::Surface(F);
03475 
03476     SMESH_subMesh*     sm = _mesh->GetSubMesh( F );
03477     SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
03478 
03479     helper.SetSubShape(F);
03480 
03481     // ===========================
03482     // Prepare data for shrinking
03483     // ===========================
03484 
03485     // Collect nodes to smooth, as src nodes are not yet replaced by tgt ones
03486     // and thus all nodes on a FACE connected to 2d elements are to be smoothed
03487     vector < const SMDS_MeshNode* > smoothNodes;
03488     {
03489       SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
03490       while ( nIt->more() )
03491       {
03492         const SMDS_MeshNode* n = nIt->next();
03493         if ( n->NbInverseElements( SMDSAbs_Face ) > 0 )
03494           smoothNodes.push_back( n );
03495       }
03496     }
03497     // Find out face orientation
03498     double refSign = 1;
03499     const set<TGeomID> ignoreShapes;
03500     bool isOkUV;
03501     if ( !smoothNodes.empty() )
03502     {
03503       vector<_Simplex> simplices;
03504       getSimplices( smoothNodes[0], simplices, ignoreShapes );
03505       helper.GetNodeUV( F, simplices[0]._nPrev, 0, &isOkUV ); // fix UV of silpmex nodes
03506       helper.GetNodeUV( F, simplices[0]._nNext, 0, &isOkUV );
03507       gp_XY uv = helper.GetNodeUV( F, smoothNodes[0], 0, &isOkUV );
03508       if ( !simplices[0].IsForward(uv, smoothNodes[0], F, helper,refSign) )
03509         refSign = -1;
03510     }
03511 
03512     // Find _LayerEdge's inflated along F
03513     vector< _LayerEdge* > lEdges;
03514     {
03515       SMESH_subMeshIteratorPtr subIt =
03516         sm->getDependsOnIterator(/*includeSelf=*/false, /*complexShapeFirst=*/false);
03517       while ( subIt->more() )
03518       {
03519         SMESH_subMesh* sub = subIt->next();
03520         SMESHDS_SubMesh* subDS = sub->GetSubMeshDS();
03521         if ( subDS->NbNodes() == 0 || !n2eMap.count( subDS->GetNodes()->next() ))
03522           continue;
03523         SMDS_NodeIteratorPtr nIt = subDS->GetNodes();
03524         while ( nIt->more() )
03525         {
03526           _LayerEdge* edge = n2eMap[ nIt->next() ];
03527           lEdges.push_back( edge );
03528           prepareEdgeToShrink( *edge, F, helper, smDS );
03529         }
03530       }
03531     }
03532 
03533     // Replace source nodes by target nodes in mesh faces to shrink
03534     const SMDS_MeshNode* nodes[20];
03535     for ( unsigned i = 0; i < lEdges.size(); ++i )
03536     {
03537       _LayerEdge& edge = *lEdges[i];
03538       const SMDS_MeshNode* srcNode = edge._nodes[0];
03539       const SMDS_MeshNode* tgtNode = edge._nodes.back();
03540       SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
03541       while ( fIt->more() )
03542       {
03543         const SMDS_MeshElement* f = fIt->next();
03544         if ( !smDS->Contains( f ))
03545           continue;
03546         SMDS_ElemIteratorPtr nIt = f->nodesIterator();
03547         for ( int iN = 0; iN < f->NbNodes(); ++iN )
03548         {
03549           const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
03550           nodes[iN] = ( n == srcNode ? tgtNode : n );
03551         }
03552         helper.GetMeshDS()->ChangeElementNodes( f, nodes, f->NbNodes() );
03553       }
03554     }
03555 
03556     // find out if a FACE is concave
03557     const bool isConcaveFace = isConcave( F, helper );
03558 
03559     // Create _SmoothNode's on face F
03560     vector< _SmoothNode > nodesToSmooth( smoothNodes.size() );
03561     {
03562       dumpFunction(SMESH_Comment("beforeShrinkFace")<<f2sd->first); // debug
03563       for ( unsigned i = 0; i < smoothNodes.size(); ++i )
03564       {
03565         const SMDS_MeshNode* n = smoothNodes[i];
03566         nodesToSmooth[ i ]._node = n;
03567         // src nodes must be replaced by tgt nodes to have tgt nodes in _simplices
03568         getSimplices( n, nodesToSmooth[ i ]._simplices, ignoreShapes, NULL, isConcaveFace );
03569         // fix up incorrect uv of nodes on the FACE
03570         helper.GetNodeUV( F, n, 0, &isOkUV);
03571         dumpMove( n );
03572       }
03573       dumpFunctionEnd();
03574     }
03575     //if ( nodesToSmooth.empty() ) continue;
03576 
03577     // Find EDGE's to shrink
03578     set< _Shrinker1D* > eShri1D;
03579     {
03580       for ( unsigned i = 0; i < lEdges.size(); ++i )
03581       {
03582         _LayerEdge* edge = lEdges[i];
03583         if ( edge->_sWOL.ShapeType() == TopAbs_EDGE )
03584         {
03585           TGeomID edgeIndex = getMeshDS()->ShapeToIndex( edge->_sWOL );
03586           _Shrinker1D& srinker = e2shrMap[ edgeIndex ];
03587           eShri1D.insert( & srinker );
03588           srinker.AddEdge( edge, helper );
03589           // restore params of nodes on EGDE if the EDGE has been already
03590           // srinked while srinking another FACE
03591           srinker.RestoreParams();
03592         }
03593       }
03594     }
03595 
03596     // ==================
03597     // Perform shrinking
03598     // ==================
03599 
03600     bool shrinked = true;
03601     int badNb, shriStep=0, smooStep=0;
03602     while ( shrinked )
03603     {
03604       // Move boundary nodes (actually just set new UV)
03605       // -----------------------------------------------
03606       dumpFunction(SMESH_Comment("moveBoundaryOnF")<<f2sd->first<<"_st"<<shriStep++ ); // debug
03607       shrinked = false;
03608       for ( unsigned i = 0; i < lEdges.size(); ++i )
03609       {
03610         shrinked |= lEdges[i]->SetNewLength2d( surface,F,helper );
03611       }
03612       dumpFunctionEnd();
03613 
03614       // Move nodes on EDGE's
03615       set< _Shrinker1D* >::iterator shr = eShri1D.begin();
03616       for ( ; shr != eShri1D.end(); ++shr )
03617         (*shr)->Compute( /*set3D=*/false, helper );
03618 
03619       // Smoothing in 2D
03620       // -----------------
03621       int nbNoImpSteps = 0;
03622       bool moved = true;
03623       badNb = 1;
03624       while (( nbNoImpSteps < 5 && badNb > 0) && moved)
03625       {
03626         dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
03627 
03628         int oldBadNb = badNb;
03629         badNb = 0;
03630         moved = false;
03631         for ( unsigned i = 0; i < nodesToSmooth.size(); ++i )
03632         {
03633           moved |= nodesToSmooth[i].Smooth( badNb,surface,helper,refSign,
03634                                             /*isCentroidal=*/isConcaveFace,/*set3D=*/false );
03635         }
03636         if ( badNb < oldBadNb )
03637           nbNoImpSteps = 0;
03638         else
03639           nbNoImpSteps++;
03640 
03641         dumpFunctionEnd();
03642       }
03643       if ( badNb > 0 )
03644         return error(SMESH_Comment("Can't shrink 2D mesh on face ") << f2sd->first );
03645     }
03646     // No wrongly shaped faces remain; final smooth. Set node XYZ.
03647     // First, find out a needed quality of smoothing (high for quadrangles only)
03648     bool highQuality;
03649     {
03650       const bool hasTria = _mesh->NbTriangles(), hasQuad = _mesh->NbQuadrangles();
03651       if ( hasTria != hasQuad )
03652       {
03653         highQuality = hasQuad;
03654       }
03655       else
03656       {
03657         set<int> nbNodesSet;
03658         SMDS_ElemIteratorPtr fIt = smDS->GetElements();
03659         while ( fIt->more() && nbNodesSet.size() < 2 )
03660           nbNodesSet.insert( fIt->next()->NbCornerNodes() );
03661         highQuality = ( *nbNodesSet.begin() == 4 );
03662       }
03663     }
03664     if ( !highQuality && isConcaveFace )
03665       fixBadFaces( F, helper ); // fix narrow faces by swaping diagonals
03666     for ( int st = highQuality ? 10 : 3; st; --st )
03667     {
03668       dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
03669       for ( unsigned i = 0; i < nodesToSmooth.size(); ++i )
03670         nodesToSmooth[i].Smooth( badNb,surface,helper,refSign,
03671                                  /*isCentroidal=*/isConcaveFace,/*set3D=*/st==1 );
03672       dumpFunctionEnd();
03673     }
03674     // Set an event listener to clear FACE sub-mesh together with SOLID sub-mesh
03675     _SrinkShapeListener::ToClearSubMeshWithSolid( sm, data._solid );
03676 
03677   } // loop on FACES to srink mesh on
03678 
03679 
03680   // Replace source nodes by target nodes in shrinked mesh edges
03681 
03682   map< int, _Shrinker1D >::iterator e2shr = e2shrMap.begin();
03683   for ( ; e2shr != e2shrMap.end(); ++e2shr )
03684     e2shr->second.SwapSrcTgtNodes( getMeshDS() );
03685 
03686   return true;
03687 }
03688 
03689 //================================================================================
03693 //================================================================================
03694 
03695 bool _ViscousBuilder::prepareEdgeToShrink( _LayerEdge&            edge,
03696                                            const TopoDS_Face&     F,
03697                                            SMESH_MesherHelper&    helper,
03698                                            const SMESHDS_SubMesh* faceSubMesh)
03699 {
03700   const SMDS_MeshNode* srcNode = edge._nodes[0];
03701   const SMDS_MeshNode* tgtNode = edge._nodes.back();
03702 
03703   edge._pos.clear();
03704 
03705   if ( edge._sWOL.ShapeType() == TopAbs_FACE )
03706   {
03707     gp_XY srcUV = helper.GetNodeUV( F, srcNode );
03708     gp_XY tgtUV = helper.GetNodeUV( F, tgtNode );
03709     gp_Vec2d uvDir( srcUV, tgtUV );
03710     double uvLen = uvDir.Magnitude();
03711     uvDir /= uvLen;
03712     edge._normal.SetCoord( uvDir.X(),uvDir.Y(), 0);
03713 
03714     // IMPORTANT to have src nodes NOT yet REPLACED by tgt nodes in shrinked faces
03715     vector<const SMDS_MeshElement*> faces;
03716     multimap< double, const SMDS_MeshNode* > proj2node;
03717     SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
03718     while ( fIt->more() )
03719     {
03720       const SMDS_MeshElement* f = fIt->next();
03721       if ( faceSubMesh->Contains( f ))
03722         faces.push_back( f );
03723     }
03724     for ( unsigned i = 0; i < faces.size(); ++i )
03725     {
03726       const int nbNodes = faces[i]->NbCornerNodes();
03727       for ( int j = 0; j < nbNodes; ++j )
03728       {
03729         const SMDS_MeshNode* n = faces[i]->GetNode(j);
03730         if ( n == srcNode ) continue;
03731         if ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE &&
03732              ( faces.size() > 1 || nbNodes > 3 ))
03733           continue;
03734         gp_Pnt2d uv = helper.GetNodeUV( F, n );
03735         gp_Vec2d uvDirN( srcUV, uv );
03736         double proj = uvDirN * uvDir;
03737         proj2node.insert( make_pair( proj, n ));
03738       }
03739     }
03740 
03741     multimap< double, const SMDS_MeshNode* >::iterator p2n = proj2node.begin(), p2nEnd;
03742     const double minProj = p2n->first;
03743     const double projThreshold = 1.1 * uvLen;
03744     if ( minProj > projThreshold )
03745     {
03746       // tgtNode is located so that it does not make faces with wrong orientation
03747       return true;
03748     }
03749     edge._pos.resize(1);
03750     edge._pos[0].SetCoord( tgtUV.X(), tgtUV.Y(), 0 );
03751 
03752     // store most risky nodes in _simplices
03753     p2nEnd = proj2node.lower_bound( projThreshold );
03754     int nbSimpl = ( std::distance( p2n, p2nEnd ) + 1) / 2;
03755     edge._simplices.resize( nbSimpl );
03756     for ( int i = 0; i < nbSimpl; ++i )
03757     {
03758       edge._simplices[i]._nPrev = p2n->second;
03759       if ( ++p2n != p2nEnd )
03760         edge._simplices[i]._nNext = p2n->second;
03761     }
03762     // set UV of source node to target node
03763     SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
03764     pos->SetUParameter( srcUV.X() );
03765     pos->SetVParameter( srcUV.Y() );
03766   }
03767   else // _sWOL is TopAbs_EDGE
03768   {
03769     TopoDS_Edge E = TopoDS::Edge( edge._sWOL);
03770     SMESHDS_SubMesh* edgeSM = getMeshDS()->MeshElements( E );
03771     if ( !edgeSM || edgeSM->NbElements() == 0 )
03772       return error(SMESH_Comment("Not meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
03773 
03774     const SMDS_MeshNode* n2 = 0;
03775     SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
03776     while ( eIt->more() && !n2 )
03777     {
03778       const SMDS_MeshElement* e = eIt->next();
03779       if ( !edgeSM->Contains(e)) continue;
03780       n2 = e->GetNode( 0 );
03781       if ( n2 == srcNode ) n2 = e->GetNode( 1 );
03782     }
03783     if ( !n2 )
03784       return error(SMESH_Comment("Wrongly meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
03785 
03786     double uSrc = helper.GetNodeU( E, srcNode, n2 );
03787     double uTgt = helper.GetNodeU( E, tgtNode, srcNode );
03788     double u2   = helper.GetNodeU( E, n2,      srcNode );
03789 
03790     if ( fabs( uSrc-uTgt ) < 0.99 * fabs( uSrc-u2 ))
03791     {
03792       // tgtNode is located so that it does not make faces with wrong orientation
03793       return true;
03794     }
03795     edge._pos.resize(1);
03796     edge._pos[0].SetCoord( U_TGT, uTgt );
03797     edge._pos[0].SetCoord( U_SRC, uSrc );
03798     edge._pos[0].SetCoord( LEN_TGT, fabs( uSrc-uTgt ));
03799 
03800     edge._simplices.resize( 1 );
03801     edge._simplices[0]._nPrev = n2;
03802 
03803     // set UV of source node to target node
03804     SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
03805     pos->SetUParameter( uSrc );
03806   }
03807   return true;
03808 
03809   //================================================================================
03813   //================================================================================
03814   
03815   // Compute UV to follow during shrinking
03816 
03817 //   const SMDS_MeshNode* srcNode = edge._nodes[0];
03818 //   const SMDS_MeshNode* tgtNode = edge._nodes.back();
03819 
03820 //   gp_XY srcUV = helper.GetNodeUV( F, srcNode );
03821 //   gp_XY tgtUV = helper.GetNodeUV( F, tgtNode );
03822 //   gp_Vec2d uvDir( srcUV, tgtUV );
03823 //   double uvLen = uvDir.Magnitude();
03824 //   uvDir /= uvLen;
03825 
03826 //   // Select shrinking step such that not to make faces with wrong orientation.
03827 //   // IMPORTANT to have src nodes NOT yet REPLACED by tgt nodes in shrinked faces
03828 //   const double minStepSize = uvLen / 20;
03829 //   double stepSize = uvLen;
03830 //   SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
03831 //   while ( fIt->more() )
03832 //   {
03833 //     const SMDS_MeshElement* f = fIt->next();
03834 //     if ( !faceSubMesh->Contains( f )) continue;
03835 //     const int nbNodes = f->NbCornerNodes();
03836 //     for ( int i = 0; i < nbNodes; ++i )
03837 //     {
03838 //       const SMDS_MeshNode* n = f->GetNode(i);
03839 //       if ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE || n == srcNode)
03840 //         continue;
03841 //       gp_XY uv = helper.GetNodeUV( F, n );
03842 //       gp_Vec2d uvDirN( srcUV, uv );
03843 //       double proj = uvDirN * uvDir;
03844 //       if ( proj < stepSize && proj > minStepSize )
03845 //         stepSize = proj;
03846 //     }
03847 //   }
03848 //   stepSize *= 0.8;
03849 
03850 //   const int nbSteps = ceil( uvLen / stepSize );
03851 //   gp_XYZ srcUV0( srcUV.X(), srcUV.Y(), 0 );
03852 //   gp_XYZ tgtUV0( tgtUV.X(), tgtUV.Y(), 0 );
03853 //   edge._pos.resize( nbSteps );
03854 //   edge._pos[0] = tgtUV0;
03855 //   for ( int i = 1; i < nbSteps; ++i )
03856 //   {
03857 //     double r = i / double( nbSteps );
03858 //     edge._pos[i] = (1-r) * tgtUV0 + r * srcUV0;
03859 //   }
03860 //   return true;
03861 }
03862 
03863 //================================================================================
03867 //================================================================================
03868 
03869 void _ViscousBuilder::fixBadFaces(const TopoDS_Face& F, SMESH_MesherHelper& helper)
03870 {
03871   SMESH::Controls::AspectRatio qualifier;
03872   SMESH::Controls::TSequenceOfXYZ points(3), points1(3), points2(3);
03873   const double maxAspectRatio = 4.;
03874 
03875   // find bad triangles
03876 
03877   vector< const SMDS_MeshElement* > badTrias;
03878   vector< double >                  badAspects;
03879   SMESHDS_SubMesh* sm = helper.GetMeshDS()->MeshElements( F );
03880   SMDS_ElemIteratorPtr fIt = sm->GetElements();
03881   while ( fIt->more() )
03882   {
03883     const SMDS_MeshElement * f = fIt->next();
03884     if ( f->NbCornerNodes() != 3 ) continue;
03885     for ( int iP = 0; iP < 3; ++iP ) points(iP+1) = SMESH_TNodeXYZ( f->GetNode(iP));
03886     double aspect = qualifier.GetValue( points );
03887     if ( aspect > maxAspectRatio )
03888     {
03889       badTrias.push_back( f );
03890       badAspects.push_back( aspect );
03891     }
03892   }
03893   if ( badTrias.empty() )
03894     return;
03895 
03896   // find couples of faces to swap diagonal
03897 
03898   typedef pair < const SMDS_MeshElement* , const SMDS_MeshElement* > T2Trias;
03899   vector< T2Trias > triaCouples; 
03900 
03901   TIDSortedElemSet involvedFaces, emptySet;
03902   for ( size_t iTia = 0; iTia < badTrias.size(); ++iTia )
03903   {
03904     T2Trias trias    [3];
03905     double  aspRatio [3];
03906     int i1, i2, i3;
03907 
03908     involvedFaces.insert( badTrias[iTia] );
03909     for ( int iP = 0; iP < 3; ++iP )
03910       points(iP+1) = SMESH_TNodeXYZ( badTrias[iTia]->GetNode(iP));
03911 
03912     // find triangles adjacent to badTrias[iTia] with better aspect ratio after diag-swaping
03913     int bestCouple = -1;
03914     for ( int iSide = 0; iSide < 3; ++iSide )
03915     {
03916       const SMDS_MeshNode* n1 = badTrias[iTia]->GetNode( iSide );
03917       const SMDS_MeshNode* n2 = badTrias[iTia]->GetNode(( iSide+1 ) % 3 );
03918       trias [iSide].first  = badTrias[iTia];
03919       trias [iSide].second = SMESH_MeshEditor::FindFaceInSet( n1, n2, emptySet, involvedFaces,
03920                                                               & i1, & i2 );
03921       if ( ! trias[iSide].second || trias[iSide].second->NbCornerNodes() != 3 )
03922         continue;
03923 
03924       // aspect ratio of an adjacent tria
03925       for ( int iP = 0; iP < 3; ++iP )
03926         points2(iP+1) = SMESH_TNodeXYZ( trias[iSide].second->GetNode(iP));
03927       double aspectInit = qualifier.GetValue( points2 );
03928 
03929       // arrange nodes as after diag-swaping
03930       if ( helper.WrapIndex( i1+1, 3 ) == i2 )
03931         i3 = helper.WrapIndex( i1-1, 3 );
03932       else
03933         i3 = helper.WrapIndex( i1+1, 3 );
03934       points1 = points;
03935       points1( 1+ iSide ) = points2( 1+ i3 );
03936       points2( 1+ i2    ) = points1( 1+ ( iSide+2 ) % 3 );
03937 
03938       // aspect ratio after diag-swaping
03939       aspRatio[ iSide ] = qualifier.GetValue( points1 ) + qualifier.GetValue( points2 );
03940       if ( aspRatio[ iSide ] > aspectInit + badAspects[ iTia ] )
03941         continue;
03942 
03943       if ( bestCouple < 0 || aspRatio[ bestCouple ] > aspRatio[ iSide ] )
03944         bestCouple = iSide;
03945     }
03946 
03947     if ( bestCouple >= 0 )
03948     {
03949       triaCouples.push_back( trias[bestCouple] );
03950       involvedFaces.insert ( trias[bestCouple].second );
03951     }
03952     else
03953     {
03954       involvedFaces.erase( badTrias[iTia] );
03955     }
03956   }
03957   if ( triaCouples.empty() )
03958     return;
03959 
03960   // swap diagonals
03961 
03962   SMESH_MeshEditor editor( helper.GetMesh() );
03963   dumpFunction(SMESH_Comment("beforeSwapDiagonals_F")<<helper.GetSubShapeID());
03964   for ( size_t i = 0; i < triaCouples.size(); ++i )
03965   {
03966     dumpChangeNodes( triaCouples[i].first );
03967     dumpChangeNodes( triaCouples[i].second );
03968     editor.InverseDiag( triaCouples[i].first, triaCouples[i].second );
03969   }
03970   dumpFunctionEnd();
03971 
03972   // just for debug dump resulting triangles
03973   dumpFunction(SMESH_Comment("swapDiagonals_F")<<helper.GetSubShapeID());
03974   for ( size_t i = 0; i < triaCouples.size(); ++i )
03975   {
03976     dumpChangeNodes( triaCouples[i].first );
03977     dumpChangeNodes( triaCouples[i].second );
03978   }
03979 }
03980 
03981 //================================================================================
03985 //================================================================================
03986 
03987 bool _LayerEdge::SetNewLength2d( Handle(Geom_Surface)& surface,
03988                                  const TopoDS_Face&    F,
03989                                  SMESH_MesherHelper&   helper )
03990 {
03991   if ( _pos.empty() )
03992     return false; // already at the target position
03993 
03994   SMDS_MeshNode* tgtNode = const_cast< SMDS_MeshNode*& >( _nodes.back() );
03995 
03996   if ( _sWOL.ShapeType() == TopAbs_FACE )
03997   {
03998     gp_XY    curUV = helper.GetNodeUV( F, tgtNode );
03999     gp_Pnt2d tgtUV( _pos[0].X(), _pos[0].Y());
04000     gp_Vec2d uvDir( _normal.X(), _normal.Y() );
04001     const double uvLen = tgtUV.Distance( curUV );
04002 
04003     // Select shrinking step such that not to make faces with wrong orientation.
04004     const double kSafe = 0.8;
04005     const double minStepSize = uvLen / 10;
04006     double stepSize = uvLen;
04007     for ( unsigned i = 0; i < _simplices.size(); ++i )
04008     {
04009       const SMDS_MeshNode* nn[2] = { _simplices[i]._nPrev, _simplices[i]._nNext };
04010       for ( int j = 0; j < 2; ++j )
04011         if ( const SMDS_MeshNode* n = nn[j] )
04012         {
04013           gp_XY uv = helper.GetNodeUV( F, n );
04014           gp_Vec2d uvDirN( curUV, uv );
04015           double proj = uvDirN * uvDir * kSafe;
04016           if ( proj < stepSize && proj > minStepSize )
04017             stepSize = proj;
04018         }
04019     }
04020 
04021     gp_Pnt2d newUV;
04022     if ( stepSize == uvLen )
04023     {
04024       newUV = tgtUV;
04025       _pos.clear();
04026     }
04027     else
04028     {
04029       newUV = curUV + uvDir.XY() * stepSize;
04030     }
04031 
04032     SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
04033     pos->SetUParameter( newUV.X() );
04034     pos->SetVParameter( newUV.Y() );
04035 
04036 #ifdef __myDEBUG
04037     gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
04038     tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
04039     dumpMove( tgtNode );
04040 #endif
04041   }
04042   else // _sWOL is TopAbs_EDGE
04043   {
04044     TopoDS_Edge E = TopoDS::Edge( _sWOL );
04045     const SMDS_MeshNode* n2 = _simplices[0]._nPrev;
04046 
04047     const double u2 = helper.GetNodeU( E, n2, tgtNode );
04048     const double uSrc   = _pos[0].Coord( U_SRC );
04049     const double lenTgt = _pos[0].Coord( LEN_TGT );
04050 
04051     double newU = _pos[0].Coord( U_TGT );
04052     if ( lenTgt < 0.99 * fabs( uSrc-u2 ))
04053     {
04054       _pos.clear();
04055     }
04056     else
04057     {
04058       newU = 0.1 * uSrc + 0.9 * u2;
04059     }
04060     SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
04061     pos->SetUParameter( newU );
04062 #ifdef __myDEBUG
04063     gp_XY newUV = helper.GetNodeUV( F, tgtNode, _nodes[0]);
04064     gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
04065     tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
04066     dumpMove( tgtNode );
04067 #endif
04068   }
04069   return true;
04070 }
04071 
04072 //================================================================================
04077 //================================================================================
04078 
04079 bool _SmoothNode::Smooth(int&                  badNb,
04080                          Handle(Geom_Surface)& surface,
04081                          SMESH_MesherHelper&   helper,
04082                          const double          refSign,
04083                          bool                  isCentroidal,
04084                          bool                  set3D)
04085 {
04086   const TopoDS_Face& face = TopoDS::Face( helper.GetSubShape() );
04087 
04088   // get uv of surrounding nodes
04089   vector<gp_XY> uv( _simplices.size() );
04090   for ( size_t i = 0; i < _simplices.size(); ++i )
04091     uv[i] = helper.GetNodeUV( face, _simplices[i]._nPrev, _node );
04092 
04093   // compute new UV for the node
04094   gp_XY newPos (0,0);
04095   if ( isCentroidal && _simplices.size() > 3 )
04096   {
04097     // average centers of diagonals wieghted with their reciprocal lengths
04098     if ( _simplices.size() == 4 )
04099     {
04100       double w1 = 1. / ( uv[2]-uv[0] ).SquareModulus();
04101       double w2 = 1. / ( uv[3]-uv[1] ).SquareModulus();
04102       newPos = ( w1 * ( uv[2]+uv[0] ) + w2 * ( uv[3]+uv[1] )) / ( w1+w2 ) / 2;
04103     }
04104     else
04105     {
04106       double sumWeight = 0;
04107       int nb = _simplices.size() == 4 ? 2 : _simplices.size();
04108       for ( int i = 0; i < nb; ++i )
04109       {
04110         int iFrom = i + 2;
04111         int iTo   = i + _simplices.size() - 1;
04112         for ( int j = iFrom; j < iTo; ++j )
04113         {
04114           int i2 = SMESH_MesherHelper::WrapIndex( j, _simplices.size() );
04115           double w = 1. / ( uv[i]-uv[i2] ).SquareModulus();
04116           sumWeight += w;
04117           newPos += w * ( uv[i]+uv[i2] );
04118         }
04119       }
04120       newPos /= 2 * sumWeight;
04121     }
04122   }
04123   else
04124   {
04125     // Laplacian smooth
04126     isCentroidal = false;
04127     for ( size_t i = 0; i < _simplices.size(); ++i )
04128       newPos += uv[i];
04129     newPos /= _simplices.size();
04130   }
04131 
04132   // count quality metrics (orientation) of triangles around the node
04133   int nbOkBefore = 0;
04134   gp_XY tgtUV = helper.GetNodeUV( face, _node );
04135   for ( unsigned i = 0; i < _simplices.size(); ++i )
04136     nbOkBefore += _simplices[i].IsForward( tgtUV, _node, face, helper, refSign );
04137 
04138   int nbOkAfter = 0;
04139   for ( unsigned i = 0; i < _simplices.size(); ++i )
04140     nbOkAfter += _simplices[i].IsForward( newPos, _node, face, helper, refSign );
04141 
04142   if ( nbOkAfter < nbOkBefore )
04143   {
04144     // if ( isCentroidal )
04145     //   return Smooth( badNb, surface, helper, refSign, !isCentroidal, set3D );
04146     badNb += _simplices.size() - nbOkBefore;
04147     return false;
04148   }
04149 
04150   SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( _node->GetPosition() );
04151   pos->SetUParameter( newPos.X() );
04152   pos->SetVParameter( newPos.Y() );
04153 
04154 #ifdef __myDEBUG
04155   set3D = true;
04156 #endif
04157   if ( set3D )
04158   {
04159     gp_Pnt p = surface->Value( newPos.X(), newPos.Y() );
04160     const_cast< SMDS_MeshNode* >( _node )->setXYZ( p.X(), p.Y(), p.Z() );
04161     dumpMove( _node );
04162   }
04163 
04164   badNb += _simplices.size() - nbOkAfter;
04165   return ( (tgtUV-newPos).SquareModulus() > 1e-10 );
04166 }
04167 
04168 //================================================================================
04172 //================================================================================
04173 
04174 _SolidData::~_SolidData()
04175 {
04176   for ( unsigned i = 0; i < _edges.size(); ++i )
04177   {
04178     if ( _edges[i] && _edges[i]->_2neibors )
04179       delete _edges[i]->_2neibors;
04180     delete _edges[i];
04181   }
04182   _edges.clear();
04183 }
04184 //================================================================================
04188 //================================================================================
04189 
04190 void _Shrinker1D::AddEdge( const _LayerEdge* e, SMESH_MesherHelper& helper )
04191 {
04192   // init
04193   if ( _nodes.empty() )
04194   {
04195     _edges[0] = _edges[1] = 0;
04196     _done = false;
04197   }
04198   // check _LayerEdge
04199   if ( e == _edges[0] || e == _edges[1] )
04200     return;
04201   if ( e->_sWOL.IsNull() || e->_sWOL.ShapeType() != TopAbs_EDGE )
04202     throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
04203   if ( _edges[0] && _edges[0]->_sWOL != e->_sWOL )
04204     throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
04205 
04206   // store _LayerEdge
04207   const TopoDS_Edge& E = TopoDS::Edge( e->_sWOL );
04208   double f,l;
04209   BRep_Tool::Range( E, f,l );
04210   double u = helper.GetNodeU( E, e->_nodes[0], e->_nodes.back());
04211   _edges[ u < 0.5*(f+l) ? 0 : 1 ] = e;
04212 
04213   // Update _nodes
04214 
04215   const SMDS_MeshNode* tgtNode0 = _edges[0] ? _edges[0]->_nodes.back() : 0;
04216   const SMDS_MeshNode* tgtNode1 = _edges[1] ? _edges[1]->_nodes.back() : 0;
04217 
04218   if ( _nodes.empty() )
04219   {
04220     SMESHDS_SubMesh * eSubMesh = helper.GetMeshDS()->MeshElements( E );
04221     if ( !eSubMesh || eSubMesh->NbNodes() < 1 )
04222       return;
04223     TopLoc_Location loc;
04224     Handle(Geom_Curve) C = BRep_Tool::Curve(E, loc, f,l);
04225     GeomAdaptor_Curve aCurve(C, f,l);
04226     const double totLen = GCPnts_AbscissaPoint::Length(aCurve, f, l);
04227 
04228     int nbExpectNodes = eSubMesh->NbNodes() - e->_nodes.size();
04229     _initU  .reserve( nbExpectNodes );
04230     _normPar.reserve( nbExpectNodes );
04231     _nodes  .reserve( nbExpectNodes );
04232     SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
04233     while ( nIt->more() )
04234     {
04235       const SMDS_MeshNode* node = nIt->next();
04236       if ( node->NbInverseElements(SMDSAbs_Edge) == 0 ||
04237            node == tgtNode0 || node == tgtNode1 )
04238         continue; // refinement nodes
04239       _nodes.push_back( node );
04240       _initU.push_back( helper.GetNodeU( E, node ));
04241       double len = GCPnts_AbscissaPoint::Length(aCurve, f, _initU.back());
04242       _normPar.push_back(  len / totLen );
04243     }
04244   }
04245   else
04246   {
04247     // remove target node of the _LayerEdge from _nodes
04248     int nbFound = 0;
04249     for ( unsigned i = 0; i < _nodes.size(); ++i )
04250       if ( !_nodes[i] || _nodes[i] == tgtNode0 || _nodes[i] == tgtNode1 )
04251         _nodes[i] = 0, nbFound++;
04252     if ( nbFound == _nodes.size() )
04253       _nodes.clear();
04254   }
04255 }
04256 
04257 //================================================================================
04261 //================================================================================
04262 
04263 void _Shrinker1D::Compute(bool set3D, SMESH_MesherHelper& helper)
04264 {
04265   if ( _done || _nodes.empty())
04266     return;
04267   const _LayerEdge* e = _edges[0];
04268   if ( !e ) e = _edges[1];
04269   if ( !e ) return;
04270 
04271   _done =  (( !_edges[0] || _edges[0]->_pos.empty() ) &&
04272             ( !_edges[1] || _edges[1]->_pos.empty() ));
04273 
04274   const TopoDS_Edge& E = TopoDS::Edge( e->_sWOL );
04275   double f,l;
04276   if ( set3D || _done )
04277   {
04278     Handle(Geom_Curve) C = BRep_Tool::Curve(E, f,l);
04279     GeomAdaptor_Curve aCurve(C, f,l);
04280 
04281     if ( _edges[0] )
04282       f = helper.GetNodeU( E, _edges[0]->_nodes.back(), _nodes[0] );
04283     if ( _edges[1] )
04284       l = helper.GetNodeU( E, _edges[1]->_nodes.back(), _nodes.back() );
04285     double totLen = GCPnts_AbscissaPoint::Length( aCurve, f, l );
04286 
04287     for ( unsigned i = 0; i < _nodes.size(); ++i )
04288     {
04289       if ( !_nodes[i] ) continue;
04290       double len = totLen * _normPar[i];
04291       GCPnts_AbscissaPoint discret( aCurve, len, f );
04292       if ( !discret.IsDone() )
04293         return throw SALOME_Exception(LOCALIZED("GCPnts_AbscissaPoint failed"));
04294       double u = discret.Parameter();
04295       SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
04296       pos->SetUParameter( u );
04297       gp_Pnt p = C->Value( u );
04298       const_cast< SMDS_MeshNode*>( _nodes[i] )->setXYZ( p.X(), p.Y(), p.Z() );
04299     }
04300   }
04301   else
04302   {
04303     BRep_Tool::Range( E, f,l );
04304     if ( _edges[0] )
04305       f = helper.GetNodeU( E, _edges[0]->_nodes.back(), _nodes[0] );
04306     if ( _edges[1] )
04307       l = helper.GetNodeU( E, _edges[1]->_nodes.back(), _nodes.back() );
04308     
04309     for ( unsigned i = 0; i < _nodes.size(); ++i )
04310     {
04311       if ( !_nodes[i] ) continue;
04312       double u = f * ( 1-_normPar[i] ) + l * _normPar[i];
04313       SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
04314       pos->SetUParameter( u );
04315     }
04316   }
04317 }
04318 
04319 //================================================================================
04323 //================================================================================
04324 
04325 void _Shrinker1D::RestoreParams()
04326 {
04327   if ( _done )
04328     for ( unsigned i = 0; i < _nodes.size(); ++i )
04329     {
04330       if ( !_nodes[i] ) continue;
04331       SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
04332       pos->SetUParameter( _initU[i] );
04333     }
04334   _done = false;
04335 }
04336 
04337 //================================================================================
04341 //================================================================================
04342 
04343 void _Shrinker1D::SwapSrcTgtNodes( SMESHDS_Mesh* mesh )
04344 {
04345   const SMDS_MeshNode* nodes[3];
04346   for ( int i = 0; i < 2; ++i )
04347   {
04348     if ( !_edges[i] ) continue;
04349 
04350     SMESHDS_SubMesh * eSubMesh = mesh->MeshElements( _edges[i]->_sWOL );
04351     if ( !eSubMesh ) return;
04352     const SMDS_MeshNode* srcNode = _edges[i]->_nodes[0];
04353     const SMDS_MeshNode* tgtNode = _edges[i]->_nodes.back();
04354     SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
04355     while ( eIt->more() )
04356     {
04357       const SMDS_MeshElement* e = eIt->next();
04358       if ( !eSubMesh->Contains( e ))
04359           continue;
04360       SMDS_ElemIteratorPtr nIt = e->nodesIterator();
04361       for ( int iN = 0; iN < e->NbNodes(); ++iN )
04362       {
04363         const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
04364         nodes[iN] = ( n == srcNode ? tgtNode : n );
04365       }
04366       mesh->ChangeElementNodes( e, nodes, e->NbNodes() );
04367     }
04368   }
04369 }
04370 
04371 //================================================================================
04375 //================================================================================
04376 
04377 bool _ViscousBuilder::addBoundaryElements()
04378 {
04379   SMESH_MesherHelper helper( *_mesh );
04380 
04381   for ( unsigned i = 0; i < _sdVec.size(); ++i )
04382   {
04383     _SolidData& data = _sdVec[i];
04384     TopTools_IndexedMapOfShape geomEdges;
04385     TopExp::MapShapes( data._solid, TopAbs_EDGE, geomEdges );
04386     for ( int iE = 1; iE <= geomEdges.Extent(); ++iE )
04387     {
04388       const TopoDS_Edge& E = TopoDS::Edge( geomEdges(iE));
04389 
04390       // Get _LayerEdge's based on E
04391 
04392       map< double, const SMDS_MeshNode* > u2nodes;
04393       if ( !SMESH_Algo::GetSortedNodesOnEdge( getMeshDS(), E, /*ignoreMedium=*/false, u2nodes))
04394         continue;
04395 
04396       vector< _LayerEdge* > ledges; ledges.reserve( u2nodes.size() );
04397       TNode2Edge & n2eMap = data._n2eMap;
04398       map< double, const SMDS_MeshNode* >::iterator u2n = u2nodes.begin();
04399       {
04400         //check if 2D elements are needed on E
04401         TNode2Edge::iterator n2e = n2eMap.find( u2n->second );
04402         if ( n2e == n2eMap.end() ) continue; // no layers on vertex
04403         ledges.push_back( n2e->second );
04404         u2n++;
04405         if (( n2e = n2eMap.find( u2n->second )) == n2eMap.end() )
04406           continue; // no layers on E
04407         ledges.push_back( n2eMap[ u2n->second ]);
04408 
04409         const SMDS_MeshNode* tgtN0 = ledges[0]->_nodes.back();
04410         const SMDS_MeshNode* tgtN1 = ledges[1]->_nodes.back();
04411         int nbSharedPyram = 0;
04412         SMDS_ElemIteratorPtr vIt = tgtN0->GetInverseElementIterator(SMDSAbs_Volume);
04413         while ( vIt->more() )
04414         {
04415           const SMDS_MeshElement* v = vIt->next();
04416           nbSharedPyram += int( v->GetNodeIndex( tgtN1 ) >= 0 );
04417         }
04418         if ( nbSharedPyram > 1 )
04419           continue; // not free border of the pyramid
04420 
04421         if ( getMeshDS()->FindFace( ledges[0]->_nodes[0], ledges[0]->_nodes[1],
04422                                     ledges[1]->_nodes[0], ledges[1]->_nodes[1]))
04423           continue; // faces already created
04424       }
04425       for ( ++u2n; u2n != u2nodes.end(); ++u2n )
04426         ledges.push_back( n2eMap[ u2n->second ]);
04427 
04428       // Find out orientation and type of face to create
04429 
04430       bool reverse = false, isOnFace;
04431       
04432       map< TGeomID, TopoDS_Shape >::iterator e2f =
04433         data._shrinkShape2Shape.find( getMeshDS()->ShapeToIndex( E ));
04434       TopoDS_Shape F;
04435       if (( isOnFace = ( e2f != data._shrinkShape2Shape.end() )))
04436       {
04437         F = e2f->second.Oriented( TopAbs_FORWARD );
04438         reverse = ( helper.GetSubShapeOri( F, E ) == TopAbs_REVERSED );
04439         if ( helper.GetSubShapeOri( data._solid, F ) == TopAbs_REVERSED )
04440           reverse = !reverse;
04441       }
04442       else
04443       {
04444         // find FACE with layers sharing E
04445         PShapeIteratorPtr fIt = helper.GetAncestors( E, *_mesh, TopAbs_FACE );
04446         while ( fIt->more() && F.IsNull() )
04447         {
04448           const TopoDS_Shape* pF = fIt->next();
04449           if ( helper.IsSubShape( *pF, data._solid) &&
04450                !_ignoreShapeIds.count( e2f->first ))
04451             F = *pF;
04452         }
04453       }
04454       // Find the sub-mesh to add new faces
04455       SMESHDS_SubMesh* sm = 0;
04456       if ( isOnFace )
04457         sm = getMeshDS()->MeshElements( F );
04458       else
04459         sm = data._proxyMesh->getFaceSubM( TopoDS::Face(F), /*create=*/true );
04460       if ( !sm )
04461         return error("error in addBoundaryElements()", data._index);
04462 
04463       // Make faces
04464       const int dj1 = reverse ? 0 : 1;
04465       const int dj2 = reverse ? 1 : 0;
04466       for ( unsigned j = 1; j < ledges.size(); ++j )
04467       {
04468         vector< const SMDS_MeshNode*>&  nn1 = ledges[j-dj1]->_nodes;
04469         vector< const SMDS_MeshNode*>&  nn2 = ledges[j-dj2]->_nodes;
04470         if ( isOnFace )
04471           for ( unsigned z = 1; z < nn1.size(); ++z )
04472             sm->AddElement( getMeshDS()->AddFace( nn1[z-1], nn2[z-1], nn2[z], nn1[z] ));
04473         else
04474           for ( unsigned z = 1; z < nn1.size(); ++z )
04475             sm->AddElement( new SMDS_FaceOfNodes( nn1[z-1], nn2[z-1], nn2[z], nn1[z]));
04476       }
04477     }
04478   }
04479 
04480   return true;
04481 }