1 // Copyright (C) 2007-2014 CEA/DEN, EDF R&D, OPEN CASCADE
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 // Lesser General Public License for more details.
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
20 // File : StdMeshers_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 ); }
117 _ProxyMeshOfFace(const SMESH_Mesh& mesh): SMESH_ProxyMesh(mesh) {}
118 _EdgeSubMesh* GetEdgeSubMesh(int ID) { return (_EdgeSubMesh*) getProxySubMesh(ID); }
119 virtual SubMesh* newSubmesh(int index=0) const { return new _EdgeSubMesh(index); }
121 //--------------------------------------------------------------------------------
123 * \brief SMESH_subMeshEventListener used to store _ProxyMeshOfFace, computed
124 * by _ViscousBuilder2D, in a SMESH_subMesh of the FACE.
125 * This is to delete _ProxyMeshOfFace when StdMeshers_ViscousLayers2D
126 * hypothesis is modified
128 struct _ProxyMeshHolder : public SMESH_subMeshEventListener
130 _ProxyMeshHolder( const TopoDS_Face& face,
131 SMESH_ProxyMesh::Ptr& mesh)
132 : SMESH_subMeshEventListener( /*deletable=*/true, Name() )
134 SMESH_subMesh* faceSM = mesh->GetMesh()->GetSubMesh( face );
135 faceSM->SetEventListener( this, new _Data( mesh ), faceSM );
137 // Finds a proxy mesh of face
138 static SMESH_ProxyMesh::Ptr FindProxyMeshOfFace( const TopoDS_Shape& face,
141 SMESH_ProxyMesh::Ptr proxy;
142 SMESH_subMesh* faceSM = mesh.GetSubMesh( face );
143 if ( EventListenerData* ld = faceSM->GetEventListenerData( Name() ))
144 proxy = static_cast< _Data* >( ld )->_mesh;
148 void ProcessEvent(const int event,
150 SMESH_subMesh* subMesh,
151 EventListenerData* data,
152 const SMESH_Hypothesis* /*hyp*/)
154 if ( event == SMESH_subMesh::CLEAN && eventType == SMESH_subMesh::COMPUTE_EVENT)
155 ((_Data*) data)->_mesh.reset();
158 // holder of a proxy mesh
159 struct _Data : public SMESH_subMeshEventListenerData
161 SMESH_ProxyMesh::Ptr _mesh;
162 _Data( SMESH_ProxyMesh::Ptr& mesh )
163 :SMESH_subMeshEventListenerData( /*isDeletable=*/true), _mesh( mesh )
166 // Returns identifier string
167 static const char* Name() { return "VISCOUS_2D::_ProxyMeshHolder"; }
171 //--------------------------------------------------------------------------------
173 * \brief Segment connecting inner ends of two _LayerEdge's.
177 const gp_XY* _uv[2]; // poiter to _LayerEdge::_uvIn
178 int _indexInLine; // position in _PolyLine
181 _Segment(const gp_XY& p1, const gp_XY& p2):_indexInLine(-1) { _uv[0] = &p1; _uv[1] = &p2; }
182 const gp_XY& p1() const { return *_uv[0]; }
183 const gp_XY& p2() const { return *_uv[1]; }
185 //--------------------------------------------------------------------------------
187 * \brief Tree of _Segment's used for a faster search of _Segment's.
189 struct _SegmentTree : public SMESH_Quadtree
191 typedef boost::shared_ptr< _SegmentTree > Ptr;
193 _SegmentTree( const vector< _Segment >& segments );
194 void GetSegmentsNear( const _Segment& seg, vector< const _Segment* >& found );
195 void GetSegmentsNear( const gp_Ax2d& ray, vector< const _Segment* >& found );
198 _SegmentTree* newChild() const { return new _SegmentTree; }
199 void buildChildrenData();
200 Bnd_B2d* buildRootBox();
202 static int maxNbSegInLeaf() { return 5; }
205 const _Segment* _seg;
207 void Set( const _Segment& seg )
210 _iMin[0] = ( seg._uv[1]->X() < seg._uv[0]->X() );
211 _iMin[1] = ( seg._uv[1]->Y() < seg._uv[0]->Y() );
213 bool IsOut( const _Segment& seg ) const;
214 bool IsOut( const gp_Ax2d& ray ) const;
216 vector< _SegBox > _segments;
218 //--------------------------------------------------------------------------------
220 * \brief Edge normal to FACE boundary, connecting a point on EDGE (_uvOut)
221 * and a point of a layer internal boundary (_uvIn)
225 gp_XY _uvOut; // UV on the FACE boundary
226 gp_XY _uvIn; // UV inside the FACE
227 double _length2D; // distance between _uvOut and _uvIn
229 bool _isBlocked;// is more inflation possible or not
231 gp_XY _normal2D; // to curve
232 double _len2dTo3dRatio; // to pass 2D <--> 3D
233 gp_Ax2d _ray; // a ray starting at _uvOut
235 vector<gp_XY> _uvRefined; // divisions by layers
237 bool SetNewLength( const double length );
243 //--------------------------------------------------------------------------------
245 * \brief Poly line composed of _Segment's of one EDGE.
246 * It's used to detect intersection of inflated layers by intersecting
251 StdMeshers_FaceSide* _wire;
252 int _edgeInd; // index of my EDGE in _wire
253 bool _advancable; // true if there is a viscous layer on my EDGE
254 bool _isStraight2D;// pcurve type
255 _PolyLine* _leftLine; // lines of neighbour EDGE's
256 _PolyLine* _rightLine;
257 int _firstPntInd; // index in vector<UVPtStruct> of _wire
259 int _index; // index in _ViscousBuilder2D::_polyLineVec
261 vector< _LayerEdge > _lEdges; /* _lEdges[0] is usually is not treated
262 as it is equal to the last one of the _leftLine */
263 vector< _Segment > _segments; // segments connecting _uvIn's of _lEdges
264 _SegmentTree::Ptr _segTree;
266 vector< _PolyLine* > _reachableLines; // lines able to interfere with my layer
268 vector< const SMDS_MeshNode* > _leftNodes; // nodes built from a left VERTEX
269 vector< const SMDS_MeshNode* > _rightNodes; // nodes built from a right VERTEX
271 typedef vector< _Segment >::iterator TSegIterator;
272 typedef vector< _LayerEdge >::iterator TEdgeIterator;
274 TIDSortedElemSet _newFaces; // faces generated from this line
276 bool IsCommonEdgeShared( const _PolyLine& other );
277 size_t FirstLEdge() const
279 return ( _leftLine->_advancable && _lEdges.size() > 2 ) ? 1 : 0;
281 bool IsAdjacent( const _Segment& seg, const _LayerEdge* LE=0 ) const
283 if ( LE /*&& seg._indexInLine < _lEdges.size()*/ )
284 return ( seg._uv[0] == & LE->_uvIn ||
285 seg._uv[1] == & LE->_uvIn );
286 return ( & seg == &_leftLine->_segments.back() ||
287 & seg == &_rightLine->_segments[0] );
289 bool IsConcave() const;
291 //--------------------------------------------------------------------------------
293 * \brief Intersector of _Segment's
295 struct _SegmentIntersection
297 gp_XY _vec1, _vec2; // Vec( _seg.p1(), _seg.p2() )
298 gp_XY _vec21; // Vec( _seg2.p1(), _seg1.p1() )
299 double _D; // _vec1.Crossed( _vec2 )
300 double _param1, _param2; // intersection param on _seg1 and _seg2
302 bool Compute(const _Segment& seg1, const _Segment& seg2, bool seg2IsRay = false )
304 // !!! If seg2IsRay, returns true at any _param2 !!!
305 const double eps = 1e-10;
306 _vec1 = seg1.p2() - seg1.p1();
307 _vec2 = seg2.p2() - seg2.p1();
308 _vec21 = seg1.p1() - seg2.p1();
309 _D = _vec1.Crossed(_vec2);
310 if ( fabs(_D) < std::numeric_limits<double>::min())
312 _param1 = _vec2.Crossed(_vec21) / _D;
313 if (_param1 < -eps || _param1 > 1 + eps )
315 _param2 = _vec1.Crossed(_vec21) / _D;
316 return seg2IsRay || ( _param2 > -eps && _param2 < 1 + eps );
318 bool Compute( const _Segment& seg1, const gp_Ax2d& ray )
320 gp_XY segEnd = ray.Location().XY() + ray.Direction().XY();
321 _Segment seg2( ray.Location().XY(), segEnd );
322 return Compute( seg1, seg2, true );
324 //gp_XY GetPoint() { return _seg1.p1() + _param1 * _vec1; }
326 //--------------------------------------------------------------------------------
328 typedef map< const SMDS_MeshNode*, _LayerEdge*, TIDCompare > TNode2Edge;
329 typedef StdMeshers_ViscousLayers2D THypVL;
331 //--------------------------------------------------------------------------------
333 * \brief Builder of viscous layers
335 class _ViscousBuilder2D
338 _ViscousBuilder2D(SMESH_Mesh& theMesh,
339 const TopoDS_Face& theFace,
340 vector< const THypVL* > & theHyp,
341 vector< TopoDS_Shape > & theHypShapes);
342 SMESH_ComputeErrorPtr GetError() const { return _error; }
344 SMESH_ProxyMesh::Ptr Compute();
348 friend class ::StdMeshers_ViscousLayers2D;
350 bool findEdgesWithLayers();
351 bool makePolyLines();
353 bool fixCollisions();
357 bool toShrinkForAdjacent( const TopoDS_Face& adjFace,
358 const TopoDS_Edge& E,
359 const TopoDS_Vertex& V);
360 void setLenRatio( _LayerEdge& LE, const gp_Pnt& pOut );
361 void setLayerEdgeData( _LayerEdge& lEdge,
363 Handle(Geom2d_Curve)& pcurve,
364 Handle(Geom_Curve)& curve,
367 GeomAPI_ProjectPointOnSurf* faceProj);
368 void adjustCommonEdge( _PolyLine& LL, _PolyLine& LR );
369 void calcLayersHeight(const double totalThick,
370 vector<double>& heights,
372 bool removeMeshFaces(const TopoDS_Shape& face);
374 const THypVL* getLineHypothesis(int iPL);
375 double getLineThickness (int iPL);
377 bool error( const string& text );
378 SMESHDS_Mesh* getMeshDS() { return _mesh->GetMeshDS(); }
379 _ProxyMeshOfFace* getProxyMesh();
382 //void makeGroupOfLE();
389 vector< const THypVL* > _hyps;
390 vector< TopoDS_Shape > _hypShapes;
393 SMESH_ProxyMesh::Ptr _proxyMesh;
394 SMESH_ComputeErrorPtr _error;
397 Handle(Geom_Surface) _surface;
398 SMESH_MesherHelper _helper;
399 TSideVector _faceSideVec; // wires (StdMeshers_FaceSide) of _face
400 vector<_PolyLine> _polyLineVec; // fronts to advance
401 vector< const THypVL* > _hypOfEdge; // a hyp per an EDGE of _faceSideVec
402 bool _is2DIsotropic; // is same U and V resoulution of _face
403 vector<TopoDS_Face> _clearedFaces; // FACEs whose mesh was removed by shrink()
405 //double _fPowN; // to compute thickness of layers
406 double _maxThickness; // max possible layers thickness
408 // sub-shapes of _face
409 set<TGeomID> _ignoreShapeIds; // ids of EDGEs w/o layers
410 set<TGeomID> _noShrinkVert; // ids of VERTEXes that are extremities
411 // of EDGEs along which _LayerEdge can't be inflated because no viscous layers
412 // defined on neighbour FACEs sharing an EDGE. Nonetheless _LayerEdge's
413 // are inflated along such EDGEs but then such _LayerEdge's are turned into
414 // a node on VERTEX, i.e. all nodes on a _LayerEdge are melded into one node.
416 int _nbLE; // for DEBUG
419 //================================================================================
421 * \brief Returns StdMeshers_ViscousLayers2D for the FACE
423 bool findHyps(SMESH_Mesh& theMesh,
424 const TopoDS_Face& theFace,
425 vector< const StdMeshers_ViscousLayers2D* > & theHyps,
426 vector< TopoDS_Shape > & theAssignedTo)
429 theAssignedTo.clear();
430 SMESH_HypoFilter hypFilter
431 ( SMESH_HypoFilter::HasName( StdMeshers_ViscousLayers2D::GetHypType() ));
432 list< const SMESHDS_Hypothesis * > hypList;
433 list< TopoDS_Shape > hypShapes;
434 int nbHyps = theMesh.GetHypotheses
435 ( theFace, hypFilter, hypList, /*ancestors=*/true, &hypShapes );
438 theHyps.reserve( nbHyps );
439 theAssignedTo.reserve( nbHyps );
440 list< const SMESHDS_Hypothesis * >::iterator hyp = hypList.begin();
441 list< TopoDS_Shape >::iterator shape = hypShapes.begin();
442 for ( ; hyp != hypList.end(); ++hyp, ++shape )
444 theHyps.push_back( static_cast< const StdMeshers_ViscousLayers2D* > ( *hyp ));
445 theAssignedTo.push_back( *shape );
451 //================================================================================
453 * \brief Returns ids of EDGEs not to create Viscous Layers on
454 * \param [in] theHyp - the hypothesis, holding edges either to ignore or not to.
455 * \param [in] theFace - the FACE whose EDGEs are checked.
456 * \param [in] theMesh - the mesh.
457 * \param [in,out] theEdgeIds - container returning EDGEs to ignore.
458 * \return int - number of found EDGEs of the FACE.
460 //================================================================================
462 int getEdgesToIgnore( const StdMeshers_ViscousLayers2D* theHyp,
463 const TopoDS_Shape& theFace,
464 const SMESHDS_Mesh* theMesh,
465 set< int > & theEdgeIds)
467 int nbEdgesToIgnore = 0;
468 vector<TGeomID> ids = theHyp->GetBndShapes();
469 if ( theHyp->IsToIgnoreShapes() ) // EDGEs to ignore are given
471 for ( size_t i = 0; i < ids.size(); ++i )
473 const TopoDS_Shape& E = theMesh->IndexToShape( ids[i] );
475 E.ShapeType() == TopAbs_EDGE &&
476 SMESH_MesherHelper::IsSubShape( E, theFace ))
478 theEdgeIds.insert( ids[i] );
483 else // EDGEs to make the Viscous Layers on are given
485 TopExp_Explorer E( theFace, TopAbs_EDGE );
486 for ( ; E.More(); E.Next(), ++nbEdgesToIgnore )
487 theEdgeIds.insert( theMesh->ShapeToIndex( E.Current() ));
489 for ( size_t i = 0; i < ids.size(); ++i )
490 nbEdgesToIgnore -= theEdgeIds.erase( ids[i] );
492 return nbEdgesToIgnore;
495 } // namespace VISCOUS_2D
497 //================================================================================
498 // StdMeshers_ViscousLayers hypothesis
500 StdMeshers_ViscousLayers2D::StdMeshers_ViscousLayers2D(int hypId, int studyId, SMESH_Gen* gen)
501 :StdMeshers_ViscousLayers(hypId, studyId, gen)
503 _name = StdMeshers_ViscousLayers2D::GetHypType();
504 _param_algo_dim = -2; // auxiliary hyp used by 2D algos
506 // --------------------------------------------------------------------------------
507 bool StdMeshers_ViscousLayers2D::SetParametersByMesh(const SMESH_Mesh* theMesh,
508 const TopoDS_Shape& theShape)
513 // --------------------------------------------------------------------------------
515 StdMeshers_ViscousLayers2D::Compute(SMESH_Mesh& theMesh,
516 const TopoDS_Face& theFace)
518 SMESH_ProxyMesh::Ptr pm;
520 vector< const StdMeshers_ViscousLayers2D* > hyps;
521 vector< TopoDS_Shape > hypShapes;
522 if ( VISCOUS_2D::findHyps( theMesh, theFace, hyps, hypShapes ))
524 VISCOUS_2D::_ViscousBuilder2D builder( theMesh, theFace, hyps, hypShapes );
525 pm = builder.Compute();
526 SMESH_ComputeErrorPtr error = builder.GetError();
527 if ( error && !error->IsOK() )
528 theMesh.GetSubMesh( theFace )->GetComputeError() = error;
530 pm.reset( new SMESH_ProxyMesh( theMesh ));
531 if ( getenv("__ONLY__VL2D__"))
536 pm.reset( new SMESH_ProxyMesh( theMesh ));
540 // --------------------------------------------------------------------------------
541 SMESH_ComputeErrorPtr
542 StdMeshers_ViscousLayers2D::CheckHypothesis(SMESH_Mesh& theMesh,
543 const TopoDS_Shape& theShape,
544 SMESH_Hypothesis::Hypothesis_Status& theStatus)
546 SMESH_ComputeErrorPtr error = SMESH_ComputeError::New(COMPERR_OK);
547 theStatus = SMESH_Hypothesis::HYP_OK;
549 TopExp_Explorer exp( theShape, TopAbs_FACE );
550 for ( ; exp.More() && theStatus == SMESH_Hypothesis::HYP_OK; exp.Next() )
552 const TopoDS_Face& face = TopoDS::Face( exp.Current() );
553 vector< const StdMeshers_ViscousLayers2D* > hyps;
554 vector< TopoDS_Shape > hypShapes;
555 if ( VISCOUS_2D::findHyps( theMesh, face, hyps, hypShapes ))
557 VISCOUS_2D::_ViscousBuilder2D builder( theMesh, face, hyps, hypShapes );
558 builder._faceSideVec =
559 StdMeshers_FaceSide::GetFaceWires( face, theMesh, true, error,
560 SMESH_ProxyMesh::Ptr(),
561 /*theCheckVertexNodes=*/false);
562 if ( error->IsOK() && !builder.findEdgesWithLayers())
564 error = builder.GetError();
565 if ( error && !error->IsOK() )
566 theStatus = SMESH_Hypothesis::HYP_INCOMPAT_HYPS;
572 // --------------------------------------------------------------------------------
573 void StdMeshers_ViscousLayers2D::RestoreListeners() const
575 StudyContextStruct* sc = _gen->GetStudyContext( _studyId );
576 std::map < int, SMESH_Mesh * >::iterator i_smesh = sc->mapMesh.begin();
577 for ( ; i_smesh != sc->mapMesh.end(); ++i_smesh )
579 SMESH_Mesh* smesh = i_smesh->second;
581 !smesh->HasShapeToMesh() ||
582 !smesh->GetMeshDS() ||
583 !smesh->GetMeshDS()->IsUsedHypothesis( this ))
586 // set event listeners to EDGE's of FACE where this hyp is used
587 TopoDS_Shape shape = i_smesh->second->GetShapeToMesh();
588 for ( TopExp_Explorer face( shape, TopAbs_FACE); face.More(); face.Next() )
589 if ( SMESH_Algo* algo = _gen->GetAlgo( *smesh, face.Current() ))
591 const std::list <const SMESHDS_Hypothesis *> & usedHyps =
592 algo->GetUsedHypothesis( *smesh, face.Current(), /*ignoreAuxiliary=*/false );
593 if ( std::find( usedHyps.begin(), usedHyps.end(), this ) != usedHyps.end() )
594 for ( TopExp_Explorer edge( face.Current(), TopAbs_EDGE); edge.More(); edge.Next() )
595 VISCOUS_3D::ToClearSubWithMain( smesh->GetSubMesh( edge.Current() ), face.Current() );
599 // END StdMeshers_ViscousLayers2D hypothesis
600 //================================================================================
602 using namespace VISCOUS_2D;
604 //================================================================================
606 * \brief Constructor of _ViscousBuilder2D
608 //================================================================================
610 _ViscousBuilder2D::_ViscousBuilder2D(SMESH_Mesh& theMesh,
611 const TopoDS_Face& theFace,
612 vector< const THypVL* > & theHyps,
613 vector< TopoDS_Shape > & theAssignedTo):
614 _mesh( &theMesh ), _face( theFace ), _helper( theMesh )
616 _hyps.swap( theHyps );
617 _hypShapes.swap( theAssignedTo );
619 _helper.SetSubShape( _face );
620 _helper.SetElementsOnShape( true );
622 _face.Orientation( TopAbs_FORWARD ); // 2D logic works only in this case
623 _surface = BRep_Tool::Surface( _face );
625 _error = SMESH_ComputeError::New(COMPERR_OK);
630 //================================================================================
632 * \brief Stores error description and returns false
634 //================================================================================
636 bool _ViscousBuilder2D::error(const string& text )
638 _error->myName = COMPERR_ALGO_FAILED;
639 _error->myComment = string("Viscous layers builder 2D: ") + text;
640 if ( SMESH_subMesh* sm = _mesh->GetSubMesh( _face ) )
642 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
643 if ( smError && smError->myAlgo )
644 _error->myAlgo = smError->myAlgo;
648 cout << "_ViscousBuilder2D::error " << text << endl;
653 //================================================================================
655 * \brief Does its job
657 //================================================================================
659 SMESH_ProxyMesh::Ptr _ViscousBuilder2D::Compute()
661 _faceSideVec = StdMeshers_FaceSide::GetFaceWires( _face, *_mesh, true, _error);
663 if ( !_error->IsOK() )
666 if ( !findEdgesWithLayers() ) // analysis of a shape
669 if ( ! makePolyLines() ) // creation of fronts
672 if ( ! inflate() ) // advance fronts
675 // remove elements and nodes from _face
676 removeMeshFaces( _face );
678 if ( !shrink() ) // shrink segments on edges w/o layers
681 if ( ! refine() ) // make faces
689 //================================================================================
691 * \brief Finds EDGE's to make viscous layers on.
693 //================================================================================
695 bool _ViscousBuilder2D::findEdgesWithLayers()
697 // collect all EDGEs to ignore defined by _hyps
698 typedef std::pair< set<TGeomID>, const THypVL* > TEdgesOfHyp;
699 vector< TEdgesOfHyp > ignoreEdgesOfHyp( _hyps.size() );
700 for ( size_t i = 0; i < _hyps.size(); ++i )
702 ignoreEdgesOfHyp[i].second = _hyps[i];
703 getEdgesToIgnore( _hyps[i], _face, getMeshDS(), ignoreEdgesOfHyp[i].first );
706 // get all shared EDGEs
707 TopTools_MapOfShape sharedEdges;
708 TopTools_IndexedMapOfShape hypFaces; // faces with VL hyps
709 for ( size_t i = 0; i < _hypShapes.size(); ++i )
710 TopExp::MapShapes( _hypShapes[i], TopAbs_FACE, hypFaces );
711 TopTools_IndexedDataMapOfShapeListOfShape facesOfEdgeMap;
712 for ( int iF = 1; iF <= hypFaces.Extent(); ++iF )
713 TopExp::MapShapesAndAncestors( hypFaces(iF), TopAbs_EDGE, TopAbs_FACE, facesOfEdgeMap);
714 for ( int iE = 1; iE <= facesOfEdgeMap.Extent(); ++iE )
715 if ( facesOfEdgeMap( iE ).Extent() > 1 )
716 sharedEdges.Add( facesOfEdgeMap.FindKey( iE ));
719 if ( _hyps.size() > 1 )
721 // check if two hypotheses define different parameters for the same EDGE
722 for ( size_t iWire = 0; iWire < _faceSideVec.size(); ++iWire )
724 StdMeshers_FaceSidePtr wire = _faceSideVec[ iWire ];
725 for ( int iE = 0; iE < wire->NbEdges(); ++iE )
727 const THypVL* hyp = 0;
728 const TGeomID edgeID = wire->EdgeID( iE );
729 if ( !sharedEdges.Contains( wire->Edge( iE )))
731 for ( size_t i = 0; i < ignoreEdgesOfHyp.size(); ++i )
732 if ( ! ignoreEdgesOfHyp[i].first.count( edgeID ))
735 return error(SMESH_Comment("Several hypotheses define "
736 "Viscous Layers on the edge #") << edgeID );
737 hyp = ignoreEdgesOfHyp[i].second;
740 _hypOfEdge.push_back( hyp );
742 _ignoreShapeIds.insert( edgeID );
744 // check if two hypotheses define different number of viscous layers for
746 const THypVL *hyp, *prevHyp = _hypOfEdge.back();
747 size_t iH = _hypOfEdge.size() - wire->NbEdges();
748 for ( ; iH < _hypOfEdge.size(); ++iH )
750 hyp = _hypOfEdge[ iH ];
751 if ( hyp && prevHyp &&
752 hyp->GetNumberLayers() != prevHyp->GetNumberLayers() )
754 return error("Two hypotheses define different number of "
755 "viscous layers on adjacent edges");
761 else if ( _hyps.size() == 1 )
763 _ignoreShapeIds.swap( ignoreEdgesOfHyp[0].first );
766 // check all EDGEs of the _face to fill _ignoreShapeIds and _noShrinkVert
768 int totalNbEdges = 0;
769 for ( size_t iWire = 0; iWire < _faceSideVec.size(); ++iWire )
771 StdMeshers_FaceSidePtr wire = _faceSideVec[ iWire ];
772 totalNbEdges += wire->NbEdges();
773 for ( int iE = 0; iE < wire->NbEdges(); ++iE )
775 if ( sharedEdges.Contains( wire->Edge( iE )))
777 // ignore internal EDGEs (shared by several FACEs)
778 const TGeomID edgeID = wire->EdgeID( iE );
779 _ignoreShapeIds.insert( edgeID );
781 // check if ends of an EDGE are to be added to _noShrinkVert
782 const TopTools_ListOfShape& faceList = facesOfEdgeMap.FindFromKey( wire->Edge( iE ));
783 TopTools_ListIteratorOfListOfShape faceIt( faceList );
784 for ( ; faceIt.More(); faceIt.Next() )
786 const TopoDS_Shape& neighbourFace = faceIt.Value();
787 if ( neighbourFace.IsSame( _face )) continue;
788 SMESH_Algo* algo = _mesh->GetGen()->GetAlgo( *_mesh, neighbourFace );
789 if ( !algo ) continue;
791 const StdMeshers_ViscousLayers2D* viscHyp = 0;
792 const list <const SMESHDS_Hypothesis *> & allHyps =
793 algo->GetUsedHypothesis(*_mesh, neighbourFace, /*noAuxiliary=*/false);
794 list< const SMESHDS_Hypothesis *>::const_iterator hyp = allHyps.begin();
795 for ( ; hyp != allHyps.end() && !viscHyp; ++hyp )
796 viscHyp = dynamic_cast<const StdMeshers_ViscousLayers2D*>( *hyp );
798 // set<TGeomID> neighbourIgnoreEdges;
800 // getEdgesToIgnore( viscHyp, neighbourFace, getMeshDS(), neighbourIgnoreEdges );
802 for ( int iV = 0; iV < 2; ++iV )
804 TopoDS_Vertex vertex = iV ? wire->LastVertex(iE) : wire->FirstVertex(iE);
806 _noShrinkVert.insert( getMeshDS()->ShapeToIndex( vertex ));
809 PShapeIteratorPtr edgeIt = _helper.GetAncestors( vertex, *_mesh, TopAbs_EDGE );
810 while ( const TopoDS_Shape* edge = edgeIt->next() )
811 if ( !edge->IsSame( wire->Edge( iE )) &&
812 _helper.IsSubShape( *edge, neighbourFace ))
814 const TGeomID neighbourID = getMeshDS()->ShapeToIndex( *edge );
815 bool hasVL = !sharedEdges.Contains( *edge );
819 for ( hyp = allHyps.begin(); hyp != allHyps.end() && !hasVL; ++hyp )
820 if ( viscHyp = dynamic_cast<const THypVL*>( *hyp ))
821 hasVL = viscHyp->IsShapeWithLayers( neighbourID );
825 _noShrinkVert.insert( getMeshDS()->ShapeToIndex( vertex ));
836 int nbMyEdgesIgnored = _ignoreShapeIds.size();
838 // add VERTEXes w/o layers to _ignoreShapeIds (this is used by toShrinkForAdjacent())
839 // for ( size_t iWire = 0; iWire < _faceSideVec.size(); ++iWire )
841 // StdMeshers_FaceSidePtr wire = _faceSideVec[ iWire ];
842 // for ( int iE = 0; iE < wire->NbEdges(); ++iE )
844 // TGeomID edge1 = wire->EdgeID( iE );
845 // TGeomID edge2 = wire->EdgeID( iE+1 );
846 // if ( _ignoreShapeIds.count( edge1 ) && _ignoreShapeIds.count( edge2 ))
847 // _ignoreShapeIds.insert( getMeshDS()->ShapeToIndex( wire->LastVertex( iE )));
851 return ( nbMyEdgesIgnored < totalNbEdges );
854 //================================================================================
856 * \brief Create the inner front of the viscous layers and prepare data for inflation
858 //================================================================================
860 bool _ViscousBuilder2D::makePolyLines()
862 // Create _PolyLines and _LayerEdge's
864 // count total nb of EDGEs to allocate _polyLineVec
866 for ( size_t iWire = 0; iWire < _faceSideVec.size(); ++iWire )
868 StdMeshers_FaceSidePtr wire = _faceSideVec[ iWire ];
869 nbEdges += wire->NbEdges();
870 if ( wire->GetUVPtStruct().empty() && wire->NbPoints() > 0 )
871 return error("Invalid node parameters on some EDGE");
873 _polyLineVec.resize( nbEdges );
875 // check if 2D normal should be computed by 3D one by means of projection
876 GeomAPI_ProjectPointOnSurf* faceProj = 0;
880 const UVPtStruct& uv = _faceSideVec[0]->GetUVPtStruct()[0];
881 gp_Pnt p = SMESH_TNodeXYZ( uv.node );
882 tmpLE._uvOut.SetCoord( uv.u, uv.v );
883 tmpLE._normal2D.SetCoord( 1., 0. );
884 setLenRatio( tmpLE, p );
885 const double r1 = tmpLE._len2dTo3dRatio;
886 tmpLE._normal2D.SetCoord( 0., 1. );
887 setLenRatio( tmpLE, p );
888 const double r2 = tmpLE._len2dTo3dRatio;
889 // projection is needed if two _len2dTo3dRatio's differ too much
890 const double maxR = Max( r2, r1 );
891 if ( Abs( r2-r1 )/maxR > 0.2*maxR )
892 faceProj = & _helper.GetProjector( _face, loc );
894 _is2DIsotropic = !faceProj;
896 // Assign data to _PolyLine's
897 // ---------------------------
900 for ( size_t iWire = 0; iWire < _faceSideVec.size(); ++iWire )
902 StdMeshers_FaceSidePtr wire = _faceSideVec[ iWire ];
903 const vector<UVPtStruct>& points = wire->GetUVPtStruct();
905 for ( int iE = 0; iE < wire->NbEdges(); ++iE )
907 _PolyLine& L = _polyLineVec[ iPoLine++ ];
908 L._index = iPoLine-1;
909 L._wire = wire.get();
911 L._advancable = !_ignoreShapeIds.count( wire->EdgeID( iE ));
913 int iRight = iPoLine - (( iE+1 < wire->NbEdges() ) ? 0 : wire->NbEdges() );
914 L._rightLine = &_polyLineVec[ iRight ];
915 _polyLineVec[ iRight ]._leftLine = &L;
917 L._firstPntInd = iPnt;
918 double lastNormPar = wire->LastParameter( iE ) - 1e-10;
919 while ( points[ iPnt ].normParam < lastNormPar )
921 L._lastPntInd = iPnt;
922 L._lEdges.resize( Max( 3, L._lastPntInd - L._firstPntInd + 1 )); // 3 edges minimum
924 // TODO: add more _LayerEdge's to strongly curved EDGEs
925 // in order not to miss collisions
928 Handle(Geom_Curve) curve = BRep_Tool::Curve( L._wire->Edge( iE ), loc, u, u );
929 Handle(Geom2d_Curve) pcurve = L._wire->Curve2d( L._edgeInd );
930 const bool reverse = (( L._wire->Edge( iE ).Orientation() == TopAbs_REVERSED ) ^
931 (_face.Orientation() == TopAbs_REVERSED ));
932 for ( int i = L._firstPntInd; i <= L._lastPntInd; ++i )
934 _LayerEdge& lEdge = L._lEdges[ i - L._firstPntInd ];
935 u = ( i == L._firstPntInd ? wire->FirstU(iE) : points[ i ].param );
936 p = SMESH_TNodeXYZ( points[ i ].node );
937 setLayerEdgeData( lEdge, u, pcurve, curve, p, reverse, faceProj );
938 setLenRatio( lEdge, p );
940 if ( L._lastPntInd - L._firstPntInd + 1 < 3 ) // add 3-d _LayerEdge in the middle
942 L._lEdges[2] = L._lEdges[1];
943 u = 0.5 * ( wire->FirstU(iE) + wire->LastU(iE) );
944 if ( !curve.IsNull() )
945 p = curve->Value( u );
947 p = 0.5 * ( SMESH_TNodeXYZ( points[ L._firstPntInd ].node ) +
948 SMESH_TNodeXYZ( points[ L._lastPntInd ].node ));
949 setLayerEdgeData( L._lEdges[1], u, pcurve, curve, p, reverse, faceProj );
950 setLenRatio( L._lEdges[1], p );
955 // Fill _PolyLine's with _segments
956 // --------------------------------
958 double maxLen2dTo3dRatio = 0;
959 for ( iPoLine = 0; iPoLine < _polyLineVec.size(); ++iPoLine )
961 _PolyLine& L = _polyLineVec[ iPoLine ];
962 L._segments.resize( L._lEdges.size() - 1 );
963 for ( size_t i = 1; i < L._lEdges.size(); ++i )
965 _Segment & S = L._segments[i-1];
966 S._uv[0] = & L._lEdges[i-1]._uvIn;
967 S._uv[1] = & L._lEdges[i ]._uvIn;
968 S._indexInLine = i-1;
969 if ( maxLen2dTo3dRatio < L._lEdges[i]._len2dTo3dRatio )
970 maxLen2dTo3dRatio = L._lEdges[i]._len2dTo3dRatio;
972 // // connect _PolyLine's with segments, the 1st _LayerEdge of every _PolyLine
973 // // becomes not connected to any segment
974 // if ( L._leftLine->_advancable )
975 // L._segments[0]._uv[0] = & L._leftLine->_lEdges.back()._uvIn;
977 L._segTree.reset( new _SegmentTree( L._segments ));
980 // Evaluate max possible _thickness if required layers thickness seems too high
981 // ----------------------------------------------------------------------------
983 _maxThickness = _hyps[0]->GetTotalThickness();
984 for ( size_t iH = 1; iH < _hyps.size(); ++iH )
985 _maxThickness = Max( _maxThickness, _hyps[iH]->GetTotalThickness() );
987 _SegmentTree::box_type faceBndBox2D;
988 for ( iPoLine = 0; iPoLine < _polyLineVec.size(); ++iPoLine )
989 faceBndBox2D.Add( *_polyLineVec[ iPoLine]._segTree->getBox() );
990 const double boxTol = 1e-3 * sqrt( faceBndBox2D.SquareExtent() );
992 if ( _maxThickness * maxLen2dTo3dRatio > sqrt( faceBndBox2D.SquareExtent() ) / 10 )
994 vector< const _Segment* > foundSegs;
995 double maxPossibleThick = 0;
996 _SegmentIntersection intersection;
997 for ( size_t iL1 = 0; iL1 < _polyLineVec.size(); ++iL1 )
999 _PolyLine& L1 = _polyLineVec[ iL1 ];
1000 _SegmentTree::box_type boxL1 = * L1._segTree->getBox();
1001 boxL1.Enlarge( boxTol );
1002 // consider case of a circle as well!
1003 for ( size_t iL2 = iL1; iL2 < _polyLineVec.size(); ++iL2 )
1005 _PolyLine& L2 = _polyLineVec[ iL2 ];
1006 _SegmentTree::box_type boxL2 = * L2._segTree->getBox();
1007 boxL2.Enlarge( boxTol );
1008 if ( boxL1.IsOut( boxL2 ))
1010 for ( size_t iLE = 1; iLE < L1._lEdges.size(); ++iLE )
1013 L2._segTree->GetSegmentsNear( L1._lEdges[iLE]._ray, foundSegs );
1014 for ( size_t i = 0; i < foundSegs.size(); ++i )
1015 if ( intersection.Compute( *foundSegs[i], L1._lEdges[iLE]._ray ))
1017 double distToL2 = intersection._param2 / L1._lEdges[iLE]._len2dTo3dRatio;
1018 double psblThick = distToL2 / ( 1 + L1._advancable + L2._advancable );
1019 maxPossibleThick = Max( psblThick, maxPossibleThick );
1024 if ( maxPossibleThick > 0. )
1025 _maxThickness = Min( _maxThickness, maxPossibleThick );
1028 // Adjust _LayerEdge's at _PolyLine's extremities
1029 // -----------------------------------------------
1031 for ( iPoLine = 0; iPoLine < _polyLineVec.size(); ++iPoLine )
1033 _PolyLine& LL = _polyLineVec[ iPoLine ];
1034 _PolyLine& LR = *LL._rightLine;
1035 adjustCommonEdge( LL, LR );
1037 // recreate _segments if some _LayerEdge's have been removed by adjustCommonEdge()
1038 for ( iPoLine = 0; iPoLine < _polyLineVec.size(); ++iPoLine )
1040 _PolyLine& L = _polyLineVec[ iPoLine ];
1041 // if ( L._segments.size() == L._lEdges.size() - 1 )
1043 L._segments.resize( L._lEdges.size() - 1 );
1044 for ( size_t i = 1; i < L._lEdges.size(); ++i )
1046 _Segment & S = L._segments[i-1];
1047 S._uv[0] = & L._lEdges[i-1]._uvIn;
1048 S._uv[1] = & L._lEdges[i ]._uvIn;
1049 S._indexInLine = i-1;
1051 L._segTree.reset( new _SegmentTree( L._segments ));
1053 // connect _PolyLine's with segments, the 1st _LayerEdge of every _PolyLine
1054 // becomes not connected to any segment
1055 for ( iPoLine = 0; iPoLine < _polyLineVec.size(); ++iPoLine )
1057 _PolyLine& L = _polyLineVec[ iPoLine ];
1058 if ( L._leftLine->_advancable )
1059 L._segments[0]._uv[0] = & L._leftLine->_lEdges.back()._uvIn;
1062 // Fill _reachableLines.
1063 // ----------------------
1065 // compute bnd boxes taking into account the layers total thickness
1066 vector< _SegmentTree::box_type > lineBoxes( _polyLineVec.size() );
1067 for ( iPoLine = 0; iPoLine < _polyLineVec.size(); ++iPoLine )
1069 lineBoxes[ iPoLine ] = *_polyLineVec[ iPoLine ]._segTree->getBox();
1070 lineBoxes[ iPoLine ].Enlarge( maxLen2dTo3dRatio * getLineThickness( iPoLine ) *
1071 ( _polyLineVec[ iPoLine ]._advancable ? 2. : 1.2 ));
1074 for ( iPoLine = 0; iPoLine < _polyLineVec.size(); ++iPoLine )
1076 _PolyLine& L1 = _polyLineVec[ iPoLine ];
1077 const double thick1 = getLineThickness( iPoLine );
1078 for ( size_t iL2 = 0; iL2 < _polyLineVec.size(); ++iL2 )
1080 _PolyLine& L2 = _polyLineVec[ iL2 ];
1081 if ( iPoLine == iL2 || lineBoxes[ iPoLine ].IsOut( lineBoxes[ iL2 ]))
1083 if ( !L1._advancable && ( L1._leftLine == &L2 || L1._rightLine == &L2 ))
1085 // check reachability by _LayerEdge's
1086 int iDelta = 1; //Max( 1, L1._lEdges.size() / 100 );
1087 for ( size_t iLE = 1; iLE < L1._lEdges.size(); iLE += iDelta )
1089 _LayerEdge& LE = L1._lEdges[iLE];
1090 if ( !lineBoxes[ iL2 ].IsOut ( LE._uvOut,
1091 LE._uvOut + LE._normal2D * thick1 * LE._len2dTo3dRatio ))
1093 L1._reachableLines.push_back( & L2 );
1098 // add self to _reachableLines
1099 Geom2dAdaptor_Curve pcurve( L1._wire->Curve2d( L1._edgeInd ));
1100 L1._isStraight2D = ( pcurve.GetType() == GeomAbs_Line );
1101 if ( !L1._isStraight2D )
1103 // TODO: check carefully
1104 L1._reachableLines.push_back( & L1 );
1111 //================================================================================
1113 * \brief adjust common _LayerEdge of two adjacent _PolyLine's
1114 * \param LL - left _PolyLine
1115 * \param LR - right _PolyLine
1117 //================================================================================
1119 void _ViscousBuilder2D::adjustCommonEdge( _PolyLine& LL, _PolyLine& LR )
1121 int nbAdvancableL = LL._advancable + LR._advancable;
1122 if ( nbAdvancableL == 0 )
1125 _LayerEdge& EL = LL._lEdges.back();
1126 _LayerEdge& ER = LR._lEdges.front();
1127 gp_XY normL = EL._normal2D;
1128 gp_XY normR = ER._normal2D;
1129 gp_XY tangL ( normL.Y(), -normL.X() );
1131 // set common direction to a VERTEX _LayerEdge shared by two _PolyLine's
1132 gp_XY normCommon = ( normL * int( LL._advancable ) +
1133 normR * int( LR._advancable )).Normalized();
1134 EL._normal2D = normCommon;
1135 EL._ray.SetLocation ( EL._uvOut );
1136 EL._ray.SetDirection( EL._normal2D );
1137 if ( nbAdvancableL == 1 ) { // _normal2D is true normal (not average)
1138 EL._isBlocked = true; // prevent intersecting with _Segments of _advancable line
1141 // update _LayerEdge::_len2dTo3dRatio according to a new direction
1142 const vector<UVPtStruct>& points = LL._wire->GetUVPtStruct();
1143 setLenRatio( EL, SMESH_TNodeXYZ( points[ LL._lastPntInd ].node ));
1147 const double dotNormTang = normR * tangL;
1148 const bool largeAngle = Abs( dotNormTang ) > 0.2;
1149 if ( largeAngle ) // not 180 degrees
1151 // recompute _len2dTo3dRatio to take into account angle between EDGEs
1152 gp_Vec2d oldNorm( LL._advancable ? normL : normR );
1153 double angleFactor = 1. / Max( 0.3, Cos( oldNorm.Angle( normCommon )));
1154 EL._len2dTo3dRatio *= angleFactor;
1155 ER._len2dTo3dRatio = EL._len2dTo3dRatio;
1157 gp_XY normAvg = ( normL + normR ).Normalized(); // average normal at VERTEX
1159 if ( dotNormTang < 0. ) // ---------------------------- CONVEX ANGLE
1161 // Remove _LayerEdge's intersecting the normAvg to avoid collisions
1162 // during inflate().
1164 // find max length of the VERTEX-based _LayerEdge whose direction is normAvg
1165 double maxLen2D = _maxThickness * EL._len2dTo3dRatio;
1166 const gp_XY& pCommOut = ER._uvOut;
1167 gp_XY pCommIn = pCommOut + normAvg * maxLen2D;
1168 _Segment segCommon( pCommOut, pCommIn );
1169 _SegmentIntersection intersection;
1170 vector< const _Segment* > foundSegs;
1171 for ( size_t iL1 = 0; iL1 < _polyLineVec.size(); ++iL1 )
1173 _PolyLine& L1 = _polyLineVec[ iL1 ];
1174 const _SegmentTree::box_type* boxL1 = L1._segTree->getBox();
1175 if ( boxL1->IsOut ( pCommOut, pCommIn ))
1177 for ( size_t iLE = 1; iLE < L1._lEdges.size(); ++iLE )
1180 L1._segTree->GetSegmentsNear( segCommon, foundSegs );
1181 for ( size_t i = 0; i < foundSegs.size(); ++i )
1182 if ( intersection.Compute( *foundSegs[i], segCommon ) &&
1183 intersection._param2 > 1e-10 )
1185 double len2D = intersection._param2 * maxLen2D / ( 2 + L1._advancable );
1186 if ( len2D < maxLen2D ) {
1188 pCommIn = pCommOut + normAvg * maxLen2D; // here length of segCommon changes
1194 // remove _LayerEdge's intersecting segCommon
1195 for ( int isR = 0; isR < 2; ++isR ) // loop on [ LL, LR ]
1197 _PolyLine& L = isR ? LR : LL;
1198 _PolyLine::TEdgeIterator eIt = isR ? L._lEdges.begin()+1 : L._lEdges.end()-2;
1199 int dIt = isR ? +1 : -1;
1200 if ( nbAdvancableL == 1 && L._advancable && normL * normR > -0.01 )
1201 continue; // obtuse internal angle
1202 // at least 3 _LayerEdge's should remain in a _PolyLine
1203 if ( L._lEdges.size() < 4 ) continue;
1205 _SegmentIntersection lastIntersection;
1206 for ( ; iLE < L._lEdges.size(); ++iLE, eIt += dIt )
1208 gp_XY uvIn = eIt->_uvOut + eIt->_normal2D * _maxThickness * eIt->_len2dTo3dRatio;
1209 _Segment segOfEdge( eIt->_uvOut, uvIn );
1210 if ( !intersection.Compute( segCommon, segOfEdge ))
1212 lastIntersection._param1 = intersection._param1;
1213 lastIntersection._param2 = intersection._param2;
1215 if ( iLE >= L._lEdges.size() - 1 )
1217 // all _LayerEdge's intersect the segCommon, limit inflation
1218 // of remaining 3 _LayerEdge's
1219 vector< _LayerEdge > newEdgeVec( Min( 3, L._lEdges.size() ));
1220 newEdgeVec.front() = L._lEdges.front();
1221 newEdgeVec.back() = L._lEdges.back();
1222 if ( newEdgeVec.size() == 3 )
1224 newEdgeVec[1] = L._lEdges[ isR ? (L._lEdges.size() - 2) : 1 ];
1225 newEdgeVec[1]._len2dTo3dRatio *= lastIntersection._param2;
1227 L._lEdges.swap( newEdgeVec );
1228 if ( !isR ) std::swap( lastIntersection._param1 , lastIntersection._param2 );
1229 L._lEdges.front()._len2dTo3dRatio *= lastIntersection._param1; // ??
1230 L._lEdges.back ()._len2dTo3dRatio *= lastIntersection._param2;
1232 else if ( iLE != 1 )
1234 // eIt points to the _LayerEdge not intersecting with segCommon
1236 LR._lEdges.erase( LR._lEdges.begin()+1, eIt );
1238 LL._lEdges.erase( eIt, --LL._lEdges.end() );
1239 // eIt = isR ? L._lEdges.begin()+1 : L._lEdges.end()-2;
1240 // for ( size_t i = 1; i < iLE; ++i, eIt += dIt )
1241 // eIt->_isBlocked = true;
1245 else // ------------------------------------------ CONCAVE ANGLE
1247 if ( nbAdvancableL == 1 )
1249 // make that the _LayerEdge at VERTEX is not shared by LL and LR:
1250 // different normals is a sign that they are not shared
1251 _LayerEdge& notSharedEdge = LL._advancable ? LR._lEdges[0] : LL._lEdges.back();
1252 _LayerEdge& sharedEdge = LR._advancable ? LR._lEdges[0] : LL._lEdges.back();
1254 notSharedEdge._normal2D.SetCoord( 0.,0. );
1255 sharedEdge._normal2D = normAvg;
1256 sharedEdge._isBlocked = false;
1257 notSharedEdge._isBlocked = true;
1263 //================================================================================
1265 * \brief initialize data of a _LayerEdge
1267 //================================================================================
1269 void _ViscousBuilder2D::setLayerEdgeData( _LayerEdge& lEdge,
1271 Handle(Geom2d_Curve)& pcurve,
1272 Handle(Geom_Curve)& curve,
1275 GeomAPI_ProjectPointOnSurf* faceProj)
1278 if ( faceProj && !curve.IsNull() )
1280 uv = pcurve->Value( u );
1281 gp_Vec tangent; gp_Pnt p; gp_Vec du, dv;
1282 curve->D1( u, p, tangent );
1285 _surface->D1( uv.X(), uv.Y(), p, du, dv );
1286 gp_Vec faceNorm = du ^ dv;
1287 gp_Vec normal = faceNorm ^ tangent;
1289 p = pOut.XYZ() + normal.XYZ() * /*1e-2 * */_hyps[0]->GetTotalThickness() / _hyps[0]->GetNumberLayers();
1290 faceProj->Perform( p );
1291 if ( !faceProj->IsDone() || faceProj->NbPoints() < 1 )
1292 return setLayerEdgeData( lEdge, u, pcurve, curve, p, reverse, NULL );
1293 Quantity_Parameter U,V;
1294 faceProj->LowerDistanceParameters(U,V);
1295 lEdge._normal2D.SetCoord( U - uv.X(), V - uv.Y() );
1296 lEdge._normal2D.Normalize();
1301 pcurve->D1( u, uv, tangent );
1302 tangent.Normalize();
1305 lEdge._normal2D.SetCoord( -tangent.Y(), tangent.X() );
1307 lEdge._uvOut = lEdge._uvIn = uv.XY();
1308 lEdge._ray.SetLocation ( lEdge._uvOut );
1309 lEdge._ray.SetDirection( lEdge._normal2D );
1310 lEdge._isBlocked = false;
1311 lEdge._length2D = 0;
1313 lEdge._ID = _nbLE++;
1317 //================================================================================
1319 * \brief Compute and set _LayerEdge::_len2dTo3dRatio
1321 //================================================================================
1323 void _ViscousBuilder2D::setLenRatio( _LayerEdge& LE, const gp_Pnt& pOut )
1325 const double probeLen2d = 1e-3;
1327 gp_Pnt2d p2d = LE._uvOut + LE._normal2D * probeLen2d;
1328 gp_Pnt p3d = _surface->Value( p2d.X(), p2d.Y() );
1329 double len3d = p3d.Distance( pOut );
1330 if ( len3d < std::numeric_limits<double>::min() )
1331 LE._len2dTo3dRatio = std::numeric_limits<double>::min();
1333 LE._len2dTo3dRatio = probeLen2d / len3d;
1336 //================================================================================
1338 * \brief Increase length of _LayerEdge's to reach the required thickness of layers
1340 //================================================================================
1342 bool _ViscousBuilder2D::inflate()
1344 // Limit size of inflation step by geometry size found by
1345 // itersecting _LayerEdge's with _Segment's
1346 double minSize = _maxThickness, maxSize = 0;
1347 vector< const _Segment* > foundSegs;
1348 _SegmentIntersection intersection;
1349 for ( size_t iL1 = 0; iL1 < _polyLineVec.size(); ++iL1 )
1351 _PolyLine& L1 = _polyLineVec[ iL1 ];
1352 for ( size_t iL2 = 0; iL2 < L1._reachableLines.size(); ++iL2 )
1354 _PolyLine& L2 = * L1._reachableLines[ iL2 ];
1355 for ( size_t iLE = 1; iLE < L1._lEdges.size(); ++iLE )
1358 L2._segTree->GetSegmentsNear( L1._lEdges[iLE]._ray, foundSegs );
1359 for ( size_t i = 0; i < foundSegs.size(); ++i )
1360 if ( ! L1.IsAdjacent( *foundSegs[i], & L1._lEdges[iLE] ) &&
1361 intersection.Compute( *foundSegs[i], L1._lEdges[iLE]._ray ))
1363 double distToL2 = intersection._param2 / L1._lEdges[iLE]._len2dTo3dRatio;
1364 double size = distToL2 / ( 1 + L1._advancable + L2._advancable );
1365 if ( 1e-10 < size && size < minSize )
1367 if ( size > maxSize )
1373 if ( minSize > maxSize ) // no collisions possible
1374 maxSize = _maxThickness;
1376 cout << "-- minSize = " << minSize << ", maxSize = " << maxSize << endl;
1379 double curThick = 0, stepSize = minSize;
1381 if ( maxSize > _maxThickness )
1382 maxSize = _maxThickness;
1383 while ( curThick < maxSize )
1385 curThick += stepSize * 1.25;
1386 if ( curThick > _maxThickness )
1387 curThick = _maxThickness;
1389 // Elongate _LayerEdge's
1390 for ( size_t iL = 0; iL < _polyLineVec.size(); ++iL )
1392 _PolyLine& L = _polyLineVec[ iL ];
1393 if ( !L._advancable ) continue;
1394 const double lineThick = Min( curThick, getLineThickness( iL ));
1395 bool lenChange = false;
1396 for ( size_t iLE = L.FirstLEdge(); iLE < L._lEdges.size(); ++iLE )
1397 lenChange |= L._lEdges[iLE].SetNewLength( lineThick );
1398 // for ( int k=0; k<L._segments.size(); ++k)
1399 // cout << "( " << L._segments[k].p1().X() << ", " <<L._segments[k].p1().Y() << " ) "
1400 // << "( " << L._segments[k].p2().X() << ", " <<L._segments[k].p2().Y() << " ) "
1403 L._segTree.reset( new _SegmentTree( L._segments ));
1406 // Avoid intersection of _Segment's
1407 bool allBlocked = fixCollisions();
1410 break; // no more inflating possible
1412 stepSize = Max( stepSize , _maxThickness / 10. );
1416 // if (nbSteps == 0 )
1417 // return error("failed at the very first inflation step");
1420 // remove _LayerEdge's of one line intersecting with each other
1421 for ( size_t iL = 0; iL < _polyLineVec.size(); ++iL )
1423 _PolyLine& L = _polyLineVec[ iL ];
1424 if ( !L._advancable ) continue;
1426 // replace an inactive (1st) _LayerEdge with an active one of a neighbour _PolyLine
1427 if ( /*!L._leftLine->_advancable &&*/ L.IsCommonEdgeShared( *L._leftLine ) ) {
1428 L._lEdges[0] = L._leftLine->_lEdges.back();
1430 if ( !L._rightLine->_advancable && L.IsCommonEdgeShared( *L._rightLine ) ) {
1431 L._lEdges.back() = L._rightLine->_lEdges[0];
1434 _SegmentIntersection intersection;
1435 for ( int isR = 0; ( isR < 2 && L._lEdges.size() > 2 ); ++isR )
1437 int nbRemove = 0, deltaIt = isR ? -1 : +1;
1438 _PolyLine::TEdgeIterator eIt = isR ? L._lEdges.end()-1 : L._lEdges.begin();
1439 if ( eIt->_length2D == 0 ) continue;
1440 _Segment seg1( eIt->_uvOut, eIt->_uvIn );
1441 for ( eIt += deltaIt; nbRemove < L._lEdges.size()-1; eIt += deltaIt )
1443 _Segment seg2( eIt->_uvOut, eIt->_uvIn );
1444 if ( !intersection.Compute( seg1, seg2 ))
1448 if ( nbRemove > 0 ) {
1449 if ( nbRemove == L._lEdges.size()-1 ) // 1st and last _LayerEdge's intersect
1452 _LayerEdge& L0 = L._lEdges.front();
1453 _LayerEdge& L1 = L._lEdges.back();
1454 L0._length2D *= intersection._param1 * 0.5;
1455 L1._length2D *= intersection._param2 * 0.5;
1456 L0._uvIn = L0._uvOut + L0._normal2D * L0._length2D;
1457 L1._uvIn = L1._uvOut + L1._normal2D * L1._length2D;
1458 if ( L.IsCommonEdgeShared( *L._leftLine ))
1459 L._leftLine->_lEdges.back() = L0;
1462 L._lEdges.erase( L._lEdges.end()-nbRemove-1,
1463 L._lEdges.end()-nbRemove );
1465 L._lEdges.erase( L._lEdges.begin()+1,
1466 L._lEdges.begin()+1+nbRemove );
1473 //================================================================================
1475 * \brief Remove intersection of _PolyLine's
1477 //================================================================================
1479 bool _ViscousBuilder2D::fixCollisions()
1481 // look for intersections of _Segment's by intersecting _LayerEdge's with
1483 vector< const _Segment* > foundSegs;
1484 _SegmentIntersection intersection;
1486 list< pair< _LayerEdge*, double > > edgeLenLimitList;
1487 list< _LayerEdge* > blockedEdgesList;
1489 for ( size_t iL1 = 0; iL1 < _polyLineVec.size(); ++iL1 )
1491 _PolyLine& L1 = _polyLineVec[ iL1 ];
1492 //if ( !L1._advancable ) continue;
1493 for ( size_t iL2 = 0; iL2 < L1._reachableLines.size(); ++iL2 )
1495 _PolyLine& L2 = * L1._reachableLines[ iL2 ];
1496 for ( size_t iLE = L1.FirstLEdge(); iLE < L1._lEdges.size(); ++iLE )
1498 _LayerEdge& LE1 = L1._lEdges[iLE];
1499 if ( LE1._isBlocked ) continue;
1501 L2._segTree->GetSegmentsNear( LE1._ray, foundSegs );
1502 for ( size_t i = 0; i < foundSegs.size(); ++i )
1504 if ( ! L1.IsAdjacent( *foundSegs[i], &LE1 ) &&
1505 intersection.Compute( *foundSegs[i], LE1._ray ))
1507 const double dist2DToL2 = intersection._param2;
1508 double newLen2D = dist2DToL2 / 2;
1509 if ( newLen2D < 1.1 * LE1._length2D ) // collision!
1511 if ( newLen2D > 0 || !L1._advancable )
1513 blockedEdgesList.push_back( &LE1 );
1514 if ( L1._advancable && newLen2D > 0 )
1516 edgeLenLimitList.push_back( make_pair( &LE1, newLen2D ));
1517 blockedEdgesList.push_back( &L2._lEdges[ foundSegs[i]->_indexInLine ]);
1518 blockedEdgesList.push_back( &L2._lEdges[ foundSegs[i]->_indexInLine + 1 ]);
1520 else // here dist2DToL2 < 0 and LE1._length2D == 0
1522 _LayerEdge* LE2[2] = { & L2._lEdges[ foundSegs[i]->_indexInLine ],
1523 & L2._lEdges[ foundSegs[i]->_indexInLine + 1 ] };
1524 _Segment outSeg2( LE2[0]->_uvOut, LE2[1]->_uvOut );
1525 intersection.Compute( outSeg2, LE1._ray );
1526 newLen2D = intersection._param2 / 2;
1529 edgeLenLimitList.push_back( make_pair( LE2[0], newLen2D ));
1530 edgeLenLimitList.push_back( make_pair( LE2[1], newLen2D ));
1541 // limit length of _LayerEdge's that are extrema of _PolyLine's
1542 // to avoid intersection of these _LayerEdge's
1543 for ( size_t iL1 = 0; iL1 < _polyLineVec.size(); ++iL1 )
1545 _PolyLine& L = _polyLineVec[ iL1 ];
1546 if ( L._lEdges.size() < 4 ) // all intermediate _LayerEdge's intersect with extremum ones
1548 _LayerEdge& LEL = L._leftLine->_lEdges.back();
1549 _LayerEdge& LER = L._lEdges.back();
1550 _Segment segL( LEL._uvOut, LEL._uvIn );
1551 _Segment segR( LER._uvOut, LER._uvIn );
1552 double newLen2DL, newLen2DR;
1553 if ( intersection.Compute( segL, LER._ray ))
1555 newLen2DR = intersection._param2 / 2;
1556 newLen2DL = LEL._length2D * intersection._param1 / 2;
1558 else if ( intersection.Compute( segR, LEL._ray ))
1560 newLen2DL = intersection._param2 / 2;
1561 newLen2DR = LER._length2D * intersection._param1 / 2;
1567 if ( newLen2DL > 0 && newLen2DR > 0 )
1569 if ( newLen2DL < 1.1 * LEL._length2D )
1570 edgeLenLimitList.push_back( make_pair( &LEL, newLen2DL ));
1571 if ( newLen2DR < 1.1 * LER._length2D )
1572 edgeLenLimitList.push_back( make_pair( &LER, newLen2DR ));
1577 // set limited length to _LayerEdge's
1578 list< pair< _LayerEdge*, double > >::iterator edge2Len = edgeLenLimitList.begin();
1579 for ( ; edge2Len != edgeLenLimitList.end(); ++edge2Len )
1581 _LayerEdge* LE = edge2Len->first;
1582 if ( LE->_length2D > edge2Len->second )
1584 LE->_isBlocked = false;
1585 LE->SetNewLength( edge2Len->second / LE->_len2dTo3dRatio );
1587 LE->_isBlocked = true;
1590 // block inflation of _LayerEdge's
1591 list< _LayerEdge* >::iterator edge = blockedEdgesList.begin();
1592 for ( ; edge != blockedEdgesList.end(); ++edge )
1593 (*edge)->_isBlocked = true;
1595 // find a not blocked _LayerEdge
1596 for ( size_t iL = 0; iL < _polyLineVec.size(); ++iL )
1598 _PolyLine& L = _polyLineVec[ iL ];
1599 if ( !L._advancable ) continue;
1600 for ( size_t iLE = L.FirstLEdge(); iLE < L._lEdges.size(); ++iLE )
1601 if ( !L._lEdges[ iLE ]._isBlocked )
1608 //================================================================================
1610 * \brief Create new edges and shrink edges existing on a non-advancable _PolyLine
1611 * adjacent to an advancable one.
1613 //================================================================================
1615 bool _ViscousBuilder2D::shrink()
1617 gp_Pnt2d uv; //gp_Vec2d tangent;
1618 _SegmentIntersection intersection;
1621 for ( size_t iL1 = 0; iL1 < _polyLineVec.size(); ++iL1 )
1623 _PolyLine& L = _polyLineVec[ iL1 ]; // line with no layers
1624 if ( L._advancable )
1626 const int nbAdvancable = ( L._rightLine->_advancable + L._leftLine->_advancable );
1627 if ( nbAdvancable == 0 )
1630 const TopoDS_Vertex& V1 = L._wire->FirstVertex( L._edgeInd );
1631 const TopoDS_Vertex& V2 = L._wire->LastVertex ( L._edgeInd );
1632 const int v1ID = getMeshDS()->ShapeToIndex( V1 );
1633 const int v2ID = getMeshDS()->ShapeToIndex( V2 );
1634 const bool isShrinkableL = ! _noShrinkVert.count( v1ID ) && L._leftLine->_advancable;
1635 const bool isShrinkableR = ! _noShrinkVert.count( v2ID ) && L._rightLine->_advancable;
1636 if ( !isShrinkableL && !isShrinkableR )
1639 const TopoDS_Edge& E = L._wire->Edge ( L._edgeInd );
1640 const int edgeID = L._wire->EdgeID ( L._edgeInd );
1641 const double edgeLen = L._wire->EdgeLength ( L._edgeInd );
1642 Handle(Geom2d_Curve) pcurve = L._wire->Curve2d ( L._edgeInd );
1643 const bool edgeReversed = ( E.Orientation() == TopAbs_REVERSED );
1645 SMESH_MesherHelper helper( *_mesh ); // to create nodes and edges on E
1646 helper.SetSubShape( E );
1647 helper.SetElementsOnShape( true );
1649 // Check a FACE adjacent to _face by E
1650 bool existingNodesFound = false;
1651 TopoDS_Face adjFace;
1652 PShapeIteratorPtr faceIt = _helper.GetAncestors( E, *_mesh, TopAbs_FACE );
1653 while ( const TopoDS_Shape* f = faceIt->next() )
1654 if ( !_face.IsSame( *f ))
1656 adjFace = TopoDS::Face( *f );
1657 SMESH_ProxyMesh::Ptr pm = _ProxyMeshHolder::FindProxyMeshOfFace( adjFace, *_mesh );
1658 if ( !pm || pm->NbProxySubMeshes() == 0 /*|| !pm->GetProxySubMesh( E )*/)
1660 // There are no viscous layers on an adjacent FACE, clear it's 2D mesh
1661 removeMeshFaces( adjFace );
1662 // if ( removeMeshFaces( adjFace ))
1663 // _clearedFaces.push_back( adjFace ); // to re-compute after all
1667 // There are viscous layers on the adjacent FACE; shrink must be already done;
1671 const vector<UVPtStruct>& points = L._wire->GetUVPtStruct();
1672 int iPFrom = L._firstPntInd, iPTo = L._lastPntInd;
1673 if ( isShrinkableL )
1675 const THypVL* hyp = getLineHypothesis( L._leftLine->_index );
1676 vector<gp_XY>& uvVec = L._lEdges.front()._uvRefined;
1677 for ( int i = 0; i < hyp->GetNumberLayers(); ++i ) {
1678 const UVPtStruct& uvPt = points[ iPFrom + i + 1 ];
1679 L._leftNodes.push_back( uvPt.node );
1680 uvVec.push_back ( pcurve->Value( uvPt.param ).XY() );
1682 iPFrom += hyp->GetNumberLayers();
1684 if ( isShrinkableR )
1686 const THypVL* hyp = getLineHypothesis( L._rightLine->_index );
1687 vector<gp_XY>& uvVec = L._lEdges.back()._uvRefined;
1688 for ( int i = 0; i < hyp->GetNumberLayers(); ++i ) {
1689 const UVPtStruct& uvPt = points[ iPTo - i - 1 ];
1690 L._rightNodes.push_back( uvPt.node );
1691 uvVec.push_back ( pcurve->Value( uvPt.param ).XY() );
1693 iPTo -= hyp->GetNumberLayers();
1695 // make proxy sub-mesh data of present nodes
1697 UVPtStructVec nodeDataVec( & points[ iPFrom ], & points[ iPTo + 1 ]);
1699 double normSize = nodeDataVec.back().normParam - nodeDataVec.front().normParam;
1700 for ( int iP = nodeDataVec.size()-1; iP >= 0 ; --iP )
1701 nodeDataVec[iP].normParam =
1702 ( nodeDataVec[iP].normParam - nodeDataVec[0].normParam ) / normSize;
1704 const SMDS_MeshNode* n = nodeDataVec.front().node;
1705 if ( n->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX )
1706 nodeDataVec.front().param = L._wire->FirstU( L._edgeInd );
1707 n = nodeDataVec.back().node;
1708 if ( n->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX )
1709 nodeDataVec.back().param = L._wire->LastU( L._edgeInd );
1711 _ProxyMeshOfFace::_EdgeSubMesh* myEdgeSM = getProxyMesh()->GetEdgeSubMesh( edgeID );
1712 myEdgeSM->SetUVPtStructVec( nodeDataVec );
1714 existingNodesFound = true;
1717 } // loop on FACEs sharing E
1719 // Commented as a case with a seam EDGE (issue 0052461) is hard to support
1720 // because SMESH_ProxyMesh can't hold different sub-meshes for two
1721 // 2D representations of the seam. But such a case is not a real practice one.
1722 // Check if L is an already shrinked seam
1723 // if ( adjFace.IsNull() && _helper.IsRealSeam( edgeID ))
1725 // for ( int iL2 = iL1-1; iL2 > -1; --iL2 )
1727 // _PolyLine& L2 = _polyLineVec[ iL2 ];
1728 // if ( edgeID == L2._wire->EdgeID( L2._edgeInd ))
1730 // // copy layer nodes
1731 // const int seamPar = _helper.GetPeriodicIndex();
1732 // vector<gp_XY>& uvVec = L._lEdges.front()._uvRefined;
1733 // if ( isShrinkableL )
1735 // L._leftNodes = L2._rightNodes;
1736 // uvVec = L2._lEdges.back()._uvRefined;
1738 // if ( isShrinkableR )
1740 // L._rightNodes = L2._leftNodes;
1741 // uvVec = L2._lEdges.front()._uvRefined;
1743 // for ( size_t i = 0; i < uvVec.size(); ++i )
1745 // gp_XY & uv = uvVec[i];
1746 // uv.SetCoord( seamPar, _helper.GetOtherParam( uv.Coord( seamPar )));
1749 // existingNodesFound = true;
1755 if ( existingNodesFound )
1756 continue; // nothing more to do in this case
1758 double u1 = L._wire->FirstU( L._edgeInd ), uf = u1;
1759 double u2 = L._wire->LastU ( L._edgeInd ), ul = u2;
1761 // a ratio to pass 2D <--> 1D
1762 const double len1D = 1e-3;
1763 const double len2D = pcurve->Value(uf).Distance( pcurve->Value(uf+len1D));
1764 double len1dTo2dRatio = len1D / len2D;
1766 // create a vector of proxy nodes
1767 const vector<UVPtStruct>& points = L._wire->GetUVPtStruct();
1768 UVPtStructVec nodeDataVec( & points[ L._firstPntInd ],
1769 & points[ L._lastPntInd + 1 ]);
1770 nodeDataVec.front().param = u1; // U on vertex is correct on only one of shared edges
1771 nodeDataVec.back ().param = u2;
1772 nodeDataVec.front().normParam = 0;
1773 nodeDataVec.back ().normParam = 1;
1775 // Get length of existing segments (from an edge start to a node) and their nodes
1776 vector< double > segLengths( nodeDataVec.size() - 1 );
1777 BRepAdaptor_Curve curve( E );
1778 for ( size_t iP = 1; iP < nodeDataVec.size(); ++iP )
1780 const double len = GCPnts_AbscissaPoint::Length( curve, uf, nodeDataVec[iP].param );
1781 segLengths[ iP-1 ] = len;
1784 // Move first and last parameters on EDGE (U of n1) according to layers' thickness
1785 // and create nodes of layers on EDGE ( -x-x-x )
1789 // x-----x-----x-----x-----
1794 // x-x-x-x-----x-----x----
1797 int isRShrinkedForAdjacent;
1798 UVPtStructVec nodeDataForAdjacent;
1799 for ( int isR = 0; isR < 2; ++isR )
1801 _PolyLine* L2 = isR ? L._rightLine : L._leftLine; // line with layers
1802 if ( !L2->_advancable &&
1803 !toShrinkForAdjacent( adjFace, E, L._wire->FirstVertex( L._edgeInd + isR )))
1805 if ( isR ? !isShrinkableR : !isShrinkableL )
1808 double & u = isR ? u2 : u1; // param to move
1809 double u0 = isR ? ul : uf; // init value of the param to move
1810 int iPEnd = isR ? nodeDataVec.size() - 1 : 0;
1812 _LayerEdge& nearLE = isR ? L._lEdges.back() : L._lEdges.front();
1813 _LayerEdge& farLE = isR ? L._lEdges.front() : L._lEdges.back();
1815 // try to find length of advancement along L by intersecting L with
1816 // an adjacent _Segment of L2
1818 double& length2D = nearLE._length2D;
1819 double length1D = 0;
1820 sign = ( isR ^ edgeReversed ) ? -1. : 1.;
1822 bool isConvex = false;
1823 if ( L2->_advancable )
1825 const uvPtStruct& tang2P1 = points[ isR ? L2->_firstPntInd : L2->_lastPntInd ];
1826 const uvPtStruct& tang2P2 = points[ isR ? L2->_firstPntInd+1 : L2->_lastPntInd-1 ];
1827 gp_XY seg2Dir( tang2P2.u - tang2P1.u,
1828 tang2P2.v - tang2P1.v );
1829 int iFSeg2 = isR ? 0 : L2->_segments.size() - 1;
1830 int iLSeg2 = isR ? 1 : L2->_segments.size() - 2;
1831 gp_XY uvLSeg2In = L2->_lEdges[ iLSeg2 ]._uvIn;
1832 Handle(Geom2d_Line) seg2Line = new Geom2d_Line( uvLSeg2In, seg2Dir );
1834 Geom2dAdaptor_Curve edgeCurve( pcurve, Min( uf, ul ), Max( uf, ul ));
1835 Geom2dAdaptor_Curve seg2Curve( seg2Line );
1836 Geom2dInt_GInter curveInt( edgeCurve, seg2Curve, 1e-7, 1e-7 );
1837 isConvex = ( curveInt.IsDone() && !curveInt.IsEmpty() );
1840 length1D = Abs( u - curveInt.Point( 1 ).ParamOnFirst() );
1841 double maxDist2d = 2 * L2->_lEdges[ iLSeg2 ]._length2D;
1842 isConvex = ( length1D < maxDist2d * len1dTo2dRatio );
1849 if ( !isConvex ) { /* concave VERTEX */ /* o-----o---
1855 length2D = L2->_lEdges[ iFSeg2 ]._length2D;
1856 //if ( L2->_advancable ) continue;
1859 else // L2 is advancable but in the face adjacent by L
1861 length2D = farLE._length2D;
1862 if ( length2D == 0 ) {
1863 _LayerEdge& neighborLE =
1864 ( isR ? L._leftLine->_lEdges.back() : L._rightLine->_lEdges.front() );
1865 length2D = neighborLE._length2D;
1866 if ( length2D == 0 )
1867 length2D = _maxThickness * nearLE._len2dTo3dRatio;
1871 // move u to the internal boundary of layers
1873 // x-x-x-x-----x-----x----
1874 double maxLen3D = Min( _maxThickness, edgeLen / ( 1 + nbAdvancable ));
1875 double maxLen2D = maxLen3D * nearLE._len2dTo3dRatio;
1876 if ( !length2D ) length2D = length1D / len1dTo2dRatio;
1877 if ( Abs( length2D ) > maxLen2D )
1878 length2D = maxLen2D;
1879 nearLE._uvIn = nearLE._uvOut + nearLE._normal2D * length2D;
1881 u += length2D * len1dTo2dRatio * sign;
1882 nodeDataVec[ iPEnd ].param = u;
1884 gp_Pnt2d newUV = pcurve->Value( u );
1885 nodeDataVec[ iPEnd ].u = newUV.X();
1886 nodeDataVec[ iPEnd ].v = newUV.Y();
1888 // compute params of layers on L
1889 vector<double> heights;
1890 const THypVL* hyp = getLineHypothesis( L2->_index );
1891 calcLayersHeight( u - u0, heights, hyp );
1893 vector< double > params( heights.size() );
1894 for ( size_t i = 0; i < params.size(); ++i )
1895 params[ i ] = u0 + heights[ i ];
1897 // create nodes of layers and edges between them
1899 vector< const SMDS_MeshNode* >& layersNode = isR ? L._rightNodes : L._leftNodes;
1900 vector<gp_XY>& nodeUV = ( isR ? L._lEdges.back() : L._lEdges[0] )._uvRefined;
1901 nodeUV.resize ( hyp->GetNumberLayers() );
1902 layersNode.resize( hyp->GetNumberLayers() );
1903 const SMDS_MeshNode* vertexNode = nodeDataVec[ iPEnd ].node;
1904 const SMDS_MeshNode * prevNode = vertexNode;
1905 for ( size_t i = 0; i < params.size(); ++i )
1907 const gp_Pnt p = curve.Value( params[i] );
1908 layersNode[ i ] = helper.AddNode( p.X(), p.Y(), p.Z(), /*id=*/0, params[i] );
1909 nodeUV [ i ] = pcurve->Value( params[i] ).XY();
1910 helper.AddEdge( prevNode, layersNode[ i ] );
1911 prevNode = layersNode[ i ];
1914 // store data of layer nodes made for adjacent FACE
1915 if ( !L2->_advancable )
1917 isRShrinkedForAdjacent = isR;
1918 nodeDataForAdjacent.resize( hyp->GetNumberLayers() );
1920 size_t iFrw = 0, iRev = nodeDataForAdjacent.size()-1, *i = isR ? &iRev : &iFrw;
1921 nodeDataForAdjacent[ *i ] = points[ isR ? L._lastPntInd : L._firstPntInd ];
1922 nodeDataForAdjacent[ *i ].param = u0;
1923 nodeDataForAdjacent[ *i ].normParam = isR;
1924 for ( ++iFrw, --iRev; iFrw < layersNode.size(); ++iFrw, --iRev )
1926 nodeDataForAdjacent[ *i ].node = layersNode[ iFrw - 1 ];
1927 nodeDataForAdjacent[ *i ].u = nodeUV [ iFrw - 1 ].X();
1928 nodeDataForAdjacent[ *i ].v = nodeUV [ iFrw - 1 ].Y();
1929 nodeDataForAdjacent[ *i ].param = params [ iFrw - 1 ];
1932 // replace a node on vertex by a node of last (most internal) layer
1933 // in a segment on E
1934 SMDS_ElemIteratorPtr segIt = vertexNode->GetInverseElementIterator( SMDSAbs_Edge );
1935 const SMDS_MeshNode* segNodes[3];
1936 while ( segIt->more() )
1938 const SMDS_MeshElement* segment = segIt->next();
1939 if ( segment->getshapeId() != edgeID ) continue;
1941 const int nbNodes = segment->NbNodes();
1942 for ( int i = 0; i < nbNodes; ++i )
1944 const SMDS_MeshNode* n = segment->GetNode( i );
1945 segNodes[ i ] = ( n == vertexNode ? layersNode.back() : n );
1947 getMeshDS()->ChangeElementNodes( segment, segNodes, nbNodes );
1950 nodeDataVec[ iPEnd ].node = layersNode.back();
1952 } // loop on the extremities of L
1954 // Shrink edges to fit in between the layers at EDGE ends
1956 double newLength = GCPnts_AbscissaPoint::Length( curve, u1, u2 );
1957 double lenRatio = newLength / edgeLen * ( edgeReversed ? -1. : 1. );
1958 for ( size_t iP = 1; iP < nodeDataVec.size()-1; ++iP )
1960 const SMDS_MeshNode* oldNode = nodeDataVec[iP].node;
1962 GCPnts_AbscissaPoint discret( curve, segLengths[iP-1] * lenRatio, u1 );
1963 if ( !discret.IsDone() )
1964 throw SALOME_Exception(LOCALIZED("GCPnts_AbscissaPoint failed"));
1966 nodeDataVec[iP].param = discret.Parameter();
1967 if ( oldNode->GetPosition()->GetTypeOfPosition() != SMDS_TOP_EDGE )
1968 throw SALOME_Exception(SMESH_Comment("ViscousBuilder2D: not SMDS_TOP_EDGE node position: ")
1969 << oldNode->GetPosition()->GetTypeOfPosition()
1970 << " of node " << oldNode->GetID());
1971 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( oldNode->GetPosition() );
1972 pos->SetUParameter( nodeDataVec[iP].param );
1974 gp_Pnt newP = curve.Value( nodeDataVec[iP].param );
1975 getMeshDS()->MoveNode( oldNode, newP.X(), newP.Y(), newP.Z() );
1977 gp_Pnt2d newUV = pcurve->Value( nodeDataVec[iP].param ).XY();
1978 nodeDataVec[iP].u = newUV.X();
1979 nodeDataVec[iP].v = newUV.Y();
1980 nodeDataVec[iP].normParam = segLengths[iP-1] / edgeLen;
1981 // nodeDataVec[iP].x = segLengths[iP-1] / edgeLen;
1982 // nodeDataVec[iP].y = segLengths[iP-1] / edgeLen;
1985 // Add nodeDataForAdjacent to nodeDataVec
1987 if ( !nodeDataForAdjacent.empty() )
1989 const double par1 = isRShrinkedForAdjacent ? u2 : uf;
1990 const double par2 = isRShrinkedForAdjacent ? ul : u1;
1991 const double shrinkLen = GCPnts_AbscissaPoint::Length( curve, par1, par2 );
1993 // compute new normParam for nodeDataVec
1994 for ( size_t iP = 0; iP < nodeDataVec.size()-1; ++iP )
1995 nodeDataVec[iP+1].normParam = segLengths[iP] / ( edgeLen + shrinkLen );
1996 double normDelta = 1 - nodeDataVec.back().normParam;
1997 if ( !isRShrinkedForAdjacent )
1998 for ( size_t iP = 0; iP < nodeDataVec.size(); ++iP )
1999 nodeDataVec[iP].normParam += normDelta;
2001 // compute new normParam for nodeDataForAdjacent
2002 const double deltaR = isRShrinkedForAdjacent ? nodeDataVec.back().normParam : 0;
2003 for ( size_t iP = !isRShrinkedForAdjacent; iP < nodeDataForAdjacent.size(); ++iP )
2005 double lenFromPar1 =
2006 GCPnts_AbscissaPoint::Length( curve, par1, nodeDataForAdjacent[iP].param );
2007 nodeDataForAdjacent[iP].normParam = deltaR + normDelta * lenFromPar1 / shrinkLen;
2009 // concatenate nodeDataVec and nodeDataForAdjacent
2010 nodeDataVec.insert(( isRShrinkedForAdjacent ? nodeDataVec.end() : nodeDataVec.begin() ),
2011 nodeDataForAdjacent.begin(), nodeDataForAdjacent.end() );
2014 // Extend nodeDataVec by a node located at the end of not shared _LayerEdge
2015 /* n - to add to nodeDataVec
2024 for ( int isR = 0; isR < 2; ++isR )
2026 _PolyLine& L2 = *( isR ? L._rightLine : L._leftLine ); // line with layers
2027 if ( ! L2._advancable || L.IsCommonEdgeShared( L2 ) )
2029 vector< const SMDS_MeshNode* >& layerNodes2 = isR ? L2._leftNodes : L2._rightNodes;
2030 _LayerEdge& LE2 = isR ? L2._lEdges.front() : L2._lEdges.back();
2031 if ( layerNodes2.empty() )
2033 // refine the not shared _LayerEdge
2034 vector<double> layersHeight;
2035 calcLayersHeight( LE2._length2D, layersHeight, getLineHypothesis( L2._index ));
2037 vector<gp_XY>& nodeUV2 = LE2._uvRefined;
2038 nodeUV2.resize ( layersHeight.size() );
2039 layerNodes2.resize( layersHeight.size() );
2040 for ( size_t i = 0; i < layersHeight.size(); ++i )
2042 gp_XY uv = LE2._uvOut + LE2._normal2D * layersHeight[i];
2043 gp_Pnt p = _surface->Value( uv.X(), uv.Y() );
2045 layerNodes2[ i ] = _helper.AddNode( p.X(), p.Y(), p.Z(), /*id=*/0, uv.X(), uv.Y() );
2048 UVPtStruct ptOfNode;
2049 ptOfNode.u = LE2._uvRefined.back().X();
2050 ptOfNode.v = LE2._uvRefined.back().Y();
2051 ptOfNode.node = layerNodes2.back();
2052 ptOfNode.param = isR ? ul : uf;
2053 ptOfNode.normParam = isR ? 1 : 0;
2055 nodeDataVec.insert(( isR ? nodeDataVec.end() : nodeDataVec.begin() ), ptOfNode );
2057 // recompute normParam of nodes in nodeDataVec
2058 newLength = GCPnts_AbscissaPoint::Length( curve,
2059 nodeDataVec.front().param,
2060 nodeDataVec.back().param);
2061 for ( size_t iP = 1; iP < nodeDataVec.size(); ++iP )
2063 const double len = GCPnts_AbscissaPoint::Length( curve,
2064 nodeDataVec.front().param,
2065 nodeDataVec[iP].param );
2066 nodeDataVec[iP].normParam = len / newLength;
2070 // create a proxy sub-mesh containing the moved nodes
2071 _ProxyMeshOfFace::_EdgeSubMesh* edgeSM = getProxyMesh()->GetEdgeSubMesh( edgeID );
2072 edgeSM->SetUVPtStructVec( nodeDataVec );
2074 // set a sub-mesh event listener to remove just created edges when
2075 // "ViscousLayers2D" hypothesis is modified
2076 VISCOUS_3D::ToClearSubWithMain( _mesh->GetSubMesh( E ), _face );
2078 } // loop on _polyLineVec
2083 //================================================================================
2085 * \brief Returns true if there will be a shrinked mesh on EDGE E of FACE adjFace
2088 //================================================================================
2090 bool _ViscousBuilder2D::toShrinkForAdjacent( const TopoDS_Face& adjFace,
2091 const TopoDS_Edge& E,
2092 const TopoDS_Vertex& V)
2094 if ( _noShrinkVert.count( getMeshDS()->ShapeToIndex( V )) || adjFace.IsNull() )
2097 vector< const StdMeshers_ViscousLayers2D* > hyps;
2098 vector< TopoDS_Shape > hypShapes;
2099 if ( VISCOUS_2D::findHyps( *_mesh, adjFace, hyps, hypShapes ))
2101 VISCOUS_2D::_ViscousBuilder2D builder( *_mesh, adjFace, hyps, hypShapes );
2102 builder._faceSideVec = StdMeshers_FaceSide::GetFaceWires( adjFace, *_mesh, true, _error );
2103 builder.findEdgesWithLayers();
2105 PShapeIteratorPtr edgeIt = _helper.GetAncestors( V, *_mesh, TopAbs_EDGE );
2106 while ( const TopoDS_Shape* edgeAtV = edgeIt->next() )
2108 if ( !edgeAtV->IsSame( E ) &&
2109 _helper.IsSubShape( *edgeAtV, adjFace ) &&
2110 !builder._ignoreShapeIds.count( getMeshDS()->ShapeToIndex( *edgeAtV )))
2119 //================================================================================
2123 //================================================================================
2125 bool _ViscousBuilder2D::refine()
2127 // find out orientation of faces to create
2129 ( _helper.GetSubShapeOri( _mesh->GetShapeToMesh(), _face ) == TopAbs_REVERSED );
2131 // store a proxyMesh in a sub-mesh
2132 // make faces on each _PolyLine
2133 vector< double > layersHeight;
2134 double prevLen2D = -1;
2135 for ( size_t iL = 0; iL < _polyLineVec.size(); ++iL )
2137 _PolyLine& L = _polyLineVec[ iL ];
2138 if ( !L._advancable ) continue;
2140 // replace an inactive (1st) _LayerEdge with an active one of a neighbour _PolyLine
2141 //size_t iLE = 0, nbLE = L._lEdges.size();
2142 const bool leftEdgeShared = L.IsCommonEdgeShared( *L._leftLine );
2143 const bool rightEdgeShared = L.IsCommonEdgeShared( *L._rightLine );
2144 if ( /*!L._leftLine->_advancable &&*/ leftEdgeShared )
2146 L._lEdges[0] = L._leftLine->_lEdges.back();
2147 //iLE += int( !L._leftLine->_advancable );
2149 if ( !L._rightLine->_advancable && rightEdgeShared )
2151 L._lEdges.back() = L._rightLine->_lEdges[0];
2155 // limit length of neighbour _LayerEdge's to avoid sharp change of layers thickness
2157 vector< double > segLen( L._lEdges.size() );
2160 // check if length modification is usefull: look for _LayerEdge's
2161 // with length limited due to collisions
2162 bool lenLimited = false;
2163 for ( size_t iLE = 1; ( iLE < L._lEdges.size()-1 && !lenLimited ); ++iLE )
2164 lenLimited = L._lEdges[ iLE ]._isBlocked;
2168 for ( size_t i = 1; i < segLen.size(); ++i )
2170 // accumulate length of segments
2171 double sLen = (L._lEdges[i-1]._uvOut - L._lEdges[i]._uvOut ).Modulus();
2172 segLen[i] = segLen[i-1] + sLen;
2174 const double totSegLen = segLen.back();
2175 // normalize the accumulated length
2176 for ( size_t iS = 1; iS < segLen.size(); ++iS )
2177 segLen[iS] /= totSegLen;
2179 for ( int isR = 0; isR < 2; ++isR )
2181 size_t iF = 0, iL = L._lEdges.size()-1;
2182 size_t *i = isR ? &iL : &iF;
2183 _LayerEdge* prevLE = & L._lEdges[ *i ];
2185 for ( ++iF, --iL; iF < L._lEdges.size()-1; ++iF, --iL )
2187 _LayerEdge& LE = L._lEdges[*i];
2188 if ( prevLE->_length2D > 0 )
2190 gp_XY tangent ( LE._normal2D.Y(), -LE._normal2D.X() );
2191 weight += Abs( tangent * ( prevLE->_uvIn - LE._uvIn )) / totSegLen;
2192 // gp_XY prevTang( LE._uvOut - prevLE->_uvOut );
2193 // gp_XY prevNorm( -prevTang.Y(), prevTang.X() );
2194 gp_XY prevNorm = LE._normal2D;
2195 double prevProj = prevNorm * ( prevLE->_uvIn - prevLE->_uvOut );
2196 if ( prevProj > 0 ) {
2197 prevProj /= prevNorm.Modulus();
2198 if ( LE._length2D < prevProj )
2199 weight += 0.75 * ( 1 - weight ); // length decrease is more preferable
2200 LE._length2D = weight * LE._length2D + ( 1 - weight ) * prevProj;
2201 LE._uvIn = LE._uvOut + LE._normal2D * LE._length2D;
2208 // DEBUG: to see _uvRefined. cout can be redirected to hide NETGEN output
2209 // cerr << "import smesh" << endl << "mesh = smesh.Mesh()"<< endl;
2211 const vector<UVPtStruct>& points = L._wire->GetUVPtStruct();
2213 // analyse extremities of the _PolyLine to find existing nodes
2214 const TopoDS_Vertex& V1 = L._wire->FirstVertex( L._edgeInd );
2215 const TopoDS_Vertex& V2 = L._wire->LastVertex ( L._edgeInd );
2216 const int v1ID = getMeshDS()->ShapeToIndex( V1 );
2217 const int v2ID = getMeshDS()->ShapeToIndex( V2 );
2218 const bool isShrinkableL = ! _noShrinkVert.count( v1ID );
2219 const bool isShrinkableR = ! _noShrinkVert.count( v2ID );
2221 bool hasLeftNode = ( !L._leftLine->_rightNodes.empty() && leftEdgeShared );
2222 bool hasRightNode = ( !L._rightLine->_leftNodes.empty() && rightEdgeShared );
2223 bool hasOwnLeftNode = ( !L._leftNodes.empty() );
2224 bool hasOwnRightNode = ( !L._rightNodes.empty() );
2225 bool isClosedEdge = ( points[ L._firstPntInd ].node == points[ L._lastPntInd ].node );
2227 nbN = L._lastPntInd - L._firstPntInd + 1,
2228 iN0 = ( hasLeftNode || hasOwnLeftNode || isClosedEdge || !isShrinkableL ),
2229 iNE = nbN - ( hasRightNode || hasOwnRightNode || !isShrinkableR );
2231 // update _uvIn of end _LayerEdge's by existing nodes
2232 const SMDS_MeshNode *nL = 0, *nR = 0;
2233 if ( hasOwnLeftNode ) nL = L._leftNodes.back();
2234 else if ( hasLeftNode ) nL = L._leftLine->_rightNodes.back();
2235 if ( hasOwnRightNode ) nR = L._rightNodes.back();
2236 else if ( hasRightNode ) nR = L._rightLine->_leftNodes.back();
2238 L._lEdges[0]._uvIn = _helper.GetNodeUV( _face, nL, points[ L._firstPntInd + 1 ].node );
2240 L._lEdges.back()._uvIn = _helper.GetNodeUV( _face, nR, points[ L._lastPntInd - 1 ].node );
2242 // compute normalized [0;1] node parameters of nodes on a _PolyLine
2243 vector< double > normPar( nbN );
2245 normF = L._wire->FirstParameter( L._edgeInd ),
2246 normL = L._wire->LastParameter ( L._edgeInd ),
2247 normDist = normL - normF;
2248 for ( int i = L._firstPntInd; i <= L._lastPntInd; ++i )
2249 normPar[ i - L._firstPntInd ] = ( points[i].normParam - normF ) / normDist;
2251 // Calculate UV of most inner nodes
2253 vector< gp_XY > innerUV( nbN );
2255 // check if innerUV should be interpolated between _LayerEdge::_uvIn's
2256 const size_t nbLE = L._lEdges.size();
2257 bool needInterpol = ( nbN != nbLE );
2258 if ( !needInterpol )
2260 // more check: compare length of inner and outer end segments
2261 double lenIn, lenOut;
2262 for ( int isR = 0; isR < 2 && !needInterpol; ++isR )
2264 const _Segment& segIn = isR ? L._segments.back() : L._segments[0];
2265 const gp_XY& uvIn1 = segIn.p1();
2266 const gp_XY& uvIn2 = segIn.p2();
2267 const gp_XY& uvOut1 = L._lEdges[ isR ? nbLE-1 : 0 ]._uvOut;
2268 const gp_XY& uvOut2 = L._lEdges[ isR ? nbLE-2 : 1 ]._uvOut;
2269 if ( _is2DIsotropic )
2271 lenIn = ( uvIn1 - uvIn2 ).Modulus();
2272 lenOut = ( uvOut1 - uvOut2 ).Modulus();
2276 lenIn = _surface->Value( uvIn1.X(), uvIn1.Y() )
2277 .Distance( _surface->Value( uvIn2.X(), uvIn2.Y() ));
2278 lenOut = _surface->Value( uvOut1.X(), uvOut1.Y() )
2279 .Distance( _surface->Value( uvOut2.X(), uvOut2.Y() ));
2281 needInterpol = ( lenIn < 0.66 * lenOut );
2287 // compute normalized accumulated length of inner segments
2289 if ( _is2DIsotropic )
2290 for ( iS = 1; iS < segLen.size(); ++iS )
2292 double sLen = ( L._lEdges[iS-1]._uvIn - L._lEdges[iS]._uvIn ).Modulus();
2293 segLen[iS] = segLen[iS-1] + sLen;
2296 for ( iS = 1; iS < segLen.size(); ++iS )
2298 const gp_XY& uv1 = L._lEdges[iS-1]._uvIn;
2299 const gp_XY& uv2 = L._lEdges[iS ]._uvIn;
2300 gp_Pnt p1 = _surface->Value( uv1.X(), uv1.Y() );
2301 gp_Pnt p2 = _surface->Value( uv2.X(), uv2.Y() );
2302 double sLen = p1.Distance( p2 );
2303 segLen[iS] = segLen[iS-1] + sLen;
2305 // normalize the accumulated length
2306 for ( iS = 1; iS < segLen.size(); ++iS )
2307 segLen[iS] /= segLen.back();
2309 // calculate UV of most inner nodes according to the normalized node parameters
2311 for ( size_t i = 0; i < innerUV.size(); ++i )
2313 while ( normPar[i] > segLen[iS+1] )
2315 double r = ( normPar[i] - segLen[iS] ) / ( segLen[iS+1] - segLen[iS] );
2316 innerUV[ i ] = r * L._lEdges[iS+1]._uvIn + (1-r) * L._lEdges[iS]._uvIn;
2319 else // ! needInterpol
2321 for ( size_t i = 0; i < nbLE; ++i )
2322 innerUV[ i ] = L._lEdges[i]._uvIn;
2325 // normalized height of layers
2326 const THypVL* hyp = getLineHypothesis( iL );
2327 calcLayersHeight( 1., layersHeight, hyp);
2329 // Create layers of faces
2331 // nodes to create 1 layer of faces
2332 vector< const SMDS_MeshNode* > outerNodes( nbN );
2333 vector< const SMDS_MeshNode* > innerNodes( nbN );
2335 // initialize outerNodes by nodes of the L._wire
2336 for ( int i = L._firstPntInd; i <= L._lastPntInd; ++i )
2337 outerNodes[ i-L._firstPntInd ] = points[i].node;
2339 L._leftNodes .reserve( hyp->GetNumberLayers() );
2340 L._rightNodes.reserve( hyp->GetNumberLayers() );
2341 int cur = 0, prev = -1; // to take into account orientation of _face
2342 if ( isReverse ) std::swap( cur, prev );
2343 for ( int iF = 0; iF < hyp->GetNumberLayers(); ++iF ) // loop on layers of faces
2345 // create innerNodes of a current layer
2346 for ( size_t i = iN0; i < iNE; ++i )
2348 gp_XY uvOut = points[ L._firstPntInd + i ].UV();
2349 gp_XY& uvIn = innerUV[ i ];
2350 gp_XY uv = layersHeight[ iF ] * uvIn + ( 1.-layersHeight[ iF ]) * uvOut;
2351 gp_Pnt p = _surface->Value( uv.X(), uv.Y() );
2352 innerNodes[i] = _helper.AddNode( p.X(), p.Y(), p.Z(), /*id=*/0, uv.X(), uv.Y() );
2354 // use nodes created for adjacent _PolyLine's
2355 if ( hasOwnLeftNode ) innerNodes.front() = L._leftNodes [ iF ];
2356 else if ( hasLeftNode ) innerNodes.front() = L._leftLine->_rightNodes[ iF ];
2357 if ( hasOwnRightNode ) innerNodes.back() = L._rightNodes[ iF ];
2358 else if ( hasRightNode ) innerNodes.back() = L._rightLine->_leftNodes[ iF ];
2359 if ( isClosedEdge ) innerNodes.front() = innerNodes.back(); // circle
2360 if ( !isShrinkableL ) innerNodes.front() = outerNodes.front();
2361 if ( !isShrinkableR ) innerNodes.back() = outerNodes.back();
2362 if ( !hasOwnLeftNode ) L._leftNodes.push_back( innerNodes.front() );
2363 if ( !hasOwnRightNode ) L._rightNodes.push_back( innerNodes.back() );
2366 for ( size_t i = 1; i < innerNodes.size(); ++i )
2367 if ( SMDS_MeshElement* f = _helper.AddFace( outerNodes[ i+prev ], outerNodes[ i+cur ],
2368 innerNodes[ i+cur ], innerNodes[ i+prev ]))
2369 L._newFaces.insert( L._newFaces.end(), f );
2371 outerNodes.swap( innerNodes );
2374 // faces between not shared _LayerEdge's (at concave VERTEX)
2375 for ( int isR = 0; isR < 2; ++isR )
2377 if ( isR ? rightEdgeShared : leftEdgeShared )
2379 vector< const SMDS_MeshNode* > &
2380 lNodes = (isR ? L._rightNodes : L._leftLine->_rightNodes ),
2381 rNodes = (isR ? L._rightLine->_leftNodes : L._leftNodes );
2382 if ( lNodes.empty() || rNodes.empty() || lNodes.size() != rNodes.size() )
2385 for ( size_t i = 1; i < lNodes.size(); ++i )
2386 _helper.AddFace( lNodes[ i+prev ], rNodes[ i+prev ],
2387 rNodes[ i+cur ], lNodes[ i+cur ]);
2389 const UVPtStruct& ptOnVertex = points[ isR ? L._lastPntInd : L._firstPntInd ];
2391 _helper.AddFace( ptOnVertex.node, lNodes[ 0 ], rNodes[ 0 ]);
2393 _helper.AddFace( ptOnVertex.node, rNodes[ 0 ], lNodes[ 0 ]);
2396 // Fill the _ProxyMeshOfFace
2398 UVPtStructVec nodeDataVec( outerNodes.size() ); // outerNodes swapped with innerNodes
2399 for ( size_t i = 0; i < outerNodes.size(); ++i )
2401 gp_XY uv = _helper.GetNodeUV( _face, outerNodes[i] );
2402 nodeDataVec[i].u = uv.X();
2403 nodeDataVec[i].v = uv.Y();
2404 nodeDataVec[i].node = outerNodes[i];
2405 nodeDataVec[i].param = points [i + L._firstPntInd].param;
2406 nodeDataVec[i].normParam = normPar[i];
2407 nodeDataVec[i].x = normPar[i];
2408 nodeDataVec[i].y = normPar[i];
2410 nodeDataVec.front().param = L._wire->FirstU( L._edgeInd );
2411 nodeDataVec.back() .param = L._wire->LastU ( L._edgeInd );
2413 _ProxyMeshOfFace::_EdgeSubMesh* edgeSM
2414 = getProxyMesh()->GetEdgeSubMesh( L._wire->EdgeID( L._edgeInd ));
2415 edgeSM->SetUVPtStructVec( nodeDataVec );
2417 } // loop on _PolyLine's
2419 // re-compute FACEs whose mesh was removed by shrink()
2420 for ( size_t i = 0; i < _clearedFaces.size(); ++i )
2422 SMESH_subMesh* sm = _mesh->GetSubMesh( _clearedFaces[i] );
2423 if ( sm->GetComputeState() == SMESH_subMesh::READY_TO_COMPUTE )
2424 sm->ComputeStateEngine( SMESH_subMesh::COMPUTE );
2430 //================================================================================
2432 * \brief Improve quality of the created mesh elements
2434 //================================================================================
2436 bool _ViscousBuilder2D::improve()
2441 // fixed nodes on EDGE's
2442 std::set<const SMDS_MeshNode*> fixedNodes;
2443 for ( size_t iWire = 0; iWire < _faceSideVec.size(); ++iWire )
2445 StdMeshers_FaceSidePtr wire = _faceSideVec[ iWire ];
2446 const vector<UVPtStruct>& points = wire->GetUVPtStruct();
2447 for ( size_t i = 0; i < points.size(); ++i )
2448 fixedNodes.insert( fixedNodes.end(), points[i].node );
2450 // fixed proxy nodes
2451 for ( size_t iL = 0; iL < _polyLineVec.size(); ++iL )
2453 _PolyLine& L = _polyLineVec[ iL ];
2454 const TopoDS_Edge& E = L._wire->Edge( L._edgeInd );
2455 if ( const SMESH_ProxyMesh::SubMesh* sm = _proxyMesh->GetProxySubMesh( E ))
2457 const UVPtStructVec& points = sm->GetUVPtStructVec();
2458 for ( size_t i = 0; i < points.size(); ++i )
2459 fixedNodes.insert( fixedNodes.end(), points[i].node );
2461 for ( size_t i = 0; i < L._rightNodes.size(); ++i )
2462 fixedNodes.insert( fixedNodes.end(), L._rightNodes[i] );
2466 SMESH_MeshEditor editor( _mesh );
2467 for ( size_t iL = 0; iL < _polyLineVec.size(); ++iL )
2469 _PolyLine& L = _polyLineVec[ iL ];
2470 if ( L._isStraight2D ) continue;
2471 // SMESH_MeshEditor::SmoothMethod how =
2472 // L._isStraight2D ? SMESH_MeshEditor::LAPLACIAN : SMESH_MeshEditor::CENTROIDAL;
2473 //editor.Smooth( L._newFaces, fixedNodes, how, /*nbIt = */3 );
2474 //editor.Smooth( L._newFaces, fixedNodes, SMESH_MeshEditor::LAPLACIAN, /*nbIt = */1 );
2475 editor.Smooth( L._newFaces, fixedNodes, SMESH_MeshEditor::CENTROIDAL, /*nbIt = */3 );
2480 //================================================================================
2482 * \brief Remove elements and nodes from a face
2484 //================================================================================
2486 bool _ViscousBuilder2D::removeMeshFaces(const TopoDS_Shape& face)
2488 // we don't use SMESH_subMesh::ComputeStateEngine() because of a listener
2489 // which clears EDGEs together with _face.
2490 bool thereWereElems = false;
2491 SMESH_subMesh* sm = _mesh->GetSubMesh( face );
2492 if ( SMESHDS_SubMesh* smDS = sm->GetSubMeshDS() )
2494 SMDS_ElemIteratorPtr eIt = smDS->GetElements();
2495 thereWereElems = eIt->more();
2496 while ( eIt->more() ) getMeshDS()->RemoveFreeElement( eIt->next(), smDS );
2497 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
2498 while ( nIt->more() ) getMeshDS()->RemoveFreeNode( nIt->next(), smDS );
2500 sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
2502 return thereWereElems;
2505 //================================================================================
2507 * \brief Returns a hypothesis for a _PolyLine
2509 //================================================================================
2511 const StdMeshers_ViscousLayers2D* _ViscousBuilder2D::getLineHypothesis(int iPL)
2513 return iPL < (int)_hypOfEdge.size() ? _hypOfEdge[ iPL ] : _hyps[0];
2516 //================================================================================
2518 * \brief Returns a layers thickness for a _PolyLine
2520 //================================================================================
2522 double _ViscousBuilder2D::getLineThickness(int iPL)
2524 if ( const StdMeshers_ViscousLayers2D* h = getLineHypothesis( iPL ))
2525 return Min( _maxThickness, h->GetTotalThickness() );
2526 return _maxThickness;
2529 //================================================================================
2531 * \brief Creates a _ProxyMeshOfFace and store it in a sub-mesh of FACE
2533 //================================================================================
2535 _ProxyMeshOfFace* _ViscousBuilder2D::getProxyMesh()
2537 if ( _proxyMesh.get() )
2538 return (_ProxyMeshOfFace*) _proxyMesh.get();
2540 _ProxyMeshOfFace* proxyMeshOfFace = new _ProxyMeshOfFace( *_mesh );
2541 _proxyMesh.reset( proxyMeshOfFace );
2542 new _ProxyMeshHolder( _face, _proxyMesh );
2544 return proxyMeshOfFace;
2547 //================================================================================
2549 * \brief Calculate height of layers for the given thickness. Height is measured
2550 * from the outer boundary
2552 //================================================================================
2554 void _ViscousBuilder2D::calcLayersHeight(const double totalThick,
2555 vector<double>& heights,
2558 const double fPowN = pow( hyp->GetStretchFactor(), hyp->GetNumberLayers() );
2559 heights.resize( hyp->GetNumberLayers() );
2561 if ( fPowN - 1 <= numeric_limits<double>::min() )
2562 h0 = totalThick / hyp->GetNumberLayers();
2564 h0 = totalThick * ( hyp->GetStretchFactor() - 1 )/( fPowN - 1 );
2566 double hSum = 0, hi = h0;
2567 for ( int i = 0; i < hyp->GetNumberLayers(); ++i )
2570 heights[ i ] = hSum;
2571 hi *= hyp->GetStretchFactor();
2575 //================================================================================
2577 * \brief Elongate this _LayerEdge
2579 //================================================================================
2581 bool _LayerEdge::SetNewLength( const double length3D )
2583 if ( _isBlocked ) return false;
2585 //_uvInPrev = _uvIn;
2586 _length2D = length3D * _len2dTo3dRatio;
2587 _uvIn = _uvOut + _normal2D * _length2D;
2591 //================================================================================
2593 * \brief Return true if _LayerEdge at a common VERTEX between EDGEs with
2594 * and w/o layer is common to the both _PolyLine's. If this is true, nodes
2595 * of this _LayerEdge are inflated along a _PolyLine w/o layer, else the nodes
2596 * are inflated along _normal2D of _LayerEdge of EDGE with layer
2598 //================================================================================
2600 bool _PolyLine::IsCommonEdgeShared( const _PolyLine& other )
2602 const double tol = 1e-30;
2604 if ( & other == _leftLine )
2605 return _lEdges[0]._normal2D.IsEqual( _leftLine->_lEdges.back()._normal2D, tol );
2607 if ( & other == _rightLine )
2608 return _lEdges.back()._normal2D.IsEqual( _rightLine->_lEdges[0]._normal2D, tol );
2613 //================================================================================
2615 * \brief Return \c true if the EDGE of this _PolyLine is concave
2617 //================================================================================
2619 bool _PolyLine::IsConcave() const
2621 if ( _lEdges.size() < 2 )
2624 gp_Vec2d v1( _lEdges[0]._uvOut, _lEdges[1]._uvOut );
2625 gp_Vec2d v2( _lEdges[0]._uvOut, _lEdges[2]._uvOut );
2626 const double size2 = v2.Magnitude();
2628 return ( v1 ^ v2 ) / size2 < -1e-3 * size2;
2631 //================================================================================
2633 * \brief Constructor of SegmentTree
2635 //================================================================================
2637 _SegmentTree::_SegmentTree( const vector< _Segment >& segments ):
2640 _segments.resize( segments.size() );
2641 for ( size_t i = 0; i < segments.size(); ++i )
2642 _segments[i].Set( segments[i] );
2647 //================================================================================
2649 * \brief Return the maximal bnd box
2651 //================================================================================
2653 _SegmentTree::box_type* _SegmentTree::buildRootBox()
2655 _SegmentTree::box_type* box = new _SegmentTree::box_type;
2656 for ( size_t i = 0; i < _segments.size(); ++i )
2658 box->Add( *_segments[i]._seg->_uv[0] );
2659 box->Add( *_segments[i]._seg->_uv[1] );
2664 //================================================================================
2666 * \brief Redistrubute _segments among children
2668 //================================================================================
2670 void _SegmentTree::buildChildrenData()
2672 for ( int i = 0; i < _segments.size(); ++i )
2673 for (int j = 0; j < nbChildren(); j++)
2674 if ( !myChildren[j]->getBox()->IsOut( *_segments[i]._seg->_uv[0],
2675 *_segments[i]._seg->_uv[1] ))
2676 ((_SegmentTree*)myChildren[j])->_segments.push_back( _segments[i]);
2678 SMESHUtils::FreeVector( _segments ); // = _elements.clear() + free memory
2680 for (int j = 0; j < nbChildren(); j++)
2682 _SegmentTree* child = static_cast<_SegmentTree*>( myChildren[j]);
2683 child->myIsLeaf = ( child->_segments.size() <= maxNbSegInLeaf() );
2687 //================================================================================
2689 * \brief Return elements which can include the point
2691 //================================================================================
2693 void _SegmentTree::GetSegmentsNear( const _Segment& seg,
2694 vector< const _Segment* >& found )
2696 if ( getBox()->IsOut( *seg._uv[0], *seg._uv[1] ))
2701 for ( int i = 0; i < _segments.size(); ++i )
2702 if ( !_segments[i].IsOut( seg ))
2703 found.push_back( _segments[i]._seg );
2707 for (int i = 0; i < nbChildren(); i++)
2708 ((_SegmentTree*) myChildren[i])->GetSegmentsNear( seg, found );
2713 //================================================================================
2715 * \brief Return segments intersecting a ray
2717 //================================================================================
2719 void _SegmentTree::GetSegmentsNear( const gp_Ax2d& ray,
2720 vector< const _Segment* >& found )
2722 if ( getBox()->IsOut( ray ))
2727 for ( int i = 0; i < _segments.size(); ++i )
2728 if ( !_segments[i].IsOut( ray ))
2729 found.push_back( _segments[i]._seg );
2733 for (int i = 0; i < nbChildren(); i++)
2734 ((_SegmentTree*) myChildren[i])->GetSegmentsNear( ray, found );
2738 //================================================================================
2740 * \brief Classify a _Segment
2742 //================================================================================
2744 bool _SegmentTree::_SegBox::IsOut( const _Segment& seg ) const
2746 const double eps = std::numeric_limits<double>::min();
2747 for ( int iC = 0; iC < 2; ++iC )
2749 if ( seg._uv[0]->Coord(iC+1) < _seg->_uv[ _iMin[iC]]->Coord(iC+1)+eps &&
2750 seg._uv[1]->Coord(iC+1) < _seg->_uv[ _iMin[iC]]->Coord(iC+1)+eps )
2752 if ( seg._uv[0]->Coord(iC+1) > _seg->_uv[ 1-_iMin[iC]]->Coord(iC+1)-eps &&
2753 seg._uv[1]->Coord(iC+1) > _seg->_uv[ 1-_iMin[iC]]->Coord(iC+1)-eps )
2759 //================================================================================
2761 * \brief Classify a ray
2763 //================================================================================
2765 bool _SegmentTree::_SegBox::IsOut( const gp_Ax2d& ray ) const
2767 double distBoxCenter2Ray =
2768 ray.Direction().XY() ^ ( ray.Location().XY() - 0.5 * (*_seg->_uv[0] + *_seg->_uv[1]));
2770 double boxSectionDiam =
2771 Abs( ray.Direction().X() ) * ( _seg->_uv[1-_iMin[1]]->Y() - _seg->_uv[_iMin[1]]->Y() ) +
2772 Abs( ray.Direction().Y() ) * ( _seg->_uv[1-_iMin[0]]->X() - _seg->_uv[_iMin[0]]->X() );
2774 return Abs( distBoxCenter2Ray ) > 0.5 * boxSectionDiam;