1 // Copyright (C) 2007-2016 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_ViscousLayers2D.cxx
21 // Created : 23 Jul 2012
22 // Author : Edward AGAPOV (eap)
24 #include "StdMeshers_ViscousLayers2D.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_MesherHelper.hxx"
41 #include "SMESH_ProxyMesh.hxx"
42 #include "SMESH_Quadtree.hxx"
43 #include "SMESH_subMesh.hxx"
44 #include "SMESH_subMeshEventListener.hxx"
45 #include "StdMeshers_FaceSide.hxx"
47 #include "utilities.h"
49 #include <BRepAdaptor_Curve.hxx>
50 #include <BRepAdaptor_Curve2d.hxx>
51 #include <BRep_Tool.hxx>
52 #include <Bnd_B2d.hxx>
53 #include <Bnd_B3d.hxx>
55 #include <GCPnts_AbscissaPoint.hxx>
56 #include <Geom2dAdaptor_Curve.hxx>
57 #include <Geom2dInt_GInter.hxx>
58 #include <Geom2d_Circle.hxx>
59 #include <Geom2d_Line.hxx>
60 #include <Geom2d_TrimmedCurve.hxx>
61 #include <GeomAdaptor_Curve.hxx>
62 #include <Geom_Circle.hxx>
63 #include <Geom_Curve.hxx>
64 #include <Geom_Line.hxx>
65 #include <Geom_TrimmedCurve.hxx>
66 #include <IntRes2d_IntersectionPoint.hxx>
67 #include <Precision.hxx>
68 #include <Standard_ErrorHandler.hxx>
69 #include <TColStd_Array1OfReal.hxx>
71 #include <TopExp_Explorer.hxx>
72 #include <TopTools_IndexedDataMapOfShapeListOfShape.hxx>
73 #include <TopTools_IndexedMapOfShape.hxx>
74 #include <TopTools_ListIteratorOfListOfShape.hxx>
75 #include <TopTools_ListOfShape.hxx>
76 #include <TopTools_MapOfShape.hxx>
78 #include <TopoDS_Edge.hxx>
79 #include <TopoDS_Face.hxx>
80 #include <TopoDS_Vertex.hxx>
96 //================================================================================
101 //--------------------------------------------------------------------------------
103 * \brief Proxy Mesh of FACE with viscous layers. It's needed only to
104 * redefine newSubmesh().
106 struct _ProxyMeshOfFace : public SMESH_ProxyMesh
108 //---------------------------------------------------
109 // Proxy sub-mesh of an EDGE. It contains nodes in _uvPtStructVec.
110 struct _EdgeSubMesh : public SMESH_ProxyMesh::SubMesh
112 _EdgeSubMesh(int index=0): SubMesh(index) {}
113 //virtual int NbElements() const { return _elements.size()+1; }
114 virtual int NbNodes() const { return Max( 0, _uvPtStructVec.size()-2 ); }
115 void SetUVPtStructVec(UVPtStructVec& vec) { _uvPtStructVec.swap( vec ); }
116 UVPtStructVec& GetUVPtStructVec() { return _uvPtStructVec; }
118 _ProxyMeshOfFace(const SMESH_Mesh& mesh): SMESH_ProxyMesh(mesh) {}
119 _EdgeSubMesh* GetEdgeSubMesh(int ID) { return (_EdgeSubMesh*) getProxySubMesh(ID); }
120 virtual SubMesh* newSubmesh(int index=0) const { return new _EdgeSubMesh(index); }
122 //--------------------------------------------------------------------------------
124 * \brief SMESH_subMeshEventListener used to store _ProxyMeshOfFace, computed
125 * by _ViscousBuilder2D, in a SMESH_subMesh of the FACE.
126 * This is to delete _ProxyMeshOfFace when StdMeshers_ViscousLayers2D
127 * hypothesis is modified
129 struct _ProxyMeshHolder : public SMESH_subMeshEventListener
131 _ProxyMeshHolder( const TopoDS_Face& face,
132 SMESH_ProxyMesh::Ptr& mesh)
133 : SMESH_subMeshEventListener( /*deletable=*/true, Name() )
135 SMESH_subMesh* faceSM = mesh->GetMesh()->GetSubMesh( face );
136 faceSM->SetEventListener( this, new _Data( mesh ), faceSM );
138 // Finds a proxy mesh of face
139 static SMESH_ProxyMesh::Ptr FindProxyMeshOfFace( const TopoDS_Shape& face,
142 SMESH_ProxyMesh::Ptr proxy;
143 SMESH_subMesh* faceSM = mesh.GetSubMesh( face );
144 if ( EventListenerData* ld = faceSM->GetEventListenerData( Name() ))
145 proxy = static_cast< _Data* >( ld )->_mesh;
149 void ProcessEvent(const int event,
151 SMESH_subMesh* subMesh,
152 EventListenerData* data,
153 const SMESH_Hypothesis* /*hyp*/)
155 if ( event == SMESH_subMesh::CLEAN && eventType == SMESH_subMesh::COMPUTE_EVENT)
156 ((_Data*) data)->_mesh.reset();
159 // holder of a proxy mesh
160 struct _Data : public SMESH_subMeshEventListenerData
162 SMESH_ProxyMesh::Ptr _mesh;
163 _Data( SMESH_ProxyMesh::Ptr& mesh )
164 :SMESH_subMeshEventListenerData( /*isDeletable=*/true), _mesh( mesh )
167 // Returns identifier string
168 static const char* Name() { return "VISCOUS_2D::_ProxyMeshHolder"; }
172 //--------------------------------------------------------------------------------
174 * \brief Segment connecting inner ends of two _LayerEdge's.
178 const gp_XY* _uv[2]; // poiter to _LayerEdge::_uvIn
179 int _indexInLine; // position in _PolyLine
182 _Segment(const gp_XY& p1, const gp_XY& p2):_indexInLine(-1) { _uv[0] = &p1; _uv[1] = &p2; }
183 const gp_XY& p1() const { return *_uv[0]; }
184 const gp_XY& p2() const { return *_uv[1]; }
186 //--------------------------------------------------------------------------------
188 * \brief Tree of _Segment's used for a faster search of _Segment's.
190 struct _SegmentTree : public SMESH_Quadtree
192 typedef boost::shared_ptr< _SegmentTree > Ptr;
194 _SegmentTree( const vector< _Segment >& segments );
195 void GetSegmentsNear( const _Segment& seg, vector< const _Segment* >& found );
196 void GetSegmentsNear( const gp_Ax2d& ray, vector< const _Segment* >& found );
199 _SegmentTree* newChild() const { return new _SegmentTree; }
200 void buildChildrenData();
201 Bnd_B2d* buildRootBox();
203 static int maxNbSegInLeaf() { return 5; }
206 const _Segment* _seg;
208 void Set( const _Segment& seg )
211 _iMin[0] = ( seg._uv[1]->X() < seg._uv[0]->X() );
212 _iMin[1] = ( seg._uv[1]->Y() < seg._uv[0]->Y() );
214 bool IsOut( const _Segment& seg ) const;
215 bool IsOut( const gp_Ax2d& ray ) const;
217 vector< _SegBox > _segments;
219 //--------------------------------------------------------------------------------
221 * \brief Edge normal to FACE boundary, connecting a point on EDGE (_uvOut)
222 * and a point of a layer internal boundary (_uvIn)
226 gp_XY _uvOut; // UV on the FACE boundary
227 gp_XY _uvIn; // UV inside the FACE
228 double _length2D; // distance between _uvOut and _uvIn
230 bool _isBlocked;// is more inflation possible or not
232 gp_XY _normal2D; // to curve
233 double _len2dTo3dRatio; // to pass 2D <--> 3D
234 gp_Ax2d _ray; // a ray starting at _uvOut
236 vector<gp_XY> _uvRefined; // divisions by layers
238 bool SetNewLength( const double length );
244 //--------------------------------------------------------------------------------
246 * \brief Poly line composed of _Segment's of one EDGE.
247 * It's used to detect intersection of inflated layers by intersecting
252 StdMeshers_FaceSide* _wire;
253 int _edgeInd; // index of my EDGE in _wire
254 bool _advancable; // true if there is a viscous layer on my EDGE
255 bool _isStraight2D;// pcurve type
256 _PolyLine* _leftLine; // lines of neighbour EDGE's
257 _PolyLine* _rightLine;
258 int _firstPntInd; // index in vector<UVPtStruct> of _wire
260 int _index; // index in _ViscousBuilder2D::_polyLineVec
262 vector< _LayerEdge > _lEdges; /* _lEdges[0] is usually is not treated
263 as it is equal to the last one of the _leftLine */
264 vector< _Segment > _segments; // segments connecting _uvIn's of _lEdges
265 _SegmentTree::Ptr _segTree;
267 vector< _PolyLine* > _reachableLines; // lines able to interfere with my layer
269 vector< const SMDS_MeshNode* > _leftNodes; // nodes built from a left VERTEX
270 vector< const SMDS_MeshNode* > _rightNodes; // nodes built from a right VERTEX
272 typedef vector< _Segment >::iterator TSegIterator;
273 typedef vector< _LayerEdge >::iterator TEdgeIterator;
275 TIDSortedElemSet _newFaces; // faces generated from this line
277 bool IsCommonEdgeShared( const _PolyLine& other );
278 size_t FirstLEdge() const
280 return ( _leftLine->_advancable && _lEdges.size() > 2 ) ? 1 : 0;
282 bool IsAdjacent( const _Segment& seg, const _LayerEdge* LE=0 ) const
284 if ( LE /*&& seg._indexInLine < _lEdges.size()*/ )
285 return ( seg._uv[0] == & LE->_uvIn ||
286 seg._uv[1] == & LE->_uvIn );
287 return ( & seg == &_leftLine->_segments.back() ||
288 & seg == &_rightLine->_segments[0] );
290 bool IsConcave() const;
292 //--------------------------------------------------------------------------------
294 * \brief Intersector of _Segment's
296 struct _SegmentIntersection
298 gp_XY _vec1, _vec2; // Vec( _seg.p1(), _seg.p2() )
299 gp_XY _vec21; // Vec( _seg2.p1(), _seg1.p1() )
300 double _D; // _vec1.Crossed( _vec2 )
301 double _param1, _param2; // intersection param on _seg1 and _seg2
303 bool Compute(const _Segment& seg1, const _Segment& seg2, bool seg2IsRay = false )
305 // !!! If seg2IsRay, returns true at any _param2 !!!
306 const double eps = 1e-10;
307 _vec1 = seg1.p2() - seg1.p1();
308 _vec2 = seg2.p2() - seg2.p1();
309 _vec21 = seg1.p1() - seg2.p1();
310 _D = _vec1.Crossed(_vec2);
311 if ( fabs(_D) < std::numeric_limits<double>::min())
313 _param1 = _vec2.Crossed(_vec21) / _D;
314 if (_param1 < -eps || _param1 > 1 + eps )
316 _param2 = _vec1.Crossed(_vec21) / _D;
317 return seg2IsRay || ( _param2 > -eps && _param2 < 1 + eps );
319 bool Compute( const _Segment& seg1, const gp_Ax2d& ray )
321 gp_XY segEnd = ray.Location().XY() + ray.Direction().XY();
322 _Segment seg2( ray.Location().XY(), segEnd );
323 return Compute( seg1, seg2, true );
325 //gp_XY GetPoint() { return _seg1.p1() + _param1 * _vec1; }
327 //--------------------------------------------------------------------------------
329 typedef map< const SMDS_MeshNode*, _LayerEdge*, TIDCompare > TNode2Edge;
330 typedef StdMeshers_ViscousLayers2D THypVL;
332 //--------------------------------------------------------------------------------
334 * \brief Builder of viscous layers
336 class _ViscousBuilder2D
339 _ViscousBuilder2D(SMESH_Mesh& theMesh,
340 const TopoDS_Face& theFace,
341 vector< const THypVL* > & theHyp,
342 vector< TopoDS_Shape > & theHypShapes);
343 SMESH_ComputeErrorPtr GetError() const { return _error; }
345 SMESH_ProxyMesh::Ptr Compute();
349 friend class ::StdMeshers_ViscousLayers2D;
351 bool findEdgesWithLayers();
352 bool makePolyLines();
354 bool fixCollisions();
358 bool toShrinkForAdjacent( const TopoDS_Face& adjFace,
359 const TopoDS_Edge& E,
360 const TopoDS_Vertex& V);
361 void setLenRatio( _LayerEdge& LE, const gp_Pnt& pOut );
362 void setLayerEdgeData( _LayerEdge& lEdge,
364 Handle(Geom2d_Curve)& pcurve,
365 Handle(Geom_Curve)& curve,
368 GeomAPI_ProjectPointOnSurf* faceProj);
369 void adjustCommonEdge( _PolyLine& LL, _PolyLine& LR );
370 void calcLayersHeight(const double totalThick,
371 vector<double>& heights,
373 bool removeMeshFaces(const TopoDS_Shape& face);
375 const THypVL* getLineHypothesis(int iPL);
376 double getLineThickness (int iPL);
378 bool error( const string& text );
379 SMESHDS_Mesh* getMeshDS() { return _mesh->GetMeshDS(); }
380 _ProxyMeshOfFace* getProxyMesh();
383 //void makeGroupOfLE();
390 vector< const THypVL* > _hyps;
391 vector< TopoDS_Shape > _hypShapes;
394 SMESH_ProxyMesh::Ptr _proxyMesh;
395 SMESH_ComputeErrorPtr _error;
398 Handle(Geom_Surface) _surface;
399 SMESH_MesherHelper _helper;
400 TSideVector _faceSideVec; // wires (StdMeshers_FaceSide) of _face
401 vector<_PolyLine> _polyLineVec; // fronts to advance
402 vector< const THypVL* > _hypOfEdge; // a hyp per an EDGE of _faceSideVec
403 bool _is2DIsotropic; // is same U and V resoulution of _face
404 vector<TopoDS_Face> _clearedFaces; // FACEs whose mesh was removed by shrink()
406 //double _fPowN; // to compute thickness of layers
407 double _maxThickness; // max possible layers thickness
409 // sub-shapes of _face
410 set<TGeomID> _ignoreShapeIds; // ids of EDGEs w/o layers
411 set<TGeomID> _noShrinkVert; // ids of VERTEXes that are extremities
412 // of EDGEs along which _LayerEdge can't be inflated because no viscous layers
413 // defined on neighbour FACEs sharing an EDGE. Nonetheless _LayerEdge's
414 // are inflated along such EDGEs but then such _LayerEdge's are turned into
415 // a node on VERTEX, i.e. all nodes on a _LayerEdge are melded into one node.
417 int _nbLE; // for DEBUG
420 //================================================================================
422 * \brief Returns StdMeshers_ViscousLayers2D for the FACE
424 bool findHyps(SMESH_Mesh& theMesh,
425 const TopoDS_Face& theFace,
426 vector< const StdMeshers_ViscousLayers2D* > & theHyps,
427 vector< TopoDS_Shape > & theAssignedTo)
430 theAssignedTo.clear();
431 SMESH_HypoFilter hypFilter
432 ( SMESH_HypoFilter::HasName( StdMeshers_ViscousLayers2D::GetHypType() ));
433 list< const SMESHDS_Hypothesis * > hypList;
434 list< TopoDS_Shape > hypShapes;
435 int nbHyps = theMesh.GetHypotheses
436 ( theFace, hypFilter, hypList, /*ancestors=*/true, &hypShapes );
439 theHyps.reserve( nbHyps );
440 theAssignedTo.reserve( nbHyps );
441 list< const SMESHDS_Hypothesis * >::iterator hyp = hypList.begin();
442 list< TopoDS_Shape >::iterator shape = hypShapes.begin();
443 for ( ; hyp != hypList.end(); ++hyp, ++shape )
445 theHyps.push_back( static_cast< const StdMeshers_ViscousLayers2D* > ( *hyp ));
446 theAssignedTo.push_back( *shape );
452 //================================================================================
454 * \brief Returns ids of EDGEs not to create Viscous Layers on
455 * \param [in] theHyp - the hypothesis, holding edges either to ignore or not to.
456 * \param [in] theFace - the FACE whose EDGEs are checked.
457 * \param [in] theMesh - the mesh.
458 * \param [in,out] theEdgeIds - container returning EDGEs to ignore.
459 * \return int - number of found EDGEs of the FACE.
461 //================================================================================
463 int getEdgesToIgnore( const StdMeshers_ViscousLayers2D* theHyp,
464 const TopoDS_Shape& theFace,
465 const SMESHDS_Mesh* theMesh,
466 set< int > & theEdgeIds)
468 int nbEdgesToIgnore = 0;
469 vector<TGeomID> ids = theHyp->GetBndShapes();
470 if ( theHyp->IsToIgnoreShapes() ) // EDGEs to ignore are given
472 for ( size_t i = 0; i < ids.size(); ++i )
474 const TopoDS_Shape& E = theMesh->IndexToShape( ids[i] );
476 E.ShapeType() == TopAbs_EDGE &&
477 SMESH_MesherHelper::IsSubShape( E, theFace ))
479 theEdgeIds.insert( ids[i] );
484 else // EDGEs to make the Viscous Layers on are given
486 TopExp_Explorer E( theFace, TopAbs_EDGE );
487 for ( ; E.More(); E.Next(), ++nbEdgesToIgnore )
488 theEdgeIds.insert( theMesh->ShapeToIndex( E.Current() ));
490 for ( size_t i = 0; i < ids.size(); ++i )
491 nbEdgesToIgnore -= theEdgeIds.erase( ids[i] );
493 return nbEdgesToIgnore;
496 } // namespace VISCOUS_2D
498 //================================================================================
499 // StdMeshers_ViscousLayers hypothesis
501 StdMeshers_ViscousLayers2D::StdMeshers_ViscousLayers2D(int hypId, int studyId, SMESH_Gen* gen)
502 :StdMeshers_ViscousLayers(hypId, studyId, gen)
504 _name = StdMeshers_ViscousLayers2D::GetHypType();
505 _param_algo_dim = -2; // auxiliary hyp used by 2D algos
507 // --------------------------------------------------------------------------------
508 bool StdMeshers_ViscousLayers2D::SetParametersByMesh(const SMESH_Mesh* theMesh,
509 const TopoDS_Shape& theShape)
514 // --------------------------------------------------------------------------------
516 StdMeshers_ViscousLayers2D::Compute(SMESH_Mesh& theMesh,
517 const TopoDS_Face& theFace)
519 using namespace VISCOUS_2D;
520 vector< const StdMeshers_ViscousLayers2D* > hyps;
521 vector< TopoDS_Shape > hypShapes;
523 SMESH_ProxyMesh::Ptr pm = _ProxyMeshHolder::FindProxyMeshOfFace( theFace, theMesh );
526 if ( findHyps( theMesh, theFace, hyps, hypShapes ))
528 VISCOUS_2D::_ViscousBuilder2D builder( theMesh, theFace, hyps, hypShapes );
529 pm = builder.Compute();
530 SMESH_ComputeErrorPtr error = builder.GetError();
531 if ( error && !error->IsOK() )
532 theMesh.GetSubMesh( theFace )->GetComputeError() = error;
534 pm.reset( new SMESH_ProxyMesh( theMesh ));
535 if ( getenv("__ONLY__VL2D__"))
540 pm.reset( new SMESH_ProxyMesh( theMesh ));
545 // --------------------------------------------------------------------------------
546 void StdMeshers_ViscousLayers2D::SetProxyMeshOfEdge( const StdMeshers_FaceSide& edgeNodes )
548 using namespace VISCOUS_2D;
549 SMESH_ProxyMesh::Ptr pm =
550 _ProxyMeshHolder::FindProxyMeshOfFace( edgeNodes.Face(), *edgeNodes.GetMesh() );
552 _ProxyMeshOfFace* proxyMeshOfFace = new _ProxyMeshOfFace( *edgeNodes.GetMesh() );
553 pm.reset( proxyMeshOfFace );
554 new _ProxyMeshHolder( edgeNodes.Face(), pm );
556 _ProxyMeshOfFace* proxyMeshOfFace = static_cast<_ProxyMeshOfFace*>( pm.get() );
557 _ProxyMeshOfFace::_EdgeSubMesh* sm = proxyMeshOfFace->GetEdgeSubMesh( edgeNodes.EdgeID(0) );
558 sm->GetUVPtStructVec() = edgeNodes.GetUVPtStruct();
560 // --------------------------------------------------------------------------------
561 bool StdMeshers_ViscousLayers2D::HasProxyMesh( const TopoDS_Face& face, SMESH_Mesh& mesh )
563 return VISCOUS_2D::_ProxyMeshHolder::FindProxyMeshOfFace( face, mesh );
565 // --------------------------------------------------------------------------------
566 SMESH_ComputeErrorPtr
567 StdMeshers_ViscousLayers2D::CheckHypothesis(SMESH_Mesh& theMesh,
568 const TopoDS_Shape& theShape,
569 SMESH_Hypothesis::Hypothesis_Status& theStatus)
571 SMESH_ComputeErrorPtr error = SMESH_ComputeError::New(COMPERR_OK);
572 theStatus = SMESH_Hypothesis::HYP_OK;
574 TopExp_Explorer exp( theShape, TopAbs_FACE );
575 for ( ; exp.More() && theStatus == SMESH_Hypothesis::HYP_OK; exp.Next() )
577 const TopoDS_Face& face = TopoDS::Face( exp.Current() );
578 vector< const StdMeshers_ViscousLayers2D* > hyps;
579 vector< TopoDS_Shape > hypShapes;
580 if ( VISCOUS_2D::findHyps( theMesh, face, hyps, hypShapes ))
582 VISCOUS_2D::_ViscousBuilder2D builder( theMesh, face, hyps, hypShapes );
583 builder._faceSideVec =
584 StdMeshers_FaceSide::GetFaceWires( face, theMesh, true, error,
585 SMESH_ProxyMesh::Ptr(),
586 /*theCheckVertexNodes=*/false);
587 if ( error->IsOK() && !builder.findEdgesWithLayers())
589 error = builder.GetError();
590 if ( error && !error->IsOK() )
591 theStatus = SMESH_Hypothesis::HYP_INCOMPAT_HYPS;
597 // --------------------------------------------------------------------------------
598 void StdMeshers_ViscousLayers2D::RestoreListeners() const
600 StudyContextStruct* sc = _gen->GetStudyContext( _studyId );
601 std::map < int, SMESH_Mesh * >::iterator i_smesh = sc->mapMesh.begin();
602 for ( ; i_smesh != sc->mapMesh.end(); ++i_smesh )
604 SMESH_Mesh* smesh = i_smesh->second;
606 !smesh->HasShapeToMesh() ||
607 !smesh->GetMeshDS() ||
608 !smesh->GetMeshDS()->IsUsedHypothesis( this ))
611 // set event listeners to EDGE's of FACE where this hyp is used
612 TopoDS_Shape shape = i_smesh->second->GetShapeToMesh();
613 for ( TopExp_Explorer face( shape, TopAbs_FACE); face.More(); face.Next() )
614 if ( SMESH_Algo* algo = _gen->GetAlgo( *smesh, face.Current() ))
616 const std::list <const SMESHDS_Hypothesis *> & usedHyps =
617 algo->GetUsedHypothesis( *smesh, face.Current(), /*ignoreAuxiliary=*/false );
618 if ( std::find( usedHyps.begin(), usedHyps.end(), this ) != usedHyps.end() )
619 for ( TopExp_Explorer edge( face.Current(), TopAbs_EDGE); edge.More(); edge.Next() )
620 VISCOUS_3D::ToClearSubWithMain( smesh->GetSubMesh( edge.Current() ), face.Current() );
624 // END StdMeshers_ViscousLayers2D hypothesis
625 //================================================================================
627 using namespace VISCOUS_2D;
629 //================================================================================
631 * \brief Constructor of _ViscousBuilder2D
633 //================================================================================
635 _ViscousBuilder2D::_ViscousBuilder2D(SMESH_Mesh& theMesh,
636 const TopoDS_Face& theFace,
637 vector< const THypVL* > & theHyps,
638 vector< TopoDS_Shape > & theAssignedTo):
639 _mesh( &theMesh ), _face( theFace ), _helper( theMesh )
641 _hyps.swap( theHyps );
642 _hypShapes.swap( theAssignedTo );
644 _helper.SetSubShape( _face );
645 _helper.SetElementsOnShape( true );
647 _face.Orientation( TopAbs_FORWARD ); // 2D logic works only in this case
648 _surface = BRep_Tool::Surface( _face );
650 _error = SMESH_ComputeError::New(COMPERR_OK);
655 //================================================================================
657 * \brief Stores error description and returns false
659 //================================================================================
661 bool _ViscousBuilder2D::error(const string& text )
663 _error->myName = COMPERR_ALGO_FAILED;
664 _error->myComment = string("Viscous layers builder 2D: ") + text;
665 if ( SMESH_subMesh* sm = _mesh->GetSubMesh( _face ) )
667 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
668 if ( smError && smError->myAlgo )
669 _error->myAlgo = smError->myAlgo;
673 cout << "_ViscousBuilder2D::error " << text << endl;
678 //================================================================================
680 * \brief Does its job
682 //================================================================================
684 SMESH_ProxyMesh::Ptr _ViscousBuilder2D::Compute()
686 _faceSideVec = StdMeshers_FaceSide::GetFaceWires( _face, *_mesh, true, _error);
688 if ( !_error->IsOK() )
691 if ( !findEdgesWithLayers() ) // analysis of a shape
694 if ( ! makePolyLines() ) // creation of fronts
697 if ( ! inflate() ) // advance fronts
700 // remove elements and nodes from _face
701 removeMeshFaces( _face );
703 if ( !shrink() ) // shrink segments on edges w/o layers
706 if ( ! refine() ) // make faces
714 //================================================================================
716 * \brief Finds EDGE's to make viscous layers on.
718 //================================================================================
720 bool _ViscousBuilder2D::findEdgesWithLayers()
722 // collect all EDGEs to ignore defined by _hyps
723 typedef std::pair< set<TGeomID>, const THypVL* > TEdgesOfHyp;
724 vector< TEdgesOfHyp > ignoreEdgesOfHyp( _hyps.size() );
725 for ( size_t i = 0; i < _hyps.size(); ++i )
727 ignoreEdgesOfHyp[i].second = _hyps[i];
728 getEdgesToIgnore( _hyps[i], _face, getMeshDS(), ignoreEdgesOfHyp[i].first );
731 // get all shared EDGEs
732 TopTools_MapOfShape sharedEdges;
733 TopTools_IndexedMapOfShape hypFaces; // faces with VL hyps
734 for ( size_t i = 0; i < _hypShapes.size(); ++i )
735 TopExp::MapShapes( _hypShapes[i], TopAbs_FACE, hypFaces );
736 TopTools_IndexedDataMapOfShapeListOfShape facesOfEdgeMap;
737 for ( int iF = 1; iF <= hypFaces.Extent(); ++iF )
738 TopExp::MapShapesAndAncestors( hypFaces(iF), TopAbs_EDGE, TopAbs_FACE, facesOfEdgeMap);
739 for ( int iE = 1; iE <= facesOfEdgeMap.Extent(); ++iE )
740 if ( facesOfEdgeMap( iE ).Extent() > 1 )
741 sharedEdges.Add( facesOfEdgeMap.FindKey( iE ));
744 if ( _hyps.size() > 1 )
746 // check if two hypotheses define different parameters for the same EDGE
747 for ( size_t iWire = 0; iWire < _faceSideVec.size(); ++iWire )
749 StdMeshers_FaceSidePtr wire = _faceSideVec[ iWire ];
750 for ( int iE = 0; iE < wire->NbEdges(); ++iE )
752 const THypVL* hyp = 0;
753 const TGeomID edgeID = wire->EdgeID( iE );
754 if ( !sharedEdges.Contains( wire->Edge( iE )))
756 for ( size_t i = 0; i < ignoreEdgesOfHyp.size(); ++i )
757 if ( ! ignoreEdgesOfHyp[i].first.count( edgeID ))
760 return error(SMESH_Comment("Several hypotheses define "
761 "Viscous Layers on the edge #") << edgeID );
762 hyp = ignoreEdgesOfHyp[i].second;
765 _hypOfEdge.push_back( hyp );
767 _ignoreShapeIds.insert( edgeID );
769 // check if two hypotheses define different number of viscous layers for
771 const THypVL *hyp, *prevHyp = _hypOfEdge.back();
772 size_t iH = _hypOfEdge.size() - wire->NbEdges();
773 for ( ; iH < _hypOfEdge.size(); ++iH )
775 hyp = _hypOfEdge[ iH ];
776 if ( hyp && prevHyp &&
777 hyp->GetNumberLayers() != prevHyp->GetNumberLayers() )
779 return error("Two hypotheses define different number of "
780 "viscous layers on adjacent edges");
786 else if ( _hyps.size() == 1 )
788 _ignoreShapeIds.swap( ignoreEdgesOfHyp[0].first );
791 // check all EDGEs of the _face to fill _ignoreShapeIds and _noShrinkVert
793 int totalNbEdges = 0;
794 for ( size_t iWire = 0; iWire < _faceSideVec.size(); ++iWire )
796 StdMeshers_FaceSidePtr wire = _faceSideVec[ iWire ];
797 totalNbEdges += wire->NbEdges();
798 for ( int iE = 0; iE < wire->NbEdges(); ++iE )
800 if ( sharedEdges.Contains( wire->Edge( iE )))
802 // ignore internal EDGEs (shared by several FACEs)
803 const TGeomID edgeID = wire->EdgeID( iE );
804 _ignoreShapeIds.insert( edgeID );
806 // check if ends of an EDGE are to be added to _noShrinkVert
807 const TopTools_ListOfShape& faceList = facesOfEdgeMap.FindFromKey( wire->Edge( iE ));
808 TopTools_ListIteratorOfListOfShape faceIt( faceList );
809 for ( ; faceIt.More(); faceIt.Next() )
811 const TopoDS_Shape& neighbourFace = faceIt.Value();
812 if ( neighbourFace.IsSame( _face )) continue;
813 SMESH_Algo* algo = _mesh->GetGen()->GetAlgo( *_mesh, neighbourFace );
814 if ( !algo ) continue;
816 const StdMeshers_ViscousLayers2D* viscHyp = 0;
817 const list <const SMESHDS_Hypothesis *> & allHyps =
818 algo->GetUsedHypothesis(*_mesh, neighbourFace, /*noAuxiliary=*/false);
819 list< const SMESHDS_Hypothesis *>::const_iterator hyp = allHyps.begin();
820 for ( ; hyp != allHyps.end() && !viscHyp; ++hyp )
821 viscHyp = dynamic_cast<const StdMeshers_ViscousLayers2D*>( *hyp );
823 // set<TGeomID> neighbourIgnoreEdges;
825 // getEdgesToIgnore( viscHyp, neighbourFace, getMeshDS(), neighbourIgnoreEdges );
827 for ( int iV = 0; iV < 2; ++iV )
829 TopoDS_Vertex vertex = iV ? wire->LastVertex(iE) : wire->FirstVertex(iE);
831 _noShrinkVert.insert( getMeshDS()->ShapeToIndex( vertex ));
834 PShapeIteratorPtr edgeIt = _helper.GetAncestors( vertex, *_mesh, TopAbs_EDGE );
835 while ( const TopoDS_Shape* edge = edgeIt->next() )
836 if ( !edge->IsSame( wire->Edge( iE )) &&
837 _helper.IsSubShape( *edge, neighbourFace ))
839 const TGeomID neighbourID = getMeshDS()->ShapeToIndex( *edge );
840 bool hasVL = !sharedEdges.Contains( *edge );
844 for ( hyp = allHyps.begin(); hyp != allHyps.end() && !hasVL; ++hyp )
845 if (( viscHyp = dynamic_cast<const THypVL*>( *hyp )))
846 hasVL = viscHyp->IsShapeWithLayers( neighbourID );
850 _noShrinkVert.insert( getMeshDS()->ShapeToIndex( vertex ));
861 int nbMyEdgesIgnored = _ignoreShapeIds.size();
863 // add VERTEXes w/o layers to _ignoreShapeIds (this is used by toShrinkForAdjacent())
864 // for ( size_t iWire = 0; iWire < _faceSideVec.size(); ++iWire )
866 // StdMeshers_FaceSidePtr wire = _faceSideVec[ iWire ];
867 // for ( int iE = 0; iE < wire->NbEdges(); ++iE )
869 // TGeomID edge1 = wire->EdgeID( iE );
870 // TGeomID edge2 = wire->EdgeID( iE+1 );
871 // if ( _ignoreShapeIds.count( edge1 ) && _ignoreShapeIds.count( edge2 ))
872 // _ignoreShapeIds.insert( getMeshDS()->ShapeToIndex( wire->LastVertex( iE )));
876 return ( nbMyEdgesIgnored < totalNbEdges );
879 //================================================================================
881 * \brief Create the inner front of the viscous layers and prepare data for inflation
883 //================================================================================
885 bool _ViscousBuilder2D::makePolyLines()
887 // Create _PolyLines and _LayerEdge's
889 // count total nb of EDGEs to allocate _polyLineVec
891 for ( size_t iWire = 0; iWire < _faceSideVec.size(); ++iWire )
893 StdMeshers_FaceSidePtr wire = _faceSideVec[ iWire ];
894 nbEdges += wire->NbEdges();
895 if ( wire->GetUVPtStruct().empty() && wire->NbPoints() > 0 )
896 return error("Invalid node parameters on some EDGE");
898 _polyLineVec.resize( nbEdges );
900 // check if 2D normal should be computed by 3D one by means of projection
901 GeomAPI_ProjectPointOnSurf* faceProj = 0;
905 const UVPtStruct& uv = _faceSideVec[0]->GetUVPtStruct()[0];
906 gp_Pnt p = SMESH_TNodeXYZ( uv.node );
907 tmpLE._uvOut.SetCoord( uv.u, uv.v );
908 tmpLE._normal2D.SetCoord( 1., 0. );
909 setLenRatio( tmpLE, p );
910 const double r1 = tmpLE._len2dTo3dRatio;
911 tmpLE._normal2D.SetCoord( 0., 1. );
912 setLenRatio( tmpLE, p );
913 const double r2 = tmpLE._len2dTo3dRatio;
914 // projection is needed if two _len2dTo3dRatio's differ too much
915 const double maxR = Max( r2, r1 );
916 if ( Abs( r2-r1 )/maxR > 0.2*maxR )
917 faceProj = & _helper.GetProjector( _face, loc );
919 _is2DIsotropic = !faceProj;
921 // Assign data to _PolyLine's
922 // ---------------------------
925 for ( size_t iWire = 0; iWire < _faceSideVec.size(); ++iWire )
927 StdMeshers_FaceSidePtr wire = _faceSideVec[ iWire ];
928 const vector<UVPtStruct>& points = wire->GetUVPtStruct();
930 for ( int iE = 0; iE < wire->NbEdges(); ++iE )
932 _PolyLine& L = _polyLineVec[ iPoLine++ ];
933 L._index = iPoLine-1;
934 L._wire = wire.get();
936 L._advancable = !_ignoreShapeIds.count( wire->EdgeID( iE ));
938 int iRight = iPoLine - (( iE+1 < wire->NbEdges() ) ? 0 : wire->NbEdges() );
939 L._rightLine = &_polyLineVec[ iRight ];
940 _polyLineVec[ iRight ]._leftLine = &L;
942 L._firstPntInd = iPnt;
943 double lastNormPar = wire->LastParameter( iE ) - 1e-10;
944 while ( points[ iPnt ].normParam < lastNormPar )
946 L._lastPntInd = iPnt;
947 L._lEdges.resize( Max( 3, L._lastPntInd - L._firstPntInd + 1 )); // 3 edges minimum
949 // TODO: add more _LayerEdge's to strongly curved EDGEs
950 // in order not to miss collisions
953 Handle(Geom_Curve) curve = BRep_Tool::Curve( L._wire->Edge( iE ), loc, u, u );
954 Handle(Geom2d_Curve) pcurve = L._wire->Curve2d( L._edgeInd );
955 const bool reverse = (( L._wire->Edge( iE ).Orientation() == TopAbs_REVERSED ) ^
956 (_face.Orientation() == TopAbs_REVERSED ));
957 for ( int i = L._firstPntInd; i <= L._lastPntInd; ++i )
959 _LayerEdge& lEdge = L._lEdges[ i - L._firstPntInd ];
960 u = ( i == L._firstPntInd ? wire->FirstU(iE) : points[ i ].param );
961 p = SMESH_TNodeXYZ( points[ i ].node );
962 setLayerEdgeData( lEdge, u, pcurve, curve, p, reverse, faceProj );
963 setLenRatio( lEdge, p );
965 if ( L._lastPntInd - L._firstPntInd + 1 < 3 ) // add 3-d _LayerEdge in the middle
967 L._lEdges[2] = L._lEdges[1];
968 u = 0.5 * ( wire->FirstU(iE) + wire->LastU(iE) );
969 if ( !curve.IsNull() )
970 p = curve->Value( u );
972 p = 0.5 * ( SMESH_TNodeXYZ( points[ L._firstPntInd ].node ) +
973 SMESH_TNodeXYZ( points[ L._lastPntInd ].node ));
974 setLayerEdgeData( L._lEdges[1], u, pcurve, curve, p, reverse, faceProj );
975 setLenRatio( L._lEdges[1], p );
980 // Fill _PolyLine's with _segments
981 // --------------------------------
983 double maxLen2dTo3dRatio = 0;
984 for ( iPoLine = 0; iPoLine < _polyLineVec.size(); ++iPoLine )
986 _PolyLine& L = _polyLineVec[ iPoLine ];
987 L._segments.resize( L._lEdges.size() - 1 );
988 for ( size_t i = 1; i < L._lEdges.size(); ++i )
990 _Segment & S = L._segments[i-1];
991 S._uv[0] = & L._lEdges[i-1]._uvIn;
992 S._uv[1] = & L._lEdges[i ]._uvIn;
993 S._indexInLine = i-1;
994 if ( maxLen2dTo3dRatio < L._lEdges[i]._len2dTo3dRatio )
995 maxLen2dTo3dRatio = L._lEdges[i]._len2dTo3dRatio;
997 // // connect _PolyLine's with segments, the 1st _LayerEdge of every _PolyLine
998 // // becomes not connected to any segment
999 // if ( L._leftLine->_advancable )
1000 // L._segments[0]._uv[0] = & L._leftLine->_lEdges.back()._uvIn;
1002 L._segTree.reset( new _SegmentTree( L._segments ));
1005 // Evaluate max possible _thickness if required layers thickness seems too high
1006 // ----------------------------------------------------------------------------
1008 _maxThickness = _hyps[0]->GetTotalThickness();
1009 for ( size_t iH = 1; iH < _hyps.size(); ++iH )
1010 _maxThickness = Max( _maxThickness, _hyps[iH]->GetTotalThickness() );
1012 _SegmentTree::box_type faceBndBox2D;
1013 for ( iPoLine = 0; iPoLine < _polyLineVec.size(); ++iPoLine )
1014 faceBndBox2D.Add( *_polyLineVec[ iPoLine]._segTree->getBox() );
1015 const double boxTol = 1e-3 * sqrt( faceBndBox2D.SquareExtent() );
1017 if ( _maxThickness * maxLen2dTo3dRatio > sqrt( faceBndBox2D.SquareExtent() ) / 10 )
1019 vector< const _Segment* > foundSegs;
1020 double maxPossibleThick = 0;
1021 _SegmentIntersection intersection;
1022 for ( size_t iL1 = 0; iL1 < _polyLineVec.size(); ++iL1 )
1024 _PolyLine& L1 = _polyLineVec[ iL1 ];
1025 _SegmentTree::box_type boxL1 = * L1._segTree->getBox();
1026 boxL1.Enlarge( boxTol );
1027 // consider case of a circle as well!
1028 for ( size_t iL2 = iL1; iL2 < _polyLineVec.size(); ++iL2 )
1030 _PolyLine& L2 = _polyLineVec[ iL2 ];
1031 _SegmentTree::box_type boxL2 = * L2._segTree->getBox();
1032 boxL2.Enlarge( boxTol );
1033 if ( boxL1.IsOut( boxL2 ))
1035 for ( size_t iLE = 1; iLE < L1._lEdges.size(); ++iLE )
1038 L2._segTree->GetSegmentsNear( L1._lEdges[iLE]._ray, foundSegs );
1039 for ( size_t i = 0; i < foundSegs.size(); ++i )
1040 if ( intersection.Compute( *foundSegs[i], L1._lEdges[iLE]._ray ))
1042 double distToL2 = intersection._param2 / L1._lEdges[iLE]._len2dTo3dRatio;
1043 double psblThick = distToL2 / ( 1 + L1._advancable + L2._advancable );
1044 maxPossibleThick = Max( psblThick, maxPossibleThick );
1049 if ( maxPossibleThick > 0. )
1050 _maxThickness = Min( _maxThickness, maxPossibleThick );
1053 // Adjust _LayerEdge's at _PolyLine's extremities
1054 // -----------------------------------------------
1056 for ( iPoLine = 0; iPoLine < _polyLineVec.size(); ++iPoLine )
1058 _PolyLine& LL = _polyLineVec[ iPoLine ];
1059 _PolyLine& LR = *LL._rightLine;
1060 adjustCommonEdge( LL, LR );
1062 // recreate _segments if some _LayerEdge's have been removed by adjustCommonEdge()
1063 for ( iPoLine = 0; iPoLine < _polyLineVec.size(); ++iPoLine )
1065 _PolyLine& L = _polyLineVec[ iPoLine ];
1066 // if ( L._segments.size() == L._lEdges.size() - 1 )
1068 L._segments.resize( L._lEdges.size() - 1 );
1069 for ( size_t i = 1; i < L._lEdges.size(); ++i )
1071 _Segment & S = L._segments[i-1];
1072 S._uv[0] = & L._lEdges[i-1]._uvIn;
1073 S._uv[1] = & L._lEdges[i ]._uvIn;
1074 S._indexInLine = i-1;
1076 L._segTree.reset( new _SegmentTree( L._segments ));
1078 // connect _PolyLine's with segments, the 1st _LayerEdge of every _PolyLine
1079 // becomes not connected to any segment
1080 for ( iPoLine = 0; iPoLine < _polyLineVec.size(); ++iPoLine )
1082 _PolyLine& L = _polyLineVec[ iPoLine ];
1083 if ( L._leftLine->_advancable )
1084 L._segments[0]._uv[0] = & L._leftLine->_lEdges.back()._uvIn;
1087 // Fill _reachableLines.
1088 // ----------------------
1090 // compute bnd boxes taking into account the layers total thickness
1091 vector< _SegmentTree::box_type > lineBoxes( _polyLineVec.size() );
1092 for ( iPoLine = 0; iPoLine < _polyLineVec.size(); ++iPoLine )
1094 lineBoxes[ iPoLine ] = *_polyLineVec[ iPoLine ]._segTree->getBox();
1095 lineBoxes[ iPoLine ].Enlarge( maxLen2dTo3dRatio * getLineThickness( iPoLine ) *
1096 ( _polyLineVec[ iPoLine ]._advancable ? 2. : 1.2 ));
1099 for ( iPoLine = 0; iPoLine < _polyLineVec.size(); ++iPoLine )
1101 _PolyLine& L1 = _polyLineVec[ iPoLine ];
1102 const double thick1 = getLineThickness( iPoLine );
1103 for ( size_t iL2 = 0; iL2 < _polyLineVec.size(); ++iL2 )
1105 _PolyLine& L2 = _polyLineVec[ iL2 ];
1106 if ( iPoLine == iL2 || lineBoxes[ iPoLine ].IsOut( lineBoxes[ iL2 ]))
1108 if ( !L1._advancable && ( L1._leftLine == &L2 || L1._rightLine == &L2 ))
1110 // check reachability by _LayerEdge's
1111 int iDelta = 1; //Max( 1, L1._lEdges.size() / 100 );
1112 for ( size_t iLE = 1; iLE < L1._lEdges.size(); iLE += iDelta )
1114 _LayerEdge& LE = L1._lEdges[iLE];
1115 if ( !lineBoxes[ iL2 ].IsOut ( LE._uvOut,
1116 LE._uvOut + LE._normal2D * thick1 * LE._len2dTo3dRatio ))
1118 L1._reachableLines.push_back( & L2 );
1123 // add self to _reachableLines
1124 Geom2dAdaptor_Curve pcurve( L1._wire->Curve2d( L1._edgeInd ));
1125 L1._isStraight2D = ( pcurve.GetType() == GeomAbs_Line );
1126 if ( !L1._isStraight2D )
1128 // TODO: check carefully
1129 L1._reachableLines.push_back( & L1 );
1136 //================================================================================
1138 * \brief adjust common _LayerEdge of two adjacent _PolyLine's
1139 * \param LL - left _PolyLine
1140 * \param LR - right _PolyLine
1142 //================================================================================
1144 void _ViscousBuilder2D::adjustCommonEdge( _PolyLine& LL, _PolyLine& LR )
1146 int nbAdvancableL = LL._advancable + LR._advancable;
1147 if ( nbAdvancableL == 0 )
1150 _LayerEdge& EL = LL._lEdges.back();
1151 _LayerEdge& ER = LR._lEdges.front();
1152 gp_XY normL = EL._normal2D;
1153 gp_XY normR = ER._normal2D;
1154 gp_XY tangL ( normL.Y(), -normL.X() );
1156 // set common direction to a VERTEX _LayerEdge shared by two _PolyLine's
1157 gp_XY normCommon = ( normL * int( LL._advancable ) +
1158 normR * int( LR._advancable )).Normalized();
1159 EL._normal2D = normCommon;
1160 EL._ray.SetLocation ( EL._uvOut );
1161 EL._ray.SetDirection( EL._normal2D );
1162 if ( nbAdvancableL == 1 ) { // _normal2D is true normal (not average)
1163 EL._isBlocked = true; // prevent intersecting with _Segments of _advancable line
1166 // update _LayerEdge::_len2dTo3dRatio according to a new direction
1167 const vector<UVPtStruct>& points = LL._wire->GetUVPtStruct();
1168 setLenRatio( EL, SMESH_TNodeXYZ( points[ LL._lastPntInd ].node ));
1172 const double dotNormTang = normR * tangL;
1173 const bool largeAngle = Abs( dotNormTang ) > 0.2;
1174 if ( largeAngle ) // not 180 degrees
1176 // recompute _len2dTo3dRatio to take into account angle between EDGEs
1177 gp_Vec2d oldNorm( LL._advancable ? normL : normR );
1178 double angleFactor = 1. / Max( 0.3, Cos( oldNorm.Angle( normCommon )));
1179 EL._len2dTo3dRatio *= angleFactor;
1180 ER._len2dTo3dRatio = EL._len2dTo3dRatio;
1182 gp_XY normAvg = ( normL + normR ).Normalized(); // average normal at VERTEX
1184 if ( dotNormTang < 0. ) // ---------------------------- CONVEX ANGLE
1186 // Remove _LayerEdge's intersecting the normAvg to avoid collisions
1187 // during inflate().
1189 // find max length of the VERTEX-based _LayerEdge whose direction is normAvg
1190 double maxLen2D = _maxThickness * EL._len2dTo3dRatio;
1191 const gp_XY& pCommOut = ER._uvOut;
1192 gp_XY pCommIn = pCommOut + normAvg * maxLen2D;
1193 _Segment segCommon( pCommOut, pCommIn );
1194 _SegmentIntersection intersection;
1195 vector< const _Segment* > foundSegs;
1196 for ( size_t iL1 = 0; iL1 < _polyLineVec.size(); ++iL1 )
1198 _PolyLine& L1 = _polyLineVec[ iL1 ];
1199 const _SegmentTree::box_type* boxL1 = L1._segTree->getBox();
1200 if ( boxL1->IsOut ( pCommOut, pCommIn ))
1202 for ( size_t iLE = 1; iLE < L1._lEdges.size(); ++iLE )
1205 L1._segTree->GetSegmentsNear( segCommon, foundSegs );
1206 for ( size_t i = 0; i < foundSegs.size(); ++i )
1207 if ( intersection.Compute( *foundSegs[i], segCommon ) &&
1208 intersection._param2 > 1e-10 )
1210 double len2D = intersection._param2 * maxLen2D / ( 2 + L1._advancable );
1211 if ( len2D < maxLen2D ) {
1213 pCommIn = pCommOut + normAvg * maxLen2D; // here length of segCommon changes
1219 // remove _LayerEdge's intersecting segCommon
1220 for ( int isR = 0; isR < 2; ++isR ) // loop on [ LL, LR ]
1222 _PolyLine& L = isR ? LR : LL;
1223 _PolyLine::TEdgeIterator eIt = isR ? L._lEdges.begin()+1 : L._lEdges.end()-2;
1224 int dIt = isR ? +1 : -1;
1225 if ( nbAdvancableL == 1 && L._advancable && normL * normR > -0.01 )
1226 continue; // obtuse internal angle
1227 // at least 3 _LayerEdge's should remain in a _PolyLine
1228 if ( L._lEdges.size() < 4 ) continue;
1230 _SegmentIntersection lastIntersection;
1231 for ( ; iLE < L._lEdges.size(); ++iLE, eIt += dIt )
1233 gp_XY uvIn = eIt->_uvOut + eIt->_normal2D * _maxThickness * eIt->_len2dTo3dRatio;
1234 _Segment segOfEdge( eIt->_uvOut, uvIn );
1235 if ( !intersection.Compute( segCommon, segOfEdge ))
1237 lastIntersection._param1 = intersection._param1;
1238 lastIntersection._param2 = intersection._param2;
1240 if ( iLE >= L._lEdges.size() - 1 )
1242 // all _LayerEdge's intersect the segCommon, limit inflation
1243 // of remaining 3 _LayerEdge's
1244 vector< _LayerEdge > newEdgeVec( Min( 3, L._lEdges.size() ));
1245 newEdgeVec.front() = L._lEdges.front();
1246 newEdgeVec.back() = L._lEdges.back();
1247 if ( newEdgeVec.size() == 3 )
1249 newEdgeVec[1] = L._lEdges[ isR ? (L._lEdges.size() - 2) : 1 ];
1250 newEdgeVec[1]._len2dTo3dRatio *= lastIntersection._param2;
1252 L._lEdges.swap( newEdgeVec );
1253 if ( !isR ) std::swap( lastIntersection._param1 , lastIntersection._param2 );
1254 L._lEdges.front()._len2dTo3dRatio *= lastIntersection._param1; // ??
1255 L._lEdges.back ()._len2dTo3dRatio *= lastIntersection._param2;
1257 else if ( iLE != 1 )
1259 // eIt points to the _LayerEdge not intersecting with segCommon
1261 LR._lEdges.erase( LR._lEdges.begin()+1, eIt );
1263 LL._lEdges.erase( eIt, --LL._lEdges.end() );
1264 // eIt = isR ? L._lEdges.begin()+1 : L._lEdges.end()-2;
1265 // for ( size_t i = 1; i < iLE; ++i, eIt += dIt )
1266 // eIt->_isBlocked = true;
1270 else // ------------------------------------------ CONCAVE ANGLE
1272 if ( nbAdvancableL == 1 )
1274 // make that the _LayerEdge at VERTEX is not shared by LL and LR:
1275 // different normals is a sign that they are not shared
1276 _LayerEdge& notSharedEdge = LL._advancable ? LR._lEdges[0] : LL._lEdges.back();
1277 _LayerEdge& sharedEdge = LR._advancable ? LR._lEdges[0] : LL._lEdges.back();
1279 notSharedEdge._normal2D.SetCoord( 0.,0. );
1280 sharedEdge._normal2D = normAvg;
1281 sharedEdge._isBlocked = false;
1282 notSharedEdge._isBlocked = true;
1288 //================================================================================
1290 * \brief initialize data of a _LayerEdge
1292 //================================================================================
1294 void _ViscousBuilder2D::setLayerEdgeData( _LayerEdge& lEdge,
1296 Handle(Geom2d_Curve)& pcurve,
1297 Handle(Geom_Curve)& curve,
1300 GeomAPI_ProjectPointOnSurf* faceProj)
1303 if ( faceProj && !curve.IsNull() )
1305 uv = pcurve->Value( u );
1306 gp_Vec tangent; gp_Pnt p; gp_Vec du, dv;
1307 curve->D1( u, p, tangent );
1310 _surface->D1( uv.X(), uv.Y(), p, du, dv );
1311 gp_Vec faceNorm = du ^ dv;
1312 gp_Vec normal = faceNorm ^ tangent;
1314 p = pOut.XYZ() + normal.XYZ() * /*1e-2 * */_hyps[0]->GetTotalThickness() / _hyps[0]->GetNumberLayers();
1315 faceProj->Perform( p );
1316 if ( !faceProj->IsDone() || faceProj->NbPoints() < 1 )
1317 return setLayerEdgeData( lEdge, u, pcurve, curve, p, reverse, NULL );
1318 Quantity_Parameter U,V;
1319 faceProj->LowerDistanceParameters(U,V);
1320 lEdge._normal2D.SetCoord( U - uv.X(), V - uv.Y() );
1321 lEdge._normal2D.Normalize();
1326 pcurve->D1( u, uv, tangent );
1327 tangent.Normalize();
1330 lEdge._normal2D.SetCoord( -tangent.Y(), tangent.X() );
1332 lEdge._uvOut = lEdge._uvIn = uv.XY();
1333 lEdge._ray.SetLocation ( lEdge._uvOut );
1334 lEdge._ray.SetDirection( lEdge._normal2D );
1335 lEdge._isBlocked = false;
1336 lEdge._length2D = 0;
1338 lEdge._ID = _nbLE++;
1342 //================================================================================
1344 * \brief Compute and set _LayerEdge::_len2dTo3dRatio
1346 //================================================================================
1348 void _ViscousBuilder2D::setLenRatio( _LayerEdge& LE, const gp_Pnt& pOut )
1350 const double probeLen2d = 1e-3;
1352 gp_Pnt2d p2d = LE._uvOut + LE._normal2D * probeLen2d;
1353 gp_Pnt p3d = _surface->Value( p2d.X(), p2d.Y() );
1354 double len3d = p3d.Distance( pOut );
1355 if ( len3d < std::numeric_limits<double>::min() )
1356 LE._len2dTo3dRatio = std::numeric_limits<double>::min();
1358 LE._len2dTo3dRatio = probeLen2d / len3d;
1361 //================================================================================
1363 * \brief Increase length of _LayerEdge's to reach the required thickness of layers
1365 //================================================================================
1367 bool _ViscousBuilder2D::inflate()
1369 // Limit size of inflation step by geometry size found by
1370 // itersecting _LayerEdge's with _Segment's
1371 double minSize = _maxThickness, maxSize = 0;
1372 vector< const _Segment* > foundSegs;
1373 _SegmentIntersection intersection;
1374 for ( size_t iL1 = 0; iL1 < _polyLineVec.size(); ++iL1 )
1376 _PolyLine& L1 = _polyLineVec[ iL1 ];
1377 for ( size_t iL2 = 0; iL2 < L1._reachableLines.size(); ++iL2 )
1379 _PolyLine& L2 = * L1._reachableLines[ iL2 ];
1380 for ( size_t iLE = 1; iLE < L1._lEdges.size(); ++iLE )
1383 L2._segTree->GetSegmentsNear( L1._lEdges[iLE]._ray, foundSegs );
1384 for ( size_t i = 0; i < foundSegs.size(); ++i )
1385 if ( ! L1.IsAdjacent( *foundSegs[i], & L1._lEdges[iLE] ) &&
1386 intersection.Compute( *foundSegs[i], L1._lEdges[iLE]._ray ))
1388 double distToL2 = intersection._param2 / L1._lEdges[iLE]._len2dTo3dRatio;
1389 double size = distToL2 / ( 1 + L1._advancable + L2._advancable );
1390 if ( 1e-10 < size && size < minSize )
1392 if ( size > maxSize )
1398 if ( minSize > maxSize ) // no collisions possible
1399 maxSize = _maxThickness;
1401 cout << "-- minSize = " << minSize << ", maxSize = " << maxSize << endl;
1404 double curThick = 0, stepSize = minSize;
1406 if ( maxSize > _maxThickness )
1407 maxSize = _maxThickness;
1408 while ( curThick < maxSize )
1410 curThick += stepSize * 1.25;
1411 if ( curThick > _maxThickness )
1412 curThick = _maxThickness;
1414 // Elongate _LayerEdge's
1415 for ( size_t iL = 0; iL < _polyLineVec.size(); ++iL )
1417 _PolyLine& L = _polyLineVec[ iL ];
1418 if ( !L._advancable ) continue;
1419 const double lineThick = Min( curThick, getLineThickness( iL ));
1420 bool lenChange = false;
1421 for ( size_t iLE = L.FirstLEdge(); iLE < L._lEdges.size(); ++iLE )
1422 lenChange |= L._lEdges[iLE].SetNewLength( lineThick );
1423 // for ( int k=0; k<L._segments.size(); ++k)
1424 // cout << "( " << L._segments[k].p1().X() << ", " <<L._segments[k].p1().Y() << " ) "
1425 // << "( " << L._segments[k].p2().X() << ", " <<L._segments[k].p2().Y() << " ) "
1428 L._segTree.reset( new _SegmentTree( L._segments ));
1431 // Avoid intersection of _Segment's
1432 bool allBlocked = fixCollisions();
1435 break; // no more inflating possible
1437 stepSize = Max( stepSize , _maxThickness / 10. );
1441 // if (nbSteps == 0 )
1442 // return error("failed at the very first inflation step");
1445 // remove _LayerEdge's of one line intersecting with each other
1446 for ( size_t iL = 0; iL < _polyLineVec.size(); ++iL )
1448 _PolyLine& L = _polyLineVec[ iL ];
1449 if ( !L._advancable ) continue;
1451 // replace an inactive (1st) _LayerEdge with an active one of a neighbour _PolyLine
1452 if ( /*!L._leftLine->_advancable &&*/ L.IsCommonEdgeShared( *L._leftLine ) ) {
1453 L._lEdges[0] = L._leftLine->_lEdges.back();
1455 if ( !L._rightLine->_advancable && L.IsCommonEdgeShared( *L._rightLine ) ) {
1456 L._lEdges.back() = L._rightLine->_lEdges[0];
1459 _SegmentIntersection intersection;
1460 for ( int isR = 0; ( isR < 2 && L._lEdges.size() > 2 ); ++isR )
1462 int nbRemove = 0, deltaIt = isR ? -1 : +1;
1463 _PolyLine::TEdgeIterator eIt = isR ? L._lEdges.end()-1 : L._lEdges.begin();
1464 if ( eIt->_length2D == 0 ) continue;
1465 _Segment seg1( eIt->_uvOut, eIt->_uvIn );
1466 for ( eIt += deltaIt; nbRemove < (int)L._lEdges.size()-1; eIt += deltaIt )
1468 _Segment seg2( eIt->_uvOut, eIt->_uvIn );
1469 if ( !intersection.Compute( seg1, seg2 ))
1473 if ( nbRemove > 0 ) {
1474 if ( nbRemove == (int)L._lEdges.size()-1 ) // 1st and last _LayerEdge's intersect
1477 _LayerEdge& L0 = L._lEdges.front();
1478 _LayerEdge& L1 = L._lEdges.back();
1479 L0._length2D *= intersection._param1 * 0.5;
1480 L1._length2D *= intersection._param2 * 0.5;
1481 L0._uvIn = L0._uvOut + L0._normal2D * L0._length2D;
1482 L1._uvIn = L1._uvOut + L1._normal2D * L1._length2D;
1483 if ( L.IsCommonEdgeShared( *L._leftLine ))
1484 L._leftLine->_lEdges.back() = L0;
1487 L._lEdges.erase( L._lEdges.end()-nbRemove-1,
1488 L._lEdges.end()-nbRemove );
1490 L._lEdges.erase( L._lEdges.begin()+1,
1491 L._lEdges.begin()+1+nbRemove );
1498 //================================================================================
1500 * \brief Remove intersection of _PolyLine's
1502 //================================================================================
1504 bool _ViscousBuilder2D::fixCollisions()
1506 // look for intersections of _Segment's by intersecting _LayerEdge's with
1508 vector< const _Segment* > foundSegs;
1509 _SegmentIntersection intersection;
1511 list< pair< _LayerEdge*, double > > edgeLenLimitList;
1512 list< _LayerEdge* > blockedEdgesList;
1514 for ( size_t iL1 = 0; iL1 < _polyLineVec.size(); ++iL1 )
1516 _PolyLine& L1 = _polyLineVec[ iL1 ];
1517 //if ( !L1._advancable ) continue;
1518 for ( size_t iL2 = 0; iL2 < L1._reachableLines.size(); ++iL2 )
1520 _PolyLine& L2 = * L1._reachableLines[ iL2 ];
1521 for ( size_t iLE = L1.FirstLEdge(); iLE < L1._lEdges.size(); ++iLE )
1523 _LayerEdge& LE1 = L1._lEdges[iLE];
1524 if ( LE1._isBlocked ) continue;
1526 L2._segTree->GetSegmentsNear( LE1._ray, foundSegs );
1527 for ( size_t i = 0; i < foundSegs.size(); ++i )
1529 if ( ! L1.IsAdjacent( *foundSegs[i], &LE1 ) &&
1530 intersection.Compute( *foundSegs[i], LE1._ray ))
1532 const double dist2DToL2 = intersection._param2;
1533 double newLen2D = dist2DToL2 / 2;
1534 if ( newLen2D < 1.1 * LE1._length2D ) // collision!
1536 if ( newLen2D > 0 || !L1._advancable )
1538 blockedEdgesList.push_back( &LE1 );
1539 if ( L1._advancable && newLen2D > 0 )
1541 edgeLenLimitList.push_back( make_pair( &LE1, newLen2D ));
1542 blockedEdgesList.push_back( &L2._lEdges[ foundSegs[i]->_indexInLine ]);
1543 blockedEdgesList.push_back( &L2._lEdges[ foundSegs[i]->_indexInLine + 1 ]);
1545 else // here dist2DToL2 < 0 and LE1._length2D == 0
1547 _LayerEdge* LE2[2] = { & L2._lEdges[ foundSegs[i]->_indexInLine ],
1548 & L2._lEdges[ foundSegs[i]->_indexInLine + 1 ] };
1549 _Segment outSeg2( LE2[0]->_uvOut, LE2[1]->_uvOut );
1550 intersection.Compute( outSeg2, LE1._ray );
1551 newLen2D = intersection._param2 / 2;
1554 edgeLenLimitList.push_back( make_pair( LE2[0], newLen2D ));
1555 edgeLenLimitList.push_back( make_pair( LE2[1], newLen2D ));
1566 // limit length of _LayerEdge's that are extrema of _PolyLine's
1567 // to avoid intersection of these _LayerEdge's
1568 for ( size_t iL1 = 0; iL1 < _polyLineVec.size(); ++iL1 )
1570 _PolyLine& L = _polyLineVec[ iL1 ];
1571 if ( L._lEdges.size() < 4 ) // all intermediate _LayerEdge's intersect with extremum ones
1573 _LayerEdge& LEL = L._leftLine->_lEdges.back();
1574 _LayerEdge& LER = L._lEdges.back();
1575 _Segment segL( LEL._uvOut, LEL._uvIn );
1576 _Segment segR( LER._uvOut, LER._uvIn );
1577 double newLen2DL, newLen2DR;
1578 if ( intersection.Compute( segL, LER._ray ))
1580 newLen2DR = intersection._param2 / 2;
1581 newLen2DL = LEL._length2D * intersection._param1 / 2;
1583 else if ( intersection.Compute( segR, LEL._ray ))
1585 newLen2DL = intersection._param2 / 2;
1586 newLen2DR = LER._length2D * intersection._param1 / 2;
1592 if ( newLen2DL > 0 && newLen2DR > 0 )
1594 if ( newLen2DL < 1.1 * LEL._length2D )
1595 edgeLenLimitList.push_back( make_pair( &LEL, newLen2DL ));
1596 if ( newLen2DR < 1.1 * LER._length2D )
1597 edgeLenLimitList.push_back( make_pair( &LER, newLen2DR ));
1602 // set limited length to _LayerEdge's
1603 list< pair< _LayerEdge*, double > >::iterator edge2Len = edgeLenLimitList.begin();
1604 for ( ; edge2Len != edgeLenLimitList.end(); ++edge2Len )
1606 _LayerEdge* LE = edge2Len->first;
1607 if ( LE->_length2D > edge2Len->second )
1609 LE->_isBlocked = false;
1610 LE->SetNewLength( edge2Len->second / LE->_len2dTo3dRatio );
1612 LE->_isBlocked = true;
1615 // block inflation of _LayerEdge's
1616 list< _LayerEdge* >::iterator edge = blockedEdgesList.begin();
1617 for ( ; edge != blockedEdgesList.end(); ++edge )
1618 (*edge)->_isBlocked = true;
1620 // find a not blocked _LayerEdge
1621 for ( size_t iL = 0; iL < _polyLineVec.size(); ++iL )
1623 _PolyLine& L = _polyLineVec[ iL ];
1624 if ( !L._advancable ) continue;
1625 for ( size_t iLE = L.FirstLEdge(); iLE < L._lEdges.size(); ++iLE )
1626 if ( !L._lEdges[ iLE ]._isBlocked )
1633 //================================================================================
1635 * \brief Create new edges and shrink edges existing on a non-advancable _PolyLine
1636 * adjacent to an advancable one.
1638 //================================================================================
1640 bool _ViscousBuilder2D::shrink()
1642 gp_Pnt2d uv; //gp_Vec2d tangent;
1643 _SegmentIntersection intersection;
1646 for ( size_t iL1 = 0; iL1 < _polyLineVec.size(); ++iL1 )
1648 _PolyLine& L = _polyLineVec[ iL1 ]; // line with no layers
1649 if ( L._advancable )
1651 const int nbAdvancable = ( L._rightLine->_advancable + L._leftLine->_advancable );
1652 if ( nbAdvancable == 0 )
1655 const TopoDS_Vertex& V1 = L._wire->FirstVertex( L._edgeInd );
1656 const TopoDS_Vertex& V2 = L._wire->LastVertex ( L._edgeInd );
1657 const int v1ID = getMeshDS()->ShapeToIndex( V1 );
1658 const int v2ID = getMeshDS()->ShapeToIndex( V2 );
1659 const bool isShrinkableL = ! _noShrinkVert.count( v1ID ) && L._leftLine->_advancable;
1660 const bool isShrinkableR = ! _noShrinkVert.count( v2ID ) && L._rightLine->_advancable;
1661 if ( !isShrinkableL && !isShrinkableR )
1664 const TopoDS_Edge& E = L._wire->Edge ( L._edgeInd );
1665 const int edgeID = L._wire->EdgeID ( L._edgeInd );
1666 const double edgeLen = L._wire->EdgeLength ( L._edgeInd );
1667 Handle(Geom2d_Curve) pcurve = L._wire->Curve2d ( L._edgeInd );
1668 const bool edgeReversed = ( E.Orientation() == TopAbs_REVERSED );
1670 SMESH_MesherHelper helper( *_mesh ); // to create nodes and edges on E
1671 helper.SetSubShape( E );
1672 helper.SetElementsOnShape( true );
1674 // Check a FACE adjacent to _face by E
1675 bool existingNodesFound = false;
1676 TopoDS_Face adjFace;
1677 PShapeIteratorPtr faceIt = _helper.GetAncestors( E, *_mesh, TopAbs_FACE );
1678 while ( const TopoDS_Shape* f = faceIt->next() )
1679 if ( !_face.IsSame( *f ))
1681 adjFace = TopoDS::Face( *f );
1682 SMESH_ProxyMesh::Ptr pm = _ProxyMeshHolder::FindProxyMeshOfFace( adjFace, *_mesh );
1683 if ( !pm || pm->NbProxySubMeshes() == 0 /*|| !pm->GetProxySubMesh( E )*/)
1685 // There are no viscous layers on an adjacent FACE, clear it's 2D mesh
1686 removeMeshFaces( adjFace );
1687 // if ( removeMeshFaces( adjFace ))
1688 // _clearedFaces.push_back( adjFace ); // to re-compute after all
1692 // There are viscous layers on the adjacent FACE; shrink must be already done;
1696 const vector<UVPtStruct>& points = L._wire->GetUVPtStruct();
1697 int iPFrom = L._firstPntInd, iPTo = L._lastPntInd;
1698 if ( isShrinkableL )
1700 const THypVL* hyp = getLineHypothesis( L._leftLine->_index );
1701 vector<gp_XY>& uvVec = L._lEdges.front()._uvRefined;
1702 for ( int i = 0; i < hyp->GetNumberLayers(); ++i ) {
1703 const UVPtStruct& uvPt = points[ iPFrom + i + 1 ];
1704 L._leftNodes.push_back( uvPt.node );
1705 uvVec.push_back ( pcurve->Value( uvPt.param ).XY() );
1707 iPFrom += hyp->GetNumberLayers();
1709 if ( isShrinkableR )
1711 const THypVL* hyp = getLineHypothesis( L._rightLine->_index );
1712 vector<gp_XY>& uvVec = L._lEdges.back()._uvRefined;
1713 for ( int i = 0; i < hyp->GetNumberLayers(); ++i ) {
1714 const UVPtStruct& uvPt = points[ iPTo - i - 1 ];
1715 L._rightNodes.push_back( uvPt.node );
1716 uvVec.push_back ( pcurve->Value( uvPt.param ).XY() );
1718 iPTo -= hyp->GetNumberLayers();
1720 // make proxy sub-mesh data of present nodes
1722 UVPtStructVec nodeDataVec( & points[ iPFrom ], & points[ iPTo + 1 ]);
1724 double normSize = nodeDataVec.back().normParam - nodeDataVec.front().normParam;
1725 for ( int iP = nodeDataVec.size()-1; iP >= 0 ; --iP )
1726 nodeDataVec[iP].normParam =
1727 ( nodeDataVec[iP].normParam - nodeDataVec[0].normParam ) / normSize;
1729 const SMDS_MeshNode* n = nodeDataVec.front().node;
1730 if ( n->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX )
1731 nodeDataVec.front().param = L._wire->FirstU( L._edgeInd );
1732 n = nodeDataVec.back().node;
1733 if ( n->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX )
1734 nodeDataVec.back().param = L._wire->LastU( L._edgeInd );
1736 _ProxyMeshOfFace::_EdgeSubMesh* myEdgeSM = getProxyMesh()->GetEdgeSubMesh( edgeID );
1737 myEdgeSM->SetUVPtStructVec( nodeDataVec );
1739 existingNodesFound = true;
1742 } // loop on FACEs sharing E
1744 // Commented as a case with a seam EDGE (issue 0052461) is hard to support
1745 // because SMESH_ProxyMesh can't hold different sub-meshes for two
1746 // 2D representations of the seam. But such a case is not a real practice one.
1747 // Check if L is an already shrinked seam
1748 // if ( adjFace.IsNull() && _helper.IsRealSeam( edgeID ))
1750 // for ( int iL2 = iL1-1; iL2 > -1; --iL2 )
1752 // _PolyLine& L2 = _polyLineVec[ iL2 ];
1753 // if ( edgeID == L2._wire->EdgeID( L2._edgeInd ))
1755 // // copy layer nodes
1756 // const int seamPar = _helper.GetPeriodicIndex();
1757 // vector<gp_XY>& uvVec = L._lEdges.front()._uvRefined;
1758 // if ( isShrinkableL )
1760 // L._leftNodes = L2._rightNodes;
1761 // uvVec = L2._lEdges.back()._uvRefined;
1763 // if ( isShrinkableR )
1765 // L._rightNodes = L2._leftNodes;
1766 // uvVec = L2._lEdges.front()._uvRefined;
1768 // for ( size_t i = 0; i < uvVec.size(); ++i )
1770 // gp_XY & uv = uvVec[i];
1771 // uv.SetCoord( seamPar, _helper.GetOtherParam( uv.Coord( seamPar )));
1774 // existingNodesFound = true;
1780 if ( existingNodesFound )
1781 continue; // nothing more to do in this case
1783 double u1 = L._wire->FirstU( L._edgeInd ), uf = u1;
1784 double u2 = L._wire->LastU ( L._edgeInd ), ul = u2;
1786 // a ratio to pass 2D <--> 1D
1787 const double len1D = 1e-3;
1788 const double len2D = pcurve->Value(uf).Distance( pcurve->Value(uf+len1D));
1789 double len1dTo2dRatio = len1D / len2D;
1791 // create a vector of proxy nodes
1792 const vector<UVPtStruct>& points = L._wire->GetUVPtStruct();
1793 UVPtStructVec nodeDataVec( & points[ L._firstPntInd ],
1794 & points[ L._lastPntInd + 1 ]);
1795 nodeDataVec.front().param = u1; // U on vertex is correct on only one of shared edges
1796 nodeDataVec.back ().param = u2;
1797 nodeDataVec.front().normParam = 0;
1798 nodeDataVec.back ().normParam = 1;
1800 // Get length of existing segments (from an edge start to a node) and their nodes
1801 vector< double > segLengths( nodeDataVec.size() - 1 );
1802 BRepAdaptor_Curve curve( E );
1803 for ( size_t iP = 1; iP < nodeDataVec.size(); ++iP )
1805 const double len = GCPnts_AbscissaPoint::Length( curve, uf, nodeDataVec[iP].param );
1806 segLengths[ iP-1 ] = len;
1809 // Move first and last parameters on EDGE (U of n1) according to layers' thickness
1810 // and create nodes of layers on EDGE ( -x-x-x )
1814 // x-----x-----x-----x-----
1819 // x-x-x-x-----x-----x----
1822 int isRShrinkedForAdjacent;
1823 UVPtStructVec nodeDataForAdjacent;
1824 for ( int isR = 0; isR < 2; ++isR )
1826 _PolyLine* L2 = isR ? L._rightLine : L._leftLine; // line with layers
1827 if ( !L2->_advancable &&
1828 !toShrinkForAdjacent( adjFace, E, L._wire->FirstVertex( L._edgeInd + isR )))
1830 if ( isR ? !isShrinkableR : !isShrinkableL )
1833 double & u = isR ? u2 : u1; // param to move
1834 double u0 = isR ? ul : uf; // init value of the param to move
1835 int iPEnd = isR ? nodeDataVec.size() - 1 : 0;
1837 _LayerEdge& nearLE = isR ? L._lEdges.back() : L._lEdges.front();
1838 _LayerEdge& farLE = isR ? L._lEdges.front() : L._lEdges.back();
1840 // try to find length of advancement along L by intersecting L with
1841 // an adjacent _Segment of L2
1843 double& length2D = nearLE._length2D;
1844 double length1D = 0;
1845 sign = ( isR ^ edgeReversed ) ? -1. : 1.;
1847 bool isConvex = false;
1848 if ( L2->_advancable )
1850 const uvPtStruct& tang2P1 = points[ isR ? L2->_firstPntInd : L2->_lastPntInd ];
1851 const uvPtStruct& tang2P2 = points[ isR ? L2->_firstPntInd+1 : L2->_lastPntInd-1 ];
1852 gp_XY seg2Dir( tang2P2.u - tang2P1.u,
1853 tang2P2.v - tang2P1.v );
1854 int iFSeg2 = isR ? 0 : L2->_segments.size() - 1;
1855 int iLSeg2 = isR ? 1 : L2->_segments.size() - 2;
1856 gp_XY uvLSeg2In = L2->_lEdges[ iLSeg2 ]._uvIn;
1857 Handle(Geom2d_Line) seg2Line = new Geom2d_Line( uvLSeg2In, seg2Dir );
1859 Geom2dAdaptor_Curve edgeCurve( pcurve, Min( uf, ul ), Max( uf, ul ));
1860 Geom2dAdaptor_Curve seg2Curve( seg2Line );
1861 Geom2dInt_GInter curveInt( edgeCurve, seg2Curve, 1e-7, 1e-7 );
1862 isConvex = ( curveInt.IsDone() && !curveInt.IsEmpty() );
1865 length1D = Abs( u - curveInt.Point( 1 ).ParamOnFirst() );
1866 double maxDist2d = 2 * L2->_lEdges[ iLSeg2 ]._length2D;
1867 isConvex = ( length1D < maxDist2d * len1dTo2dRatio );
1874 if ( !isConvex ) { /* concave VERTEX */ /* o-----o---
1880 length2D = L2->_lEdges[ iFSeg2 ]._length2D;
1881 //if ( L2->_advancable ) continue;
1884 else // L2 is advancable but in the face adjacent by L
1886 length2D = farLE._length2D;
1887 if ( length2D == 0 ) {
1888 _LayerEdge& neighborLE =
1889 ( isR ? L._leftLine->_lEdges.back() : L._rightLine->_lEdges.front() );
1890 length2D = neighborLE._length2D;
1891 if ( length2D == 0 )
1892 length2D = _maxThickness * nearLE._len2dTo3dRatio;
1896 // move u to the internal boundary of layers
1898 // x-x-x-x-----x-----x----
1899 double maxLen3D = Min( _maxThickness, edgeLen / ( 1 + nbAdvancable ));
1900 double maxLen2D = maxLen3D * nearLE._len2dTo3dRatio;
1901 if ( !length2D ) length2D = length1D / len1dTo2dRatio;
1902 if ( Abs( length2D ) > maxLen2D )
1903 length2D = maxLen2D;
1904 nearLE._uvIn = nearLE._uvOut + nearLE._normal2D * length2D;
1906 u += length2D * len1dTo2dRatio * sign;
1907 nodeDataVec[ iPEnd ].param = u;
1909 gp_Pnt2d newUV = pcurve->Value( u );
1910 nodeDataVec[ iPEnd ].u = newUV.X();
1911 nodeDataVec[ iPEnd ].v = newUV.Y();
1913 // compute params of layers on L
1914 vector<double> heights;
1915 const THypVL* hyp = getLineHypothesis( L2->_index );
1916 calcLayersHeight( u - u0, heights, hyp );
1918 vector< double > params( heights.size() );
1919 for ( size_t i = 0; i < params.size(); ++i )
1920 params[ i ] = u0 + heights[ i ];
1922 // create nodes of layers and edges between them
1924 vector< const SMDS_MeshNode* >& layersNode = isR ? L._rightNodes : L._leftNodes;
1925 vector<gp_XY>& nodeUV = ( isR ? L._lEdges.back() : L._lEdges[0] )._uvRefined;
1926 nodeUV.resize ( hyp->GetNumberLayers() );
1927 layersNode.resize( hyp->GetNumberLayers() );
1928 const SMDS_MeshNode* vertexNode = nodeDataVec[ iPEnd ].node;
1929 const SMDS_MeshNode * prevNode = vertexNode;
1930 for ( size_t i = 0; i < params.size(); ++i )
1932 const gp_Pnt p = curve.Value( params[i] );
1933 layersNode[ i ] = helper.AddNode( p.X(), p.Y(), p.Z(), /*id=*/0, params[i] );
1934 nodeUV [ i ] = pcurve->Value( params[i] ).XY();
1935 helper.AddEdge( prevNode, layersNode[ i ] );
1936 prevNode = layersNode[ i ];
1939 // store data of layer nodes made for adjacent FACE
1940 if ( !L2->_advancable )
1942 isRShrinkedForAdjacent = isR;
1943 nodeDataForAdjacent.resize( hyp->GetNumberLayers() );
1945 size_t iFrw = 0, iRev = nodeDataForAdjacent.size()-1, *i = isR ? &iRev : &iFrw;
1946 nodeDataForAdjacent[ *i ] = points[ isR ? L._lastPntInd : L._firstPntInd ];
1947 nodeDataForAdjacent[ *i ].param = u0;
1948 nodeDataForAdjacent[ *i ].normParam = isR;
1949 for ( ++iFrw, --iRev; iFrw < layersNode.size(); ++iFrw, --iRev )
1951 nodeDataForAdjacent[ *i ].node = layersNode[ iFrw - 1 ];
1952 nodeDataForAdjacent[ *i ].u = nodeUV [ iFrw - 1 ].X();
1953 nodeDataForAdjacent[ *i ].v = nodeUV [ iFrw - 1 ].Y();
1954 nodeDataForAdjacent[ *i ].param = params [ iFrw - 1 ];
1957 // replace a node on vertex by a node of last (most internal) layer
1958 // in a segment on E
1959 SMDS_ElemIteratorPtr segIt = vertexNode->GetInverseElementIterator( SMDSAbs_Edge );
1960 const SMDS_MeshNode* segNodes[3];
1961 while ( segIt->more() )
1963 const SMDS_MeshElement* segment = segIt->next();
1964 if ( segment->getshapeId() != edgeID ) continue;
1966 const int nbNodes = segment->NbNodes();
1967 for ( int i = 0; i < nbNodes; ++i )
1969 const SMDS_MeshNode* n = segment->GetNode( i );
1970 segNodes[ i ] = ( n == vertexNode ? layersNode.back() : n );
1972 getMeshDS()->ChangeElementNodes( segment, segNodes, nbNodes );
1975 nodeDataVec[ iPEnd ].node = layersNode.back();
1977 } // loop on the extremities of L
1979 // Shrink edges to fit in between the layers at EDGE ends
1981 double newLength = GCPnts_AbscissaPoint::Length( curve, u1, u2 );
1982 double lenRatio = newLength / edgeLen * ( edgeReversed ? -1. : 1. );
1983 for ( size_t iP = 1; iP < nodeDataVec.size()-1; ++iP )
1985 const SMDS_MeshNode* oldNode = nodeDataVec[iP].node;
1987 GCPnts_AbscissaPoint discret( curve, segLengths[iP-1] * lenRatio, u1 );
1988 if ( !discret.IsDone() )
1989 throw SALOME_Exception(LOCALIZED("GCPnts_AbscissaPoint failed"));
1991 nodeDataVec[iP].param = discret.Parameter();
1992 if ( oldNode->GetPosition()->GetTypeOfPosition() != SMDS_TOP_EDGE )
1993 throw SALOME_Exception(SMESH_Comment("ViscousBuilder2D: not SMDS_TOP_EDGE node position: ")
1994 << oldNode->GetPosition()->GetTypeOfPosition()
1995 << " of node " << oldNode->GetID());
1996 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( oldNode->GetPosition() );
1997 pos->SetUParameter( nodeDataVec[iP].param );
1999 gp_Pnt newP = curve.Value( nodeDataVec[iP].param );
2000 getMeshDS()->MoveNode( oldNode, newP.X(), newP.Y(), newP.Z() );
2002 gp_Pnt2d newUV = pcurve->Value( nodeDataVec[iP].param ).XY();
2003 nodeDataVec[iP].u = newUV.X();
2004 nodeDataVec[iP].v = newUV.Y();
2005 nodeDataVec[iP].normParam = segLengths[iP-1] / edgeLen;
2006 // nodeDataVec[iP].x = segLengths[iP-1] / edgeLen;
2007 // nodeDataVec[iP].y = segLengths[iP-1] / edgeLen;
2010 // Add nodeDataForAdjacent to nodeDataVec
2012 if ( !nodeDataForAdjacent.empty() )
2014 const double par1 = isRShrinkedForAdjacent ? u2 : uf;
2015 const double par2 = isRShrinkedForAdjacent ? ul : u1;
2016 const double shrinkLen = GCPnts_AbscissaPoint::Length( curve, par1, par2 );
2018 // compute new normParam for nodeDataVec
2019 for ( size_t iP = 0; iP < nodeDataVec.size()-1; ++iP )
2020 nodeDataVec[iP+1].normParam = segLengths[iP] / ( edgeLen + shrinkLen );
2021 double normDelta = 1 - nodeDataVec.back().normParam;
2022 if ( !isRShrinkedForAdjacent )
2023 for ( size_t iP = 0; iP < nodeDataVec.size(); ++iP )
2024 nodeDataVec[iP].normParam += normDelta;
2026 // compute new normParam for nodeDataForAdjacent
2027 const double deltaR = isRShrinkedForAdjacent ? nodeDataVec.back().normParam : 0;
2028 for ( size_t iP = !isRShrinkedForAdjacent; iP < nodeDataForAdjacent.size(); ++iP )
2030 double lenFromPar1 =
2031 GCPnts_AbscissaPoint::Length( curve, par1, nodeDataForAdjacent[iP].param );
2032 nodeDataForAdjacent[iP].normParam = deltaR + normDelta * lenFromPar1 / shrinkLen;
2034 // concatenate nodeDataVec and nodeDataForAdjacent
2035 nodeDataVec.insert(( isRShrinkedForAdjacent ? nodeDataVec.end() : nodeDataVec.begin() ),
2036 nodeDataForAdjacent.begin(), nodeDataForAdjacent.end() );
2039 // Extend nodeDataVec by a node located at the end of not shared _LayerEdge
2040 /* n - to add to nodeDataVec
2049 for ( int isR = 0; isR < 2; ++isR )
2051 _PolyLine& L2 = *( isR ? L._rightLine : L._leftLine ); // line with layers
2052 if ( ! L2._advancable || L.IsCommonEdgeShared( L2 ) )
2054 vector< const SMDS_MeshNode* >& layerNodes2 = isR ? L2._leftNodes : L2._rightNodes;
2055 _LayerEdge& LE2 = isR ? L2._lEdges.front() : L2._lEdges.back();
2056 if ( layerNodes2.empty() )
2058 // refine the not shared _LayerEdge
2059 vector<double> layersHeight;
2060 calcLayersHeight( LE2._length2D, layersHeight, getLineHypothesis( L2._index ));
2062 vector<gp_XY>& nodeUV2 = LE2._uvRefined;
2063 nodeUV2.resize ( layersHeight.size() );
2064 layerNodes2.resize( layersHeight.size() );
2065 for ( size_t i = 0; i < layersHeight.size(); ++i )
2067 gp_XY uv = LE2._uvOut + LE2._normal2D * layersHeight[i];
2068 gp_Pnt p = _surface->Value( uv.X(), uv.Y() );
2070 layerNodes2[ i ] = _helper.AddNode( p.X(), p.Y(), p.Z(), /*id=*/0, uv.X(), uv.Y() );
2073 UVPtStruct ptOfNode;
2074 ptOfNode.u = LE2._uvRefined.back().X();
2075 ptOfNode.v = LE2._uvRefined.back().Y();
2076 ptOfNode.node = layerNodes2.back();
2077 ptOfNode.param = isR ? ul : uf;
2078 ptOfNode.normParam = isR ? 1 : 0;
2080 nodeDataVec.insert(( isR ? nodeDataVec.end() : nodeDataVec.begin() ), ptOfNode );
2082 // recompute normParam of nodes in nodeDataVec
2083 newLength = GCPnts_AbscissaPoint::Length( curve,
2084 nodeDataVec.front().param,
2085 nodeDataVec.back().param);
2086 for ( size_t iP = 1; iP < nodeDataVec.size(); ++iP )
2088 const double len = GCPnts_AbscissaPoint::Length( curve,
2089 nodeDataVec.front().param,
2090 nodeDataVec[iP].param );
2091 nodeDataVec[iP].normParam = len / newLength;
2095 // create a proxy sub-mesh containing the moved nodes
2096 _ProxyMeshOfFace::_EdgeSubMesh* edgeSM = getProxyMesh()->GetEdgeSubMesh( edgeID );
2097 edgeSM->SetUVPtStructVec( nodeDataVec );
2099 // set a sub-mesh event listener to remove just created edges when
2100 // "ViscousLayers2D" hypothesis is modified
2101 VISCOUS_3D::ToClearSubWithMain( _mesh->GetSubMesh( E ), _face );
2103 } // loop on _polyLineVec
2108 //================================================================================
2110 * \brief Returns true if there will be a shrinked mesh on EDGE E of FACE adjFace
2113 //================================================================================
2115 bool _ViscousBuilder2D::toShrinkForAdjacent( const TopoDS_Face& adjFace,
2116 const TopoDS_Edge& E,
2117 const TopoDS_Vertex& V)
2119 if ( _noShrinkVert.count( getMeshDS()->ShapeToIndex( V )) || adjFace.IsNull() )
2122 vector< const StdMeshers_ViscousLayers2D* > hyps;
2123 vector< TopoDS_Shape > hypShapes;
2124 if ( VISCOUS_2D::findHyps( *_mesh, adjFace, hyps, hypShapes ))
2126 VISCOUS_2D::_ViscousBuilder2D builder( *_mesh, adjFace, hyps, hypShapes );
2127 builder._faceSideVec = StdMeshers_FaceSide::GetFaceWires( adjFace, *_mesh, true, _error );
2128 builder.findEdgesWithLayers();
2130 PShapeIteratorPtr edgeIt = _helper.GetAncestors( V, *_mesh, TopAbs_EDGE );
2131 while ( const TopoDS_Shape* edgeAtV = edgeIt->next() )
2133 if ( !edgeAtV->IsSame( E ) &&
2134 _helper.IsSubShape( *edgeAtV, adjFace ) &&
2135 !builder._ignoreShapeIds.count( getMeshDS()->ShapeToIndex( *edgeAtV )))
2144 //================================================================================
2148 //================================================================================
2150 bool _ViscousBuilder2D::refine()
2152 // find out orientation of faces to create
2154 ( _helper.GetSubShapeOri( _mesh->GetShapeToMesh(), _face ) == TopAbs_REVERSED );
2156 // store a proxyMesh in a sub-mesh
2157 // make faces on each _PolyLine
2158 vector< double > layersHeight;
2159 //double prevLen2D = -1;
2160 for ( size_t iL = 0; iL < _polyLineVec.size(); ++iL )
2162 _PolyLine& L = _polyLineVec[ iL ];
2163 if ( !L._advancable ) continue;
2165 // replace an inactive (1st) _LayerEdge with an active one of a neighbour _PolyLine
2166 //size_t iLE = 0, nbLE = L._lEdges.size();
2167 const bool leftEdgeShared = L.IsCommonEdgeShared( *L._leftLine );
2168 const bool rightEdgeShared = L.IsCommonEdgeShared( *L._rightLine );
2169 if ( /*!L._leftLine->_advancable &&*/ leftEdgeShared )
2171 L._lEdges[0] = L._leftLine->_lEdges.back();
2172 //iLE += int( !L._leftLine->_advancable );
2174 if ( !L._rightLine->_advancable && rightEdgeShared )
2176 L._lEdges.back() = L._rightLine->_lEdges[0];
2180 // limit length of neighbour _LayerEdge's to avoid sharp change of layers thickness
2182 vector< double > segLen( L._lEdges.size() );
2185 // check if length modification is usefull: look for _LayerEdge's
2186 // with length limited due to collisions
2187 bool lenLimited = false;
2188 for ( size_t iLE = 1; ( iLE < L._lEdges.size()-1 && !lenLimited ); ++iLE )
2189 lenLimited = L._lEdges[ iLE ]._isBlocked;
2193 for ( size_t i = 1; i < segLen.size(); ++i )
2195 // accumulate length of segments
2196 double sLen = (L._lEdges[i-1]._uvOut - L._lEdges[i]._uvOut ).Modulus();
2197 segLen[i] = segLen[i-1] + sLen;
2199 const double totSegLen = segLen.back();
2200 // normalize the accumulated length
2201 for ( size_t iS = 1; iS < segLen.size(); ++iS )
2202 segLen[iS] /= totSegLen;
2204 for ( int isR = 0; isR < 2; ++isR )
2206 size_t iF = 0, iL = L._lEdges.size()-1;
2207 size_t *i = isR ? &iL : &iF;
2208 _LayerEdge* prevLE = & L._lEdges[ *i ];
2210 for ( ++iF, --iL; iF < L._lEdges.size()-1; ++iF, --iL )
2212 _LayerEdge& LE = L._lEdges[*i];
2213 if ( prevLE->_length2D > 0 )
2215 gp_XY tangent ( LE._normal2D.Y(), -LE._normal2D.X() );
2216 weight += Abs( tangent * ( prevLE->_uvIn - LE._uvIn )) / totSegLen;
2217 // gp_XY prevTang( LE._uvOut - prevLE->_uvOut );
2218 // gp_XY prevNorm( -prevTang.Y(), prevTang.X() );
2219 gp_XY prevNorm = LE._normal2D;
2220 double prevProj = prevNorm * ( prevLE->_uvIn - prevLE->_uvOut );
2221 if ( prevProj > 0 ) {
2222 prevProj /= prevNorm.Modulus();
2223 if ( LE._length2D < prevProj )
2224 weight += 0.75 * ( 1 - weight ); // length decrease is more preferable
2225 LE._length2D = weight * LE._length2D + ( 1 - weight ) * prevProj;
2226 LE._uvIn = LE._uvOut + LE._normal2D * LE._length2D;
2233 // DEBUG: to see _uvRefined. cout can be redirected to hide NETGEN output
2234 // cerr << "import smesh" << endl << "mesh = smesh.Mesh()"<< endl;
2236 const vector<UVPtStruct>& points = L._wire->GetUVPtStruct();
2238 // analyse extremities of the _PolyLine to find existing nodes
2239 const TopoDS_Vertex& V1 = L._wire->FirstVertex( L._edgeInd );
2240 const TopoDS_Vertex& V2 = L._wire->LastVertex ( L._edgeInd );
2241 const int v1ID = getMeshDS()->ShapeToIndex( V1 );
2242 const int v2ID = getMeshDS()->ShapeToIndex( V2 );
2243 const bool isShrinkableL = ! _noShrinkVert.count( v1ID );
2244 const bool isShrinkableR = ! _noShrinkVert.count( v2ID );
2246 bool hasLeftNode = ( !L._leftLine->_rightNodes.empty() && leftEdgeShared );
2247 bool hasRightNode = ( !L._rightLine->_leftNodes.empty() && rightEdgeShared );
2248 bool hasOwnLeftNode = ( !L._leftNodes.empty() );
2249 bool hasOwnRightNode = ( !L._rightNodes.empty() );
2250 bool isClosedEdge = ( points[ L._firstPntInd ].node == points[ L._lastPntInd ].node );
2252 nbN = L._lastPntInd - L._firstPntInd + 1,
2253 iN0 = ( hasLeftNode || hasOwnLeftNode || isClosedEdge || !isShrinkableL ),
2254 iNE = nbN - ( hasRightNode || hasOwnRightNode || !isShrinkableR );
2256 // update _uvIn of end _LayerEdge's by existing nodes
2257 const SMDS_MeshNode *nL = 0, *nR = 0;
2258 if ( hasOwnLeftNode ) nL = L._leftNodes.back();
2259 else if ( hasLeftNode ) nL = L._leftLine->_rightNodes.back();
2260 if ( hasOwnRightNode ) nR = L._rightNodes.back();
2261 else if ( hasRightNode ) nR = L._rightLine->_leftNodes.back();
2263 L._lEdges[0]._uvIn = _helper.GetNodeUV( _face, nL, points[ L._firstPntInd + 1 ].node );
2265 L._lEdges.back()._uvIn = _helper.GetNodeUV( _face, nR, points[ L._lastPntInd - 1 ].node );
2267 // compute normalized [0;1] node parameters of nodes on a _PolyLine
2268 vector< double > normPar( nbN );
2270 normF = L._wire->FirstParameter( L._edgeInd ),
2271 normL = L._wire->LastParameter ( L._edgeInd ),
2272 normDist = normL - normF;
2273 for ( int i = L._firstPntInd; i <= L._lastPntInd; ++i )
2274 normPar[ i - L._firstPntInd ] = ( points[i].normParam - normF ) / normDist;
2276 // Calculate UV of most inner nodes
2278 vector< gp_XY > innerUV( nbN );
2280 // check if innerUV should be interpolated between _LayerEdge::_uvIn's
2281 const size_t nbLE = L._lEdges.size();
2282 bool needInterpol = ( nbN != nbLE );
2283 if ( !needInterpol )
2285 // more check: compare length of inner and outer end segments
2286 double lenIn, lenOut;
2287 for ( int isR = 0; isR < 2 && !needInterpol; ++isR )
2289 const _Segment& segIn = isR ? L._segments.back() : L._segments[0];
2290 const gp_XY& uvIn1 = segIn.p1();
2291 const gp_XY& uvIn2 = segIn.p2();
2292 const gp_XY& uvOut1 = L._lEdges[ isR ? nbLE-1 : 0 ]._uvOut;
2293 const gp_XY& uvOut2 = L._lEdges[ isR ? nbLE-2 : 1 ]._uvOut;
2294 if ( _is2DIsotropic )
2296 lenIn = ( uvIn1 - uvIn2 ).Modulus();
2297 lenOut = ( uvOut1 - uvOut2 ).Modulus();
2301 lenIn = _surface->Value( uvIn1.X(), uvIn1.Y() )
2302 .Distance( _surface->Value( uvIn2.X(), uvIn2.Y() ));
2303 lenOut = _surface->Value( uvOut1.X(), uvOut1.Y() )
2304 .Distance( _surface->Value( uvOut2.X(), uvOut2.Y() ));
2306 needInterpol = ( lenIn < 0.66 * lenOut );
2312 // compute normalized accumulated length of inner segments
2314 if ( _is2DIsotropic )
2315 for ( iS = 1; iS < segLen.size(); ++iS )
2317 double sLen = ( L._lEdges[iS-1]._uvIn - L._lEdges[iS]._uvIn ).Modulus();
2318 segLen[iS] = segLen[iS-1] + sLen;
2321 for ( iS = 1; iS < segLen.size(); ++iS )
2323 const gp_XY& uv1 = L._lEdges[iS-1]._uvIn;
2324 const gp_XY& uv2 = L._lEdges[iS ]._uvIn;
2325 gp_Pnt p1 = _surface->Value( uv1.X(), uv1.Y() );
2326 gp_Pnt p2 = _surface->Value( uv2.X(), uv2.Y() );
2327 double sLen = p1.Distance( p2 );
2328 segLen[iS] = segLen[iS-1] + sLen;
2330 // normalize the accumulated length
2331 for ( iS = 1; iS < segLen.size(); ++iS )
2332 segLen[iS] /= segLen.back();
2334 // calculate UV of most inner nodes according to the normalized node parameters
2336 for ( size_t i = 0; i < innerUV.size(); ++i )
2338 while ( normPar[i] > segLen[iS+1] )
2340 double r = ( normPar[i] - segLen[iS] ) / ( segLen[iS+1] - segLen[iS] );
2341 innerUV[ i ] = r * L._lEdges[iS+1]._uvIn + (1-r) * L._lEdges[iS]._uvIn;
2344 else // ! needInterpol
2346 for ( size_t i = 0; i < nbLE; ++i )
2347 innerUV[ i ] = L._lEdges[i]._uvIn;
2350 // normalized height of layers
2351 const THypVL* hyp = getLineHypothesis( iL );
2352 calcLayersHeight( 1., layersHeight, hyp);
2354 // Create layers of faces
2356 // nodes to create 1 layer of faces
2357 vector< const SMDS_MeshNode* > outerNodes( nbN );
2358 vector< const SMDS_MeshNode* > innerNodes( nbN );
2360 // initialize outerNodes by nodes of the L._wire
2361 for ( int i = L._firstPntInd; i <= L._lastPntInd; ++i )
2362 outerNodes[ i-L._firstPntInd ] = points[i].node;
2364 L._leftNodes .reserve( hyp->GetNumberLayers() );
2365 L._rightNodes.reserve( hyp->GetNumberLayers() );
2366 int cur = 0, prev = -1; // to take into account orientation of _face
2367 if ( isReverse ) std::swap( cur, prev );
2368 for ( int iF = 0; iF < hyp->GetNumberLayers(); ++iF ) // loop on layers of faces
2370 // create innerNodes of a current layer
2371 for ( size_t i = iN0; i < iNE; ++i )
2373 gp_XY uvOut = points[ L._firstPntInd + i ].UV();
2374 gp_XY& uvIn = innerUV[ i ];
2375 gp_XY uv = layersHeight[ iF ] * uvIn + ( 1.-layersHeight[ iF ]) * uvOut;
2376 gp_Pnt p = _surface->Value( uv.X(), uv.Y() );
2377 innerNodes[i] = _helper.AddNode( p.X(), p.Y(), p.Z(), /*id=*/0, uv.X(), uv.Y() );
2379 // use nodes created for adjacent _PolyLine's
2380 if ( hasOwnLeftNode ) innerNodes.front() = L._leftNodes [ iF ];
2381 else if ( hasLeftNode ) innerNodes.front() = L._leftLine->_rightNodes[ iF ];
2382 if ( hasOwnRightNode ) innerNodes.back() = L._rightNodes[ iF ];
2383 else if ( hasRightNode ) innerNodes.back() = L._rightLine->_leftNodes[ iF ];
2384 if ( isClosedEdge ) innerNodes.front() = innerNodes.back(); // circle
2385 if ( !isShrinkableL ) innerNodes.front() = outerNodes.front();
2386 if ( !isShrinkableR ) innerNodes.back() = outerNodes.back();
2387 if ( !hasOwnLeftNode ) L._leftNodes.push_back( innerNodes.front() );
2388 if ( !hasOwnRightNode ) L._rightNodes.push_back( innerNodes.back() );
2391 for ( size_t i = 1; i < innerNodes.size(); ++i )
2392 if ( SMDS_MeshElement* f = _helper.AddFace( outerNodes[ i+prev ], outerNodes[ i+cur ],
2393 innerNodes[ i+cur ], innerNodes[ i+prev ]))
2394 L._newFaces.insert( L._newFaces.end(), f );
2396 outerNodes.swap( innerNodes );
2399 // faces between not shared _LayerEdge's (at concave VERTEX)
2400 for ( int isR = 0; isR < 2; ++isR )
2402 if ( isR ? rightEdgeShared : leftEdgeShared )
2404 vector< const SMDS_MeshNode* > &
2405 lNodes = (isR ? L._rightNodes : L._leftLine->_rightNodes ),
2406 rNodes = (isR ? L._rightLine->_leftNodes : L._leftNodes );
2407 if ( lNodes.empty() || rNodes.empty() || lNodes.size() != rNodes.size() )
2410 for ( size_t i = 1; i < lNodes.size(); ++i )
2411 _helper.AddFace( lNodes[ i+prev ], rNodes[ i+prev ],
2412 rNodes[ i+cur ], lNodes[ i+cur ]);
2414 const UVPtStruct& ptOnVertex = points[ isR ? L._lastPntInd : L._firstPntInd ];
2416 _helper.AddFace( ptOnVertex.node, lNodes[ 0 ], rNodes[ 0 ]);
2418 _helper.AddFace( ptOnVertex.node, rNodes[ 0 ], lNodes[ 0 ]);
2421 // Fill the _ProxyMeshOfFace
2423 UVPtStructVec nodeDataVec( outerNodes.size() ); // outerNodes swapped with innerNodes
2424 for ( size_t i = 0; i < outerNodes.size(); ++i )
2426 gp_XY uv = _helper.GetNodeUV( _face, outerNodes[i] );
2427 nodeDataVec[i].u = uv.X();
2428 nodeDataVec[i].v = uv.Y();
2429 nodeDataVec[i].node = outerNodes[i];
2430 nodeDataVec[i].param = points [i + L._firstPntInd].param;
2431 nodeDataVec[i].normParam = normPar[i];
2432 nodeDataVec[i].x = normPar[i];
2433 nodeDataVec[i].y = normPar[i];
2435 nodeDataVec.front().param = L._wire->FirstU( L._edgeInd );
2436 nodeDataVec.back() .param = L._wire->LastU ( L._edgeInd );
2438 _ProxyMeshOfFace::_EdgeSubMesh* edgeSM
2439 = getProxyMesh()->GetEdgeSubMesh( L._wire->EdgeID( L._edgeInd ));
2440 edgeSM->SetUVPtStructVec( nodeDataVec );
2442 } // loop on _PolyLine's
2444 // re-compute FACEs whose mesh was removed by shrink()
2445 for ( size_t i = 0; i < _clearedFaces.size(); ++i )
2447 SMESH_subMesh* sm = _mesh->GetSubMesh( _clearedFaces[i] );
2448 if ( sm->GetComputeState() == SMESH_subMesh::READY_TO_COMPUTE )
2449 sm->ComputeStateEngine( SMESH_subMesh::COMPUTE );
2455 //================================================================================
2457 * \brief Improve quality of the created mesh elements
2459 //================================================================================
2461 bool _ViscousBuilder2D::improve()
2466 // fixed nodes on EDGE's
2467 std::set<const SMDS_MeshNode*> fixedNodes;
2468 for ( size_t iWire = 0; iWire < _faceSideVec.size(); ++iWire )
2470 StdMeshers_FaceSidePtr wire = _faceSideVec[ iWire ];
2471 const vector<UVPtStruct>& points = wire->GetUVPtStruct();
2472 for ( size_t i = 0; i < points.size(); ++i )
2473 fixedNodes.insert( fixedNodes.end(), points[i].node );
2475 // fixed proxy nodes
2476 for ( size_t iL = 0; iL < _polyLineVec.size(); ++iL )
2478 _PolyLine& L = _polyLineVec[ iL ];
2479 const TopoDS_Edge& E = L._wire->Edge( L._edgeInd );
2480 if ( const SMESH_ProxyMesh::SubMesh* sm = _proxyMesh->GetProxySubMesh( E ))
2482 const UVPtStructVec& points = sm->GetUVPtStructVec();
2483 for ( size_t i = 0; i < points.size(); ++i )
2484 fixedNodes.insert( fixedNodes.end(), points[i].node );
2486 for ( size_t i = 0; i < L._rightNodes.size(); ++i )
2487 fixedNodes.insert( fixedNodes.end(), L._rightNodes[i] );
2491 SMESH_MeshEditor editor( _mesh );
2492 for ( size_t iL = 0; iL < _polyLineVec.size(); ++iL )
2494 _PolyLine& L = _polyLineVec[ iL ];
2495 if ( L._isStraight2D ) continue;
2496 // SMESH_MeshEditor::SmoothMethod how =
2497 // L._isStraight2D ? SMESH_MeshEditor::LAPLACIAN : SMESH_MeshEditor::CENTROIDAL;
2498 //editor.Smooth( L._newFaces, fixedNodes, how, /*nbIt = */3 );
2499 //editor.Smooth( L._newFaces, fixedNodes, SMESH_MeshEditor::LAPLACIAN, /*nbIt = */1 );
2500 editor.Smooth( L._newFaces, fixedNodes, SMESH_MeshEditor::CENTROIDAL, /*nbIt = */3 );
2505 //================================================================================
2507 * \brief Remove elements and nodes from a face
2509 //================================================================================
2511 bool _ViscousBuilder2D::removeMeshFaces(const TopoDS_Shape& face)
2513 // we don't use SMESH_subMesh::ComputeStateEngine() because of a listener
2514 // which clears EDGEs together with _face.
2515 bool thereWereElems = false;
2516 SMESH_subMesh* sm = _mesh->GetSubMesh( face );
2517 if ( SMESHDS_SubMesh* smDS = sm->GetSubMeshDS() )
2519 SMDS_ElemIteratorPtr eIt = smDS->GetElements();
2520 thereWereElems = eIt->more();
2521 while ( eIt->more() ) getMeshDS()->RemoveFreeElement( eIt->next(), smDS );
2522 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
2523 while ( nIt->more() ) getMeshDS()->RemoveFreeNode( nIt->next(), smDS );
2525 sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
2527 return thereWereElems;
2530 //================================================================================
2532 * \brief Returns a hypothesis for a _PolyLine
2534 //================================================================================
2536 const StdMeshers_ViscousLayers2D* _ViscousBuilder2D::getLineHypothesis(int iPL)
2538 return iPL < (int)_hypOfEdge.size() ? _hypOfEdge[ iPL ] : _hyps[0];
2541 //================================================================================
2543 * \brief Returns a layers thickness for a _PolyLine
2545 //================================================================================
2547 double _ViscousBuilder2D::getLineThickness(int iPL)
2549 if ( const StdMeshers_ViscousLayers2D* h = getLineHypothesis( iPL ))
2550 return Min( _maxThickness, h->GetTotalThickness() );
2551 return _maxThickness;
2554 //================================================================================
2556 * \brief Creates a _ProxyMeshOfFace and store it in a sub-mesh of FACE
2558 //================================================================================
2560 _ProxyMeshOfFace* _ViscousBuilder2D::getProxyMesh()
2562 if ( _proxyMesh.get() )
2563 return (_ProxyMeshOfFace*) _proxyMesh.get();
2565 _ProxyMeshOfFace* proxyMeshOfFace = new _ProxyMeshOfFace( *_mesh );
2566 _proxyMesh.reset( proxyMeshOfFace );
2567 new _ProxyMeshHolder( _face, _proxyMesh );
2569 return proxyMeshOfFace;
2572 //================================================================================
2574 * \brief Calculate height of layers for the given thickness. Height is measured
2575 * from the outer boundary
2577 //================================================================================
2579 void _ViscousBuilder2D::calcLayersHeight(const double totalThick,
2580 vector<double>& heights,
2583 const double fPowN = pow( hyp->GetStretchFactor(), hyp->GetNumberLayers() );
2584 heights.resize( hyp->GetNumberLayers() );
2586 if ( fPowN - 1 <= numeric_limits<double>::min() )
2587 h0 = totalThick / hyp->GetNumberLayers();
2589 h0 = totalThick * ( hyp->GetStretchFactor() - 1 )/( fPowN - 1 );
2591 double hSum = 0, hi = h0;
2592 for ( int i = 0; i < hyp->GetNumberLayers(); ++i )
2595 heights[ i ] = hSum;
2596 hi *= hyp->GetStretchFactor();
2600 //================================================================================
2602 * \brief Elongate this _LayerEdge
2604 //================================================================================
2606 bool _LayerEdge::SetNewLength( const double length3D )
2608 if ( _isBlocked ) return false;
2610 //_uvInPrev = _uvIn;
2611 _length2D = length3D * _len2dTo3dRatio;
2612 _uvIn = _uvOut + _normal2D * _length2D;
2616 //================================================================================
2618 * \brief Return true if _LayerEdge at a common VERTEX between EDGEs with
2619 * and w/o layer is common to the both _PolyLine's. If this is true, nodes
2620 * of this _LayerEdge are inflated along a _PolyLine w/o layer, else the nodes
2621 * are inflated along _normal2D of _LayerEdge of EDGE with layer
2623 //================================================================================
2625 bool _PolyLine::IsCommonEdgeShared( const _PolyLine& other )
2627 const double tol = 1e-30;
2629 if ( & other == _leftLine )
2630 return _lEdges[0]._normal2D.IsEqual( _leftLine->_lEdges.back()._normal2D, tol );
2632 if ( & other == _rightLine )
2633 return _lEdges.back()._normal2D.IsEqual( _rightLine->_lEdges[0]._normal2D, tol );
2638 //================================================================================
2640 * \brief Return \c true if the EDGE of this _PolyLine is concave
2642 //================================================================================
2644 bool _PolyLine::IsConcave() const
2646 if ( _lEdges.size() < 2 )
2649 gp_Vec2d v1( _lEdges[0]._uvOut, _lEdges[1]._uvOut );
2650 gp_Vec2d v2( _lEdges[0]._uvOut, _lEdges[2]._uvOut );
2651 const double size2 = v2.Magnitude();
2653 return ( v1 ^ v2 ) / size2 < -1e-3 * size2;
2656 //================================================================================
2658 * \brief Constructor of SegmentTree
2660 //================================================================================
2662 _SegmentTree::_SegmentTree( const vector< _Segment >& segments ):
2665 _segments.resize( segments.size() );
2666 for ( size_t i = 0; i < segments.size(); ++i )
2667 _segments[i].Set( segments[i] );
2672 //================================================================================
2674 * \brief Return the maximal bnd box
2676 //================================================================================
2678 _SegmentTree::box_type* _SegmentTree::buildRootBox()
2680 _SegmentTree::box_type* box = new _SegmentTree::box_type;
2681 for ( size_t i = 0; i < _segments.size(); ++i )
2683 box->Add( *_segments[i]._seg->_uv[0] );
2684 box->Add( *_segments[i]._seg->_uv[1] );
2689 //================================================================================
2691 * \brief Redistrubute _segments among children
2693 //================================================================================
2695 void _SegmentTree::buildChildrenData()
2697 for ( size_t i = 0; i < _segments.size(); ++i )
2698 for (int j = 0; j < nbChildren(); j++)
2699 if ( !myChildren[j]->getBox()->IsOut( *_segments[i]._seg->_uv[0],
2700 *_segments[i]._seg->_uv[1] ))
2701 ((_SegmentTree*)myChildren[j])->_segments.push_back( _segments[i]);
2703 SMESHUtils::FreeVector( _segments ); // = _elements.clear() + free memory
2705 for (int j = 0; j < nbChildren(); j++)
2707 _SegmentTree* child = static_cast<_SegmentTree*>( myChildren[j]);
2708 child->myIsLeaf = ((int) child->_segments.size() <= maxNbSegInLeaf() );
2712 //================================================================================
2714 * \brief Return elements which can include the point
2716 //================================================================================
2718 void _SegmentTree::GetSegmentsNear( const _Segment& seg,
2719 vector< const _Segment* >& found )
2721 if ( getBox()->IsOut( *seg._uv[0], *seg._uv[1] ))
2726 for ( size_t i = 0; i < _segments.size(); ++i )
2727 if ( !_segments[i].IsOut( seg ))
2728 found.push_back( _segments[i]._seg );
2732 for (int i = 0; i < nbChildren(); i++)
2733 ((_SegmentTree*) myChildren[i])->GetSegmentsNear( seg, found );
2738 //================================================================================
2740 * \brief Return segments intersecting a ray
2742 //================================================================================
2744 void _SegmentTree::GetSegmentsNear( const gp_Ax2d& ray,
2745 vector< const _Segment* >& found )
2747 if ( getBox()->IsOut( ray ))
2752 for ( size_t i = 0; i < _segments.size(); ++i )
2753 if ( !_segments[i].IsOut( ray ))
2754 found.push_back( _segments[i]._seg );
2758 for (int i = 0; i < nbChildren(); i++)
2759 ((_SegmentTree*) myChildren[i])->GetSegmentsNear( ray, found );
2763 //================================================================================
2765 * \brief Classify a _Segment
2767 //================================================================================
2769 bool _SegmentTree::_SegBox::IsOut( const _Segment& seg ) const
2771 const double eps = std::numeric_limits<double>::min();
2772 for ( int iC = 0; iC < 2; ++iC )
2774 if ( seg._uv[0]->Coord(iC+1) < _seg->_uv[ _iMin[iC]]->Coord(iC+1)+eps &&
2775 seg._uv[1]->Coord(iC+1) < _seg->_uv[ _iMin[iC]]->Coord(iC+1)+eps )
2777 if ( seg._uv[0]->Coord(iC+1) > _seg->_uv[ 1-_iMin[iC]]->Coord(iC+1)-eps &&
2778 seg._uv[1]->Coord(iC+1) > _seg->_uv[ 1-_iMin[iC]]->Coord(iC+1)-eps )
2784 //================================================================================
2786 * \brief Classify a ray
2788 //================================================================================
2790 bool _SegmentTree::_SegBox::IsOut( const gp_Ax2d& ray ) const
2792 double distBoxCenter2Ray =
2793 ray.Direction().XY() ^ ( ray.Location().XY() - 0.5 * (*_seg->_uv[0] + *_seg->_uv[1]));
2795 double boxSectionDiam =
2796 Abs( ray.Direction().X() ) * ( _seg->_uv[1-_iMin[1]]->Y() - _seg->_uv[_iMin[1]]->Y() ) +
2797 Abs( ray.Direction().Y() ) * ( _seg->_uv[1-_iMin[0]]->X() - _seg->_uv[_iMin[0]]->X() );
2799 return Abs( distBoxCenter2Ray ) > 0.5 * boxSectionDiam;