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 <BRepAdaptor_Curve2d.hxx>
48 #include <BRepAdaptor_Surface.hxx>
49 #include <BRepLProp_SLProps.hxx>
50 #include <BRep_Tool.hxx>
51 #include <Bnd_B2d.hxx>
52 #include <Bnd_B3d.hxx>
54 #include <GCPnts_AbscissaPoint.hxx>
55 #include <Geom2d_Circle.hxx>
56 #include <Geom2d_Line.hxx>
57 #include <Geom2d_TrimmedCurve.hxx>
58 #include <GeomAdaptor_Curve.hxx>
59 #include <GeomLib.hxx>
60 #include <Geom_Circle.hxx>
61 #include <Geom_Curve.hxx>
62 #include <Geom_Line.hxx>
63 #include <Geom_TrimmedCurve.hxx>
64 #include <Precision.hxx>
65 #include <Standard_ErrorHandler.hxx>
66 #include <Standard_Failure.hxx>
67 #include <TColStd_Array1OfReal.hxx>
69 #include <TopExp_Explorer.hxx>
70 #include <TopTools_IndexedMapOfShape.hxx>
71 #include <TopTools_ListOfShape.hxx>
72 #include <TopTools_MapOfShape.hxx>
74 #include <TopoDS_Edge.hxx>
75 #include <TopoDS_Face.hxx>
76 #include <TopoDS_Vertex.hxx>
90 //================================================================================
95 enum UIndex { U_TGT = 1, U_SRC, LEN_TGT };
97 const double theMinSmoothCosin = 0.1;
98 const double theSmoothThickToElemSizeRatio = 0.3;
100 bool needSmoothing( double cosin, double tgtThick, double elemSize )
102 return cosin * tgtThick > theSmoothThickToElemSizeRatio * elemSize;
106 * \brief SMESH_ProxyMesh computed by _ViscousBuilder for a SOLID.
107 * It is stored in a SMESH_subMesh of the SOLID as SMESH_subMeshEventListenerData
109 struct _MeshOfSolid : public SMESH_ProxyMesh,
110 public SMESH_subMeshEventListenerData
112 bool _n2nMapComputed;
114 _MeshOfSolid( SMESH_Mesh* mesh)
115 :SMESH_subMeshEventListenerData( /*isDeletable=*/true),_n2nMapComputed(false)
117 SMESH_ProxyMesh::setMesh( *mesh );
120 // returns submesh for a geom face
121 SMESH_ProxyMesh::SubMesh* getFaceSubM(const TopoDS_Face& F, bool create=false)
123 TGeomID i = SMESH_ProxyMesh::shapeIndex(F);
124 return create ? SMESH_ProxyMesh::getProxySubMesh(i) : findProxySubMesh(i);
126 void setNode2Node(const SMDS_MeshNode* srcNode,
127 const SMDS_MeshNode* proxyNode,
128 const SMESH_ProxyMesh::SubMesh* subMesh)
130 SMESH_ProxyMesh::setNode2Node( srcNode,proxyNode,subMesh);
133 //--------------------------------------------------------------------------------
135 * \brief Listener of events of 3D sub-meshes computed with viscous layers.
136 * It is used to clear an inferior dim sub-meshes modified by viscous layers
138 class _ShrinkShapeListener : SMESH_subMeshEventListener
140 _ShrinkShapeListener()
141 : SMESH_subMeshEventListener(/*isDeletable=*/false,
142 "StdMeshers_ViscousLayers::_ShrinkShapeListener") {}
144 static SMESH_subMeshEventListener* Get() { static _ShrinkShapeListener l; return &l; }
145 virtual void ProcessEvent(const int event,
147 SMESH_subMesh* solidSM,
148 SMESH_subMeshEventListenerData* data,
149 const SMESH_Hypothesis* hyp)
151 if ( SMESH_subMesh::COMPUTE_EVENT == eventType && solidSM->IsEmpty() && data )
153 SMESH_subMeshEventListener::ProcessEvent(event,eventType,solidSM,data,hyp);
157 //--------------------------------------------------------------------------------
159 * \brief Listener of events of 3D sub-meshes computed with viscous layers.
160 * It is used to store data computed by _ViscousBuilder for a sub-mesh and to
161 * delete the data as soon as it has been used
163 class _ViscousListener : SMESH_subMeshEventListener
166 SMESH_subMeshEventListener(/*isDeletable=*/false,
167 "StdMeshers_ViscousLayers::_ViscousListener") {}
168 static SMESH_subMeshEventListener* Get() { static _ViscousListener l; return &l; }
170 virtual void ProcessEvent(const int event,
172 SMESH_subMesh* subMesh,
173 SMESH_subMeshEventListenerData* data,
174 const SMESH_Hypothesis* hyp)
176 if ( SMESH_subMesh::COMPUTE_EVENT == eventType )
178 // delete SMESH_ProxyMesh containing temporary faces
179 subMesh->DeleteEventListener( this );
182 // Finds or creates proxy mesh of the solid
183 static _MeshOfSolid* GetSolidMesh(SMESH_Mesh* mesh,
184 const TopoDS_Shape& solid,
187 if ( !mesh ) return 0;
188 SMESH_subMesh* sm = mesh->GetSubMesh(solid);
189 _MeshOfSolid* data = (_MeshOfSolid*) sm->GetEventListenerData( Get() );
190 if ( !data && toCreate )
192 data = new _MeshOfSolid(mesh);
193 data->mySubMeshes.push_back( sm ); // to find SOLID by _MeshOfSolid
194 sm->SetEventListener( Get(), data, sm );
198 // Removes proxy mesh of the solid
199 static void RemoveSolidMesh(SMESH_Mesh* mesh, const TopoDS_Shape& solid)
201 mesh->GetSubMesh(solid)->DeleteEventListener( _ViscousListener::Get() );
205 //================================================================================
207 * \brief sets a sub-mesh event listener to clear sub-meshes of sub-shapes of
208 * the main shape when sub-mesh of the main shape is cleared,
209 * for example to clear sub-meshes of FACEs when sub-mesh of a SOLID
212 //================================================================================
214 void ToClearSubWithMain( SMESH_subMesh* sub, const TopoDS_Shape& main)
216 SMESH_subMesh* mainSM = sub->GetFather()->GetSubMesh( main );
217 SMESH_subMeshEventListenerData* data =
218 mainSM->GetEventListenerData( _ShrinkShapeListener::Get());
221 if ( find( data->mySubMeshes.begin(), data->mySubMeshes.end(), sub ) ==
222 data->mySubMeshes.end())
223 data->mySubMeshes.push_back( sub );
227 data = SMESH_subMeshEventListenerData::MakeData( /*dependent=*/sub );
228 sub->SetEventListener( _ShrinkShapeListener::Get(), data, /*whereToListenTo=*/mainSM );
231 //--------------------------------------------------------------------------------
233 * \brief Simplex (triangle or tetrahedron) based on 1 (tria) or 2 (tet) nodes of
234 * _LayerEdge and 2 nodes of the mesh surface beening smoothed.
235 * The class is used to check validity of face or volumes around a smoothed node;
236 * it stores only 2 nodes as the other nodes are stored by _LayerEdge.
240 const SMDS_MeshNode *_nPrev, *_nNext; // nodes on a smoothed mesh surface
241 const SMDS_MeshNode *_nOpp; // in 2D case, a node opposite to a smoothed node in QUAD
242 _Simplex(const SMDS_MeshNode* nPrev=0,
243 const SMDS_MeshNode* nNext=0,
244 const SMDS_MeshNode* nOpp=0)
245 : _nPrev(nPrev), _nNext(nNext), _nOpp(nOpp) {}
246 bool IsForward(const SMDS_MeshNode* nSrc, const gp_XYZ* pntTgt) const
248 const double M[3][3] =
249 {{ _nNext->X() - nSrc->X(), _nNext->Y() - nSrc->Y(), _nNext->Z() - nSrc->Z() },
250 { pntTgt->X() - nSrc->X(), pntTgt->Y() - nSrc->Y(), pntTgt->Z() - nSrc->Z() },
251 { _nPrev->X() - nSrc->X(), _nPrev->Y() - nSrc->Y(), _nPrev->Z() - nSrc->Z() }};
252 double determinant = ( + M[0][0]*M[1][1]*M[2][2]
253 + M[0][1]*M[1][2]*M[2][0]
254 + M[0][2]*M[1][0]*M[2][1]
255 - M[0][0]*M[1][2]*M[2][1]
256 - M[0][1]*M[1][0]*M[2][2]
257 - M[0][2]*M[1][1]*M[2][0]);
258 return determinant > 1e-100;
260 bool IsForward(const gp_XY& tgtUV,
261 const SMDS_MeshNode* smoothedNode,
262 const TopoDS_Face& face,
263 SMESH_MesherHelper& helper,
264 const double refSign) const
266 gp_XY prevUV = helper.GetNodeUV( face, _nPrev, smoothedNode );
267 gp_XY nextUV = helper.GetNodeUV( face, _nNext, smoothedNode );
268 gp_Vec2d v1( tgtUV, prevUV ), v2( tgtUV, nextUV );
270 return d*refSign > 1e-100;
272 bool IsNeighbour(const _Simplex& other) const
274 return _nPrev == other._nNext || _nNext == other._nPrev;
277 //--------------------------------------------------------------------------------
279 * Structure used to take into account surface curvature while smoothing
284 double _k; // factor to correct node smoothed position
285 double _h2lenRatio; // avgNormProj / (2*avgDist)
287 static _Curvature* New( double avgNormProj, double avgDist )
290 if ( fabs( avgNormProj / avgDist ) > 1./200 )
293 c->_r = avgDist * avgDist / avgNormProj;
294 c->_k = avgDist * avgDist / c->_r / c->_r;
295 //c->_k = avgNormProj / c->_r;
296 c->_k *= ( c->_r < 0 ? 1/1.1 : 1.1 ); // not to be too restrictive
297 c->_h2lenRatio = avgNormProj / ( avgDist + avgDist );
301 double lenDelta(double len) const { return _k * ( _r + len ); }
302 double lenDeltaByDist(double dist) const { return dist * _h2lenRatio; }
305 //--------------------------------------------------------------------------------
307 * \brief Edge normal to surface, connecting a node on solid surface (_nodes[0])
308 * and a node of the most internal layer (_nodes.back())
312 vector< const SMDS_MeshNode*> _nodes;
314 gp_XYZ _normal; // to solid surface
315 vector<gp_XYZ> _pos; // points computed during inflation
316 double _len; // length achived with the last inflation step
317 double _cosin; // of angle (_normal ^ surface)
318 double _lenFactor; // to compute _len taking _cosin into account
320 // face or edge w/o layer along or near which _LayerEdge is inflated
322 // simplices connected to the source node (_nodes[0]);
323 // used for smoothing and quality check of _LayerEdge's based on the FACE
324 vector<_Simplex> _simplices;
325 // data for smoothing of _LayerEdge's based on the EDGE
326 _2NearEdges* _2neibors;
328 _Curvature* _curvature;
329 // TODO:: detele _Curvature, _plnNorm
331 void SetNewLength( double len, SMESH_MesherHelper& helper );
332 bool SetNewLength2d( Handle(Geom_Surface)& surface,
333 const TopoDS_Face& F,
334 SMESH_MesherHelper& helper );
335 void SetDataByNeighbors( const SMDS_MeshNode* n1,
336 const SMDS_MeshNode* n2,
337 SMESH_MesherHelper& helper);
338 void InvalidateStep( int curStep, bool restoreLength=false );
339 bool Smooth(int& badNb);
340 bool SmoothOnEdge(Handle(Geom_Surface)& surface,
341 const TopoDS_Face& F,
342 SMESH_MesherHelper& helper);
343 bool FindIntersection( SMESH_ElementSearcher& searcher,
345 const double& epsilon,
346 const SMDS_MeshElement** face = 0);
347 bool SegTriaInter( const gp_Ax1& lastSegment,
348 const SMDS_MeshNode* n0,
349 const SMDS_MeshNode* n1,
350 const SMDS_MeshNode* n2,
352 const double& epsilon) const;
353 gp_Ax1 LastSegment(double& segLen) const;
354 gp_XY LastUV( const TopoDS_Face& F ) const;
355 bool IsOnEdge() const { return _2neibors; }
356 gp_XYZ Copy( _LayerEdge& other, SMESH_MesherHelper& helper );
357 void SetCosin( double cosin );
361 bool operator () (const _LayerEdge* e1, const _LayerEdge* e2) const
363 const bool cmpNodes = ( e1 && e2 && e1->_nodes.size() && e2->_nodes.size() );
364 return cmpNodes ? ( e1->_nodes[0]->GetID() < e2->_nodes[0]->GetID()) : ( e1 < e2 );
368 //--------------------------------------------------------------------------------
370 * Structure used to smooth a _LayerEdge based on an EDGE.
374 double _wgt [2]; // weights of _nodes
375 _LayerEdge* _edges[2];
377 // normal to plane passing through _LayerEdge._normal and tangent of EDGE
380 _2NearEdges() { _edges[0]=_edges[1]=0; _plnNorm = 0; }
381 const SMDS_MeshNode* tgtNode(bool is2nd) {
382 return _edges[is2nd] ? _edges[is2nd]->_nodes.back() : 0;
384 const SMDS_MeshNode* srcNode(bool is2nd) {
385 return _edges[is2nd] ? _edges[is2nd]->_nodes[0] : 0;
388 std::swap( _wgt [0], _wgt [1] );
389 std::swap( _edges[0], _edges[1] );
392 //--------------------------------------------------------------------------------
394 * \brief Convex FACE whose radius of curvature is less than the thickness of
395 * layers. It is used to detect distortion of prisms based on a convex
396 * FACE and to update normals to enable further increasing the thickness
402 // edges whose _simplices are used to detect prism destorsion
403 vector< _LayerEdge* > _simplexTestEdges;
405 // map a sub-shape to it's index in _SolidData::_endEdgeOnShape vector
406 map< TGeomID, int > _subIdToEdgeEnd;
410 bool GetCenterOfCurvature( _LayerEdge* ledge,
411 BRepLProp_SLProps& surfProp,
412 SMESH_MesherHelper& helper,
413 gp_Pnt & center ) const;
414 bool CheckPrisms() const;
417 //--------------------------------------------------------------------------------
419 typedef map< const SMDS_MeshNode*, _LayerEdge*, TIDCompare > TNode2Edge;
421 //--------------------------------------------------------------------------------
423 * \brief Data of a SOLID
428 const StdMeshers_ViscousLayers* _hyp;
429 TopoDS_Shape _hypShape;
430 _MeshOfSolid* _proxyMesh;
431 set<TGeomID> _reversedFaceIds;
432 set<TGeomID> _ignoreFaceIds; // WOL FACEs and FACEs of other SOLIDS
434 double _stepSize, _stepSizeCoeff, _geomSize;
435 const SMDS_MeshNode* _stepSizeNodes[2];
437 TNode2Edge _n2eMap; // nodes and _LayerEdge's based on them
439 // map to find _n2eMap of another _SolidData by a shrink shape shared by two _SolidData's
440 map< TGeomID, TNode2Edge* > _s2neMap;
441 // edges of _n2eMap. We keep same data in two containers because
442 // iteration over the map is 5 time longer than over the vector
443 vector< _LayerEdge* > _edges;
445 // key: an id of shape (EDGE or VERTEX) shared by a FACE with
446 // layers and a FACE w/o layers
447 // value: the shape (FACE or EDGE) to shrink mesh on.
448 // _LayerEdge's basing on nodes on key shape are inflated along the value shape
449 map< TGeomID, TopoDS_Shape > _shrinkShape2Shape;
451 // Convex FACEs whose radius of curvature is less than the thickness of layers
452 map< TGeomID, _ConvexFace > _convexFaces;
454 // shapes (EDGEs and VERTEXes) srink from which is forbiden due to collisions with
455 // the adjacent SOLID
456 set< TGeomID > _noShrinkShapes;
458 // <EDGE to smooth on> to <it's curve> -- for analytic smooth
459 map< TGeomID,Handle(Geom_Curve)> _edge2curve;
461 // end indices in _edges of _LayerEdge on each shape, first go shapes to smooth
462 vector< int > _endEdgeOnShape;
463 int _nbShapesToSmooth;
465 double _epsilon; // precision for SegTriaInter()
467 TGeomID _index; // SOLID id, for debug
469 _SolidData(const TopoDS_Shape& s=TopoDS_Shape(),
470 const StdMeshers_ViscousLayers* h=0,
471 const TopoDS_Shape& hs=TopoDS_Shape(),
473 :_solid(s), _hyp(h), _hypShape(hs), _proxyMesh(m) {}
476 Handle(Geom_Curve) CurveForSmooth( const TopoDS_Edge& E,
479 Handle(Geom_Surface)& surface,
480 const TopoDS_Face& F,
481 SMESH_MesherHelper& helper);
483 void SortOnEdge( const TopoDS_Edge& E,
486 SMESH_MesherHelper& helper);
488 _ConvexFace* GetConvexFace( const TGeomID faceID )
490 map< TGeomID, _ConvexFace >::iterator id2face = _convexFaces.find( faceID );
491 return id2face == _convexFaces.end() ? 0 : & id2face->second;
493 void GetEdgesOnShape( size_t end, int & iBeg, int & iEnd )
495 iBeg = end > 0 ? _endEdgeOnShape[ end-1 ] : 0;
496 iEnd = _endEdgeOnShape[ end ];
499 bool GetShapeEdges(const TGeomID shapeID, size_t& edgeEnd, int* iBeg=0, int* iEnd=0 ) const;
501 void AddShapesToSmooth( const set< TGeomID >& shapeIDs );
503 //--------------------------------------------------------------------------------
505 * \brief Container of centers of curvature at nodes on an EDGE bounding _ConvexFace
507 struct _CentralCurveOnEdge
510 vector< gp_Pnt > _curvaCenters;
511 vector< _LayerEdge* > _ledges;
512 vector< gp_XYZ > _normals; // new normal for each of _ledges
513 vector< double > _segLength2;
516 TopoDS_Face _adjFace;
517 bool _adjFaceToSmooth;
519 void Append( const gp_Pnt& center, _LayerEdge* ledge )
521 if ( _curvaCenters.size() > 0 )
522 _segLength2.push_back( center.SquareDistance( _curvaCenters.back() ));
523 _curvaCenters.push_back( center );
524 _ledges.push_back( ledge );
525 _normals.push_back( ledge->_normal );
527 bool FindNewNormal( const gp_Pnt& center, gp_XYZ& newNormal );
528 void SetShapes( const TopoDS_Edge& edge,
529 const _ConvexFace& convFace,
530 const _SolidData& data,
531 SMESH_MesherHelper& helper);
533 //--------------------------------------------------------------------------------
535 * \brief Data of node on a shrinked FACE
539 const SMDS_MeshNode* _node;
540 vector<_Simplex> _simplices; // for quality check
542 enum SmoothType { LAPLACIAN, CENTROIDAL, ANGULAR, TFI };
544 bool Smooth(int& badNb,
545 Handle(Geom_Surface)& surface,
546 SMESH_MesherHelper& helper,
547 const double refSign,
551 gp_XY computeAngularPos(vector<gp_XY>& uv,
552 const gp_XY& uvToFix,
553 const double refSign );
555 //--------------------------------------------------------------------------------
557 * \brief Builder of viscous layers
559 class _ViscousBuilder
564 SMESH_ComputeErrorPtr Compute(SMESH_Mesh& mesh,
565 const TopoDS_Shape& shape);
567 // restore event listeners used to clear an inferior dim sub-mesh modified by viscous layers
568 void RestoreListeners();
570 // computes SMESH_ProxyMesh::SubMesh::_n2n;
571 bool MakeN2NMap( _MeshOfSolid* pm );
575 bool findSolidsWithLayers();
576 bool findFacesWithLayers();
577 bool makeLayer(_SolidData& data);
578 bool setEdgeData(_LayerEdge& edge, const set<TGeomID>& subIds,
579 SMESH_MesherHelper& helper, _SolidData& data);
580 gp_XYZ getFaceNormal(const SMDS_MeshNode* n,
581 const TopoDS_Face& face,
582 SMESH_MesherHelper& helper,
584 bool shiftInside=false);
585 gp_XYZ getWeigthedNormal( const SMDS_MeshNode* n,
586 std::pair< TGeomID, gp_XYZ > fId2Normal[],
588 bool findNeiborsOnEdge(const _LayerEdge* edge,
589 const SMDS_MeshNode*& n1,
590 const SMDS_MeshNode*& n2,
592 void getSimplices( const SMDS_MeshNode* node, vector<_Simplex>& simplices,
593 const set<TGeomID>& ingnoreShapes,
594 const _SolidData* dataToCheckOri = 0,
595 const bool toSort = false);
596 void findSimplexTestEdges( _SolidData& data,
597 vector< vector<_LayerEdge*> >& edgesByGeom);
598 void computeGeomSize( _SolidData& data );
599 bool sortEdges( _SolidData& data,
600 vector< vector<_LayerEdge*> >& edgesByGeom);
601 void limitStepSizeByCurvature( _SolidData& data );
602 void limitStepSize( _SolidData& data,
603 const SMDS_MeshElement* face,
604 const _LayerEdge* maxCosinEdge );
605 void limitStepSize( _SolidData& data, const double minSize);
606 bool inflate(_SolidData& data);
607 bool smoothAndCheck(_SolidData& data, const int nbSteps, double & distToIntersection);
608 bool smoothAnalyticEdge( _SolidData& data,
611 Handle(Geom_Surface)& surface,
612 const TopoDS_Face& F,
613 SMESH_MesherHelper& helper);
614 bool updateNormals( _SolidData& data, SMESH_MesherHelper& helper, int stepNb );
615 bool updateNormalsOfConvexFaces( _SolidData& data,
616 SMESH_MesherHelper& helper,
618 bool refine(_SolidData& data);
620 bool prepareEdgeToShrink( _LayerEdge& edge, const TopoDS_Face& F,
621 SMESH_MesherHelper& helper,
622 const SMESHDS_SubMesh* faceSubMesh );
623 void restoreNoShrink( _LayerEdge& edge ) const;
624 void fixBadFaces(const TopoDS_Face& F,
625 SMESH_MesherHelper& helper,
628 set<const SMDS_MeshNode*> * involvedNodes=NULL);
629 bool addBoundaryElements();
631 bool error( const string& text, int solidID=-1 );
632 SMESHDS_Mesh* getMeshDS() const { return _mesh->GetMeshDS(); }
635 void makeGroupOfLE();
638 SMESH_ComputeErrorPtr _error;
640 vector< _SolidData > _sdVec;
643 //--------------------------------------------------------------------------------
645 * \brief Shrinker of nodes on the EDGE
649 vector<double> _initU;
650 vector<double> _normPar;
651 vector<const SMDS_MeshNode*> _nodes;
652 const _LayerEdge* _edges[2];
655 void AddEdge( const _LayerEdge* e, SMESH_MesherHelper& helper );
656 void Compute(bool set3D, SMESH_MesherHelper& helper);
657 void RestoreParams();
658 void SwapSrcTgtNodes(SMESHDS_Mesh* mesh);
660 //--------------------------------------------------------------------------------
662 * \brief Class of temporary mesh face.
663 * We can't use SMDS_FaceOfNodes since it's impossible to set it's ID which is
664 * needed because SMESH_ElementSearcher internaly uses set of elements sorted by ID
666 struct _TmpMeshFace : public SMDS_MeshElement
668 vector<const SMDS_MeshNode* > _nn;
669 _TmpMeshFace( const vector<const SMDS_MeshNode*>& nodes, int id, int faceID=-1):
670 SMDS_MeshElement(id), _nn(nodes) { setShapeId(faceID); }
671 virtual const SMDS_MeshNode* GetNode(const int ind) const { return _nn[ind]; }
672 virtual SMDSAbs_ElementType GetType() const { return SMDSAbs_Face; }
673 virtual vtkIdType GetVtkType() const { return -1; }
674 virtual SMDSAbs_EntityType GetEntityType() const { return SMDSEntity_Last; }
675 virtual SMDSAbs_GeometryType GetGeomType() const
676 { return _nn.size() == 3 ? SMDSGeom_TRIANGLE : SMDSGeom_QUADRANGLE; }
677 virtual SMDS_ElemIteratorPtr elementsIterator(SMDSAbs_ElementType) const
678 { return SMDS_ElemIteratorPtr( new SMDS_NodeVectorElemIterator( _nn.begin(), _nn.end()));}
680 //--------------------------------------------------------------------------------
682 * \brief Class of temporary mesh face storing _LayerEdge it's based on
684 struct _TmpMeshFaceOnEdge : public _TmpMeshFace
686 _LayerEdge *_le1, *_le2;
687 _TmpMeshFaceOnEdge( _LayerEdge* le1, _LayerEdge* le2, int ID ):
688 _TmpMeshFace( vector<const SMDS_MeshNode*>(4), ID ), _le1(le1), _le2(le2)
690 _nn[0]=_le1->_nodes[0];
691 _nn[1]=_le1->_nodes.back();
692 _nn[2]=_le2->_nodes.back();
693 _nn[3]=_le2->_nodes[0];
696 //--------------------------------------------------------------------------------
698 * \brief Retriever of node coordinates either directly of from a surface by node UV.
699 * \warning Location of a surface is ignored
701 struct _NodeCoordHelper
703 SMESH_MesherHelper& _helper;
704 const TopoDS_Face& _face;
705 Handle(Geom_Surface) _surface;
706 gp_XYZ (_NodeCoordHelper::* _fun)(const SMDS_MeshNode* n) const;
708 _NodeCoordHelper(const TopoDS_Face& F, SMESH_MesherHelper& helper, bool is2D)
709 : _helper( helper ), _face( F )
714 _surface = BRep_Tool::Surface( _face, loc );
716 if ( _surface.IsNull() )
717 _fun = & _NodeCoordHelper::direct;
719 _fun = & _NodeCoordHelper::byUV;
721 gp_XYZ operator()(const SMDS_MeshNode* n) const { return (this->*_fun)( n ); }
724 gp_XYZ direct(const SMDS_MeshNode* n) const
726 return SMESH_TNodeXYZ( n );
728 gp_XYZ byUV (const SMDS_MeshNode* n) const
730 gp_XY uv = _helper.GetNodeUV( _face, n );
731 return _surface->Value( uv.X(), uv.Y() ).XYZ();
735 } // namespace VISCOUS_3D
739 //================================================================================
740 // StdMeshers_ViscousLayers hypothesis
742 StdMeshers_ViscousLayers::StdMeshers_ViscousLayers(int hypId, int studyId, SMESH_Gen* gen)
743 :SMESH_Hypothesis(hypId, studyId, gen),
744 _isToIgnoreShapes(1), _nbLayers(1), _thickness(1), _stretchFactor(1)
746 _name = StdMeshers_ViscousLayers::GetHypType();
747 _param_algo_dim = -3; // auxiliary hyp used by 3D algos
748 } // --------------------------------------------------------------------------------
749 void StdMeshers_ViscousLayers::SetBndShapes(const std::vector<int>& faceIds, bool toIgnore)
751 if ( faceIds != _shapeIds )
752 _shapeIds = faceIds, NotifySubMeshesHypothesisModification();
753 if ( _isToIgnoreShapes != toIgnore )
754 _isToIgnoreShapes = toIgnore, NotifySubMeshesHypothesisModification();
755 } // --------------------------------------------------------------------------------
756 void StdMeshers_ViscousLayers::SetTotalThickness(double thickness)
758 if ( thickness != _thickness )
759 _thickness = thickness, NotifySubMeshesHypothesisModification();
760 } // --------------------------------------------------------------------------------
761 void StdMeshers_ViscousLayers::SetNumberLayers(int nb)
763 if ( _nbLayers != nb )
764 _nbLayers = nb, NotifySubMeshesHypothesisModification();
765 } // --------------------------------------------------------------------------------
766 void StdMeshers_ViscousLayers::SetStretchFactor(double factor)
768 if ( _stretchFactor != factor )
769 _stretchFactor = factor, NotifySubMeshesHypothesisModification();
770 } // --------------------------------------------------------------------------------
772 StdMeshers_ViscousLayers::Compute(SMESH_Mesh& theMesh,
773 const TopoDS_Shape& theShape,
774 const bool toMakeN2NMap) const
776 using namespace VISCOUS_3D;
777 _ViscousBuilder bulder;
778 SMESH_ComputeErrorPtr err = bulder.Compute( theMesh, theShape );
779 if ( err && !err->IsOK() )
780 return SMESH_ProxyMesh::Ptr();
782 vector<SMESH_ProxyMesh::Ptr> components;
783 TopExp_Explorer exp( theShape, TopAbs_SOLID );
784 for ( ; exp.More(); exp.Next() )
786 if ( _MeshOfSolid* pm =
787 _ViscousListener::GetSolidMesh( &theMesh, exp.Current(), /*toCreate=*/false))
789 if ( toMakeN2NMap && !pm->_n2nMapComputed )
790 if ( !bulder.MakeN2NMap( pm ))
791 return SMESH_ProxyMesh::Ptr();
792 components.push_back( SMESH_ProxyMesh::Ptr( pm ));
793 pm->myIsDeletable = false; // it will de deleted by boost::shared_ptr
795 _ViscousListener::RemoveSolidMesh ( &theMesh, exp.Current() );
797 switch ( components.size() )
801 case 1: return components[0];
803 default: return SMESH_ProxyMesh::Ptr( new SMESH_ProxyMesh( components ));
805 return SMESH_ProxyMesh::Ptr();
806 } // --------------------------------------------------------------------------------
807 std::ostream & StdMeshers_ViscousLayers::SaveTo(std::ostream & save)
809 save << " " << _nbLayers
811 << " " << _stretchFactor
812 << " " << _shapeIds.size();
813 for ( size_t i = 0; i < _shapeIds.size(); ++i )
814 save << " " << _shapeIds[i];
815 save << " " << !_isToIgnoreShapes; // negate to keep the behavior in old studies.
817 } // --------------------------------------------------------------------------------
818 std::istream & StdMeshers_ViscousLayers::LoadFrom(std::istream & load)
820 int nbFaces, faceID, shapeToTreat;
821 load >> _nbLayers >> _thickness >> _stretchFactor >> nbFaces;
822 while ( _shapeIds.size() < nbFaces && load >> faceID )
823 _shapeIds.push_back( faceID );
824 if ( load >> shapeToTreat )
825 _isToIgnoreShapes = !shapeToTreat;
827 _isToIgnoreShapes = true; // old behavior
829 } // --------------------------------------------------------------------------------
830 bool StdMeshers_ViscousLayers::SetParametersByMesh(const SMESH_Mesh* theMesh,
831 const TopoDS_Shape& theShape)
836 // END StdMeshers_ViscousLayers hypothesis
837 //================================================================================
841 gp_XYZ getEdgeDir( const TopoDS_Edge& E, const TopoDS_Vertex& fromV )
845 Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
846 gp_Pnt p = BRep_Tool::Pnt( fromV );
847 double distF = p.SquareDistance( c->Value( f ));
848 double distL = p.SquareDistance( c->Value( l ));
849 c->D1(( distF < distL ? f : l), p, dir );
850 if ( distL < distF ) dir.Reverse();
853 //--------------------------------------------------------------------------------
854 gp_XYZ getEdgeDir( const TopoDS_Edge& E, const SMDS_MeshNode* atNode,
855 SMESH_MesherHelper& helper)
858 double f,l; gp_Pnt p;
859 Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
860 if ( c.IsNull() ) return gp_XYZ( 1e100, 1e100, 1e100 );
861 double u = helper.GetNodeU( E, atNode );
865 //--------------------------------------------------------------------------------
866 gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Vertex& fromV,
867 const SMDS_MeshNode* node, SMESH_MesherHelper& helper, bool& ok,
869 //--------------------------------------------------------------------------------
870 gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Edge& fromE,
871 const SMDS_MeshNode* node, SMESH_MesherHelper& helper, bool& ok)
874 Handle(Geom_Curve) c = BRep_Tool::Curve( fromE, f, l );
877 TopoDS_Vertex v = helper.IthVertex( 0, fromE );
878 return getFaceDir( F, v, node, helper, ok );
880 gp_XY uv = helper.GetNodeUV( F, node, 0, &ok );
881 Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
882 gp_Pnt p; gp_Vec du, dv, norm;
883 surface->D1( uv.X(),uv.Y(), p, du,dv );
886 double u = helper.GetNodeU( fromE, node, 0, &ok );
888 TopAbs_Orientation o = helper.GetSubShapeOri( F.Oriented(TopAbs_FORWARD), fromE);
889 if ( o == TopAbs_REVERSED )
892 gp_Vec dir = norm ^ du;
894 if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX &&
895 helper.IsClosedEdge( fromE ))
897 if ( fabs(u-f) < fabs(u-l)) c->D1( l, p, dv );
898 else c->D1( f, p, dv );
899 if ( o == TopAbs_REVERSED )
901 gp_Vec dir2 = norm ^ dv;
902 dir = dir.Normalized() + dir2.Normalized();
906 //--------------------------------------------------------------------------------
907 gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Vertex& fromV,
908 const SMDS_MeshNode* node, SMESH_MesherHelper& helper,
909 bool& ok, double* cosin)
911 TopoDS_Face faceFrw = F;
912 faceFrw.Orientation( TopAbs_FORWARD );
913 double f,l; TopLoc_Location loc;
914 TopoDS_Edge edges[2]; // sharing a vertex
918 TopExp_Explorer exp( faceFrw, TopAbs_EDGE );
919 for ( ; exp.More() && nbEdges < 2; exp.Next() )
921 const TopoDS_Edge& e = TopoDS::Edge( exp.Current() );
922 if ( SMESH_Algo::isDegenerated( e )) continue;
923 TopExp::Vertices( e, VV[0], VV[1], /*CumOri=*/true );
924 if ( VV[1].IsSame( fromV )) {
925 nbEdges += edges[ 0 ].IsNull();
928 else if ( VV[0].IsSame( fromV )) {
929 nbEdges += edges[ 1 ].IsNull();
934 gp_XYZ dir(0,0,0), edgeDir[2];
937 // get dirs of edges going fromV
939 for ( size_t i = 0; i < nbEdges && ok; ++i )
941 edgeDir[i] = getEdgeDir( edges[i], fromV );
942 double size2 = edgeDir[i].SquareModulus();
943 if (( ok = size2 > numeric_limits<double>::min() ))
944 edgeDir[i] /= sqrt( size2 );
946 if ( !ok ) return dir;
948 // get angle between the 2 edges
950 double angle = helper.GetAngle( edges[0], edges[1], faceFrw, fromV, &faceNormal );
951 if ( Abs( angle ) < 5 * M_PI/180 )
953 dir = ( faceNormal.XYZ() ^ edgeDir[0].Reversed()) + ( faceNormal.XYZ() ^ edgeDir[1] );
957 dir = edgeDir[0] + edgeDir[1];
962 double angle = gp_Vec( edgeDir[0] ).Angle( dir );
963 *cosin = Cos( angle );
966 else if ( nbEdges == 1 )
968 dir = getFaceDir( faceFrw, edges[ edges[0].IsNull() ], node, helper, ok );
969 if ( cosin ) *cosin = 1.;
978 //================================================================================
980 * \brief Returns true if a FACE is bound by a concave EDGE
982 //================================================================================
984 bool isConcave( const TopoDS_Face& F, SMESH_MesherHelper& helper )
986 // if ( helper.Count( F, TopAbs_WIRE, /*useMap=*/false) > 1 )
990 TopExp_Explorer eExp( F.Oriented( TopAbs_FORWARD ), TopAbs_EDGE );
991 for ( ; eExp.More(); eExp.Next() )
993 const TopoDS_Edge& E = TopoDS::Edge( eExp.Current() );
994 if ( SMESH_Algo::isDegenerated( E )) continue;
995 // check if 2D curve is concave
996 BRepAdaptor_Curve2d curve( E, F );
997 const int nbIntervals = curve.NbIntervals( GeomAbs_C2 );
998 TColStd_Array1OfReal intervals(1, nbIntervals + 1 );
999 curve.Intervals( intervals, GeomAbs_C2 );
1000 bool isConvex = true;
1001 for ( int i = 1; i <= nbIntervals && isConvex; ++i )
1003 double u1 = intervals( i );
1004 double u2 = intervals( i+1 );
1005 curve.D2( 0.5*( u1+u2 ), p, drv1, drv2 );
1006 double cross = drv2 ^ drv1;
1007 if ( E.Orientation() == TopAbs_REVERSED )
1009 isConvex = ( cross > 0.1 ); //-1e-9 );
1013 //cout << "Concave FACE " << helper.GetMeshDS()->ShapeToIndex( F ) << endl;
1017 // check angles at VERTEXes
1019 TSideVector wires = StdMeshers_FaceSide::GetFaceWires( F, *helper.GetMesh(), 0, error );
1020 for ( size_t iW = 0; iW < wires.size(); ++iW )
1022 const int nbEdges = wires[iW]->NbEdges();
1023 if ( nbEdges < 2 && SMESH_Algo::isDegenerated( wires[iW]->Edge(0)))
1025 for ( int iE1 = 0; iE1 < nbEdges; ++iE1 )
1027 if ( SMESH_Algo::isDegenerated( wires[iW]->Edge( iE1 ))) continue;
1028 int iE2 = ( iE1 + 1 ) % nbEdges;
1029 while ( SMESH_Algo::isDegenerated( wires[iW]->Edge( iE2 )))
1030 iE2 = ( iE2 + 1 ) % nbEdges;
1031 double angle = helper.GetAngle( wires[iW]->Edge( iE1 ),
1032 wires[iW]->Edge( iE2 ), F,
1033 wires[iW]->FirstVertex( iE2 ));
1034 if ( angle < -5. * M_PI / 180. )
1040 //================================================================================
1042 * \brief Computes mimimal distance of face in-FACE nodes from an EDGE
1043 * \param [in] face - the mesh face to treat
1044 * \param [in] nodeOnEdge - a node on the EDGE
1045 * \param [out] faceSize - the computed distance
1046 * \return bool - true if faceSize computed
1048 //================================================================================
1050 bool getDistFromEdge( const SMDS_MeshElement* face,
1051 const SMDS_MeshNode* nodeOnEdge,
1054 faceSize = Precision::Infinite();
1057 int nbN = face->NbCornerNodes();
1058 int iOnE = face->GetNodeIndex( nodeOnEdge );
1059 int iNext[2] = { SMESH_MesherHelper::WrapIndex( iOnE+1, nbN ),
1060 SMESH_MesherHelper::WrapIndex( iOnE-1, nbN ) };
1061 const SMDS_MeshNode* nNext[2] = { face->GetNode( iNext[0] ),
1062 face->GetNode( iNext[1] ) };
1063 gp_XYZ segVec, segEnd = SMESH_TNodeXYZ( nodeOnEdge ); // segment on EDGE
1064 double segLen = -1.;
1065 // look for two neighbor not in-FACE nodes of face
1066 for ( int i = 0; i < 2; ++i )
1068 if ( nNext[i]->GetPosition()->GetDim() != 2 &&
1069 nNext[i]->GetID() < nodeOnEdge->GetID() )
1071 // look for an in-FACE node
1072 for ( int iN = 0; iN < nbN; ++iN )
1074 if ( iN == iOnE || iN == iNext[i] )
1076 SMESH_TNodeXYZ pInFace = face->GetNode( iN );
1077 gp_XYZ v = pInFace - segEnd;
1080 segVec = SMESH_TNodeXYZ( nNext[i] ) - segEnd;
1081 segLen = segVec.Modulus();
1083 double distToSeg = v.Crossed( segVec ).Modulus() / segLen;
1084 faceSize = Min( faceSize, distToSeg );
1093 //--------------------------------------------------------------------------------
1094 // DEBUG. Dump intermediate node positions into a python script
1095 // HOWTO use: run python commands written in a console to see
1096 // construction steps of viscous layers
1102 const char* fname = "/tmp/viscous.py";
1103 cout << "execfile('"<<fname<<"')"<<endl;
1104 py = new ofstream(fname);
1105 *py << "import SMESH" << endl
1106 << "from salome.smesh import smeshBuilder" << endl
1107 << "smesh = smeshBuilder.New(salome.myStudy)" << endl
1108 << "meshSO = smesh.GetCurrentStudy().FindObjectID('0:1:2:3')" << endl
1109 << "mesh = smesh.Mesh( meshSO.GetObject() )"<<endl;
1114 *py << "mesh.GroupOnFilter(SMESH.VOLUME,'Viscous Prisms',"
1115 "smesh.GetFilter(SMESH.VOLUME,SMESH.FT_ElemGeomType,'=',SMESH.Geom_PENTA))"<<endl;
1116 *py << "mesh.GroupOnFilter(SMESH.VOLUME,'Neg Volumes',"
1117 "smesh.GetFilter(SMESH.VOLUME,SMESH.FT_Volume3D,'<',0))"<<endl;
1121 ~PyDump() { Finish(); cout << "NB FUNCTIONS: " << theNbFunc << endl; }
1123 #define dumpFunction(f) { _dumpFunction(f, __LINE__);}
1124 #define dumpMove(n) { _dumpMove(n, __LINE__);}
1125 #define dumpCmd(txt) { _dumpCmd(txt, __LINE__);}
1126 void _dumpFunction(const string& fun, int ln)
1127 { if (py) *py<< "def "<<fun<<"(): # "<< ln <<endl; cout<<fun<<"()"<<endl; ++theNbFunc; }
1128 void _dumpMove(const SMDS_MeshNode* n, int ln)
1129 { if (py) *py<< " mesh.MoveNode( "<<n->GetID()<< ", "<< n->X()
1130 << ", "<<n->Y()<<", "<< n->Z()<< ")\t\t # "<< ln <<endl; }
1131 void _dumpCmd(const string& txt, int ln)
1132 { if (py) *py<< " "<<txt<<" # "<< ln <<endl; }
1133 void dumpFunctionEnd()
1134 { if (py) *py<< " return"<< endl; }
1135 void dumpChangeNodes( const SMDS_MeshElement* f )
1136 { if (py) { *py<< " mesh.ChangeElemNodes( " << f->GetID()<<", [";
1137 for ( int i=1; i < f->NbNodes(); ++i ) *py << f->GetNode(i-1)->GetID()<<", ";
1138 *py << f->GetNode( f->NbNodes()-1 )->GetID() << " ])"<< endl; }}
1139 #define debugMsg( txt ) { cout << txt << " (line: " << __LINE__ << ")" << endl; }
1141 struct PyDump { void Finish() {} };
1142 #define dumpFunction(f) f
1144 #define dumpCmd(txt)
1145 #define dumpFunctionEnd()
1146 #define dumpChangeNodes(f)
1147 #define debugMsg( txt ) {}
1151 using namespace VISCOUS_3D;
1153 //================================================================================
1155 * \brief Constructor of _ViscousBuilder
1157 //================================================================================
1159 _ViscousBuilder::_ViscousBuilder()
1161 _error = SMESH_ComputeError::New(COMPERR_OK);
1165 //================================================================================
1167 * \brief Stores error description and returns false
1169 //================================================================================
1171 bool _ViscousBuilder::error(const string& text, int solidId )
1173 const string prefix = string("Viscous layers builder: ");
1174 _error->myName = COMPERR_ALGO_FAILED;
1175 _error->myComment = prefix + text;
1178 SMESH_subMesh* sm = _mesh->GetSubMeshContaining( solidId );
1179 if ( !sm && !_sdVec.empty() )
1180 sm = _mesh->GetSubMeshContaining( solidId = _sdVec[0]._index );
1181 if ( sm && sm->GetSubShape().ShapeType() == TopAbs_SOLID )
1183 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1184 if ( smError && smError->myAlgo )
1185 _error->myAlgo = smError->myAlgo;
1187 sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1189 // set KO to all solids
1190 for ( size_t i = 0; i < _sdVec.size(); ++i )
1192 if ( _sdVec[i]._index == solidId )
1194 sm = _mesh->GetSubMesh( _sdVec[i]._solid );
1195 if ( !sm->IsEmpty() )
1197 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1198 if ( !smError || smError->IsOK() )
1200 smError = SMESH_ComputeError::New( COMPERR_ALGO_FAILED, prefix + "failed");
1201 sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1205 makeGroupOfLE(); // debug
1210 //================================================================================
1212 * \brief At study restoration, restore event listeners used to clear an inferior
1213 * dim sub-mesh modified by viscous layers
1215 //================================================================================
1217 void _ViscousBuilder::RestoreListeners()
1222 //================================================================================
1224 * \brief computes SMESH_ProxyMesh::SubMesh::_n2n
1226 //================================================================================
1228 bool _ViscousBuilder::MakeN2NMap( _MeshOfSolid* pm )
1230 SMESH_subMesh* solidSM = pm->mySubMeshes.front();
1231 TopExp_Explorer fExp( solidSM->GetSubShape(), TopAbs_FACE );
1232 for ( ; fExp.More(); fExp.Next() )
1234 SMESHDS_SubMesh* srcSmDS = pm->GetMeshDS()->MeshElements( fExp.Current() );
1235 const SMESH_ProxyMesh::SubMesh* prxSmDS = pm->GetProxySubMesh( fExp.Current() );
1237 if ( !srcSmDS || !prxSmDS || !srcSmDS->NbElements() || !prxSmDS->NbElements() )
1239 if ( srcSmDS->GetElements()->next() == prxSmDS->GetElements()->next())
1242 if ( srcSmDS->NbElements() != prxSmDS->NbElements() )
1243 return error( "Different nb elements in a source and a proxy sub-mesh", solidSM->GetId());
1245 SMDS_ElemIteratorPtr srcIt = srcSmDS->GetElements();
1246 SMDS_ElemIteratorPtr prxIt = prxSmDS->GetElements();
1247 while( prxIt->more() )
1249 const SMDS_MeshElement* fSrc = srcIt->next();
1250 const SMDS_MeshElement* fPrx = prxIt->next();
1251 if ( fSrc->NbNodes() != fPrx->NbNodes())
1252 return error( "Different elements in a source and a proxy sub-mesh", solidSM->GetId());
1253 for ( int i = 0 ; i < fPrx->NbNodes(); ++i )
1254 pm->setNode2Node( fSrc->GetNode(i), fPrx->GetNode(i), prxSmDS );
1257 pm->_n2nMapComputed = true;
1261 //================================================================================
1263 * \brief Does its job
1265 //================================================================================
1267 SMESH_ComputeErrorPtr _ViscousBuilder::Compute(SMESH_Mesh& theMesh,
1268 const TopoDS_Shape& theShape)
1270 // TODO: set priority of solids during Gen::Compute()
1274 // check if proxy mesh already computed
1275 TopExp_Explorer exp( theShape, TopAbs_SOLID );
1277 return error("No SOLID's in theShape"), _error;
1279 if ( _ViscousListener::GetSolidMesh( _mesh, exp.Current(), /*toCreate=*/false))
1280 return SMESH_ComputeErrorPtr(); // everything already computed
1284 // TODO: ignore already computed SOLIDs
1285 if ( !findSolidsWithLayers())
1288 if ( !findFacesWithLayers() )
1291 for ( size_t i = 0; i < _sdVec.size(); ++i )
1293 if ( ! makeLayer(_sdVec[i]) )
1296 if ( _sdVec[i]._edges.size() == 0 )
1299 if ( ! inflate(_sdVec[i]) )
1302 if ( ! refine(_sdVec[i]) )
1308 addBoundaryElements();
1310 makeGroupOfLE(); // debug
1316 //================================================================================
1318 * \brief Finds SOLIDs to compute using viscous layers. Fills _sdVec
1320 //================================================================================
1322 bool _ViscousBuilder::findSolidsWithLayers()
1325 TopTools_IndexedMapOfShape allSolids;
1326 TopExp::MapShapes( _mesh->GetShapeToMesh(), TopAbs_SOLID, allSolids );
1327 _sdVec.reserve( allSolids.Extent());
1329 SMESH_Gen* gen = _mesh->GetGen();
1330 SMESH_HypoFilter filter;
1331 for ( int i = 1; i <= allSolids.Extent(); ++i )
1333 // find StdMeshers_ViscousLayers hyp assigned to the i-th solid
1334 SMESH_Algo* algo = gen->GetAlgo( *_mesh, allSolids(i) );
1335 if ( !algo ) continue;
1336 // TODO: check if algo is hidden
1337 const list <const SMESHDS_Hypothesis *> & allHyps =
1338 algo->GetUsedHypothesis(*_mesh, allSolids(i), /*ignoreAuxiliary=*/false);
1339 list< const SMESHDS_Hypothesis *>::const_iterator hyp = allHyps.begin();
1340 const StdMeshers_ViscousLayers* viscHyp = 0;
1341 for ( ; hyp != allHyps.end() && !viscHyp; ++hyp )
1342 viscHyp = dynamic_cast<const StdMeshers_ViscousLayers*>( *hyp );
1345 TopoDS_Shape hypShape;
1346 filter.Init( filter.Is( viscHyp ));
1347 _mesh->GetHypothesis( allSolids(i), filter, true, &hypShape );
1349 _MeshOfSolid* proxyMesh = _ViscousListener::GetSolidMesh( _mesh,
1352 _sdVec.push_back( _SolidData( allSolids(i), viscHyp, hypShape, proxyMesh ));
1353 _sdVec.back()._index = getMeshDS()->ShapeToIndex( allSolids(i));
1356 if ( _sdVec.empty() )
1358 ( SMESH_Comment(StdMeshers_ViscousLayers::GetHypType()) << " hypothesis not found",0);
1363 //================================================================================
1367 //================================================================================
1369 bool _ViscousBuilder::findFacesWithLayers()
1371 SMESH_MesherHelper helper( *_mesh );
1372 TopExp_Explorer exp;
1373 TopTools_IndexedMapOfShape solids;
1375 // collect all faces to ignore defined by hyp
1376 for ( size_t i = 0; i < _sdVec.size(); ++i )
1378 solids.Add( _sdVec[i]._solid );
1380 vector<TGeomID> ids = _sdVec[i]._hyp->GetBndShapes();
1381 if ( _sdVec[i]._hyp->IsToIgnoreShapes() ) // FACEs to ignore are given
1383 for ( size_t ii = 0; ii < ids.size(); ++ii )
1385 const TopoDS_Shape& s = getMeshDS()->IndexToShape( ids[ii] );
1386 if ( !s.IsNull() && s.ShapeType() == TopAbs_FACE )
1387 _sdVec[i]._ignoreFaceIds.insert( ids[ii] );
1390 else // FACEs with layers are given
1392 exp.Init( _sdVec[i]._solid, TopAbs_FACE );
1393 for ( ; exp.More(); exp.Next() )
1395 TGeomID faceInd = getMeshDS()->ShapeToIndex( exp.Current() );
1396 if ( find( ids.begin(), ids.end(), faceInd ) == ids.end() )
1397 _sdVec[i]._ignoreFaceIds.insert( faceInd );
1401 // ignore internal FACEs if inlets and outlets are specified
1403 TopTools_IndexedDataMapOfShapeListOfShape solidsOfFace;
1404 if ( _sdVec[i]._hyp->IsToIgnoreShapes() )
1405 TopExp::MapShapesAndAncestors( _sdVec[i]._hypShape,
1406 TopAbs_FACE, TopAbs_SOLID, solidsOfFace);
1408 exp.Init( _sdVec[i]._solid.Oriented( TopAbs_FORWARD ), TopAbs_FACE );
1409 for ( ; exp.More(); exp.Next() )
1411 const TopoDS_Face& face = TopoDS::Face( exp.Current() );
1412 if ( helper.NbAncestors( face, *_mesh, TopAbs_SOLID ) < 2 )
1415 const TGeomID faceInd = getMeshDS()->ShapeToIndex( face );
1416 if ( _sdVec[i]._hyp->IsToIgnoreShapes() )
1418 int nbSolids = solidsOfFace.FindFromKey( face ).Extent();
1420 _sdVec[i]._ignoreFaceIds.insert( faceInd );
1423 if ( helper.IsReversedSubMesh( face ))
1425 _sdVec[i]._reversedFaceIds.insert( faceInd );
1431 // Find faces to shrink mesh on (solution 2 in issue 0020832);
1432 TopTools_IndexedMapOfShape shapes;
1433 for ( size_t i = 0; i < _sdVec.size(); ++i )
1436 TopExp::MapShapes(_sdVec[i]._solid, TopAbs_EDGE, shapes);
1437 for ( int iE = 1; iE <= shapes.Extent(); ++iE )
1439 const TopoDS_Shape& edge = shapes(iE);
1440 // find 2 faces sharing an edge
1442 PShapeIteratorPtr fIt = helper.GetAncestors(edge, *_mesh, TopAbs_FACE);
1443 while ( fIt->more())
1445 const TopoDS_Shape* f = fIt->next();
1446 if ( helper.IsSubShape( *f, _sdVec[i]._solid))
1447 FF[ int( !FF[0].IsNull()) ] = *f;
1449 if( FF[1].IsNull() ) continue; // seam edge can be shared by 1 FACE only
1450 // check presence of layers on them
1452 for ( int j = 0; j < 2; ++j )
1453 ignore[j] = _sdVec[i]._ignoreFaceIds.count ( getMeshDS()->ShapeToIndex( FF[j] ));
1454 if ( ignore[0] == ignore[1] )
1455 continue; // nothing interesting
1456 TopoDS_Shape fWOL = FF[ ignore[0] ? 0 : 1 ];
1457 // check presence of layers on fWOL within an adjacent SOLID
1458 bool collision = false;
1459 PShapeIteratorPtr sIt = helper.GetAncestors( fWOL, *_mesh, TopAbs_SOLID );
1460 while ( const TopoDS_Shape* solid = sIt->next() )
1461 if ( !solid->IsSame( _sdVec[i]._solid ))
1463 int iSolid = solids.FindIndex( *solid );
1464 int iFace = getMeshDS()->ShapeToIndex( fWOL );
1465 if ( iSolid > 0 && !_sdVec[ iSolid-1 ]._ignoreFaceIds.count( iFace ))
1467 //_sdVec[i]._noShrinkShapes.insert( iFace );
1473 if ( !fWOL.IsNull())
1475 TGeomID edgeInd = getMeshDS()->ShapeToIndex( edge );
1476 _sdVec[i]._shrinkShape2Shape.insert( make_pair( edgeInd, fWOL ));
1479 // _shrinkShape2Shape will be used to temporary inflate _LayerEdge's based
1480 // on the edge but shrink won't be performed
1481 _sdVec[i]._noShrinkShapes.insert( edgeInd );
1486 // Exclude from _shrinkShape2Shape FACE's that can't be shrinked since
1487 // the algo of the SOLID sharing the FACE does not support it
1488 set< string > notSupportAlgos; notSupportAlgos.insert("Hexa_3D");
1489 for ( size_t i = 0; i < _sdVec.size(); ++i )
1491 map< TGeomID, TopoDS_Shape >::iterator e2f = _sdVec[i]._shrinkShape2Shape.begin();
1492 for ( ; e2f != _sdVec[i]._shrinkShape2Shape.end(); ++e2f )
1494 const TopoDS_Shape& fWOL = e2f->second;
1495 const TGeomID edgeID = e2f->first;
1496 bool notShrinkFace = false;
1497 PShapeIteratorPtr soIt = helper.GetAncestors(fWOL, *_mesh, TopAbs_SOLID);
1498 while ( soIt->more() )
1500 const TopoDS_Shape* solid = soIt->next();
1501 if ( _sdVec[i]._solid.IsSame( *solid )) continue;
1502 SMESH_Algo* algo = _mesh->GetGen()->GetAlgo( *_mesh, *solid );
1503 if ( !algo || !notSupportAlgos.count( algo->GetName() )) continue;
1504 notShrinkFace = true;
1506 for ( ; iSolid < _sdVec.size(); ++iSolid )
1508 if ( _sdVec[iSolid]._solid.IsSame( *solid ) ) {
1509 if ( _sdVec[iSolid]._shrinkShape2Shape.count( edgeID ))
1510 notShrinkFace = false;
1514 if ( notShrinkFace )
1516 _sdVec[i]._noShrinkShapes.insert( edgeID );
1518 // add VERTEXes of the edge in _noShrinkShapes
1519 TopoDS_Shape edge = getMeshDS()->IndexToShape( edgeID );
1520 for ( TopoDS_Iterator vIt( edge ); vIt.More(); vIt.Next() )
1521 _sdVec[i]._noShrinkShapes.insert( getMeshDS()->ShapeToIndex( vIt.Value() ));
1523 // check if there is a collision with to-shrink-from EDGEs in iSolid
1524 if ( iSolid == _sdVec.size() )
1525 continue; // no VL in the solid
1527 TopExp::MapShapes( fWOL, TopAbs_EDGE, shapes);
1528 for ( int iE = 1; iE <= shapes.Extent(); ++iE )
1530 const TopoDS_Edge& E = TopoDS::Edge( shapes( iE ));
1531 const TGeomID eID = getMeshDS()->ShapeToIndex( E );
1532 if ( eID == edgeID ||
1533 !_sdVec[iSolid]._shrinkShape2Shape.count( eID ) ||
1534 _sdVec[i]._noShrinkShapes.count( eID ))
1536 for ( int is1st = 0; is1st < 2; ++is1st )
1538 TopoDS_Vertex V = helper.IthVertex( is1st, E );
1539 if ( _sdVec[i]._noShrinkShapes.count( getMeshDS()->ShapeToIndex( V ) ))
1541 // _sdVec[i]._noShrinkShapes.insert( eID );
1542 // V = helper.IthVertex( !is1st, E );
1543 // _sdVec[i]._noShrinkShapes.insert( getMeshDS()->ShapeToIndex( V ));
1544 //iE = 0; // re-start the loop on EDGEs of fWOL
1545 return error("No way to make a conformal mesh with "
1546 "the given set of faces with layers", _sdVec[i]._index);
1552 } // while ( soIt->more() )
1553 } // loop on _sdVec[i]._shrinkShape2Shape
1554 } // loop on _sdVec to fill in _SolidData::_noShrinkShapes
1556 // Find the SHAPE along which to inflate _LayerEdge based on VERTEX
1558 for ( size_t i = 0; i < _sdVec.size(); ++i )
1561 TopExp::MapShapes(_sdVec[i]._solid, TopAbs_VERTEX, shapes);
1562 for ( int iV = 1; iV <= shapes.Extent(); ++iV )
1564 const TopoDS_Shape& vertex = shapes(iV);
1565 // find faces WOL sharing the vertex
1566 vector< TopoDS_Shape > facesWOL;
1567 int totalNbFaces = 0;
1568 PShapeIteratorPtr fIt = helper.GetAncestors(vertex, *_mesh, TopAbs_FACE);
1569 while ( fIt->more())
1571 const TopoDS_Shape* f = fIt->next();
1572 if ( helper.IsSubShape( *f, _sdVec[i]._solid ) )
1575 const int fID = getMeshDS()->ShapeToIndex( *f );
1576 if ( _sdVec[i]._ignoreFaceIds.count ( fID ) /*&&
1577 !_sdVec[i]._noShrinkShapes.count( fID )*/)
1578 facesWOL.push_back( *f );
1581 if ( facesWOL.size() == totalNbFaces || facesWOL.empty() )
1582 continue; // no layers at this vertex or no WOL
1583 TGeomID vInd = getMeshDS()->ShapeToIndex( vertex );
1584 switch ( facesWOL.size() )
1588 helper.SetSubShape( facesWOL[0] );
1589 if ( helper.IsRealSeam( vInd )) // inflate along a seam edge?
1591 TopoDS_Shape seamEdge;
1592 PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
1593 while ( eIt->more() && seamEdge.IsNull() )
1595 const TopoDS_Shape* e = eIt->next();
1596 if ( helper.IsRealSeam( *e ) )
1599 if ( !seamEdge.IsNull() )
1601 _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, seamEdge ));
1605 _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, facesWOL[0] ));
1610 // find an edge shared by 2 faces
1611 PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
1612 while ( eIt->more())
1614 const TopoDS_Shape* e = eIt->next();
1615 if ( helper.IsSubShape( *e, facesWOL[0]) &&
1616 helper.IsSubShape( *e, facesWOL[1]))
1618 _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, *e )); break;
1624 return error("Not yet supported case", _sdVec[i]._index);
1629 // add FACEs of other SOLIDs to _ignoreFaceIds
1630 for ( size_t i = 0; i < _sdVec.size(); ++i )
1633 TopExp::MapShapes(_sdVec[i]._solid, TopAbs_FACE, shapes);
1635 for ( exp.Init( _mesh->GetShapeToMesh(), TopAbs_FACE ); exp.More(); exp.Next() )
1637 if ( !shapes.Contains( exp.Current() ))
1638 _sdVec[i]._ignoreFaceIds.insert( getMeshDS()->ShapeToIndex( exp.Current() ));
1645 //================================================================================
1647 * \brief Create the inner surface of the viscous layer and prepare data for infation
1649 //================================================================================
1651 bool _ViscousBuilder::makeLayer(_SolidData& data)
1653 // get all sub-shapes to make layers on
1654 set<TGeomID> subIds, faceIds;
1655 subIds = data._noShrinkShapes;
1656 TopExp_Explorer exp( data._solid, TopAbs_FACE );
1657 for ( ; exp.More(); exp.Next() )
1659 SMESH_subMesh* fSubM = _mesh->GetSubMesh( exp.Current() );
1660 if ( ! data._ignoreFaceIds.count( fSubM->GetId() ))
1661 faceIds.insert( fSubM->GetId() );
1662 SMESH_subMeshIteratorPtr subIt = fSubM->getDependsOnIterator(/*includeSelf=*/true);
1663 while ( subIt->more() )
1664 subIds.insert( subIt->next()->GetId() );
1667 // make a map to find new nodes on sub-shapes shared with other SOLID
1668 map< TGeomID, TNode2Edge* >::iterator s2ne;
1669 map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
1670 for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
1672 TGeomID shapeInd = s2s->first;
1673 for ( size_t i = 0; i < _sdVec.size(); ++i )
1675 if ( _sdVec[i]._index == data._index ) continue;
1676 map< TGeomID, TopoDS_Shape >::iterator s2s2 = _sdVec[i]._shrinkShape2Shape.find( shapeInd );
1677 if ( s2s2 != _sdVec[i]._shrinkShape2Shape.end() &&
1678 *s2s == *s2s2 && !_sdVec[i]._n2eMap.empty() )
1680 data._s2neMap.insert( make_pair( shapeInd, &_sdVec[i]._n2eMap ));
1686 // Create temporary faces and _LayerEdge's
1688 dumpFunction(SMESH_Comment("makeLayers_")<<data._index);
1690 data._stepSize = Precision::Infinite();
1691 data._stepSizeNodes[0] = 0;
1693 SMESH_MesherHelper helper( *_mesh );
1694 helper.SetSubShape( data._solid );
1695 helper.SetElementsOnShape( true );
1697 vector< const SMDS_MeshNode*> newNodes; // of a mesh face
1698 TNode2Edge::iterator n2e2;
1700 // collect _LayerEdge's of shapes they are based on
1701 const int nbShapes = getMeshDS()->MaxShapeIndex();
1702 vector< vector<_LayerEdge*> > edgesByGeom( nbShapes+1 );
1704 for ( set<TGeomID>::iterator id = faceIds.begin(); id != faceIds.end(); ++id )
1706 SMESHDS_SubMesh* smDS = getMeshDS()->MeshElements( *id );
1707 if ( !smDS ) return error(SMESH_Comment("Not meshed face ") << *id, data._index );
1709 const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( *id ));
1710 SMESH_ProxyMesh::SubMesh* proxySub =
1711 data._proxyMesh->getFaceSubM( F, /*create=*/true);
1713 SMDS_ElemIteratorPtr eIt = smDS->GetElements();
1714 while ( eIt->more() )
1716 const SMDS_MeshElement* face = eIt->next();
1717 double faceMaxCosin = -1;
1718 _LayerEdge* maxCosinEdge = 0;
1719 int nbDegenNodes = 0;
1721 newNodes.resize( face->NbCornerNodes() );
1722 for ( size_t i = 0 ; i < newNodes.size(); ++i )
1724 const SMDS_MeshNode* n = face->GetNode( i );
1725 const int shapeID = n->getshapeId();
1726 const bool onDegenShap = helper.IsDegenShape( shapeID );
1727 const bool onDegenEdge = ( onDegenShap && n->GetPosition()->GetDim() == 1 );
1732 // substitute n on a degenerated EDGE with a node on a corresponding VERTEX
1733 const TopoDS_Shape& E = getMeshDS()->IndexToShape( shapeID );
1734 TopoDS_Vertex V = helper.IthVertex( 0, TopoDS::Edge( E ));
1735 if ( const SMDS_MeshNode* vN = SMESH_Algo::VertexNode( V, getMeshDS() )) {
1745 TNode2Edge::iterator n2e = data._n2eMap.insert( make_pair( n, (_LayerEdge*)0 )).first;
1746 if ( !(*n2e).second )
1749 _LayerEdge* edge = new _LayerEdge();
1750 edge->_nodes.push_back( n );
1752 edgesByGeom[ shapeID ].push_back( edge );
1753 const bool noShrink = data._noShrinkShapes.count( shapeID );
1755 SMESH_TNodeXYZ xyz( n );
1757 // set edge data or find already refined _LayerEdge and get data from it
1758 if (( !noShrink ) &&
1759 ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE ) &&
1760 (( s2ne = data._s2neMap.find( shapeID )) != data._s2neMap.end() ) &&
1761 (( n2e2 = (*s2ne).second->find( n )) != s2ne->second->end() ))
1763 _LayerEdge* foundEdge = (*n2e2).second;
1764 gp_XYZ lastPos = edge->Copy( *foundEdge, helper );
1765 foundEdge->_pos.push_back( lastPos );
1766 // location of the last node is modified and we restore it by foundEdge->_pos.back()
1767 const_cast< SMDS_MeshNode* >
1768 ( edge->_nodes.back() )->setXYZ( xyz.X(), xyz.Y(), xyz.Z() );
1774 edge->_nodes.push_back( helper.AddNode( xyz.X(), xyz.Y(), xyz.Z() ));
1776 if ( !setEdgeData( *edge, subIds, helper, data ))
1779 dumpMove(edge->_nodes.back());
1781 if ( edge->_cosin > faceMaxCosin )
1783 faceMaxCosin = edge->_cosin;
1784 maxCosinEdge = edge;
1787 newNodes[ i ] = n2e->second->_nodes.back();
1790 data._n2eMap.insert( make_pair( face->GetNode( i ), n2e->second ));
1792 if ( newNodes.size() - nbDegenNodes < 2 )
1795 // create a temporary face
1796 const SMDS_MeshElement* newFace =
1797 new _TmpMeshFace( newNodes, --_tmpFaceID, face->getshapeId() );
1798 proxySub->AddElement( newFace );
1800 // compute inflation step size by min size of element on a convex surface
1801 if ( faceMaxCosin > theMinSmoothCosin )
1802 limitStepSize( data, face, maxCosinEdge );
1804 } // loop on 2D elements on a FACE
1805 } // loop on FACEs of a SOLID
1807 data._epsilon = 1e-7;
1808 if ( data._stepSize < 1. )
1809 data._epsilon *= data._stepSize;
1811 // Put _LayerEdge's into the vector data._edges
1812 if ( !sortEdges( data, edgesByGeom ))
1815 // limit data._stepSize depending on surface curvature and fill data._convexFaces
1816 limitStepSizeByCurvature( data ); // !!! it must be before node substitution in _Simplex
1818 // Set target nodes into _Simplex and _LayerEdge's to _2NearEdges
1819 TNode2Edge::iterator n2e;
1820 const SMDS_MeshNode* nn[2];
1821 for ( size_t i = 0; i < data._edges.size(); ++i )
1823 _LayerEdge* edge = data._edges[i];
1824 if ( edge->IsOnEdge() )
1826 // get neighbor nodes
1827 bool hasData = ( edge->_2neibors->_edges[0] );
1828 if ( hasData ) // _LayerEdge is a copy of another one
1830 nn[0] = edge->_2neibors->srcNode(0);
1831 nn[1] = edge->_2neibors->srcNode(1);
1833 else if ( !findNeiborsOnEdge( edge, nn[0],nn[1], data ))
1837 // set neighbor _LayerEdge's
1838 for ( int j = 0; j < 2; ++j )
1840 if (( n2e = data._n2eMap.find( nn[j] )) == data._n2eMap.end() )
1841 return error("_LayerEdge not found by src node", data._index);
1842 edge->_2neibors->_edges[j] = n2e->second;
1845 edge->SetDataByNeighbors( nn[0], nn[1], helper);
1848 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
1850 _Simplex& s = edge->_simplices[j];
1851 s._nNext = data._n2eMap[ s._nNext ]->_nodes.back();
1852 s._nPrev = data._n2eMap[ s._nPrev ]->_nodes.back();
1855 // For an _LayerEdge on a degenerated EDGE, copy some data from
1856 // a corresponding _LayerEdge on a VERTEX
1857 // (issue 52453, pb on a downloaded SampleCase2-Tet-netgen-mephisto.hdf)
1858 if ( helper.IsDegenShape( edge->_nodes[0]->getshapeId() ))
1860 // Generally we should not get here
1861 const TopoDS_Shape& E = getMeshDS()->IndexToShape( edge->_nodes[0]->getshapeId() );
1862 if ( E.ShapeType() != TopAbs_EDGE )
1864 TopoDS_Vertex V = helper.IthVertex( 0, TopoDS::Edge( E ));
1865 const SMDS_MeshNode* vN = SMESH_Algo::VertexNode( V, getMeshDS() );
1866 if (( n2e = data._n2eMap.find( vN )) == data._n2eMap.end() )
1868 const _LayerEdge* vEdge = n2e->second;
1869 edge->_normal = vEdge->_normal;
1870 edge->_lenFactor = vEdge->_lenFactor;
1871 edge->_cosin = vEdge->_cosin;
1879 //================================================================================
1881 * \brief Compute inflation step size by min size of element on a convex surface
1883 //================================================================================
1885 void _ViscousBuilder::limitStepSize( _SolidData& data,
1886 const SMDS_MeshElement* face,
1887 const _LayerEdge* maxCosinEdge )
1890 double minSize = 10 * data._stepSize;
1891 const int nbNodes = face->NbCornerNodes();
1892 for ( int i = 0; i < nbNodes; ++i )
1894 const SMDS_MeshNode* nextN = face->GetNode( SMESH_MesherHelper::WrapIndex( i+1, nbNodes ));
1895 const SMDS_MeshNode* curN = face->GetNode( i );
1896 if ( nextN->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE ||
1897 curN-> GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE )
1899 double dist = SMESH_TNodeXYZ( curN ).Distance( nextN );
1900 if ( dist < minSize )
1901 minSize = dist, iN = i;
1904 double newStep = 0.8 * minSize / maxCosinEdge->_lenFactor;
1905 if ( newStep < data._stepSize )
1907 data._stepSize = newStep;
1908 data._stepSizeCoeff = 0.8 / maxCosinEdge->_lenFactor;
1909 data._stepSizeNodes[0] = face->GetNode( iN );
1910 data._stepSizeNodes[1] = face->GetNode( SMESH_MesherHelper::WrapIndex( iN+1, nbNodes ));
1914 //================================================================================
1916 * \brief Compute inflation step size by min size of element on a convex surface
1918 //================================================================================
1920 void _ViscousBuilder::limitStepSize( _SolidData& data, const double minSize )
1922 if ( minSize < data._stepSize )
1924 data._stepSize = minSize;
1925 if ( data._stepSizeNodes[0] )
1928 SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
1929 data._stepSizeCoeff = data._stepSize / dist;
1934 //================================================================================
1936 * \brief Limit data._stepSize by evaluating curvature of shapes and fill data._convexFaces
1938 //================================================================================
1940 void _ViscousBuilder::limitStepSizeByCurvature( _SolidData& data )
1942 const int nbTestPnt = 5; // on a FACE sub-shape
1943 const double minCurvature = 0.9 / data._hyp->GetTotalThickness();
1945 BRepLProp_SLProps surfProp( 2, 1e-6 );
1946 SMESH_MesherHelper helper( *_mesh );
1948 data._convexFaces.clear();
1950 TopExp_Explorer face( data._solid, TopAbs_FACE );
1951 for ( ; face.More(); face.Next() )
1953 const TopoDS_Face& F = TopoDS::Face( face.Current() );
1954 SMESH_subMesh * sm = _mesh->GetSubMesh( F );
1955 const TGeomID faceID = sm->GetId();
1956 if ( data._ignoreFaceIds.count( faceID )) continue;
1958 BRepAdaptor_Surface surface( F, false );
1959 surfProp.SetSurface( surface );
1961 bool isTooCurved = false;
1964 _ConvexFace cnvFace;
1965 const double oriFactor = ( F.Orientation() == TopAbs_REVERSED ? +1. : -1. );
1966 SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/true);
1967 while ( smIt->more() )
1970 const TGeomID subID = sm->GetId();
1971 // find _LayerEdge's of a sub-shape
1973 if ( data.GetShapeEdges( subID, edgesEnd, &iBeg, &iEnd ))
1974 cnvFace._subIdToEdgeEnd.insert( make_pair( subID, edgesEnd ));
1977 // check concavity and curvature and limit data._stepSize
1978 int nbLEdges = iEnd - iBeg;
1979 int iStep = Max( 1, nbLEdges / nbTestPnt );
1980 for ( ; iBeg < iEnd; iBeg += iStep )
1982 gp_XY uv = helper.GetNodeUV( F, data._edges[ iBeg ]->_nodes[0] );
1983 surfProp.SetParameters( uv.X(), uv.Y() );
1984 if ( !surfProp.IsCurvatureDefined() )
1986 if ( surfProp.MaxCurvature() * oriFactor > minCurvature )
1988 limitStepSize( data, 0.9 / surfProp.MaxCurvature() * oriFactor );
1991 if ( surfProp.MinCurvature() * oriFactor > minCurvature )
1993 limitStepSize( data, 0.9 / surfProp.MinCurvature() * oriFactor );
1997 } // loop on sub-shapes of the FACE
1999 if ( !isTooCurved ) continue;
2001 _ConvexFace & convFace =
2002 data._convexFaces.insert( make_pair( faceID, cnvFace )).first->second;
2005 convFace._normalsFixed = false;
2007 // Fill _ConvexFace::_simplexTestEdges. These _LayerEdge's are used to detect
2008 // prism distortion.
2009 map< TGeomID, int >::iterator id2end = convFace._subIdToEdgeEnd.find( faceID );
2010 if ( id2end != convFace._subIdToEdgeEnd.end() )
2012 // there are _LayerEdge's on the FACE it-self;
2013 // select _LayerEdge's near EDGEs
2014 data.GetEdgesOnShape( id2end->second, iBeg, iEnd );
2015 for ( ; iBeg < iEnd; ++iBeg )
2017 _LayerEdge* ledge = data._edges[ iBeg ];
2018 for ( size_t j = 0; j < ledge->_simplices.size(); ++j )
2019 if ( ledge->_simplices[j]._nNext->GetPosition()->GetDim() < 2 )
2021 convFace._simplexTestEdges.push_back( ledge );
2028 // where there are no _LayerEdge's on a _ConvexFace,
2029 // as e.g. on a fillet surface with no internal nodes - issue 22580,
2030 // so that collision of viscous internal faces is not detected by check of
2031 // intersection of _LayerEdge's with the viscous internal faces.
2033 set< const SMDS_MeshNode* > usedNodes;
2035 // look for _LayerEdge's with null _sWOL
2036 map< TGeomID, int >::iterator id2end = convFace._subIdToEdgeEnd.begin();
2037 for ( ; id2end != convFace._subIdToEdgeEnd.end(); ++id2end )
2039 data.GetEdgesOnShape( id2end->second, iBeg, iEnd );
2040 if ( iBeg >= iEnd || !data._edges[ iBeg ]->_sWOL.IsNull() )
2042 for ( ; iBeg < iEnd; ++iBeg )
2044 _LayerEdge* ledge = data._edges[ iBeg ];
2045 const SMDS_MeshNode* srcNode = ledge->_nodes[0];
2046 if ( !usedNodes.insert( srcNode ).second ) continue;
2048 getSimplices( srcNode, ledge->_simplices, data._ignoreFaceIds, &data );
2049 for ( size_t i = 0; i < ledge->_simplices.size(); ++i )
2051 usedNodes.insert( ledge->_simplices[i]._nPrev );
2052 usedNodes.insert( ledge->_simplices[i]._nNext );
2054 convFace._simplexTestEdges.push_back( ledge );
2058 } // loop on FACEs of data._solid
2061 //================================================================================
2063 * \brief Separate shapes (and _LayerEdge's on them) to smooth from the rest ones
2065 //================================================================================
2067 bool _ViscousBuilder::sortEdges( _SolidData& data,
2068 vector< vector<_LayerEdge*> >& edgesByGeom)
2070 // define allowed thickness
2071 computeGeomSize( data ); // compute data._geomSize
2072 const double tgtThick = Min( 0.5 * data._geomSize, data._hyp->GetTotalThickness() );
2074 // Find shapes needing smoothing; such a shape has _LayerEdge._normal on it's
2075 // boundry inclined to the shape at a sharp angle
2077 list< TGeomID > shapesToSmooth;
2079 SMESH_MesherHelper helper( *_mesh );
2082 for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS )
2084 vector<_LayerEdge*>& eS = edgesByGeom[iS];
2085 if ( eS.empty() ) continue;
2086 const TopoDS_Shape& S = getMeshDS()->IndexToShape( iS );
2087 bool needSmooth = false;
2088 switch ( S.ShapeType() )
2092 if ( SMESH_Algo::isDegenerated( TopoDS::Edge( S )))
2094 //bool isShrinkEdge = !eS[0]->_sWOL.IsNull();
2095 for ( TopoDS_Iterator vIt( S ); vIt.More() && !needSmooth; vIt.Next() )
2097 TGeomID iV = getMeshDS()->ShapeToIndex( vIt.Value() );
2098 vector<_LayerEdge*>& eV = edgesByGeom[ iV ];
2099 if ( eV.empty() ) continue;
2100 gp_Vec eDir = getEdgeDir( TopoDS::Edge( S ), TopoDS::Vertex( vIt.Value() ));
2101 double angle = eDir.Angle( eV[0]->_normal );
2102 double cosin = Cos( angle );
2103 if ( cosin > theMinSmoothCosin )
2105 // compare tgtThick with the length of an end segment
2106 SMDS_ElemIteratorPtr eIt = eV[0]->_nodes[0]->GetInverseElementIterator(SMDSAbs_Edge);
2107 while ( eIt->more() )
2109 const SMDS_MeshElement* endSeg = eIt->next();
2110 if ( endSeg->getshapeId() == iS )
2113 SMESH_TNodeXYZ( endSeg->GetNode(0) ).Distance( endSeg->GetNode(1 ));
2114 needSmooth = needSmoothing( cosin, tgtThick, segLen );
2124 for ( TopExp_Explorer eExp( S, TopAbs_EDGE ); eExp.More() && !needSmooth; eExp.Next() )
2126 TGeomID iE = getMeshDS()->ShapeToIndex( eExp.Current() );
2127 vector<_LayerEdge*>& eE = edgesByGeom[ iE ];
2128 if ( eE.empty() ) continue;
2129 // TopLoc_Location loc;
2130 // Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face( S ), loc );
2131 // bool isPlane = GeomLib_IsPlanarSurface( surface ).IsPlanar();
2132 //if ( eE[0]->_sWOL.IsNull() )
2135 for ( size_t i = 0; i < eE.size() && !needSmooth; ++i )
2136 if ( eE[i]->_cosin > theMinSmoothCosin )
2138 SMDS_ElemIteratorPtr fIt = eE[i]->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
2139 while ( fIt->more() && !needSmooth )
2141 const SMDS_MeshElement* face = fIt->next();
2142 if ( getDistFromEdge( face, eE[i]->_nodes[0], faceSize ))
2143 needSmooth = needSmoothing( eE[i]->_cosin, tgtThick, faceSize );
2149 // const TopoDS_Face& F1 = TopoDS::Face( S );
2150 // const TopoDS_Face& F2 = TopoDS::Face( eE[0]->_sWOL );
2151 // const TopoDS_Edge& E = TopoDS::Edge( eExp.Current() );
2152 // for ( size_t i = 0; i < eE.size() && !needSmooth; ++i )
2154 // gp_Vec dir1 = getFaceDir( F1, E, eE[i]->_nodes[0], helper, ok );
2155 // gp_Vec dir2 = getFaceDir( F2, E, eE[i]->_nodes[0], helper, ok );
2156 // double angle = dir1.Angle( );
2157 // double cosin = cos( angle );
2158 // needSmooth = ( cosin > theMinSmoothCosin );
2171 if ( S.ShapeType() == TopAbs_EDGE ) shapesToSmooth.push_front( iS );
2172 else shapesToSmooth.push_back ( iS );
2175 } // loop on edgesByGeom
2177 data._edges.reserve( data._n2eMap.size() );
2178 data._endEdgeOnShape.clear();
2180 // first we put _LayerEdge's on shapes to smooth
2181 data._nbShapesToSmooth = 0;
2182 list< TGeomID >::iterator gIt = shapesToSmooth.begin();
2183 for ( ; gIt != shapesToSmooth.end(); ++gIt )
2185 vector<_LayerEdge*>& eVec = edgesByGeom[ *gIt ];
2186 if ( eVec.empty() ) continue;
2187 data._edges.insert( data._edges.end(), eVec.begin(), eVec.end() );
2188 data._endEdgeOnShape.push_back( data._edges.size() );
2189 data._nbShapesToSmooth++;
2193 // then the rest _LayerEdge's
2194 for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS )
2196 vector<_LayerEdge*>& eVec = edgesByGeom[iS];
2197 if ( eVec.empty() ) continue;
2198 data._edges.insert( data._edges.end(), eVec.begin(), eVec.end() );
2199 data._endEdgeOnShape.push_back( data._edges.size() );
2206 //================================================================================
2208 * \brief Set data of _LayerEdge needed for smoothing
2209 * \param subIds - ids of sub-shapes of a SOLID to take into account faces from
2211 //================================================================================
2213 bool _ViscousBuilder::setEdgeData(_LayerEdge& edge,
2214 const set<TGeomID>& subIds,
2215 SMESH_MesherHelper& helper,
2218 SMESH_MeshEditor editor(_mesh);
2220 const SMDS_MeshNode* node = edge._nodes[0]; // source node
2221 SMDS_TypeOfPosition posType = node->GetPosition()->GetTypeOfPosition();
2225 edge._curvature = 0;
2227 // --------------------------
2228 // Compute _normal and _cosin
2229 // --------------------------
2232 edge._normal.SetCoord(0,0,0);
2234 int totalNbFaces = 0;
2238 const TGeomID shapeInd = node->getshapeId();
2239 map< TGeomID, TopoDS_Shape >::const_iterator s2s = data._shrinkShape2Shape.find( shapeInd );
2240 const bool onShrinkShape ( s2s != data._shrinkShape2Shape.end() );
2242 if ( onShrinkShape ) // one of faces the node is on has no layers
2244 TopoDS_Shape vertEdge = getMeshDS()->IndexToShape( s2s->first ); // vertex or edge
2245 if ( s2s->second.ShapeType() == TopAbs_EDGE )
2247 // inflate from VERTEX along EDGE
2248 edge._normal = getEdgeDir( TopoDS::Edge( s2s->second ), TopoDS::Vertex( vertEdge ));
2250 else if ( vertEdge.ShapeType() == TopAbs_VERTEX )
2252 // inflate from VERTEX along FACE
2253 edge._normal = getFaceDir( TopoDS::Face( s2s->second ), TopoDS::Vertex( vertEdge ),
2254 node, helper, normOK, &edge._cosin);
2258 // inflate from EDGE along FACE
2259 edge._normal = getFaceDir( TopoDS::Face( s2s->second ), TopoDS::Edge( vertEdge ),
2260 node, helper, normOK);
2263 else // layers are on all faces of SOLID the node is on
2265 // find indices of geom faces the node lies on
2266 set<TGeomID> faceIds;
2267 if ( posType == SMDS_TOP_FACE )
2269 faceIds.insert( node->getshapeId() );
2273 SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
2274 while ( fIt->more() )
2275 faceIds.insert( editor.FindShape(fIt->next()));
2278 set<TGeomID>::iterator id = faceIds.begin();
2280 std::pair< TGeomID, gp_XYZ > id2Norm[20];
2281 for ( ; id != faceIds.end(); ++id )
2283 const TopoDS_Shape& s = getMeshDS()->IndexToShape( *id );
2284 if ( s.IsNull() || s.ShapeType() != TopAbs_FACE || !subIds.count( *id ))
2286 F = TopoDS::Face( s );
2287 geomNorm = getFaceNormal( node, F, helper, normOK );
2288 if ( !normOK ) continue;
2290 if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
2292 id2Norm[ totalNbFaces ].first = *id;
2293 id2Norm[ totalNbFaces ].second = geomNorm.XYZ();
2295 edge._normal += geomNorm.XYZ();
2297 if ( totalNbFaces == 0 )
2298 return error(SMESH_Comment("Can't get normal to node ") << node->GetID(), data._index);
2300 if ( normOK && edge._normal.Modulus() < 1e-3 && totalNbFaces > 1 )
2302 // opposite normals, re-get normals at shifted positions (IPAL 52426)
2303 edge._normal.SetCoord( 0,0,0 );
2304 for ( int i = 0; i < totalNbFaces; ++i )
2306 const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( id2Norm[i].first ));
2307 geomNorm = getFaceNormal( node, F, helper, normOK, /*shiftInside=*/true );
2308 if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
2311 id2Norm[ i ].second = geomNorm.XYZ();
2312 edge._normal += id2Norm[ i ].second;
2316 if ( totalNbFaces < 3 )
2318 //edge._normal /= totalNbFaces;
2322 edge._normal = getWeigthedNormal( node, id2Norm, totalNbFaces );
2328 edge._cosin = 0; break;
2330 case SMDS_TOP_EDGE: {
2331 TopoDS_Edge E = TopoDS::Edge( helper.GetSubShapeByNode( node, getMeshDS()));
2332 gp_Vec inFaceDir = getFaceDir( F, E, node, helper, normOK );
2333 double angle = inFaceDir.Angle( edge._normal ); // [0,PI]
2334 edge._cosin = cos( angle );
2335 //cout << "Cosin on EDGE " << edge._cosin << " node " << node->GetID() << endl;
2338 case SMDS_TOP_VERTEX: {
2339 TopoDS_Vertex V = TopoDS::Vertex( helper.GetSubShapeByNode( node, getMeshDS()));
2340 gp_Vec inFaceDir = getFaceDir( F, V, node, helper, normOK );
2341 double angle = inFaceDir.Angle( edge._normal ); // [0,PI]
2342 edge._cosin = cos( angle );
2343 //cout << "Cosin on VERTEX " << edge._cosin << " node " << node->GetID() << endl;
2347 return error(SMESH_Comment("Invalid shape position of node ")<<node, data._index);
2349 } // case _sWOL.IsNull()
2351 double normSize = edge._normal.SquareModulus();
2352 if ( normSize < numeric_limits<double>::min() )
2353 return error(SMESH_Comment("Bad normal at node ")<< node->GetID(), data._index );
2355 edge._normal /= sqrt( normSize );
2357 // TODO: if ( !normOK ) then get normal by mesh faces
2359 // Set the rest data
2360 // --------------------
2361 if ( onShrinkShape )
2363 edge._sWOL = (*s2s).second;
2365 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edge._nodes.back() );
2366 if ( SMESHDS_SubMesh* sm = getMeshDS()->MeshElements( data._solid ))
2367 sm->RemoveNode( tgtNode , /*isNodeDeleted=*/false );
2369 // set initial position which is parameters on _sWOL in this case
2370 if ( edge._sWOL.ShapeType() == TopAbs_EDGE )
2372 double u = helper.GetNodeU( TopoDS::Edge( edge._sWOL ), node, 0, &normOK );
2373 edge._pos.push_back( gp_XYZ( u, 0, 0 ));
2374 if ( edge._nodes.size() > 1 )
2375 getMeshDS()->SetNodeOnEdge( tgtNode, TopoDS::Edge( edge._sWOL ), u );
2379 gp_XY uv = helper.GetNodeUV( TopoDS::Face( edge._sWOL ), node, 0, &normOK );
2380 edge._pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
2381 if ( edge._nodes.size() > 1 )
2382 getMeshDS()->SetNodeOnFace( tgtNode, TopoDS::Face( edge._sWOL ), uv.X(), uv.Y() );
2387 edge._pos.push_back( SMESH_TNodeXYZ( node ));
2389 if ( posType == SMDS_TOP_FACE )
2391 getSimplices( node, edge._simplices, data._ignoreFaceIds, &data );
2392 double avgNormProj = 0, avgLen = 0;
2393 for ( size_t i = 0; i < edge._simplices.size(); ++i )
2395 gp_XYZ vec = edge._pos.back() - SMESH_TNodeXYZ( edge._simplices[i]._nPrev );
2396 avgNormProj += edge._normal * vec;
2397 avgLen += vec.Modulus();
2399 avgNormProj /= edge._simplices.size();
2400 avgLen /= edge._simplices.size();
2401 edge._curvature = _Curvature::New( avgNormProj, avgLen );
2405 // Set neighbour nodes for a _LayerEdge based on EDGE
2407 if ( posType == SMDS_TOP_EDGE /*||
2408 ( onShrinkShape && posType == SMDS_TOP_VERTEX && fabs( edge._cosin ) < 1e-10 )*/)
2410 edge._2neibors = new _2NearEdges;
2411 // target node instead of source ones will be set later
2412 // if ( ! findNeiborsOnEdge( &edge,
2413 // edge._2neibors->_nodes[0],
2414 // edge._2neibors->_nodes[1],
2417 // edge.SetDataByNeighbors( edge._2neibors->_nodes[0],
2418 // edge._2neibors->_nodes[1],
2422 edge.SetCosin( edge._cosin ); // to update edge._lenFactor
2427 //================================================================================
2429 * \brief Return normal to a FACE at a node
2430 * \param [in] n - node
2431 * \param [in] face - FACE
2432 * \param [in] helper - helper
2433 * \param [out] isOK - true or false
2434 * \param [in] shiftInside - to find normal at a position shifted inside the face
2435 * \return gp_XYZ - normal
2437 //================================================================================
2439 gp_XYZ _ViscousBuilder::getFaceNormal(const SMDS_MeshNode* node,
2440 const TopoDS_Face& face,
2441 SMESH_MesherHelper& helper,
2448 // get a shifted position
2449 gp_Pnt p = SMESH_TNodeXYZ( node );
2450 gp_XYZ shift( 0,0,0 );
2451 TopoDS_Shape S = helper.GetSubShapeByNode( node, helper.GetMeshDS() );
2452 switch ( S.ShapeType() ) {
2455 shift = getFaceDir( face, TopoDS::Vertex( S ), node, helper, isOK );
2460 shift = getFaceDir( face, TopoDS::Edge( S ), node, helper, isOK );
2468 p.Translate( shift * 1e-5 );
2470 TopLoc_Location loc;
2471 GeomAPI_ProjectPointOnSurf& projector = helper.GetProjector( face, loc, 1e-7 );
2473 if ( !loc.IsIdentity() ) p.Transform( loc.Transformation().Inverted() );
2475 projector.Perform( p );
2476 if ( !projector.IsDone() || projector.NbPoints() < 1 )
2481 Quantity_Parameter U,V;
2482 projector.LowerDistanceParameters(U,V);
2487 uv = helper.GetNodeUV( face, node, 0, &isOK );
2493 Handle(Geom_Surface) surface = BRep_Tool::Surface( face );
2494 int pointKind = GeomLib::NormEstim( surface, uv, 1e-5, normal );
2495 enum { REGULAR = 0, QUASYSINGULAR, CONICAL, IMPOSSIBLE };
2497 if ( pointKind == IMPOSSIBLE &&
2498 node->GetPosition()->GetDim() == 2 ) // node inside the FACE
2500 // probably NormEstim() failed due to a too high tolerance
2501 pointKind = GeomLib::NormEstim( surface, uv, 1e-20, normal );
2502 isOK = ( pointKind < IMPOSSIBLE );
2504 if ( pointKind < IMPOSSIBLE )
2506 if ( pointKind != REGULAR &&
2508 node->GetPosition()->GetDim() < 2 ) // FACE boundary
2510 gp_XYZ normShift = getFaceNormal( node, face, helper, isOK, /*shiftInside=*/true );
2511 if ( normShift * normal.XYZ() < 0. )
2517 if ( !isOK ) // hard singularity, to call with shiftInside=true ?
2519 const TGeomID faceID = helper.GetMeshDS()->ShapeToIndex( face );
2521 SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
2522 while ( fIt->more() )
2524 const SMDS_MeshElement* f = fIt->next();
2525 if ( f->getshapeId() == faceID )
2527 isOK = SMESH_MeshAlgos::FaceNormal( f, (gp_XYZ&) normal.XYZ(), /*normalized=*/true );
2530 TopoDS_Face ff = face;
2531 ff.Orientation( TopAbs_FORWARD );
2532 if ( helper.IsReversedSubMesh( ff ))
2539 return normal.XYZ();
2542 //================================================================================
2544 * \brief Return a normal at a node weighted with angles taken by FACEs
2545 * \param [in] n - the node
2546 * \param [in] fId2Normal - FACE ids and normals
2547 * \param [in] nbFaces - nb of FACEs meeting at the node
2548 * \return gp_XYZ - computed normal
2550 //================================================================================
2552 gp_XYZ _ViscousBuilder::getWeigthedNormal( const SMDS_MeshNode* n,
2553 std::pair< TGeomID, gp_XYZ > fId2Normal[],
2556 gp_XYZ resNorm(0,0,0);
2557 TopoDS_Shape V = SMESH_MesherHelper::GetSubShapeByNode( n, getMeshDS() );
2558 if ( V.ShapeType() != TopAbs_VERTEX )
2560 for ( int i = 0; i < nbFaces; ++i )
2561 resNorm += fId2Normal[i].second / nbFaces ;
2566 for ( int i = 0; i < nbFaces; ++i )
2568 const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( fId2Normal[i].first ));
2570 // look for two EDGEs shared by F and other FACEs within fId2Normal
2573 PShapeIteratorPtr eIt = SMESH_MesherHelper::GetAncestors( V, *_mesh, TopAbs_EDGE );
2574 while ( const TopoDS_Shape* E = eIt->next() )
2576 if ( !SMESH_MesherHelper::IsSubShape( *E, F ))
2578 bool isSharedEdge = false;
2579 for ( int j = 0; j < nbFaces && !isSharedEdge; ++j )
2581 if ( i == j ) continue;
2582 const TopoDS_Shape& otherF = getMeshDS()->IndexToShape( fId2Normal[j].first );
2583 isSharedEdge = SMESH_MesherHelper::IsSubShape( *E, otherF );
2585 if ( !isSharedEdge )
2587 ee[ nbE ] = TopoDS::Edge( *E );
2588 ee[ nbE ].Orientation( SMESH_MesherHelper::GetSubShapeOri( F, *E ));
2593 // get an angle between the two EDGEs
2595 if ( nbE < 1 ) continue;
2602 if ( !V.IsSame( SMESH_MesherHelper::IthVertex( 0, ee[ 1 ] )))
2603 std::swap( ee[0], ee[1] );
2605 angles[i] = SMESH_MesherHelper::GetAngle( ee[0], ee[1], F, TopoDS::Vertex( V ));
2608 // compute a weighted normal
2609 double sumAngle = 0;
2610 for ( int i = 0; i < nbFaces; ++i )
2612 angles[i] = ( angles[i] > 2*M_PI ) ? 0 : M_PI - angles[i];
2613 sumAngle += angles[i];
2615 for ( int i = 0; i < nbFaces; ++i )
2616 resNorm += angles[i] / sumAngle * fId2Normal[i].second;
2621 //================================================================================
2623 * \brief Find 2 neigbor nodes of a node on EDGE
2625 //================================================================================
2627 bool _ViscousBuilder::findNeiborsOnEdge(const _LayerEdge* edge,
2628 const SMDS_MeshNode*& n1,
2629 const SMDS_MeshNode*& n2,
2632 const SMDS_MeshNode* node = edge->_nodes[0];
2633 const int shapeInd = node->getshapeId();
2634 SMESHDS_SubMesh* edgeSM = 0;
2635 if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_EDGE )
2637 edgeSM = getMeshDS()->MeshElements( shapeInd );
2638 if ( !edgeSM || edgeSM->NbElements() == 0 )
2639 return error(SMESH_Comment("Not meshed EDGE ") << shapeInd, data._index);
2643 SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator(SMDSAbs_Edge);
2644 while ( eIt->more() && !n2 )
2646 const SMDS_MeshElement* e = eIt->next();
2647 const SMDS_MeshNode* nNeibor = e->GetNode( 0 );
2648 if ( nNeibor == node ) nNeibor = e->GetNode( 1 );
2651 if (!edgeSM->Contains(e)) continue;
2655 TopoDS_Shape s = SMESH_MesherHelper::GetSubShapeByNode(nNeibor, getMeshDS() );
2656 if ( !SMESH_MesherHelper::IsSubShape( s, edge->_sWOL )) continue;
2658 ( iN++ ? n2 : n1 ) = nNeibor;
2661 return error(SMESH_Comment("Wrongly meshed EDGE ") << shapeInd, data._index);
2665 //================================================================================
2667 * \brief Set _curvature and _2neibors->_plnNorm by 2 neigbor nodes residing the same EDGE
2669 //================================================================================
2671 void _LayerEdge::SetDataByNeighbors( const SMDS_MeshNode* n1,
2672 const SMDS_MeshNode* n2,
2673 SMESH_MesherHelper& helper)
2675 if ( _nodes[0]->GetPosition()->GetTypeOfPosition() != SMDS_TOP_EDGE )
2678 gp_XYZ pos = SMESH_TNodeXYZ( _nodes[0] );
2679 gp_XYZ vec1 = pos - SMESH_TNodeXYZ( n1 );
2680 gp_XYZ vec2 = pos - SMESH_TNodeXYZ( n2 );
2684 double sumLen = vec1.Modulus() + vec2.Modulus();
2685 _2neibors->_wgt[0] = 1 - vec1.Modulus() / sumLen;
2686 _2neibors->_wgt[1] = 1 - vec2.Modulus() / sumLen;
2687 double avgNormProj = 0.5 * ( _normal * vec1 + _normal * vec2 );
2688 double avgLen = 0.5 * ( vec1.Modulus() + vec2.Modulus() );
2689 if ( _curvature ) delete _curvature;
2690 _curvature = _Curvature::New( avgNormProj, avgLen );
2691 // if ( _curvature )
2692 // debugMsg( _nodes[0]->GetID()
2693 // << " CURV r,k: " << _curvature->_r<<","<<_curvature->_k
2694 // << " proj = "<<avgNormProj<< " len = " << avgLen << "| lenDelta(0) = "
2695 // << _curvature->lenDelta(0) );
2699 if ( _sWOL.IsNull() )
2701 TopoDS_Shape S = helper.GetSubShapeByNode( _nodes[0], helper.GetMeshDS() );
2702 TopoDS_Edge E = TopoDS::Edge( S );
2703 // if ( SMESH_Algo::isDegenerated( E ))
2705 gp_XYZ dirE = getEdgeDir( E, _nodes[0], helper );
2706 gp_XYZ plnNorm = dirE ^ _normal;
2707 double proj0 = plnNorm * vec1;
2708 double proj1 = plnNorm * vec2;
2709 if ( fabs( proj0 ) > 1e-10 || fabs( proj1 ) > 1e-10 )
2711 if ( _2neibors->_plnNorm ) delete _2neibors->_plnNorm;
2712 _2neibors->_plnNorm = new gp_XYZ( plnNorm.Normalized() );
2717 //================================================================================
2719 * \brief Copy data from a _LayerEdge of other SOLID and based on the same node;
2720 * this and other _LayerEdge's are inflated along a FACE or an EDGE
2722 //================================================================================
2724 gp_XYZ _LayerEdge::Copy( _LayerEdge& other, SMESH_MesherHelper& helper )
2726 _nodes = other._nodes;
2727 _normal = other._normal;
2729 _lenFactor = other._lenFactor;
2730 _cosin = other._cosin;
2731 _sWOL = other._sWOL;
2732 _2neibors = other._2neibors;
2733 _curvature = 0; std::swap( _curvature, other._curvature );
2734 _2neibors = 0; std::swap( _2neibors, other._2neibors );
2736 gp_XYZ lastPos( 0,0,0 );
2737 if ( _sWOL.ShapeType() == TopAbs_EDGE )
2739 double u = helper.GetNodeU( TopoDS::Edge( _sWOL ), _nodes[0] );
2740 _pos.push_back( gp_XYZ( u, 0, 0));
2742 u = helper.GetNodeU( TopoDS::Edge( _sWOL ), _nodes.back() );
2747 gp_XY uv = helper.GetNodeUV( TopoDS::Face( _sWOL ), _nodes[0]);
2748 _pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
2750 uv = helper.GetNodeUV( TopoDS::Face( _sWOL ), _nodes.back() );
2751 lastPos.SetX( uv.X() );
2752 lastPos.SetY( uv.Y() );
2757 //================================================================================
2759 * \brief Set _cosin and _lenFactor
2761 //================================================================================
2763 void _LayerEdge::SetCosin( double cosin )
2766 cosin = Abs( _cosin );
2767 _lenFactor = ( /*0.1 < cosin &&*/ cosin < 1-1e-12 ) ? 1./sqrt(1-cosin*cosin) : 1.0;
2770 //================================================================================
2772 * \brief Fills a vector<_Simplex >
2774 //================================================================================
2776 void _ViscousBuilder::getSimplices( const SMDS_MeshNode* node,
2777 vector<_Simplex>& simplices,
2778 const set<TGeomID>& ingnoreShapes,
2779 const _SolidData* dataToCheckOri,
2783 SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
2784 while ( fIt->more() )
2786 const SMDS_MeshElement* f = fIt->next();
2787 const TGeomID shapeInd = f->getshapeId();
2788 if ( ingnoreShapes.count( shapeInd )) continue;
2789 const int nbNodes = f->NbCornerNodes();
2790 const int srcInd = f->GetNodeIndex( node );
2791 const SMDS_MeshNode* nPrev = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd-1, nbNodes ));
2792 const SMDS_MeshNode* nNext = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+1, nbNodes ));
2793 const SMDS_MeshNode* nOpp = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+2, nbNodes ));
2794 if ( dataToCheckOri && dataToCheckOri->_reversedFaceIds.count( shapeInd ))
2795 std::swap( nPrev, nNext );
2796 simplices.push_back( _Simplex( nPrev, nNext, nOpp ));
2801 vector<_Simplex> sortedSimplices( simplices.size() );
2802 sortedSimplices[0] = simplices[0];
2804 for ( size_t i = 1; i < simplices.size(); ++i )
2806 for ( size_t j = 1; j < simplices.size(); ++j )
2807 if ( sortedSimplices[i-1]._nNext == simplices[j]._nPrev )
2809 sortedSimplices[i] = simplices[j];
2814 if ( nbFound == simplices.size() - 1 )
2815 simplices.swap( sortedSimplices );
2819 //================================================================================
2821 * \brief DEBUG. Create groups contating temorary data of _LayerEdge's
2823 //================================================================================
2825 void _ViscousBuilder::makeGroupOfLE()
2828 for ( size_t i = 0 ; i < _sdVec.size(); ++i )
2830 if ( _sdVec[i]._edges.empty() ) continue;
2832 dumpFunction( SMESH_Comment("make_LayerEdge_") << i );
2833 for ( size_t j = 0 ; j < _sdVec[i]._edges.size(); ++j )
2835 _LayerEdge* le = _sdVec[i]._edges[j];
2836 for ( size_t iN = 1; iN < le->_nodes.size(); ++iN )
2837 dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<le->_nodes[iN-1]->GetID()
2838 << ", " << le->_nodes[iN]->GetID() <<"])");
2842 dumpFunction( SMESH_Comment("makeNormals") << i );
2843 for ( size_t j = 0 ; j < _sdVec[i]._edges.size(); ++j )
2845 _LayerEdge& edge = *_sdVec[i]._edges[j];
2846 SMESH_TNodeXYZ nXYZ( edge._nodes[0] );
2847 nXYZ += edge._normal * _sdVec[i]._stepSize;
2848 dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<edge._nodes[0]->GetID()
2849 << ", mesh.AddNode( " << nXYZ.X()<<","<< nXYZ.Y()<<","<< nXYZ.Z()<<")])");
2853 dumpFunction( SMESH_Comment("makeTmpFaces_") << i );
2854 TopExp_Explorer fExp( _sdVec[i]._solid, TopAbs_FACE );
2855 for ( ; fExp.More(); fExp.Next() )
2857 if (const SMESHDS_SubMesh* sm = _sdVec[i]._proxyMesh->GetProxySubMesh( fExp.Current()))
2859 SMDS_ElemIteratorPtr fIt = sm->GetElements();
2860 while ( fIt->more())
2862 const SMDS_MeshElement* e = fIt->next();
2863 SMESH_Comment cmd("mesh.AddFace([");
2864 for ( int j=0; j < e->NbCornerNodes(); ++j )
2865 cmd << e->GetNode(j)->GetID() << (j+1<e->NbCornerNodes() ? ",": "])");
2875 //================================================================================
2877 * \brief Find maximal _LayerEdge length (layer thickness) limited by geometry
2879 //================================================================================
2881 void _ViscousBuilder::computeGeomSize( _SolidData& data )
2883 data._geomSize = Precision::Infinite();
2884 double intersecDist;
2885 auto_ptr<SMESH_ElementSearcher> searcher
2886 ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(),
2887 data._proxyMesh->GetFaces( data._solid )) );
2889 TNode2Edge::iterator n2e = data._n2eMap.begin(), n2eEnd = data._n2eMap.end();
2890 for ( ; n2e != n2eEnd; ++n2e )
2892 _LayerEdge* edge = n2e->second;
2893 if ( edge->IsOnEdge() ) continue;
2894 edge->FindIntersection( *searcher, intersecDist, data._epsilon );
2895 if ( data._geomSize > intersecDist && intersecDist > 0 )
2896 data._geomSize = intersecDist;
2900 //================================================================================
2902 * \brief Increase length of _LayerEdge's to reach the required thickness of layers
2904 //================================================================================
2906 bool _ViscousBuilder::inflate(_SolidData& data)
2908 SMESH_MesherHelper helper( *_mesh );
2910 // Limit inflation step size by geometry size found by itersecting
2911 // normals of _LayerEdge's with mesh faces
2912 if ( data._stepSize > 0.3 * data._geomSize )
2913 limitStepSize( data, 0.3 * data._geomSize );
2915 const double tgtThick = data._hyp->GetTotalThickness();
2916 if ( data._stepSize > tgtThick )
2917 limitStepSize( data, tgtThick );
2919 if ( data._stepSize < 1. )
2920 data._epsilon = data._stepSize * 1e-7;
2922 debugMsg( "-- geomSize = " << data._geomSize << ", stepSize = " << data._stepSize );
2924 double avgThick = 0, curThick = 0, distToIntersection = Precision::Infinite();
2925 int nbSteps = 0, nbRepeats = 0;
2926 while ( 1.01 * avgThick < tgtThick )
2928 // new target length
2929 curThick += data._stepSize;
2930 if ( curThick > tgtThick )
2932 curThick = tgtThick + ( tgtThick-avgThick ) * nbRepeats;
2936 // Elongate _LayerEdge's
2937 dumpFunction(SMESH_Comment("inflate")<<data._index<<"_step"<<nbSteps); // debug
2938 for ( size_t i = 0; i < data._edges.size(); ++i )
2940 data._edges[i]->SetNewLength( curThick, helper );
2944 if ( !updateNormals( data, helper, nbSteps ))
2947 // Improve and check quality
2948 if ( !smoothAndCheck( data, nbSteps, distToIntersection ))
2952 dumpFunction(SMESH_Comment("invalidate")<<data._index<<"_step"<<nbSteps); // debug
2953 for ( size_t i = 0; i < data._edges.size(); ++i )
2955 data._edges[i]->InvalidateStep( nbSteps+1 );
2959 break; // no more inflating possible
2963 // Evaluate achieved thickness
2965 for ( size_t i = 0; i < data._edges.size(); ++i )
2966 avgThick += data._edges[i]->_len;
2967 avgThick /= data._edges.size();
2968 debugMsg( "-- Thickness " << avgThick << " reached" );
2970 if ( distToIntersection < avgThick*1.5 )
2972 debugMsg( "-- Stop inflation since "
2973 << " distToIntersection( "<<distToIntersection<<" ) < avgThick( "
2974 << avgThick << " ) * 1.5" );
2978 limitStepSize( data, 0.25 * distToIntersection );
2979 if ( data._stepSizeNodes[0] )
2980 data._stepSize = data._stepSizeCoeff *
2981 SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
2983 } // while ( 1.01 * avgThick < tgtThick )
2986 return error("failed at the very first inflation step", data._index);
2988 if ( 1.01 * avgThick < tgtThick )
2989 if ( SMESH_subMesh* sm = _mesh->GetSubMeshContaining( data._index ))
2991 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
2992 if ( !smError || smError->IsOK() )
2994 ( new SMESH_ComputeError (COMPERR_WARNING,
2995 SMESH_Comment("Thickness ") << tgtThick <<
2996 " of viscous layers not reached,"
2997 " average reached thickness is " << avgThick ));
3001 // Restore position of src nodes moved by infaltion on _noShrinkShapes
3002 dumpFunction(SMESH_Comment("restoNoShrink_So")<<data._index); // debug
3004 for ( int iS = 0; iS < data._endEdgeOnShape.size(); ++iS )
3007 iEnd = data._endEdgeOnShape[ iS ];
3008 if ( data._edges[ iBeg ]->_nodes.size() == 1 )
3009 for ( ; iBeg < iEnd; ++iBeg )
3011 restoreNoShrink( *data._edges[ iBeg ] );
3019 //================================================================================
3021 * \brief Improve quality of layer inner surface and check intersection
3023 //================================================================================
3025 bool _ViscousBuilder::smoothAndCheck(_SolidData& data,
3027 double & distToIntersection)
3029 if ( data._nbShapesToSmooth == 0 )
3030 return true; // no shapes needing smoothing
3032 bool moved, improved;
3034 SMESH_MesherHelper helper(*_mesh);
3035 Handle(Geom_Surface) surface;
3039 for ( int iS = 0; iS < data._nbShapesToSmooth; ++iS )
3042 iEnd = data._endEdgeOnShape[ iS ];
3044 if ( !data._edges[ iBeg ]->_sWOL.IsNull() &&
3045 data._edges[ iBeg ]->_sWOL.ShapeType() == TopAbs_FACE )
3047 if ( !F.IsSame( data._edges[ iBeg ]->_sWOL )) {
3048 F = TopoDS::Face( data._edges[ iBeg ]->_sWOL );
3049 helper.SetSubShape( F );
3050 surface = BRep_Tool::Surface( F );
3055 F.Nullify(); surface.Nullify();
3057 TGeomID sInd = data._edges[ iBeg ]->_nodes[0]->getshapeId();
3059 if ( data._edges[ iBeg ]->IsOnEdge() )
3061 dumpFunction(SMESH_Comment("smooth")<<data._index << "_Ed"<<sInd <<"_InfStep"<<nbSteps);
3063 // try a simple solution on an analytic EDGE
3064 if ( !smoothAnalyticEdge( data, iBeg, iEnd, surface, F, helper ))
3070 for ( int i = iBeg; i < iEnd; ++i )
3072 moved |= data._edges[i]->SmoothOnEdge(surface, F, helper);
3074 dumpCmd( SMESH_Comment("# end step ")<<step);
3076 while ( moved && step++ < 5 );
3083 int step = 0, stepLimit = 5, badNb = 0; moved = true;
3084 while (( ++step <= stepLimit && moved ) || improved )
3086 dumpFunction(SMESH_Comment("smooth")<<data._index<<"_Fa"<<sInd
3087 <<"_InfStep"<<nbSteps<<"_"<<step); // debug
3088 int oldBadNb = badNb;
3092 for ( int i = iBeg; i < iEnd; ++i )
3093 moved |= data._edges[i]->Smooth(badNb);
3095 for ( int i = iEnd-1; i >= iBeg; --i )
3096 moved |= data._edges[i]->Smooth(badNb);
3097 improved = ( badNb < oldBadNb );
3099 // issue 22576 -- no bad faces but still there are intersections to fix
3100 if ( improved && badNb == 0 )
3101 stepLimit = step + 3;
3108 for ( int i = iBeg; i < iEnd; ++i )
3110 _LayerEdge* edge = data._edges[i];
3111 SMESH_TNodeXYZ tgtXYZ( edge->_nodes.back() );
3112 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
3113 if ( !edge->_simplices[j].IsForward( edge->_nodes[0], &tgtXYZ ))
3115 cout << "Bad simplex ( " << edge->_nodes[0]->GetID()<< " "<< tgtXYZ._node->GetID()
3116 << " "<< edge->_simplices[j]._nPrev->GetID()
3117 << " "<< edge->_simplices[j]._nNext->GetID() << " )" << endl;
3125 } // loop on shapes to smooth
3127 // Check orientation of simplices of _ConvexFace::_simplexTestEdges
3128 map< TGeomID, _ConvexFace >::iterator id2face = data._convexFaces.begin();
3129 for ( ; id2face != data._convexFaces.end(); ++id2face )
3131 _ConvexFace & convFace = (*id2face).second;
3132 if ( !convFace._simplexTestEdges.empty() &&
3133 convFace._simplexTestEdges[0]->_nodes[0]->GetPosition()->GetDim() == 2 )
3134 continue; // _simplexTestEdges are based on FACE -- already checked while smoothing
3136 if ( !convFace.CheckPrisms() )
3140 // Check if the last segments of _LayerEdge intersects 2D elements;
3141 // checked elements are either temporary faces or faces on surfaces w/o the layers
3143 auto_ptr<SMESH_ElementSearcher> searcher
3144 ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(),
3145 data._proxyMesh->GetFaces( data._solid )) );
3147 distToIntersection = Precision::Infinite();
3149 const SMDS_MeshElement* intFace = 0;
3150 const SMDS_MeshElement* closestFace = 0;
3152 for ( size_t i = 0; i < data._edges.size(); ++i )
3154 if ( !data._edges[i]->_sWOL.IsNull() )
3156 if ( data._edges[i]->FindIntersection( *searcher, dist, data._epsilon, &intFace ))
3158 if ( distToIntersection > dist )
3160 // ignore intersection of a _LayerEdge based on a _ConvexFace with a face
3161 // lying on this _ConvexFace
3162 if ( _ConvexFace* convFace = data.GetConvexFace( intFace->getshapeId() ))
3163 if ( convFace->_subIdToEdgeEnd.count ( data._edges[i]->_nodes[0]->getshapeId() ))
3166 distToIntersection = dist;
3168 closestFace = intFace;
3174 SMDS_MeshElement::iterator nIt = closestFace->begin_nodes();
3175 cout << "Shortest distance: _LayerEdge nodes: tgt " << data._edges[iLE]->_nodes.back()->GetID()
3176 << " src " << data._edges[iLE]->_nodes[0]->GetID()<< ", intersection with face ("
3177 << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
3178 << ") distance = " << distToIntersection<< endl;
3185 //================================================================================
3187 * \brief Return a curve of the EDGE to be used for smoothing and arrange
3188 * _LayerEdge's to be in a consequent order
3190 //================================================================================
3192 Handle(Geom_Curve) _SolidData::CurveForSmooth( const TopoDS_Edge& E,
3195 Handle(Geom_Surface)& surface,
3196 const TopoDS_Face& F,
3197 SMESH_MesherHelper& helper)
3199 TGeomID eIndex = helper.GetMeshDS()->ShapeToIndex( E );
3201 map< TGeomID, Handle(Geom_Curve)>::iterator i2curve = _edge2curve.find( eIndex );
3203 if ( i2curve == _edge2curve.end() )
3205 // sort _LayerEdge's by position on the EDGE
3206 SortOnEdge( E, iFrom, iTo, helper );
3208 SMESHDS_SubMesh* smDS = helper.GetMeshDS()->MeshElements( eIndex );
3210 TopLoc_Location loc; double f,l;
3212 Handle(Geom_Line) line;
3213 Handle(Geom_Circle) circle;
3214 bool isLine, isCirc;
3215 if ( F.IsNull() ) // 3D case
3217 // check if the EDGE is a line
3218 Handle(Geom_Curve) curve = BRep_Tool::Curve( E, loc, f, l);
3219 if ( curve->IsKind( STANDARD_TYPE( Geom_TrimmedCurve )))
3220 curve = Handle(Geom_TrimmedCurve)::DownCast( curve )->BasisCurve();
3222 line = Handle(Geom_Line)::DownCast( curve );
3223 circle = Handle(Geom_Circle)::DownCast( curve );
3224 isLine = (!line.IsNull());
3225 isCirc = (!circle.IsNull());
3227 if ( !isLine && !isCirc ) // Check if the EDGE is close to a line
3230 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
3231 while ( nIt->more() )
3232 bndBox.Add( SMESH_TNodeXYZ( nIt->next() ));
3233 gp_XYZ size = bndBox.CornerMax() - bndBox.CornerMin();
3235 SMESH_TNodeXYZ p0( _edges[iFrom]->_2neibors->tgtNode(0) );
3236 SMESH_TNodeXYZ p1( _edges[iFrom]->_2neibors->tgtNode(1) );
3237 const double lineTol = 1e-2 * ( p0 - p1 ).Modulus();
3238 for ( int i = 0; i < 3 && !isLine; ++i )
3239 isLine = ( size.Coord( i+1 ) <= lineTol );
3241 if ( !isLine && !isCirc && iTo-iFrom > 2) // Check if the EDGE is close to a circle
3248 // check if the EDGE is a line
3249 Handle(Geom2d_Curve) curve = BRep_Tool::CurveOnSurface( E, F, f, l);
3250 if ( curve->IsKind( STANDARD_TYPE( Geom2d_TrimmedCurve )))
3251 curve = Handle(Geom2d_TrimmedCurve)::DownCast( curve )->BasisCurve();
3253 Handle(Geom2d_Line) line2d = Handle(Geom2d_Line)::DownCast( curve );
3254 Handle(Geom2d_Circle) circle2d = Handle(Geom2d_Circle)::DownCast( curve );
3255 isLine = (!line2d.IsNull());
3256 isCirc = (!circle2d.IsNull());
3258 if ( !isLine && !isCirc) // Check if the EDGE is close to a line
3261 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
3262 while ( nIt->more() )
3263 bndBox.Add( helper.GetNodeUV( F, nIt->next() ));
3264 gp_XY size = bndBox.CornerMax() - bndBox.CornerMin();
3266 const double lineTol = 1e-2 * sqrt( bndBox.SquareExtent() );
3267 for ( int i = 0; i < 2 && !isLine; ++i )
3268 isLine = ( size.Coord( i+1 ) <= lineTol );
3270 if ( !isLine && !isCirc && iTo-iFrom > 2) // Check if the EDGE is close to a circle
3276 line = new Geom_Line( gp::OX() ); // only type does matter
3280 gp_Pnt2d p = circle2d->Location();
3281 gp_Ax2 ax( gp_Pnt( p.X(), p.Y(), 0), gp::DX());
3282 circle = new Geom_Circle( ax, 1.); // only center position does matter
3286 Handle(Geom_Curve)& res = _edge2curve[ eIndex ];
3294 return i2curve->second;
3297 //================================================================================
3299 * \brief Sort _LayerEdge's by a parameter on a given EDGE
3301 //================================================================================
3303 void _SolidData::SortOnEdge( const TopoDS_Edge& E,
3306 SMESH_MesherHelper& helper)
3308 map< double, _LayerEdge* > u2edge;
3309 for ( int i = iFrom; i < iTo; ++i )
3310 u2edge.insert( make_pair( helper.GetNodeU( E, _edges[i]->_nodes[0] ), _edges[i] ));
3312 ASSERT( u2edge.size() == iTo - iFrom );
3313 map< double, _LayerEdge* >::iterator u2e = u2edge.begin();
3314 for ( int i = iFrom; i < iTo; ++i, ++u2e )
3315 _edges[i] = u2e->second;
3317 // set _2neibors according to the new order
3318 for ( int i = iFrom; i < iTo-1; ++i )
3319 if ( _edges[i]->_2neibors->tgtNode(1) != _edges[i+1]->_nodes.back() )
3320 _edges[i]->_2neibors->reverse();
3321 if ( u2edge.size() > 1 &&
3322 _edges[iTo-1]->_2neibors->tgtNode(0) != _edges[iTo-2]->_nodes.back() )
3323 _edges[iTo-1]->_2neibors->reverse();
3326 //================================================================================
3328 * \brief Return index corresponding to the shape in _endEdgeOnShape
3330 //================================================================================
3332 bool _SolidData::GetShapeEdges(const TGeomID shapeID,
3337 int beg = 0, end = 0;
3338 for ( edgesEnd = 0; edgesEnd < _endEdgeOnShape.size(); ++edgesEnd )
3340 end = _endEdgeOnShape[ edgesEnd ];
3341 TGeomID sID = _edges[ beg ]->_nodes[0]->getshapeId();
3342 if ( sID == shapeID )
3344 if ( iBeg ) *iBeg = beg;
3345 if ( iEnd ) *iEnd = end;
3353 //================================================================================
3355 * \brief Add faces for smoothing
3357 //================================================================================
3359 void _SolidData::AddShapesToSmooth( const set< TGeomID >& faceIDs )
3361 // convert faceIDs to indices in _endEdgeOnShape
3362 set< size_t > iEnds;
3364 set< TGeomID >::const_iterator fId = faceIDs.begin();
3365 for ( ; fId != faceIDs.end(); ++fId )
3366 if ( GetShapeEdges( *fId, end ) && end >= _nbShapesToSmooth )
3367 iEnds.insert( end );
3369 set< size_t >::iterator endsIt = iEnds.begin();
3371 // "add" by move of _nbShapesToSmooth
3372 int nbFacesToAdd = iEnds.size();
3373 while ( endsIt != iEnds.end() && *endsIt == _nbShapesToSmooth )
3376 ++_nbShapesToSmooth;
3379 if ( endsIt == iEnds.end() )
3382 // Move _LayerEdge's on FACEs just after _nbShapesToSmooth
3384 vector< _LayerEdge* > nonSmoothLE, smoothLE;
3385 size_t lastSmooth = *iEnds.rbegin();
3387 for ( size_t i = _nbShapesToSmooth; i <= lastSmooth; ++i )
3389 vector< _LayerEdge* > & edgesVec = iEnds.count(i) ? smoothLE : nonSmoothLE;
3390 iBeg = i ? _endEdgeOnShape[ i-1 ] : 0;
3391 iEnd = _endEdgeOnShape[ i ];
3392 edgesVec.insert( edgesVec.end(), _edges.begin() + iBeg, _edges.begin() + iEnd );
3395 iBeg = _nbShapesToSmooth ? _endEdgeOnShape[ _nbShapesToSmooth-1 ] : 0;
3396 std::copy( smoothLE.begin(), smoothLE.end(), &_edges[ iBeg ] );
3397 std::copy( nonSmoothLE.begin(), nonSmoothLE.end(), &_edges[ iBeg + smoothLE.size()]);
3399 // update _endEdgeOnShape
3400 for ( size_t i = _nbShapesToSmooth; i < _endEdgeOnShape.size(); ++i )
3402 TGeomID curShape = _edges[ iBeg ]->_nodes[0]->getshapeId();
3403 while ( ++iBeg < _edges.size() &&
3404 curShape == _edges[ iBeg ]->_nodes[0]->getshapeId() );
3406 _endEdgeOnShape[ i ] = iBeg;
3409 _nbShapesToSmooth += nbFacesToAdd;
3412 //================================================================================
3414 * \brief smooth _LayerEdge's on a staight EDGE or circular EDGE
3416 //================================================================================
3418 bool _ViscousBuilder::smoothAnalyticEdge( _SolidData& data,
3421 Handle(Geom_Surface)& surface,
3422 const TopoDS_Face& F,
3423 SMESH_MesherHelper& helper)
3425 TopoDS_Shape S = helper.GetSubShapeByNode( data._edges[ iFrom ]->_nodes[0],
3426 helper.GetMeshDS());
3427 TopoDS_Edge E = TopoDS::Edge( S );
3429 Handle(Geom_Curve) curve = data.CurveForSmooth( E, iFrom, iTo, surface, F, helper );
3430 if ( curve.IsNull() ) return false;
3432 // compute a relative length of segments
3433 vector< double > len( iTo-iFrom+1 );
3435 double curLen, prevLen = len[0] = 1.0;
3436 for ( int i = iFrom; i < iTo; ++i )
3438 curLen = prevLen * data._edges[i]->_2neibors->_wgt[0] / data._edges[i]->_2neibors->_wgt[1];
3439 len[i-iFrom+1] = len[i-iFrom] + curLen;
3444 if ( curve->IsKind( STANDARD_TYPE( Geom_Line )))
3446 if ( F.IsNull() ) // 3D
3448 SMESH_TNodeXYZ p0( data._edges[iFrom]->_2neibors->tgtNode(0));
3449 SMESH_TNodeXYZ p1( data._edges[iTo-1]->_2neibors->tgtNode(1));
3450 for ( int i = iFrom; i < iTo; ++i )
3452 double r = len[i-iFrom] / len.back();
3453 gp_XYZ newPos = p0 * ( 1. - r ) + p1 * r;
3454 data._edges[i]->_pos.back() = newPos;
3455 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( data._edges[i]->_nodes.back() );
3456 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
3457 dumpMove( tgtNode );
3462 // gp_XY uv0 = helper.GetNodeUV( F, data._edges[iFrom]->_2neibors->tgtNode(0));
3463 // gp_XY uv1 = helper.GetNodeUV( F, data._edges[iTo-1]->_2neibors->tgtNode(1));
3464 gp_XY uv0 = data._edges[iFrom]->_2neibors->_edges[0]->LastUV( F );
3465 gp_XY uv1 = data._edges[iTo-1]->_2neibors->_edges[1]->LastUV( F );
3466 if ( data._edges[iFrom]->_2neibors->tgtNode(0) ==
3467 data._edges[iTo-1]->_2neibors->tgtNode(1) ) // closed edge
3469 int iPeriodic = helper.GetPeriodicIndex();
3470 if ( iPeriodic == 1 || iPeriodic == 2 )
3472 uv1.SetCoord( iPeriodic, helper.GetOtherParam( uv1.Coord( iPeriodic )));
3473 if ( uv0.Coord( iPeriodic ) > uv1.Coord( iPeriodic ))
3474 std::swap( uv0, uv1 );
3477 const gp_XY rangeUV = uv1 - uv0;
3478 for ( int i = iFrom; i < iTo; ++i )
3480 double r = len[i-iFrom] / len.back();
3481 gp_XY newUV = uv0 + r * rangeUV;
3482 data._edges[i]->_pos.back().SetCoord( newUV.X(), newUV.Y(), 0 );
3484 gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
3485 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( data._edges[i]->_nodes.back() );
3486 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
3487 dumpMove( tgtNode );
3489 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
3490 pos->SetUParameter( newUV.X() );
3491 pos->SetVParameter( newUV.Y() );
3497 if ( curve->IsKind( STANDARD_TYPE( Geom_Circle )))
3499 Handle(Geom_Circle) circle = Handle(Geom_Circle)::DownCast( curve );
3500 gp_Pnt center3D = circle->Location();
3502 if ( F.IsNull() ) // 3D
3504 if ( data._edges[iFrom]->_2neibors->tgtNode(0) ==
3505 data._edges[iTo-1]->_2neibors->tgtNode(1) )
3506 return true; // closed EDGE - nothing to do
3508 return false; // TODO ???
3512 const gp_XY center( center3D.X(), center3D.Y() );
3514 gp_XY uv0 = data._edges[iFrom]->_2neibors->_edges[0]->LastUV( F );
3515 gp_XY uvM = data._edges[iFrom]->LastUV( F );
3516 gp_XY uv1 = data._edges[iTo-1]->_2neibors->_edges[1]->LastUV( F );
3517 // gp_XY uv0 = helper.GetNodeUV( F, data._edges[iFrom]->_2neibors->tgtNode(0));
3518 // gp_XY uvM = helper.GetNodeUV( F, data._edges[iFrom]->_nodes.back());
3519 // gp_XY uv1 = helper.GetNodeUV( F, data._edges[iTo-1]->_2neibors->tgtNode(1));
3520 gp_Vec2d vec0( center, uv0 );
3521 gp_Vec2d vecM( center, uvM );
3522 gp_Vec2d vec1( center, uv1 );
3523 double uLast = vec0.Angle( vec1 ); // -PI - +PI
3524 double uMidl = vec0.Angle( vecM );
3525 if ( uLast * uMidl <= 0. )
3526 uLast += ( uMidl > 0 ? +2. : -2. ) * M_PI;
3527 const double radius = 0.5 * ( vec0.Magnitude() + vec1.Magnitude() );
3529 gp_Ax2d axis( center, vec0 );
3530 gp_Circ2d circ( axis, radius );
3531 for ( int i = iFrom; i < iTo; ++i )
3533 double newU = uLast * len[i-iFrom] / len.back();
3534 gp_Pnt2d newUV = ElCLib::Value( newU, circ );
3535 data._edges[i]->_pos.back().SetCoord( newUV.X(), newUV.Y(), 0 );
3537 gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
3538 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( data._edges[i]->_nodes.back() );
3539 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
3540 dumpMove( tgtNode );
3542 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
3543 pos->SetUParameter( newUV.X() );
3544 pos->SetVParameter( newUV.Y() );
3553 //================================================================================
3555 * \brief Modify normals of _LayerEdge's on EDGE's to avoid intersection with
3556 * _LayerEdge's on neighbor EDGE's
3558 //================================================================================
3560 bool _ViscousBuilder::updateNormals( _SolidData& data,
3561 SMESH_MesherHelper& helper,
3565 return updateNormalsOfConvexFaces( data, helper, stepNb );
3567 // make temporary quadrangles got by extrusion of
3568 // mesh edges along _LayerEdge._normal's
3570 vector< const SMDS_MeshElement* > tmpFaces;
3572 set< SMESH_TLink > extrudedLinks; // contains target nodes
3573 vector< const SMDS_MeshNode*> nodes(4); // of a tmp mesh face
3575 dumpFunction(SMESH_Comment("makeTmpFacesOnEdges")<<data._index);
3576 for ( size_t i = 0; i < data._edges.size(); ++i )
3578 _LayerEdge* edge = data._edges[i];
3579 if ( !edge->IsOnEdge() || !edge->_sWOL.IsNull() ) continue;
3580 const SMDS_MeshNode* tgt1 = edge->_nodes.back();
3581 for ( int j = 0; j < 2; ++j ) // loop on _2NearEdges
3583 const SMDS_MeshNode* tgt2 = edge->_2neibors->tgtNode(j);
3584 pair< set< SMESH_TLink >::iterator, bool > link_isnew =
3585 extrudedLinks.insert( SMESH_TLink( tgt1, tgt2 ));
3586 if ( !link_isnew.second )
3588 extrudedLinks.erase( link_isnew.first );
3589 continue; // already extruded and will no more encounter
3591 // a _LayerEdge containg tgt2
3592 _LayerEdge* neiborEdge = edge->_2neibors->_edges[j];
3594 _TmpMeshFaceOnEdge* f = new _TmpMeshFaceOnEdge( edge, neiborEdge, --_tmpFaceID );
3595 tmpFaces.push_back( f );
3597 dumpCmd(SMESH_Comment("mesh.AddFace([ ")
3598 <<f->_nn[0]->GetID()<<", "<<f->_nn[1]->GetID()<<", "
3599 <<f->_nn[2]->GetID()<<", "<<f->_nn[3]->GetID()<<" ])");
3604 // Check if _LayerEdge's based on EDGE's intersects tmpFaces.
3605 // Perform two loops on _LayerEdge on EDGE's:
3606 // 1) to find and fix intersection
3607 // 2) to check that no new intersection appears as result of 1)
3609 SMDS_ElemIteratorPtr fIt( new SMDS_ElementVectorIterator( tmpFaces.begin(),
3611 auto_ptr<SMESH_ElementSearcher> searcher
3612 ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(), fIt ));
3614 // 1) Find intersections
3616 const SMDS_MeshElement* face;
3617 typedef map< _LayerEdge*, set< _LayerEdge*, _LayerEdgeCmp >, _LayerEdgeCmp > TLEdge2LEdgeSet;
3618 TLEdge2LEdgeSet edge2CloseEdge;
3620 const double eps = data._epsilon * data._epsilon;
3621 for ( size_t i = 0; i < data._edges.size(); ++i )
3623 _LayerEdge* edge = data._edges[i];
3624 if (( !edge->IsOnEdge() ) &&
3625 ( edge->_sWOL.IsNull() || edge->_sWOL.ShapeType() != TopAbs_FACE ))
3627 if ( edge->FindIntersection( *searcher, dist, eps, &face ))
3629 const _TmpMeshFaceOnEdge* f = (const _TmpMeshFaceOnEdge*) face;
3630 set< _LayerEdge*, _LayerEdgeCmp > & ee = edge2CloseEdge[ edge ];
3631 ee.insert( f->_le1 );
3632 ee.insert( f->_le2 );
3633 if ( f->_le1->IsOnEdge() && f->_le1->_sWOL.IsNull() )
3634 edge2CloseEdge[ f->_le1 ].insert( edge );
3635 if ( f->_le2->IsOnEdge() && f->_le2->_sWOL.IsNull() )
3636 edge2CloseEdge[ f->_le2 ].insert( edge );
3640 // Set _LayerEdge._normal
3642 if ( !edge2CloseEdge.empty() )
3644 dumpFunction(SMESH_Comment("updateNormals")<<data._index);
3646 set< TGeomID > shapesToSmooth;
3648 // vector to store new _normal and _cosin for each edge in edge2CloseEdge
3649 vector< pair< _LayerEdge*, _LayerEdge > > edge2newEdge( edge2CloseEdge.size() );
3651 TLEdge2LEdgeSet::iterator e2ee = edge2CloseEdge.begin();
3652 for ( size_t iE = 0; e2ee != edge2CloseEdge.end(); ++e2ee, ++iE )
3654 _LayerEdge* edge1 = e2ee->first;
3655 _LayerEdge* edge2 = 0;
3656 set< _LayerEdge*, _LayerEdgeCmp >& ee = e2ee->second;
3658 edge2newEdge[ iE ].first = NULL;
3660 // find EDGEs the edges reside
3661 // TopoDS_Edge E1, E2;
3662 // TopoDS_Shape S = helper.GetSubShapeByNode( edge1->_nodes[0], getMeshDS() );
3663 // if ( S.ShapeType() != TopAbs_EDGE )
3664 // continue; // TODO: find EDGE by VERTEX
3665 // E1 = TopoDS::Edge( S );
3666 set< _LayerEdge*, _LayerEdgeCmp >::iterator eIt = ee.begin();
3667 for ( ; !edge2 && eIt != ee.end(); ++eIt )
3669 if ( edge1->_sWOL == (*eIt)->_sWOL )
3672 if ( !edge2 ) continue;
3674 edge2newEdge[ iE ].first = edge1;
3675 _LayerEdge& newEdge = edge2newEdge[ iE ].second;
3676 // while ( E2.IsNull() && eIt != ee.end())
3678 // _LayerEdge* e2 = *eIt++;
3679 // TopoDS_Shape S = helper.GetSubShapeByNode( e2->_nodes[0], getMeshDS() );
3680 // if ( S.ShapeType() == TopAbs_EDGE )
3681 // E2 = TopoDS::Edge( S ), edge2 = e2;
3683 // if ( E2.IsNull() ) continue; // TODO: find EDGE by VERTEX
3685 // find 3 FACEs sharing 2 EDGEs
3687 // TopoDS_Face FF1[2], FF2[2];
3688 // PShapeIteratorPtr fIt = helper.GetAncestors(E1, *_mesh, TopAbs_FACE);
3689 // while ( fIt->more() && FF1[1].IsNull() )
3691 // const TopoDS_Face *F = (const TopoDS_Face*) fIt->next();
3692 // if ( helper.IsSubShape( *F, data._solid))
3693 // FF1[ FF1[0].IsNull() ? 0 : 1 ] = *F;
3695 // fIt = helper.GetAncestors(E2, *_mesh, TopAbs_FACE);
3696 // while ( fIt->more() && FF2[1].IsNull())
3698 // const TopoDS_Face *F = (const TopoDS_Face*) fIt->next();
3699 // if ( helper.IsSubShape( *F, data._solid))
3700 // FF2[ FF2[0].IsNull() ? 0 : 1 ] = *F;
3702 // // exclude a FACE common to E1 and E2 (put it to FFn[1] )
3703 // if ( FF1[0].IsSame( FF2[0]) || FF1[0].IsSame( FF2[1]))
3704 // std::swap( FF1[0], FF1[1] );
3705 // if ( FF2[0].IsSame( FF1[0]) )
3706 // std::swap( FF2[0], FF2[1] );
3707 // if ( FF1[0].IsNull() || FF2[0].IsNull() )
3710 // get a new normal for edge1
3712 gp_Vec dir1 = edge1->_normal, dir2 = edge2->_normal;
3713 // if ( edge1->_cosin < 0 )
3714 // dir1 = getFaceDir( FF1[0], E1, edge1->_nodes[0], helper, ok ).Normalized();
3715 // if ( edge2->_cosin < 0 )
3716 // dir2 = getFaceDir( FF2[0], E2, edge2->_nodes[0], helper, ok ).Normalized();
3718 double cos1 = Abs( edge1->_cosin ), cos2 = Abs( edge2->_cosin );
3719 double wgt1 = ( cos1 + 0.001 ) / ( cos1 + cos2 + 0.002 );
3720 double wgt2 = ( cos2 + 0.001 ) / ( cos1 + cos2 + 0.002 );
3721 newEdge._normal = ( wgt1 * dir1 + wgt2 * dir2 ).XYZ();
3722 newEdge._normal.Normalize();
3724 // cout << edge1->_nodes[0]->GetID() << " "
3725 // << edge2->_nodes[0]->GetID() << " NORM: "
3726 // << newEdge._normal.X() << ", " << newEdge._normal.Y() << ", " << newEdge._normal.Z() << endl;
3729 if ( cos1 < theMinSmoothCosin )
3731 newEdge._cosin = edge2->_cosin;
3733 else if ( cos2 > theMinSmoothCosin ) // both cos1 and cos2 > theMinSmoothCosin
3735 // gp_Vec dirInFace;
3736 // if ( edge1->_cosin < 0 )
3737 // dirInFace = dir1;
3739 // dirInFace = getFaceDir( FF1[0], E1, edge1->_nodes[0], helper, ok );
3740 // double angle = dirInFace.Angle( edge1->_normal ); // [0,PI]
3741 // edge1->SetCosin( Cos( angle ));
3742 //newEdge._cosin = 0; // ???????????
3743 newEdge._cosin = ( wgt1 * cos1 + wgt2 * cos2 ) * edge1->_cosin / cos1;
3747 newEdge._cosin = edge1->_cosin;
3750 // find shapes that need smoothing due to change of _normal
3751 if ( edge1->_cosin < theMinSmoothCosin &&
3752 newEdge._cosin > theMinSmoothCosin )
3754 if ( edge1->_sWOL.IsNull() )
3756 SMDS_ElemIteratorPtr fIt = edge1->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
3757 while ( fIt->more() )
3758 shapesToSmooth.insert( fIt->next()->getshapeId() );
3759 //limitStepSize( data, fIt->next(), edge1->_cosin ); // too late
3761 else // edge1 inflates along a FACE
3763 TopoDS_Shape V = helper.GetSubShapeByNode( edge1->_nodes[0], getMeshDS() );
3764 PShapeIteratorPtr eIt = helper.GetAncestors( V, *_mesh, TopAbs_EDGE );
3765 while ( const TopoDS_Shape* E = eIt->next() )
3767 if ( !helper.IsSubShape( *E, /*FACE=*/edge1->_sWOL ))
3769 gp_Vec edgeDir = getEdgeDir( TopoDS::Edge( *E ), TopoDS::Vertex( V ));
3770 double angle = edgeDir.Angle( newEdge._normal ); // [0,PI]
3771 if ( angle < M_PI / 2 )
3772 shapesToSmooth.insert( getMeshDS()->ShapeToIndex( *E ));
3778 data.AddShapesToSmooth( shapesToSmooth );
3780 // Update data of edges depending on a new _normal
3782 for ( size_t iE = 0; iE < edge2newEdge.size(); ++iE )
3784 _LayerEdge* edge1 = edge2newEdge[ iE ].first;
3785 _LayerEdge& newEdge = edge2newEdge[ iE ].second;
3786 if ( !edge1 ) continue;
3788 edge1->_normal = newEdge._normal;
3789 edge1->SetCosin( newEdge._cosin );
3790 edge1->InvalidateStep( 1 );
3792 edge1->SetNewLength( data._stepSize, helper );
3793 if ( edge1->IsOnEdge() )
3795 const SMDS_MeshNode * n1 = edge1->_2neibors->srcNode(0);
3796 const SMDS_MeshNode * n2 = edge1->_2neibors->srcNode(1);
3797 edge1->SetDataByNeighbors( n1, n2, helper );
3800 // Update normals and other dependent data of not intersecting _LayerEdge's
3801 // neighboring the intersecting ones
3803 if ( !edge1->_2neibors )
3805 for ( int j = 0; j < 2; ++j ) // loop on 2 neighbors
3807 _LayerEdge* neighbor = edge1->_2neibors->_edges[j];
3808 if ( edge2CloseEdge.count ( neighbor ))
3809 continue; // j-th neighbor is also intersected
3810 _LayerEdge* prevEdge = edge1;
3811 const int nbSteps = 10;
3812 for ( int step = nbSteps; step; --step ) // step from edge1 in j-th direction
3814 if ( !neighbor->_2neibors )
3815 break; // neighbor is on VERTEX
3817 _LayerEdge* nextEdge = neighbor->_2neibors->_edges[iNext];
3818 if ( nextEdge == prevEdge )
3819 nextEdge = neighbor->_2neibors->_edges[ ++iNext ];
3820 double r = double(step-1)/nbSteps;
3821 if ( !nextEdge->_2neibors )
3824 gp_XYZ newNorm = prevEdge->_normal * r + nextEdge->_normal * (1-r);
3825 newNorm.Normalize();
3827 neighbor->_normal = newNorm;
3828 neighbor->SetCosin( prevEdge->_cosin * r + nextEdge->_cosin * (1-r) );
3829 neighbor->SetDataByNeighbors( prevEdge->_nodes[0], nextEdge->_nodes[0], helper );
3831 neighbor->InvalidateStep( 1 );
3833 neighbor->SetNewLength( data._stepSize, helper );
3835 // goto the next neighbor
3836 prevEdge = neighbor;
3837 neighbor = nextEdge;
3843 // 2) Check absence of intersections
3846 for ( size_t i = 0 ; i < tmpFaces.size(); ++i )
3852 //================================================================================
3854 * \brief Modify normals of _LayerEdge's on _ConvexFace's
3856 //================================================================================
3858 bool _ViscousBuilder::updateNormalsOfConvexFaces( _SolidData& data,
3859 SMESH_MesherHelper& helper,
3862 SMESHDS_Mesh* meshDS = helper.GetMeshDS();
3865 map< TGeomID, _ConvexFace >::iterator id2face = data._convexFaces.begin();
3866 for ( ; id2face != data._convexFaces.end(); ++id2face )
3868 _ConvexFace & convFace = (*id2face).second;
3869 if ( convFace._normalsFixed )
3870 continue; // already fixed
3871 if ( convFace.CheckPrisms() )
3872 continue; // nothing to fix
3874 convFace._normalsFixed = true;
3876 BRepAdaptor_Surface surface ( convFace._face, false );
3877 BRepLProp_SLProps surfProp( surface, 2, 1e-6 );
3879 // check if the convex FACE is of spherical shape
3881 Bnd_B3d centersBox; // bbox of centers of curvature of _LayerEdge's on VERTEXes
3886 map< TGeomID, int >::iterator id2end = convFace._subIdToEdgeEnd.begin();
3887 for ( ; id2end != convFace._subIdToEdgeEnd.end(); ++id2end )
3889 data.GetEdgesOnShape( id2end->second, iBeg, iEnd );
3891 if ( meshDS->IndexToShape( id2end->first ).ShapeType() == TopAbs_VERTEX )
3893 _LayerEdge* ledge = data._edges[ iBeg ];
3894 if ( convFace.GetCenterOfCurvature( ledge, surfProp, helper, center ))
3895 centersBox.Add( center );
3897 for ( ; iBeg < iEnd; ++iBeg )
3898 nodesBox.Add( SMESH_TNodeXYZ( data._edges[ iBeg ]->_nodes[0] ));
3900 if ( centersBox.IsVoid() )
3902 debugMsg( "Error: centersBox.IsVoid()" );
3905 const bool isSpherical =
3906 ( centersBox.SquareExtent() < 1e-6 * nodesBox.SquareExtent() );
3908 int nbEdges = helper.Count( convFace._face, TopAbs_EDGE, /*ignoreSame=*/false );
3909 vector < _CentralCurveOnEdge > centerCurves( nbEdges );
3913 // set _LayerEdge::_normal as average of all normals
3915 // WARNING: different density of nodes on EDGEs is not taken into account that
3916 // can lead to an improper new normal
3918 gp_XYZ avgNormal( 0,0,0 );
3920 id2end = convFace._subIdToEdgeEnd.begin();
3921 for ( ; id2end != convFace._subIdToEdgeEnd.end(); ++id2end )
3923 data.GetEdgesOnShape( id2end->second, iBeg, iEnd );
3924 // set data of _CentralCurveOnEdge
3925 const TopoDS_Shape& S = meshDS->IndexToShape( id2end->first );
3926 if ( S.ShapeType() == TopAbs_EDGE )
3928 _CentralCurveOnEdge& ceCurve = centerCurves[ nbEdges++ ];
3929 ceCurve.SetShapes( TopoDS::Edge(S), convFace, data, helper );
3930 if ( !data._edges[ iBeg ]->_sWOL.IsNull() )
3931 ceCurve._adjFace.Nullify();
3933 ceCurve._ledges.insert( ceCurve._ledges.end(),
3934 &data._edges[ iBeg ], &data._edges[ iEnd ]);
3936 // summarize normals
3937 for ( ; iBeg < iEnd; ++iBeg )
3938 avgNormal += data._edges[ iBeg ]->_normal;
3940 double normSize = avgNormal.SquareModulus();
3941 if ( normSize < 1e-200 )
3943 debugMsg( "updateNormalsOfConvexFaces(): zero avgNormal" );
3946 avgNormal /= Sqrt( normSize );
3948 // compute new _LayerEdge::_cosin on EDGEs
3949 double avgCosin = 0;
3952 for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
3954 _CentralCurveOnEdge& ceCurve = centerCurves[ iE ];
3955 if ( ceCurve._adjFace.IsNull() )
3957 for ( size_t iLE = 0; iLE < ceCurve._ledges.size(); ++iLE )
3959 const SMDS_MeshNode* node = ceCurve._ledges[ iLE ]->_nodes[0];
3960 inFaceDir = getFaceDir( ceCurve._adjFace, ceCurve._edge, node, helper, isOK );
3963 double angle = inFaceDir.Angle( avgNormal ); // [0,PI]
3964 ceCurve._ledges[ iLE ]->_cosin = Cos( angle );
3965 avgCosin += ceCurve._ledges[ iLE ]->_cosin;
3971 avgCosin /= nbCosin;
3973 // set _LayerEdge::_normal = avgNormal
3974 id2end = convFace._subIdToEdgeEnd.begin();
3975 for ( ; id2end != convFace._subIdToEdgeEnd.end(); ++id2end )
3977 data.GetEdgesOnShape( id2end->second, iBeg, iEnd );
3978 const TopoDS_Shape& S = meshDS->IndexToShape( id2end->first );
3979 if ( S.ShapeType() != TopAbs_EDGE )
3980 for ( int i = iBeg; i < iEnd; ++i )
3981 data._edges[ i ]->_cosin = avgCosin;
3983 for ( ; iBeg < iEnd; ++iBeg )
3984 data._edges[ iBeg ]->_normal = avgNormal;
3987 else // if ( isSpherical )
3989 // We suppose that centers of curvature at all points of the FACE
3990 // lie on some curve, let's call it "central curve". For all _LayerEdge's
3991 // having a common center of curvature we define the same new normal
3992 // as a sum of normals of _LayerEdge's on EDGEs among them.
3994 // get all centers of curvature for each EDGE
3996 helper.SetSubShape( convFace._face );
3997 _LayerEdge* vertexLEdges[2], **edgeLEdge, **edgeLEdgeEnd;
3999 TopExp_Explorer edgeExp( convFace._face, TopAbs_EDGE );
4000 for ( int iE = 0; edgeExp.More(); edgeExp.Next(), ++iE )
4002 const TopoDS_Edge& edge = TopoDS::Edge( edgeExp.Current() );
4004 // set adjacent FACE
4005 centerCurves[ iE ].SetShapes( edge, convFace, data, helper );
4007 // get _LayerEdge's of the EDGE
4008 TGeomID edgeID = meshDS->ShapeToIndex( edge );
4009 id2end = convFace._subIdToEdgeEnd.find( edgeID );
4010 if ( id2end == convFace._subIdToEdgeEnd.end() )
4012 // no _LayerEdge's on EDGE, use _LayerEdge's on VERTEXes
4013 for ( int iV = 0; iV < 2; ++iV )
4015 TopoDS_Vertex v = helper.IthVertex( iV, edge );
4016 TGeomID vID = meshDS->ShapeToIndex( v );
4017 int end = convFace._subIdToEdgeEnd[ vID ];
4018 int iBeg = end > 0 ? data._endEdgeOnShape[ end-1 ] : 0;
4019 vertexLEdges[ iV ] = data._edges[ iBeg ];
4021 edgeLEdge = &vertexLEdges[0];
4022 edgeLEdgeEnd = edgeLEdge + 2;
4024 centerCurves[ iE ]._adjFace.Nullify();
4028 data.GetEdgesOnShape( id2end->second, iBeg, iEnd );
4029 if ( id2end->second >= data._nbShapesToSmooth )
4030 data.SortOnEdge( edge, iBeg, iEnd, helper );
4031 edgeLEdge = &data._edges[ iBeg ];
4032 edgeLEdgeEnd = edgeLEdge + iEnd - iBeg;
4033 vertexLEdges[0] = data._edges[ iBeg ]->_2neibors->_edges[0];
4034 vertexLEdges[1] = data._edges[ iEnd-1 ]->_2neibors->_edges[1];
4036 if ( ! data._edges[ iBeg ]->_sWOL.IsNull() )
4037 centerCurves[ iE ]._adjFace.Nullify();
4040 // Get curvature centers
4044 if ( edgeLEdge[0]->IsOnEdge() &&
4045 convFace.GetCenterOfCurvature( vertexLEdges[0], surfProp, helper, center ))
4047 centerCurves[ iE ].Append( center, vertexLEdges[0] );
4048 centersBox.Add( center );
4050 for ( ; edgeLEdge < edgeLEdgeEnd; ++edgeLEdge )
4051 if ( convFace.GetCenterOfCurvature( *edgeLEdge, surfProp, helper, center ))
4052 { // EDGE or VERTEXes
4053 centerCurves[ iE ].Append( center, *edgeLEdge );
4054 centersBox.Add( center );
4056 if ( edgeLEdge[-1]->IsOnEdge() &&
4057 convFace.GetCenterOfCurvature( vertexLEdges[1], surfProp, helper, center ))
4059 centerCurves[ iE ].Append( center, vertexLEdges[1] );
4060 centersBox.Add( center );
4062 centerCurves[ iE ]._isDegenerated =
4063 ( centersBox.IsVoid() || centersBox.SquareExtent() < 1e-6 * nodesBox.SquareExtent() );
4065 } // loop on EDGES of convFace._face to set up data of centerCurves
4067 // Compute new normals for _LayerEdge's on EDGEs
4069 double avgCosin = 0;
4072 for ( size_t iE1 = 0; iE1 < centerCurves.size(); ++iE1 )
4074 _CentralCurveOnEdge& ceCurve = centerCurves[ iE1 ];
4075 if ( ceCurve._isDegenerated )
4077 const vector< gp_Pnt >& centers = ceCurve._curvaCenters;
4078 vector< gp_XYZ > & newNormals = ceCurve._normals;
4079 for ( size_t iC1 = 0; iC1 < centers.size(); ++iC1 )
4082 for ( size_t iE2 = 0; iE2 < centerCurves.size() && !isOK; ++iE2 )
4085 isOK = centerCurves[ iE2 ].FindNewNormal( centers[ iC1 ], newNormals[ iC1 ]);
4087 if ( isOK && !ceCurve._adjFace.IsNull() )
4089 // compute new _LayerEdge::_cosin
4090 const SMDS_MeshNode* node = ceCurve._ledges[ iC1 ]->_nodes[0];
4091 inFaceDir = getFaceDir( ceCurve._adjFace, ceCurve._edge, node, helper, isOK );
4094 double angle = inFaceDir.Angle( newNormals[ iC1 ] ); // [0,PI]
4095 ceCurve._ledges[ iC1 ]->_cosin = Cos( angle );
4096 avgCosin += ceCurve._ledges[ iC1 ]->_cosin;
4102 // set new normals to _LayerEdge's of NOT degenerated central curves
4103 for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
4105 if ( centerCurves[ iE ]._isDegenerated )
4107 for ( size_t iLE = 0; iLE < centerCurves[ iE ]._ledges.size(); ++iLE )
4108 centerCurves[ iE ]._ledges[ iLE ]->_normal = centerCurves[ iE ]._normals[ iLE ];
4110 // set new normals to _LayerEdge's of degenerated central curves
4111 for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
4113 if ( !centerCurves[ iE ]._isDegenerated ||
4114 centerCurves[ iE ]._ledges.size() < 3 )
4116 // new normal is an average of new normals at VERTEXes that
4117 // was computed on non-degenerated _CentralCurveOnEdge's
4118 gp_XYZ newNorm = ( centerCurves[ iE ]._ledges.front()->_normal +
4119 centerCurves[ iE ]._ledges.back ()->_normal );
4120 double sz = newNorm.Modulus();
4124 double newCosin = ( 0.5 * centerCurves[ iE ]._ledges.front()->_cosin +
4125 0.5 * centerCurves[ iE ]._ledges.back ()->_cosin );
4126 for ( size_t iLE = 1, nb = centerCurves[ iE ]._ledges.size() - 1; iLE < nb; ++iLE )
4128 centerCurves[ iE ]._ledges[ iLE ]->_normal = newNorm;
4129 centerCurves[ iE ]._ledges[ iLE ]->_cosin = newCosin;
4133 // Find new normals for _LayerEdge's based on FACE
4136 avgCosin /= nbCosin;
4137 const TGeomID faceID = meshDS->ShapeToIndex( convFace._face );
4138 map< TGeomID, int >::iterator id2end = convFace._subIdToEdgeEnd.find( faceID );
4139 if ( id2end != convFace._subIdToEdgeEnd.end() )
4143 data.GetEdgesOnShape( id2end->second, iBeg, iEnd );
4144 for ( ; iBeg < iEnd; ++iBeg )
4146 _LayerEdge* ledge = data._edges[ iBeg ];
4147 if ( !convFace.GetCenterOfCurvature( ledge, surfProp, helper, center ))
4149 for ( size_t i = 0; i < centerCurves.size(); ++i, ++iE )
4151 iE = iE % centerCurves.size();
4152 if ( centerCurves[ iE ]._isDegenerated )
4154 newNorm.SetCoord( 0,0,0 );
4155 if ( centerCurves[ iE ].FindNewNormal( center, newNorm ))
4157 ledge->_normal = newNorm;
4158 ledge->_cosin = avgCosin;
4165 } // not a quasi-spherical FACE
4167 // Update _LayerEdge's data according to a new normal
4169 dumpFunction(SMESH_Comment("updateNormalsOfConvexFaces")<<data._index
4170 <<"_F"<<meshDS->ShapeToIndex( convFace._face ));
4172 id2end = convFace._subIdToEdgeEnd.begin();
4173 for ( ; id2end != convFace._subIdToEdgeEnd.end(); ++id2end )
4175 data.GetEdgesOnShape( id2end->second, iBeg, iEnd );
4176 for ( ; iBeg < iEnd; ++iBeg )
4178 _LayerEdge* & ledge = data._edges[ iBeg ];
4179 double len = ledge->_len;
4180 ledge->InvalidateStep( stepNb + 1, /*restoreLength=*/true );
4181 ledge->SetCosin( ledge->_cosin );
4182 ledge->SetNewLength( len, helper );
4185 } // loop on sub-shapes of convFace._face
4187 // Find FACEs adjacent to convFace._face that got necessity to smooth
4188 // as a result of normals modification
4190 set< TGeomID > adjFacesToSmooth;
4191 for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
4193 if ( centerCurves[ iE ]._adjFace.IsNull() ||
4194 centerCurves[ iE ]._adjFaceToSmooth )
4196 for ( size_t iLE = 0; iLE < centerCurves[ iE ]._ledges.size(); ++iLE )
4198 if ( centerCurves[ iE ]._ledges[ iLE ]->_cosin > theMinSmoothCosin )
4200 adjFacesToSmooth.insert( meshDS->ShapeToIndex( centerCurves[ iE ]._adjFace ));
4205 data.AddShapesToSmooth( adjFacesToSmooth );
4210 } // loop on data._convexFaces
4215 //================================================================================
4217 * \brief Finds a center of curvature of a surface at a _LayerEdge
4219 //================================================================================
4221 bool _ConvexFace::GetCenterOfCurvature( _LayerEdge* ledge,
4222 BRepLProp_SLProps& surfProp,
4223 SMESH_MesherHelper& helper,
4224 gp_Pnt & center ) const
4226 gp_XY uv = helper.GetNodeUV( _face, ledge->_nodes[0] );
4227 surfProp.SetParameters( uv.X(), uv.Y() );
4228 if ( !surfProp.IsCurvatureDefined() )
4231 const double oriFactor = ( _face.Orientation() == TopAbs_REVERSED ? +1. : -1. );
4232 double surfCurvatureMax = surfProp.MaxCurvature() * oriFactor;
4233 double surfCurvatureMin = surfProp.MinCurvature() * oriFactor;
4234 if ( surfCurvatureMin > surfCurvatureMax )
4235 center = surfProp.Value().Translated( surfProp.Normal().XYZ() / surfCurvatureMin * oriFactor );
4237 center = surfProp.Value().Translated( surfProp.Normal().XYZ() / surfCurvatureMax * oriFactor );
4242 //================================================================================
4244 * \brief Check that prisms are not distorted
4246 //================================================================================
4248 bool _ConvexFace::CheckPrisms() const
4250 for ( size_t i = 0; i < _simplexTestEdges.size(); ++i )
4252 const _LayerEdge* edge = _simplexTestEdges[i];
4253 SMESH_TNodeXYZ tgtXYZ( edge->_nodes.back() );
4254 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
4255 if ( !edge->_simplices[j].IsForward( edge->_nodes[0], &tgtXYZ ))
4257 debugMsg( "Bad simplex of _simplexTestEdges ("
4258 << " "<< edge->_nodes[0]->GetID()<< " "<< tgtXYZ._node->GetID()
4259 << " "<< edge->_simplices[j]._nPrev->GetID()
4260 << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
4267 //================================================================================
4269 * \brief Try to compute a new normal by interpolating normals of _LayerEdge's
4270 * stored in this _CentralCurveOnEdge.
4271 * \param [in] center - curvature center of a point of another _CentralCurveOnEdge.
4272 * \param [in,out] newNormal - current normal at this point, to be redefined
4273 * \return bool - true if succeeded.
4275 //================================================================================
4277 bool _CentralCurveOnEdge::FindNewNormal( const gp_Pnt& center, gp_XYZ& newNormal )
4279 if ( this->_isDegenerated )
4282 // find two centers the given one lies between
4284 for ( size_t i = 0, nb = _curvaCenters.size()-1; i < nb; ++i )
4286 double sl2 = 1.001 * _segLength2[ i ];
4288 double d1 = center.SquareDistance( _curvaCenters[ i ]);
4292 double d2 = center.SquareDistance( _curvaCenters[ i+1 ]);
4293 if ( d2 > sl2 || d2 + d1 < 1e-100 )
4298 double r = d1 / ( d1 + d2 );
4299 gp_XYZ norm = (( 1. - r ) * _ledges[ i ]->_normal +
4300 ( r ) * _ledges[ i+1 ]->_normal );
4304 double sz = newNormal.Modulus();
4313 //================================================================================
4315 * \brief Set shape members
4317 //================================================================================
4319 void _CentralCurveOnEdge::SetShapes( const TopoDS_Edge& edge,
4320 const _ConvexFace& convFace,
4321 const _SolidData& data,
4322 SMESH_MesherHelper& helper)
4326 PShapeIteratorPtr fIt = helper.GetAncestors( edge, *helper.GetMesh(), TopAbs_FACE );
4327 while ( const TopoDS_Shape* F = fIt->next())
4328 if ( !convFace._face.IsSame( *F ))
4330 _adjFace = TopoDS::Face( *F );
4331 _adjFaceToSmooth = false;
4332 // _adjFace already in a smoothing queue ?
4334 TGeomID adjFaceID = helper.GetMeshDS()->ShapeToIndex( *F );
4335 if ( data.GetShapeEdges( adjFaceID, end ))
4336 _adjFaceToSmooth = ( end < data._nbShapesToSmooth );
4341 //================================================================================
4343 * \brief Looks for intersection of it's last segment with faces
4344 * \param distance - returns shortest distance from the last node to intersection
4346 //================================================================================
4348 bool _LayerEdge::FindIntersection( SMESH_ElementSearcher& searcher,
4350 const double& epsilon,
4351 const SMDS_MeshElement** face)
4353 vector< const SMDS_MeshElement* > suspectFaces;
4355 gp_Ax1 lastSegment = LastSegment(segLen);
4356 searcher.GetElementsNearLine( lastSegment, SMDSAbs_Face, suspectFaces );
4358 bool segmentIntersected = false;
4359 distance = Precision::Infinite();
4360 int iFace = -1; // intersected face
4361 for ( size_t j = 0 ; j < suspectFaces.size() /*&& !segmentIntersected*/; ++j )
4363 const SMDS_MeshElement* face = suspectFaces[j];
4364 if ( face->GetNodeIndex( _nodes.back() ) >= 0 ||
4365 face->GetNodeIndex( _nodes[0] ) >= 0 )
4366 continue; // face sharing _LayerEdge node
4367 const int nbNodes = face->NbCornerNodes();
4368 bool intFound = false;
4370 SMDS_MeshElement::iterator nIt = face->begin_nodes();
4373 intFound = SegTriaInter( lastSegment, *nIt++, *nIt++, *nIt++, dist, epsilon );
4377 const SMDS_MeshNode* tria[3];
4380 for ( int n2 = 2; n2 < nbNodes && !intFound; ++n2 )
4383 intFound = SegTriaInter(lastSegment, tria[0], tria[1], tria[2], dist, epsilon );
4389 if ( dist < segLen*(1.01) && dist > -(_len*_lenFactor-segLen) )
4390 segmentIntersected = true;
4391 if ( distance > dist )
4392 distance = dist, iFace = j;
4395 if ( iFace != -1 && face ) *face = suspectFaces[iFace];
4397 if ( segmentIntersected )
4400 SMDS_MeshElement::iterator nIt = suspectFaces[iFace]->begin_nodes();
4401 gp_XYZ intP( lastSegment.Location().XYZ() + lastSegment.Direction().XYZ() * distance );
4402 cout << "nodes: tgt " << _nodes.back()->GetID() << " src " << _nodes[0]->GetID()
4403 << ", intersection with face ("
4404 << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
4405 << ") at point (" << intP.X() << ", " << intP.Y() << ", " << intP.Z()
4406 << ") distance = " << distance - segLen<< endl;
4412 return segmentIntersected;
4415 //================================================================================
4417 * \brief Returns size and direction of the last segment
4419 //================================================================================
4421 gp_Ax1 _LayerEdge::LastSegment(double& segLen) const
4423 // find two non-coincident positions
4424 gp_XYZ orig = _pos.back();
4426 int iPrev = _pos.size() - 2;
4427 while ( iPrev >= 0 )
4429 dir = orig - _pos[iPrev];
4430 if ( dir.SquareModulus() > 1e-100 )
4440 segDir.SetLocation( SMESH_TNodeXYZ( _nodes[0] ));
4441 segDir.SetDirection( _normal );
4446 gp_Pnt pPrev = _pos[ iPrev ];
4447 if ( !_sWOL.IsNull() )
4449 TopLoc_Location loc;
4450 if ( _sWOL.ShapeType() == TopAbs_EDGE )
4453 Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( _sWOL ), loc, f,l);
4454 pPrev = curve->Value( pPrev.X() ).Transformed( loc );
4458 Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face(_sWOL), loc );
4459 pPrev = surface->Value( pPrev.X(), pPrev.Y() ).Transformed( loc );
4461 dir = SMESH_TNodeXYZ( _nodes.back() ) - pPrev.XYZ();
4463 segDir.SetLocation( pPrev );
4464 segDir.SetDirection( dir );
4465 segLen = dir.Modulus();
4471 //================================================================================
4473 * \brief Return the last position of the target node on a FACE.
4474 * \param [in] F - the FACE this _LayerEdge is inflated along
4475 * \return gp_XY - result UV
4477 //================================================================================
4479 gp_XY _LayerEdge::LastUV( const TopoDS_Face& F ) const
4481 if ( F.IsSame( _sWOL )) // F is my FACE
4482 return gp_XY( _pos.back().X(), _pos.back().Y() );
4484 if ( _sWOL.IsNull() || _sWOL.ShapeType() != TopAbs_EDGE ) // wrong call
4485 return gp_XY( 1e100, 1e100 );
4487 // _sWOL is EDGE of F; _pos.back().X() is the last U on the EDGE
4488 double f, l, u = _pos.back().X();
4489 Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface( TopoDS::Edge(_sWOL), F, f,l);
4490 if ( !C2d.IsNull() && f <= u && u <= l )
4491 return C2d->Value( u ).XY();
4493 return gp_XY( 1e100, 1e100 );
4496 //================================================================================
4498 * \brief Test intersection of the last segment with a given triangle
4499 * using Moller-Trumbore algorithm
4500 * Intersection is detected if distance to intersection is less than _LayerEdge._len
4502 //================================================================================
4504 bool _LayerEdge::SegTriaInter( const gp_Ax1& lastSegment,
4505 const SMDS_MeshNode* n0,
4506 const SMDS_MeshNode* n1,
4507 const SMDS_MeshNode* n2,
4509 const double& EPSILON) const
4511 //const double EPSILON = 1e-6;
4513 gp_XYZ orig = lastSegment.Location().XYZ();
4514 gp_XYZ dir = lastSegment.Direction().XYZ();
4516 SMESH_TNodeXYZ vert0( n0 );
4517 SMESH_TNodeXYZ vert1( n1 );
4518 SMESH_TNodeXYZ vert2( n2 );
4520 /* calculate distance from vert0 to ray origin */
4521 gp_XYZ tvec = orig - vert0;
4523 //if ( tvec * dir > EPSILON )
4524 // intersected face is at back side of the temporary face this _LayerEdge belongs to
4527 gp_XYZ edge1 = vert1 - vert0;
4528 gp_XYZ edge2 = vert2 - vert0;
4530 /* begin calculating determinant - also used to calculate U parameter */
4531 gp_XYZ pvec = dir ^ edge2;
4533 /* if determinant is near zero, ray lies in plane of triangle */
4534 double det = edge1 * pvec;
4536 if (det > -EPSILON && det < EPSILON)
4538 double inv_det = 1.0 / det;
4540 /* calculate U parameter and test bounds */
4541 double u = ( tvec * pvec ) * inv_det;
4542 //if (u < 0.0 || u > 1.0)
4543 if (u < -EPSILON || u > 1.0 + EPSILON)
4546 /* prepare to test V parameter */
4547 gp_XYZ qvec = tvec ^ edge1;
4549 /* calculate V parameter and test bounds */
4550 double v = (dir * qvec) * inv_det;
4551 //if ( v < 0.0 || u + v > 1.0 )
4552 if ( v < -EPSILON || u + v > 1.0 + EPSILON)
4555 /* calculate t, ray intersects triangle */
4556 t = (edge2 * qvec) * inv_det;
4562 //================================================================================
4564 * \brief Perform smooth of _LayerEdge's based on EDGE's
4565 * \retval bool - true if node has been moved
4567 //================================================================================
4569 bool _LayerEdge::SmoothOnEdge(Handle(Geom_Surface)& surface,
4570 const TopoDS_Face& F,
4571 SMESH_MesherHelper& helper)
4573 ASSERT( IsOnEdge() );
4575 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _nodes.back() );
4576 SMESH_TNodeXYZ oldPos( tgtNode );
4577 double dist01, distNewOld;
4579 SMESH_TNodeXYZ p0( _2neibors->tgtNode(0));
4580 SMESH_TNodeXYZ p1( _2neibors->tgtNode(1));
4581 dist01 = p0.Distance( _2neibors->tgtNode(1) );
4583 gp_Pnt newPos = p0 * _2neibors->_wgt[0] + p1 * _2neibors->_wgt[1];
4584 double lenDelta = 0;
4587 //lenDelta = _curvature->lenDelta( _len );
4588 lenDelta = _curvature->lenDeltaByDist( dist01 );
4589 newPos.ChangeCoord() += _normal * lenDelta;
4592 distNewOld = newPos.Distance( oldPos );
4596 if ( _2neibors->_plnNorm )
4598 // put newPos on the plane defined by source node and _plnNorm
4599 gp_XYZ new2src = SMESH_TNodeXYZ( _nodes[0] ) - newPos.XYZ();
4600 double new2srcProj = (*_2neibors->_plnNorm) * new2src;
4601 newPos.ChangeCoord() += (*_2neibors->_plnNorm) * new2srcProj;
4603 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
4604 _pos.back() = newPos.XYZ();
4608 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
4609 gp_XY uv( Precision::Infinite(), 0 );
4610 helper.CheckNodeUV( F, tgtNode, uv, 1e-10, /*force=*/true );
4611 _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
4613 newPos = surface->Value( uv.X(), uv.Y() );
4614 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
4617 if ( _curvature && lenDelta < 0 )
4619 gp_Pnt prevPos( _pos[ _pos.size()-2 ]);
4620 _len -= prevPos.Distance( oldPos );
4621 _len += prevPos.Distance( newPos );
4623 bool moved = distNewOld > dist01/50;
4625 dumpMove( tgtNode ); // debug
4630 //================================================================================
4632 * \brief Perform laplacian smooth in 3D of nodes inflated from FACE
4633 * \retval bool - true if _tgtNode has been moved
4635 //================================================================================
4637 bool _LayerEdge::Smooth(int& badNb)
4639 if ( _simplices.size() < 2 )
4640 return false; // _LayerEdge inflated along EDGE or FACE
4642 // compute new position for the last _pos
4643 gp_XYZ newPos (0,0,0);
4644 for ( size_t i = 0; i < _simplices.size(); ++i )
4645 newPos += SMESH_TNodeXYZ( _simplices[i]._nPrev );
4646 newPos /= _simplices.size();
4648 const gp_XYZ& curPos ( _pos.back() );
4649 const gp_Pnt prevPos( _pos[ _pos.size()-2 ]);
4652 double delta = _curvature->lenDelta( _len );
4654 newPos += _normal * delta;
4657 double segLen = _normal * ( newPos - prevPos.XYZ() );
4658 if ( segLen + delta > 0 )
4659 newPos += _normal * delta;
4661 // double segLenChange = _normal * ( curPos - newPos );
4662 // newPos += 0.5 * _normal * segLenChange;
4665 // count quality metrics (orientation) of tetras around _tgtNode
4667 for ( size_t i = 0; i < _simplices.size(); ++i )
4668 nbOkBefore += _simplices[i].IsForward( _nodes[0], &curPos );
4671 for ( size_t i = 0; i < _simplices.size(); ++i )
4672 nbOkAfter += _simplices[i].IsForward( _nodes[0], &newPos );
4674 if ( nbOkAfter < nbOkBefore )
4677 SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
4679 _len -= prevPos.Distance(SMESH_TNodeXYZ( n ));
4680 _len += prevPos.Distance(newPos);
4682 n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
4683 _pos.back() = newPos;
4685 badNb += _simplices.size() - nbOkAfter;
4692 //================================================================================
4694 * \brief Add a new segment to _LayerEdge during inflation
4696 //================================================================================
4698 void _LayerEdge::SetNewLength( double len, SMESH_MesherHelper& helper )
4700 if ( _len - len > -1e-6 )
4702 _pos.push_back( _pos.back() );
4706 SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
4707 SMESH_TNodeXYZ oldXYZ( n );
4708 gp_XYZ nXYZ = oldXYZ + _normal * ( len - _len ) * _lenFactor;
4709 n->setXYZ( nXYZ.X(), nXYZ.Y(), nXYZ.Z() );
4711 _pos.push_back( nXYZ );
4713 if ( !_sWOL.IsNull() )
4716 if ( _sWOL.ShapeType() == TopAbs_EDGE )
4718 double u = Precision::Infinite(); // to force projection w/o distance check
4719 helper.CheckNodeU( TopoDS::Edge( _sWOL ), n, u, 1e-10, /*force=*/true, distXYZ );
4720 _pos.back().SetCoord( u, 0, 0 );
4721 if ( _nodes.size() > 1 )
4723 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( n->GetPosition() );
4724 pos->SetUParameter( u );
4729 gp_XY uv( Precision::Infinite(), 0 );
4730 helper.CheckNodeUV( TopoDS::Face( _sWOL ), n, uv, 1e-10, /*force=*/true, distXYZ );
4731 _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
4732 if ( _nodes.size() > 1 )
4734 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( n->GetPosition() );
4735 pos->SetUParameter( uv.X() );
4736 pos->SetVParameter( uv.Y() );
4739 n->setXYZ( distXYZ[1], distXYZ[2], distXYZ[3]);
4741 dumpMove( n ); //debug
4744 //================================================================================
4746 * \brief Remove last inflation step
4748 //================================================================================
4750 void _LayerEdge::InvalidateStep( int curStep, bool restoreLength )
4752 if ( _pos.size() > curStep )
4754 if ( restoreLength )
4755 _len -= ( _pos[ curStep-1 ] - _pos.back() ).Modulus();
4757 _pos.resize( curStep );
4758 gp_Pnt nXYZ = _pos.back();
4759 SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
4760 if ( !_sWOL.IsNull() )
4762 TopLoc_Location loc;
4763 if ( _sWOL.ShapeType() == TopAbs_EDGE )
4765 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( n->GetPosition() );
4766 pos->SetUParameter( nXYZ.X() );
4768 Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( _sWOL ), loc, f,l);
4769 nXYZ = curve->Value( nXYZ.X() ).Transformed( loc );
4773 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( n->GetPosition() );
4774 pos->SetUParameter( nXYZ.X() );
4775 pos->SetVParameter( nXYZ.Y() );
4776 Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face(_sWOL), loc );
4777 nXYZ = surface->Value( nXYZ.X(), nXYZ.Y() ).Transformed( loc );
4780 n->setXYZ( nXYZ.X(), nXYZ.Y(), nXYZ.Z() );
4785 //================================================================================
4787 * \brief Create layers of prisms
4789 //================================================================================
4791 bool _ViscousBuilder::refine(_SolidData& data)
4793 SMESH_MesherHelper helper( *_mesh );
4794 helper.SetSubShape( data._solid );
4795 helper.SetElementsOnShape(false);
4797 Handle(Geom_Curve) curve;
4798 Handle(Geom_Surface) surface;
4799 TopoDS_Edge geomEdge;
4800 TopoDS_Face geomFace;
4801 TopoDS_Shape prevSWOL;
4802 TopLoc_Location loc;
4806 TGeomID prevBaseId = -1;
4807 TNode2Edge* n2eMap = 0;
4808 TNode2Edge::iterator n2e;
4810 // Create intermediate nodes on each _LayerEdge
4812 for ( size_t i = 0; i < data._edges.size(); ++i )
4814 _LayerEdge& edge = *data._edges[i];
4816 if ( edge._nodes.size() < 2 )
4817 continue; // on _noShrinkShapes
4819 // get accumulated length of segments
4820 vector< double > segLen( edge._pos.size() );
4822 for ( size_t j = 1; j < edge._pos.size(); ++j )
4823 segLen[j] = segLen[j-1] + (edge._pos[j-1] - edge._pos[j] ).Modulus();
4825 // allocate memory for new nodes if it is not yet refined
4826 const SMDS_MeshNode* tgtNode = edge._nodes.back();
4827 if ( edge._nodes.size() == 2 )
4829 edge._nodes.resize( data._hyp->GetNumberLayers() + 1, 0 );
4831 edge._nodes.back() = tgtNode;
4833 // get data of a shrink shape
4834 if ( !edge._sWOL.IsNull() && edge._sWOL != prevSWOL )
4836 isOnEdge = ( edge._sWOL.ShapeType() == TopAbs_EDGE );
4839 geomEdge = TopoDS::Edge( edge._sWOL );
4840 curve = BRep_Tool::Curve( geomEdge, loc, f,l);
4844 geomFace = TopoDS::Face( edge._sWOL );
4845 surface = BRep_Tool::Surface( geomFace, loc );
4847 prevSWOL = edge._sWOL;
4849 // restore shapePos of the last node by already treated _LayerEdge of another _SolidData
4850 const TGeomID baseShapeId = edge._nodes[0]->getshapeId();
4851 if ( baseShapeId != prevBaseId )
4853 map< TGeomID, TNode2Edge* >::iterator s2ne = data._s2neMap.find( baseShapeId );
4854 n2eMap = ( s2ne == data._s2neMap.end() ) ? 0 : n2eMap = s2ne->second;
4855 prevBaseId = baseShapeId;
4857 _LayerEdge* edgeOnSameNode = 0;
4858 if ( n2eMap && (( n2e = n2eMap->find( edge._nodes[0] )) != n2eMap->end() ))
4860 edgeOnSameNode = n2e->second;
4861 const gp_XYZ& otherTgtPos = edgeOnSameNode->_pos.back();
4862 SMDS_PositionPtr lastPos = tgtNode->GetPosition();
4865 SMDS_EdgePosition* epos = static_cast<SMDS_EdgePosition*>( lastPos );
4866 epos->SetUParameter( otherTgtPos.X() );
4870 SMDS_FacePosition* fpos = static_cast<SMDS_FacePosition*>( lastPos );
4871 fpos->SetUParameter( otherTgtPos.X() );
4872 fpos->SetVParameter( otherTgtPos.Y() );
4875 // calculate height of the first layer
4877 const double T = segLen.back(); //data._hyp.GetTotalThickness();
4878 const double f = data._hyp->GetStretchFactor();
4879 const int N = data._hyp->GetNumberLayers();
4880 const double fPowN = pow( f, N );
4881 if ( fPowN - 1 <= numeric_limits<double>::min() )
4884 h0 = T * ( f - 1 )/( fPowN - 1 );
4886 const double zeroLen = std::numeric_limits<double>::min();
4888 // create intermediate nodes
4889 double hSum = 0, hi = h0/f;
4891 for ( size_t iStep = 1; iStep < edge._nodes.size(); ++iStep )
4893 // compute an intermediate position
4896 while ( hSum > segLen[iSeg] && iSeg < segLen.size()-1)
4898 int iPrevSeg = iSeg-1;
4899 while ( fabs( segLen[iPrevSeg] - segLen[iSeg]) <= zeroLen && iPrevSeg > 0 )
4901 double r = ( segLen[iSeg] - hSum ) / ( segLen[iSeg] - segLen[iPrevSeg] );
4902 gp_Pnt pos = r * edge._pos[iPrevSeg] + (1-r) * edge._pos[iSeg];
4904 SMDS_MeshNode*& node = const_cast< SMDS_MeshNode*& >( edge._nodes[ iStep ]);
4905 if ( !edge._sWOL.IsNull() )
4907 // compute XYZ by parameters <pos>
4912 pos = curve->Value( u ).Transformed(loc);
4916 uv.SetCoord( pos.X(), pos.Y() );
4918 pos = surface->Value( pos.X(), pos.Y() ).Transformed(loc);
4921 // create or update the node
4924 node = helper.AddNode( pos.X(), pos.Y(), pos.Z());
4925 if ( !edge._sWOL.IsNull() )
4928 getMeshDS()->SetNodeOnEdge( node, geomEdge, u );
4930 getMeshDS()->SetNodeOnFace( node, geomFace, uv.X(), uv.Y() );
4934 getMeshDS()->SetNodeInVolume( node, helper.GetSubShapeID() );
4939 if ( !edge._sWOL.IsNull() )
4941 // make average pos from new and current parameters
4944 u = 0.5 * ( u + helper.GetNodeU( geomEdge, node ));
4945 pos = curve->Value( u ).Transformed(loc);
4947 SMDS_EdgePosition* epos = static_cast<SMDS_EdgePosition*>( node->GetPosition() );
4948 epos->SetUParameter( u );
4952 uv = 0.5 * ( uv + helper.GetNodeUV( geomFace, node ));
4953 pos = surface->Value( uv.X(), uv.Y()).Transformed(loc);
4955 SMDS_FacePosition* fpos = static_cast<SMDS_FacePosition*>( node->GetPosition() );
4956 fpos->SetUParameter( uv.X() );
4957 fpos->SetVParameter( uv.Y() );
4960 node->setXYZ( pos.X(), pos.Y(), pos.Z() );
4962 } // loop on edge._nodes
4964 if ( !edge._sWOL.IsNull() ) // prepare for shrink()
4967 edge._pos.back().SetCoord( u, 0,0);
4969 edge._pos.back().SetCoord( uv.X(), uv.Y() ,0);
4971 if ( edgeOnSameNode )
4972 edgeOnSameNode->_pos.back() = edge._pos.back();
4975 } // loop on data._edges to create nodes
4977 if ( !getMeshDS()->IsEmbeddedMode() )
4978 // Log node movement
4979 for ( size_t i = 0; i < data._edges.size(); ++i )
4981 _LayerEdge& edge = *data._edges[i];
4982 SMESH_TNodeXYZ p ( edge._nodes.back() );
4983 getMeshDS()->MoveNode( p._node, p.X(), p.Y(), p.Z() );
4988 helper.SetElementsOnShape(true);
4990 vector< vector<const SMDS_MeshNode*>* > nnVec;
4991 set< vector<const SMDS_MeshNode*>* > nnSet;
4992 set< int > degenEdgeInd;
4993 vector<const SMDS_MeshElement*> degenVols;
4995 TopExp_Explorer exp( data._solid, TopAbs_FACE );
4996 for ( ; exp.More(); exp.Next() )
4998 if ( data._ignoreFaceIds.count( getMeshDS()->ShapeToIndex( exp.Current() )))
5000 SMESHDS_SubMesh* fSubM = getMeshDS()->MeshElements( exp.Current() );
5001 SMDS_ElemIteratorPtr fIt = fSubM->GetElements();
5002 while ( fIt->more() )
5004 const SMDS_MeshElement* face = fIt->next();
5005 const int nbNodes = face->NbCornerNodes();
5006 nnVec.resize( nbNodes );
5008 degenEdgeInd.clear();
5010 SMDS_NodeIteratorPtr nIt = face->nodeIterator();
5011 for ( int iN = 0; iN < nbNodes; ++iN )
5013 const SMDS_MeshNode* n = nIt->next();
5014 nnVec[ iN ] = & data._n2eMap[ n ]->_nodes;
5015 if ( nnVec[ iN ]->size() < 2 )
5016 degenEdgeInd.insert( iN );
5018 nbZ = nnVec[ iN ]->size();
5020 if ( helper.HasDegeneratedEdges() )
5021 nnSet.insert( nnVec[ iN ]);
5025 if ( 0 < nnSet.size() && nnSet.size() < 3 )
5031 switch ( degenEdgeInd.size() )
5035 for ( int iZ = 1; iZ < nbZ; ++iZ )
5036 helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1], (*nnVec[2])[iZ-1],
5037 (*nnVec[0])[iZ], (*nnVec[1])[iZ], (*nnVec[2])[iZ]);
5042 int i2 = *degenEdgeInd.begin();
5043 int i0 = helper.WrapIndex( i2 - 1, nbNodes );
5044 int i1 = helper.WrapIndex( i2 + 1, nbNodes );
5045 for ( int iZ = 1; iZ < nbZ; ++iZ )
5046 helper.AddVolume( (*nnVec[i0])[iZ-1], (*nnVec[i1])[iZ-1],
5047 (*nnVec[i1])[iZ], (*nnVec[i0])[iZ], (*nnVec[i2])[0]);
5052 int i3 = !degenEdgeInd.count(0) ? 0 : !degenEdgeInd.count(1) ? 1 : 2;
5053 for ( int iZ = 1; iZ < nbZ; ++iZ )
5054 helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1], (*nnVec[2])[iZ-1],
5062 switch ( degenEdgeInd.size() )
5066 for ( int iZ = 1; iZ < nbZ; ++iZ )
5067 helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1],
5068 (*nnVec[2])[iZ-1], (*nnVec[3])[iZ-1],
5069 (*nnVec[0])[iZ], (*nnVec[1])[iZ],
5070 (*nnVec[2])[iZ], (*nnVec[3])[iZ]);
5075 int i2 = *degenEdgeInd.begin();
5076 int i3 = *degenEdgeInd.rbegin();
5077 bool ok = ( i3 - i2 == 1 );
5078 if ( i2 == 0 && i3 == 3 ) { i2 = 3; i3 = 0; ok = true; }
5079 int i0 = helper.WrapIndex( i3 + 1, nbNodes );
5080 int i1 = helper.WrapIndex( i0 + 1, nbNodes );
5081 for ( int iZ = 1; iZ < nbZ; ++iZ )
5083 const SMDS_MeshElement* vol =
5084 helper.AddVolume( (*nnVec[i3])[0], (*nnVec[i0])[iZ], (*nnVec[i0])[iZ-1],
5085 (*nnVec[i2])[0], (*nnVec[i1])[iZ], (*nnVec[i1])[iZ-1]);
5087 degenVols.push_back( vol );
5091 case 3: // degen HEX
5093 const SMDS_MeshNode* nn[8];
5094 for ( int iZ = 1; iZ < nbZ; ++iZ )
5096 const SMDS_MeshElement* vol =
5097 helper.AddVolume( nnVec[0]->size() > 1 ? (*nnVec[0])[iZ-1] : (*nnVec[0])[0],
5098 nnVec[1]->size() > 1 ? (*nnVec[1])[iZ-1] : (*nnVec[1])[0],
5099 nnVec[2]->size() > 1 ? (*nnVec[2])[iZ-1] : (*nnVec[2])[0],
5100 nnVec[3]->size() > 1 ? (*nnVec[3])[iZ-1] : (*nnVec[3])[0],
5101 nnVec[0]->size() > 1 ? (*nnVec[0])[iZ] : (*nnVec[0])[0],
5102 nnVec[1]->size() > 1 ? (*nnVec[1])[iZ] : (*nnVec[1])[0],
5103 nnVec[2]->size() > 1 ? (*nnVec[2])[iZ] : (*nnVec[2])[0],
5104 nnVec[3]->size() > 1 ? (*nnVec[3])[iZ] : (*nnVec[3])[0]);
5105 degenVols.push_back( vol );
5113 return error("Not supported type of element", data._index);
5115 } // switch ( nbNodes )
5116 } // while ( fIt->more() )
5119 if ( !degenVols.empty() )
5121 SMESH_ComputeErrorPtr& err = _mesh->GetSubMesh( data._solid )->GetComputeError();
5122 if ( !err || err->IsOK() )
5124 err.reset( new SMESH_ComputeError( COMPERR_WARNING,
5125 "Degenerated volumes created" ));
5126 err->myBadElements.insert( err->myBadElements.end(),
5127 degenVols.begin(),degenVols.end() );
5134 //================================================================================
5136 * \brief Shrink 2D mesh on faces to let space for inflated layers
5138 //================================================================================
5140 bool _ViscousBuilder::shrink()
5142 // make map of (ids of FACEs to shrink mesh on) to (_SolidData containing _LayerEdge's
5143 // inflated along FACE or EDGE)
5144 map< TGeomID, _SolidData* > f2sdMap;
5145 for ( size_t i = 0 ; i < _sdVec.size(); ++i )
5147 _SolidData& data = _sdVec[i];
5148 TopTools_MapOfShape FFMap;
5149 map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
5150 for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
5151 if ( s2s->second.ShapeType() == TopAbs_FACE )
5153 f2sdMap.insert( make_pair( getMeshDS()->ShapeToIndex( s2s->second ), &data ));
5155 if ( FFMap.Add( (*s2s).second ))
5156 // Put mesh faces on the shrinked FACE to the proxy sub-mesh to avoid
5157 // usage of mesh faces made in addBoundaryElements() by the 3D algo or
5158 // by StdMeshers_QuadToTriaAdaptor
5159 if ( SMESHDS_SubMesh* smDS = getMeshDS()->MeshElements( s2s->second ))
5161 SMESH_ProxyMesh::SubMesh* proxySub =
5162 data._proxyMesh->getFaceSubM( TopoDS::Face( s2s->second ), /*create=*/true);
5163 SMDS_ElemIteratorPtr fIt = smDS->GetElements();
5164 while ( fIt->more() )
5165 proxySub->AddElement( fIt->next() );
5166 // as a result 3D algo will use elements from proxySub and not from smDS
5171 SMESH_MesherHelper helper( *_mesh );
5172 helper.ToFixNodeParameters( true );
5175 map< TGeomID, _Shrinker1D > e2shrMap;
5176 vector< _LayerEdge* > lEdges;
5178 // loop on FACES to srink mesh on
5179 map< TGeomID, _SolidData* >::iterator f2sd = f2sdMap.begin();
5180 for ( ; f2sd != f2sdMap.end(); ++f2sd )
5182 _SolidData& data = *f2sd->second;
5183 const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( f2sd->first ));
5184 SMESH_subMesh* sm = _mesh->GetSubMesh( F );
5185 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
5187 Handle(Geom_Surface) surface = BRep_Tool::Surface(F);
5189 helper.SetSubShape(F);
5191 // ===========================
5192 // Prepare data for shrinking
5193 // ===========================
5195 // Collect nodes to smooth, as src nodes are not yet replaced by tgt ones
5196 // and thus all nodes on a FACE connected to 2d elements are to be smoothed
5197 vector < const SMDS_MeshNode* > smoothNodes;
5199 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
5200 while ( nIt->more() )
5202 const SMDS_MeshNode* n = nIt->next();
5203 if ( n->NbInverseElements( SMDSAbs_Face ) > 0 )
5204 smoothNodes.push_back( n );
5207 // Find out face orientation
5209 const set<TGeomID> ignoreShapes;
5211 if ( !smoothNodes.empty() )
5213 vector<_Simplex> simplices;
5214 getSimplices( smoothNodes[0], simplices, ignoreShapes );
5215 helper.GetNodeUV( F, simplices[0]._nPrev, 0, &isOkUV ); // fix UV of silpmex nodes
5216 helper.GetNodeUV( F, simplices[0]._nNext, 0, &isOkUV );
5217 gp_XY uv = helper.GetNodeUV( F, smoothNodes[0], 0, &isOkUV );
5218 if ( !simplices[0].IsForward(uv, smoothNodes[0], F, helper,refSign) )
5222 // Find _LayerEdge's inflated along F
5225 set< TGeomID > subIDs;
5226 SMESH_subMeshIteratorPtr subIt = sm->getDependsOnIterator(/*includeSelf=*/false);
5227 while ( subIt->more() )
5228 subIDs.insert( subIt->next()->GetId() );
5231 for ( int iS = 0; iS < data._endEdgeOnShape.size() && !subIDs.empty(); ++iS )
5234 iEnd = data._endEdgeOnShape[ iS ];
5235 TGeomID shapeID = data._edges[ iBeg ]->_nodes[0]->getshapeId();
5236 set< TGeomID >::iterator idIt = subIDs.find( shapeID );
5237 if ( idIt == subIDs.end() ||
5238 data._edges[ iBeg ]->_sWOL.IsNull() ) continue;
5239 subIDs.erase( idIt );
5241 if ( !data._noShrinkShapes.count( shapeID ))
5242 for ( ; iBeg < iEnd; ++iBeg )
5244 lEdges.push_back( data._edges[ iBeg ] );
5245 prepareEdgeToShrink( *data._edges[ iBeg ], F, helper, smDS );
5250 dumpFunction(SMESH_Comment("beforeShrinkFace")<<f2sd->first); // debug
5251 SMDS_ElemIteratorPtr fIt = smDS->GetElements();
5252 while ( fIt->more() )
5253 if ( const SMDS_MeshElement* f = fIt->next() )
5254 dumpChangeNodes( f );
5256 // Replace source nodes by target nodes in mesh faces to shrink
5257 dumpFunction(SMESH_Comment("replNodesOnFace")<<f2sd->first); // debug
5258 const SMDS_MeshNode* nodes[20];
5259 for ( size_t i = 0; i < lEdges.size(); ++i )
5261 _LayerEdge& edge = *lEdges[i];
5262 const SMDS_MeshNode* srcNode = edge._nodes[0];
5263 const SMDS_MeshNode* tgtNode = edge._nodes.back();
5264 SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
5265 while ( fIt->more() )
5267 const SMDS_MeshElement* f = fIt->next();
5268 if ( !smDS->Contains( f ))
5270 SMDS_NodeIteratorPtr nIt = f->nodeIterator();
5271 for ( int iN = 0; nIt->more(); ++iN )
5273 const SMDS_MeshNode* n = nIt->next();
5274 nodes[iN] = ( n == srcNode ? tgtNode : n );
5276 helper.GetMeshDS()->ChangeElementNodes( f, nodes, f->NbNodes() );
5277 dumpChangeNodes( f );
5281 // find out if a FACE is concave
5282 const bool isConcaveFace = isConcave( F, helper );
5284 // Create _SmoothNode's on face F
5285 vector< _SmoothNode > nodesToSmooth( smoothNodes.size() );
5287 dumpFunction(SMESH_Comment("fixUVOnFace")<<f2sd->first); // debug
5288 const bool sortSimplices = isConcaveFace;
5289 for ( size_t i = 0; i < smoothNodes.size(); ++i )
5291 const SMDS_MeshNode* n = smoothNodes[i];
5292 nodesToSmooth[ i ]._node = n;
5293 // src nodes must be replaced by tgt nodes to have tgt nodes in _simplices
5294 getSimplices( n, nodesToSmooth[ i ]._simplices, ignoreShapes, NULL, sortSimplices );
5295 // fix up incorrect uv of nodes on the FACE
5296 helper.GetNodeUV( F, n, 0, &isOkUV);
5300 //if ( nodesToSmooth.empty() ) continue;
5302 // Find EDGE's to shrink and set simpices to LayerEdge's
5303 set< _Shrinker1D* > eShri1D;
5305 for ( size_t i = 0; i < lEdges.size(); ++i )
5307 _LayerEdge* edge = lEdges[i];
5308 if ( edge->_sWOL.ShapeType() == TopAbs_EDGE )
5310 TGeomID edgeIndex = getMeshDS()->ShapeToIndex( edge->_sWOL );
5311 _Shrinker1D& srinker = e2shrMap[ edgeIndex ];
5312 eShri1D.insert( & srinker );
5313 srinker.AddEdge( edge, helper );
5314 VISCOUS_3D::ToClearSubWithMain( _mesh->GetSubMesh( edge->_sWOL ), data._solid );
5315 // restore params of nodes on EGDE if the EDGE has been already
5316 // srinked while srinking another FACE
5317 srinker.RestoreParams();
5319 getSimplices( /*tgtNode=*/edge->_nodes.back(), edge->_simplices, ignoreShapes );
5323 bool toFixTria = false; // to improve quality of trias by diagonal swap
5324 if ( isConcaveFace )
5326 const bool hasTria = _mesh->NbTriangles(), hasQuad = _mesh->NbQuadrangles();
5327 if ( hasTria != hasQuad ) {
5328 toFixTria = hasTria;
5331 set<int> nbNodesSet;
5332 SMDS_ElemIteratorPtr fIt = smDS->GetElements();
5333 while ( fIt->more() && nbNodesSet.size() < 2 )
5334 nbNodesSet.insert( fIt->next()->NbCornerNodes() );
5335 toFixTria = ( *nbNodesSet.begin() == 3 );
5339 // ==================
5340 // Perform shrinking
5341 // ==================
5343 bool shrinked = true;
5344 int badNb, shriStep=0, smooStep=0;
5345 _SmoothNode::SmoothType smoothType
5346 = isConcaveFace ? _SmoothNode::ANGULAR : _SmoothNode::LAPLACIAN;
5350 // Move boundary nodes (actually just set new UV)
5351 // -----------------------------------------------
5352 dumpFunction(SMESH_Comment("moveBoundaryOnF")<<f2sd->first<<"_st"<<shriStep ); // debug
5354 for ( size_t i = 0; i < lEdges.size(); ++i )
5356 shrinked |= lEdges[i]->SetNewLength2d( surface,F,helper );
5360 // Move nodes on EDGE's
5361 // (XYZ is set as soon as a needed length reached in SetNewLength2d())
5362 set< _Shrinker1D* >::iterator shr = eShri1D.begin();
5363 for ( ; shr != eShri1D.end(); ++shr )
5364 (*shr)->Compute( /*set3D=*/false, helper );
5367 // -----------------
5368 int nbNoImpSteps = 0;
5371 while (( nbNoImpSteps < 5 && badNb > 0) && moved)
5373 dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
5375 int oldBadNb = badNb;
5378 for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
5380 moved |= nodesToSmooth[i].Smooth( badNb,surface,helper,refSign,
5381 smoothType, /*set3D=*/isConcaveFace);
5383 if ( badNb < oldBadNb )
5391 return error(SMESH_Comment("Can't shrink 2D mesh on face ") << f2sd->first );
5392 if ( shriStep > 200 )
5393 return error(SMESH_Comment("Infinite loop at shrinking 2D mesh on face ") << f2sd->first );
5395 // Fix narrow triangles by swapping diagonals
5396 // ---------------------------------------
5399 set<const SMDS_MeshNode*> usedNodes;
5400 fixBadFaces( F, helper, /*is2D=*/true, shriStep, & usedNodes); // swap diagonals
5402 // update working data
5403 set<const SMDS_MeshNode*>::iterator n;
5404 for ( size_t i = 0; i < nodesToSmooth.size() && !usedNodes.empty(); ++i )
5406 n = usedNodes.find( nodesToSmooth[ i ]._node );
5407 if ( n != usedNodes.end())
5409 getSimplices( nodesToSmooth[ i ]._node,
5410 nodesToSmooth[ i ]._simplices,
5412 /*sortSimplices=*/ smoothType == _SmoothNode::ANGULAR );
5413 usedNodes.erase( n );
5416 for ( size_t i = 0; i < lEdges.size() && !usedNodes.empty(); ++i )
5418 n = usedNodes.find( /*tgtNode=*/ lEdges[i]->_nodes.back() );
5419 if ( n != usedNodes.end())
5421 getSimplices( lEdges[i]->_nodes.back(),
5422 lEdges[i]->_simplices,
5424 usedNodes.erase( n );
5428 // TODO: check effect of this additional smooth
5429 // additional laplacian smooth to increase allowed shrink step
5430 // for ( int st = 1; st; --st )
5432 // dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
5433 // for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
5435 // nodesToSmooth[i].Smooth( badNb,surface,helper,refSign,
5436 // _SmoothNode::LAPLACIAN,/*set3D=*/false);
5439 } // while ( shrinked )
5441 // No wrongly shaped faces remain; final smooth. Set node XYZ.
5442 bool isStructuredFixed = false;
5443 if ( SMESH_2D_Algo* algo = dynamic_cast<SMESH_2D_Algo*>( sm->GetAlgo() ))
5444 isStructuredFixed = algo->FixInternalNodes( *data._proxyMesh, F );
5445 if ( !isStructuredFixed )
5447 if ( isConcaveFace ) // fix narrow faces by swapping diagonals
5448 fixBadFaces( F, helper, /*is2D=*/false, ++shriStep );
5450 for ( int st = 3; st; --st )
5453 case 1: smoothType = _SmoothNode::LAPLACIAN; break;
5454 case 2: smoothType = _SmoothNode::LAPLACIAN; break;
5455 case 3: smoothType = _SmoothNode::ANGULAR; break;
5457 dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
5458 for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
5460 nodesToSmooth[i].Smooth( badNb,surface,helper,refSign,
5461 smoothType,/*set3D=*/st==1 );
5466 // Set an event listener to clear FACE sub-mesh together with SOLID sub-mesh
5467 VISCOUS_3D::ToClearSubWithMain( sm, data._solid );
5469 if ( !getMeshDS()->IsEmbeddedMode() )
5470 // Log node movement
5471 for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
5473 SMESH_TNodeXYZ p ( nodesToSmooth[i]._node );
5474 getMeshDS()->MoveNode( nodesToSmooth[i]._node, p.X(), p.Y(), p.Z() );
5477 } // loop on FACES to srink mesh on
5480 // Replace source nodes by target nodes in shrinked mesh edges
5482 map< int, _Shrinker1D >::iterator e2shr = e2shrMap.begin();
5483 for ( ; e2shr != e2shrMap.end(); ++e2shr )
5484 e2shr->second.SwapSrcTgtNodes( getMeshDS() );
5489 //================================================================================
5491 * \brief Computes 2d shrink direction and finds nodes limiting shrinking
5493 //================================================================================
5495 bool _ViscousBuilder::prepareEdgeToShrink( _LayerEdge& edge,
5496 const TopoDS_Face& F,
5497 SMESH_MesherHelper& helper,
5498 const SMESHDS_SubMesh* faceSubMesh)
5500 const SMDS_MeshNode* srcNode = edge._nodes[0];
5501 const SMDS_MeshNode* tgtNode = edge._nodes.back();
5503 if ( edge._sWOL.ShapeType() == TopAbs_FACE )
5505 gp_XY srcUV( edge._pos[0].X(), edge._pos[0].Y() );//helper.GetNodeUV( F, srcNode );
5506 gp_XY tgtUV = edge.LastUV( F ); //helper.GetNodeUV( F, tgtNode );
5507 gp_Vec2d uvDir( srcUV, tgtUV );
5508 double uvLen = uvDir.Magnitude();
5510 edge._normal.SetCoord( uvDir.X(),uvDir.Y(), 0 );
5513 edge._pos.resize(1);
5514 edge._pos[0].SetCoord( tgtUV.X(), tgtUV.Y(), 0 );
5516 // set UV of source node to target node
5517 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
5518 pos->SetUParameter( srcUV.X() );
5519 pos->SetVParameter( srcUV.Y() );
5521 else // _sWOL is TopAbs_EDGE
5523 const TopoDS_Edge& E = TopoDS::Edge( edge._sWOL );
5524 SMESHDS_SubMesh* edgeSM = getMeshDS()->MeshElements( E );
5525 if ( !edgeSM || edgeSM->NbElements() == 0 )
5526 return error(SMESH_Comment("Not meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
5528 const SMDS_MeshNode* n2 = 0;
5529 SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
5530 while ( eIt->more() && !n2 )
5532 const SMDS_MeshElement* e = eIt->next();
5533 if ( !edgeSM->Contains(e)) continue;
5534 n2 = e->GetNode( 0 );
5535 if ( n2 == srcNode ) n2 = e->GetNode( 1 );
5538 return error(SMESH_Comment("Wrongly meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
5540 double uSrc = helper.GetNodeU( E, srcNode, n2 );
5541 double uTgt = helper.GetNodeU( E, tgtNode, srcNode );
5542 double u2 = helper.GetNodeU( E, n2, srcNode );
5546 if ( fabs( uSrc-uTgt ) < 0.99 * fabs( uSrc-u2 ))
5548 // tgtNode is located so that it does not make faces with wrong orientation
5551 edge._pos.resize(1);
5552 edge._pos[0].SetCoord( U_TGT, uTgt );
5553 edge._pos[0].SetCoord( U_SRC, uSrc );
5554 edge._pos[0].SetCoord( LEN_TGT, fabs( uSrc-uTgt ));
5556 edge._simplices.resize( 1 );
5557 edge._simplices[0]._nPrev = n2;
5559 // set U of source node to the target node
5560 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
5561 pos->SetUParameter( uSrc );
5566 //================================================================================
5568 * \brief Restore position of a sole node of a _LayerEdge based on _noShrinkShapes
5570 //================================================================================
5572 void _ViscousBuilder::restoreNoShrink( _LayerEdge& edge ) const
5574 if ( edge._nodes.size() == 1 )
5579 const SMDS_MeshNode* srcNode = edge._nodes[0];
5580 TopoDS_Shape S = SMESH_MesherHelper::GetSubShapeByNode( srcNode, getMeshDS() );
5581 if ( S.IsNull() ) return;
5585 switch ( S.ShapeType() )
5590 TopLoc_Location loc;
5591 Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( S ), loc, f, l );
5592 if ( curve.IsNull() ) return;
5593 SMDS_EdgePosition* ePos = static_cast<SMDS_EdgePosition*>( srcNode->GetPosition() );
5594 p = curve->Value( ePos->GetUParameter() );
5599 p = BRep_Tool::Pnt( TopoDS::Vertex( S ));
5604 getMeshDS()->MoveNode( srcNode, p.X(), p.Y(), p.Z() );
5605 dumpMove( srcNode );
5609 //================================================================================
5611 * \brief Try to fix triangles with high aspect ratio by swaping diagonals
5613 //================================================================================
5615 void _ViscousBuilder::fixBadFaces(const TopoDS_Face& F,
5616 SMESH_MesherHelper& helper,
5619 set<const SMDS_MeshNode*> * involvedNodes)
5621 SMESH::Controls::AspectRatio qualifier;
5622 SMESH::Controls::TSequenceOfXYZ points(3), points1(3), points2(3);
5623 const double maxAspectRatio = is2D ? 4. : 2;
5624 _NodeCoordHelper xyz( F, helper, is2D );
5626 // find bad triangles
5628 vector< const SMDS_MeshElement* > badTrias;
5629 vector< double > badAspects;
5630 SMESHDS_SubMesh* sm = helper.GetMeshDS()->MeshElements( F );
5631 SMDS_ElemIteratorPtr fIt = sm->GetElements();
5632 while ( fIt->more() )
5634 const SMDS_MeshElement * f = fIt->next();
5635 if ( f->NbCornerNodes() != 3 ) continue;
5636 for ( int iP = 0; iP < 3; ++iP ) points(iP+1) = xyz( f->GetNode(iP));
5637 double aspect = qualifier.GetValue( points );
5638 if ( aspect > maxAspectRatio )
5640 badTrias.push_back( f );
5641 badAspects.push_back( aspect );
5646 dumpFunction(SMESH_Comment("beforeSwapDiagonals_F")<<helper.GetSubShapeID());
5647 SMDS_ElemIteratorPtr fIt = sm->GetElements();
5648 while ( fIt->more() )
5650 const SMDS_MeshElement * f = fIt->next();
5651 if ( f->NbCornerNodes() == 3 )
5652 dumpChangeNodes( f );
5656 if ( badTrias.empty() )
5659 // find couples of faces to swap diagonal
5661 typedef pair < const SMDS_MeshElement* , const SMDS_MeshElement* > T2Trias;
5662 vector< T2Trias > triaCouples;
5664 TIDSortedElemSet involvedFaces, emptySet;
5665 for ( size_t iTia = 0; iTia < badTrias.size(); ++iTia )
5668 double aspRatio [3];
5671 if ( !involvedFaces.insert( badTrias[iTia] ).second )
5673 for ( int iP = 0; iP < 3; ++iP )
5674 points(iP+1) = xyz( badTrias[iTia]->GetNode(iP));
5676 // find triangles adjacent to badTrias[iTia] with better aspect ratio after diag-swaping
5677 int bestCouple = -1;
5678 for ( int iSide = 0; iSide < 3; ++iSide )
5680 const SMDS_MeshNode* n1 = badTrias[iTia]->GetNode( iSide );
5681 const SMDS_MeshNode* n2 = badTrias[iTia]->GetNode(( iSide+1 ) % 3 );
5682 trias [iSide].first = badTrias[iTia];
5683 trias [iSide].second = SMESH_MeshAlgos::FindFaceInSet( n1, n2, emptySet, involvedFaces,
5685 if (( ! trias[iSide].second ) ||
5686 ( trias[iSide].second->NbCornerNodes() != 3 ) ||
5687 ( ! sm->Contains( trias[iSide].second )))
5690 // aspect ratio of an adjacent tria
5691 for ( int iP = 0; iP < 3; ++iP )
5692 points2(iP+1) = xyz( trias[iSide].second->GetNode(iP));
5693 double aspectInit = qualifier.GetValue( points2 );
5695 // arrange nodes as after diag-swaping
5696 if ( helper.WrapIndex( i1+1, 3 ) == i2 )
5697 i3 = helper.WrapIndex( i1-1, 3 );
5699 i3 = helper.WrapIndex( i1+1, 3 );
5701 points1( 1+ iSide ) = points2( 1+ i3 );
5702 points2( 1+ i2 ) = points1( 1+ ( iSide+2 ) % 3 );
5704 // aspect ratio after diag-swaping
5705 aspRatio[ iSide ] = qualifier.GetValue( points1 ) + qualifier.GetValue( points2 );
5706 if ( aspRatio[ iSide ] > aspectInit + badAspects[ iTia ] )
5709 // prevent inversion of a triangle
5710 gp_Vec norm1 = gp_Vec( points1(1), points1(3) ) ^ gp_Vec( points1(1), points1(2) );
5711 gp_Vec norm2 = gp_Vec( points2(1), points2(3) ) ^ gp_Vec( points2(1), points2(2) );
5712 if ( norm1 * norm2 < 0. && norm1.Angle( norm2 ) > 70./180.*M_PI )
5715 if ( bestCouple < 0 || aspRatio[ bestCouple ] > aspRatio[ iSide ] )
5719 if ( bestCouple >= 0 )
5721 triaCouples.push_back( trias[bestCouple] );
5722 involvedFaces.insert ( trias[bestCouple].second );
5726 involvedFaces.erase( badTrias[iTia] );
5729 if ( triaCouples.empty() )
5734 SMESH_MeshEditor editor( helper.GetMesh() );
5735 dumpFunction(SMESH_Comment("beforeSwapDiagonals_F")<<helper.GetSubShapeID()<<"_"<<step);
5736 for ( size_t i = 0; i < triaCouples.size(); ++i )
5738 dumpChangeNodes( triaCouples[i].first );
5739 dumpChangeNodes( triaCouples[i].second );
5740 editor.InverseDiag( triaCouples[i].first, triaCouples[i].second );
5743 if ( involvedNodes )
5744 for ( size_t i = 0; i < triaCouples.size(); ++i )
5746 involvedNodes->insert( triaCouples[i].first->begin_nodes(),
5747 triaCouples[i].first->end_nodes() );
5748 involvedNodes->insert( triaCouples[i].second->begin_nodes(),
5749 triaCouples[i].second->end_nodes() );
5752 // just for debug dump resulting triangles
5753 dumpFunction(SMESH_Comment("swapDiagonals_F")<<helper.GetSubShapeID()<<"_"<<step);
5754 for ( size_t i = 0; i < triaCouples.size(); ++i )
5756 dumpChangeNodes( triaCouples[i].first );
5757 dumpChangeNodes( triaCouples[i].second );
5761 //================================================================================
5763 * \brief Move target node to it's final position on the FACE during shrinking
5765 //================================================================================
5767 bool _LayerEdge::SetNewLength2d( Handle(Geom_Surface)& surface,
5768 const TopoDS_Face& F,
5769 SMESH_MesherHelper& helper )
5772 return false; // already at the target position
5774 SMDS_MeshNode* tgtNode = const_cast< SMDS_MeshNode*& >( _nodes.back() );
5776 if ( _sWOL.ShapeType() == TopAbs_FACE )
5778 gp_XY curUV = helper.GetNodeUV( F, tgtNode );
5779 gp_Pnt2d tgtUV( _pos[0].X(), _pos[0].Y() );
5780 gp_Vec2d uvDir( _normal.X(), _normal.Y() );
5781 const double uvLen = tgtUV.Distance( curUV );
5782 const double kSafe = Max( 0.5, 1. - 0.1 * _simplices.size() );
5784 // Select shrinking step such that not to make faces with wrong orientation.
5785 double stepSize = 1e100;
5786 for ( size_t i = 0; i < _simplices.size(); ++i )
5788 // find intersection of 2 lines: curUV-tgtUV and that connecting simplex nodes
5789 gp_XY uvN1 = helper.GetNodeUV( F, _simplices[i]._nPrev );
5790 gp_XY uvN2 = helper.GetNodeUV( F, _simplices[i]._nNext );
5791 gp_XY dirN = uvN2 - uvN1;
5792 double det = uvDir.Crossed( dirN );
5793 if ( Abs( det ) < std::numeric_limits<double>::min() ) continue;
5794 gp_XY dirN2Cur = curUV - uvN1;
5795 double step = dirN.Crossed( dirN2Cur ) / det;
5797 stepSize = Min( step, stepSize );
5800 if ( uvLen <= stepSize )
5805 else if ( stepSize > 0 )
5807 newUV = curUV + uvDir.XY() * stepSize * kSafe;
5813 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
5814 pos->SetUParameter( newUV.X() );
5815 pos->SetVParameter( newUV.Y() );
5818 gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
5819 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
5820 dumpMove( tgtNode );
5823 else // _sWOL is TopAbs_EDGE
5825 const TopoDS_Edge& E = TopoDS::Edge( _sWOL );
5826 const SMDS_MeshNode* n2 = _simplices[0]._nPrev;
5827 SMDS_EdgePosition* tgtPos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
5829 const double u2 = helper.GetNodeU( E, n2, tgtNode );
5830 const double uSrc = _pos[0].Coord( U_SRC );
5831 const double lenTgt = _pos[0].Coord( LEN_TGT );
5833 double newU = _pos[0].Coord( U_TGT );
5834 if ( lenTgt < 0.99 * fabs( uSrc-u2 )) // n2 got out of src-tgt range
5840 newU = 0.1 * tgtPos->GetUParameter() + 0.9 * u2;
5842 tgtPos->SetUParameter( newU );
5844 gp_XY newUV = helper.GetNodeUV( F, tgtNode, _nodes[0]);
5845 gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
5846 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
5847 dumpMove( tgtNode );
5853 //================================================================================
5855 * \brief Perform smooth on the FACE
5856 * \retval bool - true if the node has been moved
5858 //================================================================================
5860 bool _SmoothNode::Smooth(int& badNb,
5861 Handle(Geom_Surface)& surface,
5862 SMESH_MesherHelper& helper,
5863 const double refSign,
5867 const TopoDS_Face& face = TopoDS::Face( helper.GetSubShape() );
5869 // get uv of surrounding nodes
5870 vector<gp_XY> uv( _simplices.size() );
5871 for ( size_t i = 0; i < _simplices.size(); ++i )
5872 uv[i] = helper.GetNodeUV( face, _simplices[i]._nPrev, _node );
5874 // compute new UV for the node
5876 if ( how == TFI && _simplices.size() == 4 )
5879 for ( size_t i = 0; i < _simplices.size(); ++i )
5880 if ( _simplices[i]._nOpp )
5881 corners[i] = helper.GetNodeUV( face, _simplices[i]._nOpp, _node );
5883 throw SALOME_Exception(LOCALIZED("TFI smoothing: _Simplex::_nOpp not set!"));
5885 newPos = helper.calcTFI ( 0.5, 0.5,
5886 corners[0], corners[1], corners[2], corners[3],
5887 uv[1], uv[2], uv[3], uv[0] );
5889 else if ( how == ANGULAR )
5891 newPos = computeAngularPos( uv, helper.GetNodeUV( face, _node ), refSign );
5893 else if ( how == CENTROIDAL && _simplices.size() > 3 )
5895 // average centers of diagonals wieghted with their reciprocal lengths
5896 if ( _simplices.size() == 4 )
5898 double w1 = 1. / ( uv[2]-uv[0] ).SquareModulus();
5899 double w2 = 1. / ( uv[3]-uv[1] ).SquareModulus();
5900 newPos = ( w1 * ( uv[2]+uv[0] ) + w2 * ( uv[3]+uv[1] )) / ( w1+w2 ) / 2;
5904 double sumWeight = 0;
5905 int nb = _simplices.size() == 4 ? 2 : _simplices.size();
5906 for ( int i = 0; i < nb; ++i )
5909 int iTo = i + _simplices.size() - 1;
5910 for ( int j = iFrom; j < iTo; ++j )
5912 int i2 = SMESH_MesherHelper::WrapIndex( j, _simplices.size() );
5913 double w = 1. / ( uv[i]-uv[i2] ).SquareModulus();
5915 newPos += w * ( uv[i]+uv[i2] );
5918 newPos /= 2 * sumWeight; // 2 is to get a middle between uv's
5924 for ( size_t i = 0; i < _simplices.size(); ++i )
5926 newPos /= _simplices.size();
5929 // count quality metrics (orientation) of triangles around the node
5931 gp_XY tgtUV = helper.GetNodeUV( face, _node );
5932 for ( size_t i = 0; i < _simplices.size(); ++i )
5933 nbOkBefore += _simplices[i].IsForward( tgtUV, _node, face, helper, refSign );
5936 for ( size_t i = 0; i < _simplices.size(); ++i )
5937 nbOkAfter += _simplices[i].IsForward( newPos, _node, face, helper, refSign );
5939 if ( nbOkAfter < nbOkBefore )
5941 badNb += _simplices.size() - nbOkBefore;
5945 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( _node->GetPosition() );
5946 pos->SetUParameter( newPos.X() );
5947 pos->SetVParameter( newPos.Y() );
5954 gp_Pnt p = surface->Value( newPos.X(), newPos.Y() );
5955 const_cast< SMDS_MeshNode* >( _node )->setXYZ( p.X(), p.Y(), p.Z() );
5959 badNb += _simplices.size() - nbOkAfter;
5960 return ( (tgtUV-newPos).SquareModulus() > 1e-10 );
5963 //================================================================================
5965 * \brief Computes new UV using angle based smoothing technic
5967 //================================================================================
5969 gp_XY _SmoothNode::computeAngularPos(vector<gp_XY>& uv,
5970 const gp_XY& uvToFix,
5971 const double refSign)
5973 uv.push_back( uv.front() );
5975 vector< gp_XY > edgeDir ( uv.size() );
5976 vector< double > edgeSize( uv.size() );
5977 for ( size_t i = 1; i < edgeDir.size(); ++i )
5979 edgeDir [i-1] = uv[i] - uv[i-1];
5980 edgeSize[i-1] = edgeDir[i-1].Modulus();
5981 if ( edgeSize[i-1] < numeric_limits<double>::min() )
5982 edgeDir[i-1].SetX( 100 );
5984 edgeDir[i-1] /= edgeSize[i-1] * refSign;
5986 edgeDir.back() = edgeDir.front();
5987 edgeSize.back() = edgeSize.front();
5992 for ( size_t i = 1; i < edgeDir.size(); ++i )
5994 if ( edgeDir[i-1].X() > 1. ) continue;
5996 while ( edgeDir[i].X() > 1. && ++i < edgeDir.size() );
5997 if ( i == edgeDir.size() ) break;
5999 gp_XY norm1( -edgeDir[i1].Y(), edgeDir[i1].X() );
6000 gp_XY norm2( -edgeDir[i].Y(), edgeDir[i].X() );
6001 gp_XY bisec = norm1 + norm2;
6002 double bisecSize = bisec.Modulus();
6003 if ( bisecSize < numeric_limits<double>::min() )
6005 bisec = -edgeDir[i1] + edgeDir[i];
6006 bisecSize = bisec.Modulus();
6010 gp_XY dirToN = uvToFix - p;
6011 double distToN = dirToN.Modulus();
6012 if ( bisec * dirToN < 0 )
6015 newPos += ( p + bisec * distToN ) * ( edgeSize[i1] + edgeSize[i] );
6017 sumSize += edgeSize[i1] + edgeSize[i];
6019 newPos /= /*nbEdges * */sumSize;
6023 //================================================================================
6025 * \brief Delete _SolidData
6027 //================================================================================
6029 _SolidData::~_SolidData()
6031 for ( size_t i = 0; i < _edges.size(); ++i )
6033 if ( _edges[i] && _edges[i]->_2neibors )
6034 delete _edges[i]->_2neibors;
6039 //================================================================================
6041 * \brief Add a _LayerEdge inflated along the EDGE
6043 //================================================================================
6045 void _Shrinker1D::AddEdge( const _LayerEdge* e, SMESH_MesherHelper& helper )
6048 if ( _nodes.empty() )
6050 _edges[0] = _edges[1] = 0;
6054 if ( e == _edges[0] || e == _edges[1] )
6056 if ( e->_sWOL.IsNull() || e->_sWOL.ShapeType() != TopAbs_EDGE )
6057 throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
6058 if ( _edges[0] && _edges[0]->_sWOL != e->_sWOL )
6059 throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
6062 const TopoDS_Edge& E = TopoDS::Edge( e->_sWOL );
6064 BRep_Tool::Range( E, f,l );
6065 double u = helper.GetNodeU( E, e->_nodes[0], e->_nodes.back());
6066 _edges[ u < 0.5*(f+l) ? 0 : 1 ] = e;
6070 const SMDS_MeshNode* tgtNode0 = _edges[0] ? _edges[0]->_nodes.back() : 0;
6071 const SMDS_MeshNode* tgtNode1 = _edges[1] ? _edges[1]->_nodes.back() : 0;
6073 if ( _nodes.empty() )
6075 SMESHDS_SubMesh * eSubMesh = helper.GetMeshDS()->MeshElements( E );
6076 if ( !eSubMesh || eSubMesh->NbNodes() < 1 )
6078 TopLoc_Location loc;
6079 Handle(Geom_Curve) C = BRep_Tool::Curve(E, loc, f,l);
6080 GeomAdaptor_Curve aCurve(C, f,l);
6081 const double totLen = GCPnts_AbscissaPoint::Length(aCurve, f, l);
6083 int nbExpectNodes = eSubMesh->NbNodes();
6084 _initU .reserve( nbExpectNodes );
6085 _normPar.reserve( nbExpectNodes );
6086 _nodes .reserve( nbExpectNodes );
6087 SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
6088 while ( nIt->more() )
6090 const SMDS_MeshNode* node = nIt->next();
6091 if ( node->NbInverseElements(SMDSAbs_Edge) == 0 ||
6092 node == tgtNode0 || node == tgtNode1 )
6093 continue; // refinement nodes
6094 _nodes.push_back( node );
6095 _initU.push_back( helper.GetNodeU( E, node ));
6096 double len = GCPnts_AbscissaPoint::Length(aCurve, f, _initU.back());
6097 _normPar.push_back( len / totLen );
6102 // remove target node of the _LayerEdge from _nodes
6104 for ( size_t i = 0; i < _nodes.size(); ++i )
6105 if ( !_nodes[i] || _nodes[i] == tgtNode0 || _nodes[i] == tgtNode1 )
6106 _nodes[i] = 0, nbFound++;
6107 if ( nbFound == _nodes.size() )
6112 //================================================================================
6114 * \brief Move nodes on EDGE from ends where _LayerEdge's are inflated
6116 //================================================================================
6118 void _Shrinker1D::Compute(bool set3D, SMESH_MesherHelper& helper)
6120 if ( _done || _nodes.empty())
6122 const _LayerEdge* e = _edges[0];
6123 if ( !e ) e = _edges[1];
6126 _done = (( !_edges[0] || _edges[0]->_pos.empty() ) &&
6127 ( !_edges[1] || _edges[1]->_pos.empty() ));
6129 const TopoDS_Edge& E = TopoDS::Edge( e->_sWOL );
6131 if ( set3D || _done )
6133 Handle(Geom_Curve) C = BRep_Tool::Curve(E, f,l);
6134 GeomAdaptor_Curve aCurve(C, f,l);
6137 f = helper.GetNodeU( E, _edges[0]->_nodes.back(), _nodes[0] );
6139 l = helper.GetNodeU( E, _edges[1]->_nodes.back(), _nodes.back() );
6140 double totLen = GCPnts_AbscissaPoint::Length( aCurve, f, l );
6142 for ( size_t i = 0; i < _nodes.size(); ++i )
6144 if ( !_nodes[i] ) continue;
6145 double len = totLen * _normPar[i];
6146 GCPnts_AbscissaPoint discret( aCurve, len, f );
6147 if ( !discret.IsDone() )
6148 return throw SALOME_Exception(LOCALIZED("GCPnts_AbscissaPoint failed"));
6149 double u = discret.Parameter();
6150 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
6151 pos->SetUParameter( u );
6152 gp_Pnt p = C->Value( u );
6153 const_cast< SMDS_MeshNode*>( _nodes[i] )->setXYZ( p.X(), p.Y(), p.Z() );
6158 BRep_Tool::Range( E, f,l );
6160 f = helper.GetNodeU( E, _edges[0]->_nodes.back(), _nodes[0] );
6162 l = helper.GetNodeU( E, _edges[1]->_nodes.back(), _nodes.back() );
6164 for ( size_t i = 0; i < _nodes.size(); ++i )
6166 if ( !_nodes[i] ) continue;
6167 double u = f * ( 1-_normPar[i] ) + l * _normPar[i];
6168 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
6169 pos->SetUParameter( u );
6174 //================================================================================
6176 * \brief Restore initial parameters of nodes on EDGE
6178 //================================================================================
6180 void _Shrinker1D::RestoreParams()
6183 for ( size_t i = 0; i < _nodes.size(); ++i )
6185 if ( !_nodes[i] ) continue;
6186 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
6187 pos->SetUParameter( _initU[i] );
6192 //================================================================================
6194 * \brief Replace source nodes by target nodes in shrinked mesh edges
6196 //================================================================================
6198 void _Shrinker1D::SwapSrcTgtNodes( SMESHDS_Mesh* mesh )
6200 const SMDS_MeshNode* nodes[3];
6201 for ( int i = 0; i < 2; ++i )
6203 if ( !_edges[i] ) continue;
6205 SMESHDS_SubMesh * eSubMesh = mesh->MeshElements( _edges[i]->_sWOL );
6206 if ( !eSubMesh ) return;
6207 const SMDS_MeshNode* srcNode = _edges[i]->_nodes[0];
6208 const SMDS_MeshNode* tgtNode = _edges[i]->_nodes.back();
6209 SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
6210 while ( eIt->more() )
6212 const SMDS_MeshElement* e = eIt->next();
6213 if ( !eSubMesh->Contains( e ))
6215 SMDS_ElemIteratorPtr nIt = e->nodesIterator();
6216 for ( int iN = 0; iN < e->NbNodes(); ++iN )
6218 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
6219 nodes[iN] = ( n == srcNode ? tgtNode : n );
6221 mesh->ChangeElementNodes( e, nodes, e->NbNodes() );
6226 //================================================================================
6228 * \brief Creates 2D and 1D elements on boundaries of new prisms
6230 //================================================================================
6232 bool _ViscousBuilder::addBoundaryElements()
6234 SMESH_MesherHelper helper( *_mesh );
6236 vector< const SMDS_MeshNode* > faceNodes;
6238 for ( size_t i = 0; i < _sdVec.size(); ++i )
6240 _SolidData& data = _sdVec[i];
6241 TopTools_IndexedMapOfShape geomEdges;
6242 TopExp::MapShapes( data._solid, TopAbs_EDGE, geomEdges );
6243 for ( int iE = 1; iE <= geomEdges.Extent(); ++iE )
6245 const TopoDS_Edge& E = TopoDS::Edge( geomEdges(iE));
6246 if ( data._noShrinkShapes.count( getMeshDS()->ShapeToIndex( E )))
6249 // Get _LayerEdge's based on E
6251 map< double, const SMDS_MeshNode* > u2nodes;
6252 if ( !SMESH_Algo::GetSortedNodesOnEdge( getMeshDS(), E, /*ignoreMedium=*/false, u2nodes))
6255 vector< _LayerEdge* > ledges; ledges.reserve( u2nodes.size() );
6256 TNode2Edge & n2eMap = data._n2eMap;
6257 map< double, const SMDS_MeshNode* >::iterator u2n = u2nodes.begin();
6259 //check if 2D elements are needed on E
6260 TNode2Edge::iterator n2e = n2eMap.find( u2n->second );
6261 if ( n2e == n2eMap.end() ) continue; // no layers on vertex
6262 ledges.push_back( n2e->second );
6264 if (( n2e = n2eMap.find( u2n->second )) == n2eMap.end() )
6265 continue; // no layers on E
6266 ledges.push_back( n2eMap[ u2n->second ]);
6268 const SMDS_MeshNode* tgtN0 = ledges[0]->_nodes.back();
6269 const SMDS_MeshNode* tgtN1 = ledges[1]->_nodes.back();
6270 int nbSharedPyram = 0;
6271 SMDS_ElemIteratorPtr vIt = tgtN0->GetInverseElementIterator(SMDSAbs_Volume);
6272 while ( vIt->more() )
6274 const SMDS_MeshElement* v = vIt->next();
6275 nbSharedPyram += int( v->GetNodeIndex( tgtN1 ) >= 0 );
6277 if ( nbSharedPyram > 1 )
6278 continue; // not free border of the pyramid
6281 faceNodes.push_back( ledges[0]->_nodes[0] );
6282 faceNodes.push_back( ledges[1]->_nodes[0] );
6283 if ( ledges[0]->_nodes.size() > 1 ) faceNodes.push_back( ledges[0]->_nodes[1] );
6284 if ( ledges[1]->_nodes.size() > 1 ) faceNodes.push_back( ledges[1]->_nodes[1] );
6286 if ( getMeshDS()->FindElement( faceNodes, SMDSAbs_Face, /*noMedium=*/true))
6287 continue; // faces already created
6289 for ( ++u2n; u2n != u2nodes.end(); ++u2n )
6290 ledges.push_back( n2eMap[ u2n->second ]);
6292 // Find out orientation and type of face to create
6294 bool reverse = false, isOnFace;
6296 map< TGeomID, TopoDS_Shape >::iterator e2f =
6297 data._shrinkShape2Shape.find( getMeshDS()->ShapeToIndex( E ));
6299 if (( isOnFace = ( e2f != data._shrinkShape2Shape.end() )))
6301 F = e2f->second.Oriented( TopAbs_FORWARD );
6302 reverse = ( helper.GetSubShapeOri( F, E ) == TopAbs_REVERSED );
6303 if ( helper.GetSubShapeOri( data._solid, F ) == TopAbs_REVERSED )
6304 reverse = !reverse, F.Reverse();
6305 if ( helper.IsReversedSubMesh( TopoDS::Face(F) ))
6310 // find FACE with layers sharing E
6311 PShapeIteratorPtr fIt = helper.GetAncestors( E, *_mesh, TopAbs_FACE );
6312 while ( fIt->more() && F.IsNull() )
6314 const TopoDS_Shape* pF = fIt->next();
6315 if ( helper.IsSubShape( *pF, data._solid) &&
6316 !data._ignoreFaceIds.count( e2f->first ))
6320 // Find the sub-mesh to add new faces
6321 SMESHDS_SubMesh* sm = 0;
6323 sm = getMeshDS()->MeshElements( F );
6325 sm = data._proxyMesh->getFaceSubM( TopoDS::Face(F), /*create=*/true );
6327 return error("error in addBoundaryElements()", data._index);
6330 const int dj1 = reverse ? 0 : 1;
6331 const int dj2 = reverse ? 1 : 0;
6332 for ( size_t j = 1; j < ledges.size(); ++j )
6334 vector< const SMDS_MeshNode*>& nn1 = ledges[j-dj1]->_nodes;
6335 vector< const SMDS_MeshNode*>& nn2 = ledges[j-dj2]->_nodes;
6336 if ( nn1.size() == nn2.size() )
6339 for ( size_t z = 1; z < nn1.size(); ++z )
6340 sm->AddElement( getMeshDS()->AddFace( nn1[z-1], nn2[z-1], nn2[z], nn1[z] ));
6342 for ( size_t z = 1; z < nn1.size(); ++z )
6343 sm->AddElement( new SMDS_FaceOfNodes( nn1[z-1], nn2[z-1], nn2[z], nn1[z] ));
6345 else if ( nn1.size() == 1 )
6348 for ( size_t z = 1; z < nn2.size(); ++z )
6349 sm->AddElement( getMeshDS()->AddFace( nn1[0], nn2[z-1], nn2[z] ));
6351 for ( size_t z = 1; z < nn2.size(); ++z )
6352 sm->AddElement( new SMDS_FaceOfNodes( nn1[0], nn2[z-1], nn2[z] ));
6357 for ( size_t z = 1; z < nn1.size(); ++z )
6358 sm->AddElement( getMeshDS()->AddFace( nn1[z-1], nn2[0], nn1[z] ));
6360 for ( size_t z = 1; z < nn1.size(); ++z )
6361 sm->AddElement( new SMDS_FaceOfNodes( nn1[z-1], nn2[0], nn2[z] ));
6366 for ( int isFirst = 0; isFirst < 2; ++isFirst )
6368 _LayerEdge* edge = isFirst ? ledges.front() : ledges.back();
6369 if ( !edge->_sWOL.IsNull() && edge->_sWOL.ShapeType() == TopAbs_EDGE )
6371 vector< const SMDS_MeshNode*>& nn = edge->_nodes;
6372 if ( nn.size() < 2 || nn[1]->GetInverseElementIterator( SMDSAbs_Edge )->more() )
6374 helper.SetSubShape( edge->_sWOL );
6375 helper.SetElementsOnShape( true );
6376 for ( size_t z = 1; z < nn.size(); ++z )
6377 helper.AddEdge( nn[z-1], nn[z] );