1 // Copyright (C) 2007-2012 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.
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_Mesh.hxx"
39 #include "SMESH_MesherHelper.hxx"
40 #include "SMESH_ProxyMesh.hxx"
41 #include "SMESH_subMesh.hxx"
42 #include "SMESH_subMeshEventListener.hxx"
44 #include "utilities.h"
46 #include <BRepAdaptor_Curve2d.hxx>
47 #include <BRep_Tool.hxx>
48 #include <Bnd_B2d.hxx>
49 #include <Bnd_B3d.hxx>
51 #include <GCPnts_AbscissaPoint.hxx>
52 #include <Geom2d_Circle.hxx>
53 #include <Geom2d_Line.hxx>
54 #include <Geom2d_TrimmedCurve.hxx>
55 #include <GeomAdaptor_Curve.hxx>
56 #include <Geom_Circle.hxx>
57 #include <Geom_Curve.hxx>
58 #include <Geom_Line.hxx>
59 #include <Geom_TrimmedCurve.hxx>
60 #include <Precision.hxx>
61 #include <Standard_ErrorHandler.hxx>
62 #include <TColStd_Array1OfReal.hxx>
64 #include <TopExp_Explorer.hxx>
65 #include <TopTools_IndexedMapOfShape.hxx>
66 #include <TopTools_MapOfShape.hxx>
68 #include <TopoDS_Edge.hxx>
69 #include <TopoDS_Face.hxx>
70 #include <TopoDS_Vertex.hxx>
84 //================================================================================
89 enum UIndex { U_TGT = 1, U_SRC, LEN_TGT };
92 * \brief SMESH_ProxyMesh computed by _ViscousBuilder for a SOLID.
93 * It is stored in a SMESH_subMesh of the SOLID as SMESH_subMeshEventListenerData
95 struct _MeshOfSolid : public SMESH_ProxyMesh,
96 public SMESH_subMeshEventListenerData
100 _MeshOfSolid( SMESH_Mesh* mesh)
101 :SMESH_subMeshEventListenerData( /*isDeletable=*/true),_n2nMapComputed(false)
103 SMESH_ProxyMesh::setMesh( *mesh );
106 // returns submesh for a geom face
107 SMESH_ProxyMesh::SubMesh* getFaceSubM(const TopoDS_Face& F, bool create=false)
109 TGeomID i = SMESH_ProxyMesh::shapeIndex(F);
110 return create ? SMESH_ProxyMesh::getProxySubMesh(i) : findProxySubMesh(i);
112 void setNode2Node(const SMDS_MeshNode* srcNode,
113 const SMDS_MeshNode* proxyNode,
114 const SMESH_ProxyMesh::SubMesh* subMesh)
116 SMESH_ProxyMesh::setNode2Node( srcNode,proxyNode,subMesh);
119 //--------------------------------------------------------------------------------
121 * \brief Listener of events of 3D sub-meshes computed with viscous layers.
122 * It is used to clear an inferior dim sub-meshes modified by viscous layers
124 class _SrinkShapeListener : SMESH_subMeshEventListener
126 _SrinkShapeListener()
127 : SMESH_subMeshEventListener(/*isDeletable=*/false,
128 "StdMeshers_ViscousLayers::_SrinkShapeListener") {}
129 static SMESH_subMeshEventListener* Get() { static _SrinkShapeListener l; return &l; }
131 virtual void ProcessEvent(const int event,
133 SMESH_subMesh* solidSM,
134 SMESH_subMeshEventListenerData* data,
135 const SMESH_Hypothesis* hyp)
137 if ( SMESH_subMesh::COMPUTE_EVENT == eventType && solidSM->IsEmpty() && data )
139 SMESH_subMeshEventListener::ProcessEvent(event,eventType,solidSM,data,hyp);
142 static void ToClearSubMeshWithSolid( SMESH_subMesh* sm,
143 const TopoDS_Shape& solid)
145 SMESH_subMesh* solidSM = sm->GetFather()->GetSubMesh( solid );
146 SMESH_subMeshEventListenerData* data = solidSM->GetEventListenerData( Get());
149 if ( find( data->mySubMeshes.begin(), data->mySubMeshes.end(), sm ) ==
150 data->mySubMeshes.end())
151 data->mySubMeshes.push_back( sm );
155 data = SMESH_subMeshEventListenerData::MakeData( /*dependent=*/sm );
156 sm->SetEventListener( Get(), data, /*whereToListenTo=*/solidSM );
160 //--------------------------------------------------------------------------------
162 * \brief Listener of events of 3D sub-meshes computed with viscous layers.
163 * It is used to store data computed by _ViscousBuilder for a sub-mesh and to
164 * delete the data as soon as it has been used
166 class _ViscousListener : SMESH_subMeshEventListener
169 SMESH_subMeshEventListener(/*isDeletable=*/false,
170 "StdMeshers_ViscousLayers::_ViscousListener") {}
171 static SMESH_subMeshEventListener* Get() { static _ViscousListener l; return &l; }
173 virtual void ProcessEvent(const int event,
175 SMESH_subMesh* subMesh,
176 SMESH_subMeshEventListenerData* data,
177 const SMESH_Hypothesis* hyp)
179 if ( SMESH_subMesh::COMPUTE_EVENT == eventType )
181 // delete SMESH_ProxyMesh containing temporary faces
182 subMesh->DeleteEventListener( this );
185 // Finds or creates proxy mesh of the solid
186 static _MeshOfSolid* GetSolidMesh(SMESH_Mesh* mesh,
187 const TopoDS_Shape& solid,
190 if ( !mesh ) return 0;
191 SMESH_subMesh* sm = mesh->GetSubMesh(solid);
192 _MeshOfSolid* data = (_MeshOfSolid*) sm->GetEventListenerData( Get() );
193 if ( !data && toCreate )
195 data = new _MeshOfSolid(mesh);
196 data->mySubMeshes.push_back( sm ); // to find SOLID by _MeshOfSolid
197 sm->SetEventListener( Get(), data, sm );
201 // Removes proxy mesh of the solid
202 static void RemoveSolidMesh(SMESH_Mesh* mesh, const TopoDS_Shape& solid)
204 mesh->GetSubMesh(solid)->DeleteEventListener( _ViscousListener::Get() );
208 //--------------------------------------------------------------------------------
210 * \brief Simplex (triangle or tetrahedron) based on 1 (tria) or 2 (tet) nodes of
211 * _LayerEdge and 2 nodes of the mesh surface beening smoothed.
212 * The class is used to check validity of face or volumes around a smoothed node;
213 * it stores only 2 nodes as the other nodes are stored by _LayerEdge.
217 const SMDS_MeshNode *_nPrev, *_nNext; // nodes on a smoothed mesh surface
218 _Simplex(const SMDS_MeshNode* nPrev=0, const SMDS_MeshNode* nNext=0)
219 : _nPrev(nPrev), _nNext(nNext) {}
220 bool IsForward(const SMDS_MeshNode* nSrc, const gp_XYZ* pntTgt) const
222 const double M[3][3] =
223 {{ _nNext->X() - nSrc->X(), _nNext->Y() - nSrc->Y(), _nNext->Z() - nSrc->Z() },
224 { pntTgt->X() - nSrc->X(), pntTgt->Y() - nSrc->Y(), pntTgt->Z() - nSrc->Z() },
225 { _nPrev->X() - nSrc->X(), _nPrev->Y() - nSrc->Y(), _nPrev->Z() - nSrc->Z() }};
226 double determinant = ( + M[0][0]*M[1][1]*M[2][2]
227 + M[0][1]*M[1][2]*M[2][0]
228 + M[0][2]*M[1][0]*M[2][1]
229 - M[0][0]*M[1][2]*M[2][1]
230 - M[0][1]*M[1][0]*M[2][2]
231 - M[0][2]*M[1][1]*M[2][0]);
232 return determinant > 1e-100;
234 bool IsForward(const gp_XY& tgtUV,
235 const SMDS_MeshNode* smoothedNode,
236 const TopoDS_Face& face,
237 SMESH_MesherHelper& helper,
238 const double refSign) const
240 gp_XY prevUV = helper.GetNodeUV( face, _nPrev, smoothedNode );
241 gp_XY nextUV = helper.GetNodeUV( face, _nNext, smoothedNode );
242 gp_Vec2d v1( tgtUV, prevUV ), v2( tgtUV, nextUV );
244 return d*refSign > 1e-100;
246 bool IsNeighbour(const _Simplex& other) const
248 return _nPrev == other._nNext || _nNext == other._nPrev;
251 //--------------------------------------------------------------------------------
253 * Structure used to take into account surface curvature while smoothing
258 double _k; // factor to correct node smoothed position
260 static _Curvature* New( double avgNormProj, double avgDist )
263 if ( fabs( avgNormProj / avgDist ) > 1./200 )
266 c->_r = avgDist * avgDist / avgNormProj;
267 c->_k = avgDist * avgDist / c->_r / c->_r;
268 c->_k *= ( c->_r < 0 ? 1/1.1 : 1.1 ); // not to be too restrictive
272 double lenDelta(double len) const { return _k * ( _r + len ); }
275 //--------------------------------------------------------------------------------
277 * Structure used to smooth a _LayerEdge (master) based on an EDGE.
281 // target nodes of 2 neighbour _LayerEdge's based on the same EDGE
282 const SMDS_MeshNode* _nodes[2];
283 // vectors from source nodes of 2 _LayerEdge's to the source node of master _LayerEdge
285 double _wgt[2]; // weights of _nodes
286 _LayerEdge* _edges[2];
288 // normal to plane passing through _LayerEdge._normal and tangent of EDGE
291 _2NearEdges() { _nodes[0]=_nodes[1]=0; _plnNorm = 0; }
293 std::swap( _nodes[0], _nodes[1] );
294 std::swap( _wgt[0], _wgt[1] );
297 //--------------------------------------------------------------------------------
299 * \brief Edge normal to surface, connecting a node on solid surface (_nodes[0])
300 * and a node of the most internal layer (_nodes.back())
304 vector< const SMDS_MeshNode*> _nodes;
306 gp_XYZ _normal; // to solid surface
307 vector<gp_XYZ> _pos; // points computed during inflation
308 double _len; // length achived with the last step
309 double _cosin; // of angle (_normal ^ surface)
310 double _lenFactor; // to compute _len taking _cosin into account
312 // face or edge w/o layer along or near which _LayerEdge is inflated
314 // simplices connected to the source node (_nodes[0]);
315 // used for smoothing and quality check of _LayerEdge's based on the FACE
316 vector<_Simplex> _simplices;
317 // data for smoothing of _LayerEdge's based on the EDGE
318 _2NearEdges* _2neibors;
320 _Curvature* _curvature;
321 // TODO:: detele _Curvature, _plnNorm
323 void SetNewLength( double len, SMESH_MesherHelper& helper );
324 bool SetNewLength2d( Handle(Geom_Surface)& surface,
325 const TopoDS_Face& F,
326 SMESH_MesherHelper& helper );
327 void SetDataByNeighbors( const SMDS_MeshNode* n1,
328 const SMDS_MeshNode* n2,
329 SMESH_MesherHelper& helper);
330 void InvalidateStep( int curStep );
331 bool Smooth(int& badNb);
332 bool SmoothOnEdge(Handle(Geom_Surface)& surface,
333 const TopoDS_Face& F,
334 SMESH_MesherHelper& helper);
335 bool FindIntersection( SMESH_ElementSearcher& searcher,
337 const double& epsilon,
338 const SMDS_MeshElement** face = 0);
339 bool SegTriaInter( const gp_Ax1& lastSegment,
340 const SMDS_MeshNode* n0,
341 const SMDS_MeshNode* n1,
342 const SMDS_MeshNode* n2,
344 const double& epsilon) const;
345 gp_Ax1 LastSegment(double& segLen) const;
346 bool IsOnEdge() const { return _2neibors; }
347 void Copy( _LayerEdge& other, SMESH_MesherHelper& helper );
348 void SetCosin( double cosin );
352 bool operator () (const _LayerEdge* e1, const _LayerEdge* e2) const
354 const bool cmpNodes = ( e1 && e2 && e1->_nodes.size() && e2->_nodes.size() );
355 return cmpNodes ? ( e1->_nodes[0]->GetID() < e2->_nodes[0]->GetID()) : ( e1 < e2 );
358 //--------------------------------------------------------------------------------
360 typedef map< const SMDS_MeshNode*, _LayerEdge*, TIDCompare > TNode2Edge;
362 //--------------------------------------------------------------------------------
364 * \brief Data of a SOLID
369 const StdMeshers_ViscousLayers* _hyp;
370 _MeshOfSolid* _proxyMesh;
371 set<TGeomID> _reversedFaceIds;
373 double _stepSize, _stepSizeCoeff;
374 const SMDS_MeshNode* _stepSizeNodes[2];
377 // edges of _n2eMap. We keep same data in two containers because
378 // iteration over the map is 5 time longer than over the vector
379 vector< _LayerEdge* > _edges;
381 // key: an id of shape (EDGE or VERTEX) shared by a FACE with
382 // layers and a FACE w/o layers
383 // value: the shape (FACE or EDGE) to shrink mesh on.
384 // _LayerEdge's basing on nodes on key shape are inflated along the value shape
385 map< TGeomID, TopoDS_Shape > _shrinkShape2Shape;
387 // FACE's WOL, srink on which is forbiden due to algo on the adjacent SOLID
388 set< TGeomID > _noShrinkFaces;
390 // <EDGE to smooth on> to <it's curve>
391 map< TGeomID,Handle(Geom_Curve)> _edge2curve;
393 // end indices in _edges of _LayerEdge on one shape to smooth
394 vector< int > _endEdgeToSmooth;
396 double _epsilon; // precision for SegTriaInter()
398 int _index; // for debug
400 _SolidData(const TopoDS_Shape& s=TopoDS_Shape(),
401 const StdMeshers_ViscousLayers* h=0,
402 _MeshOfSolid* m=0) :_solid(s), _hyp(h), _proxyMesh(m) {}
405 Handle(Geom_Curve) CurveForSmooth( const TopoDS_Edge& E,
408 Handle(Geom_Surface)& surface,
409 const TopoDS_Face& F,
410 SMESH_MesherHelper& helper);
412 //--------------------------------------------------------------------------------
414 * \brief Data of node on a shrinked FACE
418 const SMDS_MeshNode* _node;
419 //vector<const SMDS_MeshNode*> _nodesAround;
420 vector<_Simplex> _simplices; // for quality check
422 bool Smooth(int& badNb,
423 Handle(Geom_Surface)& surface,
424 SMESH_MesherHelper& helper,
425 const double refSign,
429 //--------------------------------------------------------------------------------
431 * \brief Builder of viscous layers
433 class _ViscousBuilder
438 SMESH_ComputeErrorPtr Compute(SMESH_Mesh& mesh,
439 const TopoDS_Shape& shape);
441 // restore event listeners used to clear an inferior dim sub-mesh modified by viscous layers
442 void RestoreListeners();
444 // computes SMESH_ProxyMesh::SubMesh::_n2n;
445 bool MakeN2NMap( _MeshOfSolid* pm );
449 bool findSolidsWithLayers();
450 bool findFacesWithLayers();
451 bool makeLayer(_SolidData& data);
452 bool setEdgeData(_LayerEdge& edge, const set<TGeomID>& subIds,
453 SMESH_MesherHelper& helper, _SolidData& data);
454 bool findNeiborsOnEdge(const _LayerEdge* edge,
455 const SMDS_MeshNode*& n1,
456 const SMDS_MeshNode*& n2,
458 void getSimplices( const SMDS_MeshNode* node, vector<_Simplex>& simplices,
459 const set<TGeomID>& ingnoreShapes,
460 const _SolidData* dataToCheckOri = 0,
461 const bool toSort = false);
462 bool sortEdges( _SolidData& data,
463 vector< vector<_LayerEdge*> >& edgesByGeom);
464 void limitStepSize( _SolidData& data,
465 const SMDS_MeshElement* face,
467 void limitStepSize( _SolidData& data, const double minSize);
468 bool inflate(_SolidData& data);
469 bool smoothAndCheck(_SolidData& data, const int nbSteps, double & distToIntersection);
470 bool smoothAnalyticEdge( _SolidData& data,
473 Handle(Geom_Surface)& surface,
474 const TopoDS_Face& F,
475 SMESH_MesherHelper& helper);
476 bool updateNormals( _SolidData& data, SMESH_MesherHelper& helper );
477 bool refine(_SolidData& data);
479 bool prepareEdgeToShrink( _LayerEdge& edge, const TopoDS_Face& F,
480 SMESH_MesherHelper& helper,
481 const SMESHDS_SubMesh* faceSubMesh );
482 void fixBadFaces(const TopoDS_Face& F, SMESH_MesherHelper& helper);
483 bool addBoundaryElements();
485 bool error( const string& text, int solidID=-1 );
486 SMESHDS_Mesh* getMeshDS() { return _mesh->GetMeshDS(); }
489 void makeGroupOfLE();
492 SMESH_ComputeErrorPtr _error;
494 vector< _SolidData > _sdVec;
495 set<TGeomID> _ignoreShapeIds;
498 //--------------------------------------------------------------------------------
500 * \brief Shrinker of nodes on the EDGE
504 vector<double> _initU;
505 vector<double> _normPar;
506 vector<const SMDS_MeshNode*> _nodes;
507 const _LayerEdge* _edges[2];
510 void AddEdge( const _LayerEdge* e, SMESH_MesherHelper& helper );
511 void Compute(bool set3D, SMESH_MesherHelper& helper);
512 void RestoreParams();
513 void SwapSrcTgtNodes(SMESHDS_Mesh* mesh);
515 //--------------------------------------------------------------------------------
517 * \brief Class of temporary mesh face.
518 * We can't use SMDS_FaceOfNodes since it's impossible to set it's ID which is
519 * needed because SMESH_ElementSearcher internaly uses set of elements sorted by ID
521 struct TmpMeshFace : public SMDS_MeshElement
523 vector<const SMDS_MeshNode* > _nn;
524 TmpMeshFace( const vector<const SMDS_MeshNode*>& nodes, int id):
525 SMDS_MeshElement(id), _nn(nodes) {}
526 virtual const SMDS_MeshNode* GetNode(const int ind) const { return _nn[ind]; }
527 virtual SMDSAbs_ElementType GetType() const { return SMDSAbs_Face; }
528 virtual vtkIdType GetVtkType() const { return -1; }
529 virtual SMDSAbs_EntityType GetEntityType() const { return SMDSEntity_Last; }
530 virtual SMDSAbs_GeometryType GetGeomType() const { return SMDSGeom_TRIANGLE; }
531 virtual SMDS_ElemIteratorPtr elementsIterator(SMDSAbs_ElementType type) const
532 { return SMDS_ElemIteratorPtr( new SMDS_NodeVectorElemIterator( _nn.begin(), _nn.end()));}
534 //--------------------------------------------------------------------------------
536 * \brief Class of temporary mesh face storing _LayerEdge it's based on
538 struct TmpMeshFaceOnEdge : public TmpMeshFace
540 _LayerEdge *_le1, *_le2;
541 TmpMeshFaceOnEdge( _LayerEdge* le1, _LayerEdge* le2, int ID ):
542 TmpMeshFace( vector<const SMDS_MeshNode*>(4), ID ), _le1(le1), _le2(le2)
544 _nn[0]=_le1->_nodes[0];
545 _nn[1]=_le1->_nodes.back();
546 _nn[2]=_le2->_nodes.back();
547 _nn[3]=_le2->_nodes[0];
550 } // namespace VISCOUS
552 //================================================================================
553 // StdMeshers_ViscousLayers hypothesis
555 StdMeshers_ViscousLayers::StdMeshers_ViscousLayers(int hypId, int studyId, SMESH_Gen* gen)
556 :SMESH_Hypothesis(hypId, studyId, gen),
557 _nbLayers(1), _thickness(1), _stretchFactor(1)
559 _name = StdMeshers_ViscousLayers::GetHypType();
560 _param_algo_dim = -3; // auxiliary hyp used by 3D algos
561 } // --------------------------------------------------------------------------------
562 void StdMeshers_ViscousLayers::SetIgnoreFaces(const std::vector<int>& faceIds)
564 if ( faceIds != _ignoreFaceIds )
565 _ignoreFaceIds = faceIds, NotifySubMeshesHypothesisModification();
566 } // --------------------------------------------------------------------------------
567 void StdMeshers_ViscousLayers::SetTotalThickness(double thickness)
569 if ( thickness != _thickness )
570 _thickness = thickness, NotifySubMeshesHypothesisModification();
571 } // --------------------------------------------------------------------------------
572 void StdMeshers_ViscousLayers::SetNumberLayers(int nb)
574 if ( _nbLayers != nb )
575 _nbLayers = nb, NotifySubMeshesHypothesisModification();
576 } // --------------------------------------------------------------------------------
577 void StdMeshers_ViscousLayers::SetStretchFactor(double factor)
579 if ( _stretchFactor != factor )
580 _stretchFactor = factor, NotifySubMeshesHypothesisModification();
581 } // --------------------------------------------------------------------------------
583 StdMeshers_ViscousLayers::Compute(SMESH_Mesh& theMesh,
584 const TopoDS_Shape& theShape,
585 const bool toMakeN2NMap) const
587 using namespace VISCOUS;
588 _ViscousBuilder bulder;
589 SMESH_ComputeErrorPtr err = bulder.Compute( theMesh, theShape );
590 if ( err && !err->IsOK() )
591 return SMESH_ProxyMesh::Ptr();
593 vector<SMESH_ProxyMesh::Ptr> components;
594 TopExp_Explorer exp( theShape, TopAbs_SOLID );
595 for ( ; exp.More(); exp.Next() )
597 if ( _MeshOfSolid* pm =
598 _ViscousListener::GetSolidMesh( &theMesh, exp.Current(), /*toCreate=*/false))
600 if ( toMakeN2NMap && !pm->_n2nMapComputed )
601 if ( !bulder.MakeN2NMap( pm ))
602 return SMESH_ProxyMesh::Ptr();
603 components.push_back( SMESH_ProxyMesh::Ptr( pm ));
604 pm->myIsDeletable = false; // it will de deleted by boost::shared_ptr
606 _ViscousListener::RemoveSolidMesh ( &theMesh, exp.Current() );
608 switch ( components.size() )
612 case 1: return components[0];
614 default: return SMESH_ProxyMesh::Ptr( new SMESH_ProxyMesh( components ));
616 return SMESH_ProxyMesh::Ptr();
617 } // --------------------------------------------------------------------------------
618 std::ostream & StdMeshers_ViscousLayers::SaveTo(std::ostream & save)
620 save << " " << _nbLayers
622 << " " << _stretchFactor
623 << " " << _ignoreFaceIds.size();
624 for ( unsigned i = 0; i < _ignoreFaceIds.size(); ++i )
625 save << " " << _ignoreFaceIds[i];
627 } // --------------------------------------------------------------------------------
628 std::istream & StdMeshers_ViscousLayers::LoadFrom(std::istream & load)
631 load >> _nbLayers >> _thickness >> _stretchFactor >> nbFaces;
632 while ( _ignoreFaceIds.size() < nbFaces && load >> faceID )
633 _ignoreFaceIds.push_back( faceID );
635 } // --------------------------------------------------------------------------------
636 bool StdMeshers_ViscousLayers::SetParametersByMesh(const SMESH_Mesh* theMesh,
637 const TopoDS_Shape& theShape)
642 // END StdMeshers_ViscousLayers hypothesis
643 //================================================================================
647 gp_XYZ getEdgeDir( const TopoDS_Edge& E, const TopoDS_Vertex& fromV )
651 Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
652 gp_Pnt p = BRep_Tool::Pnt( fromV );
653 double distF = p.SquareDistance( c->Value( f ));
654 double distL = p.SquareDistance( c->Value( l ));
655 c->D1(( distF < distL ? f : l), p, dir );
656 if ( distL < distF ) dir.Reverse();
659 //--------------------------------------------------------------------------------
660 gp_XYZ getEdgeDir( const TopoDS_Edge& E, const SMDS_MeshNode* atNode,
661 SMESH_MesherHelper& helper)
664 double f,l; gp_Pnt p;
665 Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
666 double u = helper.GetNodeU( E, atNode );
670 //--------------------------------------------------------------------------------
671 gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Edge& fromE,
672 const SMDS_MeshNode* node, SMESH_MesherHelper& helper, bool& ok)
674 gp_XY uv = helper.GetNodeUV( F, node, 0, &ok );
675 Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
676 gp_Pnt p; gp_Vec du, dv, norm;
677 surface->D1( uv.X(),uv.Y(), p, du,dv );
681 Handle(Geom_Curve) c = BRep_Tool::Curve( fromE, f, l );
682 double u = helper.GetNodeU( fromE, node, 0, &ok );
684 TopAbs_Orientation o = helper.GetSubShapeOri( F.Oriented(TopAbs_FORWARD), fromE);
685 if ( o == TopAbs_REVERSED )
688 gp_Vec dir = norm ^ du;
690 if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX &&
691 helper.IsClosedEdge( fromE ))
693 if ( fabs(u-f) < fabs(u-l )) c->D1( l, p, dv );
694 else c->D1( f, p, dv );
695 if ( o == TopAbs_REVERSED )
697 gp_Vec dir2 = norm ^ dv;
698 dir = dir.Normalized() + dir2.Normalized();
702 //--------------------------------------------------------------------------------
703 gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Vertex& fromV,
704 const SMDS_MeshNode* node, SMESH_MesherHelper& helper,
705 bool& ok, double* cosin=0)
707 double f,l; TopLoc_Location loc;
708 vector< TopoDS_Edge > edges; // sharing a vertex
709 PShapeIteratorPtr eIt = helper.GetAncestors( fromV, *helper.GetMesh(), TopAbs_EDGE);
712 const TopoDS_Edge* e = static_cast<const TopoDS_Edge*>( eIt->next() );
713 if ( helper.IsSubShape( *e, F ) && !BRep_Tool::Curve( *e, loc,f,l).IsNull() )
714 edges.push_back( *e );
717 if ( !( ok = ( edges.size() > 0 ))) return dir;
718 // get average dir of edges going fromV
720 for ( unsigned i = 0; i < edges.size(); ++i )
722 edgeDir = getEdgeDir( edges[i], fromV );
723 double size2 = edgeDir.SquareMagnitude();
724 if ( size2 > numeric_limits<double>::min() )
725 edgeDir /= sqrt( size2 );
728 dir += edgeDir.XYZ();
730 gp_XYZ fromEdgeDir = getFaceDir( F, edges[0], node, helper, ok );
731 if ( edges.size() == 1 || dir.SquareModulus() < 1e-10)
733 else if ( dir * fromEdgeDir < 0 )
737 //dir /= edges.size();
739 double angle = edgeDir.Angle( dir );
740 *cosin = cos( angle );
745 //================================================================================
747 * \brief Returns true if a FACE is bound by a concave EDGE
749 //================================================================================
751 bool isConcave( const TopoDS_Face& F, SMESH_MesherHelper& helper )
755 TopExp_Explorer eExp( F.Oriented( TopAbs_FORWARD ), TopAbs_EDGE );
756 for ( ; eExp.More(); eExp.Next() )
758 const TopoDS_Edge& E = TopoDS::Edge( eExp.Current() );
759 if ( BRep_Tool::Degenerated( E )) continue;
760 // check if 2D curve is concave
761 BRepAdaptor_Curve2d curve( E, F );
762 const int nbIntervals = curve.NbIntervals( GeomAbs_C2 );
763 TColStd_Array1OfReal intervals(1, nbIntervals + 1 );
764 curve.Intervals( intervals, GeomAbs_C2 );
765 bool isConvex = true;
766 for ( int i = 1; i <= nbIntervals && isConvex; ++i )
768 double u1 = intervals( i );
769 double u2 = intervals( i+1 );
770 curve.D2( 0.5*( u1+u2 ), p, drv1, drv2 );
771 double cross = drv2 ^ drv1;
772 if ( E.Orientation() == TopAbs_REVERSED )
774 isConvex = ( cross < 1e-9 );
776 // check if concavity is strong enough to care about it
777 //const double maxAngle = 5 * Standard_PI180;
780 //cout << "Concave FACE " << helper.GetMeshDS()->ShapeToIndex( F ) << endl;
782 // map< double, const SMDS_MeshNode* > u2nodes;
783 // if ( !SMESH_Algo::GetSortedNodesOnEdge( helper.GetMeshDS(), E,
784 // /*ignoreMedium=*/true, u2nodes))
786 // map< double, const SMDS_MeshNode* >::iterator u2n = u2nodes.begin();
787 // gp_Pnt2d uvPrev = helper.GetNodeUV( F, u2n->second );
788 // double uPrev = u2n->first;
789 // for ( ++u2n; u2n != u2nodes.end(); ++u2n )
791 // gp_Pnt2d uv = helper.GetNodeUV( F, u2n->second );
792 // gp_Vec2d segmentDir( uvPrev, uv );
793 // curve.D1( uPrev, p, drv1 );
795 // if ( fabs( segmentDir.Angle( drv1 )) > maxAngle )
800 // uPrev = u2n->first;
806 //--------------------------------------------------------------------------------
807 // DEBUG. Dump intermediate node positions into a python script
812 const char* fname = "/tmp/viscous.py";
813 cout << "execfile('"<<fname<<"')"<<endl;
814 py = new ofstream(fname);
815 *py << "from smesh import *" << endl
816 << "meshSO = GetCurrentStudy().FindObjectID('0:1:2:3')" << endl
817 << "mesh = Mesh( meshSO.GetObject() )"<<endl;
821 *py << "mesh.MakeGroup('Viscous Prisms',VOLUME,FT_ElemGeomType,'=',Geom_PENTA)"<<endl;
824 ~PyDump() { Finish(); }
826 #define dumpFunction(f) { _dumpFunction(f, __LINE__);}
827 #define dumpMove(n) { _dumpMove(n, __LINE__);}
828 #define dumpCmd(txt) { _dumpCmd(txt, __LINE__);}
829 void _dumpFunction(const string& fun, int ln)
830 { if (py) *py<< "def "<<fun<<"(): # "<< ln <<endl; cout<<fun<<"()"<<endl;}
831 void _dumpMove(const SMDS_MeshNode* n, int ln)
832 { if (py) *py<< " mesh.MoveNode( "<<n->GetID()<< ", "<< n->X()
833 << ", "<<n->Y()<<", "<< n->Z()<< ")\t\t # "<< ln <<endl; }
834 void _dumpCmd(const string& txt, int ln)
835 { if (py) *py<< " "<<txt<<" # "<< ln <<endl; }
836 void dumpFunctionEnd()
837 { if (py) *py<< " return"<< endl; }
838 void dumpChangeNodes( const SMDS_MeshElement* f )
839 { if (py) { *py<< " mesh.ChangeElemNodes( " << f->GetID()<<", [";
840 for ( int i=1; i < f->NbNodes(); ++i ) *py << f->GetNode(i-1)->GetID()<<", ";
841 *py << f->GetNode( f->NbNodes()-1 )->GetID() << " ])"<< endl; }}
843 struct PyDump { void Finish() {} };
844 #define dumpFunction(f) f
847 #define dumpFunctionEnd()
848 #define dumpChangeNodes(f)
852 using namespace VISCOUS;
854 //================================================================================
856 * \brief Constructor of _ViscousBuilder
858 //================================================================================
860 _ViscousBuilder::_ViscousBuilder()
862 _error = SMESH_ComputeError::New(COMPERR_OK);
866 //================================================================================
868 * \brief Stores error description and returns false
870 //================================================================================
872 bool _ViscousBuilder::error(const string& text, int solidId )
874 _error->myName = COMPERR_ALGO_FAILED;
875 _error->myComment = string("Viscous layers builder: ") + text;
878 SMESH_subMesh* sm = _mesh->GetSubMeshContaining( solidId );
879 if ( !sm && !_sdVec.empty() )
880 sm = _mesh->GetSubMeshContaining( _sdVec[0]._index );
881 if ( sm && sm->GetSubShape().ShapeType() == TopAbs_SOLID )
883 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
884 if ( smError && smError->myAlgo )
885 _error->myAlgo = smError->myAlgo;
889 makeGroupOfLE(); // debug
894 //================================================================================
896 * \brief At study restoration, restore event listeners used to clear an inferior
897 * dim sub-mesh modified by viscous layers
899 //================================================================================
901 void _ViscousBuilder::RestoreListeners()
906 //================================================================================
908 * \brief computes SMESH_ProxyMesh::SubMesh::_n2n
910 //================================================================================
912 bool _ViscousBuilder::MakeN2NMap( _MeshOfSolid* pm )
914 SMESH_subMesh* solidSM = pm->mySubMeshes.front();
915 TopExp_Explorer fExp( solidSM->GetSubShape(), TopAbs_FACE );
916 for ( ; fExp.More(); fExp.Next() )
918 SMESHDS_SubMesh* srcSmDS = pm->GetMeshDS()->MeshElements( fExp.Current() );
919 const SMESH_ProxyMesh::SubMesh* prxSmDS = pm->GetProxySubMesh( fExp.Current() );
921 if ( !srcSmDS || !prxSmDS || !srcSmDS->NbElements() || !prxSmDS->NbElements() )
923 if ( srcSmDS->GetElements()->next() == prxSmDS->GetElements()->next())
926 if ( srcSmDS->NbElements() != prxSmDS->NbElements() )
927 return error( "Different nb elements in a source and a proxy sub-mesh", solidSM->GetId());
929 SMDS_ElemIteratorPtr srcIt = srcSmDS->GetElements();
930 SMDS_ElemIteratorPtr prxIt = prxSmDS->GetElements();
931 while( prxIt->more() )
933 const SMDS_MeshElement* fSrc = srcIt->next();
934 const SMDS_MeshElement* fPrx = prxIt->next();
935 if ( fSrc->NbNodes() != fPrx->NbNodes())
936 return error( "Different elements in a source and a proxy sub-mesh", solidSM->GetId());
937 for ( int i = 0 ; i < fPrx->NbNodes(); ++i )
938 pm->setNode2Node( fSrc->GetNode(i), fPrx->GetNode(i), prxSmDS );
941 pm->_n2nMapComputed = true;
945 //================================================================================
947 * \brief Does its job
949 //================================================================================
951 SMESH_ComputeErrorPtr _ViscousBuilder::Compute(SMESH_Mesh& theMesh,
952 const TopoDS_Shape& theShape)
954 // TODO: set priority of solids during Gen::Compute()
958 // check if proxy mesh already computed
959 TopExp_Explorer exp( theShape, TopAbs_SOLID );
961 return error("No SOLID's in theShape"), _error;
963 if ( _ViscousListener::GetSolidMesh( _mesh, exp.Current(), /*toCreate=*/false))
964 return SMESH_ComputeErrorPtr(); // everything already computed
968 // TODO: ignore already computed SOLIDs
969 if ( !findSolidsWithLayers())
972 if ( !findFacesWithLayers() )
975 for ( unsigned i = 0; i < _sdVec.size(); ++i )
977 if ( ! makeLayer(_sdVec[i]) )
980 if ( ! inflate(_sdVec[i]) )
983 if ( ! refine(_sdVec[i]) )
989 addBoundaryElements();
991 makeGroupOfLE(); // debug
997 //================================================================================
999 * \brief Finds SOLIDs to compute using viscous layers. Fills _sdVec
1001 //================================================================================
1003 bool _ViscousBuilder::findSolidsWithLayers()
1006 TopTools_IndexedMapOfShape allSolids;
1007 TopExp::MapShapes( _mesh->GetShapeToMesh(), TopAbs_SOLID, allSolids );
1008 _sdVec.reserve( allSolids.Extent());
1010 SMESH_Gen* gen = _mesh->GetGen();
1011 for ( int i = 1; i <= allSolids.Extent(); ++i )
1013 // find StdMeshers_ViscousLayers hyp assigned to the i-th solid
1014 SMESH_Algo* algo = gen->GetAlgo( *_mesh, allSolids(i) );
1015 if ( !algo ) continue;
1016 // TODO: check if algo is hidden
1017 const list <const SMESHDS_Hypothesis *> & allHyps =
1018 algo->GetUsedHypothesis(*_mesh, allSolids(i), /*ignoreAuxiliary=*/false);
1019 list< const SMESHDS_Hypothesis *>::const_iterator hyp = allHyps.begin();
1020 const StdMeshers_ViscousLayers* viscHyp = 0;
1021 for ( ; hyp != allHyps.end() && !viscHyp; ++hyp )
1022 viscHyp = dynamic_cast<const StdMeshers_ViscousLayers*>( *hyp );
1025 _MeshOfSolid* proxyMesh = _ViscousListener::GetSolidMesh( _mesh,
1028 _sdVec.push_back( _SolidData( allSolids(i), viscHyp, proxyMesh ));
1029 _sdVec.back()._index = getMeshDS()->ShapeToIndex( allSolids(i));
1032 if ( _sdVec.empty() )
1034 ( SMESH_Comment(StdMeshers_ViscousLayers::GetHypType()) << " hypothesis not found",0);
1039 //================================================================================
1043 //================================================================================
1045 bool _ViscousBuilder::findFacesWithLayers()
1047 // collect all faces to ignore defined by hyp
1048 vector<TopoDS_Shape> ignoreFaces;
1049 for ( unsigned i = 0; i < _sdVec.size(); ++i )
1051 vector<TGeomID> ids = _sdVec[i]._hyp->GetIgnoreFaces();
1052 for ( unsigned i = 0; i < ids.size(); ++i )
1054 const TopoDS_Shape& s = getMeshDS()->IndexToShape( ids[i] );
1055 if ( !s.IsNull() && s.ShapeType() == TopAbs_FACE )
1057 _ignoreShapeIds.insert( ids[i] );
1058 ignoreFaces.push_back( s );
1063 // ignore internal faces
1064 SMESH_MesherHelper helper( *_mesh );
1065 TopExp_Explorer exp;
1066 for ( unsigned i = 0; i < _sdVec.size(); ++i )
1068 exp.Init( _sdVec[i]._solid.Oriented( TopAbs_FORWARD ), TopAbs_FACE );
1069 for ( ; exp.More(); exp.Next() )
1071 TGeomID faceInd = getMeshDS()->ShapeToIndex( exp.Current() );
1072 if ( helper.NbAncestors( exp.Current(), *_mesh, TopAbs_SOLID ) > 1 )
1074 _ignoreShapeIds.insert( faceInd );
1075 ignoreFaces.push_back( exp.Current() );
1076 if ( SMESH_Algo::IsReversedSubMesh( TopoDS::Face( exp.Current() ), getMeshDS()))
1077 _sdVec[i]._reversedFaceIds.insert( faceInd );
1082 // Find faces to shrink mesh on (solution 2 in issue 0020832);
1083 TopTools_IndexedMapOfShape shapes;
1084 for ( unsigned i = 0; i < _sdVec.size(); ++i )
1087 TopExp::MapShapes(_sdVec[i]._solid, TopAbs_EDGE, shapes);
1088 for ( int iE = 1; iE <= shapes.Extent(); ++iE )
1090 const TopoDS_Shape& edge = shapes(iE);
1091 // find 2 faces sharing an edge
1093 PShapeIteratorPtr fIt = helper.GetAncestors(edge, *_mesh, TopAbs_FACE);
1094 while ( fIt->more())
1096 const TopoDS_Shape* f = fIt->next();
1097 if ( helper.IsSubShape( *f, _sdVec[i]._solid))
1098 FF[ int( !FF[0].IsNull()) ] = *f;
1100 if( FF[1].IsNull() ) continue; // seam edge can be shared by 1 FACE only
1101 // check presence of layers on them
1103 for ( int j = 0; j < 2; ++j )
1104 ignore[j] = _ignoreShapeIds.count ( getMeshDS()->ShapeToIndex( FF[j] ));
1105 if ( ignore[0] == ignore[1] ) continue; // nothing interesting
1106 TopoDS_Shape fWOL = FF[ ignore[0] ? 0 : 1 ];
1108 TGeomID edgeInd = getMeshDS()->ShapeToIndex( edge );
1109 _sdVec[i]._shrinkShape2Shape.insert( make_pair( edgeInd, fWOL ));
1112 // Exclude from _shrinkShape2Shape FACE's that can't be shrinked since
1113 // the algo of the SOLID sharing the FACE does not support it
1114 set< string > notSupportAlgos; notSupportAlgos.insert("Hexa_3D");
1115 for ( unsigned i = 0; i < _sdVec.size(); ++i )
1117 TopTools_MapOfShape noShrinkVertices;
1118 map< TGeomID, TopoDS_Shape >::iterator e2f = _sdVec[i]._shrinkShape2Shape.begin();
1119 for ( ; e2f != _sdVec[i]._shrinkShape2Shape.end(); ++e2f )
1121 const TopoDS_Shape& fWOL = e2f->second;
1122 TGeomID edgeID = e2f->first;
1123 bool notShrinkFace = false;
1124 PShapeIteratorPtr soIt = helper.GetAncestors(fWOL, *_mesh, TopAbs_SOLID);
1125 while ( soIt->more())
1127 const TopoDS_Shape* solid = soIt->next();
1128 if ( _sdVec[i]._solid.IsSame( *solid )) continue;
1129 SMESH_Algo* algo = _mesh->GetGen()->GetAlgo( *_mesh, *solid );
1130 if ( !algo || !notSupportAlgos.count( algo->GetName() )) continue;
1131 notShrinkFace = true;
1132 for ( unsigned j = 0; j < _sdVec.size(); ++j )
1134 if ( _sdVec[j]._solid.IsSame( *solid ) )
1135 if ( _sdVec[j]._shrinkShape2Shape.count( edgeID ))
1136 notShrinkFace = false;
1139 if ( notShrinkFace )
1141 _sdVec[i]._noShrinkFaces.insert( getMeshDS()->ShapeToIndex( fWOL ));
1142 for ( TopExp_Explorer vExp( fWOL, TopAbs_VERTEX ); vExp.More(); vExp.Next() )
1143 noShrinkVertices.Add( vExp.Current() );
1146 // erase from _shrinkShape2Shape all srink EDGE's of a SOLID connected
1147 // to the found not shrinked fWOL's
1148 e2f = _sdVec[i]._shrinkShape2Shape.begin();
1149 for ( ; e2f != _sdVec[i]._shrinkShape2Shape.end(); )
1151 TGeomID edgeID = e2f->first;
1152 TopoDS_Vertex VV[2];
1153 TopExp::Vertices( TopoDS::Edge( getMeshDS()->IndexToShape( edgeID )),VV[0],VV[1]);
1154 if ( noShrinkVertices.Contains( VV[0] ) || noShrinkVertices.Contains( VV[1] ))
1156 _sdVec[i]._noShrinkFaces.insert( getMeshDS()->ShapeToIndex( e2f->second ));
1157 _sdVec[i]._shrinkShape2Shape.erase( e2f++ );
1166 // Find the SHAPE along which to inflate _LayerEdge based on VERTEX
1168 for ( unsigned i = 0; i < _sdVec.size(); ++i )
1171 TopExp::MapShapes(_sdVec[i]._solid, TopAbs_VERTEX, shapes);
1172 for ( int iV = 1; iV <= shapes.Extent(); ++iV )
1174 const TopoDS_Shape& vertex = shapes(iV);
1175 // find faces WOL sharing the vertex
1176 vector< TopoDS_Shape > facesWOL;
1177 int totalNbFaces = 0;
1178 PShapeIteratorPtr fIt = helper.GetAncestors(vertex, *_mesh, TopAbs_FACE);
1179 while ( fIt->more())
1181 const TopoDS_Shape* f = fIt->next();
1182 const int fID = getMeshDS()->ShapeToIndex( *f );
1183 if ( helper.IsSubShape( *f, _sdVec[i]._solid ) )
1186 if ( _ignoreShapeIds.count ( fID ) && ! _sdVec[i]._noShrinkFaces.count( fID ))
1187 facesWOL.push_back( *f );
1190 if ( facesWOL.size() == totalNbFaces || facesWOL.empty() )
1191 continue; // no layers at this vertex or no WOL
1192 TGeomID vInd = getMeshDS()->ShapeToIndex( vertex );
1193 switch ( facesWOL.size() )
1197 helper.SetSubShape( facesWOL[0] );
1198 if ( helper.IsRealSeam( vInd )) // inflate along a seam edge?
1200 TopoDS_Shape seamEdge;
1201 PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
1202 while ( eIt->more() && seamEdge.IsNull() )
1204 const TopoDS_Shape* e = eIt->next();
1205 if ( helper.IsRealSeam( *e ) )
1208 if ( !seamEdge.IsNull() )
1210 _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, seamEdge ));
1214 _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, facesWOL[0] ));
1219 // find an edge shared by 2 faces
1220 PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
1221 while ( eIt->more())
1223 const TopoDS_Shape* e = eIt->next();
1224 if ( helper.IsSubShape( *e, facesWOL[0]) &&
1225 helper.IsSubShape( *e, facesWOL[1]))
1227 _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, *e )); break;
1233 return error("Not yet supported case", _sdVec[i]._index);
1241 //================================================================================
1243 * \brief Create the inner surface of the viscous layer and prepare data for infation
1245 //================================================================================
1247 bool _ViscousBuilder::makeLayer(_SolidData& data)
1249 // get all sub-shapes to make layers on
1250 set<TGeomID> subIds, faceIds;
1251 subIds = data._noShrinkFaces;
1252 TopExp_Explorer exp( data._solid, TopAbs_FACE );
1253 for ( ; exp.More(); exp.Next() )
1254 if ( ! _ignoreShapeIds.count( getMeshDS()->ShapeToIndex( exp.Current() )))
1256 SMESH_subMesh* fSubM = _mesh->GetSubMesh( exp.Current() );
1257 faceIds.insert( fSubM->GetId() );
1258 SMESH_subMeshIteratorPtr subIt =
1259 fSubM->getDependsOnIterator(/*includeSelf=*/true, /*complexShapeFirst=*/false);
1260 while ( subIt->more() )
1261 subIds.insert( subIt->next()->GetId() );
1264 // make a map to find new nodes on sub-shapes shared with other SOLID
1265 map< TGeomID, TNode2Edge* > s2neMap;
1266 map< TGeomID, TNode2Edge* >::iterator s2ne;
1267 map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
1268 for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
1270 TGeomID shapeInd = s2s->first;
1271 for ( unsigned i = 0; i < _sdVec.size(); ++i )
1273 if ( _sdVec[i]._index == data._index ) continue;
1274 map< TGeomID, TopoDS_Shape >::iterator s2s2 = _sdVec[i]._shrinkShape2Shape.find( shapeInd );
1275 if ( s2s2 != _sdVec[i]._shrinkShape2Shape.end() &&
1276 *s2s == *s2s2 && !_sdVec[i]._n2eMap.empty() )
1278 s2neMap.insert( make_pair( shapeInd, &_sdVec[i]._n2eMap ));
1284 // Create temporary faces and _LayerEdge's
1286 dumpFunction(SMESH_Comment("makeLayers_")<<data._index);
1288 data._stepSize = Precision::Infinite();
1289 data._stepSizeNodes[0] = 0;
1291 SMESH_MesherHelper helper( *_mesh );
1292 helper.SetSubShape( data._solid );
1293 helper.SetElementsOnShape(true);
1295 vector< const SMDS_MeshNode*> newNodes; // of a mesh face
1296 TNode2Edge::iterator n2e2;
1298 // collect _LayerEdge's of shapes they are based on
1299 const int nbShapes = getMeshDS()->MaxShapeIndex();
1300 vector< vector<_LayerEdge*> > edgesByGeom( nbShapes+1 );
1302 for ( set<TGeomID>::iterator id = faceIds.begin(); id != faceIds.end(); ++id )
1304 SMESHDS_SubMesh* smDS = getMeshDS()->MeshElements( *id );
1305 if ( !smDS ) return error(SMESH_Comment("Not meshed face ") << *id, data._index );
1307 const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( *id ));
1308 SMESH_ProxyMesh::SubMesh* proxySub =
1309 data._proxyMesh->getFaceSubM( F, /*create=*/true);
1311 SMDS_ElemIteratorPtr eIt = smDS->GetElements();
1312 while ( eIt->more() )
1314 const SMDS_MeshElement* face = eIt->next();
1315 newNodes.resize( face->NbCornerNodes() );
1316 double faceMaxCosin = -1;
1317 for ( int i = 0 ; i < face->NbCornerNodes(); ++i )
1319 const SMDS_MeshNode* n = face->GetNode(i);
1320 TNode2Edge::iterator n2e = data._n2eMap.insert( make_pair( n, (_LayerEdge*)0 )).first;
1321 if ( !(*n2e).second )
1324 _LayerEdge* edge = new _LayerEdge();
1326 edge->_nodes.push_back( n );
1327 const int shapeID = n->getshapeId();
1328 edgesByGeom[ shapeID ].push_back( edge );
1330 // set edge data or find already refined _LayerEdge and get data from it
1331 if ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE &&
1332 ( s2ne = s2neMap.find( shapeID )) != s2neMap.end() &&
1333 ( n2e2 = (*s2ne).second->find( n )) != s2ne->second->end())
1335 _LayerEdge* foundEdge = (*n2e2).second;
1336 edge->Copy( *foundEdge, helper );
1337 // location of the last node is modified but we can restore
1338 // it by node position on _sWOL stored by the node
1339 const_cast< SMDS_MeshNode* >
1340 ( edge->_nodes.back() )->setXYZ( n->X(), n->Y(), n->Z() );
1344 edge->_nodes.push_back( helper.AddNode( n->X(), n->Y(), n->Z() ));
1345 if ( !setEdgeData( *edge, subIds, helper, data ))
1348 dumpMove(edge->_nodes.back());
1349 if ( edge->_cosin > 0.01 )
1351 if ( edge->_cosin > faceMaxCosin )
1352 faceMaxCosin = edge->_cosin;
1355 newNodes[ i ] = n2e->second->_nodes.back();
1357 // create a temporary face
1358 const SMDS_MeshElement* newFace = new TmpMeshFace( newNodes, --_tmpFaceID );
1359 proxySub->AddElement( newFace );
1361 // compute inflation step size by min size of element on a convex surface
1362 if ( faceMaxCosin > 0.1 )
1363 limitStepSize( data, face, faceMaxCosin );
1364 } // loop on 2D elements on a FACE
1365 } // loop on FACEs of a SOLID
1367 data._epsilon = 1e-7;
1368 if ( data._stepSize < 1. )
1369 data._epsilon *= data._stepSize;
1371 // Put _LayerEdge's into a vector
1373 if ( !sortEdges( data, edgesByGeom ))
1376 // Set target nodes into _Simplex and _2NearEdges
1377 TNode2Edge::iterator n2e;
1378 for ( unsigned i = 0; i < data._edges.size(); ++i )
1380 if ( data._edges[i]->IsOnEdge())
1381 for ( int j = 0; j < 2; ++j )
1383 if ( data._edges[i]->_nodes.back()->NbInverseElements(SMDSAbs_Volume) > 0 )
1384 break; // _LayerEdge is shared by two _SolidData's
1385 const SMDS_MeshNode* & n = data._edges[i]->_2neibors->_nodes[j];
1386 if (( n2e = data._n2eMap.find( n )) == data._n2eMap.end() )
1387 return error("_LayerEdge not found by src node", data._index);
1388 n = (*n2e).second->_nodes.back();
1389 data._edges[i]->_2neibors->_edges[j] = n2e->second;
1392 for ( unsigned j = 0; j < data._edges[i]->_simplices.size(); ++j )
1394 _Simplex& s = data._edges[i]->_simplices[j];
1395 s._nNext = data._n2eMap[ s._nNext ]->_nodes.back();
1396 s._nPrev = data._n2eMap[ s._nPrev ]->_nodes.back();
1404 //================================================================================
1406 * \brief Compute inflation step size by min size of element on a convex surface
1408 //================================================================================
1410 void _ViscousBuilder::limitStepSize( _SolidData& data,
1411 const SMDS_MeshElement* face,
1415 double minSize = 10 * data._stepSize;
1416 const int nbNodes = face->NbCornerNodes();
1417 for ( int i = 0; i < nbNodes; ++i )
1419 const SMDS_MeshNode* nextN = face->GetNode( SMESH_MesherHelper::WrapIndex( i+1, nbNodes ));
1420 const SMDS_MeshNode* curN = face->GetNode( i );
1421 if ( nextN->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE ||
1422 curN->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE )
1424 double dist = SMESH_TNodeXYZ( face->GetNode(i)).Distance( nextN );
1425 if ( dist < minSize )
1426 minSize = dist, iN = i;
1429 double newStep = 0.8 * minSize / cosin;
1430 if ( newStep < data._stepSize )
1432 data._stepSize = newStep;
1433 data._stepSizeCoeff = 0.8 / cosin;
1434 data._stepSizeNodes[0] = face->GetNode( iN );
1435 data._stepSizeNodes[1] = face->GetNode( SMESH_MesherHelper::WrapIndex( iN+1, nbNodes ));
1439 //================================================================================
1441 * \brief Compute inflation step size by min size of element on a convex surface
1443 //================================================================================
1445 void _ViscousBuilder::limitStepSize( _SolidData& data, const double minSize)
1447 if ( minSize < data._stepSize )
1449 data._stepSize = minSize;
1450 if ( data._stepSizeNodes[0] )
1453 SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
1454 data._stepSizeCoeff = data._stepSize / dist;
1459 //================================================================================
1461 * \brief Separate shapes (and _LayerEdge's on them) to smooth from the rest ones
1463 //================================================================================
1465 bool _ViscousBuilder::sortEdges( _SolidData& data,
1466 vector< vector<_LayerEdge*> >& edgesByGeom)
1468 // Find shapes needing smoothing; such a shape has _LayerEdge._normal on it's
1469 // boundry inclined at a sharp angle to the shape
1471 list< TGeomID > shapesToSmooth;
1473 SMESH_MesherHelper helper( *_mesh );
1476 for ( unsigned iS = 0; iS < edgesByGeom.size(); ++iS )
1478 vector<_LayerEdge*>& eS = edgesByGeom[iS];
1479 if ( eS.empty() ) continue;
1480 TopoDS_Shape S = getMeshDS()->IndexToShape( iS );
1481 bool needSmooth = false;
1482 switch ( S.ShapeType() )
1486 bool isShrinkEdge = !eS[0]->_sWOL.IsNull();
1487 for ( TopoDS_Iterator vIt( S ); vIt.More() && !needSmooth; vIt.Next() )
1489 TGeomID iV = getMeshDS()->ShapeToIndex( vIt.Value() );
1490 vector<_LayerEdge*>& eV = edgesByGeom[ iV ];
1491 if ( eV.empty() ) continue;
1492 double cosin = eV[0]->_cosin;
1494 ( !eV[0]->_sWOL.IsNull() && ( eV[0]->_sWOL.ShapeType() == TopAbs_EDGE || !isShrinkEdge));
1498 if ( eV[0]->_sWOL.ShapeType() == TopAbs_EDGE )
1499 dir1 = getEdgeDir( TopoDS::Edge( eV[0]->_sWOL ), TopoDS::Vertex( vIt.Value() ));
1501 dir1 = getFaceDir( TopoDS::Face( eV[0]->_sWOL ), TopoDS::Vertex( vIt.Value() ),
1502 eV[0]->_nodes[0], helper, ok);
1503 dir2 = getEdgeDir( TopoDS::Edge( S ), TopoDS::Vertex( vIt.Value() ));
1504 double angle = dir1.Angle( dir2 );
1505 cosin = cos( angle );
1507 needSmooth = ( cosin > 0.1 );
1513 for ( TopExp_Explorer eExp( S, TopAbs_EDGE ); eExp.More() && !needSmooth; eExp.Next() )
1515 TGeomID iE = getMeshDS()->ShapeToIndex( eExp.Current() );
1516 vector<_LayerEdge*>& eE = edgesByGeom[ iE ];
1517 if ( eE.empty() ) continue;
1518 if ( eE[0]->_sWOL.IsNull() )
1520 for ( unsigned i = 0; i < eE.size() && !needSmooth; ++i )
1521 needSmooth = ( eE[i]->_cosin > 0.1 );
1525 const TopoDS_Face& F1 = TopoDS::Face( S );
1526 const TopoDS_Face& F2 = TopoDS::Face( eE[0]->_sWOL );
1527 const TopoDS_Edge& E = TopoDS::Edge( eExp.Current() );
1528 for ( unsigned i = 0; i < eE.size() && !needSmooth; ++i )
1530 gp_Vec dir1 = getFaceDir( F1, E, eE[i]->_nodes[0], helper, ok );
1531 gp_Vec dir2 = getFaceDir( F2, E, eE[i]->_nodes[0], helper, ok );
1532 double angle = dir1.Angle( dir2 );
1533 double cosin = cos( angle );
1534 needSmooth = ( cosin > 0.1 );
1546 if ( S.ShapeType() == TopAbs_EDGE ) shapesToSmooth.push_front( iS );
1547 else shapesToSmooth.push_back ( iS );
1550 } // loop on edgesByGeom
1552 data._edges.reserve( data._n2eMap.size() );
1553 data._endEdgeToSmooth.clear();
1555 // first we put _LayerEdge's on shapes to smooth
1556 list< TGeomID >::iterator gIt = shapesToSmooth.begin();
1557 for ( ; gIt != shapesToSmooth.end(); ++gIt )
1559 vector<_LayerEdge*>& eVec = edgesByGeom[ *gIt ];
1560 if ( eVec.empty() ) continue;
1561 data._edges.insert( data._edges.end(), eVec.begin(), eVec.end() );
1562 data._endEdgeToSmooth.push_back( data._edges.size() );
1566 // then the rest _LayerEdge's
1567 for ( unsigned iS = 0; iS < edgesByGeom.size(); ++iS )
1569 vector<_LayerEdge*>& eVec = edgesByGeom[iS];
1570 data._edges.insert( data._edges.end(), eVec.begin(), eVec.end() );
1577 //================================================================================
1579 * \brief Set data of _LayerEdge needed for smoothing
1580 * \param subIds - ids of sub-shapes of a SOLID to take into account faces from
1582 //================================================================================
1584 bool _ViscousBuilder::setEdgeData(_LayerEdge& edge,
1585 const set<TGeomID>& subIds,
1586 SMESH_MesherHelper& helper,
1589 SMESH_MeshEditor editor(_mesh);
1591 const SMDS_MeshNode* node = edge._nodes[0]; // source node
1592 SMDS_TypeOfPosition posType = node->GetPosition()->GetTypeOfPosition();
1596 edge._curvature = 0;
1598 // --------------------------
1599 // Compute _normal and _cosin
1600 // --------------------------
1603 edge._normal.SetCoord(0,0,0);
1605 int totalNbFaces = 0;
1607 gp_Vec du, dv, geomNorm;
1610 TGeomID shapeInd = node->getshapeId();
1611 map< TGeomID, TopoDS_Shape >::const_iterator s2s = data._shrinkShape2Shape.find( shapeInd );
1612 bool onShrinkShape ( s2s != data._shrinkShape2Shape.end() );
1613 TopoDS_Shape vertEdge;
1615 if ( onShrinkShape ) // one of faces the node is on has no layers
1617 vertEdge = getMeshDS()->IndexToShape( s2s->first ); // vertex or edge
1618 if ( s2s->second.ShapeType() == TopAbs_EDGE )
1620 // inflate from VERTEX along EDGE
1621 edge._normal = getEdgeDir( TopoDS::Edge( s2s->second ), TopoDS::Vertex( vertEdge ));
1623 else if ( vertEdge.ShapeType() == TopAbs_VERTEX )
1625 // inflate from VERTEX along FACE
1626 edge._normal = getFaceDir( TopoDS::Face( s2s->second ), TopoDS::Vertex( vertEdge ),
1627 node, helper, normOK, &edge._cosin);
1631 // inflate from EDGE along FACE
1632 edge._normal = getFaceDir( TopoDS::Face( s2s->second ), TopoDS::Edge( vertEdge ),
1633 node, helper, normOK);
1636 else // layers are on all faces of SOLID the node is on
1638 // find indices of geom faces the node lies on
1639 set<TGeomID> faceIds;
1640 if ( posType == SMDS_TOP_FACE )
1642 faceIds.insert( node->getshapeId() );
1646 SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
1647 while ( fIt->more() )
1648 faceIds.insert( editor.FindShape(fIt->next()));
1651 set<TGeomID>::iterator id = faceIds.begin();
1653 for ( ; id != faceIds.end(); ++id )
1655 const TopoDS_Shape& s = getMeshDS()->IndexToShape( *id );
1656 if ( s.IsNull() || s.ShapeType() != TopAbs_FACE || !subIds.count( *id ))
1659 //nbLayerFaces += subIds.count( *id );
1660 F = TopoDS::Face( s );
1662 gp_XY uv = helper.GetNodeUV( F, node, 0, &normOK );
1663 Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
1664 surface->D1( uv.X(),uv.Y(), p, du,dv );
1666 double size2 = geomNorm.SquareMagnitude();
1667 if ( size2 > numeric_limits<double>::min() )
1668 geomNorm /= sqrt( size2 );
1671 if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
1673 edge._normal += geomNorm.XYZ();
1675 if ( totalNbFaces == 0 )
1676 return error(SMESH_Comment("Can't get normal to node ") << node->GetID(), data._index);
1678 edge._normal /= totalNbFaces;
1683 edge._cosin = 0; break;
1685 case SMDS_TOP_EDGE: {
1686 TopoDS_Edge E = TopoDS::Edge( helper.GetSubShapeByNode( node, getMeshDS()));
1687 gp_Vec inFaceDir = getFaceDir( F, E, node, helper, normOK);
1688 double angle = inFaceDir.Angle( edge._normal ); // [0,PI]
1689 edge._cosin = cos( angle );
1690 //cout << "Cosin on EDGE " << edge._cosin << " node " << node->GetID() << endl;
1693 case SMDS_TOP_VERTEX: {
1694 TopoDS_Vertex V = TopoDS::Vertex( helper.GetSubShapeByNode( node, getMeshDS()));
1695 gp_Vec inFaceDir = getFaceDir( F, V, node, helper, normOK);
1696 double angle = inFaceDir.Angle( edge._normal ); // [0,PI]
1697 edge._cosin = cos( angle );
1698 //cout << "Cosin on VERTEX " << edge._cosin << " node " << node->GetID() << endl;
1702 return error(SMESH_Comment("Invalid shape position of node ")<<node, data._index);
1706 double normSize = edge._normal.SquareModulus();
1707 if ( normSize < numeric_limits<double>::min() )
1708 return error(SMESH_Comment("Bad normal at node ")<< node->GetID(), data._index );
1710 edge._normal /= sqrt( normSize );
1712 // TODO: if ( !normOK ) then get normal by mesh faces
1714 // Set the rest data
1715 // --------------------
1716 if ( onShrinkShape )
1718 edge._sWOL = (*s2s).second;
1720 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edge._nodes.back() );
1721 if ( SMESHDS_SubMesh* sm = getMeshDS()->MeshElements( data._solid ))
1722 sm->RemoveNode( tgtNode , /*isNodeDeleted=*/false );
1724 // set initial position which is parameters on _sWOL in this case
1725 if ( edge._sWOL.ShapeType() == TopAbs_EDGE )
1727 double u = helper.GetNodeU( TopoDS::Edge( edge._sWOL ), node, 0, &normOK );
1728 edge._pos.push_back( gp_XYZ( u, 0, 0));
1729 getMeshDS()->SetNodeOnEdge( tgtNode, TopoDS::Edge( edge._sWOL ), u );
1733 gp_XY uv = helper.GetNodeUV( TopoDS::Face( edge._sWOL ), node, 0, &normOK );
1734 edge._pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
1735 getMeshDS()->SetNodeOnFace( tgtNode, TopoDS::Face( edge._sWOL ), uv.X(), uv.Y() );
1740 edge._pos.push_back( SMESH_TNodeXYZ( node ));
1742 if ( posType == SMDS_TOP_FACE )
1744 getSimplices( node, edge._simplices, _ignoreShapeIds, &data );
1745 double avgNormProj = 0, avgLen = 0;
1746 for ( unsigned i = 0; i < edge._simplices.size(); ++i )
1748 gp_XYZ vec = edge._pos.back() - SMESH_TNodeXYZ( edge._simplices[i]._nPrev );
1749 avgNormProj += edge._normal * vec;
1750 avgLen += vec.Modulus();
1752 avgNormProj /= edge._simplices.size();
1753 avgLen /= edge._simplices.size();
1754 edge._curvature = _Curvature::New( avgNormProj, avgLen );
1758 // Set neighbour nodes for a _LayerEdge based on EDGE
1760 if ( posType == SMDS_TOP_EDGE /*||
1761 ( onShrinkShape && posType == SMDS_TOP_VERTEX && fabs( edge._cosin ) < 1e-10 )*/)
1763 edge._2neibors = new _2NearEdges;
1764 // target node instead of source ones will be set later
1765 if ( ! findNeiborsOnEdge( &edge,
1766 edge._2neibors->_nodes[0],
1767 edge._2neibors->_nodes[1],
1770 edge.SetDataByNeighbors( edge._2neibors->_nodes[0],
1771 edge._2neibors->_nodes[1],
1775 edge.SetCosin( edge._cosin ); // to update edge._lenFactor
1780 //================================================================================
1782 * \brief Find 2 neigbor nodes of a node on EDGE
1784 //================================================================================
1786 bool _ViscousBuilder::findNeiborsOnEdge(const _LayerEdge* edge,
1787 const SMDS_MeshNode*& n1,
1788 const SMDS_MeshNode*& n2,
1791 const SMDS_MeshNode* node = edge->_nodes[0];
1792 const int shapeInd = node->getshapeId();
1793 SMESHDS_SubMesh* edgeSM = 0;
1794 if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_EDGE )
1797 edgeSM = getMeshDS()->MeshElements( shapeInd );
1798 if ( !edgeSM || edgeSM->NbElements() == 0 )
1799 return error(SMESH_Comment("Not meshed EDGE ") << shapeInd, data._index);
1803 SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator(SMDSAbs_Edge);
1804 while ( eIt->more() && !n2 )
1806 const SMDS_MeshElement* e = eIt->next();
1807 const SMDS_MeshNode* nNeibor = e->GetNode( 0 );
1808 if ( nNeibor == node ) nNeibor = e->GetNode( 1 );
1811 if (!edgeSM->Contains(e)) continue;
1815 TopoDS_Shape s = SMESH_MesherHelper::GetSubShapeByNode(nNeibor, getMeshDS() );
1816 if ( !SMESH_MesherHelper::IsSubShape( s, edge->_sWOL )) continue;
1818 ( iN++ ? n2 : n1 ) = nNeibor;
1821 return error(SMESH_Comment("Wrongly meshed EDGE ") << shapeInd, data._index);
1825 //================================================================================
1827 * \brief Set _curvature and _2neibors->_plnNorm by 2 neigbor nodes residing the same EDGE
1829 //================================================================================
1831 void _LayerEdge::SetDataByNeighbors( const SMDS_MeshNode* n1,
1832 const SMDS_MeshNode* n2,
1833 SMESH_MesherHelper& helper)
1835 if ( _nodes[0]->GetPosition()->GetTypeOfPosition() != SMDS_TOP_EDGE )
1838 gp_XYZ pos = SMESH_TNodeXYZ( _nodes[0] );
1839 gp_XYZ vec1 = pos - SMESH_TNodeXYZ( n1 );
1840 gp_XYZ vec2 = pos - SMESH_TNodeXYZ( n2 );
1844 double sumLen = vec1.Modulus() + vec2.Modulus();
1845 _2neibors->_wgt[0] = 1 - vec1.Modulus() / sumLen;
1846 _2neibors->_wgt[1] = 1 - vec2.Modulus() / sumLen;
1847 double avgNormProj = 0.5 * ( _normal * vec1 + _normal * vec2 );
1848 double avgLen = 0.5 * ( vec1.Modulus() + vec2.Modulus() );
1849 if ( _curvature ) delete _curvature;
1850 _curvature = _Curvature::New( avgNormProj, avgLen );
1852 // if ( _curvature )
1853 // cout << _nodes[0]->GetID()
1854 // << " CURV r,k: " << _curvature->_r<<","<<_curvature->_k
1855 // << " proj = "<<avgNormProj<< " len = " << avgLen << "| lenDelta(0) = "
1856 // << _curvature->lenDelta(0) << endl;
1861 if ( _sWOL.IsNull() )
1863 TopoDS_Shape S = helper.GetSubShapeByNode( _nodes[0], helper.GetMeshDS() );
1864 gp_XYZ dirE = getEdgeDir( TopoDS::Edge( S ), _nodes[0], helper );
1865 gp_XYZ plnNorm = dirE ^ _normal;
1866 double proj0 = plnNorm * vec1;
1867 double proj1 = plnNorm * vec2;
1868 if ( fabs( proj0 ) > 1e-10 || fabs( proj1 ) > 1e-10 )
1870 if ( _2neibors->_plnNorm ) delete _2neibors->_plnNorm;
1871 _2neibors->_plnNorm = new gp_XYZ( plnNorm.Normalized() );
1876 //================================================================================
1878 * \brief Copy data from a _LayerEdge of other SOLID and based on the same node;
1879 * this and other _LayerEdge's are inflated along a FACE or an EDGE
1881 //================================================================================
1883 void _LayerEdge::Copy( _LayerEdge& other, SMESH_MesherHelper& helper )
1885 _nodes = other._nodes;
1886 _normal = other._normal;
1888 _lenFactor = other._lenFactor;
1889 _cosin = other._cosin;
1890 _sWOL = other._sWOL;
1891 _2neibors = other._2neibors;
1892 _curvature = 0; std::swap( _curvature, other._curvature );
1893 _2neibors = 0; std::swap( _2neibors, other._2neibors );
1895 if ( _sWOL.ShapeType() == TopAbs_EDGE )
1897 double u = helper.GetNodeU( TopoDS::Edge( _sWOL ), _nodes[0] );
1898 _pos.push_back( gp_XYZ( u, 0, 0));
1902 gp_XY uv = helper.GetNodeUV( TopoDS::Face( _sWOL ), _nodes[0]);
1903 _pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
1907 //================================================================================
1909 * \brief Set _cosin and _lenFactor
1911 //================================================================================
1913 void _LayerEdge::SetCosin( double cosin )
1916 _lenFactor = ( _cosin > 0.1 ) ? 1./sqrt(1-_cosin*_cosin) : 1.0;
1919 //================================================================================
1921 * \brief Fills a vector<_Simplex >
1923 //================================================================================
1925 void _ViscousBuilder::getSimplices( const SMDS_MeshNode* node,
1926 vector<_Simplex>& simplices,
1927 const set<TGeomID>& ingnoreShapes,
1928 const _SolidData* dataToCheckOri,
1931 SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
1932 while ( fIt->more() )
1934 const SMDS_MeshElement* f = fIt->next();
1935 const TGeomID shapeInd = f->getshapeId();
1936 if ( ingnoreShapes.count( shapeInd )) continue;
1937 const int nbNodes = f->NbCornerNodes();
1938 int srcInd = f->GetNodeIndex( node );
1939 const SMDS_MeshNode* nPrev = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd-1, nbNodes ));
1940 const SMDS_MeshNode* nNext = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+1, nbNodes ));
1941 if ( dataToCheckOri && dataToCheckOri->_reversedFaceIds.count( shapeInd ))
1942 std::swap( nPrev, nNext );
1943 simplices.push_back( _Simplex( nPrev, nNext ));
1948 vector<_Simplex> sortedSimplices( simplices.size() );
1949 sortedSimplices[0] = simplices[0];
1951 for ( size_t i = 1; i < simplices.size(); ++i )
1953 for ( size_t j = 1; j < simplices.size(); ++j )
1954 if ( sortedSimplices[i-1]._nNext == simplices[j]._nPrev )
1956 sortedSimplices[i] = simplices[j];
1961 if ( nbFound == simplices.size() - 1 )
1962 simplices.swap( sortedSimplices );
1966 //================================================================================
1968 * \brief DEBUG. Create groups contating temorary data of _LayerEdge's
1970 //================================================================================
1972 void _ViscousBuilder::makeGroupOfLE()
1975 for ( unsigned i = 0 ; i < _sdVec.size(); ++i )
1977 if ( _sdVec[i]._edges.empty() ) continue;
1978 // string name = SMESH_Comment("_LayerEdge's_") << i;
1980 // SMESH_Group* g = _mesh->AddGroup(SMDSAbs_Edge, name.c_str(), id );
1981 // SMESHDS_Group* gDS = (SMESHDS_Group*)g->GetGroupDS();
1982 // SMESHDS_Mesh* mDS = _mesh->GetMeshDS();
1984 dumpFunction( SMESH_Comment("make_LayerEdge_") << i );
1985 for ( unsigned j = 0 ; j < _sdVec[i]._edges.size(); ++j )
1987 _LayerEdge* le = _sdVec[i]._edges[j];
1988 for ( unsigned iN = 1; iN < le->_nodes.size(); ++iN )
1989 dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<le->_nodes[iN-1]->GetID()
1990 << ", " << le->_nodes[iN]->GetID() <<"])");
1991 //gDS->SMDSGroup().Add( mDS->AddEdge( le->_nodes[iN-1], le->_nodes[iN]));
1995 dumpFunction( SMESH_Comment("makeNormals") << i );
1996 for ( unsigned j = 0 ; j < _sdVec[i]._edges.size(); ++j )
1998 _LayerEdge& edge = *_sdVec[i]._edges[j];
1999 SMESH_TNodeXYZ nXYZ( edge._nodes[0] );
2000 nXYZ += edge._normal * _sdVec[i]._stepSize;
2001 dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<edge._nodes[0]->GetID()
2002 << ", mesh.AddNode( " << nXYZ.X()<<","<< nXYZ.Y()<<","<< nXYZ.Z()<<")])");
2006 // name = SMESH_Comment("tmp_faces ") << i;
2007 // g = _mesh->AddGroup(SMDSAbs_Face, name.c_str(), id );
2008 // gDS = (SMESHDS_Group*)g->GetGroupDS();
2009 // SMESH_MeshEditor editor( _mesh );
2010 dumpFunction( SMESH_Comment("makeTmpFaces_") << i );
2011 TopExp_Explorer fExp( _sdVec[i]._solid, TopAbs_FACE );
2012 for ( ; fExp.More(); fExp.Next() )
2014 if (const SMESHDS_SubMesh* sm = _sdVec[i]._proxyMesh->GetProxySubMesh( fExp.Current()))
2016 SMDS_ElemIteratorPtr fIt = sm->GetElements();
2017 while ( fIt->more())
2019 const SMDS_MeshElement* e = fIt->next();
2020 SMESH_Comment cmd("mesh.AddFace([");
2021 for ( int j=0; j < e->NbCornerNodes(); ++j )
2022 cmd << e->GetNode(j)->GetID() << (j+1<e->NbCornerNodes() ? ",": "])");
2024 //vector<const SMDS_MeshNode*> nodes( e->begin_nodes(), e->end_nodes() );
2025 //gDS->SMDSGroup().Add( editor.AddElement( nodes, e->GetType(), e->IsPoly()));
2034 //================================================================================
2036 * \brief Increase length of _LayerEdge's to reach the required thickness of layers
2038 //================================================================================
2040 bool _ViscousBuilder::inflate(_SolidData& data)
2042 SMESH_MesherHelper helper( *_mesh );
2044 // Limit inflation step size by geometry size found by itersecting
2045 // normals of _LayerEdge's with mesh faces
2046 double geomSize = Precision::Infinite(), intersecDist;
2047 SMESH_MeshEditor editor( _mesh );
2048 auto_ptr<SMESH_ElementSearcher> searcher
2049 ( editor.GetElementSearcher( data._proxyMesh->GetFaces( data._solid )) );
2050 for ( unsigned i = 0; i < data._edges.size(); ++i )
2052 if ( data._edges[i]->IsOnEdge() ) continue;
2053 data._edges[i]->FindIntersection( *searcher, intersecDist, data._epsilon );
2054 if ( geomSize > intersecDist )
2055 geomSize = intersecDist;
2057 if ( data._stepSize > 0.3 * geomSize )
2058 limitStepSize( data, 0.3 * geomSize );
2060 const double tgtThick = data._hyp->GetTotalThickness();
2061 if ( data._stepSize > tgtThick )
2062 limitStepSize( data, tgtThick );
2064 if ( data._stepSize < 1. )
2065 data._epsilon = data._stepSize * 1e-7;
2068 cout << "-- geomSize = " << geomSize << ", stepSize = " << data._stepSize << endl;
2071 double avgThick = 0, curThick = 0, distToIntersection = Precision::Infinite();
2072 int nbSteps = 0, nbRepeats = 0;
2073 while ( 1.01 * avgThick < tgtThick )
2075 // new target length
2076 curThick += data._stepSize;
2077 if ( curThick > tgtThick )
2079 curThick = tgtThick + ( tgtThick-avgThick ) * nbRepeats;
2083 // Elongate _LayerEdge's
2084 dumpFunction(SMESH_Comment("inflate")<<data._index<<"_step"<<nbSteps); // debug
2085 for ( unsigned i = 0; i < data._edges.size(); ++i )
2087 data._edges[i]->SetNewLength( curThick, helper );
2092 if ( !updateNormals( data, helper ) )
2095 // Improve and check quality
2096 if ( !smoothAndCheck( data, nbSteps, distToIntersection ))
2100 dumpFunction(SMESH_Comment("invalidate")<<data._index<<"_step"<<nbSteps); // debug
2101 for ( unsigned i = 0; i < data._edges.size(); ++i )
2103 data._edges[i]->InvalidateStep( nbSteps+1 );
2107 break; // no more inflating possible
2111 // Evaluate achieved thickness
2113 for ( unsigned i = 0; i < data._edges.size(); ++i )
2114 avgThick += data._edges[i]->_len;
2115 avgThick /= data._edges.size();
2117 cout << "-- Thickness " << avgThick << " reached" << endl;
2120 if ( distToIntersection < avgThick*1.5 )
2123 cout << "-- Stop inflation since distToIntersection( "<<distToIntersection<<" ) < avgThick( "
2124 << avgThick << " ) * 1.5" << endl;
2129 limitStepSize( data, 0.25 * distToIntersection );
2130 if ( data._stepSizeNodes[0] )
2131 data._stepSize = data._stepSizeCoeff *
2132 SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
2136 return error("failed at the very first inflation step", data._index);
2141 //================================================================================
2143 * \brief Improve quality of layer inner surface and check intersection
2145 //================================================================================
2147 bool _ViscousBuilder::smoothAndCheck(_SolidData& data,
2149 double & distToIntersection)
2151 if ( data._endEdgeToSmooth.empty() )
2152 return true; // no shapes needing smoothing
2154 bool moved, improved;
2156 SMESH_MesherHelper helper(*_mesh);
2157 Handle(Geom_Surface) surface;
2161 for ( unsigned iS = 0; iS < data._endEdgeToSmooth.size(); ++iS )
2164 iEnd = data._endEdgeToSmooth[ iS ];
2166 if ( !data._edges[ iBeg ]->_sWOL.IsNull() &&
2167 data._edges[ iBeg ]->_sWOL.ShapeType() == TopAbs_FACE )
2169 if ( !F.IsSame( data._edges[ iBeg ]->_sWOL )) {
2170 F = TopoDS::Face( data._edges[ iBeg ]->_sWOL );
2171 helper.SetSubShape( F );
2172 surface = BRep_Tool::Surface( F );
2177 F.Nullify(); surface.Nullify();
2179 TGeomID sInd = data._edges[ iBeg ]->_nodes[0]->getshapeId();
2181 if ( data._edges[ iBeg ]->IsOnEdge() )
2183 dumpFunction(SMESH_Comment("smooth")<<data._index << "_Ed"<<sInd <<"_InfStep"<<nbSteps);
2185 // try a simple solution on an analytic EDGE
2186 if ( !smoothAnalyticEdge( data, iBeg, iEnd, surface, F, helper ))
2192 for ( int i = iBeg; i < iEnd; ++i )
2194 moved |= data._edges[i]->SmoothOnEdge(surface, F, helper);
2196 dumpCmd( SMESH_Comment("# end step ")<<step);
2198 while ( moved && step++ < 5 );
2199 //cout << " NB STEPS: " << step << endl;
2206 int step = 0, badNb = 0; moved = true;
2207 while (( ++step <= 5 && moved ) || improved )
2209 dumpFunction(SMESH_Comment("smooth")<<data._index<<"_Fa"<<sInd
2210 <<"_InfStep"<<nbSteps<<"_"<<step); // debug
2211 int oldBadNb = badNb;
2214 for ( int i = iBeg; i < iEnd; ++i )
2215 moved |= data._edges[i]->Smooth(badNb);
2216 improved = ( badNb < oldBadNb );
2223 for ( int i = iBeg; i < iEnd; ++i )
2225 _LayerEdge* edge = data._edges[i];
2226 SMESH_TNodeXYZ tgtXYZ( edge->_nodes.back() );
2227 for ( unsigned j = 0; j < edge->_simplices.size(); ++j )
2228 if ( !edge->_simplices[j].IsForward( edge->_nodes[0], &tgtXYZ ))
2230 cout << "Bad simplex ( " << edge->_nodes[0]->GetID()<< " "<< tgtXYZ._node->GetID()
2231 << " "<< edge->_simplices[j]._nPrev->GetID()
2232 << " "<< edge->_simplices[j]._nNext->GetID() << " )" << endl;
2240 } // loop on shapes to smooth
2242 // Check if the last segments of _LayerEdge intersects 2D elements;
2243 // checked elements are either temporary faces or faces on surfaces w/o the layers
2245 SMESH_MeshEditor editor( _mesh );
2246 auto_ptr<SMESH_ElementSearcher> searcher
2247 ( editor.GetElementSearcher( data._proxyMesh->GetFaces( data._solid )) );
2249 distToIntersection = Precision::Infinite();
2251 const SMDS_MeshElement* intFace = 0;
2253 const SMDS_MeshElement* closestFace = 0;
2256 for ( unsigned i = 0; i < data._edges.size(); ++i )
2258 if ( data._edges[i]->FindIntersection( *searcher, dist, data._epsilon, &intFace ))
2260 if ( distToIntersection > dist )
2262 distToIntersection = dist;
2265 closestFace = intFace;
2272 SMDS_MeshElement::iterator nIt = closestFace->begin_nodes();
2273 cout << "Shortest distance: _LayerEdge nodes: tgt " << data._edges[iLE]->_nodes.back()->GetID()
2274 << " src " << data._edges[iLE]->_nodes[0]->GetID()<< ", intersection with face ("
2275 << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
2276 << ") distance = " << distToIntersection<< endl;
2283 //================================================================================
2285 * \brief Return a curve of the EDGE to be used for smoothing and arrange
2286 * _LayerEdge's to be in a consequent order
2288 //================================================================================
2290 Handle(Geom_Curve) _SolidData::CurveForSmooth( const TopoDS_Edge& E,
2293 Handle(Geom_Surface)& surface,
2294 const TopoDS_Face& F,
2295 SMESH_MesherHelper& helper)
2297 TGeomID eIndex = helper.GetMeshDS()->ShapeToIndex( E );
2299 map< TGeomID, Handle(Geom_Curve)>::iterator i2curve = _edge2curve.find( eIndex );
2301 if ( i2curve == _edge2curve.end() )
2303 // sort _LayerEdge's by position on the EDGE
2305 map< double, _LayerEdge* > u2edge;
2306 for ( int i = iFrom; i < iTo; ++i )
2307 u2edge.insert( make_pair( helper.GetNodeU( E, _edges[i]->_nodes[0] ), _edges[i] ));
2309 ASSERT( u2edge.size() == iTo - iFrom );
2310 map< double, _LayerEdge* >::iterator u2e = u2edge.begin();
2311 for ( int i = iFrom; i < iTo; ++i, ++u2e )
2312 _edges[i] = u2e->second;
2314 // set _2neibors according to the new order
2315 for ( int i = iFrom; i < iTo-1; ++i )
2316 if ( _edges[i]->_2neibors->_nodes[1] != _edges[i+1]->_nodes.back() )
2317 _edges[i]->_2neibors->reverse();
2318 if ( u2edge.size() > 1 &&
2319 _edges[iTo-1]->_2neibors->_nodes[0] != _edges[iTo-2]->_nodes.back() )
2320 _edges[iTo-1]->_2neibors->reverse();
2323 SMESHDS_SubMesh* smDS = helper.GetMeshDS()->MeshElements( eIndex );
2325 TopLoc_Location loc; double f,l;
2327 Handle(Geom_Line) line;
2328 Handle(Geom_Circle) circle;
2329 bool isLine, isCirc;
2330 if ( F.IsNull() ) // 3D case
2332 // check if the EDGE is a line
2333 Handle(Geom_Curve) curve = BRep_Tool::Curve( E, loc, f, l);
2334 if ( curve->IsKind( STANDARD_TYPE( Geom_TrimmedCurve )))
2335 curve = Handle(Geom_TrimmedCurve)::DownCast( curve )->BasisCurve();
2337 line = Handle(Geom_Line)::DownCast( curve );
2338 circle = Handle(Geom_Circle)::DownCast( curve );
2339 isLine = (!line.IsNull());
2340 isCirc = (!circle.IsNull());
2342 if ( !isLine && !isCirc ) // Check if the EDGE is close to a line
2345 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
2346 while ( nIt->more() )
2347 bndBox.Add( SMESH_TNodeXYZ( nIt->next() ));
2348 gp_XYZ size = bndBox.CornerMax() - bndBox.CornerMin();
2350 SMESH_TNodeXYZ p0( _edges[iFrom]->_2neibors->_nodes[0] );
2351 SMESH_TNodeXYZ p1( _edges[iFrom]->_2neibors->_nodes[1] );
2352 const double lineTol = 1e-2 * ( p0 - p1 ).Modulus();
2353 for ( int i = 0; i < 3 && !isLine; ++i )
2354 isLine = ( size.Coord( i+1 ) <= lineTol );
2356 if ( !isLine && !isCirc && iTo-iFrom > 2) // Check if the EDGE is close to a circle
2363 // check if the EDGE is a line
2364 Handle(Geom2d_Curve) curve = BRep_Tool::CurveOnSurface( E, F, f, l);
2365 if ( curve->IsKind( STANDARD_TYPE( Geom2d_TrimmedCurve )))
2366 curve = Handle(Geom2d_TrimmedCurve)::DownCast( curve )->BasisCurve();
2368 Handle(Geom2d_Line) line2d = Handle(Geom2d_Line)::DownCast( curve );
2369 Handle(Geom2d_Circle) circle2d = Handle(Geom2d_Circle)::DownCast( curve );
2370 isLine = (!line2d.IsNull());
2371 isCirc = (!circle2d.IsNull());
2373 if ( !isLine && !isCirc) // Check if the EDGE is close to a line
2376 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
2377 while ( nIt->more() )
2378 bndBox.Add( helper.GetNodeUV( F, nIt->next() ));
2379 gp_XY size = bndBox.CornerMax() - bndBox.CornerMin();
2381 const double lineTol = 1e-2 * sqrt( bndBox.SquareExtent() );
2382 for ( int i = 0; i < 2 && !isLine; ++i )
2383 isLine = ( size.Coord( i+1 ) <= lineTol );
2385 if ( !isLine && !isCirc && iTo-iFrom > 2) // Check if the EDGE is close to a circle
2391 line = new Geom_Line( gp::OX() ); // only type does matter
2395 gp_Pnt2d p = circle2d->Location();
2396 gp_Ax2 ax( gp_Pnt( p.X(), p.Y(), 0), gp::DX());
2397 circle = new Geom_Circle( ax, 1.); // only center position does matter
2401 Handle(Geom_Curve)& res = _edge2curve[ eIndex ];
2409 return i2curve->second;
2412 //================================================================================
2414 * \brief smooth _LayerEdge's on a staight EDGE or circular EDGE
2416 //================================================================================
2418 bool _ViscousBuilder::smoothAnalyticEdge( _SolidData& data,
2421 Handle(Geom_Surface)& surface,
2422 const TopoDS_Face& F,
2423 SMESH_MesherHelper& helper)
2425 TopoDS_Shape S = helper.GetSubShapeByNode( data._edges[ iFrom ]->_nodes[0],
2426 helper.GetMeshDS());
2427 TopoDS_Edge E = TopoDS::Edge( S );
2429 Handle(Geom_Curve) curve = data.CurveForSmooth( E, iFrom, iTo, surface, F, helper );
2430 if ( curve.IsNull() ) return false;
2432 // compute a relative length of segments
2433 vector< double > len( iTo-iFrom+1 );
2435 double curLen, prevLen = len[0] = 1.0;
2436 for ( int i = iFrom; i < iTo; ++i )
2438 curLen = prevLen * data._edges[i]->_2neibors->_wgt[0] / data._edges[i]->_2neibors->_wgt[1];
2439 len[i-iFrom+1] = len[i-iFrom] + curLen;
2444 if ( curve->IsKind( STANDARD_TYPE( Geom_Line )))
2446 if ( F.IsNull() ) // 3D
2448 SMESH_TNodeXYZ p0( data._edges[iFrom]->_2neibors->_nodes[0]);
2449 SMESH_TNodeXYZ p1( data._edges[iTo-1]->_2neibors->_nodes[1]);
2450 for ( int i = iFrom; i < iTo; ++i )
2452 double r = len[i-iFrom] / len.back();
2453 gp_XYZ newPos = p0 * ( 1. - r ) + p1 * r;
2454 data._edges[i]->_pos.back() = newPos;
2455 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( data._edges[i]->_nodes.back() );
2456 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
2457 dumpMove( tgtNode );
2462 gp_XY uv0 = helper.GetNodeUV( F, data._edges[iFrom]->_2neibors->_nodes[0]);
2463 gp_XY uv1 = helper.GetNodeUV( F, data._edges[iTo-1]->_2neibors->_nodes[1]);
2464 if ( data._edges[iFrom]->_2neibors->_nodes[0] ==
2465 data._edges[iTo-1]->_2neibors->_nodes[1] ) // closed edge
2467 int iPeriodic = helper.GetPeriodicIndex();
2468 if ( iPeriodic == 1 || iPeriodic == 2 )
2470 uv1.SetCoord( iPeriodic, helper.GetOtherParam( uv1.Coord( iPeriodic )));
2471 if ( uv0.Coord( iPeriodic ) > uv1.Coord( iPeriodic ))
2472 std::swap( uv0, uv1 );
2475 const gp_XY rangeUV = uv1 - uv0;
2476 for ( int i = iFrom; i < iTo; ++i )
2478 double r = len[i-iFrom] / len.back();
2479 gp_XY newUV = uv0 + r * rangeUV;
2480 data._edges[i]->_pos.back().SetCoord( newUV.X(), newUV.Y(), 0 );
2482 gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
2483 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( data._edges[i]->_nodes.back() );
2484 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
2485 dumpMove( tgtNode );
2487 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
2488 pos->SetUParameter( newUV.X() );
2489 pos->SetVParameter( newUV.Y() );
2495 if ( curve->IsKind( STANDARD_TYPE( Geom_Circle )))
2497 Handle(Geom_Circle) circle = Handle(Geom_Circle)::DownCast( curve );
2498 gp_Pnt center3D = circle->Location();
2500 if ( F.IsNull() ) // 3D
2502 return false; // TODO ???
2506 const gp_XY center( center3D.X(), center3D.Y() );
2508 gp_XY uv0 = helper.GetNodeUV( F, data._edges[iFrom]->_2neibors->_nodes[0]);
2509 gp_XY uvM = helper.GetNodeUV( F, data._edges[iFrom]->_nodes.back());
2510 gp_XY uv1 = helper.GetNodeUV( F, data._edges[iTo-1]->_2neibors->_nodes[1]);
2511 gp_Vec2d vec0( center, uv0 );
2512 gp_Vec2d vecM( center, uvM);
2513 gp_Vec2d vec1( center, uv1 );
2514 double uLast = vec0.Angle( vec1 ); // -PI - +PI
2515 double uMidl = vec0.Angle( vecM );
2516 if ( uLast < 0 ) uLast += 2.*M_PI; // 0.0 - 2*PI
2517 if ( uMidl < 0 ) uMidl += 2.*M_PI;
2518 const bool sense = ( uMidl < uLast );
2519 const double radius = 0.5 * ( vec0.Magnitude() + vec1.Magnitude() );
2521 gp_Ax2d axis( center, vec0 );
2522 gp_Circ2d circ ( axis, radius, sense );
2523 for ( int i = iFrom; i < iTo; ++i )
2525 double newU = uLast * len[i-iFrom] / len.back();
2526 gp_Pnt2d newUV = ElCLib::Value( newU, circ );
2527 data._edges[i]->_pos.back().SetCoord( newUV.X(), newUV.Y(), 0 );
2529 gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
2530 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( data._edges[i]->_nodes.back() );
2531 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
2532 dumpMove( tgtNode );
2534 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
2535 pos->SetUParameter( newUV.X() );
2536 pos->SetVParameter( newUV.Y() );
2545 //================================================================================
2547 * \brief Modify normals of _LayerEdge's on EDGE's to avoid intersection with
2548 * _LayerEdge's on neighbor EDGE's
2550 //================================================================================
2552 bool _ViscousBuilder::updateNormals( _SolidData& data,
2553 SMESH_MesherHelper& helper )
2555 // make temporary quadrangles got by extrusion of
2556 // mesh edges along _LayerEdge._normal's
2558 vector< const SMDS_MeshElement* > tmpFaces;
2560 set< SMESH_TLink > extrudedLinks; // contains target nodes
2561 vector< const SMDS_MeshNode*> nodes(4); // of a tmp mesh face
2563 dumpFunction(SMESH_Comment("makeTmpFacesOnEdges")<<data._index);
2564 for ( unsigned i = 0; i < data._edges.size(); ++i )
2566 _LayerEdge* edge = data._edges[i];
2567 if ( !edge->IsOnEdge() || !edge->_sWOL.IsNull() ) continue;
2568 const SMDS_MeshNode* tgt1 = edge->_nodes.back();
2569 for ( int j = 0; j < 2; ++j ) // loop on _2NearEdges
2571 const SMDS_MeshNode* tgt2 = edge->_2neibors->_nodes[j];
2572 pair< set< SMESH_TLink >::iterator, bool > link_isnew =
2573 extrudedLinks.insert( SMESH_TLink( tgt1, tgt2 ));
2574 if ( !link_isnew.second )
2576 extrudedLinks.erase( link_isnew.first );
2577 continue; // already extruded and will no more encounter
2579 // look for a _LayerEdge containg tgt2
2580 // _LayerEdge* neiborEdge = 0;
2581 // unsigned di = 0; // check _edges[i+di] and _edges[i-di]
2582 // while ( !neiborEdge && ++di <= data._edges.size() )
2584 // if ( i+di < data._edges.size() && data._edges[i+di]->_nodes.back() == tgt2 )
2585 // neiborEdge = data._edges[i+di];
2586 // else if ( di <= i && data._edges[i-di]->_nodes.back() == tgt2 )
2587 // neiborEdge = data._edges[i-di];
2589 // if ( !neiborEdge )
2590 // return error("updateNormals(): neighbor _LayerEdge not found", data._index);
2591 _LayerEdge* neiborEdge = edge->_2neibors->_edges[j];
2593 TmpMeshFaceOnEdge* f = new TmpMeshFaceOnEdge( edge, neiborEdge, --_tmpFaceID );
2594 tmpFaces.push_back( f );
2596 dumpCmd(SMESH_Comment("mesh.AddFace([ ")
2597 <<f->_nn[0]->GetID()<<", "<<f->_nn[1]->GetID()<<", "
2598 <<f->_nn[2]->GetID()<<", "<<f->_nn[3]->GetID()<<" ])");
2603 // Check if _LayerEdge's based on EDGE's intersects tmpFaces.
2604 // Perform two loops on _LayerEdge on EDGE's:
2605 // 1) to find and fix intersection
2606 // 2) to check that no new intersection appears as result of 1)
2608 SMESH_MeshEditor editor( _mesh );
2609 SMDS_ElemIteratorPtr fIt( new SMDS_ElementVectorIterator( tmpFaces.begin(),
2611 auto_ptr<SMESH_ElementSearcher> searcher ( editor.GetElementSearcher( fIt ));
2613 // 1) Find intersections
2615 const SMDS_MeshElement* face;
2616 typedef map< _LayerEdge*, set< _LayerEdge*, _LayerEdgeCmp >, _LayerEdgeCmp > TLEdge2LEdgeSet;
2617 TLEdge2LEdgeSet edge2CloseEdge;
2619 const double eps = data._epsilon * data._epsilon;
2620 for ( unsigned i = 0; i < data._edges.size(); ++i )
2622 _LayerEdge* edge = data._edges[i];
2623 if ( !edge->IsOnEdge() || !edge->_sWOL.IsNull() ) continue;
2624 if ( edge->FindIntersection( *searcher, dist, eps, &face ))
2626 const TmpMeshFaceOnEdge* f = (const TmpMeshFaceOnEdge*) face;
2627 set< _LayerEdge*, _LayerEdgeCmp > & ee = edge2CloseEdge[ edge ];
2628 ee.insert( f->_le1 );
2629 ee.insert( f->_le2 );
2630 if ( f->_le1->IsOnEdge() && f->_le1->_sWOL.IsNull() )
2631 edge2CloseEdge[ f->_le1 ].insert( edge );
2632 if ( f->_le2->IsOnEdge() && f->_le2->_sWOL.IsNull() )
2633 edge2CloseEdge[ f->_le2 ].insert( edge );
2637 // Set _LayerEdge._normal
2639 if ( !edge2CloseEdge.empty() )
2641 dumpFunction(SMESH_Comment("updateNormals")<<data._index);
2643 TLEdge2LEdgeSet::iterator e2ee = edge2CloseEdge.begin();
2644 for ( ; e2ee != edge2CloseEdge.end(); ++e2ee )
2646 _LayerEdge* edge1 = e2ee->first;
2647 _LayerEdge* edge2 = 0;
2648 set< _LayerEdge*, _LayerEdgeCmp >& ee = e2ee->second;
2650 // find EDGEs the edges reside
2652 TopoDS_Shape S = helper.GetSubShapeByNode( edge1->_nodes[0], getMeshDS() );
2653 if ( S.ShapeType() != TopAbs_EDGE )
2654 continue; // TODO: find EDGE by VERTEX
2655 E1 = TopoDS::Edge( S );
2656 set< _LayerEdge*, _LayerEdgeCmp >::iterator eIt = ee.begin();
2657 while ( E2.IsNull() && eIt != ee.end())
2659 _LayerEdge* e2 = *eIt++;
2660 TopoDS_Shape S = helper.GetSubShapeByNode( e2->_nodes[0], getMeshDS() );
2661 if ( S.ShapeType() == TopAbs_EDGE )
2662 E2 = TopoDS::Edge( S ), edge2 = e2;
2664 if ( E2.IsNull() ) continue; // TODO: find EDGE by VERTEX
2666 // find 3 FACEs sharing 2 EDGEs
2668 TopoDS_Face FF1[2], FF2[2];
2669 PShapeIteratorPtr fIt = helper.GetAncestors(E1, *_mesh, TopAbs_FACE);
2670 while ( fIt->more() && FF1[1].IsNull())
2672 const TopoDS_Face *F = (const TopoDS_Face*) fIt->next();
2673 if ( helper.IsSubShape( *F, data._solid))
2674 FF1[ FF1[0].IsNull() ? 0 : 1 ] = *F;
2676 fIt = helper.GetAncestors(E2, *_mesh, TopAbs_FACE);
2677 while ( fIt->more() && FF2[1].IsNull())
2679 const TopoDS_Face *F = (const TopoDS_Face*) fIt->next();
2680 if ( helper.IsSubShape( *F, data._solid))
2681 FF2[ FF2[0].IsNull() ? 0 : 1 ] = *F;
2683 // exclude a FACE common to E1 and E2 (put it at [1] in FF* )
2684 if ( FF1[0].IsSame( FF2[0]) || FF1[0].IsSame( FF2[1]))
2685 std::swap( FF1[0], FF1[1] );
2686 if ( FF2[0].IsSame( FF1[0]) )
2687 std::swap( FF2[0], FF2[1] );
2688 if ( FF1[0].IsNull() || FF2[0].IsNull() )
2691 // // get a new normal for edge1
2693 gp_Vec dir1 = edge1->_normal, dir2 = edge2->_normal;
2694 if ( edge1->_cosin < 0 )
2695 dir1 = getFaceDir( FF1[0], E1, edge1->_nodes[0], helper, ok ).Normalized();
2696 if ( edge2->_cosin < 0 )
2697 dir2 = getFaceDir( FF2[0], E2, edge2->_nodes[0], helper, ok ).Normalized();
2698 // gp_Vec dir1 = getFaceDir( FF1[0], E1, edge1->_nodes[0], helper, ok );
2699 // gp_Vec dir2 = getFaceDir( FF2[0], E2, edge2->_nodes[0], helper, ok2 );
2700 // double wgt1 = ( edge1->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
2701 // double wgt2 = ( edge2->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
2702 // gp_Vec newNorm = wgt1 * dir1 + wgt2 * dir2;
2703 // newNorm.Normalize();
2705 double wgt1 = ( edge1->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
2706 double wgt2 = ( edge2->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
2707 gp_Vec newNorm = wgt1 * dir1 + wgt2 * dir2;
2708 newNorm.Normalize();
2710 edge1->_normal = newNorm.XYZ();
2712 // update data of edge1 depending on _normal
2713 const SMDS_MeshNode *n1, *n2;
2714 n1 = edge1->_2neibors->_edges[0]->_nodes[0];
2715 n2 = edge1->_2neibors->_edges[1]->_nodes[0];
2716 //if ( !findNeiborsOnEdge( edge1, n1, n2, data ))
2718 edge1->SetDataByNeighbors( n1, n2, helper );
2720 if ( edge1->_cosin < 0 )
2723 getFaceDir( FF1[0], E1, edge1->_nodes[0], helper, ok );
2724 double angle = dir1.Angle( edge1->_normal ); // [0,PI]
2725 edge1->SetCosin( cos( angle ));
2727 // limit data._stepSize
2728 if ( edge1->_cosin > 0.1 )
2730 SMDS_ElemIteratorPtr fIt = edge1->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
2731 while ( fIt->more() )
2732 limitStepSize( data, fIt->next(), edge1->_cosin );
2734 // set new XYZ of target node
2735 edge1->InvalidateStep( 1 );
2737 edge1->SetNewLength( data._stepSize, helper );
2740 // Update normals and other dependent data of not intersecting _LayerEdge's
2741 // neighboring the intersecting ones
2743 for ( e2ee = edge2CloseEdge.begin(); e2ee != edge2CloseEdge.end(); ++e2ee )
2745 _LayerEdge* edge1 = e2ee->first;
2746 if ( !edge1->_2neibors )
2748 for ( int j = 0; j < 2; ++j ) // loop on 2 neighbors
2750 _LayerEdge* neighbor = edge1->_2neibors->_edges[j];
2751 if ( edge2CloseEdge.count ( neighbor ))
2752 continue; // j-th neighbor is also intersected
2753 _LayerEdge* prevEdge = edge1;
2754 const int nbSteps = 6;
2755 for ( int step = nbSteps; step; --step ) // step from edge1 in j-th direction
2757 if ( !neighbor->_2neibors )
2758 break; // neighbor is on VERTEX
2760 _LayerEdge* nextEdge = neighbor->_2neibors->_edges[iNext];
2761 if ( nextEdge == prevEdge )
2762 nextEdge = neighbor->_2neibors->_edges[ ++iNext ];
2763 // const double& wgtPrev = neighbor->_2neibors->_wgt[1-iNext];
2764 // const double& wgtNext = neighbor->_2neibors->_wgt[iNext];
2765 double r = double(step-1)/nbSteps;
2766 if ( !nextEdge->_2neibors )
2769 gp_XYZ newNorm = prevEdge->_normal * r + nextEdge->_normal * (1-r);
2770 newNorm.Normalize();
2772 neighbor->_normal = newNorm;
2773 neighbor->SetCosin( prevEdge->_cosin * r + nextEdge->_cosin * (1-r) );
2774 neighbor->SetDataByNeighbors( prevEdge->_nodes[0], nextEdge->_nodes[0], helper );
2776 neighbor->InvalidateStep( 1 );
2778 neighbor->SetNewLength( data._stepSize, helper );
2780 // goto the next neighbor
2781 prevEdge = neighbor;
2782 neighbor = nextEdge;
2788 // 2) Check absence of intersections
2791 for ( unsigned i = 0 ; i < tmpFaces.size(); ++i )
2797 //================================================================================
2799 * \brief Looks for intersection of it's last segment with faces
2800 * \param distance - returns shortest distance from the last node to intersection
2802 //================================================================================
2804 bool _LayerEdge::FindIntersection( SMESH_ElementSearcher& searcher,
2806 const double& epsilon,
2807 const SMDS_MeshElement** face)
2809 vector< const SMDS_MeshElement* > suspectFaces;
2811 gp_Ax1 lastSegment = LastSegment(segLen);
2812 searcher.GetElementsNearLine( lastSegment, SMDSAbs_Face, suspectFaces );
2814 bool segmentIntersected = false;
2815 distance = Precision::Infinite();
2816 int iFace = -1; // intersected face
2817 for ( unsigned j = 0 ; j < suspectFaces.size() && !segmentIntersected; ++j )
2819 const SMDS_MeshElement* face = suspectFaces[j];
2820 if ( face->GetNodeIndex( _nodes.back() ) >= 0 ||
2821 face->GetNodeIndex( _nodes[0] ) >= 0 )
2822 continue; // face sharing _LayerEdge node
2823 const int nbNodes = face->NbCornerNodes();
2824 bool intFound = false;
2826 SMDS_MeshElement::iterator nIt = face->begin_nodes();
2829 intFound = SegTriaInter( lastSegment, *nIt++, *nIt++, *nIt++, dist, epsilon );
2833 const SMDS_MeshNode* tria[3];
2836 for ( int n2 = 2; n2 < nbNodes && !intFound; ++n2 )
2839 intFound = SegTriaInter(lastSegment, tria[0], tria[1], tria[2], dist, epsilon );
2845 if ( dist < segLen*(1.01))
2846 segmentIntersected = true;
2847 if ( distance > dist )
2848 distance = dist, iFace = j;
2851 if ( iFace != -1 && face ) *face = suspectFaces[iFace];
2852 // if ( distance && iFace > -1 )
2854 // // distance is used to limit size of inflation step which depends on
2855 // // whether the intersected face bears viscous layers or not
2856 // bool faceHasVL = suspectFaces[iFace]->GetID() < 1;
2860 if ( segmentIntersected )
2863 SMDS_MeshElement::iterator nIt = suspectFaces[iFace]->begin_nodes();
2864 gp_XYZ intP( lastSegment.Location().XYZ() + lastSegment.Direction().XYZ() * distance );
2865 cout << "nodes: tgt " << _nodes.back()->GetID() << " src " << _nodes[0]->GetID()
2866 << ", intersection with face ("
2867 << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
2868 << ") at point (" << intP.X() << ", " << intP.Y() << ", " << intP.Z()
2869 << ") distance = " << distance - segLen<< endl;
2875 return segmentIntersected;
2878 //================================================================================
2880 * \brief Returns size and direction of the last segment
2882 //================================================================================
2884 gp_Ax1 _LayerEdge::LastSegment(double& segLen) const
2886 // find two non-coincident positions
2887 gp_XYZ orig = _pos.back();
2889 int iPrev = _pos.size() - 2;
2890 while ( iPrev >= 0 )
2892 dir = orig - _pos[iPrev];
2893 if ( dir.SquareModulus() > 1e-100 )
2903 segDir.SetLocation( SMESH_TNodeXYZ( _nodes[0] ));
2904 segDir.SetDirection( _normal );
2909 gp_Pnt pPrev = _pos[ iPrev ];
2910 if ( !_sWOL.IsNull() )
2912 TopLoc_Location loc;
2913 if ( _sWOL.ShapeType() == TopAbs_EDGE )
2916 Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( _sWOL ), loc, f,l);
2917 pPrev = curve->Value( pPrev.X() ).Transformed( loc );
2921 Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face(_sWOL), loc );
2922 pPrev = surface->Value( pPrev.X(), pPrev.Y() ).Transformed( loc );
2924 dir = SMESH_TNodeXYZ( _nodes.back() ) - pPrev.XYZ();
2926 segDir.SetLocation( pPrev );
2927 segDir.SetDirection( dir );
2928 segLen = dir.Modulus();
2934 //================================================================================
2936 * \brief Test intersection of the last segment with a given triangle
2937 * using Moller-Trumbore algorithm
2938 * Intersection is detected if distance to intersection is less than _LayerEdge._len
2940 //================================================================================
2942 bool _LayerEdge::SegTriaInter( const gp_Ax1& lastSegment,
2943 const SMDS_MeshNode* n0,
2944 const SMDS_MeshNode* n1,
2945 const SMDS_MeshNode* n2,
2947 const double& EPSILON) const
2949 //const double EPSILON = 1e-6;
2951 gp_XYZ orig = lastSegment.Location().XYZ();
2952 gp_XYZ dir = lastSegment.Direction().XYZ();
2954 SMESH_TNodeXYZ vert0( n0 );
2955 SMESH_TNodeXYZ vert1( n1 );
2956 SMESH_TNodeXYZ vert2( n2 );
2958 /* calculate distance from vert0 to ray origin */
2959 gp_XYZ tvec = orig - vert0;
2961 if ( tvec * dir > EPSILON )
2962 // intersected face is at back side of the temporary face this _LayerEdge belongs to
2965 gp_XYZ edge1 = vert1 - vert0;
2966 gp_XYZ edge2 = vert2 - vert0;
2968 /* begin calculating determinant - also used to calculate U parameter */
2969 gp_XYZ pvec = dir ^ edge2;
2971 /* if determinant is near zero, ray lies in plane of triangle */
2972 double det = edge1 * pvec;
2974 if (det > -EPSILON && det < EPSILON)
2976 double inv_det = 1.0 / det;
2978 /* calculate U parameter and test bounds */
2979 double u = ( tvec * pvec ) * inv_det;
2980 if (u < 0.0 || u > 1.0)
2983 /* prepare to test V parameter */
2984 gp_XYZ qvec = tvec ^ edge1;
2986 /* calculate V parameter and test bounds */
2987 double v = (dir * qvec) * inv_det;
2988 if ( v < 0.0 || u + v > 1.0 )
2991 /* calculate t, ray intersects triangle */
2992 t = (edge2 * qvec) * inv_det;
2994 // if (det < EPSILON)
2997 // /* calculate distance from vert0 to ray origin */
2998 // gp_XYZ tvec = orig - vert0;
3000 // /* calculate U parameter and test bounds */
3001 // double u = tvec * pvec;
3002 // if (u < 0.0 || u > det)
3005 // /* prepare to test V parameter */
3006 // gp_XYZ qvec = tvec ^ edge1;
3008 // /* calculate V parameter and test bounds */
3009 // double v = dir * qvec;
3010 // if (v < 0.0 || u + v > det)
3013 // /* calculate t, scale parameters, ray intersects triangle */
3014 // double t = edge2 * qvec;
3015 // double inv_det = 1.0 / det;
3023 //================================================================================
3025 * \brief Perform smooth of _LayerEdge's based on EDGE's
3026 * \retval bool - true if node has been moved
3028 //================================================================================
3030 bool _LayerEdge::SmoothOnEdge(Handle(Geom_Surface)& surface,
3031 const TopoDS_Face& F,
3032 SMESH_MesherHelper& helper)
3034 ASSERT( IsOnEdge() );
3036 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _nodes.back() );
3037 SMESH_TNodeXYZ oldPos( tgtNode );
3038 double dist01, distNewOld;
3040 SMESH_TNodeXYZ p0( _2neibors->_nodes[0]);
3041 SMESH_TNodeXYZ p1( _2neibors->_nodes[1]);
3042 dist01 = p0.Distance( _2neibors->_nodes[1] );
3044 gp_Pnt newPos = p0 * _2neibors->_wgt[0] + p1 * _2neibors->_wgt[1];
3045 double lenDelta = 0;
3048 lenDelta = _curvature->lenDelta( _len );
3049 newPos.ChangeCoord() += _normal * lenDelta;
3052 distNewOld = newPos.Distance( oldPos );
3056 if ( _2neibors->_plnNorm )
3058 // put newPos on the plane defined by source node and _plnNorm
3059 gp_XYZ new2src = SMESH_TNodeXYZ( _nodes[0] ) - newPos.XYZ();
3060 double new2srcProj = (*_2neibors->_plnNorm) * new2src;
3061 newPos.ChangeCoord() += (*_2neibors->_plnNorm) * new2srcProj;
3063 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
3064 _pos.back() = newPos.XYZ();
3068 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
3069 gp_XY uv( Precision::Infinite(), 0 );
3070 helper.CheckNodeUV( F, tgtNode, uv, 1e-10, /*force=*/true );
3071 _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
3073 newPos = surface->Value( uv.X(), uv.Y() );
3074 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
3077 if ( _curvature && lenDelta < 0 )
3079 gp_Pnt prevPos( _pos[ _pos.size()-2 ]);
3080 _len -= prevPos.Distance( oldPos );
3081 _len += prevPos.Distance( newPos );
3083 bool moved = distNewOld > dist01/50;
3085 dumpMove( tgtNode ); // debug
3090 //================================================================================
3092 * \brief Perform laplacian smooth in 3D of nodes inflated from FACE
3093 * \retval bool - true if _tgtNode has been moved
3095 //================================================================================
3097 bool _LayerEdge::Smooth(int& badNb)
3099 if ( _simplices.size() < 2 )
3100 return false; // _LayerEdge inflated along EDGE or FACE
3102 // compute new position for the last _pos
3103 gp_XYZ newPos (0,0,0);
3104 for ( unsigned i = 0; i < _simplices.size(); ++i )
3105 newPos += SMESH_TNodeXYZ( _simplices[i]._nPrev );
3106 newPos /= _simplices.size();
3109 newPos += _normal * _curvature->lenDelta( _len );
3111 gp_Pnt prevPos( _pos[ _pos.size()-2 ]);
3112 // if ( _cosin < -0.1)
3114 // // Avoid decreasing length of edge on concave surface
3115 // //gp_Vec oldMove( _pos[ _pos.size()-2 ], _pos.back() );
3116 // gp_Vec newMove( prevPos, newPos );
3117 // newPos = _pos.back() + newMove.XYZ();
3119 // else if ( _cosin > 0.3 )
3121 // // Avoid increasing length of edge too much
3124 // count quality metrics (orientation) of tetras around _tgtNode
3126 SMESH_TNodeXYZ tgtXYZ( _nodes.back() );
3127 for ( unsigned i = 0; i < _simplices.size(); ++i )
3128 nbOkBefore += _simplices[i].IsForward( _nodes[0], &tgtXYZ );
3131 for ( unsigned i = 0; i < _simplices.size(); ++i )
3132 nbOkAfter += _simplices[i].IsForward( _nodes[0], &newPos );
3134 if ( nbOkAfter < nbOkBefore )
3137 SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
3139 _len -= prevPos.Distance(SMESH_TNodeXYZ( n ));
3140 _len += prevPos.Distance(newPos);
3142 n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
3143 _pos.back() = newPos;
3145 badNb += _simplices.size() - nbOkAfter;
3152 //================================================================================
3154 * \brief Add a new segment to _LayerEdge during inflation
3156 //================================================================================
3158 void _LayerEdge::SetNewLength( double len, SMESH_MesherHelper& helper )
3160 if ( _len - len > -1e-6 )
3162 _pos.push_back( _pos.back() );
3166 SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
3167 SMESH_TNodeXYZ oldXYZ( n );
3168 gp_XYZ nXYZ = oldXYZ + _normal * ( len - _len ) * _lenFactor;
3169 n->setXYZ( nXYZ.X(), nXYZ.Y(), nXYZ.Z() );
3171 _pos.push_back( nXYZ );
3173 if ( !_sWOL.IsNull() )
3176 if ( _sWOL.ShapeType() == TopAbs_EDGE )
3178 double u = Precision::Infinite(); // to force projection w/o distance check
3179 helper.CheckNodeU( TopoDS::Edge( _sWOL ), n, u, 1e-10, /*force=*/true, distXYZ );
3180 _pos.back().SetCoord( u, 0, 0 );
3181 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( n->GetPosition() );
3182 pos->SetUParameter( u );
3186 gp_XY uv( Precision::Infinite(), 0 );
3187 helper.CheckNodeUV( TopoDS::Face( _sWOL ), n, uv, 1e-10, /*force=*/true, distXYZ );
3188 _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
3189 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( n->GetPosition() );
3190 pos->SetUParameter( uv.X() );
3191 pos->SetVParameter( uv.Y() );
3193 n->setXYZ( distXYZ[1], distXYZ[2], distXYZ[3]);
3195 dumpMove( n ); //debug
3198 //================================================================================
3200 * \brief Remove last inflation step
3202 //================================================================================
3204 void _LayerEdge::InvalidateStep( int curStep )
3206 if ( _pos.size() > curStep )
3208 _pos.resize( curStep );
3209 gp_Pnt nXYZ = _pos.back();
3210 SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
3211 if ( !_sWOL.IsNull() )
3213 TopLoc_Location loc;
3214 if ( _sWOL.ShapeType() == TopAbs_EDGE )
3216 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( n->GetPosition() );
3217 pos->SetUParameter( nXYZ.X() );
3219 Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( _sWOL ), loc, f,l);
3220 nXYZ = curve->Value( nXYZ.X() ).Transformed( loc );
3224 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( n->GetPosition() );
3225 pos->SetUParameter( nXYZ.X() );
3226 pos->SetVParameter( nXYZ.Y() );
3227 Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face(_sWOL), loc );
3228 nXYZ = surface->Value( nXYZ.X(), nXYZ.Y() ).Transformed( loc );
3231 n->setXYZ( nXYZ.X(), nXYZ.Y(), nXYZ.Z() );
3236 //================================================================================
3238 * \brief Create layers of prisms
3240 //================================================================================
3242 bool _ViscousBuilder::refine(_SolidData& data)
3244 SMESH_MesherHelper helper( *_mesh );
3245 helper.SetSubShape( data._solid );
3246 helper.SetElementsOnShape(false);
3248 Handle(Geom_Curve) curve;
3249 Handle(Geom_Surface) surface;
3250 TopoDS_Edge geomEdge;
3251 TopoDS_Face geomFace;
3252 TopLoc_Location loc;
3253 double f,l, u/*, distXYZ[4]*/;
3257 for ( unsigned i = 0; i < data._edges.size(); ++i )
3259 _LayerEdge& edge = *data._edges[i];
3261 // get accumulated length of segments
3262 vector< double > segLen( edge._pos.size() );
3264 for ( unsigned j = 1; j < edge._pos.size(); ++j )
3265 segLen[j] = segLen[j-1] + (edge._pos[j-1] - edge._pos[j] ).Modulus();
3267 // allocate memory for new nodes if it is not yet refined
3268 const SMDS_MeshNode* tgtNode = edge._nodes.back();
3269 if ( edge._nodes.size() == 2 )
3271 edge._nodes.resize( data._hyp->GetNumberLayers() + 1, 0 );
3273 edge._nodes.back() = tgtNode;
3275 if ( !edge._sWOL.IsNull() )
3277 isOnEdge = ( edge._sWOL.ShapeType() == TopAbs_EDGE );
3278 // restore position of the last node
3282 geomEdge = TopoDS::Edge( edge._sWOL );
3283 curve = BRep_Tool::Curve( geomEdge, loc, f,l);
3284 // double u = helper.GetNodeU( tgtNode );
3285 // p = curve->Value( u );
3289 geomFace = TopoDS::Face( edge._sWOL );
3290 surface = BRep_Tool::Surface( geomFace, loc );
3291 // gp_XY uv = helper.GetNodeUV( tgtNode );
3292 // p = surface->Value( uv.X(), uv.Y() );
3294 // p.Transform( loc );
3295 // const_cast< SMDS_MeshNode* >( tgtNode )->setXYZ( p.X(), p.Y(), p.Z() );
3297 // calculate height of the first layer
3299 const double T = segLen.back(); //data._hyp.GetTotalThickness();
3300 const double f = data._hyp->GetStretchFactor();
3301 const int N = data._hyp->GetNumberLayers();
3302 const double fPowN = pow( f, N );
3303 if ( fPowN - 1 <= numeric_limits<double>::min() )
3306 h0 = T * ( f - 1 )/( fPowN - 1 );
3308 const double zeroLen = std::numeric_limits<double>::min();
3310 // create intermediate nodes
3311 double hSum = 0, hi = h0/f;
3313 for ( unsigned iStep = 1; iStep < edge._nodes.size(); ++iStep )
3315 // compute an intermediate position
3318 while ( hSum > segLen[iSeg] && iSeg < segLen.size()-1)
3320 int iPrevSeg = iSeg-1;
3321 while ( fabs( segLen[iPrevSeg] - segLen[iSeg]) <= zeroLen && iPrevSeg > 0 )
3323 double r = ( segLen[iSeg] - hSum ) / ( segLen[iSeg] - segLen[iPrevSeg] );
3324 gp_Pnt pos = r * edge._pos[iPrevSeg] + (1-r) * edge._pos[iSeg];
3326 SMDS_MeshNode*& node = const_cast< SMDS_MeshNode*& >(edge._nodes[ iStep ]);
3327 if ( !edge._sWOL.IsNull() )
3329 // compute XYZ by parameters <pos>
3333 pos = curve->Value( u ).Transformed(loc);
3337 uv.SetCoord( pos.X(), pos.Y() );
3338 pos = surface->Value( pos.X(), pos.Y() ).Transformed(loc);
3341 // create or update the node
3344 node = helper.AddNode( pos.X(), pos.Y(), pos.Z());
3345 if ( !edge._sWOL.IsNull() )
3348 getMeshDS()->SetNodeOnEdge( node, geomEdge, u );
3350 getMeshDS()->SetNodeOnFace( node, geomFace, uv.X(), uv.Y() );
3354 getMeshDS()->SetNodeInVolume( node, helper.GetSubShapeID() );
3359 if ( !edge._sWOL.IsNull() )
3361 // make average pos from new and current parameters
3364 u = 0.5 * ( u + helper.GetNodeU( geomEdge, node ));
3365 pos = curve->Value( u ).Transformed(loc);
3369 uv = 0.5 * ( uv + helper.GetNodeUV( geomFace, node ));
3370 pos = surface->Value( uv.X(), uv.Y()).Transformed(loc);
3373 node->setXYZ( pos.X(), pos.Y(), pos.Z() );
3378 // TODO: make quadratic prisms and polyhedrons(?)
3380 helper.SetElementsOnShape(true);
3382 TopExp_Explorer exp( data._solid, TopAbs_FACE );
3383 for ( ; exp.More(); exp.Next() )
3385 if ( _ignoreShapeIds.count( getMeshDS()->ShapeToIndex( exp.Current() )))
3387 SMESHDS_SubMesh* fSubM = getMeshDS()->MeshElements( exp.Current() );
3388 SMDS_ElemIteratorPtr fIt = fSubM->GetElements();
3389 vector< vector<const SMDS_MeshNode*>* > nnVec;
3390 while ( fIt->more() )
3392 const SMDS_MeshElement* face = fIt->next();
3393 int nbNodes = face->NbCornerNodes();
3394 nnVec.resize( nbNodes );
3395 SMDS_ElemIteratorPtr nIt = face->nodesIterator();
3396 for ( int iN = 0; iN < nbNodes; ++iN )
3398 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
3399 nnVec[ iN ] = & data._n2eMap[ n ]->_nodes;
3402 int nbZ = nnVec[0]->size();
3406 for ( int iZ = 1; iZ < nbZ; ++iZ )
3407 helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1], (*nnVec[2])[iZ-1],
3408 (*nnVec[0])[iZ], (*nnVec[1])[iZ], (*nnVec[2])[iZ]);
3411 for ( int iZ = 1; iZ < nbZ; ++iZ )
3412 helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1],
3413 (*nnVec[2])[iZ-1], (*nnVec[3])[iZ-1],
3414 (*nnVec[0])[iZ], (*nnVec[1])[iZ],
3415 (*nnVec[2])[iZ], (*nnVec[3])[iZ]);
3418 return error("Not supported type of element", data._index);
3425 //================================================================================
3427 * \brief Shrink 2D mesh on faces to let space for inflated layers
3429 //================================================================================
3431 bool _ViscousBuilder::shrink()
3433 // make map of (ids of FACEs to shrink mesh on) to (_SolidData containing _LayerEdge's
3434 // inflated along FACE or EDGE)
3435 map< TGeomID, _SolidData* > f2sdMap;
3436 for ( unsigned i = 0 ; i < _sdVec.size(); ++i )
3438 _SolidData& data = _sdVec[i];
3439 TopTools_MapOfShape FFMap;
3440 map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
3441 for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
3442 if ( s2s->second.ShapeType() == TopAbs_FACE )
3444 f2sdMap.insert( make_pair( getMeshDS()->ShapeToIndex( s2s->second ), &data ));
3446 if ( FFMap.Add( (*s2s).second ))
3447 // Put mesh faces on the shrinked FACE to the proxy sub-mesh to avoid
3448 // usage of mesh faces made in addBoundaryElements() by the 3D algo or
3449 // by StdMeshers_QuadToTriaAdaptor
3450 if ( SMESHDS_SubMesh* smDS = getMeshDS()->MeshElements( s2s->second ))
3452 SMESH_ProxyMesh::SubMesh* proxySub =
3453 data._proxyMesh->getFaceSubM( TopoDS::Face( s2s->second ), /*create=*/true);
3454 SMDS_ElemIteratorPtr fIt = smDS->GetElements();
3455 while ( fIt->more() )
3456 proxySub->AddElement( fIt->next() );
3457 // as a result 3D algo will use elements from proxySub and not from smDS
3462 SMESH_MesherHelper helper( *_mesh );
3463 helper.ToFixNodeParameters( true );
3466 map< int, _Shrinker1D > e2shrMap;
3468 // loop on FACES to srink mesh on
3469 map< TGeomID, _SolidData* >::iterator f2sd = f2sdMap.begin();
3470 for ( ; f2sd != f2sdMap.end(); ++f2sd )
3472 _SolidData& data = *f2sd->second;
3473 TNode2Edge& n2eMap = data._n2eMap;
3474 const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( f2sd->first ));
3476 Handle(Geom_Surface) surface = BRep_Tool::Surface(F);
3478 SMESH_subMesh* sm = _mesh->GetSubMesh( F );
3479 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
3481 helper.SetSubShape(F);
3483 // ===========================
3484 // Prepare data for shrinking
3485 // ===========================
3487 // Collect nodes to smooth, as src nodes are not yet replaced by tgt ones
3488 // and thus all nodes on a FACE connected to 2d elements are to be smoothed
3489 vector < const SMDS_MeshNode* > smoothNodes;
3491 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
3492 while ( nIt->more() )
3494 const SMDS_MeshNode* n = nIt->next();
3495 if ( n->NbInverseElements( SMDSAbs_Face ) > 0 )
3496 smoothNodes.push_back( n );
3499 // Find out face orientation
3501 const set<TGeomID> ignoreShapes;
3503 if ( !smoothNodes.empty() )
3505 vector<_Simplex> simplices;
3506 getSimplices( smoothNodes[0], simplices, ignoreShapes );
3507 helper.GetNodeUV( F, simplices[0]._nPrev, 0, &isOkUV ); // fix UV of silpmex nodes
3508 helper.GetNodeUV( F, simplices[0]._nNext, 0, &isOkUV );
3509 gp_XY uv = helper.GetNodeUV( F, smoothNodes[0], 0, &isOkUV );
3510 if ( !simplices[0].IsForward(uv, smoothNodes[0], F, helper,refSign) )
3514 // Find _LayerEdge's inflated along F
3515 vector< _LayerEdge* > lEdges;
3517 SMESH_subMeshIteratorPtr subIt =
3518 sm->getDependsOnIterator(/*includeSelf=*/false, /*complexShapeFirst=*/false);
3519 while ( subIt->more() )
3521 SMESH_subMesh* sub = subIt->next();
3522 SMESHDS_SubMesh* subDS = sub->GetSubMeshDS();
3523 if ( subDS->NbNodes() == 0 || !n2eMap.count( subDS->GetNodes()->next() ))
3525 SMDS_NodeIteratorPtr nIt = subDS->GetNodes();
3526 while ( nIt->more() )
3528 _LayerEdge* edge = n2eMap[ nIt->next() ];
3529 lEdges.push_back( edge );
3530 prepareEdgeToShrink( *edge, F, helper, smDS );
3535 // Replace source nodes by target nodes in mesh faces to shrink
3536 const SMDS_MeshNode* nodes[20];
3537 for ( unsigned i = 0; i < lEdges.size(); ++i )
3539 _LayerEdge& edge = *lEdges[i];
3540 const SMDS_MeshNode* srcNode = edge._nodes[0];
3541 const SMDS_MeshNode* tgtNode = edge._nodes.back();
3542 SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
3543 while ( fIt->more() )
3545 const SMDS_MeshElement* f = fIt->next();
3546 if ( !smDS->Contains( f ))
3548 SMDS_ElemIteratorPtr nIt = f->nodesIterator();
3549 for ( int iN = 0; iN < f->NbNodes(); ++iN )
3551 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
3552 nodes[iN] = ( n == srcNode ? tgtNode : n );
3554 helper.GetMeshDS()->ChangeElementNodes( f, nodes, f->NbNodes() );
3558 // find out if a FACE is concave
3559 const bool isConcaveFace = isConcave( F, helper );
3561 // Create _SmoothNode's on face F
3562 vector< _SmoothNode > nodesToSmooth( smoothNodes.size() );
3564 dumpFunction(SMESH_Comment("beforeShrinkFace")<<f2sd->first); // debug
3565 for ( unsigned i = 0; i < smoothNodes.size(); ++i )
3567 const SMDS_MeshNode* n = smoothNodes[i];
3568 nodesToSmooth[ i ]._node = n;
3569 // src nodes must be replaced by tgt nodes to have tgt nodes in _simplices
3570 getSimplices( n, nodesToSmooth[ i ]._simplices, ignoreShapes, NULL, isConcaveFace );
3571 // fix up incorrect uv of nodes on the FACE
3572 helper.GetNodeUV( F, n, 0, &isOkUV);
3577 //if ( nodesToSmooth.empty() ) continue;
3579 // Find EDGE's to shrink
3580 set< _Shrinker1D* > eShri1D;
3582 for ( unsigned i = 0; i < lEdges.size(); ++i )
3584 _LayerEdge* edge = lEdges[i];
3585 if ( edge->_sWOL.ShapeType() == TopAbs_EDGE )
3587 TGeomID edgeIndex = getMeshDS()->ShapeToIndex( edge->_sWOL );
3588 _Shrinker1D& srinker = e2shrMap[ edgeIndex ];
3589 eShri1D.insert( & srinker );
3590 srinker.AddEdge( edge, helper );
3591 // restore params of nodes on EGDE if the EDGE has been already
3592 // srinked while srinking another FACE
3593 srinker.RestoreParams();
3598 // ==================
3599 // Perform shrinking
3600 // ==================
3602 bool shrinked = true;
3603 int badNb, shriStep=0, smooStep=0;
3606 // Move boundary nodes (actually just set new UV)
3607 // -----------------------------------------------
3608 dumpFunction(SMESH_Comment("moveBoundaryOnF")<<f2sd->first<<"_st"<<shriStep++ ); // debug
3610 for ( unsigned i = 0; i < lEdges.size(); ++i )
3612 shrinked |= lEdges[i]->SetNewLength2d( surface,F,helper );
3616 // Move nodes on EDGE's
3617 set< _Shrinker1D* >::iterator shr = eShri1D.begin();
3618 for ( ; shr != eShri1D.end(); ++shr )
3619 (*shr)->Compute( /*set3D=*/false, helper );
3622 // -----------------
3623 int nbNoImpSteps = 0;
3626 while (( nbNoImpSteps < 5 && badNb > 0) && moved)
3628 dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
3630 int oldBadNb = badNb;
3633 for ( unsigned i = 0; i < nodesToSmooth.size(); ++i )
3635 moved |= nodesToSmooth[i].Smooth( badNb,surface,helper,refSign,
3636 /*isCentroidal=*/isConcaveFace,/*set3D=*/false );
3638 if ( badNb < oldBadNb )
3646 return error(SMESH_Comment("Can't shrink 2D mesh on face ") << f2sd->first );
3648 // No wrongly shaped faces remain; final smooth. Set node XYZ.
3649 // First, find out a needed quality of smoothing (high for quadrangles only)
3652 const bool hasTria = _mesh->NbTriangles(), hasQuad = _mesh->NbQuadrangles();
3653 if ( hasTria != hasQuad )
3655 highQuality = hasQuad;
3659 set<int> nbNodesSet;
3660 SMDS_ElemIteratorPtr fIt = smDS->GetElements();
3661 while ( fIt->more() && nbNodesSet.size() < 2 )
3662 nbNodesSet.insert( fIt->next()->NbCornerNodes() );
3663 highQuality = ( *nbNodesSet.begin() == 4 );
3666 if ( !highQuality && isConcaveFace )
3667 fixBadFaces( F, helper ); // fix narrow faces by swaping diagonals
3668 for ( int st = highQuality ? 10 : 3; st; --st )
3670 dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
3671 for ( unsigned i = 0; i < nodesToSmooth.size(); ++i )
3672 nodesToSmooth[i].Smooth( badNb,surface,helper,refSign,
3673 /*isCentroidal=*/isConcaveFace,/*set3D=*/st==1 );
3676 // Set an event listener to clear FACE sub-mesh together with SOLID sub-mesh
3677 _SrinkShapeListener::ToClearSubMeshWithSolid( sm, data._solid );
3679 } // loop on FACES to srink mesh on
3682 // Replace source nodes by target nodes in shrinked mesh edges
3684 map< int, _Shrinker1D >::iterator e2shr = e2shrMap.begin();
3685 for ( ; e2shr != e2shrMap.end(); ++e2shr )
3686 e2shr->second.SwapSrcTgtNodes( getMeshDS() );
3691 //================================================================================
3693 * \brief Computes 2d shrink direction and finds nodes limiting shrinking
3695 //================================================================================
3697 bool _ViscousBuilder::prepareEdgeToShrink( _LayerEdge& edge,
3698 const TopoDS_Face& F,
3699 SMESH_MesherHelper& helper,
3700 const SMESHDS_SubMesh* faceSubMesh)
3702 const SMDS_MeshNode* srcNode = edge._nodes[0];
3703 const SMDS_MeshNode* tgtNode = edge._nodes.back();
3707 if ( edge._sWOL.ShapeType() == TopAbs_FACE )
3709 gp_XY srcUV = helper.GetNodeUV( F, srcNode );
3710 gp_XY tgtUV = helper.GetNodeUV( F, tgtNode );
3711 gp_Vec2d uvDir( srcUV, tgtUV );
3712 double uvLen = uvDir.Magnitude();
3714 edge._normal.SetCoord( uvDir.X(),uvDir.Y(), 0);
3716 // IMPORTANT to have src nodes NOT yet REPLACED by tgt nodes in shrinked faces
3717 vector<const SMDS_MeshElement*> faces;
3718 multimap< double, const SMDS_MeshNode* > proj2node;
3719 SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
3720 while ( fIt->more() )
3722 const SMDS_MeshElement* f = fIt->next();
3723 if ( faceSubMesh->Contains( f ))
3724 faces.push_back( f );
3726 for ( unsigned i = 0; i < faces.size(); ++i )
3728 const int nbNodes = faces[i]->NbCornerNodes();
3729 for ( int j = 0; j < nbNodes; ++j )
3731 const SMDS_MeshNode* n = faces[i]->GetNode(j);
3732 if ( n == srcNode ) continue;
3733 if ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE &&
3734 ( faces.size() > 1 || nbNodes > 3 ))
3736 gp_Pnt2d uv = helper.GetNodeUV( F, n );
3737 gp_Vec2d uvDirN( srcUV, uv );
3738 double proj = uvDirN * uvDir;
3739 proj2node.insert( make_pair( proj, n ));
3743 multimap< double, const SMDS_MeshNode* >::iterator p2n = proj2node.begin(), p2nEnd;
3744 const double minProj = p2n->first;
3745 const double projThreshold = 1.1 * uvLen;
3746 if ( minProj > projThreshold )
3748 // tgtNode is located so that it does not make faces with wrong orientation
3751 edge._pos.resize(1);
3752 edge._pos[0].SetCoord( tgtUV.X(), tgtUV.Y(), 0 );
3754 // store most risky nodes in _simplices
3755 p2nEnd = proj2node.lower_bound( projThreshold );
3756 int nbSimpl = ( std::distance( p2n, p2nEnd ) + 1) / 2;
3757 edge._simplices.resize( nbSimpl );
3758 for ( int i = 0; i < nbSimpl; ++i )
3760 edge._simplices[i]._nPrev = p2n->second;
3761 if ( ++p2n != p2nEnd )
3762 edge._simplices[i]._nNext = p2n->second;
3764 // set UV of source node to target node
3765 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
3766 pos->SetUParameter( srcUV.X() );
3767 pos->SetVParameter( srcUV.Y() );
3769 else // _sWOL is TopAbs_EDGE
3771 TopoDS_Edge E = TopoDS::Edge( edge._sWOL);
3772 SMESHDS_SubMesh* edgeSM = getMeshDS()->MeshElements( E );
3773 if ( !edgeSM || edgeSM->NbElements() == 0 )
3774 return error(SMESH_Comment("Not meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
3776 const SMDS_MeshNode* n2 = 0;
3777 SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
3778 while ( eIt->more() && !n2 )
3780 const SMDS_MeshElement* e = eIt->next();
3781 if ( !edgeSM->Contains(e)) continue;
3782 n2 = e->GetNode( 0 );
3783 if ( n2 == srcNode ) n2 = e->GetNode( 1 );
3786 return error(SMESH_Comment("Wrongly meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
3788 double uSrc = helper.GetNodeU( E, srcNode, n2 );
3789 double uTgt = helper.GetNodeU( E, tgtNode, srcNode );
3790 double u2 = helper.GetNodeU( E, n2, srcNode );
3792 if ( fabs( uSrc-uTgt ) < 0.99 * fabs( uSrc-u2 ))
3794 // tgtNode is located so that it does not make faces with wrong orientation
3797 edge._pos.resize(1);
3798 edge._pos[0].SetCoord( U_TGT, uTgt );
3799 edge._pos[0].SetCoord( U_SRC, uSrc );
3800 edge._pos[0].SetCoord( LEN_TGT, fabs( uSrc-uTgt ));
3802 edge._simplices.resize( 1 );
3803 edge._simplices[0]._nPrev = n2;
3805 // set UV of source node to target node
3806 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
3807 pos->SetUParameter( uSrc );
3811 //================================================================================
3813 * \brief Compute positions (UV) to set to a node on edge moved during shrinking
3815 //================================================================================
3817 // Compute UV to follow during shrinking
3819 // const SMDS_MeshNode* srcNode = edge._nodes[0];
3820 // const SMDS_MeshNode* tgtNode = edge._nodes.back();
3822 // gp_XY srcUV = helper.GetNodeUV( F, srcNode );
3823 // gp_XY tgtUV = helper.GetNodeUV( F, tgtNode );
3824 // gp_Vec2d uvDir( srcUV, tgtUV );
3825 // double uvLen = uvDir.Magnitude();
3828 // // Select shrinking step such that not to make faces with wrong orientation.
3829 // // IMPORTANT to have src nodes NOT yet REPLACED by tgt nodes in shrinked faces
3830 // const double minStepSize = uvLen / 20;
3831 // double stepSize = uvLen;
3832 // SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
3833 // while ( fIt->more() )
3835 // const SMDS_MeshElement* f = fIt->next();
3836 // if ( !faceSubMesh->Contains( f )) continue;
3837 // const int nbNodes = f->NbCornerNodes();
3838 // for ( int i = 0; i < nbNodes; ++i )
3840 // const SMDS_MeshNode* n = f->GetNode(i);
3841 // if ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE || n == srcNode)
3843 // gp_XY uv = helper.GetNodeUV( F, n );
3844 // gp_Vec2d uvDirN( srcUV, uv );
3845 // double proj = uvDirN * uvDir;
3846 // if ( proj < stepSize && proj > minStepSize )
3852 // const int nbSteps = ceil( uvLen / stepSize );
3853 // gp_XYZ srcUV0( srcUV.X(), srcUV.Y(), 0 );
3854 // gp_XYZ tgtUV0( tgtUV.X(), tgtUV.Y(), 0 );
3855 // edge._pos.resize( nbSteps );
3856 // edge._pos[0] = tgtUV0;
3857 // for ( int i = 1; i < nbSteps; ++i )
3859 // double r = i / double( nbSteps );
3860 // edge._pos[i] = (1-r) * tgtUV0 + r * srcUV0;
3865 //================================================================================
3867 * \brief Try to fix triangles with high aspect ratio by swaping diagonals
3869 //================================================================================
3871 void _ViscousBuilder::fixBadFaces(const TopoDS_Face& F, SMESH_MesherHelper& helper)
3873 SMESH::Controls::AspectRatio qualifier;
3874 SMESH::Controls::TSequenceOfXYZ points(3), points1(3), points2(3);
3875 const double maxAspectRatio = 4.;
3877 // find bad triangles
3879 vector< const SMDS_MeshElement* > badTrias;
3880 vector< double > badAspects;
3881 SMESHDS_SubMesh* sm = helper.GetMeshDS()->MeshElements( F );
3882 SMDS_ElemIteratorPtr fIt = sm->GetElements();
3883 while ( fIt->more() )
3885 const SMDS_MeshElement * f = fIt->next();
3886 if ( f->NbCornerNodes() != 3 ) continue;
3887 for ( int iP = 0; iP < 3; ++iP ) points(iP+1) = SMESH_TNodeXYZ( f->GetNode(iP));
3888 double aspect = qualifier.GetValue( points );
3889 if ( aspect > maxAspectRatio )
3891 badTrias.push_back( f );
3892 badAspects.push_back( aspect );
3895 if ( badTrias.empty() )
3898 // find couples of faces to swap diagonal
3900 typedef pair < const SMDS_MeshElement* , const SMDS_MeshElement* > T2Trias;
3901 vector< T2Trias > triaCouples;
3903 TIDSortedElemSet involvedFaces, emptySet;
3904 for ( size_t iTia = 0; iTia < badTrias.size(); ++iTia )
3907 double aspRatio [3];
3910 involvedFaces.insert( badTrias[iTia] );
3911 for ( int iP = 0; iP < 3; ++iP )
3912 points(iP+1) = SMESH_TNodeXYZ( badTrias[iTia]->GetNode(iP));
3914 // find triangles adjacent to badTrias[iTia] with better aspect ratio after diag-swaping
3915 int bestCouple = -1;
3916 for ( int iSide = 0; iSide < 3; ++iSide )
3918 const SMDS_MeshNode* n1 = badTrias[iTia]->GetNode( iSide );
3919 const SMDS_MeshNode* n2 = badTrias[iTia]->GetNode(( iSide+1 ) % 3 );
3920 trias [iSide].first = badTrias[iTia];
3921 trias [iSide].second = SMESH_MeshEditor::FindFaceInSet( n1, n2, emptySet, involvedFaces,
3923 if ( ! trias[iSide].second || trias[iSide].second->NbCornerNodes() != 3 )
3926 // aspect ratio of an adjacent tria
3927 for ( int iP = 0; iP < 3; ++iP )
3928 points2(iP+1) = SMESH_TNodeXYZ( trias[iSide].second->GetNode(iP));
3929 double aspectInit = qualifier.GetValue( points2 );
3931 // arrange nodes as after diag-swaping
3932 if ( helper.WrapIndex( i1+1, 3 ) == i2 )
3933 i3 = helper.WrapIndex( i1-1, 3 );
3935 i3 = helper.WrapIndex( i1+1, 3 );
3937 points1( 1+ iSide ) = points2( 1+ i3 );
3938 points2( 1+ i2 ) = points1( 1+ ( iSide+2 ) % 3 );
3940 // aspect ratio after diag-swaping
3941 aspRatio[ iSide ] = qualifier.GetValue( points1 ) + qualifier.GetValue( points2 );
3942 if ( aspRatio[ iSide ] > aspectInit + badAspects[ iTia ] )
3945 if ( bestCouple < 0 || aspRatio[ bestCouple ] > aspRatio[ iSide ] )
3949 if ( bestCouple >= 0 )
3951 triaCouples.push_back( trias[bestCouple] );
3952 involvedFaces.insert ( trias[bestCouple].second );
3956 involvedFaces.erase( badTrias[iTia] );
3959 if ( triaCouples.empty() )
3964 SMESH_MeshEditor editor( helper.GetMesh() );
3965 dumpFunction(SMESH_Comment("beforeSwapDiagonals_F")<<helper.GetSubShapeID());
3966 for ( size_t i = 0; i < triaCouples.size(); ++i )
3968 dumpChangeNodes( triaCouples[i].first );
3969 dumpChangeNodes( triaCouples[i].second );
3970 editor.InverseDiag( triaCouples[i].first, triaCouples[i].second );
3974 // just for debug dump resulting triangles
3975 dumpFunction(SMESH_Comment("swapDiagonals_F")<<helper.GetSubShapeID());
3976 for ( size_t i = 0; i < triaCouples.size(); ++i )
3978 dumpChangeNodes( triaCouples[i].first );
3979 dumpChangeNodes( triaCouples[i].second );
3983 //================================================================================
3985 * \brief Move target node to it's final position on the FACE during shrinking
3987 //================================================================================
3989 bool _LayerEdge::SetNewLength2d( Handle(Geom_Surface)& surface,
3990 const TopoDS_Face& F,
3991 SMESH_MesherHelper& helper )
3994 return false; // already at the target position
3996 SMDS_MeshNode* tgtNode = const_cast< SMDS_MeshNode*& >( _nodes.back() );
3998 if ( _sWOL.ShapeType() == TopAbs_FACE )
4000 gp_XY curUV = helper.GetNodeUV( F, tgtNode );
4001 gp_Pnt2d tgtUV( _pos[0].X(), _pos[0].Y());
4002 gp_Vec2d uvDir( _normal.X(), _normal.Y() );
4003 const double uvLen = tgtUV.Distance( curUV );
4005 // Select shrinking step such that not to make faces with wrong orientation.
4006 const double kSafe = 0.8;
4007 const double minStepSize = uvLen / 10;
4008 double stepSize = uvLen;
4009 for ( unsigned i = 0; i < _simplices.size(); ++i )
4011 const SMDS_MeshNode* nn[2] = { _simplices[i]._nPrev, _simplices[i]._nNext };
4012 for ( int j = 0; j < 2; ++j )
4013 if ( const SMDS_MeshNode* n = nn[j] )
4015 gp_XY uv = helper.GetNodeUV( F, n );
4016 gp_Vec2d uvDirN( curUV, uv );
4017 double proj = uvDirN * uvDir * kSafe;
4018 if ( proj < stepSize && proj > minStepSize )
4024 if ( stepSize == uvLen )
4031 newUV = curUV + uvDir.XY() * stepSize;
4034 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
4035 pos->SetUParameter( newUV.X() );
4036 pos->SetVParameter( newUV.Y() );
4039 gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
4040 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
4041 dumpMove( tgtNode );
4044 else // _sWOL is TopAbs_EDGE
4046 TopoDS_Edge E = TopoDS::Edge( _sWOL );
4047 const SMDS_MeshNode* n2 = _simplices[0]._nPrev;
4049 const double u2 = helper.GetNodeU( E, n2, tgtNode );
4050 const double uSrc = _pos[0].Coord( U_SRC );
4051 const double lenTgt = _pos[0].Coord( LEN_TGT );
4053 double newU = _pos[0].Coord( U_TGT );
4054 if ( lenTgt < 0.99 * fabs( uSrc-u2 ))
4060 newU = 0.1 * uSrc + 0.9 * u2;
4062 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
4063 pos->SetUParameter( newU );
4065 gp_XY newUV = helper.GetNodeUV( F, tgtNode, _nodes[0]);
4066 gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
4067 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
4068 dumpMove( tgtNode );
4074 //================================================================================
4076 * \brief Perform smooth on the FACE
4077 * \retval bool - true if the node has been moved
4079 //================================================================================
4081 bool _SmoothNode::Smooth(int& badNb,
4082 Handle(Geom_Surface)& surface,
4083 SMESH_MesherHelper& helper,
4084 const double refSign,
4088 const TopoDS_Face& face = TopoDS::Face( helper.GetSubShape() );
4090 // get uv of surrounding nodes
4091 vector<gp_XY> uv( _simplices.size() );
4092 for ( size_t i = 0; i < _simplices.size(); ++i )
4093 uv[i] = helper.GetNodeUV( face, _simplices[i]._nPrev, _node );
4095 // compute new UV for the node
4097 if ( isCentroidal && _simplices.size() > 3 )
4099 // average centers of diagonals wieghted with their reciprocal lengths
4100 if ( _simplices.size() == 4 )
4102 double w1 = 1. / ( uv[2]-uv[0] ).SquareModulus();
4103 double w2 = 1. / ( uv[3]-uv[1] ).SquareModulus();
4104 newPos = ( w1 * ( uv[2]+uv[0] ) + w2 * ( uv[3]+uv[1] )) / ( w1+w2 ) / 2;
4108 double sumWeight = 0;
4109 int nb = _simplices.size() == 4 ? 2 : _simplices.size();
4110 for ( int i = 0; i < nb; ++i )
4113 int iTo = i + _simplices.size() - 1;
4114 for ( int j = iFrom; j < iTo; ++j )
4116 int i2 = SMESH_MesherHelper::WrapIndex( j, _simplices.size() );
4117 double w = 1. / ( uv[i]-uv[i2] ).SquareModulus();
4119 newPos += w * ( uv[i]+uv[i2] );
4122 newPos /= 2 * sumWeight;
4128 isCentroidal = false;
4129 for ( size_t i = 0; i < _simplices.size(); ++i )
4131 newPos /= _simplices.size();
4134 // count quality metrics (orientation) of triangles around the node
4136 gp_XY tgtUV = helper.GetNodeUV( face, _node );
4137 for ( unsigned i = 0; i < _simplices.size(); ++i )
4138 nbOkBefore += _simplices[i].IsForward( tgtUV, _node, face, helper, refSign );
4141 for ( unsigned i = 0; i < _simplices.size(); ++i )
4142 nbOkAfter += _simplices[i].IsForward( newPos, _node, face, helper, refSign );
4144 if ( nbOkAfter < nbOkBefore )
4146 // if ( isCentroidal )
4147 // return Smooth( badNb, surface, helper, refSign, !isCentroidal, set3D );
4148 badNb += _simplices.size() - nbOkBefore;
4152 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( _node->GetPosition() );
4153 pos->SetUParameter( newPos.X() );
4154 pos->SetVParameter( newPos.Y() );
4161 gp_Pnt p = surface->Value( newPos.X(), newPos.Y() );
4162 const_cast< SMDS_MeshNode* >( _node )->setXYZ( p.X(), p.Y(), p.Z() );
4166 badNb += _simplices.size() - nbOkAfter;
4167 return ( (tgtUV-newPos).SquareModulus() > 1e-10 );
4170 //================================================================================
4172 * \brief Delete _SolidData
4174 //================================================================================
4176 _SolidData::~_SolidData()
4178 for ( unsigned i = 0; i < _edges.size(); ++i )
4180 if ( _edges[i] && _edges[i]->_2neibors )
4181 delete _edges[i]->_2neibors;
4186 //================================================================================
4188 * \brief Add a _LayerEdge inflated along the EDGE
4190 //================================================================================
4192 void _Shrinker1D::AddEdge( const _LayerEdge* e, SMESH_MesherHelper& helper )
4195 if ( _nodes.empty() )
4197 _edges[0] = _edges[1] = 0;
4201 if ( e == _edges[0] || e == _edges[1] )
4203 if ( e->_sWOL.IsNull() || e->_sWOL.ShapeType() != TopAbs_EDGE )
4204 throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
4205 if ( _edges[0] && _edges[0]->_sWOL != e->_sWOL )
4206 throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
4209 const TopoDS_Edge& E = TopoDS::Edge( e->_sWOL );
4211 BRep_Tool::Range( E, f,l );
4212 double u = helper.GetNodeU( E, e->_nodes[0], e->_nodes.back());
4213 _edges[ u < 0.5*(f+l) ? 0 : 1 ] = e;
4217 const SMDS_MeshNode* tgtNode0 = _edges[0] ? _edges[0]->_nodes.back() : 0;
4218 const SMDS_MeshNode* tgtNode1 = _edges[1] ? _edges[1]->_nodes.back() : 0;
4220 if ( _nodes.empty() )
4222 SMESHDS_SubMesh * eSubMesh = helper.GetMeshDS()->MeshElements( E );
4223 if ( !eSubMesh || eSubMesh->NbNodes() < 1 )
4225 TopLoc_Location loc;
4226 Handle(Geom_Curve) C = BRep_Tool::Curve(E, loc, f,l);
4227 GeomAdaptor_Curve aCurve(C, f,l);
4228 const double totLen = GCPnts_AbscissaPoint::Length(aCurve, f, l);
4230 int nbExpectNodes = eSubMesh->NbNodes() - e->_nodes.size();
4231 _initU .reserve( nbExpectNodes );
4232 _normPar.reserve( nbExpectNodes );
4233 _nodes .reserve( nbExpectNodes );
4234 SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
4235 while ( nIt->more() )
4237 const SMDS_MeshNode* node = nIt->next();
4238 if ( node->NbInverseElements(SMDSAbs_Edge) == 0 ||
4239 node == tgtNode0 || node == tgtNode1 )
4240 continue; // refinement nodes
4241 _nodes.push_back( node );
4242 _initU.push_back( helper.GetNodeU( E, node ));
4243 double len = GCPnts_AbscissaPoint::Length(aCurve, f, _initU.back());
4244 _normPar.push_back( len / totLen );
4249 // remove target node of the _LayerEdge from _nodes
4251 for ( unsigned i = 0; i < _nodes.size(); ++i )
4252 if ( !_nodes[i] || _nodes[i] == tgtNode0 || _nodes[i] == tgtNode1 )
4253 _nodes[i] = 0, nbFound++;
4254 if ( nbFound == _nodes.size() )
4259 //================================================================================
4261 * \brief Move nodes on EDGE from ends where _LayerEdge's are inflated
4263 //================================================================================
4265 void _Shrinker1D::Compute(bool set3D, SMESH_MesherHelper& helper)
4267 if ( _done || _nodes.empty())
4269 const _LayerEdge* e = _edges[0];
4270 if ( !e ) e = _edges[1];
4273 _done = (( !_edges[0] || _edges[0]->_pos.empty() ) &&
4274 ( !_edges[1] || _edges[1]->_pos.empty() ));
4276 const TopoDS_Edge& E = TopoDS::Edge( e->_sWOL );
4278 if ( set3D || _done )
4280 Handle(Geom_Curve) C = BRep_Tool::Curve(E, f,l);
4281 GeomAdaptor_Curve aCurve(C, f,l);
4284 f = helper.GetNodeU( E, _edges[0]->_nodes.back(), _nodes[0] );
4286 l = helper.GetNodeU( E, _edges[1]->_nodes.back(), _nodes.back() );
4287 double totLen = GCPnts_AbscissaPoint::Length( aCurve, f, l );
4289 for ( unsigned i = 0; i < _nodes.size(); ++i )
4291 if ( !_nodes[i] ) continue;
4292 double len = totLen * _normPar[i];
4293 GCPnts_AbscissaPoint discret( aCurve, len, f );
4294 if ( !discret.IsDone() )
4295 return throw SALOME_Exception(LOCALIZED("GCPnts_AbscissaPoint failed"));
4296 double u = discret.Parameter();
4297 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
4298 pos->SetUParameter( u );
4299 gp_Pnt p = C->Value( u );
4300 const_cast< SMDS_MeshNode*>( _nodes[i] )->setXYZ( p.X(), p.Y(), p.Z() );
4305 BRep_Tool::Range( E, f,l );
4307 f = helper.GetNodeU( E, _edges[0]->_nodes.back(), _nodes[0] );
4309 l = helper.GetNodeU( E, _edges[1]->_nodes.back(), _nodes.back() );
4311 for ( unsigned i = 0; i < _nodes.size(); ++i )
4313 if ( !_nodes[i] ) continue;
4314 double u = f * ( 1-_normPar[i] ) + l * _normPar[i];
4315 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
4316 pos->SetUParameter( u );
4321 //================================================================================
4323 * \brief Restore initial parameters of nodes on EDGE
4325 //================================================================================
4327 void _Shrinker1D::RestoreParams()
4330 for ( unsigned i = 0; i < _nodes.size(); ++i )
4332 if ( !_nodes[i] ) continue;
4333 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
4334 pos->SetUParameter( _initU[i] );
4339 //================================================================================
4341 * \brief Replace source nodes by target nodes in shrinked mesh edges
4343 //================================================================================
4345 void _Shrinker1D::SwapSrcTgtNodes( SMESHDS_Mesh* mesh )
4347 const SMDS_MeshNode* nodes[3];
4348 for ( int i = 0; i < 2; ++i )
4350 if ( !_edges[i] ) continue;
4352 SMESHDS_SubMesh * eSubMesh = mesh->MeshElements( _edges[i]->_sWOL );
4353 if ( !eSubMesh ) return;
4354 const SMDS_MeshNode* srcNode = _edges[i]->_nodes[0];
4355 const SMDS_MeshNode* tgtNode = _edges[i]->_nodes.back();
4356 SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
4357 while ( eIt->more() )
4359 const SMDS_MeshElement* e = eIt->next();
4360 if ( !eSubMesh->Contains( e ))
4362 SMDS_ElemIteratorPtr nIt = e->nodesIterator();
4363 for ( int iN = 0; iN < e->NbNodes(); ++iN )
4365 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
4366 nodes[iN] = ( n == srcNode ? tgtNode : n );
4368 mesh->ChangeElementNodes( e, nodes, e->NbNodes() );
4373 //================================================================================
4375 * \brief Creates 2D and 1D elements on boundaries of new prisms
4377 //================================================================================
4379 bool _ViscousBuilder::addBoundaryElements()
4381 SMESH_MesherHelper helper( *_mesh );
4383 for ( unsigned i = 0; i < _sdVec.size(); ++i )
4385 _SolidData& data = _sdVec[i];
4386 TopTools_IndexedMapOfShape geomEdges;
4387 TopExp::MapShapes( data._solid, TopAbs_EDGE, geomEdges );
4388 for ( int iE = 1; iE <= geomEdges.Extent(); ++iE )
4390 const TopoDS_Edge& E = TopoDS::Edge( geomEdges(iE));
4392 // Get _LayerEdge's based on E
4394 map< double, const SMDS_MeshNode* > u2nodes;
4395 if ( !SMESH_Algo::GetSortedNodesOnEdge( getMeshDS(), E, /*ignoreMedium=*/false, u2nodes))
4398 vector< _LayerEdge* > ledges; ledges.reserve( u2nodes.size() );
4399 TNode2Edge & n2eMap = data._n2eMap;
4400 map< double, const SMDS_MeshNode* >::iterator u2n = u2nodes.begin();
4402 //check if 2D elements are needed on E
4403 TNode2Edge::iterator n2e = n2eMap.find( u2n->second );
4404 if ( n2e == n2eMap.end() ) continue; // no layers on vertex
4405 ledges.push_back( n2e->second );
4407 if (( n2e = n2eMap.find( u2n->second )) == n2eMap.end() )
4408 continue; // no layers on E
4409 ledges.push_back( n2eMap[ u2n->second ]);
4411 const SMDS_MeshNode* tgtN0 = ledges[0]->_nodes.back();
4412 const SMDS_MeshNode* tgtN1 = ledges[1]->_nodes.back();
4413 int nbSharedPyram = 0;
4414 SMDS_ElemIteratorPtr vIt = tgtN0->GetInverseElementIterator(SMDSAbs_Volume);
4415 while ( vIt->more() )
4417 const SMDS_MeshElement* v = vIt->next();
4418 nbSharedPyram += int( v->GetNodeIndex( tgtN1 ) >= 0 );
4420 if ( nbSharedPyram > 1 )
4421 continue; // not free border of the pyramid
4423 if ( getMeshDS()->FindFace( ledges[0]->_nodes[0], ledges[0]->_nodes[1],
4424 ledges[1]->_nodes[0], ledges[1]->_nodes[1]))
4425 continue; // faces already created
4427 for ( ++u2n; u2n != u2nodes.end(); ++u2n )
4428 ledges.push_back( n2eMap[ u2n->second ]);
4430 // Find out orientation and type of face to create
4432 bool reverse = false, isOnFace;
4434 map< TGeomID, TopoDS_Shape >::iterator e2f =
4435 data._shrinkShape2Shape.find( getMeshDS()->ShapeToIndex( E ));
4437 if (( isOnFace = ( e2f != data._shrinkShape2Shape.end() )))
4439 F = e2f->second.Oriented( TopAbs_FORWARD );
4440 reverse = ( helper.GetSubShapeOri( F, E ) == TopAbs_REVERSED );
4441 if ( helper.GetSubShapeOri( data._solid, F ) == TopAbs_REVERSED )
4442 reverse = !reverse, F.Reverse();
4443 if ( SMESH_Algo::IsReversedSubMesh( TopoDS::Face(F), getMeshDS() ))
4448 // find FACE with layers sharing E
4449 PShapeIteratorPtr fIt = helper.GetAncestors( E, *_mesh, TopAbs_FACE );
4450 while ( fIt->more() && F.IsNull() )
4452 const TopoDS_Shape* pF = fIt->next();
4453 if ( helper.IsSubShape( *pF, data._solid) &&
4454 !_ignoreShapeIds.count( e2f->first ))
4458 // Find the sub-mesh to add new faces
4459 SMESHDS_SubMesh* sm = 0;
4461 sm = getMeshDS()->MeshElements( F );
4463 sm = data._proxyMesh->getFaceSubM( TopoDS::Face(F), /*create=*/true );
4465 return error("error in addBoundaryElements()", data._index);
4468 const int dj1 = reverse ? 0 : 1;
4469 const int dj2 = reverse ? 1 : 0;
4470 for ( unsigned j = 1; j < ledges.size(); ++j )
4472 vector< const SMDS_MeshNode*>& nn1 = ledges[j-dj1]->_nodes;
4473 vector< const SMDS_MeshNode*>& nn2 = ledges[j-dj2]->_nodes;
4475 for ( size_t z = 1; z < nn1.size(); ++z )
4476 sm->AddElement( getMeshDS()->AddFace( nn1[z-1], nn2[z-1], nn2[z], nn1[z] ));
4478 for ( size_t z = 1; z < nn1.size(); ++z )
4479 sm->AddElement( new SMDS_FaceOfNodes( nn1[z-1], nn2[z-1], nn2[z], nn1[z]));
4483 for ( int isFirst = 0; isFirst < 2; ++isFirst )
4485 _LayerEdge* edge = isFirst ? ledges.front() : ledges.back();
4486 if ( !edge->_sWOL.IsNull() && edge->_sWOL.ShapeType() == TopAbs_EDGE )
4488 vector< const SMDS_MeshNode*>& nn = edge->_nodes;
4489 if ( nn[1]->GetInverseElementIterator( SMDSAbs_Edge )->more() )
4491 helper.SetSubShape( edge->_sWOL );
4492 helper.SetElementsOnShape( true );
4493 for ( size_t z = 1; z < nn.size(); ++z )
4494 helper.AddEdge( nn[z-1], nn[z] );