1 // Copyright (C) 2007-2014 CEA/DEN, EDF R&D, OPEN CASCADE
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 // Lesser General Public License for more details.
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
20 // File : StdMeshers_ViscousLayers.cxx
21 // Created : Wed Dec 1 15:15:34 2010
22 // Author : Edward AGAPOV (eap)
24 #include "StdMeshers_ViscousLayers.hxx"
26 #include "SMDS_EdgePosition.hxx"
27 #include "SMDS_FaceOfNodes.hxx"
28 #include "SMDS_FacePosition.hxx"
29 #include "SMDS_MeshNode.hxx"
30 #include "SMDS_SetIterator.hxx"
31 #include "SMESHDS_Group.hxx"
32 #include "SMESHDS_Hypothesis.hxx"
33 #include "SMESH_Algo.hxx"
34 #include "SMESH_ComputeError.hxx"
35 #include "SMESH_ControlsDef.hxx"
36 #include "SMESH_Gen.hxx"
37 #include "SMESH_Group.hxx"
38 #include "SMESH_HypoFilter.hxx"
39 #include "SMESH_Mesh.hxx"
40 #include "SMESH_MeshAlgos.hxx"
41 #include "SMESH_MesherHelper.hxx"
42 #include "SMESH_ProxyMesh.hxx"
43 #include "SMESH_subMesh.hxx"
44 #include "SMESH_subMeshEventListener.hxx"
45 #include "StdMeshers_FaceSide.hxx"
47 #include <Adaptor3d_HSurface.hxx>
48 #include <BRepAdaptor_Curve2d.hxx>
49 #include <BRepAdaptor_Surface.hxx>
50 #include <BRepLProp_SLProps.hxx>
51 #include <BRep_Tool.hxx>
52 #include <Bnd_B2d.hxx>
53 #include <Bnd_B3d.hxx>
55 #include <GCPnts_AbscissaPoint.hxx>
56 #include <Geom2d_Circle.hxx>
57 #include <Geom2d_Line.hxx>
58 #include <Geom2d_TrimmedCurve.hxx>
59 #include <GeomAdaptor_Curve.hxx>
60 #include <GeomLib.hxx>
61 #include <Geom_Circle.hxx>
62 #include <Geom_Curve.hxx>
63 #include <Geom_Line.hxx>
64 #include <Geom_TrimmedCurve.hxx>
65 #include <Precision.hxx>
66 #include <Standard_ErrorHandler.hxx>
67 #include <Standard_Failure.hxx>
68 #include <TColStd_Array1OfReal.hxx>
70 #include <TopExp_Explorer.hxx>
71 #include <TopTools_IndexedMapOfShape.hxx>
72 #include <TopTools_ListOfShape.hxx>
73 #include <TopTools_MapOfShape.hxx>
75 #include <TopoDS_Edge.hxx>
76 #include <TopoDS_Face.hxx>
77 #include <TopoDS_Vertex.hxx>
79 #include <gp_Cone.hxx>
80 #include <gp_Sphere.hxx>
91 //#define __NOT_INVALIDATE_BAD_SMOOTH
96 //================================================================================
101 enum UIndex { U_TGT = 1, U_SRC, LEN_TGT };
103 const double theMinSmoothCosin = 0.1;
104 const double theSmoothThickToElemSizeRatio = 0.3;
106 // what part of thickness is allowed till intersection
107 // (defined by SALOME_TESTS/Grids/smesh/viscous_layers_00/A5)
108 const double theThickToIntersection = 1.5;
110 bool needSmoothing( double cosin, double tgtThick, double elemSize )
112 return cosin * tgtThick > theSmoothThickToElemSizeRatio * elemSize;
116 * \brief SMESH_ProxyMesh computed by _ViscousBuilder for a SOLID.
117 * It is stored in a SMESH_subMesh of the SOLID as SMESH_subMeshEventListenerData
119 struct _MeshOfSolid : public SMESH_ProxyMesh,
120 public SMESH_subMeshEventListenerData
122 bool _n2nMapComputed;
123 SMESH_ComputeErrorPtr _warning;
125 _MeshOfSolid( SMESH_Mesh* mesh)
126 :SMESH_subMeshEventListenerData( /*isDeletable=*/true),_n2nMapComputed(false)
128 SMESH_ProxyMesh::setMesh( *mesh );
131 // returns submesh for a geom face
132 SMESH_ProxyMesh::SubMesh* getFaceSubM(const TopoDS_Face& F, bool create=false)
134 TGeomID i = SMESH_ProxyMesh::shapeIndex(F);
135 return create ? SMESH_ProxyMesh::getProxySubMesh(i) : findProxySubMesh(i);
137 void setNode2Node(const SMDS_MeshNode* srcNode,
138 const SMDS_MeshNode* proxyNode,
139 const SMESH_ProxyMesh::SubMesh* subMesh)
141 SMESH_ProxyMesh::setNode2Node( srcNode,proxyNode,subMesh);
144 //--------------------------------------------------------------------------------
146 * \brief Listener of events of 3D sub-meshes computed with viscous layers.
147 * It is used to clear an inferior dim sub-meshes modified by viscous layers
149 class _ShrinkShapeListener : SMESH_subMeshEventListener
151 _ShrinkShapeListener()
152 : SMESH_subMeshEventListener(/*isDeletable=*/false,
153 "StdMeshers_ViscousLayers::_ShrinkShapeListener") {}
155 static SMESH_subMeshEventListener* Get() { static _ShrinkShapeListener l; return &l; }
156 virtual void ProcessEvent(const int event,
158 SMESH_subMesh* solidSM,
159 SMESH_subMeshEventListenerData* data,
160 const SMESH_Hypothesis* hyp)
162 if ( SMESH_subMesh::COMPUTE_EVENT == eventType && solidSM->IsEmpty() && data )
164 SMESH_subMeshEventListener::ProcessEvent(event,eventType,solidSM,data,hyp);
168 //--------------------------------------------------------------------------------
170 * \brief Listener of events of 3D sub-meshes computed with viscous layers.
171 * It is used to store data computed by _ViscousBuilder for a sub-mesh and to
172 * delete the data as soon as it has been used
174 class _ViscousListener : SMESH_subMeshEventListener
177 SMESH_subMeshEventListener(/*isDeletable=*/false,
178 "StdMeshers_ViscousLayers::_ViscousListener") {}
179 static SMESH_subMeshEventListener* Get() { static _ViscousListener l; return &l; }
181 virtual void ProcessEvent(const int event,
183 SMESH_subMesh* subMesh,
184 SMESH_subMeshEventListenerData* data,
185 const SMESH_Hypothesis* hyp)
187 if ( SMESH_subMesh::COMPUTE_EVENT == eventType &&
188 SMESH_subMesh::CHECK_COMPUTE_STATE != event)
190 // delete SMESH_ProxyMesh containing temporary faces
191 subMesh->DeleteEventListener( this );
194 // Finds or creates proxy mesh of the solid
195 static _MeshOfSolid* GetSolidMesh(SMESH_Mesh* mesh,
196 const TopoDS_Shape& solid,
199 if ( !mesh ) return 0;
200 SMESH_subMesh* sm = mesh->GetSubMesh(solid);
201 _MeshOfSolid* data = (_MeshOfSolid*) sm->GetEventListenerData( Get() );
202 if ( !data && toCreate )
204 data = new _MeshOfSolid(mesh);
205 data->mySubMeshes.push_back( sm ); // to find SOLID by _MeshOfSolid
206 sm->SetEventListener( Get(), data, sm );
210 // Removes proxy mesh of the solid
211 static void RemoveSolidMesh(SMESH_Mesh* mesh, const TopoDS_Shape& solid)
213 mesh->GetSubMesh(solid)->DeleteEventListener( _ViscousListener::Get() );
217 //================================================================================
219 * \brief sets a sub-mesh event listener to clear sub-meshes of sub-shapes of
220 * the main shape when sub-mesh of the main shape is cleared,
221 * for example to clear sub-meshes of FACEs when sub-mesh of a SOLID
224 //================================================================================
226 void ToClearSubWithMain( SMESH_subMesh* sub, const TopoDS_Shape& main)
228 SMESH_subMesh* mainSM = sub->GetFather()->GetSubMesh( main );
229 SMESH_subMeshEventListenerData* data =
230 mainSM->GetEventListenerData( _ShrinkShapeListener::Get());
233 if ( find( data->mySubMeshes.begin(), data->mySubMeshes.end(), sub ) ==
234 data->mySubMeshes.end())
235 data->mySubMeshes.push_back( sub );
239 data = SMESH_subMeshEventListenerData::MakeData( /*dependent=*/sub );
240 sub->SetEventListener( _ShrinkShapeListener::Get(), data, /*whereToListenTo=*/mainSM );
244 //--------------------------------------------------------------------------------
246 * \brief Simplex (triangle or tetrahedron) based on 1 (tria) or 2 (tet) nodes of
247 * _LayerEdge and 2 nodes of the mesh surface beening smoothed.
248 * The class is used to check validity of face or volumes around a smoothed node;
249 * it stores only 2 nodes as the other nodes are stored by _LayerEdge.
253 const SMDS_MeshNode *_nPrev, *_nNext; // nodes on a smoothed mesh surface
254 const SMDS_MeshNode *_nOpp; // in 2D case, a node opposite to a smoothed node in QUAD
255 _Simplex(const SMDS_MeshNode* nPrev=0,
256 const SMDS_MeshNode* nNext=0,
257 const SMDS_MeshNode* nOpp=0)
258 : _nPrev(nPrev), _nNext(nNext), _nOpp(nOpp) {}
259 bool IsForward(const SMDS_MeshNode* nSrc, const gp_XYZ* pntTgt, double& vol) const
261 const double M[3][3] =
262 {{ _nNext->X() - nSrc->X(), _nNext->Y() - nSrc->Y(), _nNext->Z() - nSrc->Z() },
263 { pntTgt->X() - nSrc->X(), pntTgt->Y() - nSrc->Y(), pntTgt->Z() - nSrc->Z() },
264 { _nPrev->X() - nSrc->X(), _nPrev->Y() - nSrc->Y(), _nPrev->Z() - nSrc->Z() }};
265 vol = ( + M[0][0]*M[1][1]*M[2][2]
266 + M[0][1]*M[1][2]*M[2][0]
267 + M[0][2]*M[1][0]*M[2][1]
268 - M[0][0]*M[1][2]*M[2][1]
269 - M[0][1]*M[1][0]*M[2][2]
270 - M[0][2]*M[1][1]*M[2][0]);
273 bool IsForward(const gp_XY& tgtUV,
274 const SMDS_MeshNode* smoothedNode,
275 const TopoDS_Face& face,
276 SMESH_MesherHelper& helper,
277 const double refSign) const
279 gp_XY prevUV = helper.GetNodeUV( face, _nPrev, smoothedNode );
280 gp_XY nextUV = helper.GetNodeUV( face, _nNext, smoothedNode );
281 gp_Vec2d v1( tgtUV, prevUV ), v2( tgtUV, nextUV );
283 return d*refSign > 1e-100;
285 bool IsNeighbour(const _Simplex& other) const
287 return _nPrev == other._nNext || _nNext == other._nPrev;
289 static void GetSimplices( const SMDS_MeshNode* node,
290 vector<_Simplex>& simplices,
291 const set<TGeomID>& ingnoreShapes,
292 const _SolidData* dataToCheckOri = 0,
293 const bool toSort = false);
294 static void SortSimplices(vector<_Simplex>& simplices);
296 //--------------------------------------------------------------------------------
298 * Structure used to take into account surface curvature while smoothing
303 double _k; // factor to correct node smoothed position
304 double _h2lenRatio; // avgNormProj / (2*avgDist)
306 static _Curvature* New( double avgNormProj, double avgDist )
309 if ( fabs( avgNormProj / avgDist ) > 1./200 )
312 c->_r = avgDist * avgDist / avgNormProj;
313 c->_k = avgDist * avgDist / c->_r / c->_r;
314 //c->_k = avgNormProj / c->_r;
315 c->_k *= ( c->_r < 0 ? 1/1.1 : 1.1 ); // not to be too restrictive
316 c->_h2lenRatio = avgNormProj / ( avgDist + avgDist );
320 double lenDelta(double len) const { return _k * ( _r + len ); }
321 double lenDeltaByDist(double dist) const { return dist * _h2lenRatio; }
323 //--------------------------------------------------------------------------------
327 typedef map< const SMDS_MeshNode*, _LayerEdge*, TIDCompare > TNode2Edge;
329 //--------------------------------------------------------------------------------
331 * \brief Edge normal to surface, connecting a node on solid surface (_nodes[0])
332 * and a node of the most internal layer (_nodes.back())
336 typedef gp_XYZ (_LayerEdge::*PSmooFun)();
338 vector< const SMDS_MeshNode*> _nodes;
340 gp_XYZ _normal; // to solid surface
341 vector<gp_XYZ> _pos; // points computed during inflation
342 double _len; // length achived with the last inflation step
343 double _cosin; // of angle (_normal ^ surface)
344 double _lenFactor; // to compute _len taking _cosin into account
346 // face or edge w/o layer along or near which _LayerEdge is inflated
348 // simplices connected to the source node (_nodes[0]);
349 // used for smoothing and quality check of _LayerEdge's based on the FACE
350 vector<_Simplex> _simplices;
351 PSmooFun _smooFunction; // smoothing function
352 // data for smoothing of _LayerEdge's based on the EDGE
353 _2NearEdges* _2neibors;
355 _Curvature* _curvature;
356 // TODO:: detele _Curvature, _plnNorm
358 void SetNewLength( double len, SMESH_MesherHelper& helper );
359 bool SetNewLength2d( Handle(Geom_Surface)& surface,
360 const TopoDS_Face& F,
361 SMESH_MesherHelper& helper );
362 void SetDataByNeighbors( const SMDS_MeshNode* n1,
363 const SMDS_MeshNode* n2,
364 SMESH_MesherHelper& helper);
365 void InvalidateStep( int curStep, bool restoreLength=false );
366 void ChooseSmooFunction(const set< TGeomID >& concaveVertices,
367 const TNode2Edge& n2eMap);
368 int Smooth(const int step, const bool isConcaveFace, const bool findBest);
369 bool SmoothOnEdge(Handle(Geom_Surface)& surface,
370 const TopoDS_Face& F,
371 SMESH_MesherHelper& helper);
372 bool FindIntersection( SMESH_ElementSearcher& searcher,
374 const double& epsilon,
375 const SMDS_MeshElement** face = 0);
376 bool SegTriaInter( const gp_Ax1& lastSegment,
377 const SMDS_MeshNode* n0,
378 const SMDS_MeshNode* n1,
379 const SMDS_MeshNode* n2,
381 const double& epsilon) const;
382 gp_Ax1 LastSegment(double& segLen) const;
383 gp_XY LastUV( const TopoDS_Face& F ) const;
384 bool IsOnEdge() const { return _2neibors; }
385 gp_XYZ Copy( _LayerEdge& other, SMESH_MesherHelper& helper );
386 void SetCosin( double cosin );
387 int NbSteps() const { return _pos.size() - 1; } // nb inlation steps
389 gp_XYZ smoothLaplacian();
390 gp_XYZ smoothAngular();
391 gp_XYZ smoothLengthWeighted();
392 gp_XYZ smoothCentroidal();
393 gp_XYZ smoothNefPolygon();
395 enum { FUN_LAPLACIAN, FUN_LENWEIGHTED, FUN_CENTROIDAL, FUN_NEFPOLY, FUN_ANGULAR, FUN_NB };
396 static const int theNbSmooFuns = FUN_NB;
397 static PSmooFun _funs[theNbSmooFuns];
398 static const char* _funNames[theNbSmooFuns+1];
399 int smooFunID( PSmooFun fun=0) const;
401 _LayerEdge::PSmooFun _LayerEdge::_funs[theNbSmooFuns] = { &_LayerEdge::smoothLaplacian,
402 &_LayerEdge::smoothLengthWeighted,
403 &_LayerEdge::smoothCentroidal,
404 &_LayerEdge::smoothNefPolygon,
405 &_LayerEdge::smoothAngular };
406 const char* _LayerEdge::_funNames[theNbSmooFuns+1] = { "Laplacian",
414 bool operator () (const _LayerEdge* e1, const _LayerEdge* e2) const
416 const bool cmpNodes = ( e1 && e2 && e1->_nodes.size() && e2->_nodes.size() );
417 return cmpNodes ? ( e1->_nodes[0]->GetID() < e2->_nodes[0]->GetID()) : ( e1 < e2 );
420 //--------------------------------------------------------------------------------
422 * A 2D half plane used by _LayerEdge::smoothNefPolygon()
426 gp_XY _pos, _dir, _inNorm;
427 bool IsOut( const gp_XY p, const double tol ) const
429 return _inNorm * ( p - _pos ) < -tol;
431 bool FindInterestion( const _halfPlane& hp, gp_XY & intPnt )
433 const double eps = 1e-10;
434 double D = _dir.Crossed( hp._dir );
435 if ( fabs(D) < std::numeric_limits<double>::min())
437 gp_XY vec21 = _pos - hp._pos;
438 double u = hp._dir.Crossed( vec21 ) / D;
439 intPnt = _pos + _dir * u;
443 //--------------------------------------------------------------------------------
445 * Structure used to smooth a _LayerEdge based on an EDGE.
449 double _wgt [2]; // weights of _nodes
450 _LayerEdge* _edges[2];
452 // normal to plane passing through _LayerEdge._normal and tangent of EDGE
455 _2NearEdges() { _edges[0]=_edges[1]=0; _plnNorm = 0; }
456 const SMDS_MeshNode* tgtNode(bool is2nd) {
457 return _edges[is2nd] ? _edges[is2nd]->_nodes.back() : 0;
459 const SMDS_MeshNode* srcNode(bool is2nd) {
460 return _edges[is2nd] ? _edges[is2nd]->_nodes[0] : 0;
463 std::swap( _wgt [0], _wgt [1] );
464 std::swap( _edges[0], _edges[1] );
467 //--------------------------------------------------------------------------------
469 * \brief Convex FACE whose radius of curvature is less than the thickness of
470 * layers. It is used to detect distortion of prisms based on a convex
471 * FACE and to update normals to enable further increasing the thickness
477 // edges whose _simplices are used to detect prism destorsion
478 vector< _LayerEdge* > _simplexTestEdges;
480 // map a sub-shape to it's index in _SolidData::_endEdgeOnShape vector
481 map< TGeomID, int > _subIdToEdgeEnd;
485 bool GetCenterOfCurvature( _LayerEdge* ledge,
486 BRepLProp_SLProps& surfProp,
487 SMESH_MesherHelper& helper,
488 gp_Pnt & center ) const;
489 bool CheckPrisms() const;
492 //--------------------------------------------------------------------------------
494 * \brief Layers parameters got by averaging several hypotheses
498 AverageHyp( const StdMeshers_ViscousLayers* hyp = 0 )
499 :_nbLayers(0), _nbHyps(0), _thickness(0), _stretchFactor(0)
503 void Add( const StdMeshers_ViscousLayers* hyp )
508 _nbLayers = hyp->GetNumberLayers();
509 //_thickness += hyp->GetTotalThickness();
510 _thickness = Max( _thickness, hyp->GetTotalThickness() );
511 _stretchFactor += hyp->GetStretchFactor();
514 double GetTotalThickness() const { return _thickness; /*_nbHyps ? _thickness / _nbHyps : 0;*/ }
515 double GetStretchFactor() const { return _nbHyps ? _stretchFactor / _nbHyps : 0; }
516 int GetNumberLayers() const { return _nbLayers; }
518 int _nbLayers, _nbHyps;
519 double _thickness, _stretchFactor;
522 //--------------------------------------------------------------------------------
524 * \brief Data of a SOLID
528 typedef const StdMeshers_ViscousLayers* THyp;
530 TGeomID _index; // SOLID id
531 _MeshOfSolid* _proxyMesh;
533 list< TopoDS_Shape > _hypShapes;
534 map< TGeomID, THyp > _face2hyp; // filled if _hyps.size() > 1
535 set< TGeomID > _reversedFaceIds;
536 set< TGeomID > _ignoreFaceIds; // WOL FACEs and FACEs of other SOLIDs
538 double _stepSize, _stepSizeCoeff, _geomSize;
539 const SMDS_MeshNode* _stepSizeNodes[2];
541 TNode2Edge _n2eMap; // nodes and _LayerEdge's based on them
543 // map to find _n2eMap of another _SolidData by a shrink shape shared by two _SolidData's
544 map< TGeomID, TNode2Edge* > _s2neMap;
545 // edges of _n2eMap. We keep same data in two containers because
546 // iteration over the map is 5 times longer than over the vector
547 vector< _LayerEdge* > _edges;
549 // key: an id of shape (EDGE or VERTEX) shared by a FACE with
550 // layers and a FACE w/o layers
551 // value: the shape (FACE or EDGE) to shrink mesh on.
552 // _LayerEdge's basing on nodes on key shape are inflated along the value shape
553 map< TGeomID, TopoDS_Shape > _shrinkShape2Shape;
555 // Convex FACEs whose radius of curvature is less than the thickness of layers
556 map< TGeomID, _ConvexFace > _convexFaces;
558 // shapes (EDGEs and VERTEXes) srink from which is forbidden due to collisions with
559 // the adjacent SOLID
560 set< TGeomID > _noShrinkShapes;
562 // <EDGE to smooth on> to <it's curve> -- for analytic smooth
563 map< TGeomID,Handle(Geom_Curve)> _edge2curve;
565 // end indices in _edges of _LayerEdge on each shape, first go shapes to smooth
566 vector< int > _endEdgeOnShape;
567 int _nbShapesToSmooth;
568 set< TGeomID > _concaveFaces;
570 // data of averaged StdMeshers_ViscousLayers parameters for each shape with _LayerEdge's
571 vector< AverageHyp > _hypOnShape;
572 double _maxThickness; // of all _hyps
573 double _minThickness; // of all _hyps
575 double _epsilon; // precision for SegTriaInter()
577 _SolidData(const TopoDS_Shape& s=TopoDS_Shape(),
579 :_solid(s), _proxyMesh(m) {}
582 Handle(Geom_Curve) CurveForSmooth( const TopoDS_Edge& E,
585 const TopoDS_Face& F,
586 SMESH_MesherHelper& helper,
587 vector<_LayerEdge* >* edges=0);
589 void SortOnEdge( const TopoDS_Edge& E,
592 SMESH_MesherHelper& helper);
594 void Sort2NeiborsOnEdge( const int iFrom, const int iTo);
596 _ConvexFace* GetConvexFace( const TGeomID faceID )
598 map< TGeomID, _ConvexFace >::iterator id2face = _convexFaces.find( faceID );
599 return id2face == _convexFaces.end() ? 0 : & id2face->second;
601 void GetEdgesOnShape( size_t end, int & iBeg, int & iEnd )
603 iBeg = end > 0 ? _endEdgeOnShape[ end-1 ] : 0;
604 iEnd = _endEdgeOnShape[ end ];
607 bool GetShapeEdges(const TGeomID shapeID, size_t& iEdgeEnd, int* iBeg=0, int* iEnd=0 ) const;
609 void AddShapesToSmooth( const set< TGeomID >& shapeIDs );
611 void PrepareEdgesToSmoothOnFace( _LayerEdge** edgeBeg,
612 _LayerEdge** edgeEnd,
613 const TopoDS_Face& face,
614 bool substituteSrcNodes );
616 //--------------------------------------------------------------------------------
618 * \brief Container of centers of curvature at nodes on an EDGE bounding _ConvexFace
620 struct _CentralCurveOnEdge
623 vector< gp_Pnt > _curvaCenters;
624 vector< _LayerEdge* > _ledges;
625 vector< gp_XYZ > _normals; // new normal for each of _ledges
626 vector< double > _segLength2;
629 TopoDS_Face _adjFace;
630 bool _adjFaceToSmooth;
632 void Append( const gp_Pnt& center, _LayerEdge* ledge )
634 if ( _curvaCenters.size() > 0 )
635 _segLength2.push_back( center.SquareDistance( _curvaCenters.back() ));
636 _curvaCenters.push_back( center );
637 _ledges.push_back( ledge );
638 _normals.push_back( ledge->_normal );
640 bool FindNewNormal( const gp_Pnt& center, gp_XYZ& newNormal );
641 void SetShapes( const TopoDS_Edge& edge,
642 const _ConvexFace& convFace,
643 const _SolidData& data,
644 SMESH_MesherHelper& helper);
646 //--------------------------------------------------------------------------------
648 * \brief Data of node on a shrinked FACE
652 const SMDS_MeshNode* _node;
653 vector<_Simplex> _simplices; // for quality check
655 enum SmoothType { LAPLACIAN, CENTROIDAL, ANGULAR, TFI };
657 bool Smooth(int& badNb,
658 Handle(Geom_Surface)& surface,
659 SMESH_MesherHelper& helper,
660 const double refSign,
664 gp_XY computeAngularPos(vector<gp_XY>& uv,
665 const gp_XY& uvToFix,
666 const double refSign );
668 //--------------------------------------------------------------------------------
670 * \brief Builder of viscous layers
672 class _ViscousBuilder
677 SMESH_ComputeErrorPtr Compute(SMESH_Mesh& mesh,
678 const TopoDS_Shape& shape);
679 // check validity of hypotheses
680 SMESH_ComputeErrorPtr CheckHypotheses( SMESH_Mesh& mesh,
681 const TopoDS_Shape& shape );
683 // restore event listeners used to clear an inferior dim sub-mesh modified by viscous layers
684 void RestoreListeners();
686 // computes SMESH_ProxyMesh::SubMesh::_n2n;
687 bool MakeN2NMap( _MeshOfSolid* pm );
691 bool findSolidsWithLayers();
692 bool findFacesWithLayers(const bool onlyWith=false);
693 void getIgnoreFaces(const TopoDS_Shape& solid,
694 const StdMeshers_ViscousLayers* hyp,
695 const TopoDS_Shape& hypShape,
696 set<TGeomID>& ignoreFaces);
697 bool makeLayer(_SolidData& data);
698 bool setEdgeData(_LayerEdge& edge, const set<TGeomID>& subIds,
699 SMESH_MesherHelper& helper, _SolidData& data);
700 gp_XYZ getFaceNormal(const SMDS_MeshNode* n,
701 const TopoDS_Face& face,
702 SMESH_MesherHelper& helper,
704 bool shiftInside=false);
705 bool getFaceNormalAtSingularity(const gp_XY& uv,
706 const TopoDS_Face& face,
707 SMESH_MesherHelper& helper,
709 gp_XYZ getWeigthedNormal( const SMDS_MeshNode* n,
710 std::pair< TopoDS_Face, gp_XYZ > fId2Normal[],
712 bool findNeiborsOnEdge(const _LayerEdge* edge,
713 const SMDS_MeshNode*& n1,
714 const SMDS_MeshNode*& n2,
716 void findSimplexTestEdges( _SolidData& data,
717 vector< vector<_LayerEdge*> >& edgesByGeom);
718 void computeGeomSize( _SolidData& data );
719 bool sortEdges( _SolidData& data,
720 vector< vector<_LayerEdge*> >& edgesByGeom);
721 void limitStepSizeByCurvature( _SolidData& data );
722 void limitStepSize( _SolidData& data,
723 const SMDS_MeshElement* face,
724 const _LayerEdge* maxCosinEdge );
725 void limitStepSize( _SolidData& data, const double minSize);
726 bool inflate(_SolidData& data);
727 bool smoothAndCheck(_SolidData& data, const int nbSteps, double & distToIntersection);
728 bool smoothAnalyticEdge( _SolidData& data,
731 Handle(Geom_Surface)& surface,
732 const TopoDS_Face& F,
733 SMESH_MesherHelper& helper);
734 bool updateNormals( _SolidData& data, SMESH_MesherHelper& helper, int stepNb );
735 bool updateNormalsOfConvexFaces( _SolidData& data,
736 SMESH_MesherHelper& helper,
738 bool refine(_SolidData& data);
740 bool prepareEdgeToShrink( _LayerEdge& edge, const TopoDS_Face& F,
741 SMESH_MesherHelper& helper,
742 const SMESHDS_SubMesh* faceSubMesh );
743 void restoreNoShrink( _LayerEdge& edge ) const;
744 void fixBadFaces(const TopoDS_Face& F,
745 SMESH_MesherHelper& helper,
748 set<const SMDS_MeshNode*> * involvedNodes=NULL);
749 bool addBoundaryElements();
751 bool error( const string& text, int solidID=-1 );
752 SMESHDS_Mesh* getMeshDS() const { return _mesh->GetMeshDS(); }
755 void makeGroupOfLE();
758 SMESH_ComputeErrorPtr _error;
760 vector< _SolidData > _sdVec;
763 //--------------------------------------------------------------------------------
765 * \brief Shrinker of nodes on the EDGE
769 vector<double> _initU;
770 vector<double> _normPar;
771 vector<const SMDS_MeshNode*> _nodes;
772 const _LayerEdge* _edges[2];
775 void AddEdge( const _LayerEdge* e, SMESH_MesherHelper& helper );
776 void Compute(bool set3D, SMESH_MesherHelper& helper);
777 void RestoreParams();
778 void SwapSrcTgtNodes(SMESHDS_Mesh* mesh);
780 //--------------------------------------------------------------------------------
782 * \brief Class of temporary mesh face.
783 * We can't use SMDS_FaceOfNodes since it's impossible to set it's ID which is
784 * needed because SMESH_ElementSearcher internaly uses set of elements sorted by ID
786 struct _TmpMeshFace : public SMDS_MeshElement
788 vector<const SMDS_MeshNode* > _nn;
789 _TmpMeshFace( const vector<const SMDS_MeshNode*>& nodes, int id, int faceID=-1):
790 SMDS_MeshElement(id), _nn(nodes) { setShapeId(faceID); }
791 virtual const SMDS_MeshNode* GetNode(const int ind) const { return _nn[ind]; }
792 virtual SMDSAbs_ElementType GetType() const { return SMDSAbs_Face; }
793 virtual vtkIdType GetVtkType() const { return -1; }
794 virtual SMDSAbs_EntityType GetEntityType() const { return SMDSEntity_Last; }
795 virtual SMDSAbs_GeometryType GetGeomType() const
796 { return _nn.size() == 3 ? SMDSGeom_TRIANGLE : SMDSGeom_QUADRANGLE; }
797 virtual SMDS_ElemIteratorPtr elementsIterator(SMDSAbs_ElementType) const
798 { return SMDS_ElemIteratorPtr( new SMDS_NodeVectorElemIterator( _nn.begin(), _nn.end()));}
800 //--------------------------------------------------------------------------------
802 * \brief Class of temporary mesh face storing _LayerEdge it's based on
804 struct _TmpMeshFaceOnEdge : public _TmpMeshFace
806 _LayerEdge *_le1, *_le2;
807 _TmpMeshFaceOnEdge( _LayerEdge* le1, _LayerEdge* le2, int ID ):
808 _TmpMeshFace( vector<const SMDS_MeshNode*>(4), ID ), _le1(le1), _le2(le2)
810 _nn[0]=_le1->_nodes[0];
811 _nn[1]=_le1->_nodes.back();
812 _nn[2]=_le2->_nodes.back();
813 _nn[3]=_le2->_nodes[0];
816 //--------------------------------------------------------------------------------
818 * \brief Retriever of node coordinates either directly of from a surface by node UV.
819 * \warning Location of a surface is ignored
821 struct _NodeCoordHelper
823 SMESH_MesherHelper& _helper;
824 const TopoDS_Face& _face;
825 Handle(Geom_Surface) _surface;
826 gp_XYZ (_NodeCoordHelper::* _fun)(const SMDS_MeshNode* n) const;
828 _NodeCoordHelper(const TopoDS_Face& F, SMESH_MesherHelper& helper, bool is2D)
829 : _helper( helper ), _face( F )
834 _surface = BRep_Tool::Surface( _face, loc );
836 if ( _surface.IsNull() )
837 _fun = & _NodeCoordHelper::direct;
839 _fun = & _NodeCoordHelper::byUV;
841 gp_XYZ operator()(const SMDS_MeshNode* n) const { return (this->*_fun)( n ); }
844 gp_XYZ direct(const SMDS_MeshNode* n) const
846 return SMESH_TNodeXYZ( n );
848 gp_XYZ byUV (const SMDS_MeshNode* n) const
850 gp_XY uv = _helper.GetNodeUV( _face, n );
851 return _surface->Value( uv.X(), uv.Y() ).XYZ();
855 } // namespace VISCOUS_3D
859 //================================================================================
860 // StdMeshers_ViscousLayers hypothesis
862 StdMeshers_ViscousLayers::StdMeshers_ViscousLayers(int hypId, int studyId, SMESH_Gen* gen)
863 :SMESH_Hypothesis(hypId, studyId, gen),
864 _isToIgnoreShapes(1), _nbLayers(1), _thickness(1), _stretchFactor(1)
866 _name = StdMeshers_ViscousLayers::GetHypType();
867 _param_algo_dim = -3; // auxiliary hyp used by 3D algos
868 } // --------------------------------------------------------------------------------
869 void StdMeshers_ViscousLayers::SetBndShapes(const std::vector<int>& faceIds, bool toIgnore)
871 if ( faceIds != _shapeIds )
872 _shapeIds = faceIds, NotifySubMeshesHypothesisModification();
873 if ( _isToIgnoreShapes != toIgnore )
874 _isToIgnoreShapes = toIgnore, NotifySubMeshesHypothesisModification();
875 } // --------------------------------------------------------------------------------
876 void StdMeshers_ViscousLayers::SetTotalThickness(double thickness)
878 if ( thickness != _thickness )
879 _thickness = thickness, NotifySubMeshesHypothesisModification();
880 } // --------------------------------------------------------------------------------
881 void StdMeshers_ViscousLayers::SetNumberLayers(int nb)
883 if ( _nbLayers != nb )
884 _nbLayers = nb, NotifySubMeshesHypothesisModification();
885 } // --------------------------------------------------------------------------------
886 void StdMeshers_ViscousLayers::SetStretchFactor(double factor)
888 if ( _stretchFactor != factor )
889 _stretchFactor = factor, NotifySubMeshesHypothesisModification();
890 } // --------------------------------------------------------------------------------
892 StdMeshers_ViscousLayers::Compute(SMESH_Mesh& theMesh,
893 const TopoDS_Shape& theShape,
894 const bool toMakeN2NMap) const
896 using namespace VISCOUS_3D;
897 _ViscousBuilder bulder;
898 SMESH_ComputeErrorPtr err = bulder.Compute( theMesh, theShape );
899 if ( err && !err->IsOK() )
900 return SMESH_ProxyMesh::Ptr();
902 vector<SMESH_ProxyMesh::Ptr> components;
903 TopExp_Explorer exp( theShape, TopAbs_SOLID );
904 for ( ; exp.More(); exp.Next() )
906 if ( _MeshOfSolid* pm =
907 _ViscousListener::GetSolidMesh( &theMesh, exp.Current(), /*toCreate=*/false))
909 if ( toMakeN2NMap && !pm->_n2nMapComputed )
910 if ( !bulder.MakeN2NMap( pm ))
911 return SMESH_ProxyMesh::Ptr();
912 components.push_back( SMESH_ProxyMesh::Ptr( pm ));
913 pm->myIsDeletable = false; // it will de deleted by boost::shared_ptr
915 if ( pm->_warning && !pm->_warning->IsOK() )
917 SMESH_subMesh* sm = theMesh.GetSubMesh( exp.Current() );
918 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
919 if ( !smError || smError->IsOK() )
920 smError = pm->_warning;
923 _ViscousListener::RemoveSolidMesh ( &theMesh, exp.Current() );
925 switch ( components.size() )
929 case 1: return components[0];
931 default: return SMESH_ProxyMesh::Ptr( new SMESH_ProxyMesh( components ));
933 return SMESH_ProxyMesh::Ptr();
934 } // --------------------------------------------------------------------------------
935 std::ostream & StdMeshers_ViscousLayers::SaveTo(std::ostream & save)
937 save << " " << _nbLayers
939 << " " << _stretchFactor
940 << " " << _shapeIds.size();
941 for ( size_t i = 0; i < _shapeIds.size(); ++i )
942 save << " " << _shapeIds[i];
943 save << " " << !_isToIgnoreShapes; // negate to keep the behavior in old studies.
945 } // --------------------------------------------------------------------------------
946 std::istream & StdMeshers_ViscousLayers::LoadFrom(std::istream & load)
948 int nbFaces, faceID, shapeToTreat;
949 load >> _nbLayers >> _thickness >> _stretchFactor >> nbFaces;
950 while ( _shapeIds.size() < nbFaces && load >> faceID )
951 _shapeIds.push_back( faceID );
952 if ( load >> shapeToTreat )
953 _isToIgnoreShapes = !shapeToTreat;
955 _isToIgnoreShapes = true; // old behavior
957 } // --------------------------------------------------------------------------------
958 bool StdMeshers_ViscousLayers::SetParametersByMesh(const SMESH_Mesh* theMesh,
959 const TopoDS_Shape& theShape)
963 } // --------------------------------------------------------------------------------
964 SMESH_ComputeErrorPtr
965 StdMeshers_ViscousLayers::CheckHypothesis(SMESH_Mesh& theMesh,
966 const TopoDS_Shape& theShape,
967 SMESH_Hypothesis::Hypothesis_Status& theStatus)
969 VISCOUS_3D::_ViscousBuilder bulder;
970 SMESH_ComputeErrorPtr err = bulder.CheckHypotheses( theMesh, theShape );
971 if ( err && !err->IsOK() )
972 theStatus = SMESH_Hypothesis::HYP_INCOMPAT_HYPS;
974 theStatus = SMESH_Hypothesis::HYP_OK;
978 // --------------------------------------------------------------------------------
979 bool StdMeshers_ViscousLayers::IsShapeWithLayers(int shapeIndex) const
982 ( std::find( _shapeIds.begin(), _shapeIds.end(), shapeIndex ) != _shapeIds.end() );
983 return IsToIgnoreShapes() ? !isIn : isIn;
985 // END StdMeshers_ViscousLayers hypothesis
986 //================================================================================
990 gp_XYZ getEdgeDir( const TopoDS_Edge& E, const TopoDS_Vertex& fromV )
994 Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
995 gp_Pnt p = BRep_Tool::Pnt( fromV );
996 double distF = p.SquareDistance( c->Value( f ));
997 double distL = p.SquareDistance( c->Value( l ));
998 c->D1(( distF < distL ? f : l), p, dir );
999 if ( distL < distF ) dir.Reverse();
1002 //--------------------------------------------------------------------------------
1003 gp_XYZ getEdgeDir( const TopoDS_Edge& E, const SMDS_MeshNode* atNode,
1004 SMESH_MesherHelper& helper)
1007 double f,l; gp_Pnt p;
1008 Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
1009 if ( c.IsNull() ) return gp_XYZ( 1e100, 1e100, 1e100 );
1010 double u = helper.GetNodeU( E, atNode );
1014 //--------------------------------------------------------------------------------
1015 gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Vertex& fromV,
1016 const SMDS_MeshNode* node, SMESH_MesherHelper& helper, bool& ok,
1018 //--------------------------------------------------------------------------------
1019 gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Edge& fromE,
1020 const SMDS_MeshNode* node, SMESH_MesherHelper& helper, bool& ok)
1023 Handle(Geom_Curve) c = BRep_Tool::Curve( fromE, f, l );
1026 TopoDS_Vertex v = helper.IthVertex( 0, fromE );
1027 return getFaceDir( F, v, node, helper, ok );
1029 gp_XY uv = helper.GetNodeUV( F, node, 0, &ok );
1030 Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
1031 gp_Pnt p; gp_Vec du, dv, norm;
1032 surface->D1( uv.X(),uv.Y(), p, du,dv );
1035 double u = helper.GetNodeU( fromE, node, 0, &ok );
1037 TopAbs_Orientation o = helper.GetSubShapeOri( F.Oriented(TopAbs_FORWARD), fromE);
1038 if ( o == TopAbs_REVERSED )
1041 gp_Vec dir = norm ^ du;
1043 if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX &&
1044 helper.IsClosedEdge( fromE ))
1046 if ( fabs(u-f) < fabs(u-l)) c->D1( l, p, dv );
1047 else c->D1( f, p, dv );
1048 if ( o == TopAbs_REVERSED )
1050 gp_Vec dir2 = norm ^ dv;
1051 dir = dir.Normalized() + dir2.Normalized();
1055 //--------------------------------------------------------------------------------
1056 gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Vertex& fromV,
1057 const SMDS_MeshNode* node, SMESH_MesherHelper& helper,
1058 bool& ok, double* cosin)
1060 TopoDS_Face faceFrw = F;
1061 faceFrw.Orientation( TopAbs_FORWARD );
1062 double f,l; TopLoc_Location loc;
1063 TopoDS_Edge edges[2]; // sharing a vertex
1066 TopoDS_Vertex VV[2];
1067 TopExp_Explorer exp( faceFrw, TopAbs_EDGE );
1068 for ( ; exp.More() && nbEdges < 2; exp.Next() )
1070 const TopoDS_Edge& e = TopoDS::Edge( exp.Current() );
1071 if ( SMESH_Algo::isDegenerated( e )) continue;
1072 TopExp::Vertices( e, VV[0], VV[1], /*CumOri=*/true );
1073 if ( VV[1].IsSame( fromV )) {
1074 nbEdges += edges[ 0 ].IsNull();
1077 else if ( VV[0].IsSame( fromV )) {
1078 nbEdges += edges[ 1 ].IsNull();
1083 gp_XYZ dir(0,0,0), edgeDir[2];
1086 // get dirs of edges going fromV
1088 for ( size_t i = 0; i < nbEdges && ok; ++i )
1090 edgeDir[i] = getEdgeDir( edges[i], fromV );
1091 double size2 = edgeDir[i].SquareModulus();
1092 if (( ok = size2 > numeric_limits<double>::min() ))
1093 edgeDir[i] /= sqrt( size2 );
1095 if ( !ok ) return dir;
1097 // get angle between the 2 edges
1099 double angle = helper.GetAngle( edges[0], edges[1], faceFrw, fromV, &faceNormal );
1100 if ( Abs( angle ) < 5 * M_PI/180 )
1102 dir = ( faceNormal.XYZ() ^ edgeDir[0].Reversed()) + ( faceNormal.XYZ() ^ edgeDir[1] );
1106 dir = edgeDir[0] + edgeDir[1];
1111 double angle = gp_Vec( edgeDir[0] ).Angle( dir );
1112 *cosin = Cos( angle );
1115 else if ( nbEdges == 1 )
1117 dir = getFaceDir( faceFrw, edges[ edges[0].IsNull() ], node, helper, ok );
1118 if ( cosin ) *cosin = 1.;
1128 //================================================================================
1130 * \brief Finds concave VERTEXes of a FACE
1132 //================================================================================
1134 bool getConcaveVertices( const TopoDS_Face& F,
1135 SMESH_MesherHelper& helper,
1136 set< TGeomID >* vertices = 0)
1138 // check angles at VERTEXes
1140 TSideVector wires = StdMeshers_FaceSide::GetFaceWires( F, *helper.GetMesh(), 0, error );
1141 for ( size_t iW = 0; iW < wires.size(); ++iW )
1143 const int nbEdges = wires[iW]->NbEdges();
1144 if ( nbEdges < 2 && SMESH_Algo::isDegenerated( wires[iW]->Edge(0)))
1146 for ( int iE1 = 0; iE1 < nbEdges; ++iE1 )
1148 if ( SMESH_Algo::isDegenerated( wires[iW]->Edge( iE1 ))) continue;
1149 int iE2 = ( iE1 + 1 ) % nbEdges;
1150 while ( SMESH_Algo::isDegenerated( wires[iW]->Edge( iE2 )))
1151 iE2 = ( iE2 + 1 ) % nbEdges;
1152 TopoDS_Vertex V = wires[iW]->FirstVertex( iE2 );
1153 double angle = helper.GetAngle( wires[iW]->Edge( iE1 ),
1154 wires[iW]->Edge( iE2 ), F, V );
1155 if ( angle < -5. * M_PI / 180. )
1159 vertices->insert( helper.GetMeshDS()->ShapeToIndex( V ));
1163 return vertices ? !vertices->empty() : false;
1166 //================================================================================
1168 * \brief Returns true if a FACE is bound by a concave EDGE
1170 //================================================================================
1172 bool isConcave( const TopoDS_Face& F,
1173 SMESH_MesherHelper& helper,
1174 set< TGeomID >* vertices = 0 )
1176 bool isConcv = false;
1177 // if ( helper.Count( F, TopAbs_WIRE, /*useMap=*/false) > 1 )
1179 gp_Vec2d drv1, drv2;
1181 TopExp_Explorer eExp( F.Oriented( TopAbs_FORWARD ), TopAbs_EDGE );
1182 for ( ; eExp.More(); eExp.Next() )
1184 const TopoDS_Edge& E = TopoDS::Edge( eExp.Current() );
1185 if ( SMESH_Algo::isDegenerated( E )) continue;
1186 // check if 2D curve is concave
1187 BRepAdaptor_Curve2d curve( E, F );
1188 const int nbIntervals = curve.NbIntervals( GeomAbs_C2 );
1189 TColStd_Array1OfReal intervals(1, nbIntervals + 1 );
1190 curve.Intervals( intervals, GeomAbs_C2 );
1191 bool isConvex = true;
1192 for ( int i = 1; i <= nbIntervals && isConvex; ++i )
1194 double u1 = intervals( i );
1195 double u2 = intervals( i+1 );
1196 curve.D2( 0.5*( u1+u2 ), p, drv1, drv2 );
1197 double cross = drv2 ^ drv1;
1198 if ( E.Orientation() == TopAbs_REVERSED )
1200 isConvex = ( cross > 0.1 ); //-1e-9 );
1204 //cout << "Concave FACE " << helper.GetMeshDS()->ShapeToIndex( F ) << endl;
1213 // check angles at VERTEXes
1214 if ( getConcaveVertices( F, helper, vertices ))
1220 //================================================================================
1222 * \brief Computes mimimal distance of face in-FACE nodes from an EDGE
1223 * \param [in] face - the mesh face to treat
1224 * \param [in] nodeOnEdge - a node on the EDGE
1225 * \param [out] faceSize - the computed distance
1226 * \return bool - true if faceSize computed
1228 //================================================================================
1230 bool getDistFromEdge( const SMDS_MeshElement* face,
1231 const SMDS_MeshNode* nodeOnEdge,
1234 faceSize = Precision::Infinite();
1237 int nbN = face->NbCornerNodes();
1238 int iOnE = face->GetNodeIndex( nodeOnEdge );
1239 int iNext[2] = { SMESH_MesherHelper::WrapIndex( iOnE+1, nbN ),
1240 SMESH_MesherHelper::WrapIndex( iOnE-1, nbN ) };
1241 const SMDS_MeshNode* nNext[2] = { face->GetNode( iNext[0] ),
1242 face->GetNode( iNext[1] ) };
1243 gp_XYZ segVec, segEnd = SMESH_TNodeXYZ( nodeOnEdge ); // segment on EDGE
1244 double segLen = -1.;
1245 // look for two neighbor not in-FACE nodes of face
1246 for ( int i = 0; i < 2; ++i )
1248 if ( nNext[i]->GetPosition()->GetDim() != 2 &&
1249 nNext[i]->GetID() < nodeOnEdge->GetID() )
1251 // look for an in-FACE node
1252 for ( int iN = 0; iN < nbN; ++iN )
1254 if ( iN == iOnE || iN == iNext[i] )
1256 SMESH_TNodeXYZ pInFace = face->GetNode( iN );
1257 gp_XYZ v = pInFace - segEnd;
1260 segVec = SMESH_TNodeXYZ( nNext[i] ) - segEnd;
1261 segLen = segVec.Modulus();
1263 double distToSeg = v.Crossed( segVec ).Modulus() / segLen;
1264 faceSize = Min( faceSize, distToSeg );
1272 //================================================================================
1274 * \brief Return direction of axis or revolution of a surface
1276 //================================================================================
1278 bool getRovolutionAxis( const Adaptor3d_Surface& surface,
1281 switch ( surface.GetType() ) {
1284 gp_Cone cone = surface.Cone();
1285 axis = cone.Axis().Direction();
1288 case GeomAbs_Sphere:
1290 gp_Sphere sphere = surface.Sphere();
1291 axis = sphere.Position().Direction();
1294 case GeomAbs_SurfaceOfRevolution:
1296 axis = surface.AxeOfRevolution().Direction();
1299 //case GeomAbs_SurfaceOfExtrusion:
1300 case GeomAbs_OffsetSurface:
1302 Handle(Adaptor3d_HSurface) base = surface.BasisSurface();
1303 return getRovolutionAxis( base->Surface(), axis );
1305 default: return false;
1310 //--------------------------------------------------------------------------------
1311 // DEBUG. Dump intermediate node positions into a python script
1312 // HOWTO use: run python commands written in a console to see
1313 // construction steps of viscous layers
1318 PyDump(SMESH_Mesh& m) {
1319 int tag = 3 + m.GetId();
1320 const char* fname = "/tmp/viscous.py";
1321 cout << "execfile('"<<fname<<"')"<<endl;
1322 py = new ofstream(fname);
1323 *py << "import SMESH" << endl
1324 << "from salome.smesh import smeshBuilder" << endl
1325 << "smesh = smeshBuilder.New(salome.myStudy)" << endl
1326 << "meshSO = smesh.GetCurrentStudy().FindObjectID('0:1:2:" << tag <<"')" << endl
1327 << "mesh = smesh.Mesh( meshSO.GetObject() )"<<endl;
1332 *py << "mesh.GroupOnFilter(SMESH.VOLUME,'Viscous Prisms',"
1333 "smesh.GetFilter(SMESH.VOLUME,SMESH.FT_ElemGeomType,'=',SMESH.Geom_PENTA))"<<endl;
1334 *py << "mesh.GroupOnFilter(SMESH.VOLUME,'Neg Volumes',"
1335 "smesh.GetFilter(SMESH.VOLUME,SMESH.FT_Volume3D,'<',0))"<<endl;
1339 ~PyDump() { Finish(); cout << "NB FUNCTIONS: " << theNbPyFunc << endl; }
1341 #define dumpFunction(f) { _dumpFunction(f, __LINE__);}
1342 #define dumpMove(n) { _dumpMove(n, __LINE__);}
1343 #define dumpMoveComm(n,txt) { _dumpMove(n, __LINE__, txt);}
1344 #define dumpCmd(txt) { _dumpCmd(txt, __LINE__);}
1345 void _dumpFunction(const string& fun, int ln)
1346 { if (py) *py<< "def "<<fun<<"(): # "<< ln <<endl; cout<<fun<<"()"<<endl; ++theNbPyFunc; }
1347 void _dumpMove(const SMDS_MeshNode* n, int ln, const char* txt="")
1348 { if (py) *py<< " mesh.MoveNode( "<<n->GetID()<< ", "<< n->X()
1349 << ", "<<n->Y()<<", "<< n->Z()<< ")\t\t # "<< ln <<" "<< txt << endl; }
1350 void _dumpCmd(const string& txt, int ln)
1351 { if (py) *py<< " "<<txt<<" # "<< ln <<endl; }
1352 void dumpFunctionEnd()
1353 { if (py) *py<< " return"<< endl; }
1354 void dumpChangeNodes( const SMDS_MeshElement* f )
1355 { if (py) { *py<< " mesh.ChangeElemNodes( " << f->GetID()<<", [";
1356 for ( int i=1; i < f->NbNodes(); ++i ) *py << f->GetNode(i-1)->GetID()<<", ";
1357 *py << f->GetNode( f->NbNodes()-1 )->GetID() << " ])"<< endl; }}
1358 #define debugMsg( txt ) { cout << txt << " (line: " << __LINE__ << ")" << endl; }
1360 struct PyDump { PyDump(SMESH_Mesh&) {} void Finish() {} };
1361 #define dumpFunction(f) f
1363 #define dumpMoveComm(n,txt)
1364 #define dumpCmd(txt)
1365 #define dumpFunctionEnd()
1366 #define dumpChangeNodes(f)
1367 #define debugMsg( txt ) {}
1371 using namespace VISCOUS_3D;
1373 //================================================================================
1375 * \brief Constructor of _ViscousBuilder
1377 //================================================================================
1379 _ViscousBuilder::_ViscousBuilder()
1381 _error = SMESH_ComputeError::New(COMPERR_OK);
1385 //================================================================================
1387 * \brief Stores error description and returns false
1389 //================================================================================
1391 bool _ViscousBuilder::error(const string& text, int solidId )
1393 const string prefix = string("Viscous layers builder: ");
1394 _error->myName = COMPERR_ALGO_FAILED;
1395 _error->myComment = prefix + text;
1398 SMESH_subMesh* sm = _mesh->GetSubMeshContaining( solidId );
1399 if ( !sm && !_sdVec.empty() )
1400 sm = _mesh->GetSubMeshContaining( solidId = _sdVec[0]._index );
1401 if ( sm && sm->GetSubShape().ShapeType() == TopAbs_SOLID )
1403 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1404 if ( smError && smError->myAlgo )
1405 _error->myAlgo = smError->myAlgo;
1407 sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1409 // set KO to all solids
1410 for ( size_t i = 0; i < _sdVec.size(); ++i )
1412 if ( _sdVec[i]._index == solidId )
1414 sm = _mesh->GetSubMesh( _sdVec[i]._solid );
1415 if ( !sm->IsEmpty() )
1417 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1418 if ( !smError || smError->IsOK() )
1420 smError = SMESH_ComputeError::New( COMPERR_ALGO_FAILED, prefix + "failed");
1421 sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1425 makeGroupOfLE(); // debug
1430 //================================================================================
1432 * \brief At study restoration, restore event listeners used to clear an inferior
1433 * dim sub-mesh modified by viscous layers
1435 //================================================================================
1437 void _ViscousBuilder::RestoreListeners()
1442 //================================================================================
1444 * \brief computes SMESH_ProxyMesh::SubMesh::_n2n
1446 //================================================================================
1448 bool _ViscousBuilder::MakeN2NMap( _MeshOfSolid* pm )
1450 SMESH_subMesh* solidSM = pm->mySubMeshes.front();
1451 TopExp_Explorer fExp( solidSM->GetSubShape(), TopAbs_FACE );
1452 for ( ; fExp.More(); fExp.Next() )
1454 SMESHDS_SubMesh* srcSmDS = pm->GetMeshDS()->MeshElements( fExp.Current() );
1455 const SMESH_ProxyMesh::SubMesh* prxSmDS = pm->GetProxySubMesh( fExp.Current() );
1457 if ( !srcSmDS || !prxSmDS || !srcSmDS->NbElements() || !prxSmDS->NbElements() )
1459 if ( srcSmDS->GetElements()->next() == prxSmDS->GetElements()->next())
1462 if ( srcSmDS->NbElements() != prxSmDS->NbElements() )
1463 return error( "Different nb elements in a source and a proxy sub-mesh", solidSM->GetId());
1465 SMDS_ElemIteratorPtr srcIt = srcSmDS->GetElements();
1466 SMDS_ElemIteratorPtr prxIt = prxSmDS->GetElements();
1467 while( prxIt->more() )
1469 const SMDS_MeshElement* fSrc = srcIt->next();
1470 const SMDS_MeshElement* fPrx = prxIt->next();
1471 if ( fSrc->NbNodes() != fPrx->NbNodes())
1472 return error( "Different elements in a source and a proxy sub-mesh", solidSM->GetId());
1473 for ( int i = 0 ; i < fPrx->NbNodes(); ++i )
1474 pm->setNode2Node( fSrc->GetNode(i), fPrx->GetNode(i), prxSmDS );
1477 pm->_n2nMapComputed = true;
1481 //================================================================================
1483 * \brief Does its job
1485 //================================================================================
1487 SMESH_ComputeErrorPtr _ViscousBuilder::Compute(SMESH_Mesh& theMesh,
1488 const TopoDS_Shape& theShape)
1490 // TODO: set priority of solids during Gen::Compute()
1494 // check if proxy mesh already computed
1495 TopExp_Explorer exp( theShape, TopAbs_SOLID );
1497 return error("No SOLID's in theShape"), _error;
1499 if ( _ViscousListener::GetSolidMesh( _mesh, exp.Current(), /*toCreate=*/false))
1500 return SMESH_ComputeErrorPtr(); // everything already computed
1502 PyDump debugDump( theMesh );
1504 // TODO: ignore already computed SOLIDs
1505 if ( !findSolidsWithLayers())
1508 if ( !findFacesWithLayers() )
1511 for ( size_t i = 0; i < _sdVec.size(); ++i )
1513 if ( ! makeLayer(_sdVec[i]) )
1516 if ( _sdVec[i]._edges.size() == 0 )
1519 if ( ! inflate(_sdVec[i]) )
1522 if ( ! refine(_sdVec[i]) )
1528 addBoundaryElements();
1530 makeGroupOfLE(); // debug
1536 //================================================================================
1538 * \brief Check validity of hypotheses
1540 //================================================================================
1542 SMESH_ComputeErrorPtr _ViscousBuilder::CheckHypotheses( SMESH_Mesh& mesh,
1543 const TopoDS_Shape& shape )
1547 if ( _ViscousListener::GetSolidMesh( _mesh, shape, /*toCreate=*/false))
1548 return SMESH_ComputeErrorPtr(); // everything already computed
1551 findSolidsWithLayers();
1552 bool ok = findFacesWithLayers();
1554 // remove _MeshOfSolid's of _SolidData's
1555 for ( size_t i = 0; i < _sdVec.size(); ++i )
1556 _ViscousListener::RemoveSolidMesh( _mesh, _sdVec[i]._solid );
1561 return SMESH_ComputeErrorPtr();
1564 //================================================================================
1566 * \brief Finds SOLIDs to compute using viscous layers. Fills _sdVec
1568 //================================================================================
1570 bool _ViscousBuilder::findSolidsWithLayers()
1573 TopTools_IndexedMapOfShape allSolids;
1574 TopExp::MapShapes( _mesh->GetShapeToMesh(), TopAbs_SOLID, allSolids );
1575 _sdVec.reserve( allSolids.Extent());
1577 SMESH_Gen* gen = _mesh->GetGen();
1578 SMESH_HypoFilter filter;
1579 for ( int i = 1; i <= allSolids.Extent(); ++i )
1581 // find StdMeshers_ViscousLayers hyp assigned to the i-th solid
1582 SMESH_Algo* algo = gen->GetAlgo( *_mesh, allSolids(i) );
1583 if ( !algo ) continue;
1584 // TODO: check if algo is hidden
1585 const list <const SMESHDS_Hypothesis *> & allHyps =
1586 algo->GetUsedHypothesis(*_mesh, allSolids(i), /*ignoreAuxiliary=*/false);
1587 _SolidData* soData = 0;
1588 list< const SMESHDS_Hypothesis *>::const_iterator hyp = allHyps.begin();
1589 const StdMeshers_ViscousLayers* viscHyp = 0;
1590 for ( ; hyp != allHyps.end(); ++hyp )
1591 if ( viscHyp = dynamic_cast<const StdMeshers_ViscousLayers*>( *hyp ))
1593 TopoDS_Shape hypShape;
1594 filter.Init( filter.Is( viscHyp ));
1595 _mesh->GetHypothesis( allSolids(i), filter, true, &hypShape );
1599 _MeshOfSolid* proxyMesh = _ViscousListener::GetSolidMesh( _mesh,
1602 _sdVec.push_back( _SolidData( allSolids(i), proxyMesh ));
1603 soData = & _sdVec.back();
1604 soData->_index = getMeshDS()->ShapeToIndex( allSolids(i));
1606 soData->_hyps.push_back( viscHyp );
1607 soData->_hypShapes.push_back( hypShape );
1610 if ( _sdVec.empty() )
1612 ( SMESH_Comment(StdMeshers_ViscousLayers::GetHypType()) << " hypothesis not found",0);
1617 //================================================================================
1621 //================================================================================
1623 bool _ViscousBuilder::findFacesWithLayers(const bool onlyWith)
1625 SMESH_MesherHelper helper( *_mesh );
1626 TopExp_Explorer exp;
1627 TopTools_IndexedMapOfShape solids;
1629 // collect all faces to ignore defined by hyp
1630 for ( size_t i = 0; i < _sdVec.size(); ++i )
1632 solids.Add( _sdVec[i]._solid );
1634 // get faces to ignore defined by each hyp
1635 typedef const StdMeshers_ViscousLayers* THyp;
1636 typedef std::pair< set<TGeomID>, THyp > TFacesOfHyp;
1637 list< TFacesOfHyp > ignoreFacesOfHyps;
1638 list< THyp >::iterator hyp = _sdVec[i]._hyps.begin();
1639 list< TopoDS_Shape >::iterator hypShape = _sdVec[i]._hypShapes.begin();
1640 for ( ; hyp != _sdVec[i]._hyps.end(); ++hyp, ++hypShape )
1642 ignoreFacesOfHyps.push_back( TFacesOfHyp( set<TGeomID>(), *hyp ));
1643 getIgnoreFaces( _sdVec[i]._solid, *hyp, *hypShape, ignoreFacesOfHyps.back().first );
1646 // fill _SolidData::_face2hyp and check compatibility of hypotheses
1647 const int nbHyps = _sdVec[i]._hyps.size();
1650 // check if two hypotheses define different parameters for the same FACE
1651 list< TFacesOfHyp >::iterator igFacesOfHyp;
1652 for ( exp.Init( _sdVec[i]._solid, TopAbs_FACE ); exp.More(); exp.Next() )
1654 const TGeomID faceID = getMeshDS()->ShapeToIndex( exp.Current() );
1656 igFacesOfHyp = ignoreFacesOfHyps.begin();
1657 for ( ; igFacesOfHyp != ignoreFacesOfHyps.end(); ++igFacesOfHyp )
1658 if ( ! igFacesOfHyp->first.count( faceID ))
1661 return error(SMESH_Comment("Several hypotheses define "
1662 "Viscous Layers on the face #") << faceID );
1663 hyp = igFacesOfHyp->second;
1666 _sdVec[i]._face2hyp.insert( make_pair( faceID, hyp ));
1668 _sdVec[i]._ignoreFaceIds.insert( faceID );
1671 // check if two hypotheses define different number of viscous layers for
1672 // adjacent faces of a solid
1673 set< int > nbLayersSet;
1674 igFacesOfHyp = ignoreFacesOfHyps.begin();
1675 for ( ; igFacesOfHyp != ignoreFacesOfHyps.end(); ++igFacesOfHyp )
1677 nbLayersSet.insert( igFacesOfHyp->second->GetNumberLayers() );
1679 if ( nbLayersSet.size() > 1 )
1681 for ( exp.Init( _sdVec[i]._solid, TopAbs_EDGE ); exp.More(); exp.Next() )
1683 PShapeIteratorPtr fIt = helper.GetAncestors( exp.Current(), *_mesh, TopAbs_FACE );
1684 THyp hyp1 = 0, hyp2 = 0;
1685 while( const TopoDS_Shape* face = fIt->next() )
1687 const TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
1688 map< TGeomID, THyp >::iterator f2h = _sdVec[i]._face2hyp.find( faceID );
1689 if ( f2h != _sdVec[i]._face2hyp.end() )
1691 ( hyp1 ? hyp2 : hyp1 ) = f2h->second;
1694 if ( hyp1 && hyp2 &&
1695 hyp1->GetNumberLayers() != hyp2->GetNumberLayers() )
1697 return error("Two hypotheses define different number of "
1698 "viscous layers on adjacent faces");
1702 } // if ( nbHyps > 1 )
1705 _sdVec[i]._ignoreFaceIds.swap( ignoreFacesOfHyps.back().first );
1709 if ( onlyWith ) // is called to check hypotheses compatibility only
1712 // fill _SolidData::_reversedFaceIds
1713 for ( size_t i = 0; i < _sdVec.size(); ++i )
1715 exp.Init( _sdVec[i]._solid.Oriented( TopAbs_FORWARD ), TopAbs_FACE );
1716 for ( ; exp.More(); exp.Next() )
1718 const TopoDS_Face& face = TopoDS::Face( exp.Current() );
1719 const TGeomID faceID = getMeshDS()->ShapeToIndex( face );
1720 if ( //!sdVec[i]._ignoreFaceIds.count( faceID ) &&
1721 helper.NbAncestors( face, *_mesh, TopAbs_SOLID ) > 1 &&
1722 helper.IsReversedSubMesh( face ))
1724 _sdVec[i]._reversedFaceIds.insert( faceID );
1729 // Find faces to shrink mesh on (solution 2 in issue 0020832);
1730 TopTools_IndexedMapOfShape shapes;
1731 for ( size_t i = 0; i < _sdVec.size(); ++i )
1734 TopExp::MapShapes(_sdVec[i]._solid, TopAbs_EDGE, shapes);
1735 for ( int iE = 1; iE <= shapes.Extent(); ++iE )
1737 const TopoDS_Shape& edge = shapes(iE);
1738 // find 2 faces sharing an edge
1740 PShapeIteratorPtr fIt = helper.GetAncestors(edge, *_mesh, TopAbs_FACE);
1741 while ( fIt->more())
1743 const TopoDS_Shape* f = fIt->next();
1744 if ( helper.IsSubShape( *f, _sdVec[i]._solid))
1745 FF[ int( !FF[0].IsNull()) ] = *f;
1747 if( FF[1].IsNull() ) continue; // seam edge can be shared by 1 FACE only
1748 // check presence of layers on them
1750 for ( int j = 0; j < 2; ++j )
1751 ignore[j] = _sdVec[i]._ignoreFaceIds.count ( getMeshDS()->ShapeToIndex( FF[j] ));
1752 if ( ignore[0] == ignore[1] )
1753 continue; // nothing interesting
1754 TopoDS_Shape fWOL = FF[ ignore[0] ? 0 : 1 ];
1755 // check presence of layers on fWOL within an adjacent SOLID
1756 bool collision = false;
1757 PShapeIteratorPtr sIt = helper.GetAncestors( fWOL, *_mesh, TopAbs_SOLID );
1758 while ( const TopoDS_Shape* solid = sIt->next() )
1759 if ( !solid->IsSame( _sdVec[i]._solid ))
1761 int iSolid = solids.FindIndex( *solid );
1762 int iFace = getMeshDS()->ShapeToIndex( fWOL );
1763 if ( iSolid > 0 && !_sdVec[ iSolid-1 ]._ignoreFaceIds.count( iFace ))
1765 //_sdVec[i]._noShrinkShapes.insert( iFace );
1771 if ( !fWOL.IsNull())
1773 TGeomID edgeInd = getMeshDS()->ShapeToIndex( edge );
1774 _sdVec[i]._shrinkShape2Shape.insert( make_pair( edgeInd, fWOL ));
1777 // _shrinkShape2Shape will be used to temporary inflate _LayerEdge's based
1778 // on the edge but shrink won't be performed
1779 _sdVec[i]._noShrinkShapes.insert( edgeInd );
1784 // Exclude from _shrinkShape2Shape FACE's that can't be shrinked since
1785 // the algo of the SOLID sharing the FACE does not support it
1786 set< string > notSupportAlgos; notSupportAlgos.insert("Hexa_3D");
1787 for ( size_t i = 0; i < _sdVec.size(); ++i )
1789 map< TGeomID, TopoDS_Shape >::iterator e2f = _sdVec[i]._shrinkShape2Shape.begin();
1790 for ( ; e2f != _sdVec[i]._shrinkShape2Shape.end(); ++e2f )
1792 const TopoDS_Shape& fWOL = e2f->second;
1793 const TGeomID edgeID = e2f->first;
1794 bool notShrinkFace = false;
1795 PShapeIteratorPtr soIt = helper.GetAncestors(fWOL, *_mesh, TopAbs_SOLID);
1796 while ( soIt->more() )
1798 const TopoDS_Shape* solid = soIt->next();
1799 if ( _sdVec[i]._solid.IsSame( *solid )) continue;
1800 SMESH_Algo* algo = _mesh->GetGen()->GetAlgo( *_mesh, *solid );
1801 if ( !algo || !notSupportAlgos.count( algo->GetName() )) continue;
1802 notShrinkFace = true;
1804 for ( ; iSolid < _sdVec.size(); ++iSolid )
1806 if ( _sdVec[iSolid]._solid.IsSame( *solid ) ) {
1807 if ( _sdVec[iSolid]._shrinkShape2Shape.count( edgeID ))
1808 notShrinkFace = false;
1812 if ( notShrinkFace )
1814 _sdVec[i]._noShrinkShapes.insert( edgeID );
1816 // add VERTEXes of the edge in _noShrinkShapes
1817 TopoDS_Shape edge = getMeshDS()->IndexToShape( edgeID );
1818 for ( TopoDS_Iterator vIt( edge ); vIt.More(); vIt.Next() )
1819 _sdVec[i]._noShrinkShapes.insert( getMeshDS()->ShapeToIndex( vIt.Value() ));
1821 // check if there is a collision with to-shrink-from EDGEs in iSolid
1822 if ( iSolid == _sdVec.size() )
1823 continue; // no VL in the solid
1825 TopExp::MapShapes( fWOL, TopAbs_EDGE, shapes);
1826 for ( int iE = 1; iE <= shapes.Extent(); ++iE )
1828 const TopoDS_Edge& E = TopoDS::Edge( shapes( iE ));
1829 const TGeomID eID = getMeshDS()->ShapeToIndex( E );
1830 if ( eID == edgeID ||
1831 !_sdVec[iSolid]._shrinkShape2Shape.count( eID ) ||
1832 _sdVec[i]._noShrinkShapes.count( eID ))
1834 for ( int is1st = 0; is1st < 2; ++is1st )
1836 TopoDS_Vertex V = helper.IthVertex( is1st, E );
1837 if ( _sdVec[i]._noShrinkShapes.count( getMeshDS()->ShapeToIndex( V ) ))
1839 // _sdVec[i]._noShrinkShapes.insert( eID );
1840 // V = helper.IthVertex( !is1st, E );
1841 // _sdVec[i]._noShrinkShapes.insert( getMeshDS()->ShapeToIndex( V ));
1842 //iE = 0; // re-start the loop on EDGEs of fWOL
1843 return error("No way to make a conformal mesh with "
1844 "the given set of faces with layers", _sdVec[i]._index);
1850 } // while ( soIt->more() )
1851 } // loop on _sdVec[i]._shrinkShape2Shape
1852 } // loop on _sdVec to fill in _SolidData::_noShrinkShapes
1854 // Find the SHAPE along which to inflate _LayerEdge based on VERTEX
1856 for ( size_t i = 0; i < _sdVec.size(); ++i )
1859 TopExp::MapShapes(_sdVec[i]._solid, TopAbs_VERTEX, shapes);
1860 for ( int iV = 1; iV <= shapes.Extent(); ++iV )
1862 const TopoDS_Shape& vertex = shapes(iV);
1863 // find faces WOL sharing the vertex
1864 vector< TopoDS_Shape > facesWOL;
1865 int totalNbFaces = 0;
1866 PShapeIteratorPtr fIt = helper.GetAncestors(vertex, *_mesh, TopAbs_FACE);
1867 while ( fIt->more())
1869 const TopoDS_Shape* f = fIt->next();
1870 if ( helper.IsSubShape( *f, _sdVec[i]._solid ) )
1873 const int fID = getMeshDS()->ShapeToIndex( *f );
1874 if ( _sdVec[i]._ignoreFaceIds.count ( fID ) /*&&
1875 !_sdVec[i]._noShrinkShapes.count( fID )*/)
1876 facesWOL.push_back( *f );
1879 if ( facesWOL.size() == totalNbFaces || facesWOL.empty() )
1880 continue; // no layers at this vertex or no WOL
1881 TGeomID vInd = getMeshDS()->ShapeToIndex( vertex );
1882 switch ( facesWOL.size() )
1886 helper.SetSubShape( facesWOL[0] );
1887 if ( helper.IsRealSeam( vInd )) // inflate along a seam edge?
1889 TopoDS_Shape seamEdge;
1890 PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
1891 while ( eIt->more() && seamEdge.IsNull() )
1893 const TopoDS_Shape* e = eIt->next();
1894 if ( helper.IsRealSeam( *e ) )
1897 if ( !seamEdge.IsNull() )
1899 _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, seamEdge ));
1903 _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, facesWOL[0] ));
1908 // find an edge shared by 2 faces
1909 PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
1910 while ( eIt->more())
1912 const TopoDS_Shape* e = eIt->next();
1913 if ( helper.IsSubShape( *e, facesWOL[0]) &&
1914 helper.IsSubShape( *e, facesWOL[1]))
1916 _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, *e )); break;
1922 return error("Not yet supported case", _sdVec[i]._index);
1927 // add FACEs of other SOLIDs to _ignoreFaceIds
1928 for ( size_t i = 0; i < _sdVec.size(); ++i )
1931 TopExp::MapShapes(_sdVec[i]._solid, TopAbs_FACE, shapes);
1933 for ( exp.Init( _mesh->GetShapeToMesh(), TopAbs_FACE ); exp.More(); exp.Next() )
1935 if ( !shapes.Contains( exp.Current() ))
1936 _sdVec[i]._ignoreFaceIds.insert( getMeshDS()->ShapeToIndex( exp.Current() ));
1943 //================================================================================
1945 * \brief Finds FACEs w/o layers for a given SOLID by an hypothesis
1947 //================================================================================
1949 void _ViscousBuilder::getIgnoreFaces(const TopoDS_Shape& solid,
1950 const StdMeshers_ViscousLayers* hyp,
1951 const TopoDS_Shape& hypShape,
1952 set<TGeomID>& ignoreFaceIds)
1954 TopExp_Explorer exp;
1956 vector<TGeomID> ids = hyp->GetBndShapes();
1957 if ( hyp->IsToIgnoreShapes() ) // FACEs to ignore are given
1959 for ( size_t ii = 0; ii < ids.size(); ++ii )
1961 const TopoDS_Shape& s = getMeshDS()->IndexToShape( ids[ii] );
1962 if ( !s.IsNull() && s.ShapeType() == TopAbs_FACE )
1963 ignoreFaceIds.insert( ids[ii] );
1966 else // FACEs with layers are given
1968 exp.Init( solid, TopAbs_FACE );
1969 for ( ; exp.More(); exp.Next() )
1971 TGeomID faceInd = getMeshDS()->ShapeToIndex( exp.Current() );
1972 if ( find( ids.begin(), ids.end(), faceInd ) == ids.end() )
1973 ignoreFaceIds.insert( faceInd );
1977 // ignore internal FACEs if inlets and outlets are specified
1978 if ( hyp->IsToIgnoreShapes() )
1980 TopTools_IndexedDataMapOfShapeListOfShape solidsOfFace;
1981 TopExp::MapShapesAndAncestors( hypShape,
1982 TopAbs_FACE, TopAbs_SOLID, solidsOfFace);
1984 for ( exp.Init( solid, TopAbs_FACE ); exp.More(); exp.Next() )
1986 const TopoDS_Face& face = TopoDS::Face( exp.Current() );
1987 if ( SMESH_MesherHelper::NbAncestors( face, *_mesh, TopAbs_SOLID ) < 2 )
1990 int nbSolids = solidsOfFace.FindFromKey( face ).Extent();
1992 ignoreFaceIds.insert( getMeshDS()->ShapeToIndex( face ));
1997 //================================================================================
1999 * \brief Create the inner surface of the viscous layer and prepare data for infation
2001 //================================================================================
2003 bool _ViscousBuilder::makeLayer(_SolidData& data)
2005 // get all sub-shapes to make layers on
2006 set<TGeomID> subIds, faceIds;
2007 subIds = data._noShrinkShapes;
2008 TopExp_Explorer exp( data._solid, TopAbs_FACE );
2009 for ( ; exp.More(); exp.Next() )
2011 SMESH_subMesh* fSubM = _mesh->GetSubMesh( exp.Current() );
2012 if ( ! data._ignoreFaceIds.count( fSubM->GetId() ))
2014 faceIds.insert( fSubM->GetId() );
2015 SMESH_subMeshIteratorPtr subIt = fSubM->getDependsOnIterator(/*includeSelf=*/true);
2016 while ( subIt->more() )
2017 subIds.insert( subIt->next()->GetId() );
2021 // make a map to find new nodes on sub-shapes shared with other SOLID
2022 map< TGeomID, TNode2Edge* >::iterator s2ne;
2023 map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
2024 for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
2026 TGeomID shapeInd = s2s->first;
2027 for ( size_t i = 0; i < _sdVec.size(); ++i )
2029 if ( _sdVec[i]._index == data._index ) continue;
2030 map< TGeomID, TopoDS_Shape >::iterator s2s2 = _sdVec[i]._shrinkShape2Shape.find( shapeInd );
2031 if ( s2s2 != _sdVec[i]._shrinkShape2Shape.end() &&
2032 *s2s == *s2s2 && !_sdVec[i]._n2eMap.empty() )
2034 data._s2neMap.insert( make_pair( shapeInd, &_sdVec[i]._n2eMap ));
2040 // Create temporary faces and _LayerEdge's
2042 dumpFunction(SMESH_Comment("makeLayers_")<<data._index);
2044 data._stepSize = Precision::Infinite();
2045 data._stepSizeNodes[0] = 0;
2047 SMESH_MesherHelper helper( *_mesh );
2048 helper.SetSubShape( data._solid );
2049 helper.SetElementsOnShape( true );
2051 vector< const SMDS_MeshNode*> newNodes; // of a mesh face
2052 TNode2Edge::iterator n2e2;
2054 // collect _LayerEdge's of shapes they are based on
2055 const int nbShapes = getMeshDS()->MaxShapeIndex();
2056 vector< vector<_LayerEdge*> > edgesByGeom( nbShapes+1 );
2058 for ( set<TGeomID>::iterator id = faceIds.begin(); id != faceIds.end(); ++id )
2060 SMESHDS_SubMesh* smDS = getMeshDS()->MeshElements( *id );
2061 if ( !smDS ) return error(SMESH_Comment("Not meshed face ") << *id, data._index );
2063 const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( *id ));
2064 SMESH_ProxyMesh::SubMesh* proxySub =
2065 data._proxyMesh->getFaceSubM( F, /*create=*/true);
2067 SMDS_ElemIteratorPtr eIt = smDS->GetElements();
2068 while ( eIt->more() )
2070 const SMDS_MeshElement* face = eIt->next();
2071 double faceMaxCosin = -1;
2072 _LayerEdge* maxCosinEdge = 0;
2073 int nbDegenNodes = 0;
2075 newNodes.resize( face->NbCornerNodes() );
2076 for ( size_t i = 0 ; i < newNodes.size(); ++i )
2078 const SMDS_MeshNode* n = face->GetNode( i );
2079 const int shapeID = n->getshapeId();
2080 const bool onDegenShap = helper.IsDegenShape( shapeID );
2081 const bool onDegenEdge = ( onDegenShap && n->GetPosition()->GetDim() == 1 );
2086 // substitute n on a degenerated EDGE with a node on a corresponding VERTEX
2087 const TopoDS_Shape& E = getMeshDS()->IndexToShape( shapeID );
2088 TopoDS_Vertex V = helper.IthVertex( 0, TopoDS::Edge( E ));
2089 if ( const SMDS_MeshNode* vN = SMESH_Algo::VertexNode( V, getMeshDS() )) {
2099 TNode2Edge::iterator n2e = data._n2eMap.insert( make_pair( n, (_LayerEdge*)0 )).first;
2100 if ( !(*n2e).second )
2103 _LayerEdge* edge = new _LayerEdge();
2104 edge->_nodes.push_back( n );
2106 edgesByGeom[ shapeID ].push_back( edge );
2107 const bool noShrink = data._noShrinkShapes.count( shapeID );
2109 SMESH_TNodeXYZ xyz( n );
2111 // set edge data or find already refined _LayerEdge and get data from it
2112 if (( !noShrink ) &&
2113 ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE ) &&
2114 (( s2ne = data._s2neMap.find( shapeID )) != data._s2neMap.end() ) &&
2115 (( n2e2 = (*s2ne).second->find( n )) != s2ne->second->end() ))
2117 _LayerEdge* foundEdge = (*n2e2).second;
2118 gp_XYZ lastPos = edge->Copy( *foundEdge, helper );
2119 foundEdge->_pos.push_back( lastPos );
2120 // location of the last node is modified and we restore it by foundEdge->_pos.back()
2121 const_cast< SMDS_MeshNode* >
2122 ( edge->_nodes.back() )->setXYZ( xyz.X(), xyz.Y(), xyz.Z() );
2128 edge->_nodes.push_back( helper.AddNode( xyz.X(), xyz.Y(), xyz.Z() ));
2130 if ( !setEdgeData( *edge, subIds, helper, data ))
2133 dumpMove(edge->_nodes.back());
2135 if ( edge->_cosin > faceMaxCosin )
2137 faceMaxCosin = edge->_cosin;
2138 maxCosinEdge = edge;
2141 newNodes[ i ] = n2e->second->_nodes.back();
2144 data._n2eMap.insert( make_pair( face->GetNode( i ), n2e->second ));
2146 if ( newNodes.size() - nbDegenNodes < 2 )
2149 // create a temporary face
2150 const SMDS_MeshElement* newFace =
2151 new _TmpMeshFace( newNodes, --_tmpFaceID, face->getshapeId() );
2152 proxySub->AddElement( newFace );
2154 // compute inflation step size by min size of element on a convex surface
2155 if ( faceMaxCosin > theMinSmoothCosin )
2156 limitStepSize( data, face, maxCosinEdge );
2158 } // loop on 2D elements on a FACE
2159 } // loop on FACEs of a SOLID
2161 data._epsilon = 1e-7;
2162 if ( data._stepSize < 1. )
2163 data._epsilon *= data._stepSize;
2165 // Put _LayerEdge's into the vector data._edges
2166 if ( !sortEdges( data, edgesByGeom ))
2169 // limit data._stepSize depending on surface curvature and fill data._convexFaces
2170 limitStepSizeByCurvature( data ); // !!! it must be before node substitution in _Simplex
2172 // Set target nodes into _Simplex and _LayerEdge's to _2NearEdges
2173 TNode2Edge::iterator n2e;
2174 const SMDS_MeshNode* nn[2];
2175 for ( size_t i = 0; i < data._edges.size(); ++i )
2177 _LayerEdge* edge = data._edges[i];
2178 if ( edge->IsOnEdge() )
2180 // get neighbor nodes
2181 bool hasData = ( edge->_2neibors->_edges[0] );
2182 if ( hasData ) // _LayerEdge is a copy of another one
2184 nn[0] = edge->_2neibors->srcNode(0);
2185 nn[1] = edge->_2neibors->srcNode(1);
2187 else if ( !findNeiborsOnEdge( edge, nn[0],nn[1], data ))
2191 // set neighbor _LayerEdge's
2192 for ( int j = 0; j < 2; ++j )
2194 if (( n2e = data._n2eMap.find( nn[j] )) == data._n2eMap.end() )
2195 return error("_LayerEdge not found by src node", data._index);
2196 edge->_2neibors->_edges[j] = n2e->second;
2199 edge->SetDataByNeighbors( nn[0], nn[1], helper);
2202 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
2204 _Simplex& s = edge->_simplices[j];
2205 s._nNext = data._n2eMap[ s._nNext ]->_nodes.back();
2206 s._nPrev = data._n2eMap[ s._nPrev ]->_nodes.back();
2209 // For an _LayerEdge on a degenerated EDGE, copy some data from
2210 // a corresponding _LayerEdge on a VERTEX
2211 // (issue 52453, pb on a downloaded SampleCase2-Tet-netgen-mephisto.hdf)
2212 if ( helper.IsDegenShape( edge->_nodes[0]->getshapeId() ))
2214 // Generally we should not get here
2215 const TopoDS_Shape& E = getMeshDS()->IndexToShape( edge->_nodes[0]->getshapeId() );
2216 if ( E.ShapeType() != TopAbs_EDGE )
2218 TopoDS_Vertex V = helper.IthVertex( 0, TopoDS::Edge( E ));
2219 const SMDS_MeshNode* vN = SMESH_Algo::VertexNode( V, getMeshDS() );
2220 if (( n2e = data._n2eMap.find( vN )) == data._n2eMap.end() )
2222 const _LayerEdge* vEdge = n2e->second;
2223 edge->_normal = vEdge->_normal;
2224 edge->_lenFactor = vEdge->_lenFactor;
2225 edge->_cosin = vEdge->_cosin;
2229 // fix _LayerEdge::_2neibors on EDGEs to smooth
2230 map< TGeomID,Handle(Geom_Curve)>::iterator e2c = data._edge2curve.begin();
2231 for ( ; e2c != data._edge2curve.end(); ++e2c )
2232 if ( !e2c->second.IsNull() )
2234 size_t iEdgeEnd; int iBeg, iEnd;
2235 if ( data.GetShapeEdges( e2c->first, iEdgeEnd, &iBeg, &iEnd ))
2236 data.Sort2NeiborsOnEdge( iBeg, iEnd );
2243 //================================================================================
2245 * \brief Compute inflation step size by min size of element on a convex surface
2247 //================================================================================
2249 void _ViscousBuilder::limitStepSize( _SolidData& data,
2250 const SMDS_MeshElement* face,
2251 const _LayerEdge* maxCosinEdge )
2254 double minSize = 10 * data._stepSize;
2255 const int nbNodes = face->NbCornerNodes();
2256 for ( int i = 0; i < nbNodes; ++i )
2258 const SMDS_MeshNode* nextN = face->GetNode( SMESH_MesherHelper::WrapIndex( i+1, nbNodes ));
2259 const SMDS_MeshNode* curN = face->GetNode( i );
2260 if ( nextN->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE ||
2261 curN-> GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE )
2263 double dist = SMESH_TNodeXYZ( curN ).Distance( nextN );
2264 if ( dist < minSize )
2265 minSize = dist, iN = i;
2268 double newStep = 0.8 * minSize / maxCosinEdge->_lenFactor;
2269 if ( newStep < data._stepSize )
2271 data._stepSize = newStep;
2272 data._stepSizeCoeff = 0.8 / maxCosinEdge->_lenFactor;
2273 data._stepSizeNodes[0] = face->GetNode( iN );
2274 data._stepSizeNodes[1] = face->GetNode( SMESH_MesherHelper::WrapIndex( iN+1, nbNodes ));
2278 //================================================================================
2280 * \brief Compute inflation step size by min size of element on a convex surface
2282 //================================================================================
2284 void _ViscousBuilder::limitStepSize( _SolidData& data, const double minSize )
2286 if ( minSize < data._stepSize )
2288 data._stepSize = minSize;
2289 if ( data._stepSizeNodes[0] )
2292 SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
2293 data._stepSizeCoeff = data._stepSize / dist;
2298 //================================================================================
2300 * \brief Limit data._stepSize by evaluating curvature of shapes and fill data._convexFaces
2302 //================================================================================
2304 void _ViscousBuilder::limitStepSizeByCurvature( _SolidData& data )
2306 const int nbTestPnt = 5; // on a FACE sub-shape
2308 BRepLProp_SLProps surfProp( 2, 1e-6 );
2309 SMESH_MesherHelper helper( *_mesh );
2311 data._convexFaces.clear();
2313 TopExp_Explorer face( data._solid, TopAbs_FACE );
2314 for ( ; face.More(); face.Next() )
2316 const TopoDS_Face& F = TopoDS::Face( face.Current() );
2317 SMESH_subMesh * sm = _mesh->GetSubMesh( F );
2318 const TGeomID faceID = sm->GetId();
2319 if ( data._ignoreFaceIds.count( faceID )) continue;
2321 BRepAdaptor_Surface surface( F, false );
2322 surfProp.SetSurface( surface );
2324 bool isTooCurved = false;
2327 _ConvexFace cnvFace;
2328 const double oriFactor = ( F.Orientation() == TopAbs_REVERSED ? +1. : -1. );
2329 SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/true);
2330 while ( smIt->more() )
2333 const TGeomID subID = sm->GetId();
2334 // find _LayerEdge's of a sub-shape
2336 if ( data.GetShapeEdges( subID, edgesEnd, &iBeg, &iEnd ))
2337 cnvFace._subIdToEdgeEnd.insert( make_pair( subID, edgesEnd ));
2340 // check concavity and curvature and limit data._stepSize
2341 const double minCurvature =
2342 1. / ( data._hypOnShape[ edgesEnd ].GetTotalThickness() * ( 1+theThickToIntersection ));
2343 int nbLEdges = iEnd - iBeg;
2344 int iStep = Max( 1, nbLEdges / nbTestPnt );
2345 for ( ; iBeg < iEnd; iBeg += iStep )
2347 gp_XY uv = helper.GetNodeUV( F, data._edges[ iBeg ]->_nodes[0] );
2348 surfProp.SetParameters( uv.X(), uv.Y() );
2349 if ( !surfProp.IsCurvatureDefined() )
2351 if ( surfProp.MaxCurvature() * oriFactor > minCurvature )
2353 limitStepSize( data, 0.9 / surfProp.MaxCurvature() * oriFactor );
2356 if ( surfProp.MinCurvature() * oriFactor > minCurvature )
2358 limitStepSize( data, 0.9 / surfProp.MinCurvature() * oriFactor );
2362 } // loop on sub-shapes of the FACE
2364 if ( !isTooCurved ) continue;
2366 _ConvexFace & convFace =
2367 data._convexFaces.insert( make_pair( faceID, cnvFace )).first->second;
2370 convFace._normalsFixed = false;
2372 // Fill _ConvexFace::_simplexTestEdges. These _LayerEdge's are used to detect
2373 // prism distortion.
2374 map< TGeomID, int >::iterator id2end = convFace._subIdToEdgeEnd.find( faceID );
2375 if ( id2end != convFace._subIdToEdgeEnd.end() )
2377 // there are _LayerEdge's on the FACE it-self;
2378 // select _LayerEdge's near EDGEs
2379 data.GetEdgesOnShape( id2end->second, iBeg, iEnd );
2380 for ( ; iBeg < iEnd; ++iBeg )
2382 _LayerEdge* ledge = data._edges[ iBeg ];
2383 for ( size_t j = 0; j < ledge->_simplices.size(); ++j )
2384 if ( ledge->_simplices[j]._nNext->GetPosition()->GetDim() < 2 )
2386 convFace._simplexTestEdges.push_back( ledge );
2393 // where there are no _LayerEdge's on a _ConvexFace,
2394 // as e.g. on a fillet surface with no internal nodes - issue 22580,
2395 // so that collision of viscous internal faces is not detected by check of
2396 // intersection of _LayerEdge's with the viscous internal faces.
2398 set< const SMDS_MeshNode* > usedNodes;
2400 // look for _LayerEdge's with null _sWOL
2401 map< TGeomID, int >::iterator id2end = convFace._subIdToEdgeEnd.begin();
2402 for ( ; id2end != convFace._subIdToEdgeEnd.end(); ++id2end )
2404 data.GetEdgesOnShape( id2end->second, iBeg, iEnd );
2405 if ( iBeg >= iEnd || !data._edges[ iBeg ]->_sWOL.IsNull() )
2407 for ( ; iBeg < iEnd; ++iBeg )
2409 _LayerEdge* ledge = data._edges[ iBeg ];
2410 const SMDS_MeshNode* srcNode = ledge->_nodes[0];
2411 if ( !usedNodes.insert( srcNode ).second ) continue;
2413 _Simplex::GetSimplices( srcNode, ledge->_simplices, data._ignoreFaceIds, &data );
2414 for ( size_t i = 0; i < ledge->_simplices.size(); ++i )
2416 usedNodes.insert( ledge->_simplices[i]._nPrev );
2417 usedNodes.insert( ledge->_simplices[i]._nNext );
2419 convFace._simplexTestEdges.push_back( ledge );
2423 } // loop on FACEs of data._solid
2426 //================================================================================
2428 * \brief Separate shapes (and _LayerEdge's on them) to smooth from the rest ones
2430 //================================================================================
2432 bool _ViscousBuilder::sortEdges( _SolidData& data,
2433 vector< vector<_LayerEdge*> >& edgesByGeom)
2435 // define allowed thickness
2436 computeGeomSize( data ); // compute data._geomSize
2438 data._maxThickness = 0;
2439 data._minThickness = 1e100;
2440 list< const StdMeshers_ViscousLayers* >::iterator hyp = data._hyps.begin();
2441 for ( ; hyp != data._hyps.end(); ++hyp )
2443 data._maxThickness = Max( data._maxThickness, (*hyp)->GetTotalThickness() );
2444 data._minThickness = Min( data._minThickness, (*hyp)->GetTotalThickness() );
2446 const double tgtThick = /*Min( 0.5 * data._geomSize, */data._maxThickness;
2448 // Find shapes needing smoothing; such a shape has _LayerEdge._normal on it's
2449 // boundry inclined to the shape at a sharp angle
2451 list< TGeomID > shapesToSmooth;
2452 TopTools_MapOfShape edgesOfSmooFaces;
2454 SMESH_MesherHelper helper( *_mesh );
2457 for ( int isEdge = 0; isEdge < 2; ++isEdge ) // loop on [ FACEs, EDGEs ]
2459 const int dim = isEdge ? 1 : 2;
2461 for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS )
2463 vector<_LayerEdge*>& eS = edgesByGeom[iS];
2464 if ( eS.empty() ) continue;
2465 if ( eS[0]->_nodes[0]->GetPosition()->GetDim() != dim ) continue;
2467 const TopoDS_Shape& S = getMeshDS()->IndexToShape( iS );
2468 bool needSmooth = false;
2469 switch ( S.ShapeType() )
2473 const TopoDS_Edge& E = TopoDS::Edge( S );
2474 if ( SMESH_Algo::isDegenerated( E ) || !edgesOfSmooFaces.Contains( E ))
2478 if ( !eS[0]->_sWOL.IsNull() && eS[0]->_sWOL.ShapeType() == TopAbs_FACE )
2479 F = TopoDS::Face( eS[0]->_sWOL );
2481 for ( TopoDS_Iterator vIt( S ); vIt.More() && !needSmooth; vIt.Next() )
2483 TGeomID iV = getMeshDS()->ShapeToIndex( vIt.Value() );
2484 vector<_LayerEdge*>& eV = edgesByGeom[ iV ];
2485 if ( eV.empty() ) continue;
2486 gp_Vec eDir = getEdgeDir( TopoDS::Edge( S ), TopoDS::Vertex( vIt.Value() ));
2487 double angle = eDir.Angle( eV[0]->_normal );
2488 double cosin = Cos( angle );
2489 double cosinAbs = Abs( cosin );
2490 if ( cosinAbs > theMinSmoothCosin )
2492 // always smooth analytic EDGEs
2493 needSmooth = ! data.CurveForSmooth( E, 0, eS.size(), F, helper, &eS ).IsNull();
2495 // compare tgtThick with the length of an end segment
2496 SMDS_ElemIteratorPtr eIt = eV[0]->_nodes[0]->GetInverseElementIterator(SMDSAbs_Edge);
2497 while ( eIt->more() && !needSmooth )
2499 const SMDS_MeshElement* endSeg = eIt->next();
2500 if ( endSeg->getshapeId() == iS )
2503 SMESH_TNodeXYZ( endSeg->GetNode(0) ).Distance( endSeg->GetNode(1 ));
2504 needSmooth = needSmoothing( cosinAbs, tgtThick, segLen );
2513 for ( TopExp_Explorer eExp( S, TopAbs_EDGE ); eExp.More() && !needSmooth; eExp.Next() )
2515 TGeomID iE = getMeshDS()->ShapeToIndex( eExp.Current() );
2516 vector<_LayerEdge*>& eE = edgesByGeom[ iE ];
2517 if ( eE.empty() ) continue;
2518 // TopLoc_Location loc;
2519 // Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face( S ), loc );
2520 // bool isPlane = GeomLib_IsPlanarSurface( surface ).IsPlanar();
2521 //if ( eE[0]->_sWOL.IsNull() )
2524 for ( size_t i = 0; i < eE.size() && !needSmooth; ++i )
2525 if ( eE[i]->_cosin > theMinSmoothCosin )
2527 SMDS_ElemIteratorPtr fIt = eE[i]->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
2528 while ( fIt->more() && !needSmooth )
2530 const SMDS_MeshElement* face = fIt->next();
2531 if ( getDistFromEdge( face, eE[i]->_nodes[0], faceSize ))
2532 needSmooth = needSmoothing( eE[i]->_cosin, tgtThick, faceSize );
2538 // const TopoDS_Face& F1 = TopoDS::Face( S );
2539 // const TopoDS_Face& F2 = TopoDS::Face( eE[0]->_sWOL );
2540 // const TopoDS_Edge& E = TopoDS::Edge( eExp.Current() );
2541 // for ( size_t i = 0; i < eE.size() && !needSmooth; ++i )
2543 // gp_Vec dir1 = getFaceDir( F1, E, eE[i]->_nodes[0], helper, ok );
2544 // gp_Vec dir2 = getFaceDir( F2, E, eE[i]->_nodes[0], helper, ok );
2545 // double angle = dir1.Angle( );
2546 // double cosin = cos( angle );
2547 // needSmooth = ( cosin > theMinSmoothCosin );
2552 for ( TopExp_Explorer eExp( S, TopAbs_EDGE ); eExp.More(); eExp.Next() )
2553 edgesOfSmooFaces.Add( eExp.Current() );
2564 if ( S.ShapeType() == TopAbs_EDGE ) shapesToSmooth.push_front( iS );
2565 else shapesToSmooth.push_back ( iS );
2567 // preparation for smoothing
2568 if ( S.ShapeType() == TopAbs_FACE )
2570 data.PrepareEdgesToSmoothOnFace( & eS[0],
2571 & eS[0] + eS.size(),
2573 /*substituteSrcNodes=*/false);
2577 } // loop on edgesByGeom
2578 } // // loop on [ FACEs, EDGEs ]
2580 data._edges.reserve( data._n2eMap.size() );
2581 data._endEdgeOnShape.clear();
2583 // first we put _LayerEdge's on shapes to smooth
2584 data._nbShapesToSmooth = 0;
2585 list< TGeomID >::iterator gIt = shapesToSmooth.begin();
2586 for ( ; gIt != shapesToSmooth.end(); ++gIt )
2588 vector<_LayerEdge*>& eVec = edgesByGeom[ *gIt ];
2589 if ( eVec.empty() ) continue;
2590 data._edges.insert( data._edges.end(), eVec.begin(), eVec.end() );
2591 data._endEdgeOnShape.push_back( data._edges.size() );
2592 data._nbShapesToSmooth++;
2596 // then the rest _LayerEdge's
2597 for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS )
2599 vector<_LayerEdge*>& eVec = edgesByGeom[iS];
2600 if ( eVec.empty() ) continue;
2601 data._edges.insert( data._edges.end(), eVec.begin(), eVec.end() );
2602 data._endEdgeOnShape.push_back( data._edges.size() );
2606 // compute average StdMeshers_ViscousLayers parameters for each shape
2608 data._hypOnShape.clear();
2609 if ( data._hyps.size() == 1 )
2611 data._hypOnShape.resize( data._endEdgeOnShape.size(), AverageHyp( data._hyps.back() ));
2615 data._hypOnShape.resize( data._endEdgeOnShape.size() );
2616 map< TGeomID, const StdMeshers_ViscousLayers* >::iterator f2hyp;
2617 for ( size_t i = 0; i < data._endEdgeOnShape.size(); ++i )
2619 int iEnd = data._endEdgeOnShape[i];
2620 _LayerEdge* LE = data._edges[ iEnd-1 ];
2621 TGeomID iShape = LE->_nodes[0]->getshapeId();
2622 const TopoDS_Shape& S = getMeshDS()->IndexToShape( iShape );
2623 if ( S.ShapeType() == TopAbs_FACE )
2625 if (( f2hyp = data._face2hyp.find( iShape )) != data._face2hyp.end() )
2627 data._hypOnShape[ i ].Add( f2hyp->second );
2632 PShapeIteratorPtr fIt = SMESH_MesherHelper::GetAncestors( S, *_mesh, TopAbs_FACE );
2633 while ( const TopoDS_Shape* face = fIt->next() )
2635 TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
2636 if (( f2hyp = data._face2hyp.find( faceID )) != data._face2hyp.end() )
2638 data._hypOnShape[ i ].Add( f2hyp->second );
2648 //================================================================================
2650 * \brief Set data of _LayerEdge needed for smoothing
2651 * \param subIds - ids of sub-shapes of a SOLID to take into account faces from
2653 //================================================================================
2655 bool _ViscousBuilder::setEdgeData(_LayerEdge& edge,
2656 const set<TGeomID>& subIds,
2657 SMESH_MesherHelper& helper,
2660 SMESH_MeshEditor editor(_mesh);
2662 const SMDS_MeshNode* node = edge._nodes[0]; // source node
2663 const SMDS_TypeOfPosition posType = node->GetPosition()->GetTypeOfPosition();
2667 edge._curvature = 0;
2669 // --------------------------
2670 // Compute _normal and _cosin
2671 // --------------------------
2674 edge._normal.SetCoord(0,0,0);
2676 int totalNbFaces = 0;
2678 std::pair< TopoDS_Face, gp_XYZ > face2Norm[20];
2682 // get geom FACEs the node lies on
2684 set<TGeomID> faceIds;
2685 if ( posType == SMDS_TOP_FACE )
2687 faceIds.insert( node->getshapeId() );
2691 SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
2692 while ( fIt->more() )
2693 faceIds.insert( editor.FindShape(fIt->next()));
2695 set<TGeomID>::iterator id = faceIds.begin();
2696 for ( ; id != faceIds.end(); ++id )
2698 const TopoDS_Shape& s = getMeshDS()->IndexToShape( *id );
2699 if ( s.IsNull() || s.ShapeType() != TopAbs_FACE || !subIds.count( *id ))
2701 F = TopoDS::Face( s );
2702 face2Norm[ totalNbFaces ].first = F;
2707 const TGeomID shapeInd = node->getshapeId();
2708 map< TGeomID, TopoDS_Shape >::const_iterator s2s = data._shrinkShape2Shape.find( shapeInd );
2709 const bool onShrinkShape ( s2s != data._shrinkShape2Shape.end() );
2712 if ( onShrinkShape ) // one of faces the node is on has no layers
2714 TopoDS_Shape vertEdge = getMeshDS()->IndexToShape( s2s->first ); // vertex or edge
2715 if ( s2s->second.ShapeType() == TopAbs_EDGE )
2717 // inflate from VERTEX along EDGE
2718 edge._normal = getEdgeDir( TopoDS::Edge( s2s->second ), TopoDS::Vertex( vertEdge ));
2720 else if ( vertEdge.ShapeType() == TopAbs_VERTEX )
2722 // inflate from VERTEX along FACE
2723 edge._normal = getFaceDir( TopoDS::Face( s2s->second ), TopoDS::Vertex( vertEdge ),
2724 node, helper, normOK, &edge._cosin);
2728 // inflate from EDGE along FACE
2729 edge._normal = getFaceDir( TopoDS::Face( s2s->second ), TopoDS::Edge( vertEdge ),
2730 node, helper, normOK);
2733 else // layers are on all faces of SOLID the node is on
2736 for ( int iF = 0; iF < totalNbFaces; ++iF )
2738 F = TopoDS::Face( face2Norm[ iF ].first );
2739 geomNorm = getFaceNormal( node, F, helper, normOK );
2740 if ( !normOK ) continue;
2743 if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
2745 face2Norm[ iF ].second = geomNorm.XYZ();
2746 edge._normal += geomNorm.XYZ();
2748 if ( nbOkNorms == 0 )
2749 return error(SMESH_Comment("Can't get normal to node ") << node->GetID(), data._index);
2751 if ( edge._normal.Modulus() < 1e-3 && nbOkNorms > 1 )
2753 // opposite normals, re-get normals at shifted positions (IPAL 52426)
2754 edge._normal.SetCoord( 0,0,0 );
2755 for ( int iF = 0; iF < totalNbFaces; ++iF )
2757 const TopoDS_Face& F = face2Norm[iF].first;
2758 geomNorm = getFaceNormal( node, F, helper, normOK, /*shiftInside=*/true );
2759 if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
2762 face2Norm[ iF ].second = geomNorm.XYZ();
2763 edge._normal += face2Norm[ iF ].second;
2767 if ( totalNbFaces < 3 )
2769 //edge._normal /= totalNbFaces;
2773 edge._normal = getWeigthedNormal( node, face2Norm, totalNbFaces );
2780 case SMDS_TOP_FACE: {
2784 case SMDS_TOP_EDGE: {
2785 TopoDS_Edge E = TopoDS::Edge( helper.GetSubShapeByNode( node, getMeshDS()));
2786 gp_Vec inFaceDir = getFaceDir( F, E, node, helper, normOK );
2787 double angle = inFaceDir.Angle( edge._normal ); // [0,PI]
2788 edge._cosin = Cos( angle );
2789 //cout << "Cosin on EDGE " << edge._cosin << " node " << node->GetID() << endl;
2792 case SMDS_TOP_VERTEX: {
2793 TopoDS_Vertex V = TopoDS::Vertex( helper.GetSubShapeByNode( node, getMeshDS()));
2794 gp_Vec inFaceDir = getFaceDir( F, V, node, helper, normOK );
2795 double angle = inFaceDir.Angle( edge._normal ); // [0,PI]
2796 edge._cosin = Cos( angle );
2797 if ( totalNbFaces > 2 || helper.IsSeamShape( node->getshapeId() ))
2798 for ( int iF = totalNbFaces-2; iF >=0; --iF )
2800 F = face2Norm[ iF ].first;
2801 inFaceDir = getFaceDir( F, V, node, helper, normOK );
2803 double angle = inFaceDir.Angle( edge._normal );
2804 edge._cosin = Max( edge._cosin, Cos( angle ));
2807 //cout << "Cosin on VERTEX " << edge._cosin << " node " << node->GetID() << endl;
2811 return error(SMESH_Comment("Invalid shape position of node ")<<node, data._index);
2814 double normSize = edge._normal.SquareModulus();
2815 if ( normSize < numeric_limits<double>::min() )
2816 return error(SMESH_Comment("Bad normal at node ")<< node->GetID(), data._index );
2818 edge._normal /= sqrt( normSize );
2820 // TODO: if ( !normOK ) then get normal by mesh faces
2822 // Set the rest data
2823 // --------------------
2824 if ( onShrinkShape )
2826 edge._sWOL = (*s2s).second;
2828 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edge._nodes.back() );
2829 if ( SMESHDS_SubMesh* sm = getMeshDS()->MeshElements( data._solid ))
2830 sm->RemoveNode( tgtNode , /*isNodeDeleted=*/false );
2832 // set initial position which is parameters on _sWOL in this case
2833 if ( edge._sWOL.ShapeType() == TopAbs_EDGE )
2835 double u = helper.GetNodeU( TopoDS::Edge( edge._sWOL ), node, 0, &normOK );
2836 edge._pos.push_back( gp_XYZ( u, 0, 0 ));
2837 if ( edge._nodes.size() > 1 )
2838 getMeshDS()->SetNodeOnEdge( tgtNode, TopoDS::Edge( edge._sWOL ), u );
2842 gp_XY uv = helper.GetNodeUV( TopoDS::Face( edge._sWOL ), node, 0, &normOK );
2843 edge._pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
2844 if ( edge._nodes.size() > 1 )
2845 getMeshDS()->SetNodeOnFace( tgtNode, TopoDS::Face( edge._sWOL ), uv.X(), uv.Y() );
2850 edge._pos.push_back( SMESH_TNodeXYZ( node ));
2852 if ( posType == SMDS_TOP_FACE )
2854 _Simplex::GetSimplices( node, edge._simplices, data._ignoreFaceIds, &data );
2858 // Set neighbour nodes for a _LayerEdge based on EDGE
2860 if ( posType == SMDS_TOP_EDGE /*||
2861 ( onShrinkShape && posType == SMDS_TOP_VERTEX && fabs( edge._cosin ) < 1e-10 )*/)
2863 edge._2neibors = new _2NearEdges;
2864 // target node instead of source ones will be set later
2865 // if ( ! findNeiborsOnEdge( &edge,
2866 // edge._2neibors->_nodes[0],
2867 // edge._2neibors->_nodes[1],
2870 // edge.SetDataByNeighbors( edge._2neibors->_nodes[0],
2871 // edge._2neibors->_nodes[1],
2875 edge.SetCosin( edge._cosin ); // to update edge._lenFactor
2880 //================================================================================
2882 * \brief Return normal to a FACE at a node
2883 * \param [in] n - node
2884 * \param [in] face - FACE
2885 * \param [in] helper - helper
2886 * \param [out] isOK - true or false
2887 * \param [in] shiftInside - to find normal at a position shifted inside the face
2888 * \return gp_XYZ - normal
2890 //================================================================================
2892 gp_XYZ _ViscousBuilder::getFaceNormal(const SMDS_MeshNode* node,
2893 const TopoDS_Face& face,
2894 SMESH_MesherHelper& helper,
2901 // get a shifted position
2902 gp_Pnt p = SMESH_TNodeXYZ( node );
2903 gp_XYZ shift( 0,0,0 );
2904 TopoDS_Shape S = helper.GetSubShapeByNode( node, helper.GetMeshDS() );
2905 switch ( S.ShapeType() ) {
2908 shift = getFaceDir( face, TopoDS::Vertex( S ), node, helper, isOK );
2913 shift = getFaceDir( face, TopoDS::Edge( S ), node, helper, isOK );
2921 p.Translate( shift * 1e-5 );
2923 TopLoc_Location loc;
2924 GeomAPI_ProjectPointOnSurf& projector = helper.GetProjector( face, loc, 1e-7 );
2926 if ( !loc.IsIdentity() ) p.Transform( loc.Transformation().Inverted() );
2928 projector.Perform( p );
2929 if ( !projector.IsDone() || projector.NbPoints() < 1 )
2934 Quantity_Parameter U,V;
2935 projector.LowerDistanceParameters(U,V);
2940 uv = helper.GetNodeUV( face, node, 0, &isOK );
2946 Handle(Geom_Surface) surface = BRep_Tool::Surface( face );
2948 if ( !shiftInside &&
2949 helper.IsDegenShape( node->getshapeId() ) &&
2950 getFaceNormalAtSingularity( uv, face, helper, normal ))
2953 return normal.XYZ();
2956 int pointKind = GeomLib::NormEstim( surface, uv, 1e-5, normal );
2957 enum { REGULAR = 0, QUASYSINGULAR, CONICAL, IMPOSSIBLE };
2959 if ( pointKind == IMPOSSIBLE &&
2960 node->GetPosition()->GetDim() == 2 ) // node inside the FACE
2962 // probably NormEstim() failed due to a too high tolerance
2963 pointKind = GeomLib::NormEstim( surface, uv, 1e-20, normal );
2964 isOK = ( pointKind < IMPOSSIBLE );
2966 if ( pointKind < IMPOSSIBLE )
2968 if ( pointKind != REGULAR &&
2970 node->GetPosition()->GetDim() < 2 ) // FACE boundary
2972 gp_XYZ normShift = getFaceNormal( node, face, helper, isOK, /*shiftInside=*/true );
2973 if ( normShift * normal.XYZ() < 0. )
2979 if ( !isOK ) // hard singularity, to call with shiftInside=true ?
2981 const TGeomID faceID = helper.GetMeshDS()->ShapeToIndex( face );
2983 SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
2984 while ( fIt->more() )
2986 const SMDS_MeshElement* f = fIt->next();
2987 if ( f->getshapeId() == faceID )
2989 isOK = SMESH_MeshAlgos::FaceNormal( f, (gp_XYZ&) normal.XYZ(), /*normalized=*/true );
2992 TopoDS_Face ff = face;
2993 ff.Orientation( TopAbs_FORWARD );
2994 if ( helper.IsReversedSubMesh( ff ))
3001 return normal.XYZ();
3004 //================================================================================
3006 * \brief Try to get normal at a singularity of a surface basing on it's nature
3008 //================================================================================
3010 bool _ViscousBuilder::getFaceNormalAtSingularity( const gp_XY& uv,
3011 const TopoDS_Face& face,
3012 SMESH_MesherHelper& helper,
3015 BRepAdaptor_Surface surface( face );
3017 if ( !getRovolutionAxis( surface, axis ))
3020 double f,l, d, du, dv;
3021 f = surface.FirstUParameter();
3022 l = surface.LastUParameter();
3023 d = ( uv.X() - f ) / ( l - f );
3024 du = ( d < 0.5 ? +1. : -1 ) * 1e-5 * ( l - f );
3025 f = surface.FirstVParameter();
3026 l = surface.LastVParameter();
3027 d = ( uv.Y() - f ) / ( l - f );
3028 dv = ( d < 0.5 ? +1. : -1 ) * 1e-5 * ( l - f );
3031 gp_Pnt2d testUV = uv;
3032 enum { REGULAR = 0, QUASYSINGULAR, CONICAL, IMPOSSIBLE };
3034 Handle(Geom_Surface) geomsurf = surface.Surface().Surface();
3035 for ( int iLoop = 0; true ; ++iLoop )
3037 testUV.SetCoord( testUV.X() + du, testUV.Y() + dv );
3038 if ( GeomLib::NormEstim( geomsurf, testUV, tol, refDir ) == REGULAR )
3045 if ( axis * refDir < 0. )
3053 //================================================================================
3055 * \brief Return a normal at a node weighted with angles taken by FACEs
3056 * \param [in] n - the node
3057 * \param [in] fId2Normal - FACE ids and normals
3058 * \param [in] nbFaces - nb of FACEs meeting at the node
3059 * \return gp_XYZ - computed normal
3061 //================================================================================
3063 gp_XYZ _ViscousBuilder::getWeigthedNormal( const SMDS_MeshNode* n,
3064 std::pair< TopoDS_Face, gp_XYZ > fId2Normal[],
3067 gp_XYZ resNorm(0,0,0);
3068 TopoDS_Shape V = SMESH_MesherHelper::GetSubShapeByNode( n, getMeshDS() );
3069 if ( V.ShapeType() != TopAbs_VERTEX )
3071 for ( int i = 0; i < nbFaces; ++i )
3072 resNorm += fId2Normal[i].second;
3076 // exclude equal normals
3077 //int nbUniqNorms = nbFaces;
3078 for ( int i = 0; i < nbFaces; ++i )
3079 for ( int j = i+1; j < nbFaces; ++j )
3080 if ( fId2Normal[i].second.IsEqual( fId2Normal[j].second, 0.1 ))
3082 fId2Normal[i].second.SetCoord( 0,0,0 );
3086 //if ( nbUniqNorms < 3 )
3088 for ( int i = 0; i < nbFaces; ++i )
3089 resNorm += fId2Normal[i].second;
3094 for ( int i = 0; i < nbFaces; ++i )
3096 const TopoDS_Face& F = fId2Normal[i].first;
3098 // look for two EDGEs shared by F and other FACEs within fId2Normal
3101 PShapeIteratorPtr eIt = SMESH_MesherHelper::GetAncestors( V, *_mesh, TopAbs_EDGE );
3102 while ( const TopoDS_Shape* E = eIt->next() )
3104 if ( !SMESH_MesherHelper::IsSubShape( *E, F ))
3106 bool isSharedEdge = false;
3107 for ( int j = 0; j < nbFaces && !isSharedEdge; ++j )
3109 if ( i == j ) continue;
3110 const TopoDS_Shape& otherF = fId2Normal[j].first;
3111 isSharedEdge = SMESH_MesherHelper::IsSubShape( *E, otherF );
3113 if ( !isSharedEdge )
3115 ee[ nbE ] = TopoDS::Edge( *E );
3116 ee[ nbE ].Orientation( SMESH_MesherHelper::GetSubShapeOri( F, *E ));
3121 // get an angle between the two EDGEs
3123 if ( nbE < 1 ) continue;
3130 if ( !V.IsSame( SMESH_MesherHelper::IthVertex( 0, ee[ 1 ] )))
3131 std::swap( ee[0], ee[1] );
3133 angles[i] = SMESH_MesherHelper::GetAngle( ee[0], ee[1], F, TopoDS::Vertex( V ));
3136 // compute a weighted normal
3137 double sumAngle = 0;
3138 for ( int i = 0; i < nbFaces; ++i )
3140 angles[i] = ( angles[i] > 2*M_PI ) ? 0 : M_PI - angles[i];
3141 sumAngle += angles[i];
3143 for ( int i = 0; i < nbFaces; ++i )
3144 resNorm += angles[i] / sumAngle * fId2Normal[i].second;
3149 //================================================================================
3151 * \brief Find 2 neigbor nodes of a node on EDGE
3153 //================================================================================
3155 bool _ViscousBuilder::findNeiborsOnEdge(const _LayerEdge* edge,
3156 const SMDS_MeshNode*& n1,
3157 const SMDS_MeshNode*& n2,
3160 const SMDS_MeshNode* node = edge->_nodes[0];
3161 const int shapeInd = node->getshapeId();
3162 SMESHDS_SubMesh* edgeSM = 0;
3163 if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_EDGE )
3165 edgeSM = getMeshDS()->MeshElements( shapeInd );
3166 if ( !edgeSM || edgeSM->NbElements() == 0 )
3167 return error(SMESH_Comment("Not meshed EDGE ") << shapeInd, data._index);
3171 SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator(SMDSAbs_Edge);
3172 while ( eIt->more() && !n2 )
3174 const SMDS_MeshElement* e = eIt->next();
3175 const SMDS_MeshNode* nNeibor = e->GetNode( 0 );
3176 if ( nNeibor == node ) nNeibor = e->GetNode( 1 );
3179 if (!edgeSM->Contains(e)) continue;
3183 TopoDS_Shape s = SMESH_MesherHelper::GetSubShapeByNode(nNeibor, getMeshDS() );
3184 if ( !SMESH_MesherHelper::IsSubShape( s, edge->_sWOL )) continue;
3186 ( iN++ ? n2 : n1 ) = nNeibor;
3189 return error(SMESH_Comment("Wrongly meshed EDGE ") << shapeInd, data._index);
3193 //================================================================================
3195 * \brief Set _curvature and _2neibors->_plnNorm by 2 neigbor nodes residing the same EDGE
3197 //================================================================================
3199 void _LayerEdge::SetDataByNeighbors( const SMDS_MeshNode* n1,
3200 const SMDS_MeshNode* n2,
3201 SMESH_MesherHelper& helper)
3203 if ( _nodes[0]->GetPosition()->GetTypeOfPosition() != SMDS_TOP_EDGE )
3206 gp_XYZ pos = SMESH_TNodeXYZ( _nodes[0] );
3207 gp_XYZ vec1 = pos - SMESH_TNodeXYZ( n1 );
3208 gp_XYZ vec2 = pos - SMESH_TNodeXYZ( n2 );
3212 double sumLen = vec1.Modulus() + vec2.Modulus();
3213 _2neibors->_wgt[0] = 1 - vec1.Modulus() / sumLen;
3214 _2neibors->_wgt[1] = 1 - vec2.Modulus() / sumLen;
3215 double avgNormProj = 0.5 * ( _normal * vec1 + _normal * vec2 );
3216 double avgLen = 0.5 * ( vec1.Modulus() + vec2.Modulus() );
3217 if ( _curvature ) delete _curvature;
3218 _curvature = _Curvature::New( avgNormProj, avgLen );
3219 // if ( _curvature )
3220 // debugMsg( _nodes[0]->GetID()
3221 // << " CURV r,k: " << _curvature->_r<<","<<_curvature->_k
3222 // << " proj = "<<avgNormProj<< " len = " << avgLen << "| lenDelta(0) = "
3223 // << _curvature->lenDelta(0) );
3227 if ( _sWOL.IsNull() )
3229 TopoDS_Shape S = helper.GetSubShapeByNode( _nodes[0], helper.GetMeshDS() );
3230 TopoDS_Edge E = TopoDS::Edge( S );
3231 // if ( SMESH_Algo::isDegenerated( E ))
3233 gp_XYZ dirE = getEdgeDir( E, _nodes[0], helper );
3234 gp_XYZ plnNorm = dirE ^ _normal;
3235 double proj0 = plnNorm * vec1;
3236 double proj1 = plnNorm * vec2;
3237 if ( fabs( proj0 ) > 1e-10 || fabs( proj1 ) > 1e-10 )
3239 if ( _2neibors->_plnNorm ) delete _2neibors->_plnNorm;
3240 _2neibors->_plnNorm = new gp_XYZ( plnNorm.Normalized() );
3245 //================================================================================
3247 * \brief Copy data from a _LayerEdge of other SOLID and based on the same node;
3248 * this and other _LayerEdge's are inflated along a FACE or an EDGE
3250 //================================================================================
3252 gp_XYZ _LayerEdge::Copy( _LayerEdge& other, SMESH_MesherHelper& helper )
3254 _nodes = other._nodes;
3255 _normal = other._normal;
3257 _lenFactor = other._lenFactor;
3258 _cosin = other._cosin;
3259 _sWOL = other._sWOL;
3260 _2neibors = other._2neibors;
3261 _curvature = 0; std::swap( _curvature, other._curvature );
3262 _2neibors = 0; std::swap( _2neibors, other._2neibors );
3264 gp_XYZ lastPos( 0,0,0 );
3265 if ( _sWOL.ShapeType() == TopAbs_EDGE )
3267 double u = helper.GetNodeU( TopoDS::Edge( _sWOL ), _nodes[0] );
3268 _pos.push_back( gp_XYZ( u, 0, 0));
3270 u = helper.GetNodeU( TopoDS::Edge( _sWOL ), _nodes.back() );
3275 gp_XY uv = helper.GetNodeUV( TopoDS::Face( _sWOL ), _nodes[0]);
3276 _pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
3278 uv = helper.GetNodeUV( TopoDS::Face( _sWOL ), _nodes.back() );
3279 lastPos.SetX( uv.X() );
3280 lastPos.SetY( uv.Y() );
3285 //================================================================================
3287 * \brief Set _cosin and _lenFactor
3289 //================================================================================
3291 void _LayerEdge::SetCosin( double cosin )
3294 cosin = Abs( _cosin );
3295 _lenFactor = ( /*0.1 < cosin &&*/ cosin < 1-1e-12 ) ? 1./sqrt(1-cosin*cosin) : 1.0;
3298 //================================================================================
3300 * \brief Fills a vector<_Simplex >
3302 //================================================================================
3304 void _Simplex::GetSimplices( const SMDS_MeshNode* node,
3305 vector<_Simplex>& simplices,
3306 const set<TGeomID>& ingnoreShapes,
3307 const _SolidData* dataToCheckOri,
3311 SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
3312 while ( fIt->more() )
3314 const SMDS_MeshElement* f = fIt->next();
3315 const TGeomID shapeInd = f->getshapeId();
3316 if ( ingnoreShapes.count( shapeInd )) continue;
3317 const int nbNodes = f->NbCornerNodes();
3318 const int srcInd = f->GetNodeIndex( node );
3319 const SMDS_MeshNode* nPrev = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd-1, nbNodes ));
3320 const SMDS_MeshNode* nNext = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+1, nbNodes ));
3321 const SMDS_MeshNode* nOpp = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+2, nbNodes ));
3322 if ( dataToCheckOri && dataToCheckOri->_reversedFaceIds.count( shapeInd ))
3323 std::swap( nPrev, nNext );
3324 simplices.push_back( _Simplex( nPrev, nNext, nOpp ));
3328 SortSimplices( simplices );
3331 //================================================================================
3333 * \brief Set neighbor simplices side by side
3335 //================================================================================
3337 void _Simplex::SortSimplices(vector<_Simplex>& simplices)
3339 vector<_Simplex> sortedSimplices( simplices.size() );
3340 sortedSimplices[0] = simplices[0];
3342 for ( size_t i = 1; i < simplices.size(); ++i )
3344 for ( size_t j = 1; j < simplices.size(); ++j )
3345 if ( sortedSimplices[i-1]._nNext == simplices[j]._nPrev )
3347 sortedSimplices[i] = simplices[j];
3352 if ( nbFound == simplices.size() - 1 )
3353 simplices.swap( sortedSimplices );
3356 //================================================================================
3358 * \brief DEBUG. Create groups contating temorary data of _LayerEdge's
3360 //================================================================================
3362 void _ViscousBuilder::makeGroupOfLE()
3365 for ( size_t i = 0 ; i < _sdVec.size(); ++i )
3367 if ( _sdVec[i]._edges.empty() ) continue;
3369 dumpFunction( SMESH_Comment("make_LayerEdge_") << i );
3370 for ( size_t j = 0 ; j < _sdVec[i]._edges.size(); ++j )
3372 _LayerEdge* le = _sdVec[i]._edges[j];
3373 for ( size_t iN = 1; iN < le->_nodes.size(); ++iN )
3374 dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<le->_nodes[iN-1]->GetID()
3375 << ", " << le->_nodes[iN]->GetID() <<"])");
3379 dumpFunction( SMESH_Comment("makeNormals") << i );
3380 for ( size_t j = 0 ; j < _sdVec[i]._edges.size(); ++j )
3382 _LayerEdge& edge = *_sdVec[i]._edges[j];
3383 SMESH_TNodeXYZ nXYZ( edge._nodes[0] );
3384 nXYZ += edge._normal * _sdVec[i]._stepSize;
3385 dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<edge._nodes[0]->GetID()
3386 << ", mesh.AddNode( " << nXYZ.X()<<","<< nXYZ.Y()<<","<< nXYZ.Z()<<")])");
3390 dumpFunction( SMESH_Comment("makeTmpFaces_") << i );
3391 dumpCmd( "faceId1 = mesh.NbElements()" );
3392 TopExp_Explorer fExp( _sdVec[i]._solid, TopAbs_FACE );
3393 for ( ; fExp.More(); fExp.Next() )
3395 if (const SMESHDS_SubMesh* sm = _sdVec[i]._proxyMesh->GetProxySubMesh( fExp.Current()))
3397 if ( sm->NbElements() == 0 ) continue;
3398 SMDS_ElemIteratorPtr fIt = sm->GetElements();
3399 while ( fIt->more())
3401 const SMDS_MeshElement* e = fIt->next();
3402 SMESH_Comment cmd("mesh.AddFace([");
3403 for ( int j=0; j < e->NbCornerNodes(); ++j )
3404 cmd << e->GetNode(j)->GetID() << (j+1<e->NbCornerNodes() ? ",": "])");
3409 dumpCmd( "faceId2 = mesh.NbElements()" );
3410 dumpCmd( SMESH_Comment( "mesh.MakeGroup( 'tmpFaces_" ) << i << "',"
3411 << "SMESH.FACE, SMESH.FT_RangeOfIds,'=',"
3412 << "'%s-%s' % (faceId1+1, faceId2))");
3418 //================================================================================
3420 * \brief Find maximal _LayerEdge length (layer thickness) limited by geometry
3422 //================================================================================
3424 void _ViscousBuilder::computeGeomSize( _SolidData& data )
3426 data._geomSize = Precision::Infinite();
3427 double intersecDist;
3428 auto_ptr<SMESH_ElementSearcher> searcher
3429 ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(),
3430 data._proxyMesh->GetFaces( data._solid )) );
3432 TNode2Edge::iterator n2e = data._n2eMap.begin(), n2eEnd = data._n2eMap.end();
3433 for ( ; n2e != n2eEnd; ++n2e )
3435 _LayerEdge* edge = n2e->second;
3436 if ( edge->IsOnEdge() ) continue;
3437 edge->FindIntersection( *searcher, intersecDist, data._epsilon );
3438 if ( data._geomSize > intersecDist && intersecDist > 0 )
3439 data._geomSize = intersecDist;
3443 //================================================================================
3445 * \brief Increase length of _LayerEdge's to reach the required thickness of layers
3447 //================================================================================
3449 bool _ViscousBuilder::inflate(_SolidData& data)
3451 SMESH_MesherHelper helper( *_mesh );
3453 // Limit inflation step size by geometry size found by itersecting
3454 // normals of _LayerEdge's with mesh faces
3455 if ( data._stepSize > 0.3 * data._geomSize )
3456 limitStepSize( data, 0.3 * data._geomSize );
3458 const double tgtThick = data._maxThickness;
3459 if ( data._stepSize > data._minThickness )
3460 limitStepSize( data, data._minThickness );
3462 if ( data._stepSize < 1. )
3463 data._epsilon = data._stepSize * 1e-7;
3465 debugMsg( "-- geomSize = " << data._geomSize << ", stepSize = " << data._stepSize );
3467 const double safeFactor = ( 2*data._maxThickness < data._geomSize ) ? 1 : theThickToIntersection;
3469 double avgThick = 0, curThick = 0, distToIntersection = Precision::Infinite();
3470 int nbSteps = 0, nbRepeats = 0;
3472 while ( avgThick < 0.99 )
3474 // new target length
3475 curThick += data._stepSize;
3476 if ( curThick > tgtThick )
3478 curThick = tgtThick + tgtThick*( 1.-avgThick ) * nbRepeats;
3482 // Elongate _LayerEdge's
3483 dumpFunction(SMESH_Comment("inflate")<<data._index<<"_step"<<nbSteps); // debug
3484 for ( iBeg = 0, iS = 0; iS < data._endEdgeOnShape.size(); ++iS )
3486 const double shapeCurThick = Min( curThick, data._hypOnShape[ iS ].GetTotalThickness() );
3487 for ( iEnd = data._endEdgeOnShape[ iS ]; iBeg < iEnd; ++iBeg )
3489 data._edges[iBeg]->SetNewLength( shapeCurThick, helper );
3494 if ( !updateNormals( data, helper, nbSteps ))
3497 // Improve and check quality
3498 if ( !smoothAndCheck( data, nbSteps, distToIntersection ))
3502 #ifdef __NOT_INVALIDATE_BAD_SMOOTH
3503 debugMsg("NOT INVALIDATED STEP!");
3504 return error("Smoothing failed", data._index);
3506 dumpFunction(SMESH_Comment("invalidate")<<data._index<<"_step"<<nbSteps); // debug
3507 for ( size_t i = 0; i < data._edges.size(); ++i )
3509 data._edges[i]->InvalidateStep( nbSteps+1 );
3513 break; // no more inflating possible
3517 // Evaluate achieved thickness
3519 for ( iBeg = 0, iS = 0; iS < data._endEdgeOnShape.size(); ++iS )
3521 const double shapeTgtThick = data._hypOnShape[ iS ].GetTotalThickness();
3522 for ( iEnd = data._endEdgeOnShape[ iS ]; iBeg < iEnd; ++iBeg )
3524 avgThick += Min( 1., data._edges[iBeg]->_len / shapeTgtThick );
3527 avgThick /= data._edges.size();
3528 debugMsg( "-- Thickness " << curThick << " ("<< avgThick*100 << "%) reached" );
3530 if ( distToIntersection < tgtThick * avgThick * safeFactor && avgThick < 0.9 )
3532 debugMsg( "-- Stop inflation since "
3533 << " distToIntersection( "<<distToIntersection<<" ) < avgThick( "
3534 << tgtThick * avgThick << " ) * " << safeFactor );
3538 limitStepSize( data, 0.25 * distToIntersection );
3539 if ( data._stepSizeNodes[0] )
3540 data._stepSize = data._stepSizeCoeff *
3541 SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
3543 } // while ( avgThick < 0.99 )
3546 return error("failed at the very first inflation step", data._index);
3548 if ( avgThick < 0.99 )
3550 if ( !data._proxyMesh->_warning || data._proxyMesh->_warning->IsOK() )
3552 data._proxyMesh->_warning.reset
3553 ( new SMESH_ComputeError (COMPERR_WARNING,
3554 SMESH_Comment("Thickness ") << tgtThick <<
3555 " of viscous layers not reached,"
3556 " average reached thickness is " << avgThick*tgtThick));
3560 // Restore position of src nodes moved by infaltion on _noShrinkShapes
3561 dumpFunction(SMESH_Comment("restoNoShrink_So")<<data._index); // debug
3562 for ( iEnd = iS = 0; iS < data._endEdgeOnShape.size(); ++iS )
3565 iEnd = data._endEdgeOnShape[ iS ];
3566 if ( data._edges[ iBeg ]->_nodes.size() == 1 )
3567 for ( ; iBeg < iEnd; ++iBeg )
3569 restoreNoShrink( *data._edges[ iBeg ] );
3577 //================================================================================
3579 * \brief Improve quality of layer inner surface and check intersection
3581 //================================================================================
3583 bool _ViscousBuilder::smoothAndCheck(_SolidData& data,
3585 double & distToIntersection)
3587 if ( data._nbShapesToSmooth == 0 )
3588 return true; // no shapes needing smoothing
3590 bool moved, improved;
3591 vector< _LayerEdge* > badSmooEdges;
3593 SMESH_MesherHelper helper(*_mesh);
3594 Handle(Geom_Surface) surface;
3598 for ( int iS = 0; iS < data._nbShapesToSmooth; ++iS )
3601 iEnd = data._endEdgeOnShape[ iS ];
3603 // need to smooth this shape?
3604 bool toSmooth = ( data._hyps.front() == data._hyps.back() );
3605 for ( int i = iBeg; i < iEnd && !toSmooth; ++i )
3606 toSmooth = ( data._edges[ iBeg ]->NbSteps() >= nbSteps+1 );
3609 if ( iS+1 == data._nbShapesToSmooth )
3610 data._nbShapesToSmooth--;
3611 continue; // target length reached some steps before
3615 if ( !data._edges[ iBeg ]->_sWOL.IsNull() &&
3616 data._edges[ iBeg ]->_sWOL.ShapeType() == TopAbs_FACE )
3618 if ( !F.IsSame( data._edges[ iBeg ]->_sWOL )) {
3619 F = TopoDS::Face( data._edges[ iBeg ]->_sWOL );
3620 helper.SetSubShape( F );
3621 surface = BRep_Tool::Surface( F );
3626 F.Nullify(); surface.Nullify();
3628 const TGeomID sInd = data._edges[ iBeg ]->_nodes[0]->getshapeId();
3630 // perform smoothing
3632 if ( data._edges[ iBeg ]->IsOnEdge() )
3634 dumpFunction(SMESH_Comment("smooth")<<data._index << "_Ed"<<sInd <<"_InfStep"<<nbSteps);
3636 // try a simple solution on an analytic EDGE
3637 if ( !smoothAnalyticEdge( data, iBeg, iEnd, surface, F, helper ))
3643 for ( int i = iBeg; i < iEnd; ++i )
3645 moved |= data._edges[i]->SmoothOnEdge(surface, F, helper);
3647 dumpCmd( SMESH_Comment("# end step ")<<step);
3649 while ( moved && step++ < 5 );
3657 const bool isConcaveFace = data._concaveFaces.count( sInd );
3659 int step = 0, stepLimit = 5, badNb = 0;
3660 while (( ++step <= stepLimit ) || improved )
3662 dumpFunction(SMESH_Comment("smooth")<<data._index<<"_Fa"<<sInd
3663 <<"_InfStep"<<nbSteps<<"_"<<step); // debug
3664 int oldBadNb = badNb;
3665 badSmooEdges.clear();
3668 for ( int i = iBeg; i < iEnd; ++i ) // iterate forward
3669 if ( data._edges[i]->Smooth( step, isConcaveFace, false ))
3670 badSmooEdges.push_back( data._edges[i] );
3673 for ( int i = iEnd-1; i >= iBeg; --i ) // iterate backward
3674 if ( data._edges[i]->Smooth( step, isConcaveFace, false ))
3675 badSmooEdges.push_back( data._edges[i] );
3677 badNb = badSmooEdges.size();
3678 improved = ( badNb < oldBadNb );
3680 if ( !badSmooEdges.empty() && step >= stepLimit / 2 )
3682 // look for the best smooth of _LayerEdge's neighboring badSmooEdges
3683 vector<_Simplex> simplices;
3684 for ( size_t i = 0; i < badSmooEdges.size(); ++i )
3686 _LayerEdge* ledge = badSmooEdges[i];
3687 _Simplex::GetSimplices( ledge->_nodes[0], simplices, data._ignoreFaceIds );
3688 for ( size_t iS = 0; iS < simplices.size(); ++iS )
3690 TNode2Edge::iterator n2e = data._n2eMap.find( simplices[iS]._nNext );
3691 if ( n2e != data._n2eMap.end()) {
3692 _LayerEdge* ledge2 = n2e->second;
3693 if ( ledge2->_nodes[0]->getshapeId() == sInd )
3694 ledge2->Smooth( step, isConcaveFace, /*findBest=*/true );
3699 // issue 22576 -- no bad faces but still there are intersections to fix
3700 // if ( improved && badNb == 0 )
3701 // stepLimit = step + 3;
3709 for ( int i = iBeg; i < iEnd; ++i )
3711 _LayerEdge* edge = data._edges[i];
3712 SMESH_TNodeXYZ tgtXYZ( edge->_nodes.back() );
3713 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
3714 if ( !edge->_simplices[j].IsForward( edge->_nodes[0], &tgtXYZ, vol ))
3716 cout << "Bad simplex ( " << edge->_nodes[0]->GetID()<< " "<< tgtXYZ._node->GetID()
3717 << " "<< edge->_simplices[j]._nPrev->GetID()
3718 << " "<< edge->_simplices[j]._nNext->GetID() << " )" << endl;
3726 } // loop on shapes to smooth
3728 // Check orientation of simplices of _ConvexFace::_simplexTestEdges
3729 map< TGeomID, _ConvexFace >::iterator id2face = data._convexFaces.begin();
3730 for ( ; id2face != data._convexFaces.end(); ++id2face )
3732 _ConvexFace & convFace = (*id2face).second;
3733 if ( !convFace._simplexTestEdges.empty() &&
3734 convFace._simplexTestEdges[0]->_nodes[0]->GetPosition()->GetDim() == 2 )
3735 continue; // _simplexTestEdges are based on FACE -- already checked while smoothing
3737 if ( !convFace.CheckPrisms() )
3741 // Check if the last segments of _LayerEdge intersects 2D elements;
3742 // checked elements are either temporary faces or faces on surfaces w/o the layers
3744 auto_ptr<SMESH_ElementSearcher> searcher
3745 ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(),
3746 data._proxyMesh->GetFaces( data._solid )) );
3748 distToIntersection = Precision::Infinite();
3750 const SMDS_MeshElement* intFace = 0;
3751 const SMDS_MeshElement* closestFace = 0;
3753 for ( size_t i = 0; i < data._edges.size(); ++i )
3755 if ( !data._edges[i]->_sWOL.IsNull() )
3757 if ( data._edges[i]->FindIntersection( *searcher, dist, data._epsilon, &intFace ))
3759 if ( distToIntersection > dist )
3761 // ignore intersection of a _LayerEdge based on a _ConvexFace with a face
3762 // lying on this _ConvexFace
3763 if ( _ConvexFace* convFace = data.GetConvexFace( intFace->getshapeId() ))
3764 if ( convFace->_subIdToEdgeEnd.count ( data._edges[i]->_nodes[0]->getshapeId() ))
3767 // ignore intersection of a _LayerEdge based on a FACE with an element on this FACE
3768 // ( avoid limiting the thickness on the case of issue 22576)
3769 if ( intFace->getshapeId() == data._edges[i]->_nodes[0]->getshapeId() )
3772 distToIntersection = dist;
3774 closestFace = intFace;
3780 SMDS_MeshElement::iterator nIt = closestFace->begin_nodes();
3781 cout << "Shortest distance: _LayerEdge nodes: tgt " << data._edges[iLE]->_nodes.back()->GetID()
3782 << " src " << data._edges[iLE]->_nodes[0]->GetID()<< ", intersection with face ("
3783 << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
3784 << ") distance = " << distToIntersection<< endl;
3791 //================================================================================
3793 * \brief Return a curve of the EDGE to be used for smoothing and arrange
3794 * _LayerEdge's to be in a consequent order
3796 //================================================================================
3798 Handle(Geom_Curve) _SolidData::CurveForSmooth( const TopoDS_Edge& E,
3801 const TopoDS_Face& F,
3802 SMESH_MesherHelper& helper,
3803 vector<_LayerEdge* >* edges)
3805 TGeomID eIndex = helper.GetMeshDS()->ShapeToIndex( E );
3807 map< TGeomID, Handle(Geom_Curve)>::iterator i2curve = _edge2curve.find( eIndex );
3809 if ( i2curve == _edge2curve.end() )
3812 _edges.swap( *edges );
3814 // sort _LayerEdge's by position on the EDGE
3815 SortOnEdge( E, iFrom, iTo, helper );
3817 SMESHDS_SubMesh* smDS = helper.GetMeshDS()->MeshElements( eIndex );
3819 TopLoc_Location loc; double f,l;
3821 Handle(Geom_Line) line;
3822 Handle(Geom_Circle) circle;
3823 bool isLine, isCirc;
3824 if ( F.IsNull() ) // 3D case
3826 // check if the EDGE is a line
3827 Handle(Geom_Curve) curve = BRep_Tool::Curve( E, loc, f, l);
3828 if ( curve->IsKind( STANDARD_TYPE( Geom_TrimmedCurve )))
3829 curve = Handle(Geom_TrimmedCurve)::DownCast( curve )->BasisCurve();
3831 line = Handle(Geom_Line)::DownCast( curve );
3832 circle = Handle(Geom_Circle)::DownCast( curve );
3833 isLine = (!line.IsNull());
3834 isCirc = (!circle.IsNull());
3836 if ( !isLine && !isCirc ) // Check if the EDGE is close to a line
3839 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
3840 while ( nIt->more() )
3841 bndBox.Add( SMESH_TNodeXYZ( nIt->next() ));
3842 gp_XYZ size = bndBox.CornerMax() - bndBox.CornerMin();
3845 if ( iTo-iFrom > 1 ) {
3846 p0 = SMESH_TNodeXYZ( _edges[iFrom]->_nodes[0] );
3847 p1 = SMESH_TNodeXYZ( _edges[iFrom+1]->_nodes[0] );
3850 p0 = curve->Value( f );
3851 p1 = curve->Value( l );
3853 const double lineTol = 1e-2 * p0.Distance( p1 );
3854 for ( int i = 0; i < 3 && !isLine; ++i )
3855 isLine = ( size.Coord( i+1 ) <= lineTol );
3858 line = new Geom_Line( gp::OX() ); // only type does matter
3860 if ( !isLine && !isCirc && iTo-iFrom > 2) // Check if the EDGE is close to a circle
3867 // check if the EDGE is a line
3868 Handle(Geom2d_Curve) curve = BRep_Tool::CurveOnSurface( E, F, f, l);
3869 if ( curve->IsKind( STANDARD_TYPE( Geom2d_TrimmedCurve )))
3870 curve = Handle(Geom2d_TrimmedCurve)::DownCast( curve )->BasisCurve();
3872 Handle(Geom2d_Line) line2d = Handle(Geom2d_Line)::DownCast( curve );
3873 Handle(Geom2d_Circle) circle2d = Handle(Geom2d_Circle)::DownCast( curve );
3874 isLine = (!line2d.IsNull());
3875 isCirc = (!circle2d.IsNull());
3877 if ( !isLine && !isCirc) // Check if the EDGE is close to a line
3880 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
3881 while ( nIt->more() )
3882 bndBox.Add( helper.GetNodeUV( F, nIt->next() ));
3883 gp_XY size = bndBox.CornerMax() - bndBox.CornerMin();
3885 const double lineTol = 1e-2 * sqrt( bndBox.SquareExtent() );
3886 for ( int i = 0; i < 2 && !isLine; ++i )
3887 isLine = ( size.Coord( i+1 ) <= lineTol );
3889 if ( !isLine && !isCirc && iTo-iFrom > 2) // Check if the EDGE is close to a circle
3895 line = new Geom_Line( gp::OX() ); // only type does matter
3899 gp_Pnt2d p = circle2d->Location();
3900 gp_Ax2 ax( gp_Pnt( p.X(), p.Y(), 0), gp::DX());
3901 circle = new Geom_Circle( ax, 1.); // only center position does matter
3906 _edges.swap( *edges );
3908 Handle(Geom_Curve)& res = _edge2curve[ eIndex ];
3916 return i2curve->second;
3919 //================================================================================
3921 * \brief Sort _LayerEdge's by a parameter on a given EDGE
3923 //================================================================================
3925 void _SolidData::SortOnEdge( const TopoDS_Edge& E,
3928 SMESH_MesherHelper& helper)
3930 map< double, _LayerEdge* > u2edge;
3931 for ( int i = iFrom; i < iTo; ++i )
3932 u2edge.insert( make_pair( helper.GetNodeU( E, _edges[i]->_nodes[0] ), _edges[i] ));
3934 ASSERT( u2edge.size() == iTo - iFrom );
3935 map< double, _LayerEdge* >::iterator u2e = u2edge.begin();
3936 for ( int i = iFrom; i < iTo; ++i, ++u2e )
3937 _edges[i] = u2e->second;
3939 Sort2NeiborsOnEdge( iFrom, iTo );
3942 //================================================================================
3944 * \brief Set _2neibors according to the order of _LayerEdge on EDGE
3946 //================================================================================
3948 void _SolidData::Sort2NeiborsOnEdge( const int iFrom, const int iTo)
3950 for ( int i = iFrom; i < iTo-1; ++i )
3951 if ( _edges[i]->_2neibors->tgtNode(1) != _edges[i+1]->_nodes.back() )
3952 _edges[i]->_2neibors->reverse();
3953 if ( iTo - iFrom > 1 &&
3954 _edges[iTo-1]->_2neibors->tgtNode(0) != _edges[iTo-2]->_nodes.back() )
3955 _edges[iTo-1]->_2neibors->reverse();
3958 //================================================================================
3960 * \brief Return index corresponding to the shape in _endEdgeOnShape
3962 //================================================================================
3964 bool _SolidData::GetShapeEdges(const TGeomID shapeID,
3969 int beg = 0, end = 0;
3970 for ( iEdgesEnd = 0; iEdgesEnd < _endEdgeOnShape.size(); ++iEdgesEnd )
3972 end = _endEdgeOnShape[ iEdgesEnd ];
3973 TGeomID sID = _edges[ beg ]->_nodes[0]->getshapeId();
3974 if ( sID == shapeID )
3976 if ( iBeg ) *iBeg = beg;
3977 if ( iEnd ) *iEnd = end;
3985 //================================================================================
3987 * \brief Prepare data of the _LayerEdge for smoothing on FACE
3989 //================================================================================
3991 void _SolidData::PrepareEdgesToSmoothOnFace( _LayerEdge** edgeBeg,
3992 _LayerEdge** edgeEnd,
3993 const TopoDS_Face& face,
3994 bool substituteSrcNodes )
3996 set< TGeomID > vertices;
3997 SMESH_MesherHelper helper( *_proxyMesh->GetMesh() );
3998 if ( isConcave( face, helper, &vertices ))
3999 _concaveFaces.insert( (*edgeBeg)->_nodes[0]->getshapeId() );
4001 for ( _LayerEdge** edge = edgeBeg; edge != edgeEnd; ++edge )
4002 (*edge)->_smooFunction = 0;
4004 for ( ; edgeBeg != edgeEnd; ++edgeBeg )
4006 _LayerEdge* edge = *edgeBeg;
4007 _Simplex::GetSimplices
4008 ( edge->_nodes[0], edge->_simplices, _ignoreFaceIds, this, /*sort=*/true );
4010 edge->ChooseSmooFunction( vertices, _n2eMap );
4012 double avgNormProj = 0, avgLen = 0;
4013 for ( size_t i = 0; i < edge->_simplices.size(); ++i )
4015 _Simplex& s = edge->_simplices[i];
4017 gp_XYZ vec = edge->_pos.back() - SMESH_TNodeXYZ( s._nPrev );
4018 avgNormProj += edge->_normal * vec;
4019 avgLen += vec.Modulus();
4020 if ( substituteSrcNodes )
4022 s._nNext = _n2eMap[ s._nNext ]->_nodes.back();
4023 s._nPrev = _n2eMap[ s._nPrev ]->_nodes.back();
4026 avgNormProj /= edge->_simplices.size();
4027 avgLen /= edge->_simplices.size();
4028 edge->_curvature = _Curvature::New( avgNormProj, avgLen );
4032 //================================================================================
4034 * \brief Add faces for smoothing
4036 //================================================================================
4038 void _SolidData::AddShapesToSmooth( const set< TGeomID >& faceIDs )
4040 // convert faceIDs to indices in _endEdgeOnShape
4041 set< size_t > iEnds;
4043 set< TGeomID >::const_iterator fId = faceIDs.begin();
4044 for ( ; fId != faceIDs.end(); ++fId )
4045 if ( GetShapeEdges( *fId, end ) && end >= _nbShapesToSmooth )
4046 iEnds.insert( end );
4048 set< size_t >::iterator endsIt = iEnds.begin();
4050 // "add" by move of _nbShapesToSmooth
4051 int nbFacesToAdd = iEnds.size();
4052 while ( endsIt != iEnds.end() && *endsIt == _nbShapesToSmooth )
4055 ++_nbShapesToSmooth;
4058 if ( endsIt == iEnds.end() )
4061 // Move _LayerEdge's on FACEs just after _nbShapesToSmooth
4063 vector< _LayerEdge* > nonSmoothLE, smoothLE;
4064 size_t lastSmooth = *iEnds.rbegin();
4066 for ( size_t i = _nbShapesToSmooth; i <= lastSmooth; ++i )
4068 bool toSmooth = iEnds.count(i);
4069 vector< _LayerEdge* > & edgesVec = toSmooth ? smoothLE : nonSmoothLE;
4070 iBeg = i ? _endEdgeOnShape[ i-1 ] : 0;
4071 iEnd = _endEdgeOnShape[ i ];
4072 edgesVec.insert( edgesVec.end(), _edges.begin() + iBeg, _edges.begin() + iEnd );
4074 // preparation for smoothing on FACE
4075 if ( toSmooth && _edges[iBeg]->_nodes[0]->GetPosition()->GetDim() == 2 )
4077 TopoDS_Shape S = SMESH_MesherHelper::GetSubShapeByNode( _edges[iBeg]->_nodes[0],
4078 _proxyMesh->GetMeshDS() );
4079 if ( !S.IsNull() && S.ShapeType() == TopAbs_FACE )
4081 PrepareEdgesToSmoothOnFace( &_edges[ iBeg ],
4084 /*substituteSrcNodes=*/true );
4089 iBeg = _nbShapesToSmooth ? _endEdgeOnShape[ _nbShapesToSmooth-1 ] : 0;
4090 std::copy( smoothLE.begin(), smoothLE.end(), &_edges[ iBeg ] );
4091 std::copy( nonSmoothLE.begin(), nonSmoothLE.end(), &_edges[ iBeg + smoothLE.size()]);
4093 // update _endEdgeOnShape
4094 for ( size_t i = _nbShapesToSmooth; i < _endEdgeOnShape.size(); ++i )
4096 TGeomID curShape = _edges[ iBeg ]->_nodes[0]->getshapeId();
4097 while ( ++iBeg < _edges.size() &&
4098 curShape == _edges[ iBeg ]->_nodes[0]->getshapeId() );
4100 _endEdgeOnShape[ i ] = iBeg;
4103 _nbShapesToSmooth += nbFacesToAdd;
4106 //================================================================================
4108 * \brief smooth _LayerEdge's on a staight EDGE or circular EDGE
4110 //================================================================================
4112 bool _ViscousBuilder::smoothAnalyticEdge( _SolidData& data,
4115 Handle(Geom_Surface)& surface,
4116 const TopoDS_Face& F,
4117 SMESH_MesherHelper& helper)
4119 TopoDS_Shape S = helper.GetSubShapeByNode( data._edges[ iFrom ]->_nodes[0],
4120 helper.GetMeshDS());
4121 TopoDS_Edge E = TopoDS::Edge( S );
4123 Handle(Geom_Curve) curve = data.CurveForSmooth( E, iFrom, iTo, F, helper );
4124 if ( curve.IsNull() ) return false;
4126 // compute a relative length of segments
4127 vector< double > len( iTo-iFrom+1 );
4129 double curLen, prevLen = len[0] = 1.0;
4130 for ( int i = iFrom; i < iTo; ++i )
4132 curLen = prevLen * data._edges[i]->_2neibors->_wgt[0] / data._edges[i]->_2neibors->_wgt[1];
4133 len[i-iFrom+1] = len[i-iFrom] + curLen;
4138 if ( curve->IsKind( STANDARD_TYPE( Geom_Line )))
4140 if ( F.IsNull() ) // 3D
4142 SMESH_TNodeXYZ p0( data._edges[iFrom]->_2neibors->tgtNode(0));
4143 SMESH_TNodeXYZ p1( data._edges[iTo-1]->_2neibors->tgtNode(1));
4144 for ( int i = iFrom; i < iTo; ++i )
4146 double r = len[i-iFrom] / len.back();
4147 gp_XYZ newPos = p0 * ( 1. - r ) + p1 * r;
4148 data._edges[i]->_pos.back() = newPos;
4149 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( data._edges[i]->_nodes.back() );
4150 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
4151 dumpMove( tgtNode );
4156 // gp_XY uv0 = helper.GetNodeUV( F, data._edges[iFrom]->_2neibors->tgtNode(0));
4157 // gp_XY uv1 = helper.GetNodeUV( F, data._edges[iTo-1]->_2neibors->tgtNode(1));
4158 gp_XY uv0 = data._edges[iFrom]->_2neibors->_edges[0]->LastUV( F );
4159 gp_XY uv1 = data._edges[iTo-1]->_2neibors->_edges[1]->LastUV( F );
4160 if ( data._edges[iFrom]->_2neibors->tgtNode(0) ==
4161 data._edges[iTo-1]->_2neibors->tgtNode(1) ) // closed edge
4163 int iPeriodic = helper.GetPeriodicIndex();
4164 if ( iPeriodic == 1 || iPeriodic == 2 )
4166 uv1.SetCoord( iPeriodic, helper.GetOtherParam( uv1.Coord( iPeriodic )));
4167 if ( uv0.Coord( iPeriodic ) > uv1.Coord( iPeriodic ))
4168 std::swap( uv0, uv1 );
4171 const gp_XY rangeUV = uv1 - uv0;
4172 for ( int i = iFrom; i < iTo; ++i )
4174 double r = len[i-iFrom] / len.back();
4175 gp_XY newUV = uv0 + r * rangeUV;
4176 data._edges[i]->_pos.back().SetCoord( newUV.X(), newUV.Y(), 0 );
4178 gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
4179 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( data._edges[i]->_nodes.back() );
4180 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
4181 dumpMove( tgtNode );
4183 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
4184 pos->SetUParameter( newUV.X() );
4185 pos->SetVParameter( newUV.Y() );
4191 if ( curve->IsKind( STANDARD_TYPE( Geom_Circle )))
4193 Handle(Geom_Circle) circle = Handle(Geom_Circle)::DownCast( curve );
4194 gp_Pnt center3D = circle->Location();
4196 if ( F.IsNull() ) // 3D
4198 if ( data._edges[iFrom]->_2neibors->tgtNode(0) ==
4199 data._edges[iTo-1]->_2neibors->tgtNode(1) )
4200 return true; // closed EDGE - nothing to do
4202 return false; // TODO ???
4206 const gp_XY center( center3D.X(), center3D.Y() );
4208 gp_XY uv0 = data._edges[iFrom]->_2neibors->_edges[0]->LastUV( F );
4209 gp_XY uvM = data._edges[iFrom]->LastUV( F );
4210 gp_XY uv1 = data._edges[iTo-1]->_2neibors->_edges[1]->LastUV( F );
4211 // gp_XY uv0 = helper.GetNodeUV( F, data._edges[iFrom]->_2neibors->tgtNode(0));
4212 // gp_XY uvM = helper.GetNodeUV( F, data._edges[iFrom]->_nodes.back());
4213 // gp_XY uv1 = helper.GetNodeUV( F, data._edges[iTo-1]->_2neibors->tgtNode(1));
4214 gp_Vec2d vec0( center, uv0 );
4215 gp_Vec2d vecM( center, uvM );
4216 gp_Vec2d vec1( center, uv1 );
4217 double uLast = vec0.Angle( vec1 ); // -PI - +PI
4218 double uMidl = vec0.Angle( vecM );
4219 if ( uLast * uMidl <= 0. )
4220 uLast += ( uMidl > 0 ? +2. : -2. ) * M_PI;
4221 const double radius = 0.5 * ( vec0.Magnitude() + vec1.Magnitude() );
4223 gp_Ax2d axis( center, vec0 );
4224 gp_Circ2d circ( axis, radius );
4225 for ( int i = iFrom; i < iTo; ++i )
4227 double newU = uLast * len[i-iFrom] / len.back();
4228 gp_Pnt2d newUV = ElCLib::Value( newU, circ );
4229 data._edges[i]->_pos.back().SetCoord( newUV.X(), newUV.Y(), 0 );
4231 gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
4232 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( data._edges[i]->_nodes.back() );
4233 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
4234 dumpMove( tgtNode );
4236 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
4237 pos->SetUParameter( newUV.X() );
4238 pos->SetVParameter( newUV.Y() );
4247 //================================================================================
4249 * \brief Modify normals of _LayerEdge's on EDGE's to avoid intersection with
4250 * _LayerEdge's on neighbor EDGE's
4252 //================================================================================
4254 bool _ViscousBuilder::updateNormals( _SolidData& data,
4255 SMESH_MesherHelper& helper,
4259 return updateNormalsOfConvexFaces( data, helper, stepNb );
4261 // make temporary quadrangles got by extrusion of
4262 // mesh edges along _LayerEdge._normal's
4264 vector< const SMDS_MeshElement* > tmpFaces;
4266 set< SMESH_TLink > extrudedLinks; // contains target nodes
4267 vector< const SMDS_MeshNode*> nodes(4); // of a tmp mesh face
4269 dumpFunction(SMESH_Comment("makeTmpFacesOnEdges")<<data._index);
4270 for ( size_t i = 0; i < data._edges.size(); ++i )
4272 _LayerEdge* edge = data._edges[i];
4273 if ( !edge->IsOnEdge() || !edge->_sWOL.IsNull() ) continue;
4274 const SMDS_MeshNode* tgt1 = edge->_nodes.back();
4275 for ( int j = 0; j < 2; ++j ) // loop on _2NearEdges
4277 const SMDS_MeshNode* tgt2 = edge->_2neibors->tgtNode(j);
4278 pair< set< SMESH_TLink >::iterator, bool > link_isnew =
4279 extrudedLinks.insert( SMESH_TLink( tgt1, tgt2 ));
4280 if ( !link_isnew.second )
4282 extrudedLinks.erase( link_isnew.first );
4283 continue; // already extruded and will no more encounter
4285 // a _LayerEdge containg tgt2
4286 _LayerEdge* neiborEdge = edge->_2neibors->_edges[j];
4288 _TmpMeshFaceOnEdge* f = new _TmpMeshFaceOnEdge( edge, neiborEdge, --_tmpFaceID );
4289 tmpFaces.push_back( f );
4291 dumpCmd(SMESH_Comment("mesh.AddFace([ ")
4292 <<f->_nn[0]->GetID()<<", "<<f->_nn[1]->GetID()<<", "
4293 <<f->_nn[2]->GetID()<<", "<<f->_nn[3]->GetID()<<" ])");
4298 // Check if _LayerEdge's based on EDGE's intersects tmpFaces.
4299 // Perform two loops on _LayerEdge on EDGE's:
4300 // 1) to find and fix intersection
4301 // 2) to check that no new intersection appears as result of 1)
4303 SMDS_ElemIteratorPtr fIt( new SMDS_ElementVectorIterator( tmpFaces.begin(),
4305 auto_ptr<SMESH_ElementSearcher> searcher
4306 ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(), fIt ));
4308 // 1) Find intersections
4310 const SMDS_MeshElement* face;
4311 typedef map< _LayerEdge*, set< _LayerEdge*, _LayerEdgeCmp >, _LayerEdgeCmp > TLEdge2LEdgeSet;
4312 TLEdge2LEdgeSet edge2CloseEdge;
4314 const double eps = data._epsilon * data._epsilon;
4315 for ( size_t i = 0; i < data._edges.size(); ++i )
4317 _LayerEdge* edge = data._edges[i];
4318 if (( !edge->IsOnEdge() ) &&
4319 ( edge->_sWOL.IsNull() || edge->_sWOL.ShapeType() != TopAbs_FACE ))
4321 if ( edge->FindIntersection( *searcher, dist, eps, &face ))
4323 const _TmpMeshFaceOnEdge* f = (const _TmpMeshFaceOnEdge*) face;
4324 set< _LayerEdge*, _LayerEdgeCmp > & ee = edge2CloseEdge[ edge ];
4325 ee.insert( f->_le1 );
4326 ee.insert( f->_le2 );
4327 if ( f->_le1->IsOnEdge() && f->_le1->_sWOL.IsNull() )
4328 edge2CloseEdge[ f->_le1 ].insert( edge );
4329 if ( f->_le2->IsOnEdge() && f->_le2->_sWOL.IsNull() )
4330 edge2CloseEdge[ f->_le2 ].insert( edge );
4334 // Set _LayerEdge._normal
4336 if ( !edge2CloseEdge.empty() )
4338 dumpFunction(SMESH_Comment("updateNormals")<<data._index);
4340 set< TGeomID > shapesToSmooth;
4342 // vector to store new _normal and _cosin for each edge in edge2CloseEdge
4343 vector< pair< _LayerEdge*, _LayerEdge > > edge2newEdge( edge2CloseEdge.size() );
4345 TLEdge2LEdgeSet::iterator e2ee = edge2CloseEdge.begin();
4346 for ( size_t iE = 0; e2ee != edge2CloseEdge.end(); ++e2ee, ++iE )
4348 _LayerEdge* edge1 = e2ee->first;
4349 _LayerEdge* edge2 = 0;
4350 set< _LayerEdge*, _LayerEdgeCmp >& ee = e2ee->second;
4352 edge2newEdge[ iE ].first = NULL;
4354 // find EDGEs the edges reside
4355 // TopoDS_Edge E1, E2;
4356 // TopoDS_Shape S = helper.GetSubShapeByNode( edge1->_nodes[0], getMeshDS() );
4357 // if ( S.ShapeType() != TopAbs_EDGE )
4358 // continue; // TODO: find EDGE by VERTEX
4359 // E1 = TopoDS::Edge( S );
4360 set< _LayerEdge*, _LayerEdgeCmp >::iterator eIt = ee.begin();
4361 for ( ; !edge2 && eIt != ee.end(); ++eIt )
4363 if ( edge1->_sWOL == (*eIt)->_sWOL )
4366 if ( !edge2 ) continue;
4368 edge2newEdge[ iE ].first = edge1;
4369 _LayerEdge& newEdge = edge2newEdge[ iE ].second;
4370 // while ( E2.IsNull() && eIt != ee.end())
4372 // _LayerEdge* e2 = *eIt++;
4373 // TopoDS_Shape S = helper.GetSubShapeByNode( e2->_nodes[0], getMeshDS() );
4374 // if ( S.ShapeType() == TopAbs_EDGE )
4375 // E2 = TopoDS::Edge( S ), edge2 = e2;
4377 // if ( E2.IsNull() ) continue; // TODO: find EDGE by VERTEX
4379 // find 3 FACEs sharing 2 EDGEs
4381 // TopoDS_Face FF1[2], FF2[2];
4382 // PShapeIteratorPtr fIt = helper.GetAncestors(E1, *_mesh, TopAbs_FACE);
4383 // while ( fIt->more() && FF1[1].IsNull() )
4385 // const TopoDS_Face *F = (const TopoDS_Face*) fIt->next();
4386 // if ( helper.IsSubShape( *F, data._solid))
4387 // FF1[ FF1[0].IsNull() ? 0 : 1 ] = *F;
4389 // fIt = helper.GetAncestors(E2, *_mesh, TopAbs_FACE);
4390 // while ( fIt->more() && FF2[1].IsNull())
4392 // const TopoDS_Face *F = (const TopoDS_Face*) fIt->next();
4393 // if ( helper.IsSubShape( *F, data._solid))
4394 // FF2[ FF2[0].IsNull() ? 0 : 1 ] = *F;
4396 // // exclude a FACE common to E1 and E2 (put it to FFn[1] )
4397 // if ( FF1[0].IsSame( FF2[0]) || FF1[0].IsSame( FF2[1]))
4398 // std::swap( FF1[0], FF1[1] );
4399 // if ( FF2[0].IsSame( FF1[0]) )
4400 // std::swap( FF2[0], FF2[1] );
4401 // if ( FF1[0].IsNull() || FF2[0].IsNull() )
4404 // get a new normal for edge1
4406 gp_Vec dir1 = edge1->_normal, dir2 = edge2->_normal;
4407 // if ( edge1->_cosin < 0 )
4408 // dir1 = getFaceDir( FF1[0], E1, edge1->_nodes[0], helper, ok ).Normalized();
4409 // if ( edge2->_cosin < 0 )
4410 // dir2 = getFaceDir( FF2[0], E2, edge2->_nodes[0], helper, ok ).Normalized();
4412 double cos1 = Abs( edge1->_cosin ), cos2 = Abs( edge2->_cosin );
4413 double wgt1 = ( cos1 + 0.001 ) / ( cos1 + cos2 + 0.002 );
4414 double wgt2 = ( cos2 + 0.001 ) / ( cos1 + cos2 + 0.002 );
4415 newEdge._normal = ( wgt1 * dir1 + wgt2 * dir2 ).XYZ();
4416 newEdge._normal.Normalize();
4418 // cout << edge1->_nodes[0]->GetID() << " "
4419 // << edge2->_nodes[0]->GetID() << " NORM: "
4420 // << newEdge._normal.X() << ", " << newEdge._normal.Y() << ", " << newEdge._normal.Z() << endl;
4423 if ( cos1 < theMinSmoothCosin )
4425 newEdge._cosin = edge2->_cosin;
4427 else if ( cos2 > theMinSmoothCosin ) // both cos1 and cos2 > theMinSmoothCosin
4429 // gp_Vec dirInFace;
4430 // if ( edge1->_cosin < 0 )
4431 // dirInFace = dir1;
4433 // dirInFace = getFaceDir( FF1[0], E1, edge1->_nodes[0], helper, ok );
4434 // double angle = dirInFace.Angle( edge1->_normal ); // [0,PI]
4435 // edge1->SetCosin( Cos( angle ));
4436 //newEdge._cosin = 0; // ???????????
4437 newEdge._cosin = ( wgt1 * cos1 + wgt2 * cos2 ) * edge1->_cosin / cos1;
4441 newEdge._cosin = edge1->_cosin;
4444 // find shapes that need smoothing due to change of _normal
4445 if ( edge1->_cosin < theMinSmoothCosin &&
4446 newEdge._cosin > theMinSmoothCosin )
4448 if ( edge1->_sWOL.IsNull() )
4450 SMDS_ElemIteratorPtr fIt = edge1->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
4451 while ( fIt->more() )
4452 shapesToSmooth.insert( fIt->next()->getshapeId() );
4453 //limitStepSize( data, fIt->next(), edge1->_cosin ); // too late
4455 else // edge1 inflates along a FACE
4457 TopoDS_Shape V = helper.GetSubShapeByNode( edge1->_nodes[0], getMeshDS() );
4458 PShapeIteratorPtr eIt = helper.GetAncestors( V, *_mesh, TopAbs_EDGE );
4459 while ( const TopoDS_Shape* E = eIt->next() )
4461 if ( !helper.IsSubShape( *E, /*FACE=*/edge1->_sWOL ))
4463 gp_Vec edgeDir = getEdgeDir( TopoDS::Edge( *E ), TopoDS::Vertex( V ));
4464 double angle = edgeDir.Angle( newEdge._normal ); // [0,PI]
4465 if ( angle < M_PI / 2 )
4466 shapesToSmooth.insert( getMeshDS()->ShapeToIndex( *E ));
4472 data.AddShapesToSmooth( shapesToSmooth );
4474 // Update data of edges depending on a new _normal
4476 for ( size_t iE = 0; iE < edge2newEdge.size(); ++iE )
4478 _LayerEdge* edge1 = edge2newEdge[ iE ].first;
4479 _LayerEdge& newEdge = edge2newEdge[ iE ].second;
4480 if ( !edge1 ) continue;
4482 edge1->_normal = newEdge._normal;
4483 edge1->SetCosin( newEdge._cosin );
4484 edge1->InvalidateStep( 1 );
4486 edge1->SetNewLength( data._stepSize, helper );
4487 if ( edge1->IsOnEdge() )
4489 const SMDS_MeshNode * n1 = edge1->_2neibors->srcNode(0);
4490 const SMDS_MeshNode * n2 = edge1->_2neibors->srcNode(1);
4491 edge1->SetDataByNeighbors( n1, n2, helper );
4494 // Update normals and other dependent data of not intersecting _LayerEdge's
4495 // neighboring the intersecting ones
4497 if ( !edge1->_2neibors )
4499 for ( int j = 0; j < 2; ++j ) // loop on 2 neighbors
4501 _LayerEdge* neighbor = edge1->_2neibors->_edges[j];
4502 if ( edge2CloseEdge.count ( neighbor ))
4503 continue; // j-th neighbor is also intersected
4504 _LayerEdge* prevEdge = edge1;
4505 const int nbSteps = 10;
4506 for ( int step = nbSteps; step; --step ) // step from edge1 in j-th direction
4508 if ( !neighbor->_2neibors )
4509 break; // neighbor is on VERTEX
4511 _LayerEdge* nextEdge = neighbor->_2neibors->_edges[iNext];
4512 if ( nextEdge == prevEdge )
4513 nextEdge = neighbor->_2neibors->_edges[ ++iNext ];
4514 double r = double(step-1)/nbSteps;
4515 if ( !nextEdge->_2neibors )
4518 gp_XYZ newNorm = prevEdge->_normal * r + nextEdge->_normal * (1-r);
4519 newNorm.Normalize();
4521 neighbor->_normal = newNorm;
4522 neighbor->SetCosin( prevEdge->_cosin * r + nextEdge->_cosin * (1-r) );
4523 neighbor->SetDataByNeighbors( prevEdge->_nodes[0], nextEdge->_nodes[0], helper );
4525 neighbor->InvalidateStep( 1 );
4527 neighbor->SetNewLength( data._stepSize, helper );
4529 // goto the next neighbor
4530 prevEdge = neighbor;
4531 neighbor = nextEdge;
4537 // 2) Check absence of intersections
4540 for ( size_t i = 0 ; i < tmpFaces.size(); ++i )
4546 //================================================================================
4548 * \brief Modify normals of _LayerEdge's on _ConvexFace's
4550 //================================================================================
4552 bool _ViscousBuilder::updateNormalsOfConvexFaces( _SolidData& data,
4553 SMESH_MesherHelper& helper,
4556 SMESHDS_Mesh* meshDS = helper.GetMeshDS();
4559 map< TGeomID, _ConvexFace >::iterator id2face = data._convexFaces.begin();
4560 for ( ; id2face != data._convexFaces.end(); ++id2face )
4562 _ConvexFace & convFace = (*id2face).second;
4563 if ( convFace._normalsFixed )
4564 continue; // already fixed
4565 if ( convFace.CheckPrisms() )
4566 continue; // nothing to fix
4568 convFace._normalsFixed = true;
4570 BRepAdaptor_Surface surface ( convFace._face, false );
4571 BRepLProp_SLProps surfProp( surface, 2, 1e-6 );
4573 // check if the convex FACE is of spherical shape
4575 Bnd_B3d centersBox; // bbox of centers of curvature of _LayerEdge's on VERTEXes
4580 map< TGeomID, int >::iterator id2end = convFace._subIdToEdgeEnd.begin();
4581 for ( ; id2end != convFace._subIdToEdgeEnd.end(); ++id2end )
4583 data.GetEdgesOnShape( id2end->second, iBeg, iEnd );
4585 if ( meshDS->IndexToShape( id2end->first ).ShapeType() == TopAbs_VERTEX )
4587 _LayerEdge* ledge = data._edges[ iBeg ];
4588 if ( convFace.GetCenterOfCurvature( ledge, surfProp, helper, center ))
4589 centersBox.Add( center );
4591 for ( ; iBeg < iEnd; ++iBeg )
4592 nodesBox.Add( SMESH_TNodeXYZ( data._edges[ iBeg ]->_nodes[0] ));
4594 if ( centersBox.IsVoid() )
4596 debugMsg( "Error: centersBox.IsVoid()" );
4599 const bool isSpherical =
4600 ( centersBox.SquareExtent() < 1e-6 * nodesBox.SquareExtent() );
4602 int nbEdges = helper.Count( convFace._face, TopAbs_EDGE, /*ignoreSame=*/false );
4603 vector < _CentralCurveOnEdge > centerCurves( nbEdges );
4607 // set _LayerEdge::_normal as average of all normals
4609 // WARNING: different density of nodes on EDGEs is not taken into account that
4610 // can lead to an improper new normal
4612 gp_XYZ avgNormal( 0,0,0 );
4614 id2end = convFace._subIdToEdgeEnd.begin();
4615 for ( ; id2end != convFace._subIdToEdgeEnd.end(); ++id2end )
4617 data.GetEdgesOnShape( id2end->second, iBeg, iEnd );
4618 // set data of _CentralCurveOnEdge
4619 const TopoDS_Shape& S = meshDS->IndexToShape( id2end->first );
4620 if ( S.ShapeType() == TopAbs_EDGE )
4622 _CentralCurveOnEdge& ceCurve = centerCurves[ nbEdges++ ];
4623 ceCurve.SetShapes( TopoDS::Edge(S), convFace, data, helper );
4624 if ( !data._edges[ iBeg ]->_sWOL.IsNull() )
4625 ceCurve._adjFace.Nullify();
4627 ceCurve._ledges.insert( ceCurve._ledges.end(),
4628 &data._edges[ iBeg ], &data._edges[ iEnd ]);
4630 // summarize normals
4631 for ( ; iBeg < iEnd; ++iBeg )
4632 avgNormal += data._edges[ iBeg ]->_normal;
4634 double normSize = avgNormal.SquareModulus();
4635 if ( normSize < 1e-200 )
4637 debugMsg( "updateNormalsOfConvexFaces(): zero avgNormal" );
4640 avgNormal /= Sqrt( normSize );
4642 // compute new _LayerEdge::_cosin on EDGEs
4643 double avgCosin = 0;
4646 for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
4648 _CentralCurveOnEdge& ceCurve = centerCurves[ iE ];
4649 if ( ceCurve._adjFace.IsNull() )
4651 for ( size_t iLE = 0; iLE < ceCurve._ledges.size(); ++iLE )
4653 const SMDS_MeshNode* node = ceCurve._ledges[ iLE ]->_nodes[0];
4654 inFaceDir = getFaceDir( ceCurve._adjFace, ceCurve._edge, node, helper, isOK );
4657 double angle = inFaceDir.Angle( avgNormal ); // [0,PI]
4658 ceCurve._ledges[ iLE ]->_cosin = Cos( angle );
4659 avgCosin += ceCurve._ledges[ iLE ]->_cosin;
4665 avgCosin /= nbCosin;
4667 // set _LayerEdge::_normal = avgNormal
4668 id2end = convFace._subIdToEdgeEnd.begin();
4669 for ( ; id2end != convFace._subIdToEdgeEnd.end(); ++id2end )
4671 data.GetEdgesOnShape( id2end->second, iBeg, iEnd );
4672 const TopoDS_Shape& S = meshDS->IndexToShape( id2end->first );
4673 if ( S.ShapeType() != TopAbs_EDGE )
4674 for ( int i = iBeg; i < iEnd; ++i )
4675 data._edges[ i ]->_cosin = avgCosin;
4677 for ( ; iBeg < iEnd; ++iBeg )
4678 data._edges[ iBeg ]->_normal = avgNormal;
4681 else // if ( isSpherical )
4683 // We suppose that centers of curvature at all points of the FACE
4684 // lie on some curve, let's call it "central curve". For all _LayerEdge's
4685 // having a common center of curvature we define the same new normal
4686 // as a sum of normals of _LayerEdge's on EDGEs among them.
4688 // get all centers of curvature for each EDGE
4690 helper.SetSubShape( convFace._face );
4691 _LayerEdge* vertexLEdges[2], **edgeLEdge, **edgeLEdgeEnd;
4693 TopExp_Explorer edgeExp( convFace._face, TopAbs_EDGE );
4694 for ( int iE = 0; edgeExp.More(); edgeExp.Next(), ++iE )
4696 const TopoDS_Edge& edge = TopoDS::Edge( edgeExp.Current() );
4698 // set adjacent FACE
4699 centerCurves[ iE ].SetShapes( edge, convFace, data, helper );
4701 // get _LayerEdge's of the EDGE
4702 TGeomID edgeID = meshDS->ShapeToIndex( edge );
4703 id2end = convFace._subIdToEdgeEnd.find( edgeID );
4704 if ( id2end == convFace._subIdToEdgeEnd.end() )
4706 // no _LayerEdge's on EDGE, use _LayerEdge's on VERTEXes
4707 for ( int iV = 0; iV < 2; ++iV )
4709 TopoDS_Vertex v = helper.IthVertex( iV, edge );
4710 TGeomID vID = meshDS->ShapeToIndex( v );
4711 int end = convFace._subIdToEdgeEnd[ vID ];
4712 int iBeg = end > 0 ? data._endEdgeOnShape[ end-1 ] : 0;
4713 vertexLEdges[ iV ] = data._edges[ iBeg ];
4715 edgeLEdge = &vertexLEdges[0];
4716 edgeLEdgeEnd = edgeLEdge + 2;
4718 centerCurves[ iE ]._adjFace.Nullify();
4722 data.GetEdgesOnShape( id2end->second, iBeg, iEnd );
4723 if ( id2end->second >= data._nbShapesToSmooth )
4724 data.SortOnEdge( edge, iBeg, iEnd, helper );
4725 edgeLEdge = &data._edges[ iBeg ];
4726 edgeLEdgeEnd = edgeLEdge + iEnd - iBeg;
4727 vertexLEdges[0] = data._edges[ iBeg ]->_2neibors->_edges[0];
4728 vertexLEdges[1] = data._edges[ iEnd-1 ]->_2neibors->_edges[1];
4730 if ( ! data._edges[ iBeg ]->_sWOL.IsNull() )
4731 centerCurves[ iE ]._adjFace.Nullify();
4734 // Get curvature centers
4738 if ( edgeLEdge[0]->IsOnEdge() &&
4739 convFace.GetCenterOfCurvature( vertexLEdges[0], surfProp, helper, center ))
4741 centerCurves[ iE ].Append( center, vertexLEdges[0] );
4742 centersBox.Add( center );
4744 for ( ; edgeLEdge < edgeLEdgeEnd; ++edgeLEdge )
4745 if ( convFace.GetCenterOfCurvature( *edgeLEdge, surfProp, helper, center ))
4746 { // EDGE or VERTEXes
4747 centerCurves[ iE ].Append( center, *edgeLEdge );
4748 centersBox.Add( center );
4750 if ( edgeLEdge[-1]->IsOnEdge() &&
4751 convFace.GetCenterOfCurvature( vertexLEdges[1], surfProp, helper, center ))
4753 centerCurves[ iE ].Append( center, vertexLEdges[1] );
4754 centersBox.Add( center );
4756 centerCurves[ iE ]._isDegenerated =
4757 ( centersBox.IsVoid() || centersBox.SquareExtent() < 1e-6 * nodesBox.SquareExtent() );
4759 } // loop on EDGES of convFace._face to set up data of centerCurves
4761 // Compute new normals for _LayerEdge's on EDGEs
4763 double avgCosin = 0;
4766 for ( size_t iE1 = 0; iE1 < centerCurves.size(); ++iE1 )
4768 _CentralCurveOnEdge& ceCurve = centerCurves[ iE1 ];
4769 if ( ceCurve._isDegenerated )
4771 const vector< gp_Pnt >& centers = ceCurve._curvaCenters;
4772 vector< gp_XYZ > & newNormals = ceCurve._normals;
4773 for ( size_t iC1 = 0; iC1 < centers.size(); ++iC1 )
4776 for ( size_t iE2 = 0; iE2 < centerCurves.size() && !isOK; ++iE2 )
4779 isOK = centerCurves[ iE2 ].FindNewNormal( centers[ iC1 ], newNormals[ iC1 ]);
4781 if ( isOK && !ceCurve._adjFace.IsNull() )
4783 // compute new _LayerEdge::_cosin
4784 const SMDS_MeshNode* node = ceCurve._ledges[ iC1 ]->_nodes[0];
4785 inFaceDir = getFaceDir( ceCurve._adjFace, ceCurve._edge, node, helper, isOK );
4788 double angle = inFaceDir.Angle( newNormals[ iC1 ] ); // [0,PI]
4789 ceCurve._ledges[ iC1 ]->_cosin = Cos( angle );
4790 avgCosin += ceCurve._ledges[ iC1 ]->_cosin;
4796 // set new normals to _LayerEdge's of NOT degenerated central curves
4797 for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
4799 if ( centerCurves[ iE ]._isDegenerated )
4801 for ( size_t iLE = 0; iLE < centerCurves[ iE ]._ledges.size(); ++iLE )
4802 centerCurves[ iE ]._ledges[ iLE ]->_normal = centerCurves[ iE ]._normals[ iLE ];
4804 // set new normals to _LayerEdge's of degenerated central curves
4805 for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
4807 if ( !centerCurves[ iE ]._isDegenerated ||
4808 centerCurves[ iE ]._ledges.size() < 3 )
4810 // new normal is an average of new normals at VERTEXes that
4811 // was computed on non-degenerated _CentralCurveOnEdge's
4812 gp_XYZ newNorm = ( centerCurves[ iE ]._ledges.front()->_normal +
4813 centerCurves[ iE ]._ledges.back ()->_normal );
4814 double sz = newNorm.Modulus();
4818 double newCosin = ( 0.5 * centerCurves[ iE ]._ledges.front()->_cosin +
4819 0.5 * centerCurves[ iE ]._ledges.back ()->_cosin );
4820 for ( size_t iLE = 1, nb = centerCurves[ iE ]._ledges.size() - 1; iLE < nb; ++iLE )
4822 centerCurves[ iE ]._ledges[ iLE ]->_normal = newNorm;
4823 centerCurves[ iE ]._ledges[ iLE ]->_cosin = newCosin;
4827 // Find new normals for _LayerEdge's based on FACE
4830 avgCosin /= nbCosin;
4831 const TGeomID faceID = meshDS->ShapeToIndex( convFace._face );
4832 map< TGeomID, int >::iterator id2end = convFace._subIdToEdgeEnd.find( faceID );
4833 if ( id2end != convFace._subIdToEdgeEnd.end() )
4837 data.GetEdgesOnShape( id2end->second, iBeg, iEnd );
4838 for ( ; iBeg < iEnd; ++iBeg )
4840 _LayerEdge* ledge = data._edges[ iBeg ];
4841 if ( !convFace.GetCenterOfCurvature( ledge, surfProp, helper, center ))
4843 for ( size_t i = 0; i < centerCurves.size(); ++i, ++iE )
4845 iE = iE % centerCurves.size();
4846 if ( centerCurves[ iE ]._isDegenerated )
4848 newNorm.SetCoord( 0,0,0 );
4849 if ( centerCurves[ iE ].FindNewNormal( center, newNorm ))
4851 ledge->_normal = newNorm;
4852 ledge->_cosin = avgCosin;
4859 } // not a quasi-spherical FACE
4861 // Update _LayerEdge's data according to a new normal
4863 dumpFunction(SMESH_Comment("updateNormalsOfConvexFaces")<<data._index
4864 <<"_F"<<meshDS->ShapeToIndex( convFace._face ));
4866 id2end = convFace._subIdToEdgeEnd.begin();
4867 for ( ; id2end != convFace._subIdToEdgeEnd.end(); ++id2end )
4869 data.GetEdgesOnShape( id2end->second, iBeg, iEnd );
4870 for ( ; iBeg < iEnd; ++iBeg )
4872 _LayerEdge* & ledge = data._edges[ iBeg ];
4873 double len = ledge->_len;
4874 ledge->InvalidateStep( stepNb + 1, /*restoreLength=*/true );
4875 ledge->SetCosin( ledge->_cosin );
4876 ledge->SetNewLength( len, helper );
4879 } // loop on sub-shapes of convFace._face
4881 // Find FACEs adjacent to convFace._face that got necessity to smooth
4882 // as a result of normals modification
4884 set< TGeomID > adjFacesToSmooth;
4885 for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
4887 if ( centerCurves[ iE ]._adjFace.IsNull() ||
4888 centerCurves[ iE ]._adjFaceToSmooth )
4890 for ( size_t iLE = 0; iLE < centerCurves[ iE ]._ledges.size(); ++iLE )
4892 if ( centerCurves[ iE ]._ledges[ iLE ]->_cosin > theMinSmoothCosin )
4894 adjFacesToSmooth.insert( meshDS->ShapeToIndex( centerCurves[ iE ]._adjFace ));
4899 data.AddShapesToSmooth( adjFacesToSmooth );
4904 } // loop on data._convexFaces
4909 //================================================================================
4911 * \brief Finds a center of curvature of a surface at a _LayerEdge
4913 //================================================================================
4915 bool _ConvexFace::GetCenterOfCurvature( _LayerEdge* ledge,
4916 BRepLProp_SLProps& surfProp,
4917 SMESH_MesherHelper& helper,
4918 gp_Pnt & center ) const
4920 gp_XY uv = helper.GetNodeUV( _face, ledge->_nodes[0] );
4921 surfProp.SetParameters( uv.X(), uv.Y() );
4922 if ( !surfProp.IsCurvatureDefined() )
4925 const double oriFactor = ( _face.Orientation() == TopAbs_REVERSED ? +1. : -1. );
4926 double surfCurvatureMax = surfProp.MaxCurvature() * oriFactor;
4927 double surfCurvatureMin = surfProp.MinCurvature() * oriFactor;
4928 if ( surfCurvatureMin > surfCurvatureMax )
4929 center = surfProp.Value().Translated( surfProp.Normal().XYZ() / surfCurvatureMin * oriFactor );
4931 center = surfProp.Value().Translated( surfProp.Normal().XYZ() / surfCurvatureMax * oriFactor );
4936 //================================================================================
4938 * \brief Check that prisms are not distorted
4940 //================================================================================
4942 bool _ConvexFace::CheckPrisms() const
4945 for ( size_t i = 0; i < _simplexTestEdges.size(); ++i )
4947 const _LayerEdge* edge = _simplexTestEdges[i];
4948 SMESH_TNodeXYZ tgtXYZ( edge->_nodes.back() );
4949 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
4950 if ( !edge->_simplices[j].IsForward( edge->_nodes[0], &tgtXYZ, vol ))
4952 debugMsg( "Bad simplex of _simplexTestEdges ("
4953 << " "<< edge->_nodes[0]->GetID()<< " "<< tgtXYZ._node->GetID()
4954 << " "<< edge->_simplices[j]._nPrev->GetID()
4955 << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
4962 //================================================================================
4964 * \brief Try to compute a new normal by interpolating normals of _LayerEdge's
4965 * stored in this _CentralCurveOnEdge.
4966 * \param [in] center - curvature center of a point of another _CentralCurveOnEdge.
4967 * \param [in,out] newNormal - current normal at this point, to be redefined
4968 * \return bool - true if succeeded.
4970 //================================================================================
4972 bool _CentralCurveOnEdge::FindNewNormal( const gp_Pnt& center, gp_XYZ& newNormal )
4974 if ( this->_isDegenerated )
4977 // find two centers the given one lies between
4979 for ( size_t i = 0, nb = _curvaCenters.size()-1; i < nb; ++i )
4981 double sl2 = 1.001 * _segLength2[ i ];
4983 double d1 = center.SquareDistance( _curvaCenters[ i ]);
4987 double d2 = center.SquareDistance( _curvaCenters[ i+1 ]);
4988 if ( d2 > sl2 || d2 + d1 < 1e-100 )
4993 double r = d1 / ( d1 + d2 );
4994 gp_XYZ norm = (( 1. - r ) * _ledges[ i ]->_normal +
4995 ( r ) * _ledges[ i+1 ]->_normal );
4999 double sz = newNormal.Modulus();
5008 //================================================================================
5010 * \brief Set shape members
5012 //================================================================================
5014 void _CentralCurveOnEdge::SetShapes( const TopoDS_Edge& edge,
5015 const _ConvexFace& convFace,
5016 const _SolidData& data,
5017 SMESH_MesherHelper& helper)
5021 PShapeIteratorPtr fIt = helper.GetAncestors( edge, *helper.GetMesh(), TopAbs_FACE );
5022 while ( const TopoDS_Shape* F = fIt->next())
5023 if ( !convFace._face.IsSame( *F ))
5025 _adjFace = TopoDS::Face( *F );
5026 _adjFaceToSmooth = false;
5027 // _adjFace already in a smoothing queue ?
5029 TGeomID adjFaceID = helper.GetMeshDS()->ShapeToIndex( *F );
5030 if ( data.GetShapeEdges( adjFaceID, end ))
5031 _adjFaceToSmooth = ( end < data._nbShapesToSmooth );
5036 //================================================================================
5038 * \brief Looks for intersection of it's last segment with faces
5039 * \param distance - returns shortest distance from the last node to intersection
5041 //================================================================================
5043 bool _LayerEdge::FindIntersection( SMESH_ElementSearcher& searcher,
5045 const double& epsilon,
5046 const SMDS_MeshElement** face)
5048 vector< const SMDS_MeshElement* > suspectFaces;
5050 gp_Ax1 lastSegment = LastSegment(segLen);
5051 searcher.GetElementsNearLine( lastSegment, SMDSAbs_Face, suspectFaces );
5053 bool segmentIntersected = false;
5054 distance = Precision::Infinite();
5055 int iFace = -1; // intersected face
5056 for ( size_t j = 0 ; j < suspectFaces.size() /*&& !segmentIntersected*/; ++j )
5058 const SMDS_MeshElement* face = suspectFaces[j];
5059 if ( face->GetNodeIndex( _nodes.back() ) >= 0 ||
5060 face->GetNodeIndex( _nodes[0] ) >= 0 )
5061 continue; // face sharing _LayerEdge node
5062 const int nbNodes = face->NbCornerNodes();
5063 bool intFound = false;
5065 SMDS_MeshElement::iterator nIt = face->begin_nodes();
5068 intFound = SegTriaInter( lastSegment, *nIt++, *nIt++, *nIt++, dist, epsilon );
5072 const SMDS_MeshNode* tria[3];
5075 for ( int n2 = 2; n2 < nbNodes && !intFound; ++n2 )
5078 intFound = SegTriaInter(lastSegment, tria[0], tria[1], tria[2], dist, epsilon );
5084 if ( dist < segLen*(1.01) && dist > -(_len*_lenFactor-segLen) )
5085 segmentIntersected = true;
5086 if ( distance > dist )
5087 distance = dist, iFace = j;
5090 if ( iFace != -1 && face ) *face = suspectFaces[iFace];
5092 if ( segmentIntersected )
5095 SMDS_MeshElement::iterator nIt = suspectFaces[iFace]->begin_nodes();
5096 gp_XYZ intP( lastSegment.Location().XYZ() + lastSegment.Direction().XYZ() * distance );
5097 cout << "nodes: tgt " << _nodes.back()->GetID() << " src " << _nodes[0]->GetID()
5098 << ", intersection with face ("
5099 << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
5100 << ") at point (" << intP.X() << ", " << intP.Y() << ", " << intP.Z()
5101 << ") distance = " << distance - segLen<< endl;
5107 return segmentIntersected;
5110 //================================================================================
5112 * \brief Returns size and direction of the last segment
5114 //================================================================================
5116 gp_Ax1 _LayerEdge::LastSegment(double& segLen) const
5118 // find two non-coincident positions
5119 gp_XYZ orig = _pos.back();
5121 int iPrev = _pos.size() - 2;
5122 const double tol = ( _len > 0 ) ? 0.3*_len : 1e-100; // adjusted for IPAL52478 + PAL22576
5123 while ( iPrev >= 0 )
5125 dir = orig - _pos[iPrev];
5126 if ( dir.SquareModulus() > tol*tol )
5136 segDir.SetLocation( SMESH_TNodeXYZ( _nodes[0] ));
5137 segDir.SetDirection( _normal );
5142 gp_Pnt pPrev = _pos[ iPrev ];
5143 if ( !_sWOL.IsNull() )
5145 TopLoc_Location loc;
5146 if ( _sWOL.ShapeType() == TopAbs_EDGE )
5149 Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( _sWOL ), loc, f,l);
5150 pPrev = curve->Value( pPrev.X() ).Transformed( loc );
5154 Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face(_sWOL), loc );
5155 pPrev = surface->Value( pPrev.X(), pPrev.Y() ).Transformed( loc );
5157 dir = SMESH_TNodeXYZ( _nodes.back() ) - pPrev.XYZ();
5159 segDir.SetLocation( pPrev );
5160 segDir.SetDirection( dir );
5161 segLen = dir.Modulus();
5167 //================================================================================
5169 * \brief Return the last position of the target node on a FACE.
5170 * \param [in] F - the FACE this _LayerEdge is inflated along
5171 * \return gp_XY - result UV
5173 //================================================================================
5175 gp_XY _LayerEdge::LastUV( const TopoDS_Face& F ) const
5177 if ( F.IsSame( _sWOL )) // F is my FACE
5178 return gp_XY( _pos.back().X(), _pos.back().Y() );
5180 if ( _sWOL.IsNull() || _sWOL.ShapeType() != TopAbs_EDGE ) // wrong call
5181 return gp_XY( 1e100, 1e100 );
5183 // _sWOL is EDGE of F; _pos.back().X() is the last U on the EDGE
5184 double f, l, u = _pos.back().X();
5185 Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface( TopoDS::Edge(_sWOL), F, f,l);
5186 if ( !C2d.IsNull() && f <= u && u <= l )
5187 return C2d->Value( u ).XY();
5189 return gp_XY( 1e100, 1e100 );
5192 //================================================================================
5194 * \brief Test intersection of the last segment with a given triangle
5195 * using Moller-Trumbore algorithm
5196 * Intersection is detected if distance to intersection is less than _LayerEdge._len
5198 //================================================================================
5200 bool _LayerEdge::SegTriaInter( const gp_Ax1& lastSegment,
5201 const SMDS_MeshNode* n0,
5202 const SMDS_MeshNode* n1,
5203 const SMDS_MeshNode* n2,
5205 const double& EPSILON) const
5207 //const double EPSILON = 1e-6;
5209 const gp_Pnt& orig = lastSegment.Location();
5210 const gp_Dir& dir = lastSegment.Direction();
5212 SMESH_TNodeXYZ vert0( n0 );
5213 SMESH_TNodeXYZ vert1( n1 );
5214 SMESH_TNodeXYZ vert2( n2 );
5216 /* calculate distance from vert0 to ray origin */
5217 gp_XYZ tvec = orig.XYZ() - vert0;
5219 //if ( tvec * dir > EPSILON )
5220 // intersected face is at back side of the temporary face this _LayerEdge belongs to
5223 gp_XYZ edge1 = vert1 - vert0;
5224 gp_XYZ edge2 = vert2 - vert0;
5226 /* begin calculating determinant - also used to calculate U parameter */
5227 gp_XYZ pvec = dir.XYZ() ^ edge2;
5229 /* if determinant is near zero, ray lies in plane of triangle */
5230 double det = edge1 * pvec;
5232 if (det > -EPSILON && det < EPSILON)
5235 /* calculate U parameter and test bounds */
5236 double u = ( tvec * pvec ) / det;
5237 //if (u < 0.0 || u > 1.0)
5238 if (u < -EPSILON || u > 1.0 + EPSILON)
5241 /* prepare to test V parameter */
5242 gp_XYZ qvec = tvec ^ edge1;
5244 /* calculate V parameter and test bounds */
5245 double v = (dir.XYZ() * qvec) / det;
5246 //if ( v < 0.0 || u + v > 1.0 )
5247 if ( v < -EPSILON || u + v > 1.0 + EPSILON)
5250 /* calculate t, ray intersects triangle */
5251 t = (edge2 * qvec) / det;
5257 //================================================================================
5259 * \brief Perform smooth of _LayerEdge's based on EDGE's
5260 * \retval bool - true if node has been moved
5262 //================================================================================
5264 bool _LayerEdge::SmoothOnEdge(Handle(Geom_Surface)& surface,
5265 const TopoDS_Face& F,
5266 SMESH_MesherHelper& helper)
5268 ASSERT( IsOnEdge() );
5270 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _nodes.back() );
5271 SMESH_TNodeXYZ oldPos( tgtNode );
5272 double dist01, distNewOld;
5274 SMESH_TNodeXYZ p0( _2neibors->tgtNode(0));
5275 SMESH_TNodeXYZ p1( _2neibors->tgtNode(1));
5276 dist01 = p0.Distance( _2neibors->tgtNode(1) );
5278 gp_Pnt newPos = p0 * _2neibors->_wgt[0] + p1 * _2neibors->_wgt[1];
5279 double lenDelta = 0;
5282 //lenDelta = _curvature->lenDelta( _len );
5283 lenDelta = _curvature->lenDeltaByDist( dist01 );
5284 newPos.ChangeCoord() += _normal * lenDelta;
5287 distNewOld = newPos.Distance( oldPos );
5291 if ( _2neibors->_plnNorm )
5293 // put newPos on the plane defined by source node and _plnNorm
5294 gp_XYZ new2src = SMESH_TNodeXYZ( _nodes[0] ) - newPos.XYZ();
5295 double new2srcProj = (*_2neibors->_plnNorm) * new2src;
5296 newPos.ChangeCoord() += (*_2neibors->_plnNorm) * new2srcProj;
5298 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
5299 _pos.back() = newPos.XYZ();
5303 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
5304 gp_XY uv( Precision::Infinite(), 0 );
5305 helper.CheckNodeUV( F, tgtNode, uv, 1e-10, /*force=*/true );
5306 _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
5308 newPos = surface->Value( uv.X(), uv.Y() );
5309 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
5312 // commented for IPAL0052478
5313 // if ( _curvature && lenDelta < 0 )
5315 // gp_Pnt prevPos( _pos[ _pos.size()-2 ]);
5316 // _len -= prevPos.Distance( oldPos );
5317 // _len += prevPos.Distance( newPos );
5319 bool moved = distNewOld > dist01/50;
5321 dumpMove( tgtNode ); // debug
5326 //================================================================================
5328 * \brief Perform laplacian smooth in 3D of nodes inflated from FACE
5329 * \retval bool - true if _tgtNode has been moved
5331 //================================================================================
5333 int _LayerEdge::Smooth(const int step, const bool isConcaveFace, const bool findBest )
5335 if ( _simplices.size() < 2 )
5336 return 0; // _LayerEdge inflated along EDGE or FACE
5338 const gp_XYZ& curPos ( _pos.back() );
5339 const gp_XYZ& prevPos( _pos[ _pos.size()-2 ]);
5341 // quality metrics (orientation) of tetras around _tgtNode
5343 double vol, minVolBefore = 1e100;
5344 for ( size_t i = 0; i < _simplices.size(); ++i )
5346 nbOkBefore += _simplices[i].IsForward( _nodes[0], &curPos, vol );
5347 minVolBefore = Min( minVolBefore, vol );
5349 int nbBad = _simplices.size() - nbOkBefore;
5351 // compute new position for the last _pos using different _funs
5353 for ( int iFun = -1; iFun < theNbSmooFuns; ++iFun )
5356 newPos = (this->*_smooFunction)(); // fun chosen by ChooseSmooFunction()
5357 else if ( _funs[ iFun ] == _smooFunction )
5358 continue; // _smooFunction again
5359 else if ( step > 0 )
5360 newPos = (this->*_funs[ iFun ])(); // try other smoothing fun
5362 break; // let "easy" functions improve elements around distorted ones
5366 double delta = _curvature->lenDelta( _len );
5368 newPos += _normal * delta;
5371 double segLen = _normal * ( newPos - prevPos );
5372 if ( segLen + delta > 0 )
5373 newPos += _normal * delta;
5375 // double segLenChange = _normal * ( curPos - newPos );
5376 // newPos += 0.5 * _normal * segLenChange;
5380 double minVolAfter = 1e100;
5381 for ( size_t i = 0; i < _simplices.size(); ++i )
5383 nbOkAfter += _simplices[i].IsForward( _nodes[0], &newPos, vol );
5384 minVolAfter = Min( minVolAfter, vol );
5387 if ( nbOkAfter < nbOkBefore )
5389 if (( isConcaveFace || findBest ) &&
5390 ( nbOkAfter == nbOkBefore ) &&
5391 //( iFun > -1 || nbOkAfter < _simplices.size() ) &&
5392 ( minVolAfter <= minVolBefore ))
5395 SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
5397 // commented for IPAL0052478
5398 // _len -= prevPos.Distance(SMESH_TNodeXYZ( n ));
5399 // _len += prevPos.Distance(newPos);
5401 n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
5402 _pos.back() = newPos;
5403 dumpMoveComm( n, _funNames[ iFun < 0 ? smooFunID() : iFun ]);
5405 nbBad = _simplices.size() - nbOkAfter;
5409 //_smooFunction = _funs[ iFun ];
5410 // cout << "# " << _funNames[ iFun ] << "\t N:" << _nodes.back()->GetID()
5411 // << "\t nbBad: " << _simplices.size() - nbOkAfter
5412 // << " minVol: " << minVolAfter
5413 // << " " << newPos.X() << " " << newPos.Y() << " " << newPos.Z()
5415 minVolBefore = minVolAfter;
5416 nbOkBefore = nbOkAfter;
5417 continue; // look for a better function
5423 } // loop on smoothing functions
5428 //================================================================================
5430 * \brief Chooses a smoothing technic giving a position most close to an initial one.
5431 * For a correct result, _simplices must contain nodes lying on geometry.
5433 //================================================================================
5435 void _LayerEdge::ChooseSmooFunction( const set< TGeomID >& concaveVertices,
5436 const TNode2Edge& n2eMap)
5438 if ( _smooFunction ) return;
5440 // use smoothNefPolygon() near concaveVertices
5441 if ( !concaveVertices.empty() )
5443 for ( size_t i = 0; i < _simplices.size(); ++i )
5445 if ( concaveVertices.count( _simplices[i]._nPrev->getshapeId() ))
5447 _smooFunction = _funs[ FUN_NEFPOLY ];
5449 // set FUN_CENTROIDAL to neighbor edges
5450 TNode2Edge::const_iterator n2e;
5451 for ( i = 0; i < _simplices.size(); ++i )
5453 if (( _simplices[i]._nPrev->GetPosition()->GetDim() == 2 ) &&
5454 (( n2e = n2eMap.find( _simplices[i]._nPrev )) != n2eMap.end() ))
5456 n2e->second->_smooFunction = _funs[ FUN_CENTROIDAL ];
5464 // this coice is done only if ( !concaveVertices.empty() ) for Grids/smesh/bugs_19/X1
5465 // where the nodes are smoothed too far along a sphere thus creating
5466 // inverted _simplices
5467 double dist[theNbSmooFuns];
5468 //double coef[theNbSmooFuns] = { 1., 1.2, 1.4, 1.4 };
5469 double coef[theNbSmooFuns] = { 1., 1., 1., 1. };
5471 double minDist = Precision::Infinite();
5472 gp_Pnt p = SMESH_TNodeXYZ( _nodes[0] );
5473 for ( int i = 0; i < FUN_NEFPOLY; ++i )
5475 gp_Pnt newP = (this->*_funs[i])();
5476 dist[i] = p.SquareDistance( newP );
5477 if ( dist[i]*coef[i] < minDist )
5479 _smooFunction = _funs[i];
5480 minDist = dist[i]*coef[i];
5486 _smooFunction = _funs[ FUN_LAPLACIAN ];
5489 // for ( size_t i = 0; i < _simplices.size(); ++i )
5490 // minDim = Min( minDim, _simplices[i]._nPrev->GetPosition()->GetDim() );
5491 // if ( minDim == 0 )
5492 // _smooFunction = _funs[ FUN_CENTROIDAL ];
5493 // else if ( minDim == 1 )
5494 // _smooFunction = _funs[ FUN_CENTROIDAL ];
5498 // for ( int i = 0; i < FUN_NB; ++i )
5500 // //cout << dist[i] << " ";
5501 // if ( _smooFunction == _funs[i] ) {
5503 // //debugMsg( fNames[i] );
5507 // cout << _funNames[ iMin ] << "\t N:" << _nodes.back()->GetID() << endl;
5510 //================================================================================
5512 * \brief Returns a name of _SmooFunction
5514 //================================================================================
5516 int _LayerEdge::smooFunID( _LayerEdge::PSmooFun fun) const
5519 fun = _smooFunction;
5520 for ( int i = 0; i < theNbSmooFuns; ++i )
5521 if ( fun == _funs[i] )
5524 return theNbSmooFuns;
5527 //================================================================================
5529 * \brief Computes a new node position using Laplacian smoothing
5531 //================================================================================
5533 gp_XYZ _LayerEdge::smoothLaplacian()
5535 gp_XYZ newPos (0,0,0);
5536 for ( size_t i = 0; i < _simplices.size(); ++i )
5537 newPos += SMESH_TNodeXYZ( _simplices[i]._nPrev );
5538 newPos /= _simplices.size();
5543 //================================================================================
5545 * \brief Computes a new node position using angular-based smoothing
5547 //================================================================================
5549 gp_XYZ _LayerEdge::smoothAngular()
5551 vector< gp_Vec > edgeDir; edgeDir. reserve( _simplices.size() + 1);
5552 vector< double > edgeSize; edgeSize.reserve( _simplices.size() );
5553 vector< gp_XYZ > points; points. reserve( _simplices.size() );
5555 gp_XYZ pPrev = SMESH_TNodeXYZ( _simplices.back()._nPrev );
5557 for ( size_t i = 0; i < _simplices.size(); ++i )
5559 gp_XYZ p = SMESH_TNodeXYZ( _simplices[i]._nPrev );
5560 edgeDir.push_back( p - pPrev );
5561 edgeSize.push_back( edgeDir.back().Magnitude() );
5562 //double edgeSize = edgeDir.back().Magnitude();
5563 if ( edgeSize.back() < numeric_limits<double>::min() )
5566 edgeSize.pop_back();
5570 edgeDir.back() /= edgeSize.back();
5571 points.push_back( p );
5576 edgeDir.push_back ( edgeDir[0] );
5577 edgeSize.push_back( edgeSize[0] );
5578 pN /= points.size();
5580 gp_XYZ newPos(0,0,0);
5581 //gp_XYZ pN = SMESH_TNodeXYZ( _nodes.back() );
5583 for ( size_t i = 0; i < points.size(); ++i )
5585 gp_Vec toN( pN - points[i]);
5586 double toNLen = toN.Magnitude();
5587 if ( toNLen < numeric_limits<double>::min() )
5592 gp_Vec bisec = edgeDir[i] + edgeDir[i+1];
5593 double bisecLen = bisec.SquareMagnitude();
5594 if ( bisecLen < numeric_limits<double>::min() )
5596 gp_Vec norm = edgeDir[i] ^ toN;
5597 bisec = norm ^ edgeDir[i];
5598 bisecLen = bisec.SquareMagnitude();
5600 bisecLen = Sqrt( bisecLen );
5605 gp_XYZ pNew = ( points[i] + bisec.XYZ() * toNLen ) * bisecLen;
5606 sumSize += bisecLen;
5608 gp_XYZ pNew = ( points[i] + bisec.XYZ() * toNLen ) * ( edgeSize[i] + edgeSize[i+1] );
5609 sumSize += ( edgeSize[i] + edgeSize[i+1] );
5618 //================================================================================
5620 * \brief Computes a new node position using weigthed node positions
5622 //================================================================================
5624 gp_XYZ _LayerEdge::smoothLengthWeighted()
5626 vector< double > edgeSize; edgeSize.reserve( _simplices.size() + 1);
5627 vector< gp_XYZ > points; points. reserve( _simplices.size() );
5629 gp_XYZ pPrev = SMESH_TNodeXYZ( _simplices.back()._nPrev );
5630 for ( size_t i = 0; i < _simplices.size(); ++i )
5632 gp_XYZ p = SMESH_TNodeXYZ( _simplices[i]._nPrev );
5633 edgeSize.push_back( ( p - pPrev ).Modulus() );
5634 if ( edgeSize.back() < numeric_limits<double>::min() )
5636 edgeSize.pop_back();
5640 points.push_back( p );
5644 edgeSize.push_back( edgeSize[0] );
5646 gp_XYZ newPos(0,0,0);
5648 for ( size_t i = 0; i < points.size(); ++i )
5650 newPos += points[i] * ( edgeSize[i] + edgeSize[i+1] );
5651 sumSize += edgeSize[i] + edgeSize[i+1];
5657 //================================================================================
5659 * \brief Computes a new node position using angular-based smoothing
5661 //================================================================================
5663 gp_XYZ _LayerEdge::smoothCentroidal()
5665 gp_XYZ newPos(0,0,0);
5666 gp_XYZ pN = SMESH_TNodeXYZ( _nodes.back() );
5668 for ( size_t i = 0; i < _simplices.size(); ++i )
5670 gp_XYZ p1 = SMESH_TNodeXYZ( _simplices[i]._nPrev );
5671 gp_XYZ p2 = SMESH_TNodeXYZ( _simplices[i]._nNext );
5672 gp_XYZ gc = ( pN + p1 + p2 ) / 3.;
5673 double size = (( p1 - pN ) ^ ( p2 - pN )).Modulus();
5676 newPos += gc * size;
5683 //================================================================================
5685 * \brief Computes a new node position located inside a Nef polygon
5687 //================================================================================
5689 gp_XYZ _LayerEdge::smoothNefPolygon()
5691 gp_XYZ newPos(0,0,0);
5693 // get a plane to seach a solution on
5695 vector< gp_XYZ > vecs( _simplices.size() + 1 );
5697 const double tol = numeric_limits<double>::min();
5698 gp_XYZ center(0,0,0);
5699 for ( i = 0; i < _simplices.size(); ++i )
5701 vecs[i] = ( SMESH_TNodeXYZ( _simplices[i]._nNext ) -
5702 SMESH_TNodeXYZ( _simplices[i]._nPrev ));
5703 center += SMESH_TNodeXYZ( _simplices[i]._nPrev );
5705 vecs.back() = vecs[0];
5706 center /= _simplices.size();
5708 gp_XYZ zAxis(0,0,0);
5709 for ( i = 0; i < _simplices.size(); ++i )
5710 zAxis += vecs[i] ^ vecs[i+1];
5713 for ( i = 0; i < _simplices.size(); ++i )
5716 if ( yAxis.SquareModulus() > tol )
5719 gp_XYZ xAxis = yAxis ^ zAxis;
5720 // SMESH_TNodeXYZ p0( _simplices[0]._nPrev );
5721 // const double tol = 1e-6 * ( p0.Distance( _simplices[1]._nPrev ) +
5722 // p0.Distance( _simplices[2]._nPrev ));
5723 // gp_XYZ center = smoothLaplacian();
5724 // gp_XYZ xAxis, yAxis, zAxis;
5725 // for ( i = 0; i < _simplices.size(); ++i )
5727 // xAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
5728 // if ( xAxis.SquareModulus() > tol*tol )
5731 // for ( i = 1; i < _simplices.size(); ++i )
5733 // yAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
5734 // zAxis = xAxis ^ yAxis;
5735 // if ( zAxis.SquareModulus() > tol*tol )
5738 // if ( i == _simplices.size() ) return newPos;
5740 yAxis = zAxis ^ xAxis;
5741 xAxis /= xAxis.Modulus();
5742 yAxis /= yAxis.Modulus();
5744 // get half-planes of _simplices
5746 vector< _halfPlane > halfPlns( _simplices.size() );
5748 for ( size_t i = 0; i < _simplices.size(); ++i )
5750 gp_XYZ OP1 = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
5751 gp_XYZ OP2 = SMESH_TNodeXYZ( _simplices[i]._nNext ) - center;
5752 gp_XY p1( OP1 * xAxis, OP1 * yAxis );
5753 gp_XY p2( OP2 * xAxis, OP2 * yAxis );
5754 gp_XY vec12 = p2 - p1;
5755 double dist12 = vec12.Modulus();
5759 halfPlns[ nbHP ]._pos = p1;
5760 halfPlns[ nbHP ]._dir = vec12;
5761 halfPlns[ nbHP ]._inNorm.SetCoord( -vec12.Y(), vec12.X() );
5765 // intersect boundaries of half-planes, define state of intersection points
5766 // in relation to all half-planes and calculate internal point of a 2D polygon
5769 gp_XY newPos2D (0,0);
5771 enum { UNDEF = -1, NOT_OUT, IS_OUT, NO_INT };
5772 typedef std::pair< gp_XY, int > TIntPntState; // coord and isOut state
5773 TIntPntState undefIPS( gp_XY(1e100,1e100), UNDEF );
5775 vector< vector< TIntPntState > > allIntPnts( nbHP );
5776 for ( int iHP1 = 0; iHP1 < nbHP; ++iHP1 )
5778 vector< TIntPntState > & intPnts1 = allIntPnts[ iHP1 ];
5779 if ( intPnts1.empty() ) intPnts1.resize( nbHP, undefIPS );
5781 int iPrev = SMESH_MesherHelper::WrapIndex( iHP1 - 1, nbHP );
5782 int iNext = SMESH_MesherHelper::WrapIndex( iHP1 + 1, nbHP );
5785 const gp_XY* segEnds[2] = { 0, 0 }; // NOT_OUT points
5787 for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
5789 if ( iHP1 == iHP2 ) continue;
5791 TIntPntState & ips1 = intPnts1[ iHP2 ];
5792 if ( ips1.second == UNDEF )
5794 // find an intersection point of boundaries of iHP1 and iHP2
5796 if ( iHP2 == iPrev ) // intersection with neighbors is known
5797 ips1.first = halfPlns[ iHP1 ]._pos;
5798 else if ( iHP2 == iNext )
5799 ips1.first = halfPlns[ iHP2 ]._pos;
5800 else if ( !halfPlns[ iHP1 ].FindInterestion( halfPlns[ iHP2 ], ips1.first ))
5801 ips1.second = NO_INT;
5803 // classify the found intersection point
5804 if ( ips1.second != NO_INT )
5806 ips1.second = NOT_OUT;
5807 for ( int i = 0; i < nbHP && ips1.second == NOT_OUT; ++i )
5808 if ( i != iHP1 && i != iHP2 &&
5809 halfPlns[ i ].IsOut( ips1.first, tol ))
5810 ips1.second = IS_OUT;
5812 vector< TIntPntState > & intPnts2 = allIntPnts[ iHP2 ];
5813 if ( intPnts2.empty() ) intPnts2.resize( nbHP, undefIPS );
5814 TIntPntState & ips2 = intPnts2[ iHP1 ];
5817 if ( ips1.second == NOT_OUT )
5820 segEnds[ bool(segEnds[0]) ] = & ips1.first;
5824 // find a NOT_OUT segment of boundary which is located between
5825 // two NOT_OUT int points
5828 continue; // no such a segment
5832 // sort points along the boundary
5833 map< double, TIntPntState* > ipsByParam;
5834 for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
5836 TIntPntState & ips1 = intPnts1[ iHP2 ];
5837 if ( ips1.second != NO_INT )
5839 gp_XY op = ips1.first - halfPlns[ iHP1 ]._pos;
5840 double param = op * halfPlns[ iHP1 ]._dir;
5841 ipsByParam.insert( make_pair( param, & ips1 ));
5844 // look for two neighboring NOT_OUT points
5846 map< double, TIntPntState* >::iterator u2ips = ipsByParam.begin();
5847 for ( ; u2ips != ipsByParam.end(); ++u2ips )
5849 TIntPntState & ips1 = *(u2ips->second);
5850 if ( ips1.second == NOT_OUT )
5851 segEnds[ bool( nbNotOut++ ) ] = & ips1.first;
5852 else if ( nbNotOut >= 2 )
5859 if ( nbNotOut >= 2 )
5861 double len = ( *segEnds[0] - *segEnds[1] ).Modulus();
5864 newPos2D += 0.5 * len * ( *segEnds[0] + *segEnds[1] );
5871 newPos = center + xAxis * newPos2D.X() + yAxis * newPos2D.Y();
5881 //================================================================================
5883 * \brief Add a new segment to _LayerEdge during inflation
5885 //================================================================================
5887 void _LayerEdge::SetNewLength( double len, SMESH_MesherHelper& helper )
5889 if ( _len - len > -1e-6 )
5891 //_pos.push_back( _pos.back() );
5895 SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
5896 SMESH_TNodeXYZ oldXYZ( n );
5897 gp_XYZ nXYZ = oldXYZ + _normal * ( len - _len ) * _lenFactor;
5898 n->setXYZ( nXYZ.X(), nXYZ.Y(), nXYZ.Z() );
5900 _pos.push_back( nXYZ );
5902 if ( !_sWOL.IsNull() )
5905 if ( _sWOL.ShapeType() == TopAbs_EDGE )
5907 double u = Precision::Infinite(); // to force projection w/o distance check
5908 helper.CheckNodeU( TopoDS::Edge( _sWOL ), n, u, 1e-10, /*force=*/true, distXYZ );
5909 _pos.back().SetCoord( u, 0, 0 );
5910 if ( _nodes.size() > 1 )
5912 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( n->GetPosition() );
5913 pos->SetUParameter( u );
5918 gp_XY uv( Precision::Infinite(), 0 );
5919 helper.CheckNodeUV( TopoDS::Face( _sWOL ), n, uv, 1e-10, /*force=*/true, distXYZ );
5920 _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
5921 if ( _nodes.size() > 1 )
5923 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( n->GetPosition() );
5924 pos->SetUParameter( uv.X() );
5925 pos->SetVParameter( uv.Y() );
5928 n->setXYZ( distXYZ[1], distXYZ[2], distXYZ[3]);
5930 dumpMove( n ); //debug
5933 //================================================================================
5935 * \brief Remove last inflation step
5937 //================================================================================
5939 void _LayerEdge::InvalidateStep( int curStep, bool restoreLength )
5941 if ( _pos.size() > curStep )
5943 if ( restoreLength )
5944 _len -= ( _pos[ curStep-1 ] - _pos.back() ).Modulus();
5946 _pos.resize( curStep );
5947 gp_Pnt nXYZ = _pos.back();
5948 SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
5949 if ( !_sWOL.IsNull() )
5951 TopLoc_Location loc;
5952 if ( _sWOL.ShapeType() == TopAbs_EDGE )
5954 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( n->GetPosition() );
5955 pos->SetUParameter( nXYZ.X() );
5957 Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( _sWOL ), loc, f,l);
5958 nXYZ = curve->Value( nXYZ.X() ).Transformed( loc );
5962 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( n->GetPosition() );
5963 pos->SetUParameter( nXYZ.X() );
5964 pos->SetVParameter( nXYZ.Y() );
5965 Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face(_sWOL), loc );
5966 nXYZ = surface->Value( nXYZ.X(), nXYZ.Y() ).Transformed( loc );
5969 n->setXYZ( nXYZ.X(), nXYZ.Y(), nXYZ.Z() );
5974 //================================================================================
5976 * \brief Create layers of prisms
5978 //================================================================================
5980 bool _ViscousBuilder::refine(_SolidData& data)
5982 SMESH_MesherHelper helper( *_mesh );
5983 helper.SetSubShape( data._solid );
5984 helper.SetElementsOnShape(false);
5986 Handle(Geom_Curve) curve;
5987 Handle(Geom_Surface) surface;
5988 TopoDS_Edge geomEdge;
5989 TopoDS_Face geomFace;
5990 TopoDS_Shape prevSWOL;
5991 TopLoc_Location loc;
5995 TGeomID prevBaseId = -1;
5996 TNode2Edge* n2eMap = 0;
5997 TNode2Edge::iterator n2e;
5999 // Create intermediate nodes on each _LayerEdge
6001 int iS = 0, iEnd = data._endEdgeOnShape[ iS ];
6003 for ( size_t i = 0; i < data._edges.size(); ++i )
6005 _LayerEdge& edge = *data._edges[i];
6007 if ( edge._nodes.size() < 2 )
6008 continue; // on _noShrinkShapes
6010 // get parameters of layers for the edge
6012 iEnd = data._endEdgeOnShape[ ++iS ];
6013 const AverageHyp& hyp = data._hypOnShape[ iS ];
6015 // get accumulated length of segments
6016 vector< double > segLen( edge._pos.size() );
6018 for ( size_t j = 1; j < edge._pos.size(); ++j )
6019 segLen[j] = segLen[j-1] + (edge._pos[j-1] - edge._pos[j] ).Modulus();
6021 // allocate memory for new nodes if it is not yet refined
6022 const SMDS_MeshNode* tgtNode = edge._nodes.back();
6023 if ( edge._nodes.size() == 2 )
6025 edge._nodes.resize( hyp.GetNumberLayers() + 1, 0 );
6027 edge._nodes.back() = tgtNode;
6029 // get data of a shrink shape
6030 if ( !edge._sWOL.IsNull() && edge._sWOL != prevSWOL )
6032 isOnEdge = ( edge._sWOL.ShapeType() == TopAbs_EDGE );
6035 geomEdge = TopoDS::Edge( edge._sWOL );
6036 curve = BRep_Tool::Curve( geomEdge, loc, f,l);
6040 geomFace = TopoDS::Face( edge._sWOL );
6041 surface = BRep_Tool::Surface( geomFace, loc );
6043 prevSWOL = edge._sWOL;
6045 // restore shapePos of the last node by already treated _LayerEdge of another _SolidData
6046 const TGeomID baseShapeId = edge._nodes[0]->getshapeId();
6047 if ( baseShapeId != prevBaseId )
6049 map< TGeomID, TNode2Edge* >::iterator s2ne = data._s2neMap.find( baseShapeId );
6050 n2eMap = ( s2ne == data._s2neMap.end() ) ? 0 : n2eMap = s2ne->second;
6051 prevBaseId = baseShapeId;
6053 _LayerEdge* edgeOnSameNode = 0;
6054 if ( n2eMap && (( n2e = n2eMap->find( edge._nodes[0] )) != n2eMap->end() ))
6056 edgeOnSameNode = n2e->second;
6057 const gp_XYZ& otherTgtPos = edgeOnSameNode->_pos.back();
6058 SMDS_PositionPtr lastPos = tgtNode->GetPosition();
6061 SMDS_EdgePosition* epos = static_cast<SMDS_EdgePosition*>( lastPos );
6062 epos->SetUParameter( otherTgtPos.X() );
6066 SMDS_FacePosition* fpos = static_cast<SMDS_FacePosition*>( lastPos );
6067 fpos->SetUParameter( otherTgtPos.X() );
6068 fpos->SetVParameter( otherTgtPos.Y() );
6071 // calculate height of the first layer
6073 const double T = segLen.back(); //data._hyp.GetTotalThickness();
6074 const double f = hyp.GetStretchFactor();
6075 const int N = hyp.GetNumberLayers();
6076 const double fPowN = pow( f, N );
6077 if ( fPowN - 1 <= numeric_limits<double>::min() )
6080 h0 = T * ( f - 1 )/( fPowN - 1 );
6082 const double zeroLen = std::numeric_limits<double>::min();
6084 // create intermediate nodes
6085 double hSum = 0, hi = h0/f;
6087 for ( size_t iStep = 1; iStep < edge._nodes.size(); ++iStep )
6089 // compute an intermediate position
6092 while ( hSum > segLen[iSeg] && iSeg < segLen.size()-1)
6094 int iPrevSeg = iSeg-1;
6095 while ( fabs( segLen[iPrevSeg] - segLen[iSeg]) <= zeroLen && iPrevSeg > 0 )
6097 double r = ( segLen[iSeg] - hSum ) / ( segLen[iSeg] - segLen[iPrevSeg] );
6098 gp_Pnt pos = r * edge._pos[iPrevSeg] + (1-r) * edge._pos[iSeg];
6100 SMDS_MeshNode*& node = const_cast< SMDS_MeshNode*& >( edge._nodes[ iStep ]);
6101 if ( !edge._sWOL.IsNull() )
6103 // compute XYZ by parameters <pos>
6108 pos = curve->Value( u ).Transformed(loc);
6112 uv.SetCoord( pos.X(), pos.Y() );
6114 pos = surface->Value( pos.X(), pos.Y() ).Transformed(loc);
6117 // create or update the node
6120 node = helper.AddNode( pos.X(), pos.Y(), pos.Z());
6121 if ( !edge._sWOL.IsNull() )
6124 getMeshDS()->SetNodeOnEdge( node, geomEdge, u );
6126 getMeshDS()->SetNodeOnFace( node, geomFace, uv.X(), uv.Y() );
6130 getMeshDS()->SetNodeInVolume( node, helper.GetSubShapeID() );
6135 if ( !edge._sWOL.IsNull() )
6137 // make average pos from new and current parameters
6140 u = 0.5 * ( u + helper.GetNodeU( geomEdge, node ));
6141 pos = curve->Value( u ).Transformed(loc);
6143 SMDS_EdgePosition* epos = static_cast<SMDS_EdgePosition*>( node->GetPosition() );
6144 epos->SetUParameter( u );
6148 uv = 0.5 * ( uv + helper.GetNodeUV( geomFace, node ));
6149 pos = surface->Value( uv.X(), uv.Y()).Transformed(loc);
6151 SMDS_FacePosition* fpos = static_cast<SMDS_FacePosition*>( node->GetPosition() );
6152 fpos->SetUParameter( uv.X() );
6153 fpos->SetVParameter( uv.Y() );
6156 node->setXYZ( pos.X(), pos.Y(), pos.Z() );
6158 } // loop on edge._nodes
6160 if ( !edge._sWOL.IsNull() ) // prepare for shrink()
6163 edge._pos.back().SetCoord( u, 0,0);
6165 edge._pos.back().SetCoord( uv.X(), uv.Y() ,0);
6167 if ( edgeOnSameNode )
6168 edgeOnSameNode->_pos.back() = edge._pos.back();
6171 } // loop on data._edges to create nodes
6173 if ( !getMeshDS()->IsEmbeddedMode() )
6174 // Log node movement
6175 for ( size_t i = 0; i < data._edges.size(); ++i )
6177 _LayerEdge& edge = *data._edges[i];
6178 SMESH_TNodeXYZ p ( edge._nodes.back() );
6179 getMeshDS()->MoveNode( p._node, p.X(), p.Y(), p.Z() );
6184 helper.SetElementsOnShape(true);
6186 vector< vector<const SMDS_MeshNode*>* > nnVec;
6187 set< vector<const SMDS_MeshNode*>* > nnSet;
6188 set< int > degenEdgeInd;
6189 vector<const SMDS_MeshElement*> degenVols;
6191 TopExp_Explorer exp( data._solid, TopAbs_FACE );
6192 for ( ; exp.More(); exp.Next() )
6194 const TGeomID faceID = getMeshDS()->ShapeToIndex( exp.Current() );
6195 if ( data._ignoreFaceIds.count( faceID ))
6197 const bool isReversedFace = data._reversedFaceIds.count( faceID );
6198 SMESHDS_SubMesh* fSubM = getMeshDS()->MeshElements( exp.Current() );
6199 SMDS_ElemIteratorPtr fIt = fSubM->GetElements();
6200 while ( fIt->more() )
6202 const SMDS_MeshElement* face = fIt->next();
6203 const int nbNodes = face->NbCornerNodes();
6204 nnVec.resize( nbNodes );
6206 degenEdgeInd.clear();
6208 SMDS_NodeIteratorPtr nIt = face->nodeIterator();
6209 for ( int iN = 0; iN < nbNodes; ++iN )
6211 const SMDS_MeshNode* n = nIt->next();
6212 const int i = isReversedFace ? nbNodes-1-iN : iN;
6213 nnVec[ i ] = & data._n2eMap[ n ]->_nodes;
6214 if ( nnVec[ i ]->size() < 2 )
6215 degenEdgeInd.insert( iN );
6217 nbZ = nnVec[ i ]->size();
6219 if ( helper.HasDegeneratedEdges() )
6220 nnSet.insert( nnVec[ i ]);
6224 if ( 0 < nnSet.size() && nnSet.size() < 3 )
6230 switch ( degenEdgeInd.size() )
6234 for ( int iZ = 1; iZ < nbZ; ++iZ )
6235 helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1], (*nnVec[2])[iZ-1],
6236 (*nnVec[0])[iZ], (*nnVec[1])[iZ], (*nnVec[2])[iZ]);
6241 int i2 = *degenEdgeInd.begin();
6242 int i0 = helper.WrapIndex( i2 - 1, nbNodes );
6243 int i1 = helper.WrapIndex( i2 + 1, nbNodes );
6244 for ( int iZ = 1; iZ < nbZ; ++iZ )
6245 helper.AddVolume( (*nnVec[i0])[iZ-1], (*nnVec[i1])[iZ-1],
6246 (*nnVec[i1])[iZ], (*nnVec[i0])[iZ], (*nnVec[i2])[0]);
6251 int i3 = !degenEdgeInd.count(0) ? 0 : !degenEdgeInd.count(1) ? 1 : 2;
6252 for ( int iZ = 1; iZ < nbZ; ++iZ )
6253 helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1], (*nnVec[2])[iZ-1],
6261 switch ( degenEdgeInd.size() )
6265 for ( int iZ = 1; iZ < nbZ; ++iZ )
6266 helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1],
6267 (*nnVec[2])[iZ-1], (*nnVec[3])[iZ-1],
6268 (*nnVec[0])[iZ], (*nnVec[1])[iZ],
6269 (*nnVec[2])[iZ], (*nnVec[3])[iZ]);
6274 int i2 = *degenEdgeInd.begin();
6275 int i3 = *degenEdgeInd.rbegin();
6276 bool ok = ( i3 - i2 == 1 );
6277 if ( i2 == 0 && i3 == 3 ) { i2 = 3; i3 = 0; ok = true; }
6278 int i0 = helper.WrapIndex( i3 + 1, nbNodes );
6279 int i1 = helper.WrapIndex( i0 + 1, nbNodes );
6280 for ( int iZ = 1; iZ < nbZ; ++iZ )
6282 const SMDS_MeshElement* vol =
6283 helper.AddVolume( (*nnVec[i3])[0], (*nnVec[i0])[iZ], (*nnVec[i0])[iZ-1],
6284 (*nnVec[i2])[0], (*nnVec[i1])[iZ], (*nnVec[i1])[iZ-1]);
6286 degenVols.push_back( vol );
6290 case 3: // degen HEX
6292 const SMDS_MeshNode* nn[8];
6293 for ( int iZ = 1; iZ < nbZ; ++iZ )
6295 const SMDS_MeshElement* vol =
6296 helper.AddVolume( nnVec[0]->size() > 1 ? (*nnVec[0])[iZ-1] : (*nnVec[0])[0],
6297 nnVec[1]->size() > 1 ? (*nnVec[1])[iZ-1] : (*nnVec[1])[0],
6298 nnVec[2]->size() > 1 ? (*nnVec[2])[iZ-1] : (*nnVec[2])[0],
6299 nnVec[3]->size() > 1 ? (*nnVec[3])[iZ-1] : (*nnVec[3])[0],
6300 nnVec[0]->size() > 1 ? (*nnVec[0])[iZ] : (*nnVec[0])[0],
6301 nnVec[1]->size() > 1 ? (*nnVec[1])[iZ] : (*nnVec[1])[0],
6302 nnVec[2]->size() > 1 ? (*nnVec[2])[iZ] : (*nnVec[2])[0],
6303 nnVec[3]->size() > 1 ? (*nnVec[3])[iZ] : (*nnVec[3])[0]);
6304 degenVols.push_back( vol );
6312 return error("Not supported type of element", data._index);
6314 } // switch ( nbNodes )
6315 } // while ( fIt->more() )
6318 if ( !degenVols.empty() )
6320 SMESH_ComputeErrorPtr& err = _mesh->GetSubMesh( data._solid )->GetComputeError();
6321 if ( !err || err->IsOK() )
6323 err.reset( new SMESH_ComputeError( COMPERR_WARNING,
6324 "Degenerated volumes created" ));
6325 err->myBadElements.insert( err->myBadElements.end(),
6326 degenVols.begin(),degenVols.end() );
6333 //================================================================================
6335 * \brief Shrink 2D mesh on faces to let space for inflated layers
6337 //================================================================================
6339 bool _ViscousBuilder::shrink()
6341 // make map of (ids of FACEs to shrink mesh on) to (_SolidData containing _LayerEdge's
6342 // inflated along FACE or EDGE)
6343 map< TGeomID, _SolidData* > f2sdMap;
6344 for ( size_t i = 0 ; i < _sdVec.size(); ++i )
6346 _SolidData& data = _sdVec[i];
6347 TopTools_MapOfShape FFMap;
6348 map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
6349 for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
6350 if ( s2s->second.ShapeType() == TopAbs_FACE )
6352 f2sdMap.insert( make_pair( getMeshDS()->ShapeToIndex( s2s->second ), &data ));
6354 if ( FFMap.Add( (*s2s).second ))
6355 // Put mesh faces on the shrinked FACE to the proxy sub-mesh to avoid
6356 // usage of mesh faces made in addBoundaryElements() by the 3D algo or
6357 // by StdMeshers_QuadToTriaAdaptor
6358 if ( SMESHDS_SubMesh* smDS = getMeshDS()->MeshElements( s2s->second ))
6360 SMESH_ProxyMesh::SubMesh* proxySub =
6361 data._proxyMesh->getFaceSubM( TopoDS::Face( s2s->second ), /*create=*/true);
6362 SMDS_ElemIteratorPtr fIt = smDS->GetElements();
6363 while ( fIt->more() )
6364 proxySub->AddElement( fIt->next() );
6365 // as a result 3D algo will use elements from proxySub and not from smDS
6370 SMESH_MesherHelper helper( *_mesh );
6371 helper.ToFixNodeParameters( true );
6374 map< TGeomID, _Shrinker1D > e2shrMap;
6375 vector< _LayerEdge* > lEdges;
6377 // loop on FACES to srink mesh on
6378 map< TGeomID, _SolidData* >::iterator f2sd = f2sdMap.begin();
6379 for ( ; f2sd != f2sdMap.end(); ++f2sd )
6381 _SolidData& data = *f2sd->second;
6382 const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( f2sd->first ));
6383 SMESH_subMesh* sm = _mesh->GetSubMesh( F );
6384 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
6386 Handle(Geom_Surface) surface = BRep_Tool::Surface(F);
6388 helper.SetSubShape(F);
6390 // ===========================
6391 // Prepare data for shrinking
6392 // ===========================
6394 // Collect nodes to smooth, as src nodes are not yet replaced by tgt ones
6395 // and thus all nodes on a FACE connected to 2d elements are to be smoothed
6396 vector < const SMDS_MeshNode* > smoothNodes;
6398 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
6399 while ( nIt->more() )
6401 const SMDS_MeshNode* n = nIt->next();
6402 if ( n->NbInverseElements( SMDSAbs_Face ) > 0 )
6403 smoothNodes.push_back( n );
6406 // Find out face orientation
6408 const set<TGeomID> ignoreShapes;
6410 if ( !smoothNodes.empty() )
6412 vector<_Simplex> simplices;
6413 _Simplex::GetSimplices( smoothNodes[0], simplices, ignoreShapes );
6414 helper.GetNodeUV( F, simplices[0]._nPrev, 0, &isOkUV ); // fix UV of silpmex nodes
6415 helper.GetNodeUV( F, simplices[0]._nNext, 0, &isOkUV );
6416 gp_XY uv = helper.GetNodeUV( F, smoothNodes[0], 0, &isOkUV );
6417 if ( !simplices[0].IsForward(uv, smoothNodes[0], F, helper,refSign) )
6421 // Find _LayerEdge's inflated along F
6424 set< TGeomID > subIDs;
6425 SMESH_subMeshIteratorPtr subIt = sm->getDependsOnIterator(/*includeSelf=*/false);
6426 while ( subIt->more() )
6427 subIDs.insert( subIt->next()->GetId() );
6430 for ( int iS = 0; iS < data._endEdgeOnShape.size() && !subIDs.empty(); ++iS )
6433 iEnd = data._endEdgeOnShape[ iS ];
6434 TGeomID shapeID = data._edges[ iBeg ]->_nodes[0]->getshapeId();
6435 set< TGeomID >::iterator idIt = subIDs.find( shapeID );
6436 if ( idIt == subIDs.end() ||
6437 data._edges[ iBeg ]->_sWOL.IsNull() ) continue;
6438 subIDs.erase( idIt );
6440 if ( !data._noShrinkShapes.count( shapeID ))
6441 for ( ; iBeg < iEnd; ++iBeg )
6443 lEdges.push_back( data._edges[ iBeg ] );
6444 prepareEdgeToShrink( *data._edges[ iBeg ], F, helper, smDS );
6449 dumpFunction(SMESH_Comment("beforeShrinkFace")<<f2sd->first); // debug
6450 SMDS_ElemIteratorPtr fIt = smDS->GetElements();
6451 while ( fIt->more() )
6452 if ( const SMDS_MeshElement* f = fIt->next() )
6453 dumpChangeNodes( f );
6456 // Replace source nodes by target nodes in mesh faces to shrink
6457 dumpFunction(SMESH_Comment("replNodesOnFace")<<f2sd->first); // debug
6458 const SMDS_MeshNode* nodes[20];
6459 for ( size_t i = 0; i < lEdges.size(); ++i )
6461 _LayerEdge& edge = *lEdges[i];
6462 const SMDS_MeshNode* srcNode = edge._nodes[0];
6463 const SMDS_MeshNode* tgtNode = edge._nodes.back();
6464 SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
6465 while ( fIt->more() )
6467 const SMDS_MeshElement* f = fIt->next();
6468 if ( !smDS->Contains( f ))
6470 SMDS_NodeIteratorPtr nIt = f->nodeIterator();
6471 for ( int iN = 0; nIt->more(); ++iN )
6473 const SMDS_MeshNode* n = nIt->next();
6474 nodes[iN] = ( n == srcNode ? tgtNode : n );
6476 helper.GetMeshDS()->ChangeElementNodes( f, nodes, f->NbNodes() );
6477 dumpChangeNodes( f );
6482 // find out if a FACE is concave
6483 const bool isConcaveFace = isConcave( F, helper );
6485 // Create _SmoothNode's on face F
6486 vector< _SmoothNode > nodesToSmooth( smoothNodes.size() );
6488 dumpFunction(SMESH_Comment("fixUVOnFace")<<f2sd->first); // debug
6489 const bool sortSimplices = isConcaveFace;
6490 for ( size_t i = 0; i < smoothNodes.size(); ++i )
6492 const SMDS_MeshNode* n = smoothNodes[i];
6493 nodesToSmooth[ i ]._node = n;
6494 // src nodes must be replaced by tgt nodes to have tgt nodes in _simplices
6495 _Simplex::GetSimplices( n, nodesToSmooth[ i ]._simplices, ignoreShapes, 0, sortSimplices);
6496 // fix up incorrect uv of nodes on the FACE
6497 helper.GetNodeUV( F, n, 0, &isOkUV);
6502 //if ( nodesToSmooth.empty() ) continue;
6504 // Find EDGE's to shrink and set simpices to LayerEdge's
6505 set< _Shrinker1D* > eShri1D;
6507 for ( size_t i = 0; i < lEdges.size(); ++i )
6509 _LayerEdge* edge = lEdges[i];
6510 if ( edge->_sWOL.ShapeType() == TopAbs_EDGE )
6512 TGeomID edgeIndex = getMeshDS()->ShapeToIndex( edge->_sWOL );
6513 _Shrinker1D& srinker = e2shrMap[ edgeIndex ];
6514 eShri1D.insert( & srinker );
6515 srinker.AddEdge( edge, helper );
6516 VISCOUS_3D::ToClearSubWithMain( _mesh->GetSubMesh( edge->_sWOL ), data._solid );
6517 // restore params of nodes on EGDE if the EDGE has been already
6518 // srinked while srinking another FACE
6519 srinker.RestoreParams();
6521 _Simplex::GetSimplices( /*tgtNode=*/edge->_nodes.back(), edge->_simplices, ignoreShapes );
6525 bool toFixTria = false; // to improve quality of trias by diagonal swap
6526 if ( isConcaveFace )
6528 const bool hasTria = _mesh->NbTriangles(), hasQuad = _mesh->NbQuadrangles();
6529 if ( hasTria != hasQuad ) {
6530 toFixTria = hasTria;
6533 set<int> nbNodesSet;
6534 SMDS_ElemIteratorPtr fIt = smDS->GetElements();
6535 while ( fIt->more() && nbNodesSet.size() < 2 )
6536 nbNodesSet.insert( fIt->next()->NbCornerNodes() );
6537 toFixTria = ( *nbNodesSet.begin() == 3 );
6541 // ==================
6542 // Perform shrinking
6543 // ==================
6545 bool shrinked = true;
6546 int badNb, shriStep=0, smooStep=0;
6547 _SmoothNode::SmoothType smoothType
6548 = isConcaveFace ? _SmoothNode::ANGULAR : _SmoothNode::LAPLACIAN;
6552 // Move boundary nodes (actually just set new UV)
6553 // -----------------------------------------------
6554 dumpFunction(SMESH_Comment("moveBoundaryOnF")<<f2sd->first<<"_st"<<shriStep ); // debug
6556 for ( size_t i = 0; i < lEdges.size(); ++i )
6558 shrinked |= lEdges[i]->SetNewLength2d( surface,F,helper );
6562 // Move nodes on EDGE's
6563 // (XYZ is set as soon as a needed length reached in SetNewLength2d())
6564 set< _Shrinker1D* >::iterator shr = eShri1D.begin();
6565 for ( ; shr != eShri1D.end(); ++shr )
6566 (*shr)->Compute( /*set3D=*/false, helper );
6569 // -----------------
6570 int nbNoImpSteps = 0;
6573 while (( nbNoImpSteps < 5 && badNb > 0) && moved)
6575 dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
6577 int oldBadNb = badNb;
6580 for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
6582 moved |= nodesToSmooth[i].Smooth( badNb,surface,helper,refSign,
6583 smoothType, /*set3D=*/isConcaveFace);
6585 if ( badNb < oldBadNb )
6593 return error(SMESH_Comment("Can't shrink 2D mesh on face ") << f2sd->first );
6594 if ( shriStep > 200 )
6595 return error(SMESH_Comment("Infinite loop at shrinking 2D mesh on face ") << f2sd->first );
6597 // Fix narrow triangles by swapping diagonals
6598 // ---------------------------------------
6601 set<const SMDS_MeshNode*> usedNodes;
6602 fixBadFaces( F, helper, /*is2D=*/true, shriStep, & usedNodes); // swap diagonals
6604 // update working data
6605 set<const SMDS_MeshNode*>::iterator n;
6606 for ( size_t i = 0; i < nodesToSmooth.size() && !usedNodes.empty(); ++i )
6608 n = usedNodes.find( nodesToSmooth[ i ]._node );
6609 if ( n != usedNodes.end())
6611 _Simplex::GetSimplices( nodesToSmooth[ i ]._node,
6612 nodesToSmooth[ i ]._simplices,
6614 /*sortSimplices=*/ smoothType == _SmoothNode::ANGULAR );
6615 usedNodes.erase( n );
6618 for ( size_t i = 0; i < lEdges.size() && !usedNodes.empty(); ++i )
6620 n = usedNodes.find( /*tgtNode=*/ lEdges[i]->_nodes.back() );
6621 if ( n != usedNodes.end())
6623 _Simplex::GetSimplices( lEdges[i]->_nodes.back(),
6624 lEdges[i]->_simplices,
6626 usedNodes.erase( n );
6630 // TODO: check effect of this additional smooth
6631 // additional laplacian smooth to increase allowed shrink step
6632 // for ( int st = 1; st; --st )
6634 // dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
6635 // for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
6637 // nodesToSmooth[i].Smooth( badNb,surface,helper,refSign,
6638 // _SmoothNode::LAPLACIAN,/*set3D=*/false);
6641 } // while ( shrinked )
6643 // No wrongly shaped faces remain; final smooth. Set node XYZ.
6644 bool isStructuredFixed = false;
6645 if ( SMESH_2D_Algo* algo = dynamic_cast<SMESH_2D_Algo*>( sm->GetAlgo() ))
6646 isStructuredFixed = algo->FixInternalNodes( *data._proxyMesh, F );
6647 if ( !isStructuredFixed )
6649 if ( isConcaveFace ) // fix narrow faces by swapping diagonals
6650 fixBadFaces( F, helper, /*is2D=*/false, ++shriStep );
6652 for ( int st = 3; st; --st )
6655 case 1: smoothType = _SmoothNode::LAPLACIAN; break;
6656 case 2: smoothType = _SmoothNode::LAPLACIAN; break;
6657 case 3: smoothType = _SmoothNode::ANGULAR; break;
6659 dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
6660 for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
6662 nodesToSmooth[i].Smooth( badNb,surface,helper,refSign,
6663 smoothType,/*set3D=*/st==1 );
6668 // Set an event listener to clear FACE sub-mesh together with SOLID sub-mesh
6669 VISCOUS_3D::ToClearSubWithMain( sm, data._solid );
6671 if ( !getMeshDS()->IsEmbeddedMode() )
6672 // Log node movement
6673 for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
6675 SMESH_TNodeXYZ p ( nodesToSmooth[i]._node );
6676 getMeshDS()->MoveNode( nodesToSmooth[i]._node, p.X(), p.Y(), p.Z() );
6679 } // loop on FACES to srink mesh on
6682 // Replace source nodes by target nodes in shrinked mesh edges
6684 map< int, _Shrinker1D >::iterator e2shr = e2shrMap.begin();
6685 for ( ; e2shr != e2shrMap.end(); ++e2shr )
6686 e2shr->second.SwapSrcTgtNodes( getMeshDS() );
6691 //================================================================================
6693 * \brief Computes 2d shrink direction and finds nodes limiting shrinking
6695 //================================================================================
6697 bool _ViscousBuilder::prepareEdgeToShrink( _LayerEdge& edge,
6698 const TopoDS_Face& F,
6699 SMESH_MesherHelper& helper,
6700 const SMESHDS_SubMesh* faceSubMesh)
6702 const SMDS_MeshNode* srcNode = edge._nodes[0];
6703 const SMDS_MeshNode* tgtNode = edge._nodes.back();
6705 if ( edge._sWOL.ShapeType() == TopAbs_FACE )
6707 gp_XY srcUV( edge._pos[0].X(), edge._pos[0].Y() );//helper.GetNodeUV( F, srcNode );
6708 gp_XY tgtUV = edge.LastUV( F ); //helper.GetNodeUV( F, tgtNode );
6709 gp_Vec2d uvDir( srcUV, tgtUV );
6710 double uvLen = uvDir.Magnitude();
6712 edge._normal.SetCoord( uvDir.X(),uvDir.Y(), 0 );
6715 edge._pos.resize(1);
6716 edge._pos[0].SetCoord( tgtUV.X(), tgtUV.Y(), 0 );
6718 // set UV of source node to target node
6719 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
6720 pos->SetUParameter( srcUV.X() );
6721 pos->SetVParameter( srcUV.Y() );
6723 else // _sWOL is TopAbs_EDGE
6725 const TopoDS_Edge& E = TopoDS::Edge( edge._sWOL );
6726 SMESHDS_SubMesh* edgeSM = getMeshDS()->MeshElements( E );
6727 if ( !edgeSM || edgeSM->NbElements() == 0 )
6728 return error(SMESH_Comment("Not meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
6730 const SMDS_MeshNode* n2 = 0;
6731 SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
6732 while ( eIt->more() && !n2 )
6734 const SMDS_MeshElement* e = eIt->next();
6735 if ( !edgeSM->Contains(e)) continue;
6736 n2 = e->GetNode( 0 );
6737 if ( n2 == srcNode ) n2 = e->GetNode( 1 );
6740 return error(SMESH_Comment("Wrongly meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
6742 double uSrc = helper.GetNodeU( E, srcNode, n2 );
6743 double uTgt = helper.GetNodeU( E, tgtNode, srcNode );
6744 double u2 = helper.GetNodeU( E, n2, srcNode );
6748 if ( fabs( uSrc-uTgt ) < 0.99 * fabs( uSrc-u2 ))
6750 // tgtNode is located so that it does not make faces with wrong orientation
6753 edge._pos.resize(1);
6754 edge._pos[0].SetCoord( U_TGT, uTgt );
6755 edge._pos[0].SetCoord( U_SRC, uSrc );
6756 edge._pos[0].SetCoord( LEN_TGT, fabs( uSrc-uTgt ));
6758 edge._simplices.resize( 1 );
6759 edge._simplices[0]._nPrev = n2;
6761 // set U of source node to the target node
6762 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
6763 pos->SetUParameter( uSrc );
6768 //================================================================================
6770 * \brief Restore position of a sole node of a _LayerEdge based on _noShrinkShapes
6772 //================================================================================
6774 void _ViscousBuilder::restoreNoShrink( _LayerEdge& edge ) const
6776 if ( edge._nodes.size() == 1 )
6781 const SMDS_MeshNode* srcNode = edge._nodes[0];
6782 TopoDS_Shape S = SMESH_MesherHelper::GetSubShapeByNode( srcNode, getMeshDS() );
6783 if ( S.IsNull() ) return;
6787 switch ( S.ShapeType() )
6792 TopLoc_Location loc;
6793 Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( S ), loc, f, l );
6794 if ( curve.IsNull() ) return;
6795 SMDS_EdgePosition* ePos = static_cast<SMDS_EdgePosition*>( srcNode->GetPosition() );
6796 p = curve->Value( ePos->GetUParameter() );
6801 p = BRep_Tool::Pnt( TopoDS::Vertex( S ));
6806 getMeshDS()->MoveNode( srcNode, p.X(), p.Y(), p.Z() );
6807 dumpMove( srcNode );
6811 //================================================================================
6813 * \brief Try to fix triangles with high aspect ratio by swaping diagonals
6815 //================================================================================
6817 void _ViscousBuilder::fixBadFaces(const TopoDS_Face& F,
6818 SMESH_MesherHelper& helper,
6821 set<const SMDS_MeshNode*> * involvedNodes)
6823 SMESH::Controls::AspectRatio qualifier;
6824 SMESH::Controls::TSequenceOfXYZ points(3), points1(3), points2(3);
6825 const double maxAspectRatio = is2D ? 4. : 2;
6826 _NodeCoordHelper xyz( F, helper, is2D );
6828 // find bad triangles
6830 vector< const SMDS_MeshElement* > badTrias;
6831 vector< double > badAspects;
6832 SMESHDS_SubMesh* sm = helper.GetMeshDS()->MeshElements( F );
6833 SMDS_ElemIteratorPtr fIt = sm->GetElements();
6834 while ( fIt->more() )
6836 const SMDS_MeshElement * f = fIt->next();
6837 if ( f->NbCornerNodes() != 3 ) continue;
6838 for ( int iP = 0; iP < 3; ++iP ) points(iP+1) = xyz( f->GetNode(iP));
6839 double aspect = qualifier.GetValue( points );
6840 if ( aspect > maxAspectRatio )
6842 badTrias.push_back( f );
6843 badAspects.push_back( aspect );
6848 dumpFunction(SMESH_Comment("beforeSwapDiagonals_F")<<helper.GetSubShapeID());
6849 SMDS_ElemIteratorPtr fIt = sm->GetElements();
6850 while ( fIt->more() )
6852 const SMDS_MeshElement * f = fIt->next();
6853 if ( f->NbCornerNodes() == 3 )
6854 dumpChangeNodes( f );
6858 if ( badTrias.empty() )
6861 // find couples of faces to swap diagonal
6863 typedef pair < const SMDS_MeshElement* , const SMDS_MeshElement* > T2Trias;
6864 vector< T2Trias > triaCouples;
6866 TIDSortedElemSet involvedFaces, emptySet;
6867 for ( size_t iTia = 0; iTia < badTrias.size(); ++iTia )
6870 double aspRatio [3];
6873 if ( !involvedFaces.insert( badTrias[iTia] ).second )
6875 for ( int iP = 0; iP < 3; ++iP )
6876 points(iP+1) = xyz( badTrias[iTia]->GetNode(iP));
6878 // find triangles adjacent to badTrias[iTia] with better aspect ratio after diag-swaping
6879 int bestCouple = -1;
6880 for ( int iSide = 0; iSide < 3; ++iSide )
6882 const SMDS_MeshNode* n1 = badTrias[iTia]->GetNode( iSide );
6883 const SMDS_MeshNode* n2 = badTrias[iTia]->GetNode(( iSide+1 ) % 3 );
6884 trias [iSide].first = badTrias[iTia];
6885 trias [iSide].second = SMESH_MeshAlgos::FindFaceInSet( n1, n2, emptySet, involvedFaces,
6887 if (( ! trias[iSide].second ) ||
6888 ( trias[iSide].second->NbCornerNodes() != 3 ) ||
6889 ( ! sm->Contains( trias[iSide].second )))
6892 // aspect ratio of an adjacent tria
6893 for ( int iP = 0; iP < 3; ++iP )
6894 points2(iP+1) = xyz( trias[iSide].second->GetNode(iP));
6895 double aspectInit = qualifier.GetValue( points2 );
6897 // arrange nodes as after diag-swaping
6898 if ( helper.WrapIndex( i1+1, 3 ) == i2 )
6899 i3 = helper.WrapIndex( i1-1, 3 );
6901 i3 = helper.WrapIndex( i1+1, 3 );
6903 points1( 1+ iSide ) = points2( 1+ i3 );
6904 points2( 1+ i2 ) = points1( 1+ ( iSide+2 ) % 3 );
6906 // aspect ratio after diag-swaping
6907 aspRatio[ iSide ] = qualifier.GetValue( points1 ) + qualifier.GetValue( points2 );
6908 if ( aspRatio[ iSide ] > aspectInit + badAspects[ iTia ] )
6911 // prevent inversion of a triangle
6912 gp_Vec norm1 = gp_Vec( points1(1), points1(3) ) ^ gp_Vec( points1(1), points1(2) );
6913 gp_Vec norm2 = gp_Vec( points2(1), points2(3) ) ^ gp_Vec( points2(1), points2(2) );
6914 if ( norm1 * norm2 < 0. && norm1.Angle( norm2 ) > 70./180.*M_PI )
6917 if ( bestCouple < 0 || aspRatio[ bestCouple ] > aspRatio[ iSide ] )
6921 if ( bestCouple >= 0 )
6923 triaCouples.push_back( trias[bestCouple] );
6924 involvedFaces.insert ( trias[bestCouple].second );
6928 involvedFaces.erase( badTrias[iTia] );
6931 if ( triaCouples.empty() )
6936 SMESH_MeshEditor editor( helper.GetMesh() );
6937 dumpFunction(SMESH_Comment("beforeSwapDiagonals_F")<<helper.GetSubShapeID()<<"_"<<step);
6938 for ( size_t i = 0; i < triaCouples.size(); ++i )
6940 dumpChangeNodes( triaCouples[i].first );
6941 dumpChangeNodes( triaCouples[i].second );
6942 editor.InverseDiag( triaCouples[i].first, triaCouples[i].second );
6945 if ( involvedNodes )
6946 for ( size_t i = 0; i < triaCouples.size(); ++i )
6948 involvedNodes->insert( triaCouples[i].first->begin_nodes(),
6949 triaCouples[i].first->end_nodes() );
6950 involvedNodes->insert( triaCouples[i].second->begin_nodes(),
6951 triaCouples[i].second->end_nodes() );
6954 // just for debug dump resulting triangles
6955 dumpFunction(SMESH_Comment("swapDiagonals_F")<<helper.GetSubShapeID()<<"_"<<step);
6956 for ( size_t i = 0; i < triaCouples.size(); ++i )
6958 dumpChangeNodes( triaCouples[i].first );
6959 dumpChangeNodes( triaCouples[i].second );
6963 //================================================================================
6965 * \brief Move target node to it's final position on the FACE during shrinking
6967 //================================================================================
6969 bool _LayerEdge::SetNewLength2d( Handle(Geom_Surface)& surface,
6970 const TopoDS_Face& F,
6971 SMESH_MesherHelper& helper )
6974 return false; // already at the target position
6976 SMDS_MeshNode* tgtNode = const_cast< SMDS_MeshNode*& >( _nodes.back() );
6978 if ( _sWOL.ShapeType() == TopAbs_FACE )
6980 gp_XY curUV = helper.GetNodeUV( F, tgtNode );
6981 gp_Pnt2d tgtUV( _pos[0].X(), _pos[0].Y() );
6982 gp_Vec2d uvDir( _normal.X(), _normal.Y() );
6983 const double uvLen = tgtUV.Distance( curUV );
6984 const double kSafe = Max( 0.5, 1. - 0.1 * _simplices.size() );
6986 // Select shrinking step such that not to make faces with wrong orientation.
6987 double stepSize = 1e100;
6988 for ( size_t i = 0; i < _simplices.size(); ++i )
6990 // find intersection of 2 lines: curUV-tgtUV and that connecting simplex nodes
6991 gp_XY uvN1 = helper.GetNodeUV( F, _simplices[i]._nPrev );
6992 gp_XY uvN2 = helper.GetNodeUV( F, _simplices[i]._nNext );
6993 gp_XY dirN = uvN2 - uvN1;
6994 double det = uvDir.Crossed( dirN );
6995 if ( Abs( det ) < std::numeric_limits<double>::min() ) continue;
6996 gp_XY dirN2Cur = curUV - uvN1;
6997 double step = dirN.Crossed( dirN2Cur ) / det;
6999 stepSize = Min( step, stepSize );
7002 if ( uvLen <= stepSize )
7007 else if ( stepSize > 0 )
7009 newUV = curUV + uvDir.XY() * stepSize * kSafe;
7015 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
7016 pos->SetUParameter( newUV.X() );
7017 pos->SetVParameter( newUV.Y() );
7020 gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
7021 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
7022 dumpMove( tgtNode );
7025 else // _sWOL is TopAbs_EDGE
7027 const TopoDS_Edge& E = TopoDS::Edge( _sWOL );
7028 const SMDS_MeshNode* n2 = _simplices[0]._nPrev;
7029 SMDS_EdgePosition* tgtPos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
7031 const double u2 = helper.GetNodeU( E, n2, tgtNode );
7032 const double uSrc = _pos[0].Coord( U_SRC );
7033 const double lenTgt = _pos[0].Coord( LEN_TGT );
7035 double newU = _pos[0].Coord( U_TGT );
7036 if ( lenTgt < 0.99 * fabs( uSrc-u2 )) // n2 got out of src-tgt range
7042 newU = 0.1 * tgtPos->GetUParameter() + 0.9 * u2;
7044 tgtPos->SetUParameter( newU );
7046 gp_XY newUV = helper.GetNodeUV( F, tgtNode, _nodes[0]);
7047 gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
7048 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
7049 dumpMove( tgtNode );
7055 //================================================================================
7057 * \brief Perform smooth on the FACE
7058 * \retval bool - true if the node has been moved
7060 //================================================================================
7062 bool _SmoothNode::Smooth(int& badNb,
7063 Handle(Geom_Surface)& surface,
7064 SMESH_MesherHelper& helper,
7065 const double refSign,
7069 const TopoDS_Face& face = TopoDS::Face( helper.GetSubShape() );
7071 // get uv of surrounding nodes
7072 vector<gp_XY> uv( _simplices.size() );
7073 for ( size_t i = 0; i < _simplices.size(); ++i )
7074 uv[i] = helper.GetNodeUV( face, _simplices[i]._nPrev, _node );
7076 // compute new UV for the node
7078 if ( how == TFI && _simplices.size() == 4 )
7081 for ( size_t i = 0; i < _simplices.size(); ++i )
7082 if ( _simplices[i]._nOpp )
7083 corners[i] = helper.GetNodeUV( face, _simplices[i]._nOpp, _node );
7085 throw SALOME_Exception(LOCALIZED("TFI smoothing: _Simplex::_nOpp not set!"));
7087 newPos = helper.calcTFI ( 0.5, 0.5,
7088 corners[0], corners[1], corners[2], corners[3],
7089 uv[1], uv[2], uv[3], uv[0] );
7091 else if ( how == ANGULAR )
7093 newPos = computeAngularPos( uv, helper.GetNodeUV( face, _node ), refSign );
7095 else if ( how == CENTROIDAL && _simplices.size() > 3 )
7097 // average centers of diagonals wieghted with their reciprocal lengths
7098 if ( _simplices.size() == 4 )
7100 double w1 = 1. / ( uv[2]-uv[0] ).SquareModulus();
7101 double w2 = 1. / ( uv[3]-uv[1] ).SquareModulus();
7102 newPos = ( w1 * ( uv[2]+uv[0] ) + w2 * ( uv[3]+uv[1] )) / ( w1+w2 ) / 2;
7106 double sumWeight = 0;
7107 int nb = _simplices.size() == 4 ? 2 : _simplices.size();
7108 for ( int i = 0; i < nb; ++i )
7111 int iTo = i + _simplices.size() - 1;
7112 for ( int j = iFrom; j < iTo; ++j )
7114 int i2 = SMESH_MesherHelper::WrapIndex( j, _simplices.size() );
7115 double w = 1. / ( uv[i]-uv[i2] ).SquareModulus();
7117 newPos += w * ( uv[i]+uv[i2] );
7120 newPos /= 2 * sumWeight; // 2 is to get a middle between uv's
7126 for ( size_t i = 0; i < _simplices.size(); ++i )
7128 newPos /= _simplices.size();
7131 // count quality metrics (orientation) of triangles around the node
7133 gp_XY tgtUV = helper.GetNodeUV( face, _node );
7134 for ( size_t i = 0; i < _simplices.size(); ++i )
7135 nbOkBefore += _simplices[i].IsForward( tgtUV, _node, face, helper, refSign );
7138 for ( size_t i = 0; i < _simplices.size(); ++i )
7139 nbOkAfter += _simplices[i].IsForward( newPos, _node, face, helper, refSign );
7141 if ( nbOkAfter < nbOkBefore )
7143 badNb += _simplices.size() - nbOkBefore;
7147 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( _node->GetPosition() );
7148 pos->SetUParameter( newPos.X() );
7149 pos->SetVParameter( newPos.Y() );
7156 gp_Pnt p = surface->Value( newPos.X(), newPos.Y() );
7157 const_cast< SMDS_MeshNode* >( _node )->setXYZ( p.X(), p.Y(), p.Z() );
7161 badNb += _simplices.size() - nbOkAfter;
7162 return ( (tgtUV-newPos).SquareModulus() > 1e-10 );
7165 //================================================================================
7167 * \brief Computes new UV using angle based smoothing technic
7169 //================================================================================
7171 gp_XY _SmoothNode::computeAngularPos(vector<gp_XY>& uv,
7172 const gp_XY& uvToFix,
7173 const double refSign)
7175 uv.push_back( uv.front() );
7177 vector< gp_XY > edgeDir ( uv.size() );
7178 vector< double > edgeSize( uv.size() );
7179 for ( size_t i = 1; i < edgeDir.size(); ++i )
7181 edgeDir [i-1] = uv[i] - uv[i-1];
7182 edgeSize[i-1] = edgeDir[i-1].Modulus();
7183 if ( edgeSize[i-1] < numeric_limits<double>::min() )
7184 edgeDir[i-1].SetX( 100 );
7186 edgeDir[i-1] /= edgeSize[i-1] * refSign;
7188 edgeDir.back() = edgeDir.front();
7189 edgeSize.back() = edgeSize.front();
7194 for ( size_t i = 1; i < edgeDir.size(); ++i )
7196 if ( edgeDir[i-1].X() > 1. ) continue;
7198 while ( edgeDir[i].X() > 1. && ++i < edgeDir.size() );
7199 if ( i == edgeDir.size() ) break;
7201 gp_XY norm1( -edgeDir[i1].Y(), edgeDir[i1].X() );
7202 gp_XY norm2( -edgeDir[i].Y(), edgeDir[i].X() );
7203 gp_XY bisec = norm1 + norm2;
7204 double bisecSize = bisec.Modulus();
7205 if ( bisecSize < numeric_limits<double>::min() )
7207 bisec = -edgeDir[i1] + edgeDir[i];
7208 bisecSize = bisec.Modulus();
7212 gp_XY dirToN = uvToFix - p;
7213 double distToN = dirToN.Modulus();
7214 if ( bisec * dirToN < 0 )
7217 newPos += ( p + bisec * distToN ) * ( edgeSize[i1] + edgeSize[i] );
7219 sumSize += edgeSize[i1] + edgeSize[i];
7221 newPos /= /*nbEdges * */sumSize;
7225 //================================================================================
7227 * \brief Delete _SolidData
7229 //================================================================================
7231 _SolidData::~_SolidData()
7233 for ( size_t i = 0; i < _edges.size(); ++i )
7235 if ( _edges[i] && _edges[i]->_2neibors )
7236 delete _edges[i]->_2neibors;
7241 //================================================================================
7243 * \brief Add a _LayerEdge inflated along the EDGE
7245 //================================================================================
7247 void _Shrinker1D::AddEdge( const _LayerEdge* e, SMESH_MesherHelper& helper )
7250 if ( _nodes.empty() )
7252 _edges[0] = _edges[1] = 0;
7256 if ( e == _edges[0] || e == _edges[1] )
7258 if ( e->_sWOL.IsNull() || e->_sWOL.ShapeType() != TopAbs_EDGE )
7259 throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
7260 if ( _edges[0] && _edges[0]->_sWOL != e->_sWOL )
7261 throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
7264 const TopoDS_Edge& E = TopoDS::Edge( e->_sWOL );
7266 BRep_Tool::Range( E, f,l );
7267 double u = helper.GetNodeU( E, e->_nodes[0], e->_nodes.back());
7268 _edges[ u < 0.5*(f+l) ? 0 : 1 ] = e;
7272 const SMDS_MeshNode* tgtNode0 = _edges[0] ? _edges[0]->_nodes.back() : 0;
7273 const SMDS_MeshNode* tgtNode1 = _edges[1] ? _edges[1]->_nodes.back() : 0;
7275 if ( _nodes.empty() )
7277 SMESHDS_SubMesh * eSubMesh = helper.GetMeshDS()->MeshElements( E );
7278 if ( !eSubMesh || eSubMesh->NbNodes() < 1 )
7280 TopLoc_Location loc;
7281 Handle(Geom_Curve) C = BRep_Tool::Curve(E, loc, f,l);
7282 GeomAdaptor_Curve aCurve(C, f,l);
7283 const double totLen = GCPnts_AbscissaPoint::Length(aCurve, f, l);
7285 int nbExpectNodes = eSubMesh->NbNodes();
7286 _initU .reserve( nbExpectNodes );
7287 _normPar.reserve( nbExpectNodes );
7288 _nodes .reserve( nbExpectNodes );
7289 SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
7290 while ( nIt->more() )
7292 const SMDS_MeshNode* node = nIt->next();
7293 if ( node->NbInverseElements(SMDSAbs_Edge) == 0 ||
7294 node == tgtNode0 || node == tgtNode1 )
7295 continue; // refinement nodes
7296 _nodes.push_back( node );
7297 _initU.push_back( helper.GetNodeU( E, node ));
7298 double len = GCPnts_AbscissaPoint::Length(aCurve, f, _initU.back());
7299 _normPar.push_back( len / totLen );
7304 // remove target node of the _LayerEdge from _nodes
7306 for ( size_t i = 0; i < _nodes.size(); ++i )
7307 if ( !_nodes[i] || _nodes[i] == tgtNode0 || _nodes[i] == tgtNode1 )
7308 _nodes[i] = 0, nbFound++;
7309 if ( nbFound == _nodes.size() )
7314 //================================================================================
7316 * \brief Move nodes on EDGE from ends where _LayerEdge's are inflated
7318 //================================================================================
7320 void _Shrinker1D::Compute(bool set3D, SMESH_MesherHelper& helper)
7322 if ( _done || _nodes.empty())
7324 const _LayerEdge* e = _edges[0];
7325 if ( !e ) e = _edges[1];
7328 _done = (( !_edges[0] || _edges[0]->_pos.empty() ) &&
7329 ( !_edges[1] || _edges[1]->_pos.empty() ));
7331 const TopoDS_Edge& E = TopoDS::Edge( e->_sWOL );
7333 if ( set3D || _done )
7335 Handle(Geom_Curve) C = BRep_Tool::Curve(E, f,l);
7336 GeomAdaptor_Curve aCurve(C, f,l);
7339 f = helper.GetNodeU( E, _edges[0]->_nodes.back(), _nodes[0] );
7341 l = helper.GetNodeU( E, _edges[1]->_nodes.back(), _nodes.back() );
7342 double totLen = GCPnts_AbscissaPoint::Length( aCurve, f, l );
7344 for ( size_t i = 0; i < _nodes.size(); ++i )
7346 if ( !_nodes[i] ) continue;
7347 double len = totLen * _normPar[i];
7348 GCPnts_AbscissaPoint discret( aCurve, len, f );
7349 if ( !discret.IsDone() )
7350 return throw SALOME_Exception(LOCALIZED("GCPnts_AbscissaPoint failed"));
7351 double u = discret.Parameter();
7352 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
7353 pos->SetUParameter( u );
7354 gp_Pnt p = C->Value( u );
7355 const_cast< SMDS_MeshNode*>( _nodes[i] )->setXYZ( p.X(), p.Y(), p.Z() );
7360 BRep_Tool::Range( E, f,l );
7362 f = helper.GetNodeU( E, _edges[0]->_nodes.back(), _nodes[0] );
7364 l = helper.GetNodeU( E, _edges[1]->_nodes.back(), _nodes.back() );
7366 for ( size_t i = 0; i < _nodes.size(); ++i )
7368 if ( !_nodes[i] ) continue;
7369 double u = f * ( 1-_normPar[i] ) + l * _normPar[i];
7370 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
7371 pos->SetUParameter( u );
7376 //================================================================================
7378 * \brief Restore initial parameters of nodes on EDGE
7380 //================================================================================
7382 void _Shrinker1D::RestoreParams()
7385 for ( size_t i = 0; i < _nodes.size(); ++i )
7387 if ( !_nodes[i] ) continue;
7388 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
7389 pos->SetUParameter( _initU[i] );
7394 //================================================================================
7396 * \brief Replace source nodes by target nodes in shrinked mesh edges
7398 //================================================================================
7400 void _Shrinker1D::SwapSrcTgtNodes( SMESHDS_Mesh* mesh )
7402 const SMDS_MeshNode* nodes[3];
7403 for ( int i = 0; i < 2; ++i )
7405 if ( !_edges[i] ) continue;
7407 SMESHDS_SubMesh * eSubMesh = mesh->MeshElements( _edges[i]->_sWOL );
7408 if ( !eSubMesh ) return;
7409 const SMDS_MeshNode* srcNode = _edges[i]->_nodes[0];
7410 const SMDS_MeshNode* tgtNode = _edges[i]->_nodes.back();
7411 SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
7412 while ( eIt->more() )
7414 const SMDS_MeshElement* e = eIt->next();
7415 if ( !eSubMesh->Contains( e ))
7417 SMDS_ElemIteratorPtr nIt = e->nodesIterator();
7418 for ( int iN = 0; iN < e->NbNodes(); ++iN )
7420 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
7421 nodes[iN] = ( n == srcNode ? tgtNode : n );
7423 mesh->ChangeElementNodes( e, nodes, e->NbNodes() );
7428 //================================================================================
7430 * \brief Creates 2D and 1D elements on boundaries of new prisms
7432 //================================================================================
7434 bool _ViscousBuilder::addBoundaryElements()
7436 SMESH_MesherHelper helper( *_mesh );
7438 vector< const SMDS_MeshNode* > faceNodes;
7440 for ( size_t i = 0; i < _sdVec.size(); ++i )
7442 _SolidData& data = _sdVec[i];
7443 TopTools_IndexedMapOfShape geomEdges;
7444 TopExp::MapShapes( data._solid, TopAbs_EDGE, geomEdges );
7445 for ( int iE = 1; iE <= geomEdges.Extent(); ++iE )
7447 const TopoDS_Edge& E = TopoDS::Edge( geomEdges(iE));
7448 if ( data._noShrinkShapes.count( getMeshDS()->ShapeToIndex( E )))
7451 // Get _LayerEdge's based on E
7453 map< double, const SMDS_MeshNode* > u2nodes;
7454 if ( !SMESH_Algo::GetSortedNodesOnEdge( getMeshDS(), E, /*ignoreMedium=*/false, u2nodes))
7457 vector< _LayerEdge* > ledges; ledges.reserve( u2nodes.size() );
7458 TNode2Edge & n2eMap = data._n2eMap;
7459 map< double, const SMDS_MeshNode* >::iterator u2n = u2nodes.begin();
7461 //check if 2D elements are needed on E
7462 TNode2Edge::iterator n2e = n2eMap.find( u2n->second );
7463 if ( n2e == n2eMap.end() ) continue; // no layers on vertex
7464 ledges.push_back( n2e->second );
7466 if (( n2e = n2eMap.find( u2n->second )) == n2eMap.end() )
7467 continue; // no layers on E
7468 ledges.push_back( n2eMap[ u2n->second ]);
7470 const SMDS_MeshNode* tgtN0 = ledges[0]->_nodes.back();
7471 const SMDS_MeshNode* tgtN1 = ledges[1]->_nodes.back();
7472 int nbSharedPyram = 0;
7473 SMDS_ElemIteratorPtr vIt = tgtN0->GetInverseElementIterator(SMDSAbs_Volume);
7474 while ( vIt->more() )
7476 const SMDS_MeshElement* v = vIt->next();
7477 nbSharedPyram += int( v->GetNodeIndex( tgtN1 ) >= 0 );
7479 if ( nbSharedPyram > 1 )
7480 continue; // not free border of the pyramid
7483 faceNodes.push_back( ledges[0]->_nodes[0] );
7484 faceNodes.push_back( ledges[1]->_nodes[0] );
7485 if ( ledges[0]->_nodes.size() > 1 ) faceNodes.push_back( ledges[0]->_nodes[1] );
7486 if ( ledges[1]->_nodes.size() > 1 ) faceNodes.push_back( ledges[1]->_nodes[1] );
7488 if ( getMeshDS()->FindElement( faceNodes, SMDSAbs_Face, /*noMedium=*/true))
7489 continue; // faces already created
7491 for ( ++u2n; u2n != u2nodes.end(); ++u2n )
7492 ledges.push_back( n2eMap[ u2n->second ]);
7494 // Find out orientation and type of face to create
7496 bool reverse = false, isOnFace;
7498 map< TGeomID, TopoDS_Shape >::iterator e2f =
7499 data._shrinkShape2Shape.find( getMeshDS()->ShapeToIndex( E ));
7501 if (( isOnFace = ( e2f != data._shrinkShape2Shape.end() )))
7503 F = e2f->second.Oriented( TopAbs_FORWARD );
7504 reverse = ( helper.GetSubShapeOri( F, E ) == TopAbs_REVERSED );
7505 if ( helper.GetSubShapeOri( data._solid, F ) == TopAbs_REVERSED )
7506 reverse = !reverse, F.Reverse();
7507 if ( helper.IsReversedSubMesh( TopoDS::Face(F) ))
7512 // find FACE with layers sharing E
7513 PShapeIteratorPtr fIt = helper.GetAncestors( E, *_mesh, TopAbs_FACE );
7514 while ( fIt->more() && F.IsNull() )
7516 const TopoDS_Shape* pF = fIt->next();
7517 if ( helper.IsSubShape( *pF, data._solid) &&
7518 !data._ignoreFaceIds.count( e2f->first ))
7522 // Find the sub-mesh to add new faces
7523 SMESHDS_SubMesh* sm = 0;
7525 sm = getMeshDS()->MeshElements( F );
7527 sm = data._proxyMesh->getFaceSubM( TopoDS::Face(F), /*create=*/true );
7529 return error("error in addBoundaryElements()", data._index);
7532 const int dj1 = reverse ? 0 : 1;
7533 const int dj2 = reverse ? 1 : 0;
7534 for ( size_t j = 1; j < ledges.size(); ++j )
7536 vector< const SMDS_MeshNode*>& nn1 = ledges[j-dj1]->_nodes;
7537 vector< const SMDS_MeshNode*>& nn2 = ledges[j-dj2]->_nodes;
7538 if ( nn1.size() == nn2.size() )
7541 for ( size_t z = 1; z < nn1.size(); ++z )
7542 sm->AddElement( getMeshDS()->AddFace( nn1[z-1], nn2[z-1], nn2[z], nn1[z] ));
7544 for ( size_t z = 1; z < nn1.size(); ++z )
7545 sm->AddElement( new SMDS_FaceOfNodes( nn1[z-1], nn2[z-1], nn2[z], nn1[z] ));
7547 else if ( nn1.size() == 1 )
7550 for ( size_t z = 1; z < nn2.size(); ++z )
7551 sm->AddElement( getMeshDS()->AddFace( nn1[0], nn2[z-1], nn2[z] ));
7553 for ( size_t z = 1; z < nn2.size(); ++z )
7554 sm->AddElement( new SMDS_FaceOfNodes( nn1[0], nn2[z-1], nn2[z] ));
7559 for ( size_t z = 1; z < nn1.size(); ++z )
7560 sm->AddElement( getMeshDS()->AddFace( nn1[z-1], nn2[0], nn1[z] ));
7562 for ( size_t z = 1; z < nn1.size(); ++z )
7563 sm->AddElement( new SMDS_FaceOfNodes( nn1[z-1], nn2[0], nn2[z] ));
7568 for ( int isFirst = 0; isFirst < 2; ++isFirst )
7570 _LayerEdge* edge = isFirst ? ledges.front() : ledges.back();
7571 if ( !edge->_sWOL.IsNull() && edge->_sWOL.ShapeType() == TopAbs_EDGE )
7573 vector< const SMDS_MeshNode*>& nn = edge->_nodes;
7574 if ( nn.size() < 2 || nn[1]->GetInverseElementIterator( SMDSAbs_Edge )->more() )
7576 helper.SetSubShape( edge->_sWOL );
7577 helper.SetElementsOnShape( true );
7578 for ( size_t z = 1; z < nn.size(); ++z )
7579 helper.AddEdge( nn[z-1], nn[z] );