1 // Copyright (C) 2007-2014 CEA/DEN, EDF R&D, OPEN CASCADE
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 // Lesser General Public License for more details.
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
20 // File : StdMeshers_ViscousLayers.cxx
21 // Created : Wed Dec 1 15:15:34 2010
22 // Author : Edward AGAPOV (eap)
24 #include "StdMeshers_ViscousLayers.hxx"
26 #include "SMDS_EdgePosition.hxx"
27 #include "SMDS_FaceOfNodes.hxx"
28 #include "SMDS_FacePosition.hxx"
29 #include "SMDS_MeshNode.hxx"
30 #include "SMDS_SetIterator.hxx"
31 #include "SMESHDS_Group.hxx"
32 #include "SMESHDS_Hypothesis.hxx"
33 #include "SMESH_Algo.hxx"
34 #include "SMESH_ComputeError.hxx"
35 #include "SMESH_ControlsDef.hxx"
36 #include "SMESH_Gen.hxx"
37 #include "SMESH_Group.hxx"
38 #include "SMESH_HypoFilter.hxx"
39 #include "SMESH_Mesh.hxx"
40 #include "SMESH_MeshAlgos.hxx"
41 #include "SMESH_MesherHelper.hxx"
42 #include "SMESH_ProxyMesh.hxx"
43 #include "SMESH_subMesh.hxx"
44 #include "SMESH_subMeshEventListener.hxx"
45 #include "StdMeshers_FaceSide.hxx"
47 #include <BRepAdaptor_Curve2d.hxx>
48 #include <BRepAdaptor_Surface.hxx>
49 #include <BRepLProp_SLProps.hxx>
50 #include <BRep_Tool.hxx>
51 #include <Bnd_B2d.hxx>
52 #include <Bnd_B3d.hxx>
54 #include <GCPnts_AbscissaPoint.hxx>
55 #include <Geom2d_Circle.hxx>
56 #include <Geom2d_Line.hxx>
57 #include <Geom2d_TrimmedCurve.hxx>
58 #include <GeomAdaptor_Curve.hxx>
59 #include <GeomLib.hxx>
60 #include <Geom_Circle.hxx>
61 #include <Geom_Curve.hxx>
62 #include <Geom_Line.hxx>
63 #include <Geom_TrimmedCurve.hxx>
64 #include <Precision.hxx>
65 #include <Standard_ErrorHandler.hxx>
66 #include <Standard_Failure.hxx>
67 #include <TColStd_Array1OfReal.hxx>
69 #include <TopExp_Explorer.hxx>
70 #include <TopTools_IndexedMapOfShape.hxx>
71 #include <TopTools_ListOfShape.hxx>
72 #include <TopTools_MapOfShape.hxx>
74 #include <TopoDS_Edge.hxx>
75 #include <TopoDS_Face.hxx>
76 #include <TopoDS_Vertex.hxx>
90 //================================================================================
95 enum UIndex { U_TGT = 1, U_SRC, LEN_TGT };
98 * \brief SMESH_ProxyMesh computed by _ViscousBuilder for a SOLID.
99 * It is stored in a SMESH_subMesh of the SOLID as SMESH_subMeshEventListenerData
101 struct _MeshOfSolid : public SMESH_ProxyMesh,
102 public SMESH_subMeshEventListenerData
104 bool _n2nMapComputed;
106 _MeshOfSolid( SMESH_Mesh* mesh)
107 :SMESH_subMeshEventListenerData( /*isDeletable=*/true),_n2nMapComputed(false)
109 SMESH_ProxyMesh::setMesh( *mesh );
112 // returns submesh for a geom face
113 SMESH_ProxyMesh::SubMesh* getFaceSubM(const TopoDS_Face& F, bool create=false)
115 TGeomID i = SMESH_ProxyMesh::shapeIndex(F);
116 return create ? SMESH_ProxyMesh::getProxySubMesh(i) : findProxySubMesh(i);
118 void setNode2Node(const SMDS_MeshNode* srcNode,
119 const SMDS_MeshNode* proxyNode,
120 const SMESH_ProxyMesh::SubMesh* subMesh)
122 SMESH_ProxyMesh::setNode2Node( srcNode,proxyNode,subMesh);
125 //--------------------------------------------------------------------------------
127 * \brief Listener of events of 3D sub-meshes computed with viscous layers.
128 * It is used to clear an inferior dim sub-meshes modified by viscous layers
130 class _ShrinkShapeListener : SMESH_subMeshEventListener
132 _ShrinkShapeListener()
133 : SMESH_subMeshEventListener(/*isDeletable=*/false,
134 "StdMeshers_ViscousLayers::_ShrinkShapeListener") {}
136 static SMESH_subMeshEventListener* Get() { static _ShrinkShapeListener l; return &l; }
137 virtual void ProcessEvent(const int event,
139 SMESH_subMesh* solidSM,
140 SMESH_subMeshEventListenerData* data,
141 const SMESH_Hypothesis* hyp)
143 if ( SMESH_subMesh::COMPUTE_EVENT == eventType && solidSM->IsEmpty() && data )
145 SMESH_subMeshEventListener::ProcessEvent(event,eventType,solidSM,data,hyp);
149 //--------------------------------------------------------------------------------
151 * \brief Listener of events of 3D sub-meshes computed with viscous layers.
152 * It is used to store data computed by _ViscousBuilder for a sub-mesh and to
153 * delete the data as soon as it has been used
155 class _ViscousListener : SMESH_subMeshEventListener
158 SMESH_subMeshEventListener(/*isDeletable=*/false,
159 "StdMeshers_ViscousLayers::_ViscousListener") {}
160 static SMESH_subMeshEventListener* Get() { static _ViscousListener l; return &l; }
162 virtual void ProcessEvent(const int event,
164 SMESH_subMesh* subMesh,
165 SMESH_subMeshEventListenerData* data,
166 const SMESH_Hypothesis* hyp)
168 if ( SMESH_subMesh::COMPUTE_EVENT == eventType )
170 // delete SMESH_ProxyMesh containing temporary faces
171 subMesh->DeleteEventListener( this );
174 // Finds or creates proxy mesh of the solid
175 static _MeshOfSolid* GetSolidMesh(SMESH_Mesh* mesh,
176 const TopoDS_Shape& solid,
179 if ( !mesh ) return 0;
180 SMESH_subMesh* sm = mesh->GetSubMesh(solid);
181 _MeshOfSolid* data = (_MeshOfSolid*) sm->GetEventListenerData( Get() );
182 if ( !data && toCreate )
184 data = new _MeshOfSolid(mesh);
185 data->mySubMeshes.push_back( sm ); // to find SOLID by _MeshOfSolid
186 sm->SetEventListener( Get(), data, sm );
190 // Removes proxy mesh of the solid
191 static void RemoveSolidMesh(SMESH_Mesh* mesh, const TopoDS_Shape& solid)
193 mesh->GetSubMesh(solid)->DeleteEventListener( _ViscousListener::Get() );
197 //================================================================================
199 * \brief sets a sub-mesh event listener to clear sub-meshes of sub-shapes of
200 * the main shape when sub-mesh of the main shape is cleared,
201 * for example to clear sub-meshes of FACEs when sub-mesh of a SOLID
204 //================================================================================
206 void ToClearSubWithMain( SMESH_subMesh* sub, const TopoDS_Shape& main)
208 SMESH_subMesh* mainSM = sub->GetFather()->GetSubMesh( main );
209 SMESH_subMeshEventListenerData* data =
210 mainSM->GetEventListenerData( _ShrinkShapeListener::Get());
213 if ( find( data->mySubMeshes.begin(), data->mySubMeshes.end(), sub ) ==
214 data->mySubMeshes.end())
215 data->mySubMeshes.push_back( sub );
219 data = SMESH_subMeshEventListenerData::MakeData( /*dependent=*/sub );
220 sub->SetEventListener( _ShrinkShapeListener::Get(), data, /*whereToListenTo=*/mainSM );
223 //--------------------------------------------------------------------------------
225 * \brief Simplex (triangle or tetrahedron) based on 1 (tria) or 2 (tet) nodes of
226 * _LayerEdge and 2 nodes of the mesh surface beening smoothed.
227 * The class is used to check validity of face or volumes around a smoothed node;
228 * it stores only 2 nodes as the other nodes are stored by _LayerEdge.
232 const SMDS_MeshNode *_nPrev, *_nNext; // nodes on a smoothed mesh surface
233 const SMDS_MeshNode *_nOpp; // in 2D case, a node opposite to a smoothed node in QUAD
234 _Simplex(const SMDS_MeshNode* nPrev=0,
235 const SMDS_MeshNode* nNext=0,
236 const SMDS_MeshNode* nOpp=0)
237 : _nPrev(nPrev), _nNext(nNext), _nOpp(nOpp) {}
238 bool IsForward(const SMDS_MeshNode* nSrc, const gp_XYZ* pntTgt) const
240 const double M[3][3] =
241 {{ _nNext->X() - nSrc->X(), _nNext->Y() - nSrc->Y(), _nNext->Z() - nSrc->Z() },
242 { pntTgt->X() - nSrc->X(), pntTgt->Y() - nSrc->Y(), pntTgt->Z() - nSrc->Z() },
243 { _nPrev->X() - nSrc->X(), _nPrev->Y() - nSrc->Y(), _nPrev->Z() - nSrc->Z() }};
244 double determinant = ( + M[0][0]*M[1][1]*M[2][2]
245 + M[0][1]*M[1][2]*M[2][0]
246 + M[0][2]*M[1][0]*M[2][1]
247 - M[0][0]*M[1][2]*M[2][1]
248 - M[0][1]*M[1][0]*M[2][2]
249 - M[0][2]*M[1][1]*M[2][0]);
250 return determinant > 1e-100;
252 bool IsForward(const gp_XY& tgtUV,
253 const SMDS_MeshNode* smoothedNode,
254 const TopoDS_Face& face,
255 SMESH_MesherHelper& helper,
256 const double refSign) const
258 gp_XY prevUV = helper.GetNodeUV( face, _nPrev, smoothedNode );
259 gp_XY nextUV = helper.GetNodeUV( face, _nNext, smoothedNode );
260 gp_Vec2d v1( tgtUV, prevUV ), v2( tgtUV, nextUV );
262 return d*refSign > 1e-100;
264 bool IsNeighbour(const _Simplex& other) const
266 return _nPrev == other._nNext || _nNext == other._nPrev;
269 //--------------------------------------------------------------------------------
271 * Structure used to take into account surface curvature while smoothing
276 double _k; // factor to correct node smoothed position
277 double _h2lenRatio; // avgNormProj / (2*avgDist)
279 static _Curvature* New( double avgNormProj, double avgDist )
282 if ( fabs( avgNormProj / avgDist ) > 1./200 )
285 c->_r = avgDist * avgDist / avgNormProj;
286 c->_k = avgDist * avgDist / c->_r / c->_r;
287 c->_k *= ( c->_r < 0 ? 1/1.1 : 1.1 ); // not to be too restrictive
288 c->_h2lenRatio = avgNormProj / ( avgDist + avgDist );
292 double lenDelta(double len) const { return _k * ( _r + len ); }
293 double lenDeltaByDist(double dist) const { return dist * _h2lenRatio; }
296 //--------------------------------------------------------------------------------
298 * Structure used to smooth a _LayerEdge (master) based on an EDGE.
302 // target nodes of 2 neighbour _LayerEdge's based on the same EDGE
303 const SMDS_MeshNode* _nodes[2];
304 // vectors from source nodes of 2 _LayerEdge's to the source node of master _LayerEdge
306 double _wgt[2]; // weights of _nodes
307 _LayerEdge* _edges[2];
309 // normal to plane passing through _LayerEdge._normal and tangent of EDGE
312 _2NearEdges() { _nodes[0]=_nodes[1]=0; _plnNorm = 0; }
314 std::swap( _nodes[0], _nodes[1] );
315 std::swap( _wgt[0], _wgt[1] );
318 //--------------------------------------------------------------------------------
320 * \brief Edge normal to surface, connecting a node on solid surface (_nodes[0])
321 * and a node of the most internal layer (_nodes.back())
325 vector< const SMDS_MeshNode*> _nodes;
327 gp_XYZ _normal; // to solid surface
328 vector<gp_XYZ> _pos; // points computed during inflation
329 double _len; // length achived with the last step
330 double _cosin; // of angle (_normal ^ surface)
331 double _lenFactor; // to compute _len taking _cosin into account
333 // face or edge w/o layer along or near which _LayerEdge is inflated
335 // simplices connected to the source node (_nodes[0]);
336 // used for smoothing and quality check of _LayerEdge's based on the FACE
337 vector<_Simplex> _simplices;
338 // data for smoothing of _LayerEdge's based on the EDGE
339 _2NearEdges* _2neibors;
341 _Curvature* _curvature;
342 // TODO:: detele _Curvature, _plnNorm
344 void SetNewLength( double len, SMESH_MesherHelper& helper );
345 bool SetNewLength2d( Handle(Geom_Surface)& surface,
346 const TopoDS_Face& F,
347 SMESH_MesherHelper& helper );
348 void SetDataByNeighbors( const SMDS_MeshNode* n1,
349 const SMDS_MeshNode* n2,
350 SMESH_MesherHelper& helper);
351 void InvalidateStep( int curStep );
352 bool Smooth(int& badNb);
353 bool SmoothOnEdge(Handle(Geom_Surface)& surface,
354 const TopoDS_Face& F,
355 SMESH_MesherHelper& helper);
356 bool FindIntersection( SMESH_ElementSearcher& searcher,
358 const double& epsilon,
359 const SMDS_MeshElement** face = 0);
360 bool SegTriaInter( const gp_Ax1& lastSegment,
361 const SMDS_MeshNode* n0,
362 const SMDS_MeshNode* n1,
363 const SMDS_MeshNode* n2,
365 const double& epsilon) const;
366 gp_Ax1 LastSegment(double& segLen) const;
367 bool IsOnEdge() const { return _2neibors; }
368 void Copy( _LayerEdge& other, SMESH_MesherHelper& helper );
369 void SetCosin( double cosin );
373 bool operator () (const _LayerEdge* e1, const _LayerEdge* e2) const
375 const bool cmpNodes = ( e1 && e2 && e1->_nodes.size() && e2->_nodes.size() );
376 return cmpNodes ? ( e1->_nodes[0]->GetID() < e2->_nodes[0]->GetID()) : ( e1 < e2 );
379 //--------------------------------------------------------------------------------
381 typedef map< const SMDS_MeshNode*, _LayerEdge*, TIDCompare > TNode2Edge;
383 //--------------------------------------------------------------------------------
385 * \brief Data of a SOLID
390 const StdMeshers_ViscousLayers* _hyp;
391 TopoDS_Shape _hypShape;
392 _MeshOfSolid* _proxyMesh;
393 set<TGeomID> _reversedFaceIds;
394 set<TGeomID> _ignoreFaceIds;
396 double _stepSize, _stepSizeCoeff;
397 const SMDS_MeshNode* _stepSizeNodes[2];
400 // edges of _n2eMap. We keep same data in two containers because
401 // iteration over the map is 5 time longer than over the vector
402 vector< _LayerEdge* > _edges;
403 // edges on EDGE's with null _sWOL, whose _simplices are used to stop inflation
404 vector< _LayerEdge* > _simplexTestEdges;
406 // key: an id of shape (EDGE or VERTEX) shared by a FACE with
407 // layers and a FACE w/o layers
408 // value: the shape (FACE or EDGE) to shrink mesh on.
409 // _LayerEdge's basing on nodes on key shape are inflated along the value shape
410 map< TGeomID, TopoDS_Shape > _shrinkShape2Shape;
412 // FACE's WOL, srink on which is forbiden due to algo on the adjacent SOLID
413 set< TGeomID > _noShrinkFaces;
415 // <EDGE to smooth on> to <it's curve>
416 map< TGeomID,Handle(Geom_Curve)> _edge2curve;
418 // end indices in _edges of _LayerEdge on one shape to smooth
419 vector< int > _endEdgeToSmooth;
421 double _epsilon; // precision for SegTriaInter()
423 int _index; // for debug
425 _SolidData(const TopoDS_Shape& s=TopoDS_Shape(),
426 const StdMeshers_ViscousLayers* h=0,
427 const TopoDS_Shape& hs=TopoDS_Shape(),
429 :_solid(s), _hyp(h), _hypShape(hs), _proxyMesh(m) {}
432 Handle(Geom_Curve) CurveForSmooth( const TopoDS_Edge& E,
435 Handle(Geom_Surface)& surface,
436 const TopoDS_Face& F,
437 SMESH_MesherHelper& helper);
439 //--------------------------------------------------------------------------------
441 * \brief Data of node on a shrinked FACE
445 const SMDS_MeshNode* _node;
446 //vector<const SMDS_MeshNode*> _nodesAround;
447 vector<_Simplex> _simplices; // for quality check
449 enum SmoothType { LAPLACIAN, CENTROIDAL, ANGULAR, TFI };
451 bool Smooth(int& badNb,
452 Handle(Geom_Surface)& surface,
453 SMESH_MesherHelper& helper,
454 const double refSign,
458 gp_XY computeAngularPos(vector<gp_XY>& uv,
459 const gp_XY& uvToFix,
460 const double refSign );
462 //--------------------------------------------------------------------------------
464 * \brief Builder of viscous layers
466 class _ViscousBuilder
471 SMESH_ComputeErrorPtr Compute(SMESH_Mesh& mesh,
472 const TopoDS_Shape& shape);
474 // restore event listeners used to clear an inferior dim sub-mesh modified by viscous layers
475 void RestoreListeners();
477 // computes SMESH_ProxyMesh::SubMesh::_n2n;
478 bool MakeN2NMap( _MeshOfSolid* pm );
482 bool findSolidsWithLayers();
483 bool findFacesWithLayers();
484 bool makeLayer(_SolidData& data);
485 bool setEdgeData(_LayerEdge& edge, const set<TGeomID>& subIds,
486 SMESH_MesherHelper& helper, _SolidData& data);
487 gp_XYZ getWeigthedNormal( const SMDS_MeshNode* n,
488 std::pair< TGeomID, gp_XYZ > fId2Normal[],
490 bool findNeiborsOnEdge(const _LayerEdge* edge,
491 const SMDS_MeshNode*& n1,
492 const SMDS_MeshNode*& n2,
494 void getSimplices( const SMDS_MeshNode* node, vector<_Simplex>& simplices,
495 const set<TGeomID>& ingnoreShapes,
496 const _SolidData* dataToCheckOri = 0,
497 const bool toSort = false);
498 void findSimplexTestEdges( _SolidData& data,
499 vector< vector<_LayerEdge*> >& edgesByGeom);
500 bool sortEdges( _SolidData& data,
501 vector< vector<_LayerEdge*> >& edgesByGeom);
502 void limitStepSize( _SolidData& data,
503 const SMDS_MeshElement* face,
505 void limitStepSize( _SolidData& data, const double minSize);
506 bool inflate(_SolidData& data);
507 bool smoothAndCheck(_SolidData& data, const int nbSteps, double & distToIntersection);
508 bool smoothAnalyticEdge( _SolidData& data,
511 Handle(Geom_Surface)& surface,
512 const TopoDS_Face& F,
513 SMESH_MesherHelper& helper);
514 bool updateNormals( _SolidData& data, SMESH_MesherHelper& helper );
515 bool refine(_SolidData& data);
517 bool prepareEdgeToShrink( _LayerEdge& edge, const TopoDS_Face& F,
518 SMESH_MesherHelper& helper,
519 const SMESHDS_SubMesh* faceSubMesh );
520 void fixBadFaces(const TopoDS_Face& F,
521 SMESH_MesherHelper& helper,
524 set<const SMDS_MeshNode*> * involvedNodes=NULL);
525 bool addBoundaryElements();
527 bool error( const string& text, int solidID=-1 );
528 SMESHDS_Mesh* getMeshDS() { return _mesh->GetMeshDS(); }
531 void makeGroupOfLE();
534 SMESH_ComputeErrorPtr _error;
536 vector< _SolidData > _sdVec;
539 //--------------------------------------------------------------------------------
541 * \brief Shrinker of nodes on the EDGE
545 vector<double> _initU;
546 vector<double> _normPar;
547 vector<const SMDS_MeshNode*> _nodes;
548 const _LayerEdge* _edges[2];
551 void AddEdge( const _LayerEdge* e, SMESH_MesherHelper& helper );
552 void Compute(bool set3D, SMESH_MesherHelper& helper);
553 void RestoreParams();
554 void SwapSrcTgtNodes(SMESHDS_Mesh* mesh);
556 //--------------------------------------------------------------------------------
558 * \brief Class of temporary mesh face.
559 * We can't use SMDS_FaceOfNodes since it's impossible to set it's ID which is
560 * needed because SMESH_ElementSearcher internaly uses set of elements sorted by ID
562 struct TmpMeshFace : public SMDS_MeshElement
564 vector<const SMDS_MeshNode* > _nn;
565 TmpMeshFace( const vector<const SMDS_MeshNode*>& nodes, int id):
566 SMDS_MeshElement(id), _nn(nodes) {}
567 virtual const SMDS_MeshNode* GetNode(const int ind) const { return _nn[ind]; }
568 virtual SMDSAbs_ElementType GetType() const { return SMDSAbs_Face; }
569 virtual vtkIdType GetVtkType() const { return -1; }
570 virtual SMDSAbs_EntityType GetEntityType() const { return SMDSEntity_Last; }
571 virtual SMDSAbs_GeometryType GetGeomType() const { return SMDSGeom_TRIANGLE; }
572 virtual SMDS_ElemIteratorPtr elementsIterator(SMDSAbs_ElementType) const
573 { return SMDS_ElemIteratorPtr( new SMDS_NodeVectorElemIterator( _nn.begin(), _nn.end()));}
575 //--------------------------------------------------------------------------------
577 * \brief Class of temporary mesh face storing _LayerEdge it's based on
579 struct TmpMeshFaceOnEdge : public TmpMeshFace
581 _LayerEdge *_le1, *_le2;
582 TmpMeshFaceOnEdge( _LayerEdge* le1, _LayerEdge* le2, int ID ):
583 TmpMeshFace( vector<const SMDS_MeshNode*>(4), ID ), _le1(le1), _le2(le2)
585 _nn[0]=_le1->_nodes[0];
586 _nn[1]=_le1->_nodes.back();
587 _nn[2]=_le2->_nodes.back();
588 _nn[3]=_le2->_nodes[0];
591 //--------------------------------------------------------------------------------
593 * \brief Retriever of node coordinates either directly of from a surface by node UV.
594 * \warning Location of a surface is ignored
596 struct NodeCoordHelper
598 SMESH_MesherHelper& _helper;
599 const TopoDS_Face& _face;
600 Handle(Geom_Surface) _surface;
601 gp_XYZ (NodeCoordHelper::* _fun)(const SMDS_MeshNode* n) const;
603 NodeCoordHelper(const TopoDS_Face& F, SMESH_MesherHelper& helper, bool is2D)
604 : _helper( helper ), _face( F )
609 _surface = BRep_Tool::Surface( _face, loc );
611 if ( _surface.IsNull() )
612 _fun = & NodeCoordHelper::direct;
614 _fun = & NodeCoordHelper::byUV;
616 gp_XYZ operator()(const SMDS_MeshNode* n) const { return (this->*_fun)( n ); }
619 gp_XYZ direct(const SMDS_MeshNode* n) const
621 return SMESH_TNodeXYZ( n );
623 gp_XYZ byUV (const SMDS_MeshNode* n) const
625 gp_XY uv = _helper.GetNodeUV( _face, n );
626 return _surface->Value( uv.X(), uv.Y() ).XYZ();
629 } // namespace VISCOUS_3D
631 //================================================================================
632 // StdMeshers_ViscousLayers hypothesis
634 StdMeshers_ViscousLayers::StdMeshers_ViscousLayers(int hypId, int studyId, SMESH_Gen* gen)
635 :SMESH_Hypothesis(hypId, studyId, gen),
636 _isToIgnoreShapes(1), _nbLayers(1), _thickness(1), _stretchFactor(1)
638 _name = StdMeshers_ViscousLayers::GetHypType();
639 _param_algo_dim = -3; // auxiliary hyp used by 3D algos
640 } // --------------------------------------------------------------------------------
641 void StdMeshers_ViscousLayers::SetBndShapes(const std::vector<int>& faceIds, bool toIgnore)
643 if ( faceIds != _shapeIds )
644 _shapeIds = faceIds, NotifySubMeshesHypothesisModification();
645 if ( _isToIgnoreShapes != toIgnore )
646 _isToIgnoreShapes = toIgnore, NotifySubMeshesHypothesisModification();
647 } // --------------------------------------------------------------------------------
648 void StdMeshers_ViscousLayers::SetTotalThickness(double thickness)
650 if ( thickness != _thickness )
651 _thickness = thickness, NotifySubMeshesHypothesisModification();
652 } // --------------------------------------------------------------------------------
653 void StdMeshers_ViscousLayers::SetNumberLayers(int nb)
655 if ( _nbLayers != nb )
656 _nbLayers = nb, NotifySubMeshesHypothesisModification();
657 } // --------------------------------------------------------------------------------
658 void StdMeshers_ViscousLayers::SetStretchFactor(double factor)
660 if ( _stretchFactor != factor )
661 _stretchFactor = factor, NotifySubMeshesHypothesisModification();
662 } // --------------------------------------------------------------------------------
664 StdMeshers_ViscousLayers::Compute(SMESH_Mesh& theMesh,
665 const TopoDS_Shape& theShape,
666 const bool toMakeN2NMap) const
668 using namespace VISCOUS_3D;
669 _ViscousBuilder bulder;
670 SMESH_ComputeErrorPtr err = bulder.Compute( theMesh, theShape );
671 if ( err && !err->IsOK() )
672 return SMESH_ProxyMesh::Ptr();
674 vector<SMESH_ProxyMesh::Ptr> components;
675 TopExp_Explorer exp( theShape, TopAbs_SOLID );
676 for ( ; exp.More(); exp.Next() )
678 if ( _MeshOfSolid* pm =
679 _ViscousListener::GetSolidMesh( &theMesh, exp.Current(), /*toCreate=*/false))
681 if ( toMakeN2NMap && !pm->_n2nMapComputed )
682 if ( !bulder.MakeN2NMap( pm ))
683 return SMESH_ProxyMesh::Ptr();
684 components.push_back( SMESH_ProxyMesh::Ptr( pm ));
685 pm->myIsDeletable = false; // it will de deleted by boost::shared_ptr
687 _ViscousListener::RemoveSolidMesh ( &theMesh, exp.Current() );
689 switch ( components.size() )
693 case 1: return components[0];
695 default: return SMESH_ProxyMesh::Ptr( new SMESH_ProxyMesh( components ));
697 return SMESH_ProxyMesh::Ptr();
698 } // --------------------------------------------------------------------------------
699 std::ostream & StdMeshers_ViscousLayers::SaveTo(std::ostream & save)
701 save << " " << _nbLayers
703 << " " << _stretchFactor
704 << " " << _shapeIds.size();
705 for ( size_t i = 0; i < _shapeIds.size(); ++i )
706 save << " " << _shapeIds[i];
707 save << " " << !_isToIgnoreShapes; // negate to keep the behavior in old studies.
709 } // --------------------------------------------------------------------------------
710 std::istream & StdMeshers_ViscousLayers::LoadFrom(std::istream & load)
712 int nbFaces, faceID, shapeToTreat;
713 load >> _nbLayers >> _thickness >> _stretchFactor >> nbFaces;
714 while ( _shapeIds.size() < nbFaces && load >> faceID )
715 _shapeIds.push_back( faceID );
716 if ( load >> shapeToTreat )
717 _isToIgnoreShapes = !shapeToTreat;
719 _isToIgnoreShapes = true; // old behavior
721 } // --------------------------------------------------------------------------------
722 bool StdMeshers_ViscousLayers::SetParametersByMesh(const SMESH_Mesh* theMesh,
723 const TopoDS_Shape& theShape)
728 // END StdMeshers_ViscousLayers hypothesis
729 //================================================================================
733 gp_XYZ getEdgeDir( const TopoDS_Edge& E, const TopoDS_Vertex& fromV )
737 Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
738 gp_Pnt p = BRep_Tool::Pnt( fromV );
739 double distF = p.SquareDistance( c->Value( f ));
740 double distL = p.SquareDistance( c->Value( l ));
741 c->D1(( distF < distL ? f : l), p, dir );
742 if ( distL < distF ) dir.Reverse();
745 //--------------------------------------------------------------------------------
746 gp_XYZ getEdgeDir( const TopoDS_Edge& E, const SMDS_MeshNode* atNode,
747 SMESH_MesherHelper& helper)
750 double f,l; gp_Pnt p;
751 Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
752 double u = helper.GetNodeU( E, atNode );
756 //--------------------------------------------------------------------------------
757 gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Edge& fromE,
758 const SMDS_MeshNode* node, SMESH_MesherHelper& helper, bool& ok)
760 gp_XY uv = helper.GetNodeUV( F, node, 0, &ok );
761 Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
762 gp_Pnt p; gp_Vec du, dv, norm;
763 surface->D1( uv.X(),uv.Y(), p, du,dv );
767 Handle(Geom_Curve) c = BRep_Tool::Curve( fromE, f, l );
768 double u = helper.GetNodeU( fromE, node, 0, &ok );
770 TopAbs_Orientation o = helper.GetSubShapeOri( F.Oriented(TopAbs_FORWARD), fromE);
771 if ( o == TopAbs_REVERSED )
774 gp_Vec dir = norm ^ du;
776 if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX &&
777 helper.IsClosedEdge( fromE ))
779 if ( fabs(u-f) < fabs(u-l )) c->D1( l, p, dv );
780 else c->D1( f, p, dv );
781 if ( o == TopAbs_REVERSED )
783 gp_Vec dir2 = norm ^ dv;
784 dir = dir.Normalized() + dir2.Normalized();
788 //--------------------------------------------------------------------------------
789 gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Vertex& fromV,
790 const SMDS_MeshNode* node, SMESH_MesherHelper& helper,
791 bool& ok, double* cosin=0)
793 double f,l; TopLoc_Location loc;
794 vector< TopoDS_Edge > edges; // sharing a vertex
795 PShapeIteratorPtr eIt = helper.GetAncestors( fromV, *helper.GetMesh(), TopAbs_EDGE);
798 const TopoDS_Edge* e = static_cast<const TopoDS_Edge*>( eIt->next() );
799 if ( helper.IsSubShape( *e, F ) && !BRep_Tool::Curve( *e, loc,f,l).IsNull() )
800 edges.push_back( *e );
803 if ( !( ok = ( edges.size() > 0 ))) return dir;
804 // get average dir of edges going fromV
806 //if ( edges.size() > 1 )
807 for ( size_t i = 0; i < edges.size(); ++i )
809 edgeDir = getEdgeDir( edges[i], fromV );
810 double size2 = edgeDir.SquareModulus();
811 if ( size2 > numeric_limits<double>::min() )
812 edgeDir /= sqrt( size2 );
817 gp_XYZ fromEdgeDir = getFaceDir( F, edges[0], node, helper, ok );
819 if ( edges.size() == 1 )
821 else if ( dir.SquareModulus() < 0.1 ) // ~< 20 degrees
822 dir = fromEdgeDir.Normalized() + getFaceDir( F, edges[1], node, helper, ok ).Normalized();
823 else if ( dir * fromEdgeDir < 0 )
826 catch ( Standard_Failure )
832 //dir /= edges.size();
834 double angle = gp_Vec( edgeDir ).Angle( dir );
835 *cosin = cos( angle );
840 //================================================================================
842 * \brief Returns true if a FACE is bound by a concave EDGE
844 //================================================================================
846 bool isConcave( const TopoDS_Face& F, SMESH_MesherHelper& helper )
848 // if ( helper.Count( F, TopAbs_WIRE, /*useMap=*/false) > 1 )
852 TopExp_Explorer eExp( F.Oriented( TopAbs_FORWARD ), TopAbs_EDGE );
853 for ( ; eExp.More(); eExp.Next() )
855 const TopoDS_Edge& E = TopoDS::Edge( eExp.Current() );
856 if ( SMESH_Algo::isDegenerated( E )) continue;
857 // check if 2D curve is concave
858 BRepAdaptor_Curve2d curve( E, F );
859 const int nbIntervals = curve.NbIntervals( GeomAbs_C2 );
860 TColStd_Array1OfReal intervals(1, nbIntervals + 1 );
861 curve.Intervals( intervals, GeomAbs_C2 );
862 bool isConvex = true;
863 for ( int i = 1; i <= nbIntervals && isConvex; ++i )
865 double u1 = intervals( i );
866 double u2 = intervals( i+1 );
867 curve.D2( 0.5*( u1+u2 ), p, drv1, drv2 );
868 double cross = drv2 ^ drv1;
869 if ( E.Orientation() == TopAbs_REVERSED )
871 isConvex = ( cross > 0.1 ); //-1e-9 );
873 // check if concavity is strong enough to care about it
874 //const double maxAngle = 5 * Standard_PI180;
877 //cout << "Concave FACE " << helper.GetMeshDS()->ShapeToIndex( F ) << endl;
879 // map< double, const SMDS_MeshNode* > u2nodes;
880 // if ( !SMESH_Algo::GetSortedNodesOnEdge( helper.GetMeshDS(), E,
881 // /*ignoreMedium=*/true, u2nodes))
883 // map< double, const SMDS_MeshNode* >::iterator u2n = u2nodes.begin();
884 // gp_Pnt2d uvPrev = helper.GetNodeUV( F, u2n->second );
885 // double uPrev = u2n->first;
886 // for ( ++u2n; u2n != u2nodes.end(); ++u2n )
888 // gp_Pnt2d uv = helper.GetNodeUV( F, u2n->second );
889 // gp_Vec2d segmentDir( uvPrev, uv );
890 // curve.D1( uPrev, p, drv1 );
892 // if ( fabs( segmentDir.Angle( drv1 )) > maxAngle )
897 // uPrev = u2n->first;
901 // check angles at VERTEXes
903 TSideVector wires = StdMeshers_FaceSide::GetFaceWires( F, *helper.GetMesh(), 0, error );
904 for ( size_t iW = 0; iW < wires.size(); ++iW )
906 const int nbEdges = wires[iW]->NbEdges();
907 if ( nbEdges < 2 && SMESH_Algo::isDegenerated( wires[iW]->Edge(0)))
909 for ( int iE1 = 0; iE1 < nbEdges; ++iE1 )
911 if ( SMESH_Algo::isDegenerated( wires[iW]->Edge( iE1 ))) continue;
912 int iE2 = ( iE1 + 1 ) % nbEdges;
913 while ( SMESH_Algo::isDegenerated( wires[iW]->Edge( iE2 )))
914 iE2 = ( iE2 + 1 ) % nbEdges;
915 double angle = helper.GetAngle( wires[iW]->Edge( iE1 ),
916 wires[iW]->Edge( iE2 ), F );
917 if ( angle < -5. * M_PI / 180. )
923 //--------------------------------------------------------------------------------
924 // DEBUG. Dump intermediate node positions into a python script
929 const char* fname = "/tmp/viscous.py";
930 cout << "execfile('"<<fname<<"')"<<endl;
931 py = new ofstream(fname);
932 *py << "import SMESH" << endl
933 << "from salome.smesh import smeshBuilder" << endl
934 << "smesh = smeshBuilder.New(salome.myStudy)" << endl
935 << "meshSO = smesh.GetCurrentStudy().FindObjectID('0:1:2:3')" << endl
936 << "mesh = smesh.Mesh( meshSO.GetObject() )"<<endl;
940 *py << "mesh.MakeGroup('Viscous Prisms',SMESH.VOLUME,SMESH.FT_ElemGeomType,'=',SMESH.Geom_PENTA)"<<endl;
943 ~PyDump() { Finish(); }
945 #define dumpFunction(f) { _dumpFunction(f, __LINE__);}
946 #define dumpMove(n) { _dumpMove(n, __LINE__);}
947 #define dumpCmd(txt) { _dumpCmd(txt, __LINE__);}
948 void _dumpFunction(const string& fun, int ln)
949 { if (py) *py<< "def "<<fun<<"(): # "<< ln <<endl; cout<<fun<<"()"<<endl;}
950 void _dumpMove(const SMDS_MeshNode* n, int ln)
951 { if (py) *py<< " mesh.MoveNode( "<<n->GetID()<< ", "<< n->X()
952 << ", "<<n->Y()<<", "<< n->Z()<< ")\t\t # "<< ln <<endl; }
953 void _dumpCmd(const string& txt, int ln)
954 { if (py) *py<< " "<<txt<<" # "<< ln <<endl; }
955 void dumpFunctionEnd()
956 { if (py) *py<< " return"<< endl; }
957 void dumpChangeNodes( const SMDS_MeshElement* f )
958 { if (py) { *py<< " mesh.ChangeElemNodes( " << f->GetID()<<", [";
959 for ( int i=1; i < f->NbNodes(); ++i ) *py << f->GetNode(i-1)->GetID()<<", ";
960 *py << f->GetNode( f->NbNodes()-1 )->GetID() << " ])"<< endl; }}
962 struct PyDump { void Finish() {} };
963 #define dumpFunction(f) f
966 #define dumpFunctionEnd()
967 #define dumpChangeNodes(f)
971 using namespace VISCOUS_3D;
973 //================================================================================
975 * \brief Constructor of _ViscousBuilder
977 //================================================================================
979 _ViscousBuilder::_ViscousBuilder()
981 _error = SMESH_ComputeError::New(COMPERR_OK);
985 //================================================================================
987 * \brief Stores error description and returns false
989 //================================================================================
991 bool _ViscousBuilder::error(const string& text, int solidId )
993 _error->myName = COMPERR_ALGO_FAILED;
994 _error->myComment = string("Viscous layers builder: ") + text;
997 SMESH_subMesh* sm = _mesh->GetSubMeshContaining( solidId );
998 if ( !sm && !_sdVec.empty() )
999 sm = _mesh->GetSubMeshContaining( _sdVec[0]._index );
1000 if ( sm && sm->GetSubShape().ShapeType() == TopAbs_SOLID )
1002 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1003 if ( smError && smError->myAlgo )
1004 _error->myAlgo = smError->myAlgo;
1008 makeGroupOfLE(); // debug
1013 //================================================================================
1015 * \brief At study restoration, restore event listeners used to clear an inferior
1016 * dim sub-mesh modified by viscous layers
1018 //================================================================================
1020 void _ViscousBuilder::RestoreListeners()
1025 //================================================================================
1027 * \brief computes SMESH_ProxyMesh::SubMesh::_n2n
1029 //================================================================================
1031 bool _ViscousBuilder::MakeN2NMap( _MeshOfSolid* pm )
1033 SMESH_subMesh* solidSM = pm->mySubMeshes.front();
1034 TopExp_Explorer fExp( solidSM->GetSubShape(), TopAbs_FACE );
1035 for ( ; fExp.More(); fExp.Next() )
1037 SMESHDS_SubMesh* srcSmDS = pm->GetMeshDS()->MeshElements( fExp.Current() );
1038 const SMESH_ProxyMesh::SubMesh* prxSmDS = pm->GetProxySubMesh( fExp.Current() );
1040 if ( !srcSmDS || !prxSmDS || !srcSmDS->NbElements() || !prxSmDS->NbElements() )
1042 if ( srcSmDS->GetElements()->next() == prxSmDS->GetElements()->next())
1045 if ( srcSmDS->NbElements() != prxSmDS->NbElements() )
1046 return error( "Different nb elements in a source and a proxy sub-mesh", solidSM->GetId());
1048 SMDS_ElemIteratorPtr srcIt = srcSmDS->GetElements();
1049 SMDS_ElemIteratorPtr prxIt = prxSmDS->GetElements();
1050 while( prxIt->more() )
1052 const SMDS_MeshElement* fSrc = srcIt->next();
1053 const SMDS_MeshElement* fPrx = prxIt->next();
1054 if ( fSrc->NbNodes() != fPrx->NbNodes())
1055 return error( "Different elements in a source and a proxy sub-mesh", solidSM->GetId());
1056 for ( int i = 0 ; i < fPrx->NbNodes(); ++i )
1057 pm->setNode2Node( fSrc->GetNode(i), fPrx->GetNode(i), prxSmDS );
1060 pm->_n2nMapComputed = true;
1064 //================================================================================
1066 * \brief Does its job
1068 //================================================================================
1070 SMESH_ComputeErrorPtr _ViscousBuilder::Compute(SMESH_Mesh& theMesh,
1071 const TopoDS_Shape& theShape)
1073 // TODO: set priority of solids during Gen::Compute()
1077 // check if proxy mesh already computed
1078 TopExp_Explorer exp( theShape, TopAbs_SOLID );
1080 return error("No SOLID's in theShape"), _error;
1082 if ( _ViscousListener::GetSolidMesh( _mesh, exp.Current(), /*toCreate=*/false))
1083 return SMESH_ComputeErrorPtr(); // everything already computed
1087 // TODO: ignore already computed SOLIDs
1088 if ( !findSolidsWithLayers())
1091 if ( !findFacesWithLayers() )
1094 for ( size_t i = 0; i < _sdVec.size(); ++i )
1096 if ( ! makeLayer(_sdVec[i]) )
1099 if ( _sdVec[i]._edges.size() == 0 )
1102 if ( ! inflate(_sdVec[i]) )
1105 if ( ! refine(_sdVec[i]) )
1111 addBoundaryElements();
1113 makeGroupOfLE(); // debug
1119 //================================================================================
1121 * \brief Finds SOLIDs to compute using viscous layers. Fills _sdVec
1123 //================================================================================
1125 bool _ViscousBuilder::findSolidsWithLayers()
1128 TopTools_IndexedMapOfShape allSolids;
1129 TopExp::MapShapes( _mesh->GetShapeToMesh(), TopAbs_SOLID, allSolids );
1130 _sdVec.reserve( allSolids.Extent());
1132 SMESH_Gen* gen = _mesh->GetGen();
1133 SMESH_HypoFilter filter;
1134 for ( int i = 1; i <= allSolids.Extent(); ++i )
1136 // find StdMeshers_ViscousLayers hyp assigned to the i-th solid
1137 SMESH_Algo* algo = gen->GetAlgo( *_mesh, allSolids(i) );
1138 if ( !algo ) continue;
1139 // TODO: check if algo is hidden
1140 const list <const SMESHDS_Hypothesis *> & allHyps =
1141 algo->GetUsedHypothesis(*_mesh, allSolids(i), /*ignoreAuxiliary=*/false);
1142 list< const SMESHDS_Hypothesis *>::const_iterator hyp = allHyps.begin();
1143 const StdMeshers_ViscousLayers* viscHyp = 0;
1144 for ( ; hyp != allHyps.end() && !viscHyp; ++hyp )
1145 viscHyp = dynamic_cast<const StdMeshers_ViscousLayers*>( *hyp );
1148 TopoDS_Shape hypShape;
1149 filter.Init( filter.Is( viscHyp ));
1150 _mesh->GetHypothesis( allSolids(i), filter, true, &hypShape );
1152 _MeshOfSolid* proxyMesh = _ViscousListener::GetSolidMesh( _mesh,
1155 _sdVec.push_back( _SolidData( allSolids(i), viscHyp, hypShape, proxyMesh ));
1156 _sdVec.back()._index = getMeshDS()->ShapeToIndex( allSolids(i));
1159 if ( _sdVec.empty() )
1161 ( SMESH_Comment(StdMeshers_ViscousLayers::GetHypType()) << " hypothesis not found",0);
1166 //================================================================================
1170 //================================================================================
1172 bool _ViscousBuilder::findFacesWithLayers()
1174 SMESH_MesherHelper helper( *_mesh );
1175 TopExp_Explorer exp;
1176 TopTools_IndexedMapOfShape solids;
1178 // collect all faces to ignore defined by hyp
1179 for ( size_t i = 0; i < _sdVec.size(); ++i )
1181 solids.Add( _sdVec[i]._solid );
1183 vector<TGeomID> ids = _sdVec[i]._hyp->GetBndShapes();
1184 if ( _sdVec[i]._hyp->IsToIgnoreShapes() ) // FACEs to ignore are given
1186 for ( size_t ii = 0; ii < ids.size(); ++ii )
1188 const TopoDS_Shape& s = getMeshDS()->IndexToShape( ids[ii] );
1189 if ( !s.IsNull() && s.ShapeType() == TopAbs_FACE )
1190 _sdVec[i]._ignoreFaceIds.insert( ids[ii] );
1193 else // FACEs with layers are given
1195 exp.Init( _sdVec[i]._solid, TopAbs_FACE );
1196 for ( ; exp.More(); exp.Next() )
1198 TGeomID faceInd = getMeshDS()->ShapeToIndex( exp.Current() );
1199 if ( find( ids.begin(), ids.end(), faceInd ) == ids.end() )
1200 _sdVec[i]._ignoreFaceIds.insert( faceInd );
1204 // ignore internal FACEs if inlets and outlets are specified
1206 TopTools_IndexedDataMapOfShapeListOfShape solidsOfFace;
1207 if ( _sdVec[i]._hyp->IsToIgnoreShapes() )
1208 TopExp::MapShapesAndAncestors( _sdVec[i]._hypShape,
1209 TopAbs_FACE, TopAbs_SOLID, solidsOfFace);
1211 exp.Init( _sdVec[i]._solid.Oriented( TopAbs_FORWARD ), TopAbs_FACE );
1212 for ( ; exp.More(); exp.Next() )
1214 const TopoDS_Face& face = TopoDS::Face( exp.Current() );
1215 if ( helper.NbAncestors( face, *_mesh, TopAbs_SOLID ) < 2 )
1218 const TGeomID faceInd = getMeshDS()->ShapeToIndex( face );
1219 if ( _sdVec[i]._hyp->IsToIgnoreShapes() )
1221 int nbSolids = solidsOfFace.FindFromKey( face ).Extent();
1223 _sdVec[i]._ignoreFaceIds.insert( faceInd );
1226 if ( helper.IsReversedSubMesh( face ))
1228 _sdVec[i]._reversedFaceIds.insert( faceInd );
1234 // Find faces to shrink mesh on (solution 2 in issue 0020832);
1235 TopTools_IndexedMapOfShape shapes;
1236 for ( size_t i = 0; i < _sdVec.size(); ++i )
1239 TopExp::MapShapes(_sdVec[i]._solid, TopAbs_EDGE, shapes);
1240 for ( int iE = 1; iE <= shapes.Extent(); ++iE )
1242 const TopoDS_Shape& edge = shapes(iE);
1243 // find 2 faces sharing an edge
1245 PShapeIteratorPtr fIt = helper.GetAncestors(edge, *_mesh, TopAbs_FACE);
1246 while ( fIt->more())
1248 const TopoDS_Shape* f = fIt->next();
1249 if ( helper.IsSubShape( *f, _sdVec[i]._solid))
1250 FF[ int( !FF[0].IsNull()) ] = *f;
1252 if( FF[1].IsNull() ) continue; // seam edge can be shared by 1 FACE only
1253 // check presence of layers on them
1255 for ( int j = 0; j < 2; ++j )
1256 ignore[j] = _sdVec[i]._ignoreFaceIds.count ( getMeshDS()->ShapeToIndex( FF[j] ));
1257 if ( ignore[0] == ignore[1] )
1258 continue; // nothing interesting
1259 TopoDS_Shape fWOL = FF[ ignore[0] ? 0 : 1 ];
1260 // check presence of layers on fWOL within an adjacent SOLID
1261 PShapeIteratorPtr sIt = helper.GetAncestors( fWOL, *_mesh, TopAbs_SOLID );
1262 while ( const TopoDS_Shape* solid = sIt->next() )
1263 if ( !solid->IsSame( _sdVec[i]._solid ))
1265 int iSolid = solids.FindIndex( *solid );
1266 int iFace = getMeshDS()->ShapeToIndex( fWOL );
1267 if ( iSolid > 0 && !_sdVec[ iSolid-1 ]._ignoreFaceIds.count( iFace ))
1269 _sdVec[i]._noShrinkFaces.insert( iFace );
1274 if ( !fWOL.IsNull())
1276 TGeomID edgeInd = getMeshDS()->ShapeToIndex( edge );
1277 _sdVec[i]._shrinkShape2Shape.insert( make_pair( edgeInd, fWOL ));
1281 // Exclude from _shrinkShape2Shape FACE's that can't be shrinked since
1282 // the algo of the SOLID sharing the FACE does not support it
1283 set< string > notSupportAlgos; notSupportAlgos.insert("Hexa_3D");
1284 for ( size_t i = 0; i < _sdVec.size(); ++i )
1286 TopTools_MapOfShape noShrinkVertices;
1287 map< TGeomID, TopoDS_Shape >::iterator e2f = _sdVec[i]._shrinkShape2Shape.begin();
1288 for ( ; e2f != _sdVec[i]._shrinkShape2Shape.end(); ++e2f )
1290 const TopoDS_Shape& fWOL = e2f->second;
1291 TGeomID edgeID = e2f->first;
1292 bool notShrinkFace = false;
1293 PShapeIteratorPtr soIt = helper.GetAncestors(fWOL, *_mesh, TopAbs_SOLID);
1294 while ( soIt->more())
1296 const TopoDS_Shape* solid = soIt->next();
1297 if ( _sdVec[i]._solid.IsSame( *solid )) continue;
1298 SMESH_Algo* algo = _mesh->GetGen()->GetAlgo( *_mesh, *solid );
1299 if ( !algo || !notSupportAlgos.count( algo->GetName() )) continue;
1300 notShrinkFace = true;
1301 for ( size_t j = 0; j < _sdVec.size(); ++j )
1303 if ( _sdVec[j]._solid.IsSame( *solid ) )
1304 if ( _sdVec[j]._shrinkShape2Shape.count( edgeID ))
1305 notShrinkFace = false;
1308 if ( notShrinkFace )
1310 _sdVec[i]._noShrinkFaces.insert( getMeshDS()->ShapeToIndex( fWOL ));
1311 for ( TopExp_Explorer vExp( fWOL, TopAbs_VERTEX ); vExp.More(); vExp.Next() )
1312 noShrinkVertices.Add( vExp.Current() );
1315 // erase from _shrinkShape2Shape all srink EDGE's of a SOLID connected
1316 // to the found not shrinked fWOL's
1317 e2f = _sdVec[i]._shrinkShape2Shape.begin();
1318 for ( ; e2f != _sdVec[i]._shrinkShape2Shape.end(); )
1320 TGeomID edgeID = e2f->first;
1321 TopoDS_Vertex VV[2];
1322 TopExp::Vertices( TopoDS::Edge( getMeshDS()->IndexToShape( edgeID )),VV[0],VV[1]);
1323 if ( noShrinkVertices.Contains( VV[0] ) || noShrinkVertices.Contains( VV[1] ))
1325 _sdVec[i]._noShrinkFaces.insert( getMeshDS()->ShapeToIndex( e2f->second ));
1326 _sdVec[i]._shrinkShape2Shape.erase( e2f++ );
1335 // Find the SHAPE along which to inflate _LayerEdge based on VERTEX
1337 for ( size_t i = 0; i < _sdVec.size(); ++i )
1340 TopExp::MapShapes(_sdVec[i]._solid, TopAbs_VERTEX, shapes);
1341 for ( int iV = 1; iV <= shapes.Extent(); ++iV )
1343 const TopoDS_Shape& vertex = shapes(iV);
1344 // find faces WOL sharing the vertex
1345 vector< TopoDS_Shape > facesWOL;
1346 int totalNbFaces = 0;
1347 PShapeIteratorPtr fIt = helper.GetAncestors(vertex, *_mesh, TopAbs_FACE);
1348 while ( fIt->more())
1350 const TopoDS_Shape* f = fIt->next();
1351 if ( helper.IsSubShape( *f, _sdVec[i]._solid ) )
1354 const int fID = getMeshDS()->ShapeToIndex( *f );
1355 if ( _sdVec[i]._ignoreFaceIds.count ( fID ) &&
1356 !_sdVec[i]._noShrinkFaces.count( fID ))
1357 facesWOL.push_back( *f );
1360 if ( facesWOL.size() == totalNbFaces || facesWOL.empty() )
1361 continue; // no layers at this vertex or no WOL
1362 TGeomID vInd = getMeshDS()->ShapeToIndex( vertex );
1363 switch ( facesWOL.size() )
1367 helper.SetSubShape( facesWOL[0] );
1368 if ( helper.IsRealSeam( vInd )) // inflate along a seam edge?
1370 TopoDS_Shape seamEdge;
1371 PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
1372 while ( eIt->more() && seamEdge.IsNull() )
1374 const TopoDS_Shape* e = eIt->next();
1375 if ( helper.IsRealSeam( *e ) )
1378 if ( !seamEdge.IsNull() )
1380 _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, seamEdge ));
1384 _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, facesWOL[0] ));
1389 // find an edge shared by 2 faces
1390 PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
1391 while ( eIt->more())
1393 const TopoDS_Shape* e = eIt->next();
1394 if ( helper.IsSubShape( *e, facesWOL[0]) &&
1395 helper.IsSubShape( *e, facesWOL[1]))
1397 _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, *e )); break;
1403 return error("Not yet supported case", _sdVec[i]._index);
1408 // add FACEs of other SOLIDs to _ignoreFaceIds
1409 for ( size_t i = 0; i < _sdVec.size(); ++i )
1412 TopExp::MapShapes(_sdVec[i]._solid, TopAbs_FACE, shapes);
1414 for ( exp.Init( _mesh->GetShapeToMesh(), TopAbs_FACE ); exp.More(); exp.Next() )
1416 if ( !shapes.Contains( exp.Current() ))
1417 _sdVec[i]._ignoreFaceIds.insert( getMeshDS()->ShapeToIndex( exp.Current() ));
1424 //================================================================================
1426 * \brief Create the inner surface of the viscous layer and prepare data for infation
1428 //================================================================================
1430 bool _ViscousBuilder::makeLayer(_SolidData& data)
1432 // get all sub-shapes to make layers on
1433 set<TGeomID> subIds, faceIds;
1434 subIds = data._noShrinkFaces;
1435 TopExp_Explorer exp( data._solid, TopAbs_FACE );
1436 for ( ; exp.More(); exp.Next() )
1438 SMESH_subMesh* fSubM = _mesh->GetSubMesh( exp.Current() );
1439 if ( ! data._ignoreFaceIds.count( getMeshDS()->ShapeToIndex( exp.Current() )))
1440 faceIds.insert( fSubM->GetId() );
1441 SMESH_subMeshIteratorPtr subIt =
1442 fSubM->getDependsOnIterator(/*includeSelf=*/true, /*complexShapeFirst=*/false);
1443 while ( subIt->more() )
1444 subIds.insert( subIt->next()->GetId() );
1447 // make a map to find new nodes on sub-shapes shared with other SOLID
1448 map< TGeomID, TNode2Edge* > s2neMap;
1449 map< TGeomID, TNode2Edge* >::iterator s2ne;
1450 map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
1451 for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
1453 TGeomID shapeInd = s2s->first;
1454 for ( size_t i = 0; i < _sdVec.size(); ++i )
1456 if ( _sdVec[i]._index == data._index ) continue;
1457 map< TGeomID, TopoDS_Shape >::iterator s2s2 = _sdVec[i]._shrinkShape2Shape.find( shapeInd );
1458 if ( s2s2 != _sdVec[i]._shrinkShape2Shape.end() &&
1459 *s2s == *s2s2 && !_sdVec[i]._n2eMap.empty() )
1461 s2neMap.insert( make_pair( shapeInd, &_sdVec[i]._n2eMap ));
1467 // Create temporary faces and _LayerEdge's
1469 dumpFunction(SMESH_Comment("makeLayers_")<<data._index);
1471 data._stepSize = Precision::Infinite();
1472 data._stepSizeNodes[0] = 0;
1474 SMESH_MesherHelper helper( *_mesh );
1475 helper.SetSubShape( data._solid );
1476 helper.SetElementsOnShape(true);
1478 vector< const SMDS_MeshNode*> newNodes; // of a mesh face
1479 TNode2Edge::iterator n2e2;
1481 // collect _LayerEdge's of shapes they are based on
1482 const int nbShapes = getMeshDS()->MaxShapeIndex();
1483 vector< vector<_LayerEdge*> > edgesByGeom( nbShapes+1 );
1485 for ( set<TGeomID>::iterator id = faceIds.begin(); id != faceIds.end(); ++id )
1487 SMESHDS_SubMesh* smDS = getMeshDS()->MeshElements( *id );
1488 if ( !smDS ) return error(SMESH_Comment("Not meshed face ") << *id, data._index );
1490 const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( *id ));
1491 SMESH_ProxyMesh::SubMesh* proxySub =
1492 data._proxyMesh->getFaceSubM( F, /*create=*/true);
1494 SMDS_ElemIteratorPtr eIt = smDS->GetElements();
1495 while ( eIt->more() )
1497 const SMDS_MeshElement* face = eIt->next();
1498 newNodes.resize( face->NbCornerNodes() );
1499 double faceMaxCosin = -1;
1500 for ( int i = 0 ; i < face->NbCornerNodes(); ++i )
1502 const SMDS_MeshNode* n = face->GetNode(i);
1503 TNode2Edge::iterator n2e = data._n2eMap.insert( make_pair( n, (_LayerEdge*)0 )).first;
1504 if ( !(*n2e).second )
1507 _LayerEdge* edge = new _LayerEdge();
1509 edge->_nodes.push_back( n );
1510 const int shapeID = n->getshapeId();
1511 edgesByGeom[ shapeID ].push_back( edge );
1513 // set edge data or find already refined _LayerEdge and get data from it
1514 if ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE &&
1515 ( s2ne = s2neMap.find( shapeID )) != s2neMap.end() &&
1516 ( n2e2 = (*s2ne).second->find( n )) != s2ne->second->end())
1518 _LayerEdge* foundEdge = (*n2e2).second;
1519 edge->Copy( *foundEdge, helper );
1520 // location of the last node is modified but we can restore
1521 // it by node position on _sWOL stored by the node
1522 const_cast< SMDS_MeshNode* >
1523 ( edge->_nodes.back() )->setXYZ( n->X(), n->Y(), n->Z() );
1527 edge->_nodes.push_back( helper.AddNode( n->X(), n->Y(), n->Z() ));
1528 if ( !setEdgeData( *edge, subIds, helper, data ))
1531 dumpMove(edge->_nodes.back());
1532 if ( edge->_cosin > 0.01 )
1534 if ( edge->_cosin > faceMaxCosin )
1535 faceMaxCosin = edge->_cosin;
1538 newNodes[ i ] = n2e->second->_nodes.back();
1540 // create a temporary face
1541 const SMDS_MeshElement* newFace = new TmpMeshFace( newNodes, --_tmpFaceID );
1542 proxySub->AddElement( newFace );
1544 // compute inflation step size by min size of element on a convex surface
1545 if ( faceMaxCosin > 0.1 )
1546 limitStepSize( data, face, faceMaxCosin );
1547 } // loop on 2D elements on a FACE
1548 } // loop on FACEs of a SOLID
1550 data._epsilon = 1e-7;
1551 if ( data._stepSize < 1. )
1552 data._epsilon *= data._stepSize;
1554 // fill data._simplexTestEdges
1555 findSimplexTestEdges( data, edgesByGeom );
1557 // Put _LayerEdge's into the vector data._edges
1558 if ( !sortEdges( data, edgesByGeom ))
1561 // Set target nodes into _Simplex and _2NearEdges of _LayerEdge's
1562 TNode2Edge::iterator n2e;
1563 for ( size_t i = 0; i < data._edges.size(); ++i )
1565 if ( data._edges[i]->IsOnEdge())
1566 for ( int j = 0; j < 2; ++j )
1568 if ( data._edges[i]->_nodes.back()->NbInverseElements(SMDSAbs_Volume) > 0 )
1569 break; // _LayerEdge is shared by two _SolidData's
1570 const SMDS_MeshNode* & n = data._edges[i]->_2neibors->_nodes[j];
1571 if (( n2e = data._n2eMap.find( n )) == data._n2eMap.end() )
1572 return error("_LayerEdge not found by src node", data._index);
1573 n = (*n2e).second->_nodes.back();
1574 data._edges[i]->_2neibors->_edges[j] = n2e->second;
1577 for ( size_t j = 0; j < data._edges[i]->_simplices.size(); ++j )
1579 _Simplex& s = data._edges[i]->_simplices[j];
1580 s._nNext = data._n2eMap[ s._nNext ]->_nodes.back();
1581 s._nPrev = data._n2eMap[ s._nPrev ]->_nodes.back();
1589 //================================================================================
1591 * \brief Compute inflation step size by min size of element on a convex surface
1593 //================================================================================
1595 void _ViscousBuilder::limitStepSize( _SolidData& data,
1596 const SMDS_MeshElement* face,
1600 double minSize = 10 * data._stepSize;
1601 const int nbNodes = face->NbCornerNodes();
1602 for ( int i = 0; i < nbNodes; ++i )
1604 const SMDS_MeshNode* nextN = face->GetNode( SMESH_MesherHelper::WrapIndex( i+1, nbNodes ));
1605 const SMDS_MeshNode* curN = face->GetNode( i );
1606 if ( nextN->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE ||
1607 curN->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE )
1609 double dist = SMESH_TNodeXYZ( face->GetNode(i)).Distance( nextN );
1610 if ( dist < minSize )
1611 minSize = dist, iN = i;
1614 double newStep = 0.8 * minSize / cosin;
1615 if ( newStep < data._stepSize )
1617 data._stepSize = newStep;
1618 data._stepSizeCoeff = 0.8 / cosin;
1619 data._stepSizeNodes[0] = face->GetNode( iN );
1620 data._stepSizeNodes[1] = face->GetNode( SMESH_MesherHelper::WrapIndex( iN+1, nbNodes ));
1624 //================================================================================
1626 * \brief Compute inflation step size by min size of element on a convex surface
1628 //================================================================================
1630 void _ViscousBuilder::limitStepSize( _SolidData& data, const double minSize)
1632 if ( minSize < data._stepSize )
1634 data._stepSize = minSize;
1635 if ( data._stepSizeNodes[0] )
1638 SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
1639 data._stepSizeCoeff = data._stepSize / dist;
1644 //================================================================================
1646 * Fill data._simplexTestEdges. These _LayerEdge's are used to stop inflation
1647 * in the case where there are no _LayerEdge's on a curved convex FACE,
1648 * as e.g. on a fillet surface with no internal nodes - issue 22580,
1649 * so that collision of viscous internal faces is not detected by check of
1650 * intersection of _LayerEdge's with the viscous internal faces.
1652 //================================================================================
1654 void _ViscousBuilder::findSimplexTestEdges( _SolidData& data,
1655 vector< vector<_LayerEdge*> >& edgesByGeom)
1657 data._simplexTestEdges.clear();
1659 SMESH_MesherHelper helper( *_mesh );
1661 vector< vector<_LayerEdge*> * > ledgesOnEdges;
1662 set< const SMDS_MeshNode* > usedNodes;
1664 const double minCurvature = 1. / data._hyp->GetTotalThickness();
1666 for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS )
1668 // look for a FACE with layers and w/o _LayerEdge's
1669 const vector<_LayerEdge*>& eS = edgesByGeom[iS];
1670 if ( !eS.empty() ) continue;
1671 const TopoDS_Shape& S = getMeshDS()->IndexToShape( iS );
1672 if ( S.IsNull() || S.ShapeType() != TopAbs_FACE ) continue;
1673 if ( data._ignoreFaceIds.count( iS )) continue;
1675 const TopoDS_Face& F = TopoDS::Face( S );
1677 // look for _LayerEdge's on EDGEs with null _sWOL
1678 ledgesOnEdges.clear();
1679 TopExp_Explorer eExp( F, TopAbs_EDGE );
1680 for ( ; eExp.More(); eExp.Next() )
1682 TGeomID iE = getMeshDS()->ShapeToIndex( eExp.Current() );
1683 vector<_LayerEdge*>& eE = edgesByGeom[iE];
1684 if ( !eE.empty() && eE[0]->_sWOL.IsNull() )
1685 ledgesOnEdges.push_back( & eE );
1687 if ( ledgesOnEdges.empty() ) continue;
1689 // check FACE convexity
1690 const _LayerEdge* le = ledgesOnEdges[0]->back();
1691 gp_XY uv = helper.GetNodeUV( F, le->_nodes[0] );
1692 BRepAdaptor_Surface surf( F );
1693 BRepLProp_SLProps surfProp( surf, uv.X(), uv.Y(), 2, 1e-6 );
1694 if ( !surfProp.IsCurvatureDefined() )
1696 double surfCurvature = Max( Abs( surfProp.MaxCurvature() ),
1697 Abs( surfProp.MinCurvature() ));
1698 if ( surfCurvature < minCurvature )
1700 gp_Dir minDir, maxDir;
1701 surfProp.CurvatureDirections( maxDir, minDir );
1702 if ( F.Orientation() == TopAbs_REVERSED ) {
1703 maxDir.Reverse(); minDir.Reverse();
1705 const gp_XYZ& inDir = le->_normal;
1706 if ( inDir * maxDir.XYZ() < 0 &&
1707 inDir * minDir.XYZ() < 0 )
1710 // add _simplices to the _LayerEdge's
1711 for ( size_t iE = 0; iE < ledgesOnEdges.size(); ++iE )
1713 const vector<_LayerEdge*>& ledges = *ledgesOnEdges[iE];
1714 for ( size_t iLE = 0; iLE < ledges.size(); ++iLE )
1716 _LayerEdge* ledge = ledges[iLE];
1717 const SMDS_MeshNode* srcNode = ledge->_nodes[0];
1718 if ( !usedNodes.insert( srcNode ).second ) continue;
1720 getSimplices( srcNode, ledge->_simplices, data._ignoreFaceIds, &data );
1721 for ( size_t i = 0; i < ledge->_simplices.size(); ++i )
1723 usedNodes.insert( ledge->_simplices[i]._nPrev );
1724 usedNodes.insert( ledge->_simplices[i]._nNext );
1726 data._simplexTestEdges.push_back( ledge );
1732 //================================================================================
1734 * \brief Separate shapes (and _LayerEdge's on them) to smooth from the rest ones
1736 //================================================================================
1738 bool _ViscousBuilder::sortEdges( _SolidData& data,
1739 vector< vector<_LayerEdge*> >& edgesByGeom)
1741 // Find shapes needing smoothing; such a shape has _LayerEdge._normal on it's
1742 // boundry inclined at a sharp angle to the shape
1744 list< TGeomID > shapesToSmooth;
1746 SMESH_MesherHelper helper( *_mesh );
1749 for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS )
1751 vector<_LayerEdge*>& eS = edgesByGeom[iS];
1752 if ( eS.empty() ) continue;
1753 const TopoDS_Shape& S = getMeshDS()->IndexToShape( iS );
1754 bool needSmooth = false;
1755 switch ( S.ShapeType() )
1759 bool isShrinkEdge = !eS[0]->_sWOL.IsNull();
1760 for ( TopoDS_Iterator vIt( S ); vIt.More() && !needSmooth; vIt.Next() )
1762 TGeomID iV = getMeshDS()->ShapeToIndex( vIt.Value() );
1763 vector<_LayerEdge*>& eV = edgesByGeom[ iV ];
1764 if ( eV.empty() ) continue;
1765 double cosin = eV[0]->_cosin;
1767 ( !eV[0]->_sWOL.IsNull() && ( eV[0]->_sWOL.ShapeType() == TopAbs_EDGE || !isShrinkEdge));
1771 if ( eV[0]->_sWOL.ShapeType() == TopAbs_EDGE )
1772 dir1 = getEdgeDir( TopoDS::Edge( eV[0]->_sWOL ), TopoDS::Vertex( vIt.Value() ));
1774 dir1 = getFaceDir( TopoDS::Face( eV[0]->_sWOL ), TopoDS::Vertex( vIt.Value() ),
1775 eV[0]->_nodes[0], helper, ok);
1776 dir2 = getEdgeDir( TopoDS::Edge( S ), TopoDS::Vertex( vIt.Value() ));
1777 double angle = dir1.Angle( dir2 );
1778 cosin = cos( angle );
1780 needSmooth = ( cosin > 0.1 );
1786 for ( TopExp_Explorer eExp( S, TopAbs_EDGE ); eExp.More() && !needSmooth; eExp.Next() )
1788 TGeomID iE = getMeshDS()->ShapeToIndex( eExp.Current() );
1789 vector<_LayerEdge*>& eE = edgesByGeom[ iE ];
1790 if ( eE.empty() ) continue;
1791 if ( eE[0]->_sWOL.IsNull() )
1793 for ( size_t i = 0; i < eE.size() && !needSmooth; ++i )
1794 needSmooth = ( eE[i]->_cosin > 0.1 );
1798 const TopoDS_Face& F1 = TopoDS::Face( S );
1799 const TopoDS_Face& F2 = TopoDS::Face( eE[0]->_sWOL );
1800 const TopoDS_Edge& E = TopoDS::Edge( eExp.Current() );
1801 for ( size_t i = 0; i < eE.size() && !needSmooth; ++i )
1803 gp_Vec dir1 = getFaceDir( F1, E, eE[i]->_nodes[0], helper, ok );
1804 gp_Vec dir2 = getFaceDir( F2, E, eE[i]->_nodes[0], helper, ok );
1805 double angle = dir1.Angle( dir2 );
1806 double cosin = cos( angle );
1807 needSmooth = ( cosin > 0.1 );
1819 if ( S.ShapeType() == TopAbs_EDGE ) shapesToSmooth.push_front( iS );
1820 else shapesToSmooth.push_back ( iS );
1823 } // loop on edgesByGeom
1825 data._edges.reserve( data._n2eMap.size() );
1826 data._endEdgeToSmooth.clear();
1828 // first we put _LayerEdge's on shapes to smooth
1829 list< TGeomID >::iterator gIt = shapesToSmooth.begin();
1830 for ( ; gIt != shapesToSmooth.end(); ++gIt )
1832 vector<_LayerEdge*>& eVec = edgesByGeom[ *gIt ];
1833 if ( eVec.empty() ) continue;
1834 data._edges.insert( data._edges.end(), eVec.begin(), eVec.end() );
1835 data._endEdgeToSmooth.push_back( data._edges.size() );
1839 // then the rest _LayerEdge's
1840 for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS )
1842 vector<_LayerEdge*>& eVec = edgesByGeom[iS];
1843 data._edges.insert( data._edges.end(), eVec.begin(), eVec.end() );
1850 //================================================================================
1852 * \brief Set data of _LayerEdge needed for smoothing
1853 * \param subIds - ids of sub-shapes of a SOLID to take into account faces from
1855 //================================================================================
1857 bool _ViscousBuilder::setEdgeData(_LayerEdge& edge,
1858 const set<TGeomID>& subIds,
1859 SMESH_MesherHelper& helper,
1862 SMESH_MeshEditor editor(_mesh);
1864 const SMDS_MeshNode* node = edge._nodes[0]; // source node
1865 SMDS_TypeOfPosition posType = node->GetPosition()->GetTypeOfPosition();
1869 edge._curvature = 0;
1871 // --------------------------
1872 // Compute _normal and _cosin
1873 // --------------------------
1876 edge._normal.SetCoord(0,0,0);
1878 int totalNbFaces = 0;
1880 gp_Vec du, dv, geomNorm;
1883 TGeomID shapeInd = node->getshapeId();
1884 map< TGeomID, TopoDS_Shape >::const_iterator s2s = data._shrinkShape2Shape.find( shapeInd );
1885 bool onShrinkShape ( s2s != data._shrinkShape2Shape.end() );
1886 TopoDS_Shape vertEdge;
1888 if ( onShrinkShape ) // one of faces the node is on has no layers
1890 vertEdge = getMeshDS()->IndexToShape( s2s->first ); // vertex or edge
1891 if ( s2s->second.ShapeType() == TopAbs_EDGE )
1893 // inflate from VERTEX along EDGE
1894 edge._normal = getEdgeDir( TopoDS::Edge( s2s->second ), TopoDS::Vertex( vertEdge ));
1896 else if ( vertEdge.ShapeType() == TopAbs_VERTEX )
1898 // inflate from VERTEX along FACE
1899 edge._normal = getFaceDir( TopoDS::Face( s2s->second ), TopoDS::Vertex( vertEdge ),
1900 node, helper, normOK, &edge._cosin);
1904 // inflate from EDGE along FACE
1905 edge._normal = getFaceDir( TopoDS::Face( s2s->second ), TopoDS::Edge( vertEdge ),
1906 node, helper, normOK);
1909 else // layers are on all faces of SOLID the node is on
1911 // find indices of geom faces the node lies on
1912 set<TGeomID> faceIds;
1913 if ( posType == SMDS_TOP_FACE )
1915 faceIds.insert( node->getshapeId() );
1919 SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
1920 while ( fIt->more() )
1921 faceIds.insert( editor.FindShape(fIt->next()));
1924 set<TGeomID>::iterator id = faceIds.begin();
1926 std::pair< TGeomID, gp_XYZ > id2Norm[20];
1927 for ( ; id != faceIds.end(); ++id )
1929 const TopoDS_Shape& s = getMeshDS()->IndexToShape( *id );
1930 if ( s.IsNull() || s.ShapeType() != TopAbs_FACE || !subIds.count( *id ))
1932 F = TopoDS::Face( s );
1934 gp_XY uv = helper.GetNodeUV( F, node, 0, &normOK );
1935 Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
1938 if ( GeomLib::NormEstim( surface, uv, 1e-10, normal ) < 3 )
1943 else // hard singularity
1945 SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
1946 while ( fIt->more() )
1948 const SMDS_MeshElement* f = fIt->next();
1949 if ( editor.FindShape( f ) == *id )
1951 SMESH_MeshAlgos::FaceNormal( f, (gp_XYZ&) geomNorm.XYZ(), /*normalized=*/false );
1952 if ( helper.IsReversedSubMesh( F ))
1957 double size2 = geomNorm.SquareMagnitude();
1958 if ( size2 > numeric_limits<double>::min() )
1959 geomNorm /= sqrt( size2 );
1964 if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
1966 id2Norm[ totalNbFaces ].first = *id;
1967 id2Norm[ totalNbFaces ].second = geomNorm.XYZ();
1969 edge._normal += geomNorm.XYZ();
1971 if ( totalNbFaces == 0 )
1972 return error(SMESH_Comment("Can't get normal to node ") << node->GetID(), data._index);
1974 if ( totalNbFaces < 3 )
1976 //edge._normal /= totalNbFaces;
1980 edge._normal = getWeigthedNormal( node, id2Norm, totalNbFaces );
1986 edge._cosin = 0; break;
1988 case SMDS_TOP_EDGE: {
1989 TopoDS_Edge E = TopoDS::Edge( helper.GetSubShapeByNode( node, getMeshDS()));
1990 gp_Vec inFaceDir = getFaceDir( F, E, node, helper, normOK);
1991 double angle = inFaceDir.Angle( edge._normal ); // [0,PI]
1992 edge._cosin = cos( angle );
1993 //cout << "Cosin on EDGE " << edge._cosin << " node " << node->GetID() << endl;
1996 case SMDS_TOP_VERTEX: {
1997 TopoDS_Vertex V = TopoDS::Vertex( helper.GetSubShapeByNode( node, getMeshDS()));
1998 gp_XYZ inFaceDir = getFaceDir( F, V, node, helper, normOK);
1999 double angle = gp_Vec( inFaceDir).Angle( edge._normal ); // [0,PI]
2000 edge._cosin = cos( angle );
2001 //cout << "Cosin on VERTEX " << edge._cosin << " node " << node->GetID() << endl;
2005 return error(SMESH_Comment("Invalid shape position of node ")<<node, data._index);
2009 double normSize = edge._normal.SquareModulus();
2010 if ( normSize < numeric_limits<double>::min() )
2011 return error(SMESH_Comment("Bad normal at node ")<< node->GetID(), data._index );
2013 edge._normal /= sqrt( normSize );
2015 // TODO: if ( !normOK ) then get normal by mesh faces
2017 // Set the rest data
2018 // --------------------
2019 if ( onShrinkShape )
2021 edge._sWOL = (*s2s).second;
2023 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edge._nodes.back() );
2024 if ( SMESHDS_SubMesh* sm = getMeshDS()->MeshElements( data._solid ))
2025 sm->RemoveNode( tgtNode , /*isNodeDeleted=*/false );
2027 // set initial position which is parameters on _sWOL in this case
2028 if ( edge._sWOL.ShapeType() == TopAbs_EDGE )
2030 double u = helper.GetNodeU( TopoDS::Edge( edge._sWOL ), node, 0, &normOK );
2031 edge._pos.push_back( gp_XYZ( u, 0, 0));
2032 getMeshDS()->SetNodeOnEdge( tgtNode, TopoDS::Edge( edge._sWOL ), u );
2036 gp_XY uv = helper.GetNodeUV( TopoDS::Face( edge._sWOL ), node, 0, &normOK );
2037 edge._pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
2038 getMeshDS()->SetNodeOnFace( tgtNode, TopoDS::Face( edge._sWOL ), uv.X(), uv.Y() );
2043 edge._pos.push_back( SMESH_TNodeXYZ( node ));
2045 if ( posType == SMDS_TOP_FACE )
2047 getSimplices( node, edge._simplices, data._ignoreFaceIds, &data );
2048 double avgNormProj = 0, avgLen = 0;
2049 for ( size_t i = 0; i < edge._simplices.size(); ++i )
2051 gp_XYZ vec = edge._pos.back() - SMESH_TNodeXYZ( edge._simplices[i]._nPrev );
2052 avgNormProj += edge._normal * vec;
2053 avgLen += vec.Modulus();
2055 avgNormProj /= edge._simplices.size();
2056 avgLen /= edge._simplices.size();
2057 edge._curvature = _Curvature::New( avgNormProj, avgLen );
2061 // Set neighbour nodes for a _LayerEdge based on EDGE
2063 if ( posType == SMDS_TOP_EDGE /*||
2064 ( onShrinkShape && posType == SMDS_TOP_VERTEX && fabs( edge._cosin ) < 1e-10 )*/)
2066 edge._2neibors = new _2NearEdges;
2067 // target node instead of source ones will be set later
2068 if ( ! findNeiborsOnEdge( &edge,
2069 edge._2neibors->_nodes[0],
2070 edge._2neibors->_nodes[1],
2073 edge.SetDataByNeighbors( edge._2neibors->_nodes[0],
2074 edge._2neibors->_nodes[1],
2078 edge.SetCosin( edge._cosin ); // to update edge._lenFactor
2083 //================================================================================
2085 * \brief Return normal at a node weighted with angles taken by FACEs
2086 * \param [in] n - the node
2087 * \param [in] fId2Normal - FACE ids and normals
2088 * \param [in] nbFaces - nb of FACEs meeting at the node
2089 * \return gp_XYZ - computed normal
2091 //================================================================================
2093 gp_XYZ _ViscousBuilder::getWeigthedNormal( const SMDS_MeshNode* n,
2094 std::pair< TGeomID, gp_XYZ > fId2Normal[],
2097 gp_XYZ resNorm(0,0,0);
2098 TopoDS_Shape V = SMESH_MesherHelper::GetSubShapeByNode( n, getMeshDS() );
2099 if ( V.ShapeType() != TopAbs_VERTEX )
2101 for ( int i = 0; i < nbFaces; ++i )
2102 resNorm += fId2Normal[i].second / nbFaces ;
2107 for ( int i = 0; i < nbFaces; ++i )
2109 const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( fId2Normal[i].first ));
2111 // look for two EDGEs shared by F and other FACEs within fId2Normal
2114 PShapeIteratorPtr eIt = SMESH_MesherHelper::GetAncestors( V, *_mesh, TopAbs_EDGE );
2115 while ( const TopoDS_Shape* E = eIt->next() )
2117 if ( !SMESH_MesherHelper::IsSubShape( *E, F ))
2119 bool isSharedEdge = false;
2120 for ( int j = 0; j < nbFaces && !isSharedEdge; ++j )
2122 if ( i == j ) continue;
2123 const TopoDS_Shape& otherF = getMeshDS()->IndexToShape( fId2Normal[j].first );
2124 isSharedEdge = SMESH_MesherHelper::IsSubShape( *E, otherF );
2126 if ( !isSharedEdge )
2128 ee[ nbE ] = TopoDS::Edge( *E );
2129 ee[ nbE ].Orientation( SMESH_MesherHelper::GetSubShapeOri( F, *E ));
2134 // get an angle between the two EDGEs
2136 if ( nbE < 1 ) continue;
2143 TopoDS_Vertex v10 = SMESH_MesherHelper::IthVertex( 1, ee[ 0 ]);
2144 TopoDS_Vertex v01 = SMESH_MesherHelper::IthVertex( 0, ee[ 1 ]);
2145 if ( !v10.IsSame( v01 ))
2146 std::swap( ee[0], ee[1] );
2148 angles[i] = SMESH_MesherHelper::GetAngle( ee[0], ee[1], F );
2151 // compute a weighted normal
2152 double sumAngle = 0;
2153 for ( int i = 0; i < nbFaces; ++i )
2155 angles[i] = ( angles[i] > 2*M_PI ) ? 0 : M_PI - angles[i];
2156 sumAngle += angles[i];
2158 for ( int i = 0; i < nbFaces; ++i )
2159 resNorm += angles[i] / sumAngle * fId2Normal[i].second;
2164 //================================================================================
2166 * \brief Find 2 neigbor nodes of a node on EDGE
2168 //================================================================================
2170 bool _ViscousBuilder::findNeiborsOnEdge(const _LayerEdge* edge,
2171 const SMDS_MeshNode*& n1,
2172 const SMDS_MeshNode*& n2,
2175 const SMDS_MeshNode* node = edge->_nodes[0];
2176 const int shapeInd = node->getshapeId();
2177 SMESHDS_SubMesh* edgeSM = 0;
2178 if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_EDGE )
2181 edgeSM = getMeshDS()->MeshElements( shapeInd );
2182 if ( !edgeSM || edgeSM->NbElements() == 0 )
2183 return error(SMESH_Comment("Not meshed EDGE ") << shapeInd, data._index);
2187 SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator(SMDSAbs_Edge);
2188 while ( eIt->more() && !n2 )
2190 const SMDS_MeshElement* e = eIt->next();
2191 const SMDS_MeshNode* nNeibor = e->GetNode( 0 );
2192 if ( nNeibor == node ) nNeibor = e->GetNode( 1 );
2195 if (!edgeSM->Contains(e)) continue;
2199 TopoDS_Shape s = SMESH_MesherHelper::GetSubShapeByNode(nNeibor, getMeshDS() );
2200 if ( !SMESH_MesherHelper::IsSubShape( s, edge->_sWOL )) continue;
2202 ( iN++ ? n2 : n1 ) = nNeibor;
2205 return error(SMESH_Comment("Wrongly meshed EDGE ") << shapeInd, data._index);
2209 //================================================================================
2211 * \brief Set _curvature and _2neibors->_plnNorm by 2 neigbor nodes residing the same EDGE
2213 //================================================================================
2215 void _LayerEdge::SetDataByNeighbors( const SMDS_MeshNode* n1,
2216 const SMDS_MeshNode* n2,
2217 SMESH_MesherHelper& helper)
2219 if ( _nodes[0]->GetPosition()->GetTypeOfPosition() != SMDS_TOP_EDGE )
2222 gp_XYZ pos = SMESH_TNodeXYZ( _nodes[0] );
2223 gp_XYZ vec1 = pos - SMESH_TNodeXYZ( n1 );
2224 gp_XYZ vec2 = pos - SMESH_TNodeXYZ( n2 );
2228 double sumLen = vec1.Modulus() + vec2.Modulus();
2229 _2neibors->_wgt[0] = 1 - vec1.Modulus() / sumLen;
2230 _2neibors->_wgt[1] = 1 - vec2.Modulus() / sumLen;
2231 double avgNormProj = 0.5 * ( _normal * vec1 + _normal * vec2 );
2232 double avgLen = 0.5 * ( vec1.Modulus() + vec2.Modulus() );
2233 if ( _curvature ) delete _curvature;
2234 _curvature = _Curvature::New( avgNormProj, avgLen );
2236 // if ( _curvature )
2237 // cout << _nodes[0]->GetID()
2238 // << " CURV r,k: " << _curvature->_r<<","<<_curvature->_k
2239 // << " proj = "<<avgNormProj<< " len = " << avgLen << "| lenDelta(0) = "
2240 // << _curvature->lenDelta(0) << endl;
2245 if ( _sWOL.IsNull() )
2247 TopoDS_Shape S = helper.GetSubShapeByNode( _nodes[0], helper.GetMeshDS() );
2248 gp_XYZ dirE = getEdgeDir( TopoDS::Edge( S ), _nodes[0], helper );
2249 gp_XYZ plnNorm = dirE ^ _normal;
2250 double proj0 = plnNorm * vec1;
2251 double proj1 = plnNorm * vec2;
2252 if ( fabs( proj0 ) > 1e-10 || fabs( proj1 ) > 1e-10 )
2254 if ( _2neibors->_plnNorm ) delete _2neibors->_plnNorm;
2255 _2neibors->_plnNorm = new gp_XYZ( plnNorm.Normalized() );
2260 //================================================================================
2262 * \brief Copy data from a _LayerEdge of other SOLID and based on the same node;
2263 * this and other _LayerEdge's are inflated along a FACE or an EDGE
2265 //================================================================================
2267 void _LayerEdge::Copy( _LayerEdge& other, SMESH_MesherHelper& helper )
2269 _nodes = other._nodes;
2270 _normal = other._normal;
2272 _lenFactor = other._lenFactor;
2273 _cosin = other._cosin;
2274 _sWOL = other._sWOL;
2275 _2neibors = other._2neibors;
2276 _curvature = 0; std::swap( _curvature, other._curvature );
2277 _2neibors = 0; std::swap( _2neibors, other._2neibors );
2279 if ( _sWOL.ShapeType() == TopAbs_EDGE )
2281 double u = helper.GetNodeU( TopoDS::Edge( _sWOL ), _nodes[0] );
2282 _pos.push_back( gp_XYZ( u, 0, 0));
2286 gp_XY uv = helper.GetNodeUV( TopoDS::Face( _sWOL ), _nodes[0]);
2287 _pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
2291 //================================================================================
2293 * \brief Set _cosin and _lenFactor
2295 //================================================================================
2297 void _LayerEdge::SetCosin( double cosin )
2300 _lenFactor = ( Abs( _cosin ) > 0.1 ) ? 1./sqrt(1-_cosin*_cosin) : 1.0;
2303 //================================================================================
2305 * \brief Fills a vector<_Simplex >
2307 //================================================================================
2309 void _ViscousBuilder::getSimplices( const SMDS_MeshNode* node,
2310 vector<_Simplex>& simplices,
2311 const set<TGeomID>& ingnoreShapes,
2312 const _SolidData* dataToCheckOri,
2316 SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
2317 while ( fIt->more() )
2319 const SMDS_MeshElement* f = fIt->next();
2320 const TGeomID shapeInd = f->getshapeId();
2321 if ( ingnoreShapes.count( shapeInd )) continue;
2322 const int nbNodes = f->NbCornerNodes();
2323 const int srcInd = f->GetNodeIndex( node );
2324 const SMDS_MeshNode* nPrev = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd-1, nbNodes ));
2325 const SMDS_MeshNode* nNext = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+1, nbNodes ));
2326 const SMDS_MeshNode* nOpp = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+2, nbNodes ));
2327 if ( dataToCheckOri && dataToCheckOri->_reversedFaceIds.count( shapeInd ))
2328 std::swap( nPrev, nNext );
2329 simplices.push_back( _Simplex( nPrev, nNext, nOpp ));
2334 vector<_Simplex> sortedSimplices( simplices.size() );
2335 sortedSimplices[0] = simplices[0];
2337 for ( size_t i = 1; i < simplices.size(); ++i )
2339 for ( size_t j = 1; j < simplices.size(); ++j )
2340 if ( sortedSimplices[i-1]._nNext == simplices[j]._nPrev )
2342 sortedSimplices[i] = simplices[j];
2347 if ( nbFound == simplices.size() - 1 )
2348 simplices.swap( sortedSimplices );
2352 //================================================================================
2354 * \brief DEBUG. Create groups contating temorary data of _LayerEdge's
2356 //================================================================================
2358 void _ViscousBuilder::makeGroupOfLE()
2361 for ( size_t i = 0 ; i < _sdVec.size(); ++i )
2363 if ( _sdVec[i]._edges.empty() ) continue;
2364 // string name = SMESH_Comment("_LayerEdge's_") << i;
2366 // SMESH_Group* g = _mesh->AddGroup(SMDSAbs_Edge, name.c_str(), id );
2367 // SMESHDS_Group* gDS = (SMESHDS_Group*)g->GetGroupDS();
2368 // SMESHDS_Mesh* mDS = _mesh->GetMeshDS();
2370 dumpFunction( SMESH_Comment("make_LayerEdge_") << i );
2371 for ( size_t j = 0 ; j < _sdVec[i]._edges.size(); ++j )
2373 _LayerEdge* le = _sdVec[i]._edges[j];
2374 for ( size_t iN = 1; iN < le->_nodes.size(); ++iN )
2375 dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<le->_nodes[iN-1]->GetID()
2376 << ", " << le->_nodes[iN]->GetID() <<"])");
2377 //gDS->SMDSGroup().Add( mDS->AddEdge( le->_nodes[iN-1], le->_nodes[iN]));
2381 dumpFunction( SMESH_Comment("makeNormals") << i );
2382 for ( size_t j = 0 ; j < _sdVec[i]._edges.size(); ++j )
2384 _LayerEdge& edge = *_sdVec[i]._edges[j];
2385 SMESH_TNodeXYZ nXYZ( edge._nodes[0] );
2386 nXYZ += edge._normal * _sdVec[i]._stepSize;
2387 dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<edge._nodes[0]->GetID()
2388 << ", mesh.AddNode( " << nXYZ.X()<<","<< nXYZ.Y()<<","<< nXYZ.Z()<<")])");
2392 // name = SMESH_Comment("tmp_faces ") << i;
2393 // g = _mesh->AddGroup(SMDSAbs_Face, name.c_str(), id );
2394 // gDS = (SMESHDS_Group*)g->GetGroupDS();
2395 // SMESH_MeshEditor editor( _mesh );
2396 dumpFunction( SMESH_Comment("makeTmpFaces_") << i );
2397 TopExp_Explorer fExp( _sdVec[i]._solid, TopAbs_FACE );
2398 for ( ; fExp.More(); fExp.Next() )
2400 if (const SMESHDS_SubMesh* sm = _sdVec[i]._proxyMesh->GetProxySubMesh( fExp.Current()))
2402 SMDS_ElemIteratorPtr fIt = sm->GetElements();
2403 while ( fIt->more())
2405 const SMDS_MeshElement* e = fIt->next();
2406 SMESH_Comment cmd("mesh.AddFace([");
2407 for ( int j=0; j < e->NbCornerNodes(); ++j )
2408 cmd << e->GetNode(j)->GetID() << (j+1<e->NbCornerNodes() ? ",": "])");
2410 //vector<const SMDS_MeshNode*> nodes( e->begin_nodes(), e->end_nodes() );
2411 //gDS->SMDSGroup().Add( editor.AddElement( nodes, e->GetType(), e->IsPoly()));
2420 //================================================================================
2422 * \brief Increase length of _LayerEdge's to reach the required thickness of layers
2424 //================================================================================
2426 bool _ViscousBuilder::inflate(_SolidData& data)
2428 SMESH_MesherHelper helper( *_mesh );
2430 // Limit inflation step size by geometry size found by itersecting
2431 // normals of _LayerEdge's with mesh faces
2432 double geomSize = Precision::Infinite(), intersecDist;
2433 auto_ptr<SMESH_ElementSearcher> searcher
2434 ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(),
2435 data._proxyMesh->GetFaces( data._solid )) );
2436 for ( size_t i = 0; i < data._edges.size(); ++i )
2438 if ( data._edges[i]->IsOnEdge() ) continue;
2439 data._edges[i]->FindIntersection( *searcher, intersecDist, data._epsilon );
2440 if ( geomSize > intersecDist && intersecDist > 0 )
2441 geomSize = intersecDist;
2443 if ( data._stepSize > 0.3 * geomSize )
2444 limitStepSize( data, 0.3 * geomSize );
2446 const double tgtThick = data._hyp->GetTotalThickness();
2447 if ( data._stepSize > tgtThick )
2448 limitStepSize( data, tgtThick );
2450 if ( data._stepSize < 1. )
2451 data._epsilon = data._stepSize * 1e-7;
2454 cout << "-- geomSize = " << geomSize << ", stepSize = " << data._stepSize << endl;
2457 double avgThick = 0, curThick = 0, distToIntersection = Precision::Infinite();
2458 int nbSteps = 0, nbRepeats = 0;
2459 while ( 1.01 * avgThick < tgtThick )
2461 // new target length
2462 curThick += data._stepSize;
2463 if ( curThick > tgtThick )
2465 curThick = tgtThick + ( tgtThick-avgThick ) * nbRepeats;
2469 // Elongate _LayerEdge's
2470 dumpFunction(SMESH_Comment("inflate")<<data._index<<"_step"<<nbSteps); // debug
2471 for ( size_t i = 0; i < data._edges.size(); ++i )
2473 data._edges[i]->SetNewLength( curThick, helper );
2478 if ( !updateNormals( data, helper ) )
2481 // Improve and check quality
2482 if ( !smoothAndCheck( data, nbSteps, distToIntersection ))
2486 dumpFunction(SMESH_Comment("invalidate")<<data._index<<"_step"<<nbSteps); // debug
2487 for ( size_t i = 0; i < data._edges.size(); ++i )
2489 data._edges[i]->InvalidateStep( nbSteps+1 );
2493 break; // no more inflating possible
2497 // Evaluate achieved thickness
2499 for ( size_t i = 0; i < data._edges.size(); ++i )
2500 avgThick += data._edges[i]->_len;
2501 avgThick /= data._edges.size();
2503 cout << "-- Thickness " << avgThick << " reached" << endl;
2506 if ( distToIntersection < avgThick*1.5 )
2509 cout << "-- Stop inflation since distToIntersection( "<<distToIntersection<<" ) < avgThick( "
2510 << avgThick << " ) * 1.5" << endl;
2515 limitStepSize( data, 0.25 * distToIntersection );
2516 if ( data._stepSizeNodes[0] )
2517 data._stepSize = data._stepSizeCoeff *
2518 SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
2522 return error("failed at the very first inflation step", data._index);
2527 //================================================================================
2529 * \brief Improve quality of layer inner surface and check intersection
2531 //================================================================================
2533 bool _ViscousBuilder::smoothAndCheck(_SolidData& data,
2535 double & distToIntersection)
2537 if ( data._endEdgeToSmooth.empty() )
2538 return true; // no shapes needing smoothing
2540 bool moved, improved;
2542 SMESH_MesherHelper helper(*_mesh);
2543 Handle(Geom_Surface) surface;
2547 for ( size_t iS = 0; iS < data._endEdgeToSmooth.size(); ++iS )
2550 iEnd = data._endEdgeToSmooth[ iS ];
2552 if ( !data._edges[ iBeg ]->_sWOL.IsNull() &&
2553 data._edges[ iBeg ]->_sWOL.ShapeType() == TopAbs_FACE )
2555 if ( !F.IsSame( data._edges[ iBeg ]->_sWOL )) {
2556 F = TopoDS::Face( data._edges[ iBeg ]->_sWOL );
2557 helper.SetSubShape( F );
2558 surface = BRep_Tool::Surface( F );
2563 F.Nullify(); surface.Nullify();
2565 TGeomID sInd = data._edges[ iBeg ]->_nodes[0]->getshapeId();
2567 if ( data._edges[ iBeg ]->IsOnEdge() )
2569 dumpFunction(SMESH_Comment("smooth")<<data._index << "_Ed"<<sInd <<"_InfStep"<<nbSteps);
2571 // try a simple solution on an analytic EDGE
2572 if ( !smoothAnalyticEdge( data, iBeg, iEnd, surface, F, helper ))
2578 for ( int i = iBeg; i < iEnd; ++i )
2580 moved |= data._edges[i]->SmoothOnEdge(surface, F, helper);
2582 dumpCmd( SMESH_Comment("# end step ")<<step);
2584 while ( moved && step++ < 5 );
2585 //cout << " NB STEPS: " << step << endl;
2592 int step = 0, stepLimit = 5, badNb = 0; moved = true;
2593 while (( ++step <= stepLimit && moved ) || improved )
2595 dumpFunction(SMESH_Comment("smooth")<<data._index<<"_Fa"<<sInd
2596 <<"_InfStep"<<nbSteps<<"_"<<step); // debug
2597 int oldBadNb = badNb;
2600 for ( int i = iBeg; i < iEnd; ++i )
2601 moved |= data._edges[i]->Smooth(badNb);
2602 improved = ( badNb < oldBadNb );
2604 // issue 22576. no bad faces but still there are intersections to fix
2605 if ( improved && badNb == 0 )
2606 stepLimit = step + 3;
2613 for ( int i = iBeg; i < iEnd; ++i )
2615 _LayerEdge* edge = data._edges[i];
2616 SMESH_TNodeXYZ tgtXYZ( edge->_nodes.back() );
2617 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
2618 if ( !edge->_simplices[j].IsForward( edge->_nodes[0], &tgtXYZ ))
2620 cout << "Bad simplex ( " << edge->_nodes[0]->GetID()<< " "<< tgtXYZ._node->GetID()
2621 << " "<< edge->_simplices[j]._nPrev->GetID()
2622 << " "<< edge->_simplices[j]._nNext->GetID() << " )" << endl;
2630 } // loop on shapes to smooth
2632 // Check orientation of simplices of _simplexTestEdges
2633 for ( size_t i = 0; i < data._simplexTestEdges.size(); ++i )
2635 const _LayerEdge* edge = data._simplexTestEdges[i];
2636 SMESH_TNodeXYZ tgtXYZ( edge->_nodes.back() );
2637 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
2638 if ( !edge->_simplices[j].IsForward( edge->_nodes[0], &tgtXYZ ))
2641 cout << "Bad simplex of _simplexTestEdges ("
2642 << " "<< edge->_nodes[0]->GetID()<< " "<< tgtXYZ._node->GetID()
2643 << " "<< edge->_simplices[j]._nPrev->GetID()
2644 << " "<< edge->_simplices[j]._nNext->GetID() << " )" << endl;
2650 // Check if the last segments of _LayerEdge intersects 2D elements;
2651 // checked elements are either temporary faces or faces on surfaces w/o the layers
2653 auto_ptr<SMESH_ElementSearcher> searcher
2654 ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(),
2655 data._proxyMesh->GetFaces( data._solid )) );
2657 distToIntersection = Precision::Infinite();
2659 const SMDS_MeshElement* intFace = 0;
2661 const SMDS_MeshElement* closestFace = 0;
2664 for ( size_t i = 0; i < data._edges.size(); ++i )
2666 if ( data._edges[i]->FindIntersection( *searcher, dist, data._epsilon, &intFace ))
2668 if ( distToIntersection > dist )
2670 distToIntersection = dist;
2673 closestFace = intFace;
2680 SMDS_MeshElement::iterator nIt = closestFace->begin_nodes();
2681 cout << "Shortest distance: _LayerEdge nodes: tgt " << data._edges[iLE]->_nodes.back()->GetID()
2682 << " src " << data._edges[iLE]->_nodes[0]->GetID()<< ", intersection with face ("
2683 << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
2684 << ") distance = " << distToIntersection<< endl;
2691 //================================================================================
2693 * \brief Return a curve of the EDGE to be used for smoothing and arrange
2694 * _LayerEdge's to be in a consequent order
2696 //================================================================================
2698 Handle(Geom_Curve) _SolidData::CurveForSmooth( const TopoDS_Edge& E,
2701 Handle(Geom_Surface)& surface,
2702 const TopoDS_Face& F,
2703 SMESH_MesherHelper& helper)
2705 TGeomID eIndex = helper.GetMeshDS()->ShapeToIndex( E );
2707 map< TGeomID, Handle(Geom_Curve)>::iterator i2curve = _edge2curve.find( eIndex );
2709 if ( i2curve == _edge2curve.end() )
2711 // sort _LayerEdge's by position on the EDGE
2713 map< double, _LayerEdge* > u2edge;
2714 for ( int i = iFrom; i < iTo; ++i )
2715 u2edge.insert( make_pair( helper.GetNodeU( E, _edges[i]->_nodes[0] ), _edges[i] ));
2717 ASSERT( u2edge.size() == iTo - iFrom );
2718 map< double, _LayerEdge* >::iterator u2e = u2edge.begin();
2719 for ( int i = iFrom; i < iTo; ++i, ++u2e )
2720 _edges[i] = u2e->second;
2722 // set _2neibors according to the new order
2723 for ( int i = iFrom; i < iTo-1; ++i )
2724 if ( _edges[i]->_2neibors->_nodes[1] != _edges[i+1]->_nodes.back() )
2725 _edges[i]->_2neibors->reverse();
2726 if ( u2edge.size() > 1 &&
2727 _edges[iTo-1]->_2neibors->_nodes[0] != _edges[iTo-2]->_nodes.back() )
2728 _edges[iTo-1]->_2neibors->reverse();
2731 SMESHDS_SubMesh* smDS = helper.GetMeshDS()->MeshElements( eIndex );
2733 TopLoc_Location loc; double f,l;
2735 Handle(Geom_Line) line;
2736 Handle(Geom_Circle) circle;
2737 bool isLine, isCirc;
2738 if ( F.IsNull() ) // 3D case
2740 // check if the EDGE is a line
2741 Handle(Geom_Curve) curve = BRep_Tool::Curve( E, loc, f, l);
2742 if ( curve->IsKind( STANDARD_TYPE( Geom_TrimmedCurve )))
2743 curve = Handle(Geom_TrimmedCurve)::DownCast( curve )->BasisCurve();
2745 line = Handle(Geom_Line)::DownCast( curve );
2746 circle = Handle(Geom_Circle)::DownCast( curve );
2747 isLine = (!line.IsNull());
2748 isCirc = (!circle.IsNull());
2750 if ( !isLine && !isCirc ) // Check if the EDGE is close to a line
2753 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
2754 while ( nIt->more() )
2755 bndBox.Add( SMESH_TNodeXYZ( nIt->next() ));
2756 gp_XYZ size = bndBox.CornerMax() - bndBox.CornerMin();
2758 SMESH_TNodeXYZ p0( _edges[iFrom]->_2neibors->_nodes[0] );
2759 SMESH_TNodeXYZ p1( _edges[iFrom]->_2neibors->_nodes[1] );
2760 const double lineTol = 1e-2 * ( p0 - p1 ).Modulus();
2761 for ( int i = 0; i < 3 && !isLine; ++i )
2762 isLine = ( size.Coord( i+1 ) <= lineTol );
2764 if ( !isLine && !isCirc && iTo-iFrom > 2) // Check if the EDGE is close to a circle
2771 // check if the EDGE is a line
2772 Handle(Geom2d_Curve) curve = BRep_Tool::CurveOnSurface( E, F, f, l);
2773 if ( curve->IsKind( STANDARD_TYPE( Geom2d_TrimmedCurve )))
2774 curve = Handle(Geom2d_TrimmedCurve)::DownCast( curve )->BasisCurve();
2776 Handle(Geom2d_Line) line2d = Handle(Geom2d_Line)::DownCast( curve );
2777 Handle(Geom2d_Circle) circle2d = Handle(Geom2d_Circle)::DownCast( curve );
2778 isLine = (!line2d.IsNull());
2779 isCirc = (!circle2d.IsNull());
2781 if ( !isLine && !isCirc) // Check if the EDGE is close to a line
2784 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
2785 while ( nIt->more() )
2786 bndBox.Add( helper.GetNodeUV( F, nIt->next() ));
2787 gp_XY size = bndBox.CornerMax() - bndBox.CornerMin();
2789 const double lineTol = 1e-2 * sqrt( bndBox.SquareExtent() );
2790 for ( int i = 0; i < 2 && !isLine; ++i )
2791 isLine = ( size.Coord( i+1 ) <= lineTol );
2793 if ( !isLine && !isCirc && iTo-iFrom > 2) // Check if the EDGE is close to a circle
2799 line = new Geom_Line( gp::OX() ); // only type does matter
2803 gp_Pnt2d p = circle2d->Location();
2804 gp_Ax2 ax( gp_Pnt( p.X(), p.Y(), 0), gp::DX());
2805 circle = new Geom_Circle( ax, 1.); // only center position does matter
2809 Handle(Geom_Curve)& res = _edge2curve[ eIndex ];
2817 return i2curve->second;
2820 //================================================================================
2822 * \brief smooth _LayerEdge's on a staight EDGE or circular EDGE
2824 //================================================================================
2826 bool _ViscousBuilder::smoothAnalyticEdge( _SolidData& data,
2829 Handle(Geom_Surface)& surface,
2830 const TopoDS_Face& F,
2831 SMESH_MesherHelper& helper)
2833 TopoDS_Shape S = helper.GetSubShapeByNode( data._edges[ iFrom ]->_nodes[0],
2834 helper.GetMeshDS());
2835 TopoDS_Edge E = TopoDS::Edge( S );
2837 Handle(Geom_Curve) curve = data.CurveForSmooth( E, iFrom, iTo, surface, F, helper );
2838 if ( curve.IsNull() ) return false;
2840 // compute a relative length of segments
2841 vector< double > len( iTo-iFrom+1 );
2843 double curLen, prevLen = len[0] = 1.0;
2844 for ( int i = iFrom; i < iTo; ++i )
2846 curLen = prevLen * data._edges[i]->_2neibors->_wgt[0] / data._edges[i]->_2neibors->_wgt[1];
2847 len[i-iFrom+1] = len[i-iFrom] + curLen;
2852 if ( curve->IsKind( STANDARD_TYPE( Geom_Line )))
2854 if ( F.IsNull() ) // 3D
2856 SMESH_TNodeXYZ p0( data._edges[iFrom]->_2neibors->_nodes[0]);
2857 SMESH_TNodeXYZ p1( data._edges[iTo-1]->_2neibors->_nodes[1]);
2858 for ( int i = iFrom; i < iTo; ++i )
2860 double r = len[i-iFrom] / len.back();
2861 gp_XYZ newPos = p0 * ( 1. - r ) + p1 * r;
2862 data._edges[i]->_pos.back() = newPos;
2863 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( data._edges[i]->_nodes.back() );
2864 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
2865 dumpMove( tgtNode );
2870 gp_XY uv0 = helper.GetNodeUV( F, data._edges[iFrom]->_2neibors->_nodes[0]);
2871 gp_XY uv1 = helper.GetNodeUV( F, data._edges[iTo-1]->_2neibors->_nodes[1]);
2872 if ( data._edges[iFrom]->_2neibors->_nodes[0] ==
2873 data._edges[iTo-1]->_2neibors->_nodes[1] ) // closed edge
2875 int iPeriodic = helper.GetPeriodicIndex();
2876 if ( iPeriodic == 1 || iPeriodic == 2 )
2878 uv1.SetCoord( iPeriodic, helper.GetOtherParam( uv1.Coord( iPeriodic )));
2879 if ( uv0.Coord( iPeriodic ) > uv1.Coord( iPeriodic ))
2880 std::swap( uv0, uv1 );
2883 const gp_XY rangeUV = uv1 - uv0;
2884 for ( int i = iFrom; i < iTo; ++i )
2886 double r = len[i-iFrom] / len.back();
2887 gp_XY newUV = uv0 + r * rangeUV;
2888 data._edges[i]->_pos.back().SetCoord( newUV.X(), newUV.Y(), 0 );
2890 gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
2891 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( data._edges[i]->_nodes.back() );
2892 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
2893 dumpMove( tgtNode );
2895 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
2896 pos->SetUParameter( newUV.X() );
2897 pos->SetVParameter( newUV.Y() );
2903 if ( curve->IsKind( STANDARD_TYPE( Geom_Circle )))
2905 Handle(Geom_Circle) circle = Handle(Geom_Circle)::DownCast( curve );
2906 gp_Pnt center3D = circle->Location();
2908 if ( F.IsNull() ) // 3D
2910 if ( data._edges[iFrom]->_2neibors->_nodes[0] ==
2911 data._edges[iTo-1]->_2neibors->_nodes[1] )
2912 return true; // closed EDGE - nothing to do
2914 return false; // TODO ???
2918 const gp_XY center( center3D.X(), center3D.Y() );
2920 gp_XY uv0 = helper.GetNodeUV( F, data._edges[iFrom]->_2neibors->_nodes[0]);
2921 gp_XY uvM = helper.GetNodeUV( F, data._edges[iFrom]->_nodes.back());
2922 gp_XY uv1 = helper.GetNodeUV( F, data._edges[iTo-1]->_2neibors->_nodes[1]);
2923 gp_Vec2d vec0( center, uv0 );
2924 gp_Vec2d vecM( center, uvM );
2925 gp_Vec2d vec1( center, uv1 );
2926 double uLast = vec0.Angle( vec1 ); // -PI - +PI
2927 double uMidl = vec0.Angle( vecM );
2928 if ( uLast * uMidl < 0. )
2929 uLast += ( uMidl > 0 ? +2. : -2. ) * M_PI;
2930 const double radius = 0.5 * ( vec0.Magnitude() + vec1.Magnitude() );
2932 gp_Ax2d axis( center, vec0 );
2933 gp_Circ2d circ( axis, radius );
2934 for ( int i = iFrom; i < iTo; ++i )
2936 double newU = uLast * len[i-iFrom] / len.back();
2937 gp_Pnt2d newUV = ElCLib::Value( newU, circ );
2938 data._edges[i]->_pos.back().SetCoord( newUV.X(), newUV.Y(), 0 );
2940 gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
2941 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( data._edges[i]->_nodes.back() );
2942 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
2943 dumpMove( tgtNode );
2945 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
2946 pos->SetUParameter( newUV.X() );
2947 pos->SetVParameter( newUV.Y() );
2956 //================================================================================
2958 * \brief Modify normals of _LayerEdge's on EDGE's to avoid intersection with
2959 * _LayerEdge's on neighbor EDGE's
2961 //================================================================================
2963 bool _ViscousBuilder::updateNormals( _SolidData& data,
2964 SMESH_MesherHelper& helper )
2966 // make temporary quadrangles got by extrusion of
2967 // mesh edges along _LayerEdge._normal's
2969 vector< const SMDS_MeshElement* > tmpFaces;
2971 set< SMESH_TLink > extrudedLinks; // contains target nodes
2972 vector< const SMDS_MeshNode*> nodes(4); // of a tmp mesh face
2974 dumpFunction(SMESH_Comment("makeTmpFacesOnEdges")<<data._index);
2975 for ( size_t i = 0; i < data._edges.size(); ++i )
2977 _LayerEdge* edge = data._edges[i];
2978 if ( !edge->IsOnEdge() || !edge->_sWOL.IsNull() ) continue;
2979 const SMDS_MeshNode* tgt1 = edge->_nodes.back();
2980 for ( int j = 0; j < 2; ++j ) // loop on _2NearEdges
2982 const SMDS_MeshNode* tgt2 = edge->_2neibors->_nodes[j];
2983 pair< set< SMESH_TLink >::iterator, bool > link_isnew =
2984 extrudedLinks.insert( SMESH_TLink( tgt1, tgt2 ));
2985 if ( !link_isnew.second )
2987 extrudedLinks.erase( link_isnew.first );
2988 continue; // already extruded and will no more encounter
2990 // look for a _LayerEdge containg tgt2
2991 // _LayerEdge* neiborEdge = 0;
2992 // size_t di = 0; // check _edges[i+di] and _edges[i-di]
2993 // while ( !neiborEdge && ++di <= data._edges.size() )
2995 // if ( i+di < data._edges.size() && data._edges[i+di]->_nodes.back() == tgt2 )
2996 // neiborEdge = data._edges[i+di];
2997 // else if ( di <= i && data._edges[i-di]->_nodes.back() == tgt2 )
2998 // neiborEdge = data._edges[i-di];
3000 // if ( !neiborEdge )
3001 // return error("updateNormals(): neighbor _LayerEdge not found", data._index);
3002 _LayerEdge* neiborEdge = edge->_2neibors->_edges[j];
3004 TmpMeshFaceOnEdge* f = new TmpMeshFaceOnEdge( edge, neiborEdge, --_tmpFaceID );
3005 tmpFaces.push_back( f );
3007 dumpCmd(SMESH_Comment("mesh.AddFace([ ")
3008 <<f->_nn[0]->GetID()<<", "<<f->_nn[1]->GetID()<<", "
3009 <<f->_nn[2]->GetID()<<", "<<f->_nn[3]->GetID()<<" ])");
3014 // Check if _LayerEdge's based on EDGE's intersects tmpFaces.
3015 // Perform two loops on _LayerEdge on EDGE's:
3016 // 1) to find and fix intersection
3017 // 2) to check that no new intersection appears as result of 1)
3019 SMDS_ElemIteratorPtr fIt( new SMDS_ElementVectorIterator( tmpFaces.begin(),
3021 auto_ptr<SMESH_ElementSearcher> searcher
3022 ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(), fIt ));
3024 // 1) Find intersections
3026 const SMDS_MeshElement* face;
3027 typedef map< _LayerEdge*, set< _LayerEdge*, _LayerEdgeCmp >, _LayerEdgeCmp > TLEdge2LEdgeSet;
3028 TLEdge2LEdgeSet edge2CloseEdge;
3030 const double eps = data._epsilon * data._epsilon;
3031 for ( size_t i = 0; i < data._edges.size(); ++i )
3033 _LayerEdge* edge = data._edges[i];
3034 if ( !edge->IsOnEdge() || !edge->_sWOL.IsNull() ) continue;
3035 if ( edge->FindIntersection( *searcher, dist, eps, &face ))
3037 const TmpMeshFaceOnEdge* f = (const TmpMeshFaceOnEdge*) face;
3038 set< _LayerEdge*, _LayerEdgeCmp > & ee = edge2CloseEdge[ edge ];
3039 ee.insert( f->_le1 );
3040 ee.insert( f->_le2 );
3041 if ( f->_le1->IsOnEdge() && f->_le1->_sWOL.IsNull() )
3042 edge2CloseEdge[ f->_le1 ].insert( edge );
3043 if ( f->_le2->IsOnEdge() && f->_le2->_sWOL.IsNull() )
3044 edge2CloseEdge[ f->_le2 ].insert( edge );
3048 // Set _LayerEdge._normal
3050 if ( !edge2CloseEdge.empty() )
3052 dumpFunction(SMESH_Comment("updateNormals")<<data._index);
3054 TLEdge2LEdgeSet::iterator e2ee = edge2CloseEdge.begin();
3055 for ( ; e2ee != edge2CloseEdge.end(); ++e2ee )
3057 _LayerEdge* edge1 = e2ee->first;
3058 _LayerEdge* edge2 = 0;
3059 set< _LayerEdge*, _LayerEdgeCmp >& ee = e2ee->second;
3061 // find EDGEs the edges reside
3063 TopoDS_Shape S = helper.GetSubShapeByNode( edge1->_nodes[0], getMeshDS() );
3064 if ( S.ShapeType() != TopAbs_EDGE )
3065 continue; // TODO: find EDGE by VERTEX
3066 E1 = TopoDS::Edge( S );
3067 set< _LayerEdge*, _LayerEdgeCmp >::iterator eIt = ee.begin();
3068 while ( E2.IsNull() && eIt != ee.end())
3070 _LayerEdge* e2 = *eIt++;
3071 TopoDS_Shape S = helper.GetSubShapeByNode( e2->_nodes[0], getMeshDS() );
3072 if ( S.ShapeType() == TopAbs_EDGE )
3073 E2 = TopoDS::Edge( S ), edge2 = e2;
3075 if ( E2.IsNull() ) continue; // TODO: find EDGE by VERTEX
3077 // find 3 FACEs sharing 2 EDGEs
3079 TopoDS_Face FF1[2], FF2[2];
3080 PShapeIteratorPtr fIt = helper.GetAncestors(E1, *_mesh, TopAbs_FACE);
3081 while ( fIt->more() && FF1[1].IsNull())
3083 const TopoDS_Face *F = (const TopoDS_Face*) fIt->next();
3084 if ( helper.IsSubShape( *F, data._solid))
3085 FF1[ FF1[0].IsNull() ? 0 : 1 ] = *F;
3087 fIt = helper.GetAncestors(E2, *_mesh, TopAbs_FACE);
3088 while ( fIt->more() && FF2[1].IsNull())
3090 const TopoDS_Face *F = (const TopoDS_Face*) fIt->next();
3091 if ( helper.IsSubShape( *F, data._solid))
3092 FF2[ FF2[0].IsNull() ? 0 : 1 ] = *F;
3094 // exclude a FACE common to E1 and E2 (put it at [1] in FF* )
3095 if ( FF1[0].IsSame( FF2[0]) || FF1[0].IsSame( FF2[1]))
3096 std::swap( FF1[0], FF1[1] );
3097 if ( FF2[0].IsSame( FF1[0]) )
3098 std::swap( FF2[0], FF2[1] );
3099 if ( FF1[0].IsNull() || FF2[0].IsNull() )
3102 // // get a new normal for edge1
3104 gp_Vec dir1 = edge1->_normal, dir2 = edge2->_normal;
3105 if ( edge1->_cosin < 0 )
3106 dir1 = getFaceDir( FF1[0], E1, edge1->_nodes[0], helper, ok ).Normalized();
3107 if ( edge2->_cosin < 0 )
3108 dir2 = getFaceDir( FF2[0], E2, edge2->_nodes[0], helper, ok ).Normalized();
3109 // gp_Vec dir1 = getFaceDir( FF1[0], E1, edge1->_nodes[0], helper, ok );
3110 // gp_Vec dir2 = getFaceDir( FF2[0], E2, edge2->_nodes[0], helper, ok2 );
3111 // double wgt1 = ( edge1->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
3112 // double wgt2 = ( edge2->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
3113 // gp_Vec newNorm = wgt1 * dir1 + wgt2 * dir2;
3114 // newNorm.Normalize();
3116 double wgt1 = ( edge1->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
3117 double wgt2 = ( edge2->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
3118 gp_Vec newNorm = wgt1 * dir1 + wgt2 * dir2;
3119 newNorm.Normalize();
3121 edge1->_normal = newNorm.XYZ();
3123 // update data of edge1 depending on _normal
3124 const SMDS_MeshNode *n1, *n2;
3125 n1 = edge1->_2neibors->_edges[0]->_nodes[0];
3126 n2 = edge1->_2neibors->_edges[1]->_nodes[0];
3127 //if ( !findNeiborsOnEdge( edge1, n1, n2, data ))
3129 edge1->SetDataByNeighbors( n1, n2, helper );
3131 if ( edge1->_cosin < 0 )
3134 getFaceDir( FF1[0], E1, edge1->_nodes[0], helper, ok );
3135 double angle = dir1.Angle( edge1->_normal ); // [0,PI]
3136 edge1->SetCosin( cos( angle ));
3138 // limit data._stepSize
3139 if ( edge1->_cosin > 0.1 )
3141 SMDS_ElemIteratorPtr fIt = edge1->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
3142 while ( fIt->more() )
3143 limitStepSize( data, fIt->next(), edge1->_cosin );
3145 // set new XYZ of target node
3146 edge1->InvalidateStep( 1 );
3148 edge1->SetNewLength( data._stepSize, helper );
3151 // Update normals and other dependent data of not intersecting _LayerEdge's
3152 // neighboring the intersecting ones
3154 for ( e2ee = edge2CloseEdge.begin(); e2ee != edge2CloseEdge.end(); ++e2ee )
3156 _LayerEdge* edge1 = e2ee->first;
3157 if ( !edge1->_2neibors )
3159 for ( int j = 0; j < 2; ++j ) // loop on 2 neighbors
3161 _LayerEdge* neighbor = edge1->_2neibors->_edges[j];
3162 if ( edge2CloseEdge.count ( neighbor ))
3163 continue; // j-th neighbor is also intersected
3164 _LayerEdge* prevEdge = edge1;
3165 const int nbSteps = 6;
3166 for ( int step = nbSteps; step; --step ) // step from edge1 in j-th direction
3168 if ( !neighbor->_2neibors )
3169 break; // neighbor is on VERTEX
3171 _LayerEdge* nextEdge = neighbor->_2neibors->_edges[iNext];
3172 if ( nextEdge == prevEdge )
3173 nextEdge = neighbor->_2neibors->_edges[ ++iNext ];
3174 // const double& wgtPrev = neighbor->_2neibors->_wgt[1-iNext];
3175 // const double& wgtNext = neighbor->_2neibors->_wgt[iNext];
3176 double r = double(step-1)/nbSteps;
3177 if ( !nextEdge->_2neibors )
3180 gp_XYZ newNorm = prevEdge->_normal * r + nextEdge->_normal * (1-r);
3181 newNorm.Normalize();
3183 neighbor->_normal = newNorm;
3184 neighbor->SetCosin( prevEdge->_cosin * r + nextEdge->_cosin * (1-r) );
3185 neighbor->SetDataByNeighbors( prevEdge->_nodes[0], nextEdge->_nodes[0], helper );
3187 neighbor->InvalidateStep( 1 );
3189 neighbor->SetNewLength( data._stepSize, helper );
3191 // goto the next neighbor
3192 prevEdge = neighbor;
3193 neighbor = nextEdge;
3199 // 2) Check absence of intersections
3202 for ( size_t i = 0 ; i < tmpFaces.size(); ++i )
3208 //================================================================================
3210 * \brief Looks for intersection of it's last segment with faces
3211 * \param distance - returns shortest distance from the last node to intersection
3213 //================================================================================
3215 bool _LayerEdge::FindIntersection( SMESH_ElementSearcher& searcher,
3217 const double& epsilon,
3218 const SMDS_MeshElement** face)
3220 vector< const SMDS_MeshElement* > suspectFaces;
3222 gp_Ax1 lastSegment = LastSegment(segLen);
3223 searcher.GetElementsNearLine( lastSegment, SMDSAbs_Face, suspectFaces );
3225 bool segmentIntersected = false;
3226 distance = Precision::Infinite();
3227 int iFace = -1; // intersected face
3228 for ( size_t j = 0 ; j < suspectFaces.size() && !segmentIntersected; ++j )
3230 const SMDS_MeshElement* face = suspectFaces[j];
3231 if ( face->GetNodeIndex( _nodes.back() ) >= 0 ||
3232 face->GetNodeIndex( _nodes[0] ) >= 0 )
3233 continue; // face sharing _LayerEdge node
3234 const int nbNodes = face->NbCornerNodes();
3235 bool intFound = false;
3237 SMDS_MeshElement::iterator nIt = face->begin_nodes();
3240 intFound = SegTriaInter( lastSegment, *nIt++, *nIt++, *nIt++, dist, epsilon );
3244 const SMDS_MeshNode* tria[3];
3247 for ( int n2 = 2; n2 < nbNodes && !intFound; ++n2 )
3250 intFound = SegTriaInter(lastSegment, tria[0], tria[1], tria[2], dist, epsilon );
3256 if ( dist < segLen*(1.01) && dist > -(_len-segLen) )
3257 segmentIntersected = true;
3258 if ( distance > dist )
3259 distance = dist, iFace = j;
3262 if ( iFace != -1 && face ) *face = suspectFaces[iFace];
3263 // if ( distance && iFace > -1 )
3265 // // distance is used to limit size of inflation step which depends on
3266 // // whether the intersected face bears viscous layers or not
3267 // bool faceHasVL = suspectFaces[iFace]->GetID() < 1;
3271 if ( segmentIntersected )
3274 SMDS_MeshElement::iterator nIt = suspectFaces[iFace]->begin_nodes();
3275 gp_XYZ intP( lastSegment.Location().XYZ() + lastSegment.Direction().XYZ() * distance );
3276 cout << "nodes: tgt " << _nodes.back()->GetID() << " src " << _nodes[0]->GetID()
3277 << ", intersection with face ("
3278 << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
3279 << ") at point (" << intP.X() << ", " << intP.Y() << ", " << intP.Z()
3280 << ") distance = " << distance - segLen<< endl;
3286 return segmentIntersected;
3289 //================================================================================
3291 * \brief Returns size and direction of the last segment
3293 //================================================================================
3295 gp_Ax1 _LayerEdge::LastSegment(double& segLen) const
3297 // find two non-coincident positions
3298 gp_XYZ orig = _pos.back();
3300 int iPrev = _pos.size() - 2;
3301 while ( iPrev >= 0 )
3303 dir = orig - _pos[iPrev];
3304 if ( dir.SquareModulus() > 1e-100 )
3314 segDir.SetLocation( SMESH_TNodeXYZ( _nodes[0] ));
3315 segDir.SetDirection( _normal );
3320 gp_Pnt pPrev = _pos[ iPrev ];
3321 if ( !_sWOL.IsNull() )
3323 TopLoc_Location loc;
3324 if ( _sWOL.ShapeType() == TopAbs_EDGE )
3327 Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( _sWOL ), loc, f,l);
3328 pPrev = curve->Value( pPrev.X() ).Transformed( loc );
3332 Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face(_sWOL), loc );
3333 pPrev = surface->Value( pPrev.X(), pPrev.Y() ).Transformed( loc );
3335 dir = SMESH_TNodeXYZ( _nodes.back() ) - pPrev.XYZ();
3337 segDir.SetLocation( pPrev );
3338 segDir.SetDirection( dir );
3339 segLen = dir.Modulus();
3345 //================================================================================
3347 * \brief Test intersection of the last segment with a given triangle
3348 * using Moller-Trumbore algorithm
3349 * Intersection is detected if distance to intersection is less than _LayerEdge._len
3351 //================================================================================
3353 bool _LayerEdge::SegTriaInter( const gp_Ax1& lastSegment,
3354 const SMDS_MeshNode* n0,
3355 const SMDS_MeshNode* n1,
3356 const SMDS_MeshNode* n2,
3358 const double& EPSILON) const
3360 //const double EPSILON = 1e-6;
3362 gp_XYZ orig = lastSegment.Location().XYZ();
3363 gp_XYZ dir = lastSegment.Direction().XYZ();
3365 SMESH_TNodeXYZ vert0( n0 );
3366 SMESH_TNodeXYZ vert1( n1 );
3367 SMESH_TNodeXYZ vert2( n2 );
3369 /* calculate distance from vert0 to ray origin */
3370 gp_XYZ tvec = orig - vert0;
3372 if ( tvec * dir > EPSILON )
3373 // intersected face is at back side of the temporary face this _LayerEdge belongs to
3376 gp_XYZ edge1 = vert1 - vert0;
3377 gp_XYZ edge2 = vert2 - vert0;
3379 /* begin calculating determinant - also used to calculate U parameter */
3380 gp_XYZ pvec = dir ^ edge2;
3382 /* if determinant is near zero, ray lies in plane of triangle */
3383 double det = edge1 * pvec;
3385 if (det > -EPSILON && det < EPSILON)
3387 double inv_det = 1.0 / det;
3389 /* calculate U parameter and test bounds */
3390 double u = ( tvec * pvec ) * inv_det;
3391 if (u < 0.0 || u > 1.0)
3394 /* prepare to test V parameter */
3395 gp_XYZ qvec = tvec ^ edge1;
3397 /* calculate V parameter and test bounds */
3398 double v = (dir * qvec) * inv_det;
3399 if ( v < 0.0 || u + v > 1.0 )
3402 /* calculate t, ray intersects triangle */
3403 t = (edge2 * qvec) * inv_det;
3405 // if (det < EPSILON)
3408 // /* calculate distance from vert0 to ray origin */
3409 // gp_XYZ tvec = orig - vert0;
3411 // /* calculate U parameter and test bounds */
3412 // double u = tvec * pvec;
3413 // if (u < 0.0 || u > det)
3416 // /* prepare to test V parameter */
3417 // gp_XYZ qvec = tvec ^ edge1;
3419 // /* calculate V parameter and test bounds */
3420 // double v = dir * qvec;
3421 // if (v < 0.0 || u + v > det)
3424 // /* calculate t, scale parameters, ray intersects triangle */
3425 // double t = edge2 * qvec;
3426 // double inv_det = 1.0 / det;
3434 //================================================================================
3436 * \brief Perform smooth of _LayerEdge's based on EDGE's
3437 * \retval bool - true if node has been moved
3439 //================================================================================
3441 bool _LayerEdge::SmoothOnEdge(Handle(Geom_Surface)& surface,
3442 const TopoDS_Face& F,
3443 SMESH_MesherHelper& helper)
3445 ASSERT( IsOnEdge() );
3447 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _nodes.back() );
3448 SMESH_TNodeXYZ oldPos( tgtNode );
3449 double dist01, distNewOld;
3451 SMESH_TNodeXYZ p0( _2neibors->_nodes[0]);
3452 SMESH_TNodeXYZ p1( _2neibors->_nodes[1]);
3453 dist01 = p0.Distance( _2neibors->_nodes[1] );
3455 gp_Pnt newPos = p0 * _2neibors->_wgt[0] + p1 * _2neibors->_wgt[1];
3456 double lenDelta = 0;
3459 //lenDelta = _curvature->lenDelta( _len );
3460 lenDelta = _curvature->lenDeltaByDist( dist01 );
3461 newPos.ChangeCoord() += _normal * lenDelta;
3464 distNewOld = newPos.Distance( oldPos );
3468 if ( _2neibors->_plnNorm )
3470 // put newPos on the plane defined by source node and _plnNorm
3471 gp_XYZ new2src = SMESH_TNodeXYZ( _nodes[0] ) - newPos.XYZ();
3472 double new2srcProj = (*_2neibors->_plnNorm) * new2src;
3473 newPos.ChangeCoord() += (*_2neibors->_plnNorm) * new2srcProj;
3475 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
3476 _pos.back() = newPos.XYZ();
3480 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
3481 gp_XY uv( Precision::Infinite(), 0 );
3482 helper.CheckNodeUV( F, tgtNode, uv, 1e-10, /*force=*/true );
3483 _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
3485 newPos = surface->Value( uv.X(), uv.Y() );
3486 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
3489 if ( _curvature && lenDelta < 0 )
3491 gp_Pnt prevPos( _pos[ _pos.size()-2 ]);
3492 _len -= prevPos.Distance( oldPos );
3493 _len += prevPos.Distance( newPos );
3495 bool moved = distNewOld > dist01/50;
3497 dumpMove( tgtNode ); // debug
3502 //================================================================================
3504 * \brief Perform laplacian smooth in 3D of nodes inflated from FACE
3505 * \retval bool - true if _tgtNode has been moved
3507 //================================================================================
3509 bool _LayerEdge::Smooth(int& badNb)
3511 if ( _simplices.size() < 2 )
3512 return false; // _LayerEdge inflated along EDGE or FACE
3514 // compute new position for the last _pos
3515 gp_XYZ newPos (0,0,0);
3516 for ( size_t i = 0; i < _simplices.size(); ++i )
3517 newPos += SMESH_TNodeXYZ( _simplices[i]._nPrev );
3518 newPos /= _simplices.size();
3521 newPos += _normal * _curvature->lenDelta( _len );
3523 gp_Pnt prevPos( _pos[ _pos.size()-2 ]);
3524 // if ( _cosin < -0.1)
3526 // // Avoid decreasing length of edge on concave surface
3527 // //gp_Vec oldMove( _pos[ _pos.size()-2 ], _pos.back() );
3528 // gp_Vec newMove( prevPos, newPos );
3529 // newPos = _pos.back() + newMove.XYZ();
3531 // else if ( _cosin > 0.3 )
3533 // // Avoid increasing length of edge too much
3536 // count quality metrics (orientation) of tetras around _tgtNode
3538 SMESH_TNodeXYZ tgtXYZ( _nodes.back() );
3539 for ( size_t i = 0; i < _simplices.size(); ++i )
3540 nbOkBefore += _simplices[i].IsForward( _nodes[0], &tgtXYZ );
3543 for ( size_t i = 0; i < _simplices.size(); ++i )
3544 nbOkAfter += _simplices[i].IsForward( _nodes[0], &newPos );
3546 if ( nbOkAfter < nbOkBefore )
3549 SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
3551 _len -= prevPos.Distance(SMESH_TNodeXYZ( n ));
3552 _len += prevPos.Distance(newPos);
3554 n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
3555 _pos.back() = newPos;
3557 badNb += _simplices.size() - nbOkAfter;
3564 //================================================================================
3566 * \brief Add a new segment to _LayerEdge during inflation
3568 //================================================================================
3570 void _LayerEdge::SetNewLength( double len, SMESH_MesherHelper& helper )
3572 if ( _len - len > -1e-6 )
3574 _pos.push_back( _pos.back() );
3578 SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
3579 SMESH_TNodeXYZ oldXYZ( n );
3580 gp_XYZ nXYZ = oldXYZ + _normal * ( len - _len ) * _lenFactor;
3581 n->setXYZ( nXYZ.X(), nXYZ.Y(), nXYZ.Z() );
3583 _pos.push_back( nXYZ );
3585 if ( !_sWOL.IsNull() )
3588 if ( _sWOL.ShapeType() == TopAbs_EDGE )
3590 double u = Precision::Infinite(); // to force projection w/o distance check
3591 helper.CheckNodeU( TopoDS::Edge( _sWOL ), n, u, 1e-10, /*force=*/true, distXYZ );
3592 _pos.back().SetCoord( u, 0, 0 );
3593 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( n->GetPosition() );
3594 pos->SetUParameter( u );
3598 gp_XY uv( Precision::Infinite(), 0 );
3599 helper.CheckNodeUV( TopoDS::Face( _sWOL ), n, uv, 1e-10, /*force=*/true, distXYZ );
3600 _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
3601 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( n->GetPosition() );
3602 pos->SetUParameter( uv.X() );
3603 pos->SetVParameter( uv.Y() );
3605 n->setXYZ( distXYZ[1], distXYZ[2], distXYZ[3]);
3607 dumpMove( n ); //debug
3610 //================================================================================
3612 * \brief Remove last inflation step
3614 //================================================================================
3616 void _LayerEdge::InvalidateStep( int curStep )
3618 if ( _pos.size() > curStep )
3620 _pos.resize( curStep );
3621 gp_Pnt nXYZ = _pos.back();
3622 SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
3623 if ( !_sWOL.IsNull() )
3625 TopLoc_Location loc;
3626 if ( _sWOL.ShapeType() == TopAbs_EDGE )
3628 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( n->GetPosition() );
3629 pos->SetUParameter( nXYZ.X() );
3631 Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( _sWOL ), loc, f,l);
3632 nXYZ = curve->Value( nXYZ.X() ).Transformed( loc );
3636 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( n->GetPosition() );
3637 pos->SetUParameter( nXYZ.X() );
3638 pos->SetVParameter( nXYZ.Y() );
3639 Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face(_sWOL), loc );
3640 nXYZ = surface->Value( nXYZ.X(), nXYZ.Y() ).Transformed( loc );
3643 n->setXYZ( nXYZ.X(), nXYZ.Y(), nXYZ.Z() );
3648 //================================================================================
3650 * \brief Create layers of prisms
3652 //================================================================================
3654 bool _ViscousBuilder::refine(_SolidData& data)
3656 SMESH_MesherHelper helper( *_mesh );
3657 helper.SetSubShape( data._solid );
3658 helper.SetElementsOnShape(false);
3660 Handle(Geom_Curve) curve;
3661 Handle(Geom_Surface) surface;
3662 TopoDS_Edge geomEdge;
3663 TopoDS_Face geomFace;
3664 TopLoc_Location loc;
3665 double f,l, u/*, distXYZ[4]*/;
3669 for ( size_t i = 0; i < data._edges.size(); ++i )
3671 _LayerEdge& edge = *data._edges[i];
3673 // get accumulated length of segments
3674 vector< double > segLen( edge._pos.size() );
3676 for ( size_t j = 1; j < edge._pos.size(); ++j )
3677 segLen[j] = segLen[j-1] + (edge._pos[j-1] - edge._pos[j] ).Modulus();
3679 // allocate memory for new nodes if it is not yet refined
3680 const SMDS_MeshNode* tgtNode = edge._nodes.back();
3681 if ( edge._nodes.size() == 2 )
3683 edge._nodes.resize( data._hyp->GetNumberLayers() + 1, 0 );
3685 edge._nodes.back() = tgtNode;
3687 if ( !edge._sWOL.IsNull() )
3689 isOnEdge = ( edge._sWOL.ShapeType() == TopAbs_EDGE );
3690 // restore position of the last node
3694 geomEdge = TopoDS::Edge( edge._sWOL );
3695 curve = BRep_Tool::Curve( geomEdge, loc, f,l);
3696 // double u = helper.GetNodeU( tgtNode );
3697 // p = curve->Value( u );
3701 geomFace = TopoDS::Face( edge._sWOL );
3702 surface = BRep_Tool::Surface( geomFace, loc );
3703 // gp_XY uv = helper.GetNodeUV( tgtNode );
3704 // p = surface->Value( uv.X(), uv.Y() );
3706 // p.Transform( loc );
3707 // const_cast< SMDS_MeshNode* >( tgtNode )->setXYZ( p.X(), p.Y(), p.Z() );
3709 // calculate height of the first layer
3711 const double T = segLen.back(); //data._hyp.GetTotalThickness();
3712 const double f = data._hyp->GetStretchFactor();
3713 const int N = data._hyp->GetNumberLayers();
3714 const double fPowN = pow( f, N );
3715 if ( fPowN - 1 <= numeric_limits<double>::min() )
3718 h0 = T * ( f - 1 )/( fPowN - 1 );
3720 const double zeroLen = std::numeric_limits<double>::min();
3722 // create intermediate nodes
3723 double hSum = 0, hi = h0/f;
3725 for ( size_t iStep = 1; iStep < edge._nodes.size(); ++iStep )
3727 // compute an intermediate position
3730 while ( hSum > segLen[iSeg] && iSeg < segLen.size()-1)
3732 int iPrevSeg = iSeg-1;
3733 while ( fabs( segLen[iPrevSeg] - segLen[iSeg]) <= zeroLen && iPrevSeg > 0 )
3735 double r = ( segLen[iSeg] - hSum ) / ( segLen[iSeg] - segLen[iPrevSeg] );
3736 gp_Pnt pos = r * edge._pos[iPrevSeg] + (1-r) * edge._pos[iSeg];
3738 SMDS_MeshNode*& node = const_cast< SMDS_MeshNode*& >(edge._nodes[ iStep ]);
3739 if ( !edge._sWOL.IsNull() )
3741 // compute XYZ by parameters <pos>
3745 pos = curve->Value( u ).Transformed(loc);
3749 uv.SetCoord( pos.X(), pos.Y() );
3750 pos = surface->Value( pos.X(), pos.Y() ).Transformed(loc);
3753 // create or update the node
3756 node = helper.AddNode( pos.X(), pos.Y(), pos.Z());
3757 if ( !edge._sWOL.IsNull() )
3760 getMeshDS()->SetNodeOnEdge( node, geomEdge, u );
3762 getMeshDS()->SetNodeOnFace( node, geomFace, uv.X(), uv.Y() );
3766 getMeshDS()->SetNodeInVolume( node, helper.GetSubShapeID() );
3771 if ( !edge._sWOL.IsNull() )
3773 // make average pos from new and current parameters
3776 u = 0.5 * ( u + helper.GetNodeU( geomEdge, node ));
3777 pos = curve->Value( u ).Transformed(loc);
3781 uv = 0.5 * ( uv + helper.GetNodeUV( geomFace, node ));
3782 pos = surface->Value( uv.X(), uv.Y()).Transformed(loc);
3785 node->setXYZ( pos.X(), pos.Y(), pos.Z() );
3790 if ( !getMeshDS()->IsEmbeddedMode() )
3791 // Log node movement
3792 for ( size_t i = 0; i < data._edges.size(); ++i )
3794 _LayerEdge& edge = *data._edges[i];
3795 SMESH_TNodeXYZ p ( edge._nodes.back() );
3796 getMeshDS()->MoveNode( p._node, p.X(), p.Y(), p.Z() );
3799 // TODO: make quadratic prisms and polyhedrons(?)
3801 helper.SetElementsOnShape(true);
3803 TopExp_Explorer exp( data._solid, TopAbs_FACE );
3804 for ( ; exp.More(); exp.Next() )
3806 if ( data._ignoreFaceIds.count( getMeshDS()->ShapeToIndex( exp.Current() )))
3808 SMESHDS_SubMesh* fSubM = getMeshDS()->MeshElements( exp.Current() );
3809 SMDS_ElemIteratorPtr fIt = fSubM->GetElements();
3810 vector< vector<const SMDS_MeshNode*>* > nnVec;
3811 while ( fIt->more() )
3813 const SMDS_MeshElement* face = fIt->next();
3814 int nbNodes = face->NbCornerNodes();
3815 nnVec.resize( nbNodes );
3816 SMDS_ElemIteratorPtr nIt = face->nodesIterator();
3817 for ( int iN = 0; iN < nbNodes; ++iN )
3819 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
3820 nnVec[ iN ] = & data._n2eMap[ n ]->_nodes;
3823 int nbZ = nnVec[0]->size();
3827 for ( int iZ = 1; iZ < nbZ; ++iZ )
3828 helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1], (*nnVec[2])[iZ-1],
3829 (*nnVec[0])[iZ], (*nnVec[1])[iZ], (*nnVec[2])[iZ]);
3832 for ( int iZ = 1; iZ < nbZ; ++iZ )
3833 helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1],
3834 (*nnVec[2])[iZ-1], (*nnVec[3])[iZ-1],
3835 (*nnVec[0])[iZ], (*nnVec[1])[iZ],
3836 (*nnVec[2])[iZ], (*nnVec[3])[iZ]);
3839 return error("Not supported type of element", data._index);
3846 //================================================================================
3848 * \brief Shrink 2D mesh on faces to let space for inflated layers
3850 //================================================================================
3852 bool _ViscousBuilder::shrink()
3854 // make map of (ids of FACEs to shrink mesh on) to (_SolidData containing _LayerEdge's
3855 // inflated along FACE or EDGE)
3856 map< TGeomID, _SolidData* > f2sdMap;
3857 for ( size_t i = 0 ; i < _sdVec.size(); ++i )
3859 _SolidData& data = _sdVec[i];
3860 TopTools_MapOfShape FFMap;
3861 map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
3862 for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
3863 if ( s2s->second.ShapeType() == TopAbs_FACE )
3865 f2sdMap.insert( make_pair( getMeshDS()->ShapeToIndex( s2s->second ), &data ));
3867 if ( FFMap.Add( (*s2s).second ))
3868 // Put mesh faces on the shrinked FACE to the proxy sub-mesh to avoid
3869 // usage of mesh faces made in addBoundaryElements() by the 3D algo or
3870 // by StdMeshers_QuadToTriaAdaptor
3871 if ( SMESHDS_SubMesh* smDS = getMeshDS()->MeshElements( s2s->second ))
3873 SMESH_ProxyMesh::SubMesh* proxySub =
3874 data._proxyMesh->getFaceSubM( TopoDS::Face( s2s->second ), /*create=*/true);
3875 SMDS_ElemIteratorPtr fIt = smDS->GetElements();
3876 while ( fIt->more() )
3877 proxySub->AddElement( fIt->next() );
3878 // as a result 3D algo will use elements from proxySub and not from smDS
3883 SMESH_MesherHelper helper( *_mesh );
3884 helper.ToFixNodeParameters( true );
3887 map< TGeomID, _Shrinker1D > e2shrMap;
3889 // loop on FACES to srink mesh on
3890 map< TGeomID, _SolidData* >::iterator f2sd = f2sdMap.begin();
3891 for ( ; f2sd != f2sdMap.end(); ++f2sd )
3893 _SolidData& data = *f2sd->second;
3894 TNode2Edge& n2eMap = data._n2eMap;
3895 const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( f2sd->first ));
3897 Handle(Geom_Surface) surface = BRep_Tool::Surface(F);
3899 SMESH_subMesh* sm = _mesh->GetSubMesh( F );
3900 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
3902 helper.SetSubShape(F);
3904 // ===========================
3905 // Prepare data for shrinking
3906 // ===========================
3908 // Collect nodes to smooth, as src nodes are not yet replaced by tgt ones
3909 // and thus all nodes on a FACE connected to 2d elements are to be smoothed
3910 vector < const SMDS_MeshNode* > smoothNodes;
3912 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
3913 while ( nIt->more() )
3915 const SMDS_MeshNode* n = nIt->next();
3916 if ( n->NbInverseElements( SMDSAbs_Face ) > 0 )
3917 smoothNodes.push_back( n );
3920 // Find out face orientation
3922 const set<TGeomID> ignoreShapes;
3924 if ( !smoothNodes.empty() )
3926 vector<_Simplex> simplices;
3927 getSimplices( smoothNodes[0], simplices, ignoreShapes );
3928 helper.GetNodeUV( F, simplices[0]._nPrev, 0, &isOkUV ); // fix UV of silpmex nodes
3929 helper.GetNodeUV( F, simplices[0]._nNext, 0, &isOkUV );
3930 gp_XY uv = helper.GetNodeUV( F, smoothNodes[0], 0, &isOkUV );
3931 if ( !simplices[0].IsForward(uv, smoothNodes[0], F, helper,refSign) )
3935 // Find _LayerEdge's inflated along F
3936 vector< _LayerEdge* > lEdges;
3938 SMESH_subMeshIteratorPtr subIt =
3939 sm->getDependsOnIterator(/*includeSelf=*/false, /*complexShapeFirst=*/false);
3940 while ( subIt->more() )
3942 SMESH_subMesh* sub = subIt->next();
3943 SMESHDS_SubMesh* subDS = sub->GetSubMeshDS();
3944 if ( subDS->NbNodes() == 0 || !n2eMap.count( subDS->GetNodes()->next() ))
3946 SMDS_NodeIteratorPtr nIt = subDS->GetNodes();
3947 while ( nIt->more() )
3949 _LayerEdge* edge = n2eMap[ nIt->next() ];
3950 lEdges.push_back( edge );
3951 prepareEdgeToShrink( *edge, F, helper, smDS );
3956 dumpFunction(SMESH_Comment("beforeShrinkFace")<<f2sd->first); // debug
3957 SMDS_ElemIteratorPtr fIt = smDS->GetElements();
3958 while ( fIt->more() )
3959 if ( const SMDS_MeshElement* f = fIt->next() )
3960 dumpChangeNodes( f );
3962 // Replace source nodes by target nodes in mesh faces to shrink
3963 const SMDS_MeshNode* nodes[20];
3964 for ( size_t i = 0; i < lEdges.size(); ++i )
3966 _LayerEdge& edge = *lEdges[i];
3967 const SMDS_MeshNode* srcNode = edge._nodes[0];
3968 const SMDS_MeshNode* tgtNode = edge._nodes.back();
3969 SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
3970 while ( fIt->more() )
3972 const SMDS_MeshElement* f = fIt->next();
3973 if ( !smDS->Contains( f ))
3975 SMDS_NodeIteratorPtr nIt = f->nodeIterator();
3976 for ( int iN = 0; nIt->more(); ++iN )
3978 const SMDS_MeshNode* n = nIt->next();
3979 nodes[iN] = ( n == srcNode ? tgtNode : n );
3981 helper.GetMeshDS()->ChangeElementNodes( f, nodes, f->NbNodes() );
3985 // find out if a FACE is concave
3986 const bool isConcaveFace = isConcave( F, helper );
3988 // Create _SmoothNode's on face F
3989 vector< _SmoothNode > nodesToSmooth( smoothNodes.size() );
3991 const bool sortSimplices = isConcaveFace;
3992 for ( size_t i = 0; i < smoothNodes.size(); ++i )
3994 const SMDS_MeshNode* n = smoothNodes[i];
3995 nodesToSmooth[ i ]._node = n;
3996 // src nodes must be replaced by tgt nodes to have tgt nodes in _simplices
3997 getSimplices( n, nodesToSmooth[ i ]._simplices, ignoreShapes, NULL, sortSimplices );
3998 // fix up incorrect uv of nodes on the FACE
3999 helper.GetNodeUV( F, n, 0, &isOkUV);
4003 //if ( nodesToSmooth.empty() ) continue;
4005 // Find EDGE's to shrink and set simpices to LayerEdge's
4006 set< _Shrinker1D* > eShri1D;
4008 for ( size_t i = 0; i < lEdges.size(); ++i )
4010 _LayerEdge* edge = lEdges[i];
4011 if ( edge->_sWOL.ShapeType() == TopAbs_EDGE )
4013 TGeomID edgeIndex = getMeshDS()->ShapeToIndex( edge->_sWOL );
4014 _Shrinker1D& srinker = e2shrMap[ edgeIndex ];
4015 eShri1D.insert( & srinker );
4016 srinker.AddEdge( edge, helper );
4017 VISCOUS_3D::ToClearSubWithMain( _mesh->GetSubMesh( edge->_sWOL ), data._solid );
4018 // restore params of nodes on EGDE if the EDGE has been already
4019 // srinked while srinking another FACE
4020 srinker.RestoreParams();
4022 getSimplices( /*tgtNode=*/edge->_nodes.back(), edge->_simplices, ignoreShapes );
4026 bool toFixTria = false; // to improve quality of trias by diagonal swap
4027 if ( isConcaveFace )
4029 const bool hasTria = _mesh->NbTriangles(), hasQuad = _mesh->NbQuadrangles();
4030 if ( hasTria != hasQuad ) {
4031 toFixTria = hasTria;
4034 set<int> nbNodesSet;
4035 SMDS_ElemIteratorPtr fIt = smDS->GetElements();
4036 while ( fIt->more() && nbNodesSet.size() < 2 )
4037 nbNodesSet.insert( fIt->next()->NbCornerNodes() );
4038 toFixTria = ( *nbNodesSet.begin() == 3 );
4042 // ==================
4043 // Perform shrinking
4044 // ==================
4046 bool shrinked = true;
4047 int badNb, shriStep=0, smooStep=0;
4048 _SmoothNode::SmoothType smoothType
4049 = isConcaveFace ? _SmoothNode::ANGULAR : _SmoothNode::LAPLACIAN;
4053 // Move boundary nodes (actually just set new UV)
4054 // -----------------------------------------------
4055 dumpFunction(SMESH_Comment("moveBoundaryOnF")<<f2sd->first<<"_st"<<shriStep ); // debug
4057 for ( size_t i = 0; i < lEdges.size(); ++i )
4059 shrinked |= lEdges[i]->SetNewLength2d( surface,F,helper );
4063 // Move nodes on EDGE's
4064 // (XYZ is set as soon as a needed length reached in SetNewLength2d())
4065 set< _Shrinker1D* >::iterator shr = eShri1D.begin();
4066 for ( ; shr != eShri1D.end(); ++shr )
4067 (*shr)->Compute( /*set3D=*/false, helper );
4070 // -----------------
4071 int nbNoImpSteps = 0;
4074 while (( nbNoImpSteps < 5 && badNb > 0) && moved)
4076 dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
4078 int oldBadNb = badNb;
4081 for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
4083 moved |= nodesToSmooth[i].Smooth( badNb,surface,helper,refSign,
4084 smoothType, /*set3D=*/isConcaveFace);
4086 if ( badNb < oldBadNb )
4094 return error(SMESH_Comment("Can't shrink 2D mesh on face ") << f2sd->first );
4095 if ( shriStep > 200 )
4096 return error(SMESH_Comment("Infinite loop at shrinking 2D mesh on face ") << f2sd->first );
4098 // Fix narrow triangles by swapping diagonals
4099 // ---------------------------------------
4102 set<const SMDS_MeshNode*> usedNodes;
4103 fixBadFaces( F, helper, /*is2D=*/true, shriStep, & usedNodes); // swap diagonals
4105 // update working data
4106 set<const SMDS_MeshNode*>::iterator n;
4107 for ( size_t i = 0; i < nodesToSmooth.size() && !usedNodes.empty(); ++i )
4109 n = usedNodes.find( nodesToSmooth[ i ]._node );
4110 if ( n != usedNodes.end())
4112 getSimplices( nodesToSmooth[ i ]._node,
4113 nodesToSmooth[ i ]._simplices,
4115 /*sortSimplices=*/ smoothType == _SmoothNode::ANGULAR );
4116 usedNodes.erase( n );
4119 for ( size_t i = 0; i < lEdges.size() && !usedNodes.empty(); ++i )
4121 n = usedNodes.find( /*tgtNode=*/ lEdges[i]->_nodes.back() );
4122 if ( n != usedNodes.end())
4124 getSimplices( lEdges[i]->_nodes.back(),
4125 lEdges[i]->_simplices,
4127 usedNodes.erase( n );
4131 } // while ( shrinked )
4133 // No wrongly shaped faces remain; final smooth. Set node XYZ.
4134 bool isStructuredFixed = false;
4135 if ( SMESH_2D_Algo* algo = dynamic_cast<SMESH_2D_Algo*>( sm->GetAlgo() ))
4136 isStructuredFixed = algo->FixInternalNodes( *data._proxyMesh, F );
4137 if ( !isStructuredFixed )
4139 if ( isConcaveFace ) // fix narrow faces by swapping diagonals
4140 fixBadFaces( F, helper, /*is2D=*/false, ++shriStep );
4142 for ( int st = 3; st; --st )
4145 case 1: smoothType = _SmoothNode::LAPLACIAN; break;
4146 case 2: smoothType = _SmoothNode::LAPLACIAN; break;
4147 case 3: smoothType = _SmoothNode::ANGULAR; break;
4149 dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
4150 for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
4152 nodesToSmooth[i].Smooth( badNb,surface,helper,refSign,
4153 smoothType,/*set3D=*/st==1 );
4158 // Set an event listener to clear FACE sub-mesh together with SOLID sub-mesh
4159 VISCOUS_3D::ToClearSubWithMain( sm, data._solid );
4161 if ( !getMeshDS()->IsEmbeddedMode() )
4162 // Log node movement
4163 for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
4165 SMESH_TNodeXYZ p ( nodesToSmooth[i]._node );
4166 getMeshDS()->MoveNode( nodesToSmooth[i]._node, p.X(), p.Y(), p.Z() );
4169 } // loop on FACES to srink mesh on
4172 // Replace source nodes by target nodes in shrinked mesh edges
4174 map< int, _Shrinker1D >::iterator e2shr = e2shrMap.begin();
4175 for ( ; e2shr != e2shrMap.end(); ++e2shr )
4176 e2shr->second.SwapSrcTgtNodes( getMeshDS() );
4181 //================================================================================
4183 * \brief Computes 2d shrink direction and finds nodes limiting shrinking
4185 //================================================================================
4187 bool _ViscousBuilder::prepareEdgeToShrink( _LayerEdge& edge,
4188 const TopoDS_Face& F,
4189 SMESH_MesherHelper& helper,
4190 const SMESHDS_SubMesh* faceSubMesh)
4192 const SMDS_MeshNode* srcNode = edge._nodes[0];
4193 const SMDS_MeshNode* tgtNode = edge._nodes.back();
4197 if ( edge._sWOL.ShapeType() == TopAbs_FACE )
4199 gp_XY srcUV = helper.GetNodeUV( F, srcNode );
4200 gp_XY tgtUV = helper.GetNodeUV( F, tgtNode );
4201 gp_Vec2d uvDir( srcUV, tgtUV );
4202 double uvLen = uvDir.Magnitude();
4204 edge._normal.SetCoord( uvDir.X(),uvDir.Y(), 0);
4207 // // IMPORTANT to have src nodes NOT yet REPLACED by tgt nodes in shrinked faces
4208 // vector<const SMDS_MeshElement*> faces;
4209 // multimap< double, const SMDS_MeshNode* > proj2node;
4210 // SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
4211 // while ( fIt->more() )
4213 // const SMDS_MeshElement* f = fIt->next();
4214 // if ( faceSubMesh->Contains( f ))
4215 // faces.push_back( f );
4217 // for ( size_t i = 0; i < faces.size(); ++i )
4219 // const int nbNodes = faces[i]->NbCornerNodes();
4220 // for ( int j = 0; j < nbNodes; ++j )
4222 // const SMDS_MeshNode* n = faces[i]->GetNode(j);
4223 // if ( n == srcNode ) continue;
4224 // if ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE &&
4225 // ( faces.size() > 1 || nbNodes > 3 ))
4227 // gp_Pnt2d uv = helper.GetNodeUV( F, n );
4228 // gp_Vec2d uvDirN( srcUV, uv );
4229 // double proj = uvDirN * uvDir;
4230 // proj2node.insert( make_pair( proj, n ));
4234 // multimap< double, const SMDS_MeshNode* >::iterator p2n = proj2node.begin(), p2nEnd;
4235 // const double minProj = p2n->first;
4236 // const double projThreshold = 1.1 * uvLen;
4237 // if ( minProj > projThreshold )
4239 // // tgtNode is located so that it does not make faces with wrong orientation
4242 edge._pos.resize(1);
4243 edge._pos[0].SetCoord( tgtUV.X(), tgtUV.Y(), 0 );
4245 // store most risky nodes in _simplices
4246 // p2nEnd = proj2node.lower_bound( projThreshold );
4247 // int nbSimpl = ( std::distance( p2n, p2nEnd ) + 1) / 2;
4248 // edge._simplices.resize( nbSimpl );
4249 // for ( int i = 0; i < nbSimpl; ++i )
4251 // edge._simplices[i]._nPrev = p2n->second;
4252 // if ( ++p2n != p2nEnd )
4253 // edge._simplices[i]._nNext = p2n->second;
4255 // set UV of source node to target node
4256 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
4257 pos->SetUParameter( srcUV.X() );
4258 pos->SetVParameter( srcUV.Y() );
4260 else // _sWOL is TopAbs_EDGE
4262 TopoDS_Edge E = TopoDS::Edge( edge._sWOL);
4263 SMESHDS_SubMesh* edgeSM = getMeshDS()->MeshElements( E );
4264 if ( !edgeSM || edgeSM->NbElements() == 0 )
4265 return error(SMESH_Comment("Not meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
4267 const SMDS_MeshNode* n2 = 0;
4268 SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
4269 while ( eIt->more() && !n2 )
4271 const SMDS_MeshElement* e = eIt->next();
4272 if ( !edgeSM->Contains(e)) continue;
4273 n2 = e->GetNode( 0 );
4274 if ( n2 == srcNode ) n2 = e->GetNode( 1 );
4277 return error(SMESH_Comment("Wrongly meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
4279 double uSrc = helper.GetNodeU( E, srcNode, n2 );
4280 double uTgt = helper.GetNodeU( E, tgtNode, srcNode );
4281 double u2 = helper.GetNodeU( E, n2, srcNode );
4283 if ( fabs( uSrc-uTgt ) < 0.99 * fabs( uSrc-u2 ))
4285 // tgtNode is located so that it does not make faces with wrong orientation
4288 edge._pos.resize(1);
4289 edge._pos[0].SetCoord( U_TGT, uTgt );
4290 edge._pos[0].SetCoord( U_SRC, uSrc );
4291 edge._pos[0].SetCoord( LEN_TGT, fabs( uSrc-uTgt ));
4293 edge._simplices.resize( 1 );
4294 edge._simplices[0]._nPrev = n2;
4296 // set UV of source node to target node
4297 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
4298 pos->SetUParameter( uSrc );
4302 //================================================================================
4304 * \brief Compute positions (UV) to set to a node on edge moved during shrinking
4306 //================================================================================
4308 // Compute UV to follow during shrinking
4310 // const SMDS_MeshNode* srcNode = edge._nodes[0];
4311 // const SMDS_MeshNode* tgtNode = edge._nodes.back();
4313 // gp_XY srcUV = helper.GetNodeUV( F, srcNode );
4314 // gp_XY tgtUV = helper.GetNodeUV( F, tgtNode );
4315 // gp_Vec2d uvDir( srcUV, tgtUV );
4316 // double uvLen = uvDir.Magnitude();
4319 // // Select shrinking step such that not to make faces with wrong orientation.
4320 // // IMPORTANT to have src nodes NOT yet REPLACED by tgt nodes in shrinked faces
4321 // const double minStepSize = uvLen / 20;
4322 // double stepSize = uvLen;
4323 // SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
4324 // while ( fIt->more() )
4326 // const SMDS_MeshElement* f = fIt->next();
4327 // if ( !faceSubMesh->Contains( f )) continue;
4328 // const int nbNodes = f->NbCornerNodes();
4329 // for ( int i = 0; i < nbNodes; ++i )
4331 // const SMDS_MeshNode* n = f->GetNode(i);
4332 // if ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE || n == srcNode)
4334 // gp_XY uv = helper.GetNodeUV( F, n );
4335 // gp_Vec2d uvDirN( srcUV, uv );
4336 // double proj = uvDirN * uvDir;
4337 // if ( proj < stepSize && proj > minStepSize )
4343 // const int nbSteps = ceil( uvLen / stepSize );
4344 // gp_XYZ srcUV0( srcUV.X(), srcUV.Y(), 0 );
4345 // gp_XYZ tgtUV0( tgtUV.X(), tgtUV.Y(), 0 );
4346 // edge._pos.resize( nbSteps );
4347 // edge._pos[0] = tgtUV0;
4348 // for ( int i = 1; i < nbSteps; ++i )
4350 // double r = i / double( nbSteps );
4351 // edge._pos[i] = (1-r) * tgtUV0 + r * srcUV0;
4356 //================================================================================
4358 * \brief Try to fix triangles with high aspect ratio by swaping diagonals
4360 //================================================================================
4362 void _ViscousBuilder::fixBadFaces(const TopoDS_Face& F,
4363 SMESH_MesherHelper& helper,
4366 set<const SMDS_MeshNode*> * involvedNodes)
4368 SMESH::Controls::AspectRatio qualifier;
4369 SMESH::Controls::TSequenceOfXYZ points(3), points1(3), points2(3);
4370 const double maxAspectRatio = is2D ? 4. : 2;
4371 NodeCoordHelper xyz( F, helper, is2D );
4373 // find bad triangles
4375 vector< const SMDS_MeshElement* > badTrias;
4376 vector< double > badAspects;
4377 SMESHDS_SubMesh* sm = helper.GetMeshDS()->MeshElements( F );
4378 SMDS_ElemIteratorPtr fIt = sm->GetElements();
4379 while ( fIt->more() )
4381 const SMDS_MeshElement * f = fIt->next();
4382 if ( f->NbCornerNodes() != 3 ) continue;
4383 for ( int iP = 0; iP < 3; ++iP ) points(iP+1) = xyz( f->GetNode(iP));
4384 double aspect = qualifier.GetValue( points );
4385 if ( aspect > maxAspectRatio )
4387 badTrias.push_back( f );
4388 badAspects.push_back( aspect );
4393 dumpFunction(SMESH_Comment("beforeSwapDiagonals_F")<<helper.GetSubShapeID());
4394 SMDS_ElemIteratorPtr fIt = sm->GetElements();
4395 while ( fIt->more() )
4397 const SMDS_MeshElement * f = fIt->next();
4398 if ( f->NbCornerNodes() == 3 )
4399 dumpChangeNodes( f );
4403 if ( badTrias.empty() )
4406 // find couples of faces to swap diagonal
4408 typedef pair < const SMDS_MeshElement* , const SMDS_MeshElement* > T2Trias;
4409 vector< T2Trias > triaCouples;
4411 TIDSortedElemSet involvedFaces, emptySet;
4412 for ( size_t iTia = 0; iTia < badTrias.size(); ++iTia )
4415 double aspRatio [3];
4418 if ( !involvedFaces.insert( badTrias[iTia] ).second )
4420 for ( int iP = 0; iP < 3; ++iP )
4421 points(iP+1) = xyz( badTrias[iTia]->GetNode(iP));
4423 // find triangles adjacent to badTrias[iTia] with better aspect ratio after diag-swaping
4424 int bestCouple = -1;
4425 for ( int iSide = 0; iSide < 3; ++iSide )
4427 const SMDS_MeshNode* n1 = badTrias[iTia]->GetNode( iSide );
4428 const SMDS_MeshNode* n2 = badTrias[iTia]->GetNode(( iSide+1 ) % 3 );
4429 trias [iSide].first = badTrias[iTia];
4430 trias [iSide].second = SMESH_MeshAlgos::FindFaceInSet( n1, n2, emptySet, involvedFaces,
4432 if (( ! trias[iSide].second ) ||
4433 ( trias[iSide].second->NbCornerNodes() != 3 ) ||
4434 ( ! sm->Contains( trias[iSide].second )))
4437 // aspect ratio of an adjacent tria
4438 for ( int iP = 0; iP < 3; ++iP )
4439 points2(iP+1) = xyz( trias[iSide].second->GetNode(iP));
4440 double aspectInit = qualifier.GetValue( points2 );
4442 // arrange nodes as after diag-swaping
4443 if ( helper.WrapIndex( i1+1, 3 ) == i2 )
4444 i3 = helper.WrapIndex( i1-1, 3 );
4446 i3 = helper.WrapIndex( i1+1, 3 );
4448 points1( 1+ iSide ) = points2( 1+ i3 );
4449 points2( 1+ i2 ) = points1( 1+ ( iSide+2 ) % 3 );
4451 // aspect ratio after diag-swaping
4452 aspRatio[ iSide ] = qualifier.GetValue( points1 ) + qualifier.GetValue( points2 );
4453 if ( aspRatio[ iSide ] > aspectInit + badAspects[ iTia ] )
4456 // prevent inversion of a triangle
4457 gp_Vec norm1 = gp_Vec( points1(1), points1(3) ) ^ gp_Vec( points1(1), points1(2) );
4458 gp_Vec norm2 = gp_Vec( points2(1), points2(3) ) ^ gp_Vec( points2(1), points2(2) );
4459 if ( norm1 * norm2 < 0. && norm1.Angle( norm2 ) > 70./180.*M_PI )
4462 if ( bestCouple < 0 || aspRatio[ bestCouple ] > aspRatio[ iSide ] )
4466 if ( bestCouple >= 0 )
4468 triaCouples.push_back( trias[bestCouple] );
4469 involvedFaces.insert ( trias[bestCouple].second );
4473 involvedFaces.erase( badTrias[iTia] );
4476 if ( triaCouples.empty() )
4481 SMESH_MeshEditor editor( helper.GetMesh() );
4482 dumpFunction(SMESH_Comment("beforeSwapDiagonals_F")<<helper.GetSubShapeID()<<"_"<<step);
4483 for ( size_t i = 0; i < triaCouples.size(); ++i )
4485 dumpChangeNodes( triaCouples[i].first );
4486 dumpChangeNodes( triaCouples[i].second );
4487 editor.InverseDiag( triaCouples[i].first, triaCouples[i].second );
4490 if ( involvedNodes )
4491 for ( size_t i = 0; i < triaCouples.size(); ++i )
4493 involvedNodes->insert( triaCouples[i].first->begin_nodes(),
4494 triaCouples[i].first->end_nodes() );
4495 involvedNodes->insert( triaCouples[i].second->begin_nodes(),
4496 triaCouples[i].second->end_nodes() );
4499 // just for debug dump resulting triangles
4500 dumpFunction(SMESH_Comment("swapDiagonals_F")<<helper.GetSubShapeID()<<"_"<<step);
4501 for ( size_t i = 0; i < triaCouples.size(); ++i )
4503 dumpChangeNodes( triaCouples[i].first );
4504 dumpChangeNodes( triaCouples[i].second );
4508 //================================================================================
4510 * \brief Move target node to it's final position on the FACE during shrinking
4512 //================================================================================
4514 bool _LayerEdge::SetNewLength2d( Handle(Geom_Surface)& surface,
4515 const TopoDS_Face& F,
4516 SMESH_MesherHelper& helper )
4519 return false; // already at the target position
4521 SMDS_MeshNode* tgtNode = const_cast< SMDS_MeshNode*& >( _nodes.back() );
4523 if ( _sWOL.ShapeType() == TopAbs_FACE )
4525 gp_XY curUV = helper.GetNodeUV( F, tgtNode );
4526 gp_Pnt2d tgtUV( _pos[0].X(), _pos[0].Y() );
4527 gp_Vec2d uvDir( _normal.X(), _normal.Y() );
4528 const double uvLen = tgtUV.Distance( curUV );
4529 const double kSafe = Max( 0.5, 1. - 0.1 * _simplices.size() );
4531 // Select shrinking step such that not to make faces with wrong orientation.
4532 double stepSize = uvLen;
4533 for ( size_t i = 0; i < _simplices.size(); ++i )
4535 // find intersection of 2 lines: curUV-tgtUV and that connecting simplex nodes
4536 gp_XY uvN1 = helper.GetNodeUV( F, _simplices[i]._nPrev );
4537 gp_XY uvN2 = helper.GetNodeUV( F, _simplices[i]._nNext );
4538 gp_XY dirN = uvN2 - uvN1;
4539 double det = uvDir.Crossed( dirN );
4540 if ( Abs( det ) < std::numeric_limits<double>::min() ) continue;
4541 gp_XY dirN2Cur = curUV - uvN1;
4542 double step = dirN.Crossed( dirN2Cur ) / det;
4544 stepSize = Min( step, stepSize );
4547 if ( uvLen - stepSize < _len / 200. )
4552 else if ( stepSize > 0 )
4554 newUV = curUV + uvDir.XY() * stepSize * kSafe;
4560 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
4561 pos->SetUParameter( newUV.X() );
4562 pos->SetVParameter( newUV.Y() );
4565 gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
4566 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
4567 dumpMove( tgtNode );
4570 else // _sWOL is TopAbs_EDGE
4572 TopoDS_Edge E = TopoDS::Edge( _sWOL );
4573 const SMDS_MeshNode* n2 = _simplices[0]._nPrev;
4574 SMDS_EdgePosition* tgtPos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
4576 const double u2 = helper.GetNodeU( E, n2, tgtNode );
4577 const double uSrc = _pos[0].Coord( U_SRC );
4578 const double lenTgt = _pos[0].Coord( LEN_TGT );
4580 double newU = _pos[0].Coord( U_TGT );
4581 if ( lenTgt < 0.99 * fabs( uSrc-u2 )) // n2 got out of src-tgt range
4587 newU = 0.1 * tgtPos->GetUParameter() + 0.9 * u2;
4589 tgtPos->SetUParameter( newU );
4591 gp_XY newUV = helper.GetNodeUV( F, tgtNode, _nodes[0]);
4592 gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
4593 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
4594 dumpMove( tgtNode );
4600 //================================================================================
4602 * \brief Perform smooth on the FACE
4603 * \retval bool - true if the node has been moved
4605 //================================================================================
4607 bool _SmoothNode::Smooth(int& badNb,
4608 Handle(Geom_Surface)& surface,
4609 SMESH_MesherHelper& helper,
4610 const double refSign,
4614 const TopoDS_Face& face = TopoDS::Face( helper.GetSubShape() );
4616 // get uv of surrounding nodes
4617 vector<gp_XY> uv( _simplices.size() );
4618 for ( size_t i = 0; i < _simplices.size(); ++i )
4619 uv[i] = helper.GetNodeUV( face, _simplices[i]._nPrev, _node );
4621 // compute new UV for the node
4623 if ( how == TFI && _simplices.size() == 4 )
4626 for ( size_t i = 0; i < _simplices.size(); ++i )
4627 if ( _simplices[i]._nOpp )
4628 corners[i] = helper.GetNodeUV( face, _simplices[i]._nOpp, _node );
4630 throw SALOME_Exception(LOCALIZED("TFI smoothing: _Simplex::_nOpp not set!"));
4632 newPos = helper.calcTFI ( 0.5, 0.5,
4633 corners[0], corners[1], corners[2], corners[3],
4634 uv[1], uv[2], uv[3], uv[0] );
4636 else if ( how == ANGULAR )
4638 newPos = computeAngularPos( uv, helper.GetNodeUV( face, _node ), refSign );
4640 else if ( how == CENTROIDAL && _simplices.size() > 3 )
4642 // average centers of diagonals wieghted with their reciprocal lengths
4643 if ( _simplices.size() == 4 )
4645 double w1 = 1. / ( uv[2]-uv[0] ).SquareModulus();
4646 double w2 = 1. / ( uv[3]-uv[1] ).SquareModulus();
4647 newPos = ( w1 * ( uv[2]+uv[0] ) + w2 * ( uv[3]+uv[1] )) / ( w1+w2 ) / 2;
4651 double sumWeight = 0;
4652 int nb = _simplices.size() == 4 ? 2 : _simplices.size();
4653 for ( int i = 0; i < nb; ++i )
4656 int iTo = i + _simplices.size() - 1;
4657 for ( int j = iFrom; j < iTo; ++j )
4659 int i2 = SMESH_MesherHelper::WrapIndex( j, _simplices.size() );
4660 double w = 1. / ( uv[i]-uv[i2] ).SquareModulus();
4662 newPos += w * ( uv[i]+uv[i2] );
4665 newPos /= 2 * sumWeight; // 2 is to get a middle between uv's
4671 for ( size_t i = 0; i < _simplices.size(); ++i )
4673 newPos /= _simplices.size();
4676 // count quality metrics (orientation) of triangles around the node
4678 gp_XY tgtUV = helper.GetNodeUV( face, _node );
4679 for ( size_t i = 0; i < _simplices.size(); ++i )
4680 nbOkBefore += _simplices[i].IsForward( tgtUV, _node, face, helper, refSign );
4683 for ( size_t i = 0; i < _simplices.size(); ++i )
4684 nbOkAfter += _simplices[i].IsForward( newPos, _node, face, helper, refSign );
4686 if ( nbOkAfter < nbOkBefore )
4688 badNb += _simplices.size() - nbOkBefore;
4692 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( _node->GetPosition() );
4693 pos->SetUParameter( newPos.X() );
4694 pos->SetVParameter( newPos.Y() );
4701 gp_Pnt p = surface->Value( newPos.X(), newPos.Y() );
4702 const_cast< SMDS_MeshNode* >( _node )->setXYZ( p.X(), p.Y(), p.Z() );
4706 badNb += _simplices.size() - nbOkAfter;
4707 return ( (tgtUV-newPos).SquareModulus() > 1e-10 );
4710 //================================================================================
4712 * \brief Computes new UV using angle based smoothing technic
4714 //================================================================================
4716 gp_XY _SmoothNode::computeAngularPos(vector<gp_XY>& uv,
4717 const gp_XY& uvToFix,
4718 const double refSign)
4720 uv.push_back( uv.front() );
4722 vector< gp_XY > edgeDir ( uv.size() );
4723 vector< double > edgeSize( uv.size() );
4724 for ( size_t i = 1; i < edgeDir.size(); ++i )
4726 edgeDir [i-1] = uv[i] - uv[i-1];
4727 edgeSize[i-1] = edgeDir[i-1].Modulus();
4728 if ( edgeSize[i-1] < numeric_limits<double>::min() )
4729 edgeDir[i-1].SetX( 100 );
4731 edgeDir[i-1] /= edgeSize[i-1] * refSign;
4733 edgeDir.back() = edgeDir.front();
4734 edgeSize.back() = edgeSize.front();
4739 for ( size_t i = 1; i < edgeDir.size(); ++i )
4741 if ( edgeDir[i-1].X() > 1. ) continue;
4743 while ( edgeDir[i].X() > 1. && ++i < edgeDir.size() );
4744 if ( i == edgeDir.size() ) break;
4746 gp_XY norm1( -edgeDir[i1].Y(), edgeDir[i1].X() );
4747 gp_XY norm2( -edgeDir[i].Y(), edgeDir[i].X() );
4748 gp_XY bisec = norm1 + norm2;
4749 double bisecSize = bisec.Modulus();
4750 if ( bisecSize < numeric_limits<double>::min() )
4752 bisec = -edgeDir[i1] + edgeDir[i];
4753 bisecSize = bisec.Modulus();
4757 gp_XY dirToN = uvToFix - p;
4758 double distToN = dirToN.Modulus();
4759 if ( bisec * dirToN < 0 )
4762 newPos += ( p + bisec * distToN ) * ( edgeSize[i1] + edgeSize[i] );
4764 sumSize += edgeSize[i1] + edgeSize[i];
4766 newPos /= /*nbEdges * */sumSize;
4770 //================================================================================
4772 * \brief Delete _SolidData
4774 //================================================================================
4776 _SolidData::~_SolidData()
4778 for ( size_t i = 0; i < _edges.size(); ++i )
4780 if ( _edges[i] && _edges[i]->_2neibors )
4781 delete _edges[i]->_2neibors;
4786 //================================================================================
4788 * \brief Add a _LayerEdge inflated along the EDGE
4790 //================================================================================
4792 void _Shrinker1D::AddEdge( const _LayerEdge* e, SMESH_MesherHelper& helper )
4795 if ( _nodes.empty() )
4797 _edges[0] = _edges[1] = 0;
4801 if ( e == _edges[0] || e == _edges[1] )
4803 if ( e->_sWOL.IsNull() || e->_sWOL.ShapeType() != TopAbs_EDGE )
4804 throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
4805 if ( _edges[0] && _edges[0]->_sWOL != e->_sWOL )
4806 throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
4809 const TopoDS_Edge& E = TopoDS::Edge( e->_sWOL );
4811 BRep_Tool::Range( E, f,l );
4812 double u = helper.GetNodeU( E, e->_nodes[0], e->_nodes.back());
4813 _edges[ u < 0.5*(f+l) ? 0 : 1 ] = e;
4817 const SMDS_MeshNode* tgtNode0 = _edges[0] ? _edges[0]->_nodes.back() : 0;
4818 const SMDS_MeshNode* tgtNode1 = _edges[1] ? _edges[1]->_nodes.back() : 0;
4820 if ( _nodes.empty() )
4822 SMESHDS_SubMesh * eSubMesh = helper.GetMeshDS()->MeshElements( E );
4823 if ( !eSubMesh || eSubMesh->NbNodes() < 1 )
4825 TopLoc_Location loc;
4826 Handle(Geom_Curve) C = BRep_Tool::Curve(E, loc, f,l);
4827 GeomAdaptor_Curve aCurve(C, f,l);
4828 const double totLen = GCPnts_AbscissaPoint::Length(aCurve, f, l);
4830 int nbExpectNodes = eSubMesh->NbNodes();
4831 _initU .reserve( nbExpectNodes );
4832 _normPar.reserve( nbExpectNodes );
4833 _nodes .reserve( nbExpectNodes );
4834 SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
4835 while ( nIt->more() )
4837 const SMDS_MeshNode* node = nIt->next();
4838 if ( node->NbInverseElements(SMDSAbs_Edge) == 0 ||
4839 node == tgtNode0 || node == tgtNode1 )
4840 continue; // refinement nodes
4841 _nodes.push_back( node );
4842 _initU.push_back( helper.GetNodeU( E, node ));
4843 double len = GCPnts_AbscissaPoint::Length(aCurve, f, _initU.back());
4844 _normPar.push_back( len / totLen );
4849 // remove target node of the _LayerEdge from _nodes
4851 for ( size_t i = 0; i < _nodes.size(); ++i )
4852 if ( !_nodes[i] || _nodes[i] == tgtNode0 || _nodes[i] == tgtNode1 )
4853 _nodes[i] = 0, nbFound++;
4854 if ( nbFound == _nodes.size() )
4859 //================================================================================
4861 * \brief Move nodes on EDGE from ends where _LayerEdge's are inflated
4863 //================================================================================
4865 void _Shrinker1D::Compute(bool set3D, SMESH_MesherHelper& helper)
4867 if ( _done || _nodes.empty())
4869 const _LayerEdge* e = _edges[0];
4870 if ( !e ) e = _edges[1];
4873 _done = (( !_edges[0] || _edges[0]->_pos.empty() ) &&
4874 ( !_edges[1] || _edges[1]->_pos.empty() ));
4876 const TopoDS_Edge& E = TopoDS::Edge( e->_sWOL );
4878 if ( set3D || _done )
4880 Handle(Geom_Curve) C = BRep_Tool::Curve(E, f,l);
4881 GeomAdaptor_Curve aCurve(C, f,l);
4884 f = helper.GetNodeU( E, _edges[0]->_nodes.back(), _nodes[0] );
4886 l = helper.GetNodeU( E, _edges[1]->_nodes.back(), _nodes.back() );
4887 double totLen = GCPnts_AbscissaPoint::Length( aCurve, f, l );
4889 for ( size_t i = 0; i < _nodes.size(); ++i )
4891 if ( !_nodes[i] ) continue;
4892 double len = totLen * _normPar[i];
4893 GCPnts_AbscissaPoint discret( aCurve, len, f );
4894 if ( !discret.IsDone() )
4895 return throw SALOME_Exception(LOCALIZED("GCPnts_AbscissaPoint failed"));
4896 double u = discret.Parameter();
4897 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
4898 pos->SetUParameter( u );
4899 gp_Pnt p = C->Value( u );
4900 const_cast< SMDS_MeshNode*>( _nodes[i] )->setXYZ( p.X(), p.Y(), p.Z() );
4905 BRep_Tool::Range( E, f,l );
4907 f = helper.GetNodeU( E, _edges[0]->_nodes.back(), _nodes[0] );
4909 l = helper.GetNodeU( E, _edges[1]->_nodes.back(), _nodes.back() );
4911 for ( size_t i = 0; i < _nodes.size(); ++i )
4913 if ( !_nodes[i] ) continue;
4914 double u = f * ( 1-_normPar[i] ) + l * _normPar[i];
4915 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
4916 pos->SetUParameter( u );
4921 //================================================================================
4923 * \brief Restore initial parameters of nodes on EDGE
4925 //================================================================================
4927 void _Shrinker1D::RestoreParams()
4930 for ( size_t i = 0; i < _nodes.size(); ++i )
4932 if ( !_nodes[i] ) continue;
4933 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
4934 pos->SetUParameter( _initU[i] );
4939 //================================================================================
4941 * \brief Replace source nodes by target nodes in shrinked mesh edges
4943 //================================================================================
4945 void _Shrinker1D::SwapSrcTgtNodes( SMESHDS_Mesh* mesh )
4947 const SMDS_MeshNode* nodes[3];
4948 for ( int i = 0; i < 2; ++i )
4950 if ( !_edges[i] ) continue;
4952 SMESHDS_SubMesh * eSubMesh = mesh->MeshElements( _edges[i]->_sWOL );
4953 if ( !eSubMesh ) return;
4954 const SMDS_MeshNode* srcNode = _edges[i]->_nodes[0];
4955 const SMDS_MeshNode* tgtNode = _edges[i]->_nodes.back();
4956 SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
4957 while ( eIt->more() )
4959 const SMDS_MeshElement* e = eIt->next();
4960 if ( !eSubMesh->Contains( e ))
4962 SMDS_ElemIteratorPtr nIt = e->nodesIterator();
4963 for ( int iN = 0; iN < e->NbNodes(); ++iN )
4965 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
4966 nodes[iN] = ( n == srcNode ? tgtNode : n );
4968 mesh->ChangeElementNodes( e, nodes, e->NbNodes() );
4973 //================================================================================
4975 * \brief Creates 2D and 1D elements on boundaries of new prisms
4977 //================================================================================
4979 bool _ViscousBuilder::addBoundaryElements()
4981 SMESH_MesherHelper helper( *_mesh );
4983 for ( size_t i = 0; i < _sdVec.size(); ++i )
4985 _SolidData& data = _sdVec[i];
4986 TopTools_IndexedMapOfShape geomEdges;
4987 TopExp::MapShapes( data._solid, TopAbs_EDGE, geomEdges );
4988 for ( int iE = 1; iE <= geomEdges.Extent(); ++iE )
4990 const TopoDS_Edge& E = TopoDS::Edge( geomEdges(iE));
4992 // Get _LayerEdge's based on E
4994 map< double, const SMDS_MeshNode* > u2nodes;
4995 if ( !SMESH_Algo::GetSortedNodesOnEdge( getMeshDS(), E, /*ignoreMedium=*/false, u2nodes))
4998 vector< _LayerEdge* > ledges; ledges.reserve( u2nodes.size() );
4999 TNode2Edge & n2eMap = data._n2eMap;
5000 map< double, const SMDS_MeshNode* >::iterator u2n = u2nodes.begin();
5002 //check if 2D elements are needed on E
5003 TNode2Edge::iterator n2e = n2eMap.find( u2n->second );
5004 if ( n2e == n2eMap.end() ) continue; // no layers on vertex
5005 ledges.push_back( n2e->second );
5007 if (( n2e = n2eMap.find( u2n->second )) == n2eMap.end() )
5008 continue; // no layers on E
5009 ledges.push_back( n2eMap[ u2n->second ]);
5011 const SMDS_MeshNode* tgtN0 = ledges[0]->_nodes.back();
5012 const SMDS_MeshNode* tgtN1 = ledges[1]->_nodes.back();
5013 int nbSharedPyram = 0;
5014 SMDS_ElemIteratorPtr vIt = tgtN0->GetInverseElementIterator(SMDSAbs_Volume);
5015 while ( vIt->more() )
5017 const SMDS_MeshElement* v = vIt->next();
5018 nbSharedPyram += int( v->GetNodeIndex( tgtN1 ) >= 0 );
5020 if ( nbSharedPyram > 1 )
5021 continue; // not free border of the pyramid
5023 if ( getMeshDS()->FindFace( ledges[0]->_nodes[0], ledges[0]->_nodes[1],
5024 ledges[1]->_nodes[0], ledges[1]->_nodes[1]))
5025 continue; // faces already created
5027 for ( ++u2n; u2n != u2nodes.end(); ++u2n )
5028 ledges.push_back( n2eMap[ u2n->second ]);
5030 // Find out orientation and type of face to create
5032 bool reverse = false, isOnFace;
5034 map< TGeomID, TopoDS_Shape >::iterator e2f =
5035 data._shrinkShape2Shape.find( getMeshDS()->ShapeToIndex( E ));
5037 if (( isOnFace = ( e2f != data._shrinkShape2Shape.end() )))
5039 F = e2f->second.Oriented( TopAbs_FORWARD );
5040 reverse = ( helper.GetSubShapeOri( F, E ) == TopAbs_REVERSED );
5041 if ( helper.GetSubShapeOri( data._solid, F ) == TopAbs_REVERSED )
5042 reverse = !reverse, F.Reverse();
5043 if ( helper.IsReversedSubMesh( TopoDS::Face(F) ))
5048 // find FACE with layers sharing E
5049 PShapeIteratorPtr fIt = helper.GetAncestors( E, *_mesh, TopAbs_FACE );
5050 while ( fIt->more() && F.IsNull() )
5052 const TopoDS_Shape* pF = fIt->next();
5053 if ( helper.IsSubShape( *pF, data._solid) &&
5054 !data._ignoreFaceIds.count( e2f->first ))
5058 // Find the sub-mesh to add new faces
5059 SMESHDS_SubMesh* sm = 0;
5061 sm = getMeshDS()->MeshElements( F );
5063 sm = data._proxyMesh->getFaceSubM( TopoDS::Face(F), /*create=*/true );
5065 return error("error in addBoundaryElements()", data._index);
5068 const int dj1 = reverse ? 0 : 1;
5069 const int dj2 = reverse ? 1 : 0;
5070 for ( size_t j = 1; j < ledges.size(); ++j )
5072 vector< const SMDS_MeshNode*>& nn1 = ledges[j-dj1]->_nodes;
5073 vector< const SMDS_MeshNode*>& nn2 = ledges[j-dj2]->_nodes;
5075 for ( size_t z = 1; z < nn1.size(); ++z )
5076 sm->AddElement( getMeshDS()->AddFace( nn1[z-1], nn2[z-1], nn2[z], nn1[z] ));
5078 for ( size_t z = 1; z < nn1.size(); ++z )
5079 sm->AddElement( new SMDS_FaceOfNodes( nn1[z-1], nn2[z-1], nn2[z], nn1[z]));
5083 for ( int isFirst = 0; isFirst < 2; ++isFirst )
5085 _LayerEdge* edge = isFirst ? ledges.front() : ledges.back();
5086 if ( !edge->_sWOL.IsNull() && edge->_sWOL.ShapeType() == TopAbs_EDGE )
5088 vector< const SMDS_MeshNode*>& nn = edge->_nodes;
5089 if ( nn[1]->GetInverseElementIterator( SMDSAbs_Edge )->more() )
5091 helper.SetSubShape( edge->_sWOL );
5092 helper.SetElementsOnShape( true );
5093 for ( size_t z = 1; z < nn.size(); ++z )
5094 helper.AddEdge( nn[z-1], nn[z] );