1 // Copyright (C) 2007-2011 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_Gen.hxx"
36 #include "SMESH_Group.hxx"
37 #include "SMESH_Mesh.hxx"
38 #include "SMESH_MesherHelper.hxx"
39 #include "SMESH_subMesh.hxx"
40 #include "SMESH_subMeshEventListener.hxx"
41 #include "SMESH_ProxyMesh.hxx"
43 #include "utilities.h"
45 #include <BRep_Tool.hxx>
46 #include <Bnd_B2d.hxx>
47 #include <Bnd_B3d.hxx>
49 #include <GCPnts_AbscissaPoint.hxx>
50 #include <Geom2d_Circle.hxx>
51 #include <Geom2d_Line.hxx>
52 #include <Geom2d_TrimmedCurve.hxx>
53 #include <GeomAdaptor_Curve.hxx>
54 #include <Geom_Circle.hxx>
55 #include <Geom_Curve.hxx>
56 #include <Geom_Line.hxx>
57 #include <Geom_TrimmedCurve.hxx>
58 #include <Precision.hxx>
60 #include <TopExp_Explorer.hxx>
61 #include <TopTools_IndexedMapOfShape.hxx>
62 #include <TopTools_MapOfShape.hxx>
64 #include <TopoDS_Edge.hxx>
65 #include <TopoDS_Face.hxx>
66 #include <TopoDS_Vertex.hxx>
81 //================================================================================
86 enum UIndex { U_TGT = 1, U_SRC, LEN_TGT };
89 * \brief SMESH_ProxyMesh computed by _ViscousBuilder for a SOLID.
90 * It is stored in a SMESH_subMesh of the SOLID as SMESH_subMeshEventListenerData
92 struct _MeshOfSolid : public SMESH_ProxyMesh,
93 public SMESH_subMeshEventListenerData
97 _MeshOfSolid( SMESH_Mesh* mesh)
98 :SMESH_subMeshEventListenerData( /*isDeletable=*/true),_n2nMapComputed(false)
100 SMESH_ProxyMesh::setMesh( *mesh );
103 // returns submesh for a geom face
104 SMESH_ProxyMesh::SubMesh* getFaceSubM(const TopoDS_Face& F, bool create=false)
106 TGeomID i = SMESH_ProxyMesh::shapeIndex(F);
107 return create ? SMESH_ProxyMesh::getProxySubMesh(i) : findProxySubMesh(i);
109 void setNode2Node(const SMDS_MeshNode* srcNode,
110 const SMDS_MeshNode* proxyNode,
111 const SMESH_ProxyMesh::SubMesh* subMesh)
113 SMESH_ProxyMesh::setNode2Node( srcNode,proxyNode,subMesh);
116 //--------------------------------------------------------------------------------
118 * \brief Listener of events of 3D sub-meshes computed with viscous layers.
119 * It is used to clear an inferior dim sub-meshes modified by viscous layers
121 class _SrinkShapeListener : SMESH_subMeshEventListener
123 _SrinkShapeListener(): SMESH_subMeshEventListener(/*isDeletable=*/false) {}
124 static SMESH_subMeshEventListener* Get() { static _SrinkShapeListener l; return &l; }
126 virtual void ProcessEvent(const int event,
128 SMESH_subMesh* solidSM,
129 SMESH_subMeshEventListenerData* data,
130 const SMESH_Hypothesis* hyp)
132 if ( SMESH_subMesh::COMPUTE_EVENT == eventType && solidSM->IsEmpty() && data )
134 SMESH_subMeshEventListener::ProcessEvent(event,eventType,solidSM,data,hyp);
137 static void ToClearSubMeshWithSolid( SMESH_subMesh* sm,
138 const TopoDS_Shape& solid)
140 SMESH_subMesh* solidSM = sm->GetFather()->GetSubMesh( solid );
141 SMESH_subMeshEventListenerData* data = solidSM->GetEventListenerData( Get());
144 if ( find( data->mySubMeshes.begin(), data->mySubMeshes.end(), sm ) ==
145 data->mySubMeshes.end())
146 data->mySubMeshes.push_back( sm );
150 data = SMESH_subMeshEventListenerData::MakeData( /*dependent=*/sm );
151 sm->SetEventListener( Get(), data, /*whereToListenTo=*/solidSM );
155 //--------------------------------------------------------------------------------
157 * \brief Listener of events of 3D sub-meshes computed with viscous layers.
158 * It is used to store data computed by _ViscousBuilder for a sub-mesh and to
159 * delete the data as soon as it has been used
161 class _ViscousListener : SMESH_subMeshEventListener
163 _ViscousListener(): SMESH_subMeshEventListener(/*isDeletable=*/false) {}
164 static SMESH_subMeshEventListener* Get() { static _ViscousListener l; return &l; }
166 virtual void ProcessEvent(const int event,
168 SMESH_subMesh* subMesh,
169 SMESH_subMeshEventListenerData* data,
170 const SMESH_Hypothesis* hyp)
172 if ( SMESH_subMesh::COMPUTE_EVENT == eventType )
174 // delete SMESH_ProxyMesh containing temporary faces
175 subMesh->DeleteEventListener( this );
178 // Finds or creates proxy mesh of the solid
179 static _MeshOfSolid* GetSolidMesh(SMESH_Mesh* mesh,
180 const TopoDS_Shape& solid,
183 if ( !mesh ) return 0;
184 SMESH_subMesh* sm = mesh->GetSubMesh(solid);
185 _MeshOfSolid* data = (_MeshOfSolid*) sm->GetEventListenerData( Get() );
186 if ( !data && toCreate )
188 data = new _MeshOfSolid(mesh);
189 data->mySubMeshes.push_back( sm ); // to find SOLID by _MeshOfSolid
190 sm->SetEventListener( Get(), data, sm );
194 // Removes proxy mesh of the solid
195 static void RemoveSolidMesh(SMESH_Mesh* mesh, const TopoDS_Shape& solid)
197 mesh->GetSubMesh(solid)->DeleteEventListener( _ViscousListener::Get() );
201 //--------------------------------------------------------------------------------
203 * \brief Simplex (triangle or tetrahedron) based on 1 (tria) or 2 (tet) nodes of
204 * _LayerEdge and 2 nodes of the mesh surface beening smoothed.
205 * The class is used to check validity of face or volumes around a smoothed node;
206 * it stores only 2 nodes as the other nodes are stored by _LayerEdge.
210 const SMDS_MeshNode *_nPrev, *_nNext; // nodes on a smoothed mesh surface
211 _Simplex(const SMDS_MeshNode* nPrev=0, const SMDS_MeshNode* nNext=0)
212 : _nPrev(nPrev), _nNext(nNext) {}
213 bool IsForward(const SMDS_MeshNode* nSrc, const gp_XYZ* pntTgt) const
215 const double M[3][3] =
216 {{ _nNext->X() - nSrc->X(), _nNext->Y() - nSrc->Y(), _nNext->Z() - nSrc->Z() },
217 { pntTgt->X() - nSrc->X(), pntTgt->Y() - nSrc->Y(), pntTgt->Z() - nSrc->Z() },
218 { _nPrev->X() - nSrc->X(), _nPrev->Y() - nSrc->Y(), _nPrev->Z() - nSrc->Z() }};
219 double determinant = ( + M[0][0]*M[1][1]*M[2][2]
220 + M[0][1]*M[1][2]*M[2][0]
221 + M[0][2]*M[1][0]*M[2][1]
222 - M[0][0]*M[1][2]*M[2][1]
223 - M[0][1]*M[1][0]*M[2][2]
224 - M[0][2]*M[1][1]*M[2][0]);
225 return determinant > 1e-100;
227 bool IsForward(const gp_XY& tgtUV,
228 const TopoDS_Face& face,
229 SMESH_MesherHelper& helper,
230 const double refSign) const
232 gp_XY prevUV = helper.GetNodeUV( face, _nPrev );
233 gp_XY nextUV = helper.GetNodeUV( face, _nNext );
234 gp_Vec2d v1( tgtUV, prevUV ), v2( tgtUV, nextUV );
236 return d*refSign > 1e-100;
239 //--------------------------------------------------------------------------------
241 * Structure used to take into account surface curvature while smoothing
246 double _k; // factor to correct node smoothed position
248 static _Curvature* New( double avgNormProj, double avgDist )
251 if ( fabs( avgNormProj / avgDist ) > 1./200 )
254 c->_r = avgDist * avgDist / avgNormProj;
255 c->_k = avgDist * avgDist / c->_r / c->_r;
256 c->_k *= ( c->_r < 0 ? 1/1.1 : 1.1 ); // not to be too restrictive
260 double lenDelta(double len) const { return _k * ( _r + len ); }
263 //--------------------------------------------------------------------------------
265 * Structure used to smooth a _LayerEdge (master) based on an EDGE.
269 // target nodes of 2 neighbour _LayerEdge's based on the same EDGE
270 const SMDS_MeshNode* _nodes[2];
271 // vectors from source nodes of 2 _LayerEdge's to the source node of master _LayerEdge
273 double _wgt[2]; // weights of _nodes
274 _LayerEdge* _edges[2];
276 // normal to plane passing through _LayerEdge._normal and tangent of EDGE
279 _2NearEdges() { _nodes[0]=_nodes[1]=0; _plnNorm = 0; }
281 std::swap( _nodes[0], _nodes[1] );
282 std::swap( _wgt[0], _wgt[1] );
285 //--------------------------------------------------------------------------------
287 * \brief Edge normal to surface, connecting a node on solid surface (_nodes[0])
288 * and a node of the most internal layer (_nodes.back())
292 vector< const SMDS_MeshNode*> _nodes;
294 gp_XYZ _normal; // to solid surface
295 vector<gp_XYZ> _pos; // points computed during inflation
296 double _len; // length achived with the last step
297 double _cosin; // of angle (_normal ^ surface)
298 double _lenFactor; // to compute _len taking _cosin into account
300 // face or edge w/o layer along or near which _LayerEdge is inflated
302 // simplices connected to the source node (_nodes[0]);
303 // used for smoothing and quality check of _LayerEdge's based on the FACE
304 vector<_Simplex> _simplices;
305 // data for smoothing of _LayerEdge's based on the EDGE
306 _2NearEdges* _2neibors;
308 _Curvature* _curvature;
309 // TODO:: detele _Curvature, _plnNorm
311 void SetNewLength( double len, SMESH_MesherHelper& helper );
312 bool SetNewLength2d( Handle(Geom_Surface)& surface,
313 const TopoDS_Face& F,
314 SMESH_MesherHelper& helper );
315 void SetDataByNeighbors( const SMDS_MeshNode* n1,
316 const SMDS_MeshNode* n2,
317 SMESH_MesherHelper& helper);
318 void InvalidateStep( int curStep );
319 bool Smooth(int& badNb);
320 bool SmoothOnEdge(Handle(Geom_Surface)& surface,
321 const TopoDS_Face& F,
322 SMESH_MesherHelper& helper);
323 bool FindIntersection( SMESH_ElementSearcher& searcher,
325 const double& epsilon,
326 const SMDS_MeshElement** face = 0);
327 bool SegTriaInter( const gp_Ax1& lastSegment,
328 const SMDS_MeshNode* n0,
329 const SMDS_MeshNode* n1,
330 const SMDS_MeshNode* n2,
332 const double& epsilon) const;
333 gp_Ax1 LastSegment(double& segLen) const;
334 bool IsOnEdge() const { return _2neibors; }
335 void Copy( _LayerEdge& other, SMESH_MesherHelper& helper );
336 void SetCosin( double cosin );
340 bool operator () (const _LayerEdge* e1, const _LayerEdge* e2) const
342 const bool cmpNodes = ( e1 && e2 && e1->_nodes.size() && e2->_nodes.size() );
343 return cmpNodes ? ( e1->_nodes[0]->GetID() < e2->_nodes[0]->GetID()) : ( e1 < e2 );
346 //--------------------------------------------------------------------------------
348 typedef map< const SMDS_MeshNode*, _LayerEdge*, TIDCompare > TNode2Edge;
350 //--------------------------------------------------------------------------------
352 * \brief Data of a SOLID
357 const StdMeshers_ViscousLayers* _hyp;
358 _MeshOfSolid* _proxyMesh;
359 set<TGeomID> _reversedFaceIds;
361 double _stepSize, _stepSizeCoeff;
362 const SMDS_MeshNode* _stepSizeNodes[2];
365 // edges of _n2eMap. We keep same data in two containers because
366 // iteration over the map is 5 time longer than over the vector
367 vector< _LayerEdge* > _edges;
369 // key: an id of shape (EDGE or VERTEX) shared by a FACE with
370 // layers and a FACE w/o layers
371 // value: the shape (FACE or EDGE) to shrink mesh on.
372 // _LayerEdge's basing on nodes on key shape are inflated along the value shape
373 map< TGeomID, TopoDS_Shape > _shrinkShape2Shape;
375 // FACE's WOL, srink on which is forbiden due to algo on the adjacent SOLID
376 set< TGeomID > _noShrinkFaces;
378 // <EDGE to smooth on> to <it's curve>
379 map< TGeomID,Handle(Geom_Curve)> _edge2curve;
381 // end indices in _edges of _LayerEdge on one shape to smooth
382 vector< int > _endEdgeToSmooth;
384 double _epsilon; // precision for SegTriaInter()
386 int _index; // for debug
388 _SolidData(const TopoDS_Shape& s=TopoDS_Shape(),
389 const StdMeshers_ViscousLayers* h=0,
390 _MeshOfSolid* m=0) :_solid(s), _hyp(h), _proxyMesh(m) {}
393 Handle(Geom_Curve) CurveForSmooth( const TopoDS_Edge& E,
396 Handle(Geom_Surface)& surface,
397 const TopoDS_Face& F,
398 SMESH_MesherHelper& helper);
400 //--------------------------------------------------------------------------------
402 * \brief Data of node on a shrinked FACE
406 const SMDS_MeshNode* _node;
407 //vector<const SMDS_MeshNode*> _nodesAround;
408 vector<_Simplex> _simplices; // for quality check
410 bool Smooth(int& badNb,
411 Handle(Geom_Surface)& surface,
412 SMESH_MesherHelper& helper,
413 const double refSign,
416 //--------------------------------------------------------------------------------
418 * \brief Builder of viscous layers
420 class _ViscousBuilder
425 SMESH_ComputeErrorPtr Compute(SMESH_Mesh& mesh,
426 const TopoDS_Shape& shape);
428 // restore event listeners used to clear an inferior dim sub-mesh modified by viscous layers
429 void RestoreListeners();
431 // computes SMESH_ProxyMesh::SubMesh::_n2n;
432 bool MakeN2NMap( _MeshOfSolid* pm );
436 bool findSolidsWithLayers();
437 bool findFacesWithLayers();
438 bool makeLayer(_SolidData& data);
439 bool setEdgeData(_LayerEdge& edge, const set<TGeomID>& subIds,
440 SMESH_MesherHelper& helper, _SolidData& data);
441 bool findNeiborsOnEdge(const _LayerEdge* edge,
442 const SMDS_MeshNode*& n1,
443 const SMDS_MeshNode*& n2,
445 void getSimplices( const SMDS_MeshNode* node, vector<_Simplex>& simplices,
446 const set<TGeomID>& ingnoreShapes,
447 const _SolidData* dataToCheckOri = 0);
448 bool sortEdges( _SolidData& data,
449 vector< vector<_LayerEdge*> >& edgesByGeom);
450 void limitStepSize( _SolidData& data,
451 const SMDS_MeshElement* face,
453 void limitStepSize( _SolidData& data, const double minSize);
454 bool inflate(_SolidData& data);
455 bool smoothAndCheck(_SolidData& data, const int nbSteps, double & distToIntersection);
456 bool smoothAnalyticEdge( _SolidData& data,
459 Handle(Geom_Surface)& surface,
460 const TopoDS_Face& F,
461 SMESH_MesherHelper& helper);
462 bool updateNormals( _SolidData& data, SMESH_MesherHelper& helper );
463 bool refine(_SolidData& data);
465 bool prepareEdgeToShrink( _LayerEdge& edge, const TopoDS_Face& F,
466 SMESH_MesherHelper& helper,
467 const SMESHDS_SubMesh* faceSubMesh );
468 bool addBoundaryElements();
470 bool error( const string& text, int solidID=-1 );
471 SMESHDS_Mesh* getMeshDS() { return _mesh->GetMeshDS(); }
474 void makeGroupOfLE();
477 SMESH_ComputeErrorPtr _error;
479 vector< _SolidData > _sdVec;
480 set<TGeomID> _ignoreShapeIds;
483 //--------------------------------------------------------------------------------
485 * \brief Shrinker of nodes on the EDGE
489 vector<double> _initU;
490 vector<double> _normPar;
491 vector<const SMDS_MeshNode*> _nodes;
492 const _LayerEdge* _edges[2];
495 void AddEdge( const _LayerEdge* e, SMESH_MesherHelper& helper );
496 void Compute(bool set3D, SMESH_MesherHelper& helper);
497 void RestoreParams();
498 void SwapSrcTgtNodes(SMESHDS_Mesh* mesh);
500 //--------------------------------------------------------------------------------
502 * \brief Class of temporary mesh face.
503 * We can't use SMDS_FaceOfNodes since it's impossible to set it's ID which is
504 * needed because SMESH_ElementSearcher internaly uses set of elements sorted by ID
506 struct TmpMeshFace : public SMDS_MeshElement
508 vector<const SMDS_MeshNode* > _nn;
509 TmpMeshFace( const vector<const SMDS_MeshNode*>& nodes, int id):
510 SMDS_MeshElement(id), _nn(nodes) {}
511 virtual const SMDS_MeshNode* GetNode(const int ind) const { return _nn[ind]; }
512 virtual SMDSAbs_ElementType GetType() const { return SMDSAbs_Face; }
513 virtual vtkIdType GetVtkType() const { return -1; }
514 virtual SMDSAbs_EntityType GetEntityType() const { return SMDSEntity_Last; }
515 virtual SMDS_ElemIteratorPtr elementsIterator(SMDSAbs_ElementType type) const
516 { return SMDS_ElemIteratorPtr( new SMDS_NodeVectorElemIterator( _nn.begin(), _nn.end()));}
518 //--------------------------------------------------------------------------------
520 * \brief Class of temporary mesh face storing _LayerEdge it's based on
522 struct TmpMeshFaceOnEdge : public TmpMeshFace
524 _LayerEdge *_le1, *_le2;
525 TmpMeshFaceOnEdge( _LayerEdge* le1, _LayerEdge* le2, int ID ):
526 TmpMeshFace( vector<const SMDS_MeshNode*>(4), ID ), _le1(le1), _le2(le2)
528 _nn[0]=_le1->_nodes[0];
529 _nn[1]=_le1->_nodes.back();
530 _nn[2]=_le2->_nodes.back();
531 _nn[3]=_le2->_nodes[0];
534 } // namespace VISCOUS
536 //================================================================================
537 // StdMeshers_ViscousLayers hypothesis
539 StdMeshers_ViscousLayers::StdMeshers_ViscousLayers(int hypId, int studyId, SMESH_Gen* gen)
540 :SMESH_Hypothesis(hypId, studyId, gen),
541 _nbLayers(1), _thickness(1), _stretchFactor(1)
543 _name = StdMeshers_ViscousLayers::GetHypType();
544 _param_algo_dim = -3; // auxiliary hyp used by 3D algos
545 } // --------------------------------------------------------------------------------
546 void StdMeshers_ViscousLayers::SetIgnoreFaces(const std::vector<int>& faceIds)
548 if ( faceIds != _ignoreFaceIds )
549 _ignoreFaceIds = faceIds, NotifySubMeshesHypothesisModification();
550 } // --------------------------------------------------------------------------------
551 void StdMeshers_ViscousLayers::SetTotalThickness(double thickness)
553 if ( thickness != _thickness )
554 _thickness = thickness, NotifySubMeshesHypothesisModification();
555 } // --------------------------------------------------------------------------------
556 void StdMeshers_ViscousLayers::SetNumberLayers(int nb)
558 if ( _nbLayers != nb )
559 _nbLayers = nb, NotifySubMeshesHypothesisModification();
560 } // --------------------------------------------------------------------------------
561 void StdMeshers_ViscousLayers::SetStretchFactor(double factor)
563 if ( _stretchFactor != factor )
564 _stretchFactor = factor, NotifySubMeshesHypothesisModification();
565 } // --------------------------------------------------------------------------------
567 StdMeshers_ViscousLayers::Compute(SMESH_Mesh& theMesh,
568 const TopoDS_Shape& theShape,
569 const bool toMakeN2NMap) const
571 using namespace VISCOUS;
572 _ViscousBuilder bulder;
573 SMESH_ComputeErrorPtr err = bulder.Compute( theMesh, theShape );
574 if ( err && !err->IsOK() )
575 return SMESH_ProxyMesh::Ptr();
577 vector<SMESH_ProxyMesh::Ptr> components;
578 TopExp_Explorer exp( theShape, TopAbs_SOLID );
579 for ( ; exp.More(); exp.Next() )
581 if ( _MeshOfSolid* pm =
582 _ViscousListener::GetSolidMesh( &theMesh, exp.Current(), /*toCreate=*/false))
584 if ( toMakeN2NMap && !pm->_n2nMapComputed )
585 if ( !bulder.MakeN2NMap( pm ))
586 return SMESH_ProxyMesh::Ptr();
587 components.push_back( SMESH_ProxyMesh::Ptr( pm ));
588 pm->myIsDeletable = false; // it will de deleted by boost::shared_ptr
590 _ViscousListener::RemoveSolidMesh ( &theMesh, exp.Current() );
592 switch ( components.size() )
596 case 1: return components[0];
598 default: return SMESH_ProxyMesh::Ptr( new SMESH_ProxyMesh( components ));
600 return SMESH_ProxyMesh::Ptr();
601 } // --------------------------------------------------------------------------------
602 std::ostream & StdMeshers_ViscousLayers::SaveTo(std::ostream & save)
604 save << " " << _nbLayers
606 << " " << _stretchFactor
607 << " " << _ignoreFaceIds.size();
608 for ( unsigned i = 0; i < _ignoreFaceIds.size(); ++i )
609 save << " " << _ignoreFaceIds[i];
611 } // --------------------------------------------------------------------------------
612 std::istream & StdMeshers_ViscousLayers::LoadFrom(std::istream & load)
615 load >> _nbLayers >> _thickness >> _stretchFactor >> nbFaces;
616 while ( _ignoreFaceIds.size() < nbFaces && load >> faceID )
617 _ignoreFaceIds.push_back( faceID );
619 } // --------------------------------------------------------------------------------
620 bool StdMeshers_ViscousLayers::SetParametersByMesh(const SMESH_Mesh* theMesh,
621 const TopoDS_Shape& theShape)
626 // END StdMeshers_ViscousLayers hypothesis
627 //================================================================================
631 gp_XYZ getEdgeDir( const TopoDS_Edge& E, const TopoDS_Vertex& fromV )
635 Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
636 gp_Pnt p = BRep_Tool::Pnt( fromV );
637 double distF = p.SquareDistance( c->Value( f ));
638 double distL = p.SquareDistance( c->Value( l ));
639 c->D1(( distF < distL ? f : l), p, dir );
640 if ( distL < distF ) dir.Reverse();
643 //--------------------------------------------------------------------------------
644 gp_XYZ getEdgeDir( const TopoDS_Edge& E, const SMDS_MeshNode* atNode,
645 SMESH_MesherHelper& helper)
648 double f,l; gp_Pnt p;
649 Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
650 double u = helper.GetNodeU( E, atNode );
654 //--------------------------------------------------------------------------------
655 gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Edge& fromE,
656 const SMDS_MeshNode* node, SMESH_MesherHelper& helper, bool& ok)
658 gp_XY uv = helper.GetNodeUV( F, node, 0, &ok );
659 Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
660 gp_Pnt p; gp_Vec du, dv, norm;
661 surface->D1( uv.X(),uv.Y(), p, du,dv );
665 Handle(Geom_Curve) c = BRep_Tool::Curve( fromE, f, l );
666 double u = helper.GetNodeU( fromE, node, 0, &ok );
668 TopAbs_Orientation o = helper.GetSubShapeOri( F.Oriented(TopAbs_FORWARD), fromE);
669 if ( o == TopAbs_REVERSED )
672 gp_Vec dir = norm ^ du;
674 if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX &&
675 helper.IsClosedEdge( fromE ))
677 if ( fabs(u-f) < fabs(u-l )) c->D1( l, p, dv );
678 else c->D1( f, p, dv );
679 if ( o == TopAbs_REVERSED )
681 gp_Vec dir2 = norm ^ dv;
682 dir = dir.Normalized() + dir2.Normalized();
686 //--------------------------------------------------------------------------------
687 gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Vertex& fromV,
688 const SMDS_MeshNode* node, SMESH_MesherHelper& helper,
689 bool& ok, double* cosin=0)
691 double f,l; TopLoc_Location loc;
692 vector< TopoDS_Edge > edges; // sharing a vertex
693 PShapeIteratorPtr eIt = helper.GetAncestors( fromV, *helper.GetMesh(), TopAbs_EDGE);
696 const TopoDS_Edge* e = static_cast<const TopoDS_Edge*>( eIt->next() );
697 if ( helper.IsSubShape( *e, F ) && !BRep_Tool::Curve( *e, loc,f,l).IsNull() )
698 edges.push_back( *e );
701 if ( !( ok = ( edges.size() > 0 ))) return dir;
702 // get average dir of edges going fromV
704 for ( unsigned i = 0; i < edges.size(); ++i )
706 edgeDir = getEdgeDir( edges[i], fromV );
707 double size2 = edgeDir.SquareMagnitude();
708 if ( size2 > numeric_limits<double>::min() )
709 edgeDir /= sqrt( size2 );
712 dir += edgeDir.XYZ();
714 gp_XYZ fromEdgeDir = getFaceDir( F, edges[0], node, helper, ok );
715 if ( edges.size() == 1 || dir.SquareModulus() < 1e-10)
717 else if ( dir * fromEdgeDir < 0 )
721 //dir /= edges.size();
723 double angle = edgeDir.Angle( dir );
724 *cosin = cos( angle );
729 //--------------------------------------------------------------------------------
730 // DEBUG. Dump intermediate node positions into a python script
735 const char* fname = "/tmp/viscous.py";
736 cout << "execfile('"<<fname<<"')"<<endl;
737 py = new ofstream(fname);
738 *py << "from smesh import *" << endl
739 << "meshSO = GetCurrentStudy().FindObjectID('0:1:2:3')" << endl
740 << "mesh = Mesh( meshSO.GetObject()._narrow( SMESH.SMESH_Mesh ))"<<endl;
743 *py << "mesh.MakeGroup('Prisms of viscous layers',VOLUME,FT_ElemGeomType,'=',Geom_PENTA)"
744 <<endl; delete py; py=0;
747 #define dumpFunction(f) { _dumpFunction(f, __LINE__);}
748 #define dumpMove(n) { _dumpMove(n, __LINE__);}
749 #define dumpCmd(txt) { _dumpCmd(txt, __LINE__);}
750 void _dumpFunction(const string& fun, int ln)
751 { *py<< "def "<<fun<<"(): # "<< ln <<endl; cout<<fun<<"()"<<endl;}
752 void _dumpMove(const SMDS_MeshNode* n, int ln)
753 { *py<< " mesh.MoveNode( "<<n->GetID()<< ", "<< n->X()
754 << ", "<<n->Y()<<", "<< n->Z()<< ")\t\t # "<< ln <<endl; }
755 void _dumpCmd(const string& txt, int ln)
756 { *py<< " "<<txt<<" # "<< ln <<endl; }
757 void dumpFunctionEnd()
758 { *py<< " return"<< endl; }
760 struct PyDump { PyDump() {} };
761 void dumpFunction(const string& fun ){}
762 void dumpFunctionEnd() {}
763 void dumpMove(const SMDS_MeshNode* n ){}
764 void dumpCmd(const string& txt){}
768 using namespace VISCOUS;
770 //================================================================================
772 * \brief Constructor of _ViscousBuilder
774 //================================================================================
776 _ViscousBuilder::_ViscousBuilder()
778 _error = SMESH_ComputeError::New(COMPERR_OK);
782 //================================================================================
784 * \brief Stores error description and returns false
786 //================================================================================
788 bool _ViscousBuilder::error(const string& text, int solidId )
790 _error->myName = COMPERR_ALGO_FAILED;
791 _error->myComment = string("Viscous layers builder: ") + text;
794 SMESH_subMesh* sm = _mesh->GetSubMeshContaining( solidId );
795 if ( !sm && !_sdVec.empty() )
796 sm = _mesh->GetSubMeshContaining( _sdVec[0]._index );
797 if ( sm && sm->GetSubShape().ShapeType() == TopAbs_SOLID )
799 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
800 if ( smError && smError->myAlgo )
801 _error->myAlgo = smError->myAlgo;
805 makeGroupOfLE(); // debug
810 //================================================================================
812 * \brief At study restoration, restore event listeners used to clear an inferior
813 * dim sub-mesh modified by viscous layers
815 //================================================================================
817 void _ViscousBuilder::RestoreListeners()
822 //================================================================================
824 * \brief computes SMESH_ProxyMesh::SubMesh::_n2n
826 //================================================================================
828 bool _ViscousBuilder::MakeN2NMap( _MeshOfSolid* pm )
830 SMESH_subMesh* solidSM = pm->mySubMeshes.front();
831 TopExp_Explorer fExp( solidSM->GetSubShape(), TopAbs_FACE );
832 for ( ; fExp.More(); fExp.Next() )
834 SMESHDS_SubMesh* srcSmDS = pm->GetMeshDS()->MeshElements( fExp.Current() );
835 const SMESH_ProxyMesh::SubMesh* prxSmDS = pm->GetProxySubMesh( fExp.Current() );
837 if ( !srcSmDS || !prxSmDS || !srcSmDS->NbElements() || !prxSmDS->NbElements() )
839 if ( srcSmDS->GetElements()->next() == prxSmDS->GetElements()->next())
842 if ( srcSmDS->NbElements() != prxSmDS->NbElements() )
843 return error( "Different nb elements in a source and a proxy sub-mesh", solidSM->GetId());
845 SMDS_ElemIteratorPtr srcIt = srcSmDS->GetElements();
846 SMDS_ElemIteratorPtr prxIt = prxSmDS->GetElements();
847 while( prxIt->more() )
849 const SMDS_MeshElement* fSrc = srcIt->next();
850 const SMDS_MeshElement* fPrx = prxIt->next();
851 if ( fSrc->NbNodes() != fPrx->NbNodes())
852 return error( "Different elements in a source and a proxy sub-mesh", solidSM->GetId());
853 for ( int i = 0 ; i < fPrx->NbNodes(); ++i )
854 pm->setNode2Node( fSrc->GetNode(i), fPrx->GetNode(i), prxSmDS );
857 pm->_n2nMapComputed = true;
861 //================================================================================
863 * \brief Does its job
865 //================================================================================
867 SMESH_ComputeErrorPtr _ViscousBuilder::Compute(SMESH_Mesh& theMesh,
868 const TopoDS_Shape& theShape)
870 // TODO: set priority of solids during Gen::Compute()
874 // check if proxy mesh already computed
875 TopExp_Explorer exp( theShape, TopAbs_SOLID );
877 return error("No SOLID's in theShape"), _error;
879 if ( _ViscousListener::GetSolidMesh( _mesh, exp.Current(), /*toCreate=*/false))
880 return SMESH_ComputeErrorPtr(); // everything already computed
884 // TODO: ignore already computed SOLIDs
885 if ( !findSolidsWithLayers())
888 if ( !findFacesWithLayers() )
891 for ( unsigned i = 0; i < _sdVec.size(); ++i )
893 if ( ! makeLayer(_sdVec[i]) )
896 if ( ! inflate(_sdVec[i]) )
899 if ( ! refine(_sdVec[i]) )
905 addBoundaryElements();
907 makeGroupOfLE(); // debug
912 //================================================================================
914 * \brief Finds SOLIDs to compute using viscous layers. Fills _sdVec
916 //================================================================================
918 bool _ViscousBuilder::findSolidsWithLayers()
921 TopTools_IndexedMapOfShape allSolids;
922 TopExp::MapShapes( _mesh->GetShapeToMesh(), TopAbs_SOLID, allSolids );
923 _sdVec.reserve( allSolids.Extent());
925 SMESH_Gen* gen = _mesh->GetGen();
926 for ( int i = 1; i <= allSolids.Extent(); ++i )
928 // find StdMeshers_ViscousLayers hyp assigned to the i-th solid
929 SMESH_Algo* algo = gen->GetAlgo( *_mesh, allSolids(i) );
930 if ( !algo ) continue;
931 // TODO: check if algo is hidden
932 const list <const SMESHDS_Hypothesis *> & allHyps =
933 algo->GetUsedHypothesis(*_mesh, allSolids(i), /*ignoreAuxiliary=*/false);
934 list< const SMESHDS_Hypothesis *>::const_iterator hyp = allHyps.begin();
935 const StdMeshers_ViscousLayers* viscHyp = 0;
936 for ( ; hyp != allHyps.end() && !viscHyp; ++hyp )
937 viscHyp = dynamic_cast<const StdMeshers_ViscousLayers*>( *hyp );
940 _MeshOfSolid* proxyMesh = _ViscousListener::GetSolidMesh( _mesh,
943 _sdVec.push_back( _SolidData( allSolids(i), viscHyp, proxyMesh ));
944 _sdVec.back()._index = getMeshDS()->ShapeToIndex( allSolids(i));
947 if ( _sdVec.empty() )
949 ( SMESH_Comment(StdMeshers_ViscousLayers::GetHypType()) << " hypothesis not found",0);
954 //================================================================================
958 //================================================================================
960 bool _ViscousBuilder::findFacesWithLayers()
962 // collect all faces to ignore defined by hyp
963 vector<TopoDS_Shape> ignoreFaces;
964 for ( unsigned i = 0; i < _sdVec.size(); ++i )
966 vector<TGeomID> ids = _sdVec[i]._hyp->GetIgnoreFaces();
967 for ( unsigned i = 0; i < ids.size(); ++i )
969 const TopoDS_Shape& s = getMeshDS()->IndexToShape( ids[i] );
970 if ( !s.IsNull() && s.ShapeType() == TopAbs_FACE )
972 _ignoreShapeIds.insert( ids[i] );
973 ignoreFaces.push_back( s );
978 // ignore internal faces
979 SMESH_MesherHelper helper( *_mesh );
981 for ( unsigned i = 0; i < _sdVec.size(); ++i )
983 exp.Init( _sdVec[i]._solid.Oriented( TopAbs_FORWARD ), TopAbs_FACE );
984 for ( ; exp.More(); exp.Next() )
986 TGeomID faceInd = getMeshDS()->ShapeToIndex( exp.Current() );
987 if ( helper.NbAncestors( exp.Current(), *_mesh, TopAbs_SOLID ) > 1 )
989 _ignoreShapeIds.insert( faceInd );
990 ignoreFaces.push_back( exp.Current() );
991 if ( SMESH_Algo::IsReversedSubMesh( TopoDS::Face( exp.Current() ), getMeshDS()))
992 _sdVec[i]._reversedFaceIds.insert( faceInd );
997 // Find faces to shrink mesh on (solution 2 in issue 0020832);
998 TopTools_IndexedMapOfShape shapes;
999 for ( unsigned i = 0; i < _sdVec.size(); ++i )
1002 TopExp::MapShapes(_sdVec[i]._solid, TopAbs_EDGE, shapes);
1003 for ( int iE = 1; iE <= shapes.Extent(); ++iE )
1005 const TopoDS_Shape& edge = shapes(iE);
1006 // find 2 faces sharing an edge
1008 PShapeIteratorPtr fIt = helper.GetAncestors(edge, *_mesh, TopAbs_FACE);
1009 while ( fIt->more())
1011 const TopoDS_Shape* f = fIt->next();
1012 if ( helper.IsSubShape( *f, _sdVec[i]._solid))
1013 FF[ int( !FF[0].IsNull()) ] = *f;
1015 if( FF[1].IsNull() ) continue; // seam edge can be shared by 1 FACE only
1016 // check presence of layers on them
1018 for ( int j = 0; j < 2; ++j )
1019 ignore[j] = _ignoreShapeIds.count ( getMeshDS()->ShapeToIndex( FF[j] ));
1020 if ( ignore[0] == ignore[1] ) continue; // nothing interesting
1021 TopoDS_Shape fWOL = FF[ ignore[0] ? 0 : 1 ];
1023 TGeomID edgeInd = getMeshDS()->ShapeToIndex( edge );
1024 _sdVec[i]._shrinkShape2Shape.insert( make_pair( edgeInd, fWOL ));
1027 // Exclude from _shrinkShape2Shape FACE's that can't be shrinked since
1028 // the algo of the SOLID sharing the FACE does not support it
1029 set< string > notSupportAlgos; notSupportAlgos.insert("Hexa_3D");
1030 for ( unsigned i = 0; i < _sdVec.size(); ++i )
1032 TopTools_MapOfShape noShrinkVertices;
1033 map< TGeomID, TopoDS_Shape >::iterator e2f = _sdVec[i]._shrinkShape2Shape.begin();
1034 for ( ; e2f != _sdVec[i]._shrinkShape2Shape.end(); ++e2f )
1036 const TopoDS_Shape& fWOL = e2f->second;
1037 TGeomID edgeID = e2f->first;
1038 bool notShrinkFace = false;
1039 PShapeIteratorPtr soIt = helper.GetAncestors(fWOL, *_mesh, TopAbs_SOLID);
1040 while ( soIt->more())
1042 const TopoDS_Shape* solid = soIt->next();
1043 if ( _sdVec[i]._solid.IsSame( *solid )) continue;
1044 SMESH_Algo* algo = _mesh->GetGen()->GetAlgo( *_mesh, *solid );
1045 if ( !algo || !notSupportAlgos.count( algo->GetName() )) continue;
1046 notShrinkFace = true;
1047 for ( unsigned j = 0; j < _sdVec.size(); ++j )
1049 if ( _sdVec[j]._solid.IsSame( *solid ) )
1050 if ( _sdVec[j]._shrinkShape2Shape.count( edgeID ))
1051 notShrinkFace = false;
1054 if ( notShrinkFace )
1056 _sdVec[i]._noShrinkFaces.insert( getMeshDS()->ShapeToIndex( fWOL ));
1057 for ( TopExp_Explorer vExp( fWOL, TopAbs_VERTEX ); vExp.More(); vExp.Next() )
1058 noShrinkVertices.Add( vExp.Current() );
1061 // erase from _shrinkShape2Shape all srink EDGE's of a SOLID connected
1062 // to the found not shrinked fWOL's
1063 e2f = _sdVec[i]._shrinkShape2Shape.begin();
1064 for ( ; e2f != _sdVec[i]._shrinkShape2Shape.end(); )
1066 TGeomID edgeID = e2f->first;
1067 TopoDS_Vertex VV[2];
1068 TopExp::Vertices( TopoDS::Edge( getMeshDS()->IndexToShape( edgeID )),VV[0],VV[1]);
1069 if ( noShrinkVertices.Contains( VV[0] ) || noShrinkVertices.Contains( VV[1] ))
1070 _sdVec[i]._shrinkShape2Shape.erase( e2f++ );
1076 // Find the SHAPE along which to inflate _LayerEdge based on VERTEX
1078 for ( unsigned i = 0; i < _sdVec.size(); ++i )
1081 TopExp::MapShapes(_sdVec[i]._solid, TopAbs_VERTEX, shapes);
1082 for ( int iV = 1; iV <= shapes.Extent(); ++iV )
1084 const TopoDS_Shape& vertex = shapes(iV);
1085 // find faces WOL sharing the vertex
1086 vector< TopoDS_Shape > facesWOL;
1087 int totalNbFaces = 0;
1088 PShapeIteratorPtr fIt = helper.GetAncestors(vertex, *_mesh, TopAbs_FACE);
1089 while ( fIt->more())
1091 const TopoDS_Shape* f = fIt->next();
1092 const int fID = getMeshDS()->ShapeToIndex( *f );
1093 if ( helper.IsSubShape( *f, _sdVec[i]._solid ) )
1096 if ( _ignoreShapeIds.count ( fID ) && ! _sdVec[i]._noShrinkFaces.count( fID ))
1097 facesWOL.push_back( *f );
1100 if ( facesWOL.size() == totalNbFaces || facesWOL.empty() )
1101 continue; // no layers at this vertex or no WOL
1102 TGeomID vInd = getMeshDS()->ShapeToIndex( vertex );
1103 switch ( facesWOL.size() )
1107 _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, facesWOL[0] )); break;
1111 // find an edge shared by 2 faces
1112 PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
1113 while ( eIt->more())
1115 const TopoDS_Shape* e = eIt->next();
1116 if ( helper.IsSubShape( *e, facesWOL[0]) &&
1117 helper.IsSubShape( *e, facesWOL[1]))
1119 _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, *e )); break;
1125 return error("Not yet supported case", _sdVec[i]._index);
1133 //================================================================================
1135 * \brief Create the inner surface of the viscous layer and prepare data for infation
1137 //================================================================================
1139 bool _ViscousBuilder::makeLayer(_SolidData& data)
1141 // get all sub-shapes to make layers on
1142 set<TGeomID> subIds, faceIds;
1143 subIds = data._noShrinkFaces;
1144 TopExp_Explorer exp( data._solid, TopAbs_FACE );
1145 for ( ; exp.More(); exp.Next() )
1146 if ( ! _ignoreShapeIds.count( getMeshDS()->ShapeToIndex( exp.Current() )))
1148 SMESH_subMesh* fSubM = _mesh->GetSubMesh( exp.Current() );
1149 faceIds.insert( fSubM->GetId() );
1150 SMESH_subMeshIteratorPtr subIt =
1151 fSubM->getDependsOnIterator(/*includeSelf=*/true, /*complexShapeFirst=*/false);
1152 while ( subIt->more() )
1153 subIds.insert( subIt->next()->GetId() );
1156 // make a map to find new nodes on sub-shapes shared with other SOLID
1157 map< TGeomID, TNode2Edge* > s2neMap;
1158 map< TGeomID, TNode2Edge* >::iterator s2ne;
1159 map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
1160 for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
1162 TGeomID shapeInd = s2s->first;
1163 for ( unsigned i = 0; i < _sdVec.size(); ++i )
1165 if ( _sdVec[i]._index == data._index ) continue;
1166 map< TGeomID, TopoDS_Shape >::iterator s2s2 = _sdVec[i]._shrinkShape2Shape.find( shapeInd );
1167 if ( s2s2 != _sdVec[i]._shrinkShape2Shape.end() &&
1168 *s2s == *s2s2 && !_sdVec[i]._n2eMap.empty() )
1170 s2neMap.insert( make_pair( shapeInd, &_sdVec[i]._n2eMap ));
1176 // Create temporary faces and _LayerEdge's
1178 dumpFunction(SMESH_Comment("makeLayers_")<<data._index);
1180 data._stepSize = Precision::Infinite();
1181 data._stepSizeNodes[0] = 0;
1183 SMESH_MesherHelper helper( *_mesh );
1184 helper.SetSubShape( data._solid );
1185 helper.SetElementsOnShape(true);
1187 vector< const SMDS_MeshNode*> newNodes; // of a mesh face
1188 TNode2Edge::iterator n2e2;
1190 // collect _LayerEdge's of shapes they are based on
1191 const int nbShapes = getMeshDS()->MaxShapeIndex();
1192 vector< vector<_LayerEdge*> > edgesByGeom( nbShapes+1 );
1194 for ( set<TGeomID>::iterator id = faceIds.begin(); id != faceIds.end(); ++id )
1196 SMESHDS_SubMesh* smDS = getMeshDS()->MeshElements( *id );
1197 if ( !smDS ) return error(SMESH_Comment("Not meshed face ") << *id, data._index );
1199 const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( *id ));
1200 SMESH_ProxyMesh::SubMesh* proxySub =
1201 data._proxyMesh->getFaceSubM( F, /*create=*/true);
1203 SMDS_ElemIteratorPtr eIt = smDS->GetElements();
1204 while ( eIt->more() )
1206 const SMDS_MeshElement* face = eIt->next();
1207 newNodes.resize( face->NbCornerNodes() );
1208 double faceMaxCosin = -1;
1209 for ( int i = 0 ; i < face->NbCornerNodes(); ++i )
1211 const SMDS_MeshNode* n = face->GetNode(i);
1212 TNode2Edge::iterator n2e = data._n2eMap.insert( make_pair( n, (_LayerEdge*)0 )).first;
1213 if ( !(*n2e).second )
1216 _LayerEdge* edge = new _LayerEdge();
1218 edge->_nodes.push_back( n );
1219 const int shapeID = n->getshapeId();
1220 edgesByGeom[ shapeID ].push_back( edge );
1222 // set edge data or find already refined _LayerEdge and get data from it
1223 if ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE &&
1224 ( s2ne = s2neMap.find( shapeID )) != s2neMap.end() &&
1225 ( n2e2 = (*s2ne).second->find( n )) != s2ne->second->end())
1227 _LayerEdge* foundEdge = (*n2e2).second;
1228 edge->Copy( *foundEdge, helper );
1229 // location of the last node is modified but we can restore
1230 // it by node position on _sWOL stored by the node
1231 const_cast< SMDS_MeshNode* >
1232 ( edge->_nodes.back() )->setXYZ( n->X(), n->Y(), n->Z() );
1236 edge->_nodes.push_back( helper.AddNode( n->X(), n->Y(), n->Z() ));
1237 if ( !setEdgeData( *edge, subIds, helper, data ))
1240 dumpMove(edge->_nodes.back());
1241 if ( edge->_cosin > 0.01 )
1243 if ( edge->_cosin > faceMaxCosin )
1244 faceMaxCosin = edge->_cosin;
1247 newNodes[ i ] = n2e->second->_nodes.back();
1249 // create a temporary face
1250 const SMDS_MeshElement* newFace = new TmpMeshFace( newNodes, --_tmpFaceID );
1251 proxySub->AddElement( newFace );
1253 // compute inflation step size by min size of element on a convex surface
1254 if ( faceMaxCosin > 0.1 )
1255 limitStepSize( data, face, faceMaxCosin );
1256 } // loop on 2D elements on a FACE
1257 } // loop on FACEs of a SOLID
1259 data._epsilon = 1e-7;
1260 if ( data._stepSize < 1. )
1261 data._epsilon *= data._stepSize;
1263 // Put _LayerEdge's into a vector
1265 if ( !sortEdges( data, edgesByGeom ))
1268 // Set target nodes into _Simplex and _2NearEdges
1269 TNode2Edge::iterator n2e;
1270 for ( unsigned i = 0; i < data._edges.size(); ++i )
1272 if ( data._edges[i]->IsOnEdge())
1273 for ( int j = 0; j < 2; ++j )
1275 if ( data._edges[i]->_nodes.back()->NbInverseElements(SMDSAbs_Volume) > 0 )
1276 break; // _LayerEdge is shared by two _SolidData's
1277 const SMDS_MeshNode* & n = data._edges[i]->_2neibors->_nodes[j];
1278 if (( n2e = data._n2eMap.find( n )) == data._n2eMap.end() )
1279 return error("_LayerEdge not found by src node", data._index);
1280 n = (*n2e).second->_nodes.back();
1281 data._edges[i]->_2neibors->_edges[j] = n2e->second;
1284 for ( unsigned j = 0; j < data._edges[i]->_simplices.size(); ++j )
1286 _Simplex& s = data._edges[i]->_simplices[j];
1287 s._nNext = data._n2eMap[ s._nNext ]->_nodes.back();
1288 s._nPrev = data._n2eMap[ s._nPrev ]->_nodes.back();
1296 //================================================================================
1298 * \brief Compute inflation step size by min size of element on a convex surface
1300 //================================================================================
1302 void _ViscousBuilder::limitStepSize( _SolidData& data,
1303 const SMDS_MeshElement* face,
1307 double minSize = 10 * data._stepSize;
1308 const int nbNodes = face->NbCornerNodes();
1309 for ( int i = 0; i < nbNodes; ++i )
1311 const SMDS_MeshNode* nextN = face->GetNode( SMESH_MesherHelper::WrapIndex( i+1, nbNodes ));
1312 const SMDS_MeshNode* curN = face->GetNode( i );
1313 if ( nextN->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE ||
1314 curN->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE )
1316 double dist = SMESH_TNodeXYZ( face->GetNode(i)).Distance( nextN );
1317 if ( dist < minSize )
1318 minSize = dist, iN = i;
1321 double newStep = 0.8 * minSize / cosin;
1322 if ( newStep < data._stepSize )
1324 data._stepSize = newStep;
1325 data._stepSizeCoeff = 0.8 / cosin;
1326 data._stepSizeNodes[0] = face->GetNode( iN );
1327 data._stepSizeNodes[1] = face->GetNode( SMESH_MesherHelper::WrapIndex( iN+1, nbNodes ));
1331 //================================================================================
1333 * \brief Compute inflation step size by min size of element on a convex surface
1335 //================================================================================
1337 void _ViscousBuilder::limitStepSize( _SolidData& data, const double minSize)
1339 if ( minSize < data._stepSize )
1341 data._stepSize = minSize;
1342 if ( data._stepSizeNodes[0] )
1345 SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
1346 data._stepSizeCoeff = data._stepSize / dist;
1351 //================================================================================
1353 * \brief Separate shapes (and _LayerEdge's on them) to smooth from the rest ones
1355 //================================================================================
1357 bool _ViscousBuilder::sortEdges( _SolidData& data,
1358 vector< vector<_LayerEdge*> >& edgesByGeom)
1360 // Find shapes needing smoothing; such a shape has _LayerEdge._normal on it's
1361 // boundry inclined at a sharp angle to the shape
1363 list< TGeomID > shapesToSmooth;
1365 SMESH_MesherHelper helper( *_mesh );
1368 for ( unsigned iS = 0; iS < edgesByGeom.size(); ++iS )
1370 vector<_LayerEdge*>& eS = edgesByGeom[iS];
1371 if ( eS.empty() ) continue;
1372 TopoDS_Shape S = getMeshDS()->IndexToShape( iS );
1373 bool needSmooth = false;
1374 switch ( S.ShapeType() )
1378 bool isShrinkEdge = !eS[0]->_sWOL.IsNull();
1379 for ( TopoDS_Iterator vIt( S ); vIt.More() && !needSmooth; vIt.Next() )
1381 TGeomID iV = getMeshDS()->ShapeToIndex( vIt.Value() );
1382 vector<_LayerEdge*>& eV = edgesByGeom[ iV ];
1383 if ( eV.empty() ) continue;
1384 double cosin = eV[0]->_cosin;
1386 ( !eV[0]->_sWOL.IsNull() && ( eV[0]->_sWOL.ShapeType() == TopAbs_EDGE || !isShrinkEdge));
1390 if ( eV[0]->_sWOL.ShapeType() == TopAbs_EDGE )
1391 dir1 = getEdgeDir( TopoDS::Edge( eV[0]->_sWOL ), TopoDS::Vertex( vIt.Value() ));
1393 dir1 = getFaceDir( TopoDS::Face( eV[0]->_sWOL ), TopoDS::Vertex( vIt.Value() ),
1394 eV[0]->_nodes[0], helper, ok);
1395 dir2 = getEdgeDir( TopoDS::Edge( S ), TopoDS::Vertex( vIt.Value() ));
1396 double angle = dir1.Angle( dir2 );
1397 cosin = cos( angle );
1399 needSmooth = ( cosin > 0.1 );
1405 for ( TopExp_Explorer eExp( S, TopAbs_EDGE ); eExp.More() && !needSmooth; eExp.Next() )
1407 TGeomID iE = getMeshDS()->ShapeToIndex( eExp.Current() );
1408 vector<_LayerEdge*>& eE = edgesByGeom[ iE ];
1409 if ( eE.empty() ) continue;
1410 if ( eE[0]->_sWOL.IsNull() )
1412 for ( unsigned i = 0; i < eE.size() && !needSmooth; ++i )
1413 needSmooth = ( eE[i]->_cosin > 0.1 );
1417 const TopoDS_Face& F1 = TopoDS::Face( S );
1418 const TopoDS_Face& F2 = TopoDS::Face( eE[0]->_sWOL );
1419 const TopoDS_Edge& E = TopoDS::Edge( eExp.Current() );
1420 for ( unsigned i = 0; i < eE.size() && !needSmooth; ++i )
1422 gp_Vec dir1 = getFaceDir( F1, E, eE[i]->_nodes[0], helper, ok );
1423 gp_Vec dir2 = getFaceDir( F2, E, eE[i]->_nodes[0], helper, ok );
1424 double angle = dir1.Angle( dir2 );
1425 double cosin = cos( angle );
1426 needSmooth = ( cosin > 0.1 );
1438 if ( S.ShapeType() == TopAbs_EDGE ) shapesToSmooth.push_front( iS );
1439 else shapesToSmooth.push_back ( iS );
1442 } // loop on edgesByGeom
1444 data._edges.reserve( data._n2eMap.size() );
1445 data._endEdgeToSmooth.clear();
1447 // first we put _LayerEdge's on shapes to smooth
1448 list< TGeomID >::iterator gIt = shapesToSmooth.begin();
1449 for ( ; gIt != shapesToSmooth.end(); ++gIt )
1451 vector<_LayerEdge*>& eVec = edgesByGeom[ *gIt ];
1452 if ( eVec.empty() ) continue;
1453 data._edges.insert( data._edges.end(), eVec.begin(), eVec.end() );
1454 data._endEdgeToSmooth.push_back( data._edges.size() );
1458 // then the rest _LayerEdge's
1459 for ( unsigned iS = 0; iS < edgesByGeom.size(); ++iS )
1461 vector<_LayerEdge*>& eVec = edgesByGeom[iS];
1462 data._edges.insert( data._edges.end(), eVec.begin(), eVec.end() );
1469 //================================================================================
1471 * \brief Set data of _LayerEdge needed for smoothing
1472 * \param subIds - ids of sub-shapes of a SOLID to take into account faces from
1474 //================================================================================
1476 bool _ViscousBuilder::setEdgeData(_LayerEdge& edge,
1477 const set<TGeomID>& subIds,
1478 SMESH_MesherHelper& helper,
1481 SMESH_MeshEditor editor(_mesh);
1483 const SMDS_MeshNode* node = edge._nodes[0]; // source node
1484 SMDS_TypeOfPosition posType = node->GetPosition()->GetTypeOfPosition();
1488 edge._curvature = 0;
1490 // --------------------------
1491 // Compute _normal and _cosin
1492 // --------------------------
1495 edge._normal.SetCoord(0,0,0);
1497 int totalNbFaces = 0;
1499 gp_Vec du, dv, geomNorm;
1502 TGeomID shapeInd = node->getshapeId();
1503 map< TGeomID, TopoDS_Shape >::const_iterator s2s = data._shrinkShape2Shape.find( shapeInd );
1504 bool onShrinkShape ( s2s != data._shrinkShape2Shape.end() );
1505 TopoDS_Shape vertEdge;
1507 if ( onShrinkShape ) // one of faces the node is on has no layers
1509 vertEdge = getMeshDS()->IndexToShape( s2s->first ); // vertex or edge
1510 if ( s2s->second.ShapeType() == TopAbs_EDGE )
1512 // inflate from VERTEX along EDGE
1513 edge._normal = getEdgeDir( TopoDS::Edge( s2s->second ), TopoDS::Vertex( vertEdge ));
1515 else if ( vertEdge.ShapeType() == TopAbs_VERTEX )
1517 // inflate from VERTEX along FACE
1518 edge._normal = getFaceDir( TopoDS::Face( s2s->second ), TopoDS::Vertex( vertEdge ),
1519 node, helper, normOK, &edge._cosin);
1523 // inflate from EDGE along FACE
1524 edge._normal = getFaceDir( TopoDS::Face( s2s->second ), TopoDS::Edge( vertEdge ),
1525 node, helper, normOK);
1528 else // layers are on all faces of SOLID the node is on
1530 // find indices of geom faces the node lies on
1531 set<TGeomID> faceIds;
1532 if ( posType == SMDS_TOP_FACE )
1534 faceIds.insert( node->getshapeId() );
1538 SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
1539 while ( fIt->more() )
1540 faceIds.insert( editor.FindShape(fIt->next()));
1543 set<TGeomID>::iterator id = faceIds.begin();
1545 for ( ; id != faceIds.end(); ++id )
1547 const TopoDS_Shape& s = getMeshDS()->IndexToShape( *id );
1548 if ( s.IsNull() || s.ShapeType() != TopAbs_FACE || !subIds.count( *id ))
1551 //nbLayerFaces += subIds.count( *id );
1552 F = TopoDS::Face( s );
1554 gp_XY uv = helper.GetNodeUV( F, node, 0, &normOK );
1555 Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
1556 surface->D1( uv.X(),uv.Y(), p, du,dv );
1558 double size2 = geomNorm.SquareMagnitude();
1559 if ( size2 > numeric_limits<double>::min() )
1560 geomNorm /= sqrt( size2 );
1563 if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
1565 edge._normal += geomNorm.XYZ();
1567 if ( totalNbFaces == 0 )
1568 return error(SMESH_Comment("Can't get normal to node ") << node->GetID(), data._index);
1570 edge._normal /= totalNbFaces;
1575 edge._cosin = 0; break;
1577 case SMDS_TOP_EDGE: {
1578 TopoDS_Edge E = TopoDS::Edge( helper.GetSubShapeByNode( node, getMeshDS()));
1579 gp_Vec inFaceDir = getFaceDir( F, E, node, helper, normOK);
1580 double angle = inFaceDir.Angle( edge._normal ); // [0,PI]
1581 edge._cosin = cos( angle );
1582 //cout << "Cosin on EDGE " << edge._cosin << " node " << node->GetID() << endl;
1585 case SMDS_TOP_VERTEX: {
1586 TopoDS_Vertex V = TopoDS::Vertex( helper.GetSubShapeByNode( node, getMeshDS()));
1587 gp_Vec inFaceDir = getFaceDir( F, V, node, helper, normOK);
1588 double angle = inFaceDir.Angle( edge._normal ); // [0,PI]
1589 edge._cosin = cos( angle );
1590 //cout << "Cosin on VERTEX " << edge._cosin << " node " << node->GetID() << endl;
1594 return error(SMESH_Comment("Invalid shape position of node ")<<node, data._index);
1598 double normSize = edge._normal.SquareModulus();
1599 if ( normSize < numeric_limits<double>::min() )
1600 return error(SMESH_Comment("Bad normal at node ")<< node->GetID(), data._index );
1602 edge._normal /= sqrt( normSize );
1604 // TODO: if ( !normOK ) then get normal by mesh faces
1606 // Set the rest data
1607 // --------------------
1608 if ( onShrinkShape )
1610 edge._sWOL = (*s2s).second;
1612 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edge._nodes.back() );
1613 if ( SMESHDS_SubMesh* sm = getMeshDS()->MeshElements( data._solid ))
1614 sm->RemoveNode( tgtNode , /*isNodeDeleted=*/false );
1616 // set initial position which is parameters on _sWOL in this case
1617 if ( edge._sWOL.ShapeType() == TopAbs_EDGE )
1619 double u = helper.GetNodeU( TopoDS::Edge( edge._sWOL ), node, 0, &normOK );
1620 edge._pos.push_back( gp_XYZ( u, 0, 0));
1621 getMeshDS()->SetNodeOnEdge( tgtNode, TopoDS::Edge( edge._sWOL ), u );
1625 gp_XY uv = helper.GetNodeUV( TopoDS::Face( edge._sWOL ), node, 0, &normOK );
1626 edge._pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
1627 getMeshDS()->SetNodeOnFace( tgtNode, TopoDS::Face( edge._sWOL ), uv.X(), uv.Y() );
1632 edge._pos.push_back( SMESH_TNodeXYZ( node ));
1634 if ( posType == SMDS_TOP_FACE )
1636 getSimplices( node, edge._simplices, _ignoreShapeIds, &data );
1637 double avgNormProj = 0, avgLen = 0;
1638 for ( unsigned i = 0; i < edge._simplices.size(); ++i )
1640 gp_XYZ vec = edge._pos.back() - SMESH_TNodeXYZ( edge._simplices[i]._nPrev );
1641 avgNormProj += edge._normal * vec;
1642 avgLen += vec.Modulus();
1644 avgNormProj /= edge._simplices.size();
1645 avgLen /= edge._simplices.size();
1646 edge._curvature = _Curvature::New( avgNormProj, avgLen );
1650 // Set neighbour nodes for a _LayerEdge based on EDGE
1652 if ( posType == SMDS_TOP_EDGE /*||
1653 ( onShrinkShape && posType == SMDS_TOP_VERTEX && fabs( edge._cosin ) < 1e-10 )*/)
1655 edge._2neibors = new _2NearEdges;
1656 // target node instead of source ones will be set later
1657 if ( ! findNeiborsOnEdge( &edge,
1658 edge._2neibors->_nodes[0],
1659 edge._2neibors->_nodes[1],
1662 edge.SetDataByNeighbors( edge._2neibors->_nodes[0],
1663 edge._2neibors->_nodes[1],
1667 edge.SetCosin( edge._cosin ); // to update edge._lenFactor
1672 //================================================================================
1674 * \brief Find 2 neigbor nodes of a node on EDGE
1676 //================================================================================
1678 bool _ViscousBuilder::findNeiborsOnEdge(const _LayerEdge* edge,
1679 const SMDS_MeshNode*& n1,
1680 const SMDS_MeshNode*& n2,
1683 const SMDS_MeshNode* node = edge->_nodes[0];
1684 const int shapeInd = node->getshapeId();
1685 SMESHDS_SubMesh* edgeSM = 0;
1686 if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_EDGE )
1689 edgeSM = getMeshDS()->MeshElements( shapeInd );
1690 if ( !edgeSM || edgeSM->NbElements() == 0 )
1691 return error(SMESH_Comment("Not meshed EDGE ") << shapeInd, data._index);
1695 SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator(SMDSAbs_Edge);
1696 while ( eIt->more() && !n2 )
1698 const SMDS_MeshElement* e = eIt->next();
1699 const SMDS_MeshNode* nNeibor = e->GetNode( 0 );
1700 if ( nNeibor == node ) nNeibor = e->GetNode( 1 );
1703 if (!edgeSM->Contains(e)) continue;
1707 TopoDS_Shape s = SMESH_MesherHelper::GetSubShapeByNode(nNeibor, getMeshDS() );
1708 if ( !SMESH_MesherHelper::IsSubShape( s, edge->_sWOL )) continue;
1710 ( iN++ ? n2 : n1 ) = nNeibor;
1713 return error(SMESH_Comment("Wrongly meshed EDGE ") << shapeInd, data._index);
1717 //================================================================================
1719 * \brief Set _curvature and _2neibors->_plnNorm by 2 neigbor nodes residing the same EDGE
1721 //================================================================================
1723 void _LayerEdge::SetDataByNeighbors( const SMDS_MeshNode* n1,
1724 const SMDS_MeshNode* n2,
1725 SMESH_MesherHelper& helper)
1727 if ( _nodes[0]->GetPosition()->GetTypeOfPosition() != SMDS_TOP_EDGE )
1730 gp_XYZ pos = SMESH_TNodeXYZ( _nodes[0] );
1731 gp_XYZ vec1 = pos - SMESH_TNodeXYZ( n1 );
1732 gp_XYZ vec2 = pos - SMESH_TNodeXYZ( n2 );
1736 double sumLen = vec1.Modulus() + vec2.Modulus();
1737 _2neibors->_wgt[0] = 1 - vec1.Modulus() / sumLen;
1738 _2neibors->_wgt[1] = 1 - vec2.Modulus() / sumLen;
1739 double avgNormProj = 0.5 * ( _normal * vec1 + _normal * vec2 );
1740 double avgLen = 0.5 * ( vec1.Modulus() + vec2.Modulus() );
1741 if ( _curvature ) delete _curvature;
1742 _curvature = _Curvature::New( avgNormProj, avgLen );
1744 // if ( _curvature )
1745 // cout << _nodes[0]->GetID()
1746 // << " CURV r,k: " << _curvature->_r<<","<<_curvature->_k
1747 // << " proj = "<<avgNormProj<< " len = " << avgLen << "| lenDelta(0) = "
1748 // << _curvature->lenDelta(0) << endl;
1753 if ( _sWOL.IsNull() )
1755 TopoDS_Shape S = helper.GetSubShapeByNode( _nodes[0], helper.GetMeshDS() );
1756 gp_XYZ dirE = getEdgeDir( TopoDS::Edge( S ), _nodes[0], helper );
1757 gp_XYZ plnNorm = dirE ^ _normal;
1758 double proj0 = plnNorm * vec1;
1759 double proj1 = plnNorm * vec2;
1760 if ( fabs( proj0 ) > 1e-10 || fabs( proj1 ) > 1e-10 )
1762 if ( _2neibors->_plnNorm ) delete _2neibors->_plnNorm;
1763 _2neibors->_plnNorm = new gp_XYZ( plnNorm.Normalized() );
1768 //================================================================================
1770 * \brief Copy data from a _LayerEdge of other SOLID and based on the same node;
1771 * this and other _LayerEdge's are inflated along a FACE or an EDGE
1773 //================================================================================
1775 void _LayerEdge::Copy( _LayerEdge& other, SMESH_MesherHelper& helper )
1777 _nodes = other._nodes;
1778 _normal = other._normal;
1780 _lenFactor = other._lenFactor;
1781 _cosin = other._cosin;
1782 _sWOL = other._sWOL;
1783 _2neibors = other._2neibors;
1784 _curvature = 0; std::swap( _curvature, other._curvature );
1785 _2neibors = 0; std::swap( _2neibors, other._2neibors );
1787 if ( _sWOL.ShapeType() == TopAbs_EDGE )
1789 double u = helper.GetNodeU( TopoDS::Edge( _sWOL ), _nodes[0] );
1790 _pos.push_back( gp_XYZ( u, 0, 0));
1794 gp_XY uv = helper.GetNodeUV( TopoDS::Face( _sWOL ), _nodes[0]);
1795 _pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
1799 //================================================================================
1801 * \brief Set _cosin and _lenFactor
1803 //================================================================================
1805 void _LayerEdge::SetCosin( double cosin )
1808 _lenFactor = ( _cosin > 0.1 ) ? 1./sqrt(1-_cosin*_cosin) : 1.0;
1811 //================================================================================
1813 * \brief Fills a vector<_Simplex >
1815 //================================================================================
1817 void _ViscousBuilder::getSimplices( const SMDS_MeshNode* node,
1818 vector<_Simplex>& simplices,
1819 const set<TGeomID>& ingnoreShapes,
1820 const _SolidData* dataToCheckOri)
1822 SMESH_MeshEditor editor( _mesh );
1823 SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
1824 while ( fIt->more() )
1826 const SMDS_MeshElement* f = fIt->next();
1827 const TGeomID shapeInd = editor.FindShape( f );
1828 if ( ingnoreShapes.count( shapeInd )) continue;
1829 const int nbNodes = f->NbCornerNodes();
1830 int srcInd = f->GetNodeIndex( node );
1831 const SMDS_MeshNode* nPrev = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd-1, nbNodes ));
1832 const SMDS_MeshNode* nNext = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+1, nbNodes ));
1833 if ( dataToCheckOri && dataToCheckOri->_reversedFaceIds.count( shapeInd ))
1834 std::swap( nPrev, nNext );
1835 simplices.push_back( _Simplex( nPrev, nNext ));
1837 simplices.resize( simplices.size() );
1840 //================================================================================
1842 * \brief DEBUG. Create groups contating temorary data of _LayerEdge's
1844 //================================================================================
1846 void _ViscousBuilder::makeGroupOfLE()
1849 for ( unsigned i = 0 ; i < _sdVec.size(); ++i )
1851 if ( _sdVec[i]._edges.empty() ) continue;
1852 // string name = SMESH_Comment("_LayerEdge's_") << i;
1854 // SMESH_Group* g = _mesh->AddGroup(SMDSAbs_Edge, name.c_str(), id );
1855 // SMESHDS_Group* gDS = (SMESHDS_Group*)g->GetGroupDS();
1856 // SMESHDS_Mesh* mDS = _mesh->GetMeshDS();
1858 dumpFunction( SMESH_Comment("make_LayerEdge_") << i );
1859 for ( unsigned j = 0 ; j < _sdVec[i]._edges.size(); ++j )
1861 _LayerEdge* le = _sdVec[i]._edges[j];
1862 for ( unsigned iN = 1; iN < le->_nodes.size(); ++iN )
1863 dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<le->_nodes[iN-1]->GetID()
1864 << ", " << le->_nodes[iN]->GetID() <<"])");
1865 //gDS->SMDSGroup().Add( mDS->AddEdge( le->_nodes[iN-1], le->_nodes[iN]));
1869 dumpFunction( SMESH_Comment("makeNormals") << i );
1870 for ( unsigned j = 0 ; j < _sdVec[i]._edges.size(); ++j )
1872 _LayerEdge& edge = *_sdVec[i]._edges[j];
1873 SMESH_TNodeXYZ nXYZ( edge._nodes[0] );
1874 nXYZ += edge._normal * _sdVec[i]._stepSize;
1875 dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<edge._nodes[0]->GetID()
1876 << ", mesh.AddNode( " << nXYZ.X()<<","<< nXYZ.Y()<<","<< nXYZ.Z()<<")])");
1880 // name = SMESH_Comment("tmp_faces ") << i;
1881 // g = _mesh->AddGroup(SMDSAbs_Face, name.c_str(), id );
1882 // gDS = (SMESHDS_Group*)g->GetGroupDS();
1883 // SMESH_MeshEditor editor( _mesh );
1884 dumpFunction( SMESH_Comment("makeTmpFaces_") << i );
1885 TopExp_Explorer fExp( _sdVec[i]._solid, TopAbs_FACE );
1886 for ( ; fExp.More(); fExp.Next() )
1888 if (const SMESHDS_SubMesh* sm = _sdVec[i]._proxyMesh->GetProxySubMesh( fExp.Current()))
1890 SMDS_ElemIteratorPtr fIt = sm->GetElements();
1891 while ( fIt->more())
1893 const SMDS_MeshElement* e = fIt->next();
1894 SMESH_Comment cmd("mesh.AddFace([");
1895 for ( int j=0; j < e->NbCornerNodes(); ++j )
1896 cmd << e->GetNode(j)->GetID() << (j+1<e->NbCornerNodes() ? ",": "])");
1898 //vector<const SMDS_MeshNode*> nodes( e->begin_nodes(), e->end_nodes() );
1899 //gDS->SMDSGroup().Add( editor.AddElement( nodes, e->GetType(), e->IsPoly()));
1908 //================================================================================
1910 * \brief Increase length of _LayerEdge's to reach the required thickness of layers
1912 //================================================================================
1914 bool _ViscousBuilder::inflate(_SolidData& data)
1916 SMESH_MesherHelper helper( *_mesh );
1918 // Limit inflation step size by geometry size found by itersecting
1919 // normals of _LayerEdge's with mesh faces
1920 double geomSize = Precision::Infinite(), intersecDist;
1921 SMESH_MeshEditor editor( _mesh );
1922 auto_ptr<SMESH_ElementSearcher> searcher
1923 ( editor.GetElementSearcher( data._proxyMesh->GetFaces( data._solid )) );
1924 for ( unsigned i = 0; i < data._edges.size(); ++i )
1926 if ( data._edges[i]->IsOnEdge() ) continue;
1927 data._edges[i]->FindIntersection( *searcher, intersecDist, data._epsilon );
1928 if ( geomSize > intersecDist )
1929 geomSize = intersecDist;
1931 if ( data._stepSize > 0.3 * geomSize )
1932 limitStepSize( data, 0.3 * geomSize );
1934 const double tgtThick = data._hyp->GetTotalThickness();
1935 if ( data._stepSize > tgtThick )
1936 limitStepSize( data, tgtThick );
1938 if ( data._stepSize < 1. )
1939 data._epsilon = data._stepSize * 1e-7;
1942 cout << "-- geomSize = " << geomSize << ", stepSize = " << data._stepSize << endl;
1945 double avgThick = 0, curThick = 0, distToIntersection = Precision::Infinite();
1946 int nbSteps = 0, nbRepeats = 0;
1947 while ( 1.01 * avgThick < tgtThick )
1949 // new target length
1950 curThick += data._stepSize;
1951 if ( curThick > tgtThick )
1953 curThick = tgtThick + ( tgtThick-avgThick ) * nbRepeats;
1957 // Elongate _LayerEdge's
1958 dumpFunction(SMESH_Comment("inflate")<<data._index<<"_step"<<nbSteps); // debug
1959 for ( unsigned i = 0; i < data._edges.size(); ++i )
1961 data._edges[i]->SetNewLength( curThick, helper );
1966 if ( !updateNormals( data, helper ) )
1969 // Improve and check quality
1970 if ( !smoothAndCheck( data, nbSteps, distToIntersection ))
1974 dumpFunction(SMESH_Comment("invalidate")<<data._index<<"_step"<<nbSteps); // debug
1975 for ( unsigned i = 0; i < data._edges.size(); ++i )
1977 data._edges[i]->InvalidateStep( nbSteps+1 );
1981 break; // no more inflating possible
1985 // Evaluate achieved thickness
1987 for ( unsigned i = 0; i < data._edges.size(); ++i )
1988 avgThick += data._edges[i]->_len;
1989 avgThick /= data._edges.size();
1991 cout << "-- Thickness " << avgThick << " reached" << endl;
1994 if ( distToIntersection < avgThick*1.5 )
1997 cout << "-- Stop inflation since distToIntersection( "<<distToIntersection<<" ) < avgThick( "
1998 << avgThick << " ) * 1.5" << endl;
2003 limitStepSize( data, 0.25 * distToIntersection );
2004 if ( data._stepSizeNodes[0] )
2005 data._stepSize = data._stepSizeCoeff *
2006 SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
2010 return error("failed at the very first inflation step", data._index);
2015 //================================================================================
2017 * \brief Improve quality of layer inner surface and check intersection
2019 //================================================================================
2021 bool _ViscousBuilder::smoothAndCheck(_SolidData& data,
2023 double & distToIntersection)
2025 if ( data._endEdgeToSmooth.empty() )
2026 return true; // no shapes needing smoothing
2028 bool moved, improved;
2030 SMESH_MesherHelper helper(*_mesh);
2031 Handle(Geom_Surface) surface;
2035 for ( unsigned iS = 0; iS < data._endEdgeToSmooth.size(); ++iS )
2038 iEnd = data._endEdgeToSmooth[ iS ];
2040 if ( !data._edges[ iBeg ]->_sWOL.IsNull() &&
2041 data._edges[ iBeg ]->_sWOL.ShapeType() == TopAbs_FACE )
2043 if ( !F.IsSame( data._edges[ iBeg ]->_sWOL )) {
2044 F = TopoDS::Face( data._edges[ iBeg ]->_sWOL );
2045 helper.SetSubShape( F );
2046 surface = BRep_Tool::Surface( F );
2051 F.Nullify(); surface.Nullify();
2053 TGeomID sInd = data._edges[ iBeg ]->_nodes[0]->getshapeId();
2055 if ( data._edges[ iBeg ]->IsOnEdge() )
2056 { // try a simple solution on an analytic EDGE
2057 if ( !smoothAnalyticEdge( data, iBeg, iEnd, surface, F, helper ))
2059 dumpFunction(SMESH_Comment("smooth")<<data._index << "_Ed"<<sInd <<"_InfStep"<<nbSteps);
2064 for ( int i = iBeg; i < iEnd; ++i )
2066 moved |= data._edges[i]->SmoothOnEdge(surface, F, helper);
2068 dumpCmd( SMESH_Comment("# end step ")<<step);
2070 while ( moved && step++ < 5 );
2071 //cout << " NB STEPS: " << step << endl;
2079 int step = 0, badNb = 0; moved = true;
2080 while (( ++step <= 5 && moved ) || improved )
2082 dumpFunction(SMESH_Comment("smooth")<<data._index<<"_Fa"<<sInd
2083 <<"_InfStep"<<nbSteps<<"_"<<step); // debug
2084 int oldBadNb = badNb;
2087 for ( int i = iBeg; i < iEnd; ++i )
2088 moved |= data._edges[i]->Smooth(badNb);
2089 improved = ( badNb < oldBadNb );
2096 for ( int i = iBeg; i < iEnd; ++i )
2098 _LayerEdge* edge = data._edges[i];
2099 SMESH_TNodeXYZ tgtXYZ( edge->_nodes.back() );
2100 for ( unsigned j = 0; j < edge->_simplices.size(); ++j )
2101 if ( !edge->_simplices[j].IsForward( edge->_nodes[0], &tgtXYZ ))
2103 cout << "Bad simplex ( " << edge->_nodes[0]->GetID()<< " "<< tgtXYZ._node->GetID()
2104 << " "<< edge->_simplices[j]._nPrev->GetID()
2105 << " "<< edge->_simplices[j]._nNext->GetID() << " )" << endl;
2113 } // loop on shapes to smooth
2115 // Check if the last segments of _LayerEdge intersects 2D elements;
2116 // checked elements are either temporary faces or faces on surfaces w/o the layers
2118 SMESH_MeshEditor editor( _mesh );
2119 auto_ptr<SMESH_ElementSearcher> searcher
2120 ( editor.GetElementSearcher( data._proxyMesh->GetFaces( data._solid )) );
2122 distToIntersection = Precision::Infinite();
2124 const SMDS_MeshElement* intFace = 0;
2126 const SMDS_MeshElement* closestFace = 0;
2129 for ( unsigned i = 0; i < data._edges.size(); ++i )
2131 if ( data._edges[i]->FindIntersection( *searcher, dist, data._epsilon, &intFace ))
2133 if ( distToIntersection > dist )
2135 distToIntersection = dist;
2138 closestFace = intFace;
2145 SMDS_MeshElement::iterator nIt = closestFace->begin_nodes();
2146 cout << "Shortest distance: _LayerEdge nodes: tgt " << data._edges[iLE]->_nodes.back()->GetID()
2147 << " src " << data._edges[iLE]->_nodes[0]->GetID()<< ", intersection with face ("
2148 << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
2149 << ") distance = " << distToIntersection<< endl;
2156 //================================================================================
2158 * \brief Return a curve of the EDGE to be used for smoothing and arrange
2159 * _LayerEdge's to be in a consequent order
2161 //================================================================================
2163 Handle(Geom_Curve) _SolidData::CurveForSmooth( const TopoDS_Edge& E,
2166 Handle(Geom_Surface)& surface,
2167 const TopoDS_Face& F,
2168 SMESH_MesherHelper& helper)
2170 TGeomID eIndex = helper.GetMeshDS()->ShapeToIndex( E );
2172 map< TGeomID, Handle(Geom_Curve)>::iterator i2curve = _edge2curve.find( eIndex );
2174 if ( i2curve == _edge2curve.end() )
2176 // sort _LayerEdge's by position on the EDGE
2178 map< double, _LayerEdge* > u2edge;
2179 for ( int i = iFrom; i < iTo; ++i )
2180 u2edge.insert( make_pair( helper.GetNodeU( E, _edges[i]->_nodes[0] ), _edges[i] ));
2182 ASSERT( u2edge.size() == iTo - iFrom );
2183 map< double, _LayerEdge* >::iterator u2e = u2edge.begin();
2184 for ( int i = iFrom; i < iTo; ++i, ++u2e )
2185 _edges[i] = u2e->second;
2187 // set _2neibors according to the new order
2188 for ( int i = iFrom; i < iTo-1; ++i )
2189 if ( _edges[i]->_2neibors->_nodes[1] != _edges[i+1]->_nodes.back() )
2190 _edges[i]->_2neibors->reverse();
2191 if ( u2edge.size() > 1 &&
2192 _edges[iTo-1]->_2neibors->_nodes[0] != _edges[iTo-2]->_nodes.back() )
2193 _edges[iTo-1]->_2neibors->reverse();
2196 SMESHDS_SubMesh* smDS = helper.GetMeshDS()->MeshElements( eIndex );
2198 TopLoc_Location loc; double f,l;
2200 Handle(Geom_Line) line;
2201 Handle(Geom_Circle) circle;
2202 bool isLine, isCirc;
2203 if ( F.IsNull() ) // 3D case
2205 // check if the EDGE is a line
2206 Handle(Geom_Curve) curve = BRep_Tool::Curve( E, loc, f, l);
2207 if ( curve->IsKind( STANDARD_TYPE( Geom_TrimmedCurve )))
2208 curve = Handle(Geom_TrimmedCurve)::DownCast( curve )->BasisCurve();
2210 line = Handle(Geom_Line)::DownCast( curve );
2211 circle = Handle(Geom_Circle)::DownCast( curve );
2212 isLine = (!line.IsNull());
2213 isCirc = (!circle.IsNull());
2215 if ( !isLine && !isCirc ) // Check if the EDGE is close to a line
2218 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
2219 while ( nIt->more() )
2220 bndBox.Add( SMESH_TNodeXYZ( nIt->next() ));
2221 gp_XYZ size = bndBox.CornerMax() - bndBox.CornerMin();
2223 SMESH_TNodeXYZ p0( _edges[iFrom]->_2neibors->_nodes[0] );
2224 SMESH_TNodeXYZ p1( _edges[iFrom]->_2neibors->_nodes[1] );
2225 const double lineTol = 1e-2 * ( p0 - p1 ).Modulus();
2226 for ( int i = 0; i < 3 && !isLine; ++i )
2227 isLine = ( size.Coord( i+1 ) <= lineTol );
2229 if ( !isLine && !isCirc && iTo-iFrom > 2) // Check if the EDGE is close to a circle
2236 // check if the EDGE is a line
2237 Handle(Geom2d_Curve) curve = BRep_Tool::CurveOnSurface( E, F, f, l);
2238 if ( curve->IsKind( STANDARD_TYPE( Geom2d_TrimmedCurve )))
2239 curve = Handle(Geom2d_TrimmedCurve)::DownCast( curve )->BasisCurve();
2241 Handle(Geom2d_Line) line2d = Handle(Geom2d_Line)::DownCast( curve );
2242 Handle(Geom2d_Circle) circle2d = Handle(Geom2d_Circle)::DownCast( curve );
2243 isLine = (!line2d.IsNull());
2244 isCirc = (!circle2d.IsNull());
2246 if ( !isLine && !isCirc) // Check if the EDGE is close to a line
2249 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
2250 while ( nIt->more() )
2251 bndBox.Add( helper.GetNodeUV( F, nIt->next() ));
2252 gp_XY size = bndBox.CornerMax() - bndBox.CornerMin();
2254 const double lineTol = 1e-2 * sqrt( bndBox.SquareExtent() );
2255 for ( int i = 0; i < 2 && !isLine; ++i )
2256 isLine = ( size.Coord( i+1 ) <= lineTol );
2258 if ( !isLine && !isCirc && iTo-iFrom > 2) // Check if the EDGE is close to a circle
2264 line = new Geom_Line( gp::OX() ); // only type does matter
2268 gp_Pnt2d p = circle2d->Location();
2269 gp_Ax2 ax( gp_Pnt( p.X(), p.Y(), 0), gp::DX());
2270 circle = new Geom_Circle( ax, 1.); // only center position does matter
2274 Handle(Geom_Curve)& res = _edge2curve[ eIndex ];
2282 return i2curve->second;
2285 //================================================================================
2287 * \brief smooth _LayerEdge's on a staight EDGE or circular EDGE
2289 //================================================================================
2291 bool _ViscousBuilder::smoothAnalyticEdge( _SolidData& data,
2294 Handle(Geom_Surface)& surface,
2295 const TopoDS_Face& F,
2296 SMESH_MesherHelper& helper)
2298 TopoDS_Shape S = helper.GetSubShapeByNode( data._edges[ iFrom ]->_nodes[0],
2299 helper.GetMeshDS());
2300 TopoDS_Edge E = TopoDS::Edge( S );
2302 Handle(Geom_Curve) curve = data.CurveForSmooth( E, iFrom, iTo, surface, F, helper );
2303 if ( curve.IsNull() ) return false;
2305 // compute a relative length of segments
2306 vector< double > len( iTo-iFrom+1 );
2308 double curLen, prevLen = len[0] = 1.0;
2309 for ( int i = iFrom; i < iTo; ++i )
2311 curLen = prevLen * data._edges[i]->_2neibors->_wgt[0] / data._edges[i]->_2neibors->_wgt[1];
2312 len[i-iFrom+1] = len[i-iFrom] + curLen;
2317 if ( curve->IsKind( STANDARD_TYPE( Geom_Line )))
2319 if ( F.IsNull() ) // 3D
2321 SMESH_TNodeXYZ p0( data._edges[iFrom]->_2neibors->_nodes[0]);
2322 SMESH_TNodeXYZ p1( data._edges[iTo-1]->_2neibors->_nodes[1]);
2323 for ( int i = iFrom; i < iTo; ++i )
2325 double r = len[i-iFrom] / len.back();
2326 gp_XYZ newPos = p0 * ( 1. - r ) + p1 * r;
2327 data._edges[i]->_pos.back() = newPos;
2328 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( data._edges[i]->_nodes.back() );
2329 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
2334 gp_XY uv0 = helper.GetNodeUV( F, data._edges[iFrom]->_2neibors->_nodes[0]);
2335 gp_XY uv1 = helper.GetNodeUV( F, data._edges[iTo-1]->_2neibors->_nodes[1]);
2336 for ( int i = iFrom; i < iTo; ++i )
2338 double r = len[i-iFrom] / len.back();
2339 gp_XY newUV = uv0 * ( 1. - r ) + uv1 * r;
2340 data._edges[i]->_pos.back().SetCoord( newUV.X(), newUV.Y(), 0 );
2342 gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
2343 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( data._edges[i]->_nodes.back() );
2344 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
2346 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
2347 pos->SetUParameter( newUV.X() );
2348 pos->SetVParameter( newUV.Y() );
2354 if ( curve->IsKind( STANDARD_TYPE( Geom_Circle )))
2356 Handle(Geom_Circle) circle = Handle(Geom_Circle)::DownCast( curve );
2357 gp_Pnt center3D = circle->Location();
2359 if ( F.IsNull() ) // 3D
2361 return false; // TODO ???
2365 const gp_XY center( center3D.X(), center3D.Y() );
2367 gp_XY uv0 = helper.GetNodeUV( F, data._edges[iFrom]->_2neibors->_nodes[0]);
2368 gp_XY uvM = helper.GetNodeUV( F, data._edges[iFrom]->_nodes.back());
2369 gp_XY uv1 = helper.GetNodeUV( F, data._edges[iTo-1]->_2neibors->_nodes[1]);
2370 gp_Vec2d vec0( center, uv0 );
2371 gp_Vec2d vecM( center, uvM);
2372 gp_Vec2d vec1( center, uv1 );
2373 double uLast = vec0.Angle( vec1 ); // -PI - +PI
2374 double uMidl = vec0.Angle( vecM );
2375 if ( uLast < 0 ) uLast += 2*PI; // 0.0 - 2*PI
2376 if ( uMidl < 0 ) uMidl += 2*PI;
2377 const bool sense = ( uMidl < uLast );
2378 const double radius = 0.5 * ( vec0.Magnitude() + vec1.Magnitude() );
2380 gp_Ax2d axis( center, vec0 );
2381 gp_Circ2d circ ( axis, radius, sense );
2382 for ( int i = iFrom; i < iTo; ++i )
2384 double newU = uLast * len[i-iFrom] / len.back();
2385 gp_Pnt2d newUV = ElCLib::Value( newU, circ );
2386 data._edges[i]->_pos.back().SetCoord( newUV.X(), newUV.Y(), 0 );
2388 gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
2389 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( data._edges[i]->_nodes.back() );
2390 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
2392 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
2393 pos->SetUParameter( newUV.X() );
2394 pos->SetVParameter( newUV.Y() );
2403 //================================================================================
2405 * \brief Modify normals of _LayerEdge's on EDGE's to avoid intersection with
2406 * _LayerEdge's on neighbor EDGE's
2408 //================================================================================
2410 bool _ViscousBuilder::updateNormals( _SolidData& data,
2411 SMESH_MesherHelper& helper )
2413 // make temporary quadrangles got by extrusion of
2414 // mesh edges along _LayerEdge._normal's
2416 vector< const SMDS_MeshElement* > tmpFaces;
2418 set< SMESH_TLink > extrudedLinks; // contains target nodes
2419 vector< const SMDS_MeshNode*> nodes(4); // of a tmp mesh face
2421 dumpFunction(SMESH_Comment("makeTmpFacesOnEdges")<<data._index);
2422 for ( unsigned i = 0; i < data._edges.size(); ++i )
2424 _LayerEdge* edge = data._edges[i];
2425 if ( !edge->IsOnEdge() || !edge->_sWOL.IsNull() ) continue;
2426 const SMDS_MeshNode* tgt1 = edge->_nodes.back();
2427 for ( int j = 0; j < 2; ++j ) // loop on _2NearEdges
2429 const SMDS_MeshNode* tgt2 = edge->_2neibors->_nodes[j];
2430 pair< set< SMESH_TLink >::iterator, bool > link_isnew =
2431 extrudedLinks.insert( SMESH_TLink( tgt1, tgt2 ));
2432 if ( !link_isnew.second )
2434 extrudedLinks.erase( link_isnew.first );
2435 continue; // already extruded and will no more encounter
2437 // look for a _LayerEdge containg tgt2
2438 // _LayerEdge* neiborEdge = 0;
2439 // unsigned di = 0; // check _edges[i+di] and _edges[i-di]
2440 // while ( !neiborEdge && ++di <= data._edges.size() )
2442 // if ( i+di < data._edges.size() && data._edges[i+di]->_nodes.back() == tgt2 )
2443 // neiborEdge = data._edges[i+di];
2444 // else if ( di <= i && data._edges[i-di]->_nodes.back() == tgt2 )
2445 // neiborEdge = data._edges[i-di];
2447 // if ( !neiborEdge )
2448 // return error("updateNormals(): neighbor _LayerEdge not found", data._index);
2449 _LayerEdge* neiborEdge = edge->_2neibors->_edges[j];
2451 TmpMeshFaceOnEdge* f = new TmpMeshFaceOnEdge( edge, neiborEdge, --_tmpFaceID );
2452 tmpFaces.push_back( f );
2454 dumpCmd(SMESH_Comment("mesh.AddFace([ ")
2455 <<f->_nn[0]->GetID()<<", "<<f->_nn[1]->GetID()<<", "
2456 <<f->_nn[2]->GetID()<<", "<<f->_nn[3]->GetID()<<" ])");
2461 // Check if _LayerEdge's based on EDGE's intersects tmpFaces.
2462 // Perform two loops on _LayerEdge on EDGE's:
2463 // 1) to find and fix intersection
2464 // 2) to check that no new intersection appears as result of 1)
2466 SMESH_MeshEditor editor( _mesh );
2467 SMDS_ElemIteratorPtr fIt( new SMDS_ElementVectorIterator( tmpFaces.begin(),
2469 auto_ptr<SMESH_ElementSearcher> searcher ( editor.GetElementSearcher( fIt ));
2471 // 1) Find intersections
2473 const SMDS_MeshElement* face;
2474 typedef map< _LayerEdge*, set< _LayerEdge*, _LayerEdgeCmp >, _LayerEdgeCmp > TLEdge2LEdgeSet;
2475 TLEdge2LEdgeSet edge2CloseEdge;
2477 const double eps = data._epsilon * data._epsilon;
2478 for ( unsigned i = 0; i < data._edges.size(); ++i )
2480 _LayerEdge* edge = data._edges[i];
2481 if ( !edge->IsOnEdge() || !edge->_sWOL.IsNull() ) continue;
2482 if ( edge->FindIntersection( *searcher, dist, eps, &face ))
2484 const TmpMeshFaceOnEdge* f = (const TmpMeshFaceOnEdge*) face;
2485 set< _LayerEdge*, _LayerEdgeCmp > & ee = edge2CloseEdge[ edge ];
2486 ee.insert( f->_le1 );
2487 ee.insert( f->_le2 );
2488 if ( f->_le1->IsOnEdge() && f->_le1->_sWOL.IsNull() )
2489 edge2CloseEdge[ f->_le1 ].insert( edge );
2490 if ( f->_le2->IsOnEdge() && f->_le2->_sWOL.IsNull() )
2491 edge2CloseEdge[ f->_le2 ].insert( edge );
2495 // Set _LayerEdge._normal
2497 if ( !edge2CloseEdge.empty() )
2499 dumpFunction(SMESH_Comment("updateNormals")<<data._index);
2501 TLEdge2LEdgeSet::iterator e2ee = edge2CloseEdge.begin();
2502 for ( ; e2ee != edge2CloseEdge.end(); ++e2ee )
2504 _LayerEdge* edge1 = e2ee->first;
2505 _LayerEdge* edge2 = 0;
2506 set< _LayerEdge*, _LayerEdgeCmp >& ee = e2ee->second;
2508 // find EDGEs the edges reside
2510 TopoDS_Shape S = helper.GetSubShapeByNode( edge1->_nodes[0], getMeshDS() );
2511 if ( S.ShapeType() != TopAbs_EDGE )
2512 continue; // TODO: find EDGE by VERTEX
2513 E1 = TopoDS::Edge( S );
2514 set< _LayerEdge*, _LayerEdgeCmp >::iterator eIt = ee.begin();
2515 while ( E2.IsNull() && eIt != ee.end())
2517 _LayerEdge* e2 = *eIt++;
2518 TopoDS_Shape S = helper.GetSubShapeByNode( e2->_nodes[0], getMeshDS() );
2519 if ( S.ShapeType() == TopAbs_EDGE )
2520 E2 = TopoDS::Edge( S ), edge2 = e2;
2522 if ( E2.IsNull() ) continue; // TODO: find EDGE by VERTEX
2524 // find 3 FACEs sharing 2 EDGEs
2526 TopoDS_Face FF1[2], FF2[2];
2527 PShapeIteratorPtr fIt = helper.GetAncestors(E1, *_mesh, TopAbs_FACE);
2528 while ( fIt->more() && FF1[1].IsNull())
2530 const TopoDS_Face *F = (const TopoDS_Face*) fIt->next();
2531 if ( helper.IsSubShape( *F, data._solid))
2532 FF1[ FF1[0].IsNull() ? 0 : 1 ] = *F;
2534 fIt = helper.GetAncestors(E2, *_mesh, TopAbs_FACE);
2535 while ( fIt->more() && FF2[1].IsNull())
2537 const TopoDS_Face *F = (const TopoDS_Face*) fIt->next();
2538 if ( helper.IsSubShape( *F, data._solid))
2539 FF2[ FF2[0].IsNull() ? 0 : 1 ] = *F;
2541 // exclude a FACE common to E1 and E2 (put it at [1] in FF* )
2542 if ( FF1[0].IsSame( FF2[0]) || FF1[0].IsSame( FF2[1]))
2543 std::swap( FF1[0], FF1[1] );
2544 if ( FF2[0].IsSame( FF1[0]) )
2545 std::swap( FF2[0], FF2[1] );
2546 if ( FF1[0].IsNull() || FF2[0].IsNull() )
2549 // // get a new normal for edge1
2551 gp_Vec dir1 = edge1->_normal, dir2 = edge2->_normal;
2552 if ( edge1->_cosin < 0 )
2553 dir1 = getFaceDir( FF1[0], E1, edge1->_nodes[0], helper, ok ).Normalized();
2554 if ( edge2->_cosin < 0 )
2555 dir2 = getFaceDir( FF2[0], E2, edge2->_nodes[0], helper, ok ).Normalized();
2556 // gp_Vec dir1 = getFaceDir( FF1[0], E1, edge1->_nodes[0], helper, ok );
2557 // gp_Vec dir2 = getFaceDir( FF2[0], E2, edge2->_nodes[0], helper, ok2 );
2558 // double wgt1 = ( edge1->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
2559 // double wgt2 = ( edge2->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
2560 // gp_Vec newNorm = wgt1 * dir1 + wgt2 * dir2;
2561 // newNorm.Normalize();
2563 double wgt1 = ( edge1->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
2564 double wgt2 = ( edge2->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
2565 gp_Vec newNorm = wgt1 * dir1 + wgt2 * dir2;
2566 newNorm.Normalize();
2568 edge1->_normal = newNorm.XYZ();
2570 // update data of edge1 depending on _normal
2571 const SMDS_MeshNode *n1, *n2;
2572 n1 = edge1->_2neibors->_edges[0]->_nodes[0];
2573 n2 = edge1->_2neibors->_edges[1]->_nodes[0];
2574 //if ( !findNeiborsOnEdge( edge1, n1, n2, data ))
2576 edge1->SetDataByNeighbors( n1, n2, helper );
2578 if ( edge1->_cosin < 0 )
2581 getFaceDir( FF1[0], E1, edge1->_nodes[0], helper, ok );
2582 double angle = dir1.Angle( edge1->_normal ); // [0,PI]
2583 edge1->SetCosin( cos( angle ));
2585 // limit data._stepSize
2586 if ( edge1->_cosin > 0.1 )
2588 SMDS_ElemIteratorPtr fIt = edge1->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
2589 while ( fIt->more() )
2590 limitStepSize( data, fIt->next(), edge1->_cosin );
2592 // set new XYZ of target node
2593 edge1->InvalidateStep( 1 );
2595 edge1->SetNewLength( data._stepSize, helper );
2598 // Update normals and other dependent data of not intersecting _LayerEdge's
2599 // neighboring the intersecting ones
2601 for ( e2ee = edge2CloseEdge.begin(); e2ee != edge2CloseEdge.end(); ++e2ee )
2603 _LayerEdge* edge1 = e2ee->first;
2604 if ( !edge1->_2neibors )
2606 for ( int j = 0; j < 2; ++j ) // loop on 2 neighbors
2608 _LayerEdge* neighbor = edge1->_2neibors->_edges[j];
2609 if ( edge2CloseEdge.count ( neighbor ))
2610 continue; // j-th neighbor is also intersected
2611 _LayerEdge* prevEdge = edge1;
2612 const int nbSteps = 6;
2613 for ( int step = nbSteps; step; --step ) // step from edge1 in j-th direction
2615 if ( !neighbor->_2neibors )
2616 break; // neighbor is on VERTEX
2618 _LayerEdge* nextEdge = neighbor->_2neibors->_edges[iNext];
2619 if ( nextEdge == prevEdge )
2620 nextEdge = neighbor->_2neibors->_edges[ ++iNext ];
2621 // const double& wgtPrev = neighbor->_2neibors->_wgt[1-iNext];
2622 // const double& wgtNext = neighbor->_2neibors->_wgt[iNext];
2623 double r = double(step-1)/nbSteps;
2624 if ( !nextEdge->_2neibors )
2627 gp_XYZ newNorm = prevEdge->_normal * r + nextEdge->_normal * (1-r);
2628 newNorm.Normalize();
2630 neighbor->_normal = newNorm;
2631 neighbor->SetCosin( prevEdge->_cosin * r + nextEdge->_cosin * (1-r) );
2632 neighbor->SetDataByNeighbors( prevEdge->_nodes[0], nextEdge->_nodes[0], helper );
2634 neighbor->InvalidateStep( 1 );
2636 neighbor->SetNewLength( data._stepSize, helper );
2638 // goto the next neighbor
2639 prevEdge = neighbor;
2640 neighbor = nextEdge;
2646 // 2) Check absence of intersections
2649 for ( unsigned i = 0 ; i < tmpFaces.size(); ++i )
2655 //================================================================================
2657 * \brief Looks for intersection of it's last segment with faces
2658 * \param distance - returns shortest distance from the last node to intersection
2660 //================================================================================
2662 bool _LayerEdge::FindIntersection( SMESH_ElementSearcher& searcher,
2664 const double& epsilon,
2665 const SMDS_MeshElement** face)
2667 vector< const SMDS_MeshElement* > suspectFaces;
2669 gp_Ax1 lastSegment = LastSegment(segLen);
2670 searcher.GetElementsNearLine( lastSegment, SMDSAbs_Face, suspectFaces );
2672 bool segmentIntersected = false;
2673 distance = Precision::Infinite();
2674 int iFace = -1; // intersected face
2675 for ( unsigned j = 0 ; j < suspectFaces.size() && !segmentIntersected; ++j )
2677 const SMDS_MeshElement* face = suspectFaces[j];
2678 if ( face->GetNodeIndex( _nodes.back() ) >= 0 ||
2679 face->GetNodeIndex( _nodes[0] ) >= 0 )
2680 continue; // face sharing _LayerEdge node
2681 const int nbNodes = face->NbCornerNodes();
2682 bool intFound = false;
2684 SMDS_MeshElement::iterator nIt = face->begin_nodes();
2687 intFound = SegTriaInter( lastSegment, *nIt++, *nIt++, *nIt++, dist, epsilon );
2691 const SMDS_MeshNode* tria[3];
2694 for ( int n2 = 2; n2 < nbNodes && !intFound; ++n2 )
2697 intFound = SegTriaInter(lastSegment, tria[0], tria[1], tria[2], dist, epsilon );
2703 if ( dist < segLen*(1.01))
2704 segmentIntersected = true;
2705 if ( distance > dist )
2706 distance = dist, iFace = j;
2709 if ( iFace != -1 && face ) *face = suspectFaces[iFace];
2710 // if ( distance && iFace > -1 )
2712 // // distance is used to limit size of inflation step which depends on
2713 // // whether the intersected face bears viscous layers or not
2714 // bool faceHasVL = suspectFaces[iFace]->GetID() < 1;
2718 if ( segmentIntersected )
2721 SMDS_MeshElement::iterator nIt = suspectFaces[iFace]->begin_nodes();
2722 gp_XYZ intP( lastSegment.Location().XYZ() + lastSegment.Direction().XYZ() * distance );
2723 cout << "nodes: tgt " << _nodes.back()->GetID() << " src " << _nodes[0]->GetID()
2724 << ", intersection with face ("
2725 << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
2726 << ") at point (" << intP.X() << ", " << intP.Y() << ", " << intP.Z()
2727 << ") distance = " << distance - segLen<< endl;
2733 return segmentIntersected;
2736 //================================================================================
2738 * \brief Returns size and direction of the last segment
2740 //================================================================================
2742 gp_Ax1 _LayerEdge::LastSegment(double& segLen) const
2744 // find two non-coincident positions
2745 gp_XYZ orig = _pos.back();
2747 int iPrev = _pos.size() - 2;
2748 while ( iPrev >= 0 )
2750 dir = orig - _pos[iPrev];
2751 if ( dir.SquareModulus() > 1e-100 )
2761 segDir.SetLocation( SMESH_TNodeXYZ( _nodes[0] ));
2762 segDir.SetDirection( _normal );
2767 gp_Pnt pPrev = _pos[ iPrev ];
2768 if ( !_sWOL.IsNull() )
2770 TopLoc_Location loc;
2771 if ( _sWOL.ShapeType() == TopAbs_EDGE )
2774 Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( _sWOL ), loc, f,l);
2775 pPrev = curve->Value( pPrev.X() ).Transformed( loc );
2779 Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face(_sWOL), loc );
2780 pPrev = surface->Value( pPrev.X(), pPrev.Y() ).Transformed( loc );
2782 dir = SMESH_TNodeXYZ( _nodes.back() ) - pPrev.XYZ();
2784 segDir.SetLocation( pPrev );
2785 segDir.SetDirection( dir );
2786 segLen = dir.Modulus();
2792 //================================================================================
2794 * \brief Test intersection of the last segment with a given triangle
2795 * using Moller-Trumbore algorithm
2796 * Intersection is detected if distance to intersection is less than _LayerEdge._len
2798 //================================================================================
2800 bool _LayerEdge::SegTriaInter( const gp_Ax1& lastSegment,
2801 const SMDS_MeshNode* n0,
2802 const SMDS_MeshNode* n1,
2803 const SMDS_MeshNode* n2,
2805 const double& EPSILON) const
2807 //const double EPSILON = 1e-6;
2809 gp_XYZ orig = lastSegment.Location().XYZ();
2810 gp_XYZ dir = lastSegment.Direction().XYZ();
2812 SMESH_TNodeXYZ vert0( n0 );
2813 SMESH_TNodeXYZ vert1( n1 );
2814 SMESH_TNodeXYZ vert2( n2 );
2816 /* calculate distance from vert0 to ray origin */
2817 gp_XYZ tvec = orig - vert0;
2819 if ( tvec * dir > EPSILON )
2820 // intersected face is at back side of the temporary face this _LayerEdge belongs to
2823 gp_XYZ edge1 = vert1 - vert0;
2824 gp_XYZ edge2 = vert2 - vert0;
2826 /* begin calculating determinant - also used to calculate U parameter */
2827 gp_XYZ pvec = dir ^ edge2;
2829 /* if determinant is near zero, ray lies in plane of triangle */
2830 double det = edge1 * pvec;
2832 if (det > -EPSILON && det < EPSILON)
2834 double inv_det = 1.0 / det;
2836 /* calculate U parameter and test bounds */
2837 double u = ( tvec * pvec ) * inv_det;
2838 if (u < 0.0 || u > 1.0)
2841 /* prepare to test V parameter */
2842 gp_XYZ qvec = tvec ^ edge1;
2844 /* calculate V parameter and test bounds */
2845 double v = (dir * qvec) * inv_det;
2846 if ( v < 0.0 || u + v > 1.0 )
2849 /* calculate t, ray intersects triangle */
2850 t = (edge2 * qvec) * inv_det;
2852 // if (det < EPSILON)
2855 // /* calculate distance from vert0 to ray origin */
2856 // gp_XYZ tvec = orig - vert0;
2858 // /* calculate U parameter and test bounds */
2859 // double u = tvec * pvec;
2860 // if (u < 0.0 || u > det)
2863 // /* prepare to test V parameter */
2864 // gp_XYZ qvec = tvec ^ edge1;
2866 // /* calculate V parameter and test bounds */
2867 // double v = dir * qvec;
2868 // if (v < 0.0 || u + v > det)
2871 // /* calculate t, scale parameters, ray intersects triangle */
2872 // double t = edge2 * qvec;
2873 // double inv_det = 1.0 / det;
2881 //================================================================================
2883 * \brief Perform smooth of _LayerEdge's based on EDGE's
2884 * \retval bool - true if node has been moved
2886 //================================================================================
2888 bool _LayerEdge::SmoothOnEdge(Handle(Geom_Surface)& surface,
2889 const TopoDS_Face& F,
2890 SMESH_MesherHelper& helper)
2892 ASSERT( IsOnEdge() );
2894 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _nodes.back() );
2895 SMESH_TNodeXYZ oldPos( tgtNode );
2896 double dist01, distNewOld;
2898 SMESH_TNodeXYZ p0( _2neibors->_nodes[0]);
2899 SMESH_TNodeXYZ p1( _2neibors->_nodes[1]);
2900 dist01 = p0.Distance( _2neibors->_nodes[1] );
2902 gp_Pnt newPos = p0 * _2neibors->_wgt[0] + p1 * _2neibors->_wgt[1];
2903 double lenDelta = 0;
2906 lenDelta = _curvature->lenDelta( _len );
2907 newPos.ChangeCoord() += _normal * lenDelta;
2910 distNewOld = newPos.Distance( oldPos );
2914 if ( _2neibors->_plnNorm )
2916 // put newPos on the plane defined by source node and _plnNorm
2917 gp_XYZ new2src = SMESH_TNodeXYZ( _nodes[0] ) - newPos.XYZ();
2918 double new2srcProj = (*_2neibors->_plnNorm) * new2src;
2919 newPos.ChangeCoord() += (*_2neibors->_plnNorm) * new2srcProj;
2921 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
2922 _pos.back() = newPos.XYZ();
2926 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
2927 gp_XY uv( Precision::Infinite(), 0 );
2928 helper.CheckNodeUV( F, tgtNode, uv, 1e-10, /*force=*/true );
2929 _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
2931 newPos = surface->Value( uv.X(), uv.Y() );
2932 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
2935 if ( _curvature && lenDelta < 0 )
2937 gp_Pnt prevPos( _pos[ _pos.size()-2 ]);
2938 _len -= prevPos.Distance( oldPos );
2939 _len += prevPos.Distance( newPos );
2941 bool moved = distNewOld > dist01/50;
2943 dumpMove( tgtNode ); // debug
2948 //================================================================================
2950 * \brief Perform laplacian smooth in 3D of nodes inflated from FACE
2951 * \retval bool - true if _tgtNode has been moved
2953 //================================================================================
2955 bool _LayerEdge::Smooth(int& badNb)
2957 if ( _simplices.size() < 2 )
2958 return false; // _LayerEdge inflated along EDGE or FACE
2960 // compute new position for the last _pos
2961 gp_XYZ newPos (0,0,0);
2962 for ( unsigned i = 0; i < _simplices.size(); ++i )
2963 newPos += SMESH_TNodeXYZ( _simplices[i]._nPrev );
2964 newPos /= _simplices.size();
2967 newPos += _normal * _curvature->lenDelta( _len );
2969 gp_Pnt prevPos( _pos[ _pos.size()-2 ]);
2970 // if ( _cosin < -0.1)
2972 // // Avoid decreasing length of edge on concave surface
2973 // //gp_Vec oldMove( _pos[ _pos.size()-2 ], _pos.back() );
2974 // gp_Vec newMove( prevPos, newPos );
2975 // newPos = _pos.back() + newMove.XYZ();
2977 // else if ( _cosin > 0.3 )
2979 // // Avoid increasing length of edge too much
2982 // count quality metrics (orientation) of tetras around _tgtNode
2984 SMESH_TNodeXYZ tgtXYZ( _nodes.back() );
2985 for ( unsigned i = 0; i < _simplices.size(); ++i )
2986 nbOkBefore += _simplices[i].IsForward( _nodes[0], &tgtXYZ );
2989 for ( unsigned i = 0; i < _simplices.size(); ++i )
2990 nbOkAfter += _simplices[i].IsForward( _nodes[0], &newPos );
2992 if ( nbOkAfter < nbOkBefore )
2995 SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
2997 _len -= prevPos.Distance(SMESH_TNodeXYZ( n ));
2998 _len += prevPos.Distance(newPos);
3000 n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
3001 _pos.back() = newPos;
3003 badNb += _simplices.size() - nbOkAfter;
3010 //================================================================================
3012 * \brief Add a new segment to _LayerEdge during inflation
3014 //================================================================================
3016 void _LayerEdge::SetNewLength( double len, SMESH_MesherHelper& helper )
3018 if ( _len - len > -1e-6 )
3020 _pos.push_back( _pos.back() );
3024 SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
3025 SMESH_TNodeXYZ oldXYZ( n );
3026 gp_XYZ nXYZ = oldXYZ + _normal * ( len - _len ) * _lenFactor;
3027 n->setXYZ( nXYZ.X(), nXYZ.Y(), nXYZ.Z() );
3029 _pos.push_back( nXYZ );
3031 if ( !_sWOL.IsNull() )
3034 if ( _sWOL.ShapeType() == TopAbs_EDGE )
3036 double u = Precision::Infinite(); // to force projection w/o distance check
3037 helper.CheckNodeU( TopoDS::Edge( _sWOL ), n, u, 1e-10, /*force=*/true, distXYZ );
3038 _pos.back().SetCoord( u, 0, 0 );
3039 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( n->GetPosition() );
3040 pos->SetUParameter( u );
3044 gp_XY uv( Precision::Infinite(), 0 );
3045 helper.CheckNodeUV( TopoDS::Face( _sWOL ), n, uv, 1e-10, /*force=*/true, distXYZ );
3046 _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
3047 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( n->GetPosition() );
3048 pos->SetUParameter( uv.X() );
3049 pos->SetVParameter( uv.Y() );
3051 n->setXYZ( distXYZ[1], distXYZ[2], distXYZ[3]);
3053 dumpMove( n ); //debug
3056 //================================================================================
3058 * \brief Remove last inflation step
3060 //================================================================================
3062 void _LayerEdge::InvalidateStep( int curStep )
3064 if ( _pos.size() > curStep )
3066 _pos.resize( curStep );
3067 gp_Pnt nXYZ = _pos.back();
3068 SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
3069 if ( !_sWOL.IsNull() )
3071 TopLoc_Location loc;
3072 if ( _sWOL.ShapeType() == TopAbs_EDGE )
3074 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( n->GetPosition() );
3075 pos->SetUParameter( nXYZ.X() );
3077 Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( _sWOL ), loc, f,l);
3078 nXYZ = curve->Value( nXYZ.X() ).Transformed( loc );
3082 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( n->GetPosition() );
3083 pos->SetUParameter( nXYZ.X() );
3084 pos->SetVParameter( nXYZ.Y() );
3085 Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face(_sWOL), loc );
3086 nXYZ = surface->Value( nXYZ.X(), nXYZ.Y() ).Transformed( loc );
3089 n->setXYZ( nXYZ.X(), nXYZ.Y(), nXYZ.Z() );
3094 //================================================================================
3096 * \brief Create layers of prisms
3098 //================================================================================
3100 bool _ViscousBuilder::refine(_SolidData& data)
3102 SMESH_MesherHelper helper( *_mesh );
3103 helper.SetSubShape( data._solid );
3104 helper.SetElementsOnShape(false);
3106 Handle(Geom_Curve) curve;
3107 Handle(Geom_Surface) surface;
3108 TopoDS_Edge geomEdge;
3109 TopoDS_Face geomFace;
3110 TopLoc_Location loc;
3111 double f,l, u/*, distXYZ[4]*/;
3115 for ( unsigned i = 0; i < data._edges.size(); ++i )
3117 _LayerEdge& edge = *data._edges[i];
3119 // get accumulated length of segments
3120 vector< double > segLen( edge._pos.size() );
3122 for ( unsigned j = 1; j < edge._pos.size(); ++j )
3123 segLen[j] = segLen[j-1] + (edge._pos[j-1] - edge._pos[j] ).Modulus();
3125 // allocate memory for new nodes if it is not yet refined
3126 const SMDS_MeshNode* tgtNode = edge._nodes.back();
3127 if ( edge._nodes.size() == 2 )
3129 edge._nodes.resize( data._hyp->GetNumberLayers() + 1, 0 );
3131 edge._nodes.back() = tgtNode;
3133 if ( !edge._sWOL.IsNull() )
3135 isOnEdge = ( edge._sWOL.ShapeType() == TopAbs_EDGE );
3136 // restore position of the last node
3140 geomEdge = TopoDS::Edge( edge._sWOL );
3141 curve = BRep_Tool::Curve( geomEdge, loc, f,l);
3142 // double u = helper.GetNodeU( tgtNode );
3143 // p = curve->Value( u );
3147 geomFace = TopoDS::Face( edge._sWOL );
3148 surface = BRep_Tool::Surface( geomFace, loc );
3149 // gp_XY uv = helper.GetNodeUV( tgtNode );
3150 // p = surface->Value( uv.X(), uv.Y() );
3152 // p.Transform( loc );
3153 // const_cast< SMDS_MeshNode* >( tgtNode )->setXYZ( p.X(), p.Y(), p.Z() );
3155 // calculate height of the first layer
3157 const double T = segLen.back(); //data._hyp.GetTotalThickness();
3158 const double f = data._hyp->GetStretchFactor();
3159 const int N = data._hyp->GetNumberLayers();
3160 const double fPowN = pow( f, N );
3161 if ( fPowN - 1 <= numeric_limits<double>::min() )
3164 h0 = T * ( f - 1 )/( fPowN - 1 );
3166 const double zeroLen = std::numeric_limits<double>::min();
3168 // create intermediate nodes
3169 double hSum = 0, hi = h0/f;
3171 for ( unsigned iStep = 1; iStep < edge._nodes.size(); ++iStep )
3173 // compute an intermediate position
3176 while ( hSum > segLen[iSeg] && iSeg < segLen.size()-1)
3178 int iPrevSeg = iSeg-1;
3179 while ( fabs( segLen[iPrevSeg] - segLen[iSeg]) <= zeroLen && iPrevSeg > 0 )
3181 double r = ( segLen[iSeg] - hSum ) / ( segLen[iSeg] - segLen[iPrevSeg] );
3182 gp_Pnt pos = r * edge._pos[iPrevSeg] + (1-r) * edge._pos[iSeg];
3184 SMDS_MeshNode*& node = const_cast< SMDS_MeshNode*& >(edge._nodes[ iStep ]);
3185 if ( !edge._sWOL.IsNull() )
3187 // compute XYZ by parameters <pos>
3191 pos = curve->Value( u ).Transformed(loc);
3195 uv.SetCoord( pos.X(), pos.Y() );
3196 pos = surface->Value( pos.X(), pos.Y() ).Transformed(loc);
3199 // create or update the node
3202 node = helper.AddNode( pos.X(), pos.Y(), pos.Z());
3203 if ( !edge._sWOL.IsNull() )
3206 getMeshDS()->SetNodeOnEdge( node, geomEdge, u );
3208 getMeshDS()->SetNodeOnFace( node, geomFace, uv.X(), uv.Y() );
3212 getMeshDS()->SetNodeInVolume( node, helper.GetSubShapeID() );
3217 if ( !edge._sWOL.IsNull() )
3219 // make average pos from new and current parameters
3222 u = 0.5 * ( u + helper.GetNodeU( geomEdge, node ));
3223 pos = curve->Value( u ).Transformed(loc);
3227 uv = 0.5 * ( uv + helper.GetNodeUV( geomFace, node ));
3228 pos = surface->Value( uv.X(), uv.Y()).Transformed(loc);
3231 node->setXYZ( pos.X(), pos.Y(), pos.Z() );
3236 // TODO: make quadratic prisms and polyhedrons(?)
3238 helper.SetElementsOnShape(true);
3240 TopExp_Explorer exp( data._solid, TopAbs_FACE );
3241 for ( ; exp.More(); exp.Next() )
3243 if ( _ignoreShapeIds.count( getMeshDS()->ShapeToIndex( exp.Current() )))
3245 SMESHDS_SubMesh* fSubM = getMeshDS()->MeshElements( exp.Current() );
3246 SMDS_ElemIteratorPtr fIt = fSubM->GetElements();
3247 vector< vector<const SMDS_MeshNode*>* > nnVec;
3248 while ( fIt->more() )
3250 const SMDS_MeshElement* face = fIt->next();
3251 int nbNodes = face->NbCornerNodes();
3252 nnVec.resize( nbNodes );
3253 SMDS_ElemIteratorPtr nIt = face->nodesIterator();
3254 for ( int iN = 0; iN < nbNodes; ++iN )
3256 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
3257 nnVec[ iN ] = & data._n2eMap[ n ]->_nodes;
3260 int nbZ = nnVec[0]->size();
3264 for ( int iZ = 1; iZ < nbZ; ++iZ )
3265 helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1], (*nnVec[2])[iZ-1],
3266 (*nnVec[0])[iZ], (*nnVec[1])[iZ], (*nnVec[2])[iZ]);
3269 for ( int iZ = 1; iZ < nbZ; ++iZ )
3270 helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1],
3271 (*nnVec[2])[iZ-1], (*nnVec[3])[iZ-1],
3272 (*nnVec[0])[iZ], (*nnVec[1])[iZ],
3273 (*nnVec[2])[iZ], (*nnVec[3])[iZ]);
3276 return error("Not supported type of element", data._index);
3283 //================================================================================
3285 * \brief Shrink 2D mesh on faces to let space for inflated layers
3287 //================================================================================
3289 bool _ViscousBuilder::shrink()
3291 // make map of (ids of FACEs to shrink mesh on) to (_SolidData containing _LayerEdge's
3292 // inflated along FACE or EDGE)
3293 map< TGeomID, _SolidData* > f2sdMap;
3294 for ( unsigned i = 0 ; i < _sdVec.size(); ++i )
3296 _SolidData& data = _sdVec[i];
3297 TopTools_MapOfShape FFMap;
3298 map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
3299 for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
3300 if ( s2s->second.ShapeType() == TopAbs_FACE )
3302 f2sdMap.insert( make_pair( getMeshDS()->ShapeToIndex( s2s->second ), &data ));
3304 if ( FFMap.Add( (*s2s).second ))
3305 // Put mesh faces on the shrinked FACE to the proxy sub-mesh to avoid
3306 // usage of mesh faces made in addBoundaryElements() by the 3D algo or
3307 // by StdMeshers_QuadToTriaAdaptor
3308 if ( SMESHDS_SubMesh* smDS = getMeshDS()->MeshElements( s2s->second ))
3310 SMESH_ProxyMesh::SubMesh* proxySub =
3311 data._proxyMesh->getFaceSubM( TopoDS::Face( s2s->second ), /*create=*/true);
3312 SMDS_ElemIteratorPtr fIt = smDS->GetElements();
3313 while ( fIt->more() )
3314 proxySub->AddElement( fIt->next() );
3315 // as a result 3D algo will use elements from proxySub and not from smDS
3320 SMESH_MesherHelper helper( *_mesh );
3323 map< int, _Shrinker1D > e2shrMap;
3325 // loop on FACES to srink mesh on
3326 map< TGeomID, _SolidData* >::iterator f2sd = f2sdMap.begin();
3327 for ( ; f2sd != f2sdMap.end(); ++f2sd )
3329 _SolidData& data = *f2sd->second;
3330 TNode2Edge& n2eMap = data._n2eMap;
3331 const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( f2sd->first ));
3332 const bool reverse = ( data._reversedFaceIds.count( f2sd->first ));
3334 Handle(Geom_Surface) surface = BRep_Tool::Surface(F);
3336 SMESH_subMesh* sm = _mesh->GetSubMesh( F );
3337 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
3339 helper.SetSubShape(F);
3341 // ===========================
3342 // Prepare data for shrinking
3343 // ===========================
3345 // Collect nodes to smooth, as src nodes are not yet replaced by tgt ones
3346 // and thus all nodes on a FACE connected to 2d elements are to be smoothed
3347 vector < const SMDS_MeshNode* > smoothNodes;
3349 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
3350 while ( nIt->more() )
3352 const SMDS_MeshNode* n = nIt->next();
3353 if ( n->NbInverseElements( SMDSAbs_Face ) > 0 )
3354 smoothNodes.push_back( n );
3357 // Find out face orientation
3359 const set<TGeomID> ignoreShapes;
3360 if ( !smoothNodes.empty() )
3362 gp_XY uv = helper.GetNodeUV( F, smoothNodes[0] );
3363 vector<_Simplex> simplices;
3364 getSimplices( smoothNodes[0], simplices, ignoreShapes );
3365 if ( simplices[0].IsForward(uv, F, helper,refSign) != (!reverse))
3369 // Find _LayerEdge's inflated along F
3370 vector< _LayerEdge* > lEdges;
3372 SMESH_subMeshIteratorPtr subIt =
3373 sm->getDependsOnIterator(/*includeSelf=*/false, /*complexShapeFirst=*/false);
3374 while ( subIt->more() )
3376 SMESH_subMesh* sub = subIt->next();
3377 SMESHDS_SubMesh* subDS = sub->GetSubMeshDS();
3378 if ( subDS->NbNodes() == 0 || !n2eMap.count( subDS->GetNodes()->next() ))
3380 SMDS_NodeIteratorPtr nIt = subDS->GetNodes();
3381 while ( nIt->more() )
3383 _LayerEdge* edge = n2eMap[ nIt->next() ];
3384 lEdges.push_back( edge );
3385 prepareEdgeToShrink( *edge, F, helper, smDS );
3390 // Replace source nodes by target nodes in mesh faces to shrink
3391 const SMDS_MeshNode* nodes[20];
3392 for ( unsigned i = 0; i < lEdges.size(); ++i )
3394 _LayerEdge& edge = *lEdges[i];
3395 const SMDS_MeshNode* srcNode = edge._nodes[0];
3396 const SMDS_MeshNode* tgtNode = edge._nodes.back();
3397 SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
3398 while ( fIt->more() )
3400 const SMDS_MeshElement* f = fIt->next();
3401 if ( !smDS->Contains( f ))
3403 SMDS_ElemIteratorPtr nIt = f->nodesIterator();
3404 for ( int iN = 0; iN < f->NbNodes(); ++iN )
3406 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
3407 nodes[iN] = ( n == srcNode ? tgtNode : n );
3409 helper.GetMeshDS()->ChangeElementNodes( f, nodes, f->NbNodes() );
3413 // Create _SmoothNode's on face F
3415 vector< _SmoothNode > nodesToSmooth( smoothNodes.size() );
3417 dumpFunction(SMESH_Comment("beforeShrinkFace")<<f2sd->first); // debug
3418 for ( unsigned i = 0; i < smoothNodes.size(); ++i )
3420 const SMDS_MeshNode* n = smoothNodes[i];
3421 nodesToSmooth[ i ]._node = n;
3422 // src nodes must be replaced by tgt nodes to have tgt nodes in _simplices
3423 getSimplices( n, nodesToSmooth[ i ]._simplices, ignoreShapes );
3424 // fix up incorrect uv of nodes on the FACE
3425 helper.GetNodeUV( F, n, 0, &isOkUV);
3430 //if ( nodesToSmooth.empty() ) continue;
3432 // Find EDGE's to shrink
3433 set< _Shrinker1D* > eShri1D;
3435 for ( unsigned i = 0; i < lEdges.size(); ++i )
3437 _LayerEdge* edge = lEdges[i];
3438 if ( edge->_sWOL.ShapeType() == TopAbs_EDGE )
3440 TGeomID edgeIndex = getMeshDS()->ShapeToIndex( edge->_sWOL );
3441 _Shrinker1D& srinker = e2shrMap[ edgeIndex ];
3442 eShri1D.insert( & srinker );
3443 srinker.AddEdge( edge, helper );
3444 // restore params of nodes on EGDE if the EDGE has been already
3445 // srinked while srinking another FACE
3446 srinker.RestoreParams();
3451 // ==================
3452 // Perform shrinking
3453 // ==================
3455 bool shrinked = true;
3456 int badNb, shriStep=0, smooStep=0;
3459 // Move boundary nodes (actually just set new UV)
3460 // -----------------------------------------------
3461 dumpFunction(SMESH_Comment("moveBoundaryOnF")<<f2sd->first<<"_st"<<shriStep++ ); // debug
3463 for ( unsigned i = 0; i < lEdges.size(); ++i )
3465 shrinked |= lEdges[i]->SetNewLength2d( surface,F,helper );
3471 // Move nodes on EDGE's
3472 set< _Shrinker1D* >::iterator shr = eShri1D.begin();
3473 for ( ; shr != eShri1D.end(); ++shr )
3474 (*shr)->Compute( /*set3D=*/false, helper );
3477 // -----------------
3478 int nbNoImpSteps = 0;
3481 while (( nbNoImpSteps < 5 && badNb > 0) && moved)
3483 dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
3485 int oldBadNb = badNb;
3488 for ( unsigned i = 0; i < nodesToSmooth.size(); ++i )
3490 moved |= nodesToSmooth[i].Smooth( badNb,surface,helper,refSign,/*set3D=*/false );
3492 if ( badNb < oldBadNb )
3500 return error(SMESH_Comment("Can't shrink 2D mesh on face ") << f2sd->first );
3502 // No wrongly shaped faces remain; final smooth. Set node XYZ.
3503 // First, find out a needed quality of smoothing (high for quadrangles only)
3506 const bool hasTria = _mesh->NbTriangles(), hasQuad = _mesh->NbQuadrangles();
3507 if ( hasTria != hasQuad )
3509 highQuality = hasQuad;
3513 set<int> nbNodesSet;
3514 SMDS_ElemIteratorPtr fIt = smDS->GetElements();
3515 while ( fIt->more() && nbNodesSet.size() < 2 )
3516 nbNodesSet.insert( fIt->next()->NbCornerNodes() );
3517 highQuality = ( *nbNodesSet.begin() == 4 );
3520 for ( int st = highQuality ? 8 : 3; st; --st )
3522 dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
3523 for ( unsigned i = 0; i < nodesToSmooth.size(); ++i )
3524 nodesToSmooth[i].Smooth( badNb,surface,helper,refSign,/*set3D=*/st==1 );
3527 // Set an event listener to clear FACE sub-mesh together with SOLID sub-mesh
3528 _SrinkShapeListener::ToClearSubMeshWithSolid( sm, data._solid );
3530 }// loop on FACES to srink mesh on
3533 // Replace source nodes by target nodes in shrinked mesh edges
3535 map< int, _Shrinker1D >::iterator e2shr = e2shrMap.begin();
3536 for ( ; e2shr != e2shrMap.end(); ++e2shr )
3537 e2shr->second.SwapSrcTgtNodes( getMeshDS() );
3542 //================================================================================
3544 * \brief Computes 2d shrink direction and finds nodes limiting shrinking
3546 //================================================================================
3548 bool _ViscousBuilder::prepareEdgeToShrink( _LayerEdge& edge,
3549 const TopoDS_Face& F,
3550 SMESH_MesherHelper& helper,
3551 const SMESHDS_SubMesh* faceSubMesh)
3553 const SMDS_MeshNode* srcNode = edge._nodes[0];
3554 const SMDS_MeshNode* tgtNode = edge._nodes.back();
3558 if ( edge._sWOL.ShapeType() == TopAbs_FACE )
3560 gp_XY srcUV = helper.GetNodeUV( F, srcNode );
3561 gp_XY tgtUV = helper.GetNodeUV( F, tgtNode );
3562 gp_Vec2d uvDir( srcUV, tgtUV );
3563 double uvLen = uvDir.Magnitude();
3565 edge._normal.SetCoord( uvDir.X(),uvDir.Y(), 0);
3567 // IMPORTANT to have src nodes NOT yet REPLACED by tgt nodes in shrinked faces
3568 vector<const SMDS_MeshElement*> faces;
3569 multimap< double, const SMDS_MeshNode* > proj2node;
3570 SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
3571 while ( fIt->more() )
3573 const SMDS_MeshElement* f = fIt->next();
3574 if ( faceSubMesh->Contains( f ))
3575 faces.push_back( f );
3577 for ( unsigned i = 0; i < faces.size(); ++i )
3579 const int nbNodes = faces[i]->NbCornerNodes();
3580 for ( int j = 0; j < nbNodes; ++j )
3582 const SMDS_MeshNode* n = faces[i]->GetNode(j);
3583 if ( n == srcNode ) continue;
3584 if ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE &&
3585 ( faces.size() > 1 || nbNodes > 3 ))
3587 gp_Pnt2d uv = helper.GetNodeUV( F, n );
3588 gp_Vec2d uvDirN( srcUV, uv );
3589 double proj = uvDirN * uvDir;
3590 proj2node.insert( make_pair( proj, n ));
3594 multimap< double, const SMDS_MeshNode* >::iterator p2n = proj2node.begin(), p2nEnd;
3595 const double minProj = p2n->first;
3596 const double projThreshold = 1.1 * uvLen;
3597 if ( minProj > projThreshold )
3599 // tgtNode is located so that it does not make faces with wrong orientation
3602 edge._pos.resize(1);
3603 edge._pos[0].SetCoord( tgtUV.X(), tgtUV.Y(), 0 );
3605 // store most risky nodes in _simplices
3606 p2nEnd = proj2node.lower_bound( projThreshold );
3607 int nbSimpl = ( std::distance( p2n, p2nEnd ) + 1) / 2;
3608 edge._simplices.resize( nbSimpl );
3609 for ( int i = 0; i < nbSimpl; ++i )
3611 edge._simplices[i]._nPrev = p2n->second;
3612 if ( ++p2n != p2nEnd )
3613 edge._simplices[i]._nNext = p2n->second;
3615 // set UV of source node to target node
3616 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
3617 pos->SetUParameter( srcUV.X() );
3618 pos->SetVParameter( srcUV.Y() );
3620 else // _sWOL is TopAbs_EDGE
3622 TopoDS_Edge E = TopoDS::Edge( edge._sWOL);
3623 SMESHDS_SubMesh* edgeSM = getMeshDS()->MeshElements( E );
3624 if ( !edgeSM || edgeSM->NbElements() == 0 )
3625 return error(SMESH_Comment("Not meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
3627 const SMDS_MeshNode* n2 = 0;
3628 SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
3629 while ( eIt->more() && !n2 )
3631 const SMDS_MeshElement* e = eIt->next();
3632 if ( !edgeSM->Contains(e)) continue;
3633 n2 = e->GetNode( 0 );
3634 if ( n2 == srcNode ) n2 = e->GetNode( 1 );
3637 return error(SMESH_Comment("Wrongly meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
3639 double uSrc = helper.GetNodeU( E, srcNode, n2 );
3640 double uTgt = helper.GetNodeU( E, tgtNode, srcNode );
3641 double u2 = helper.GetNodeU( E, n2, srcNode );
3643 if ( fabs( uSrc-uTgt ) < 0.99 * fabs( uSrc-u2 ))
3645 // tgtNode is located so that it does not make faces with wrong orientation
3648 edge._pos.resize(1);
3649 edge._pos[0].SetCoord( U_TGT, uTgt );
3650 edge._pos[0].SetCoord( U_SRC, uSrc );
3651 edge._pos[0].SetCoord( LEN_TGT, fabs( uSrc-uTgt ));
3653 edge._simplices.resize( 1 );
3654 edge._simplices[0]._nPrev = n2;
3656 // set UV of source node to target node
3657 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
3658 pos->SetUParameter( uSrc );
3662 //================================================================================
3664 * \brief Compute positions (UV) to set to a node on edge moved during shrinking
3666 //================================================================================
3668 // Compute UV to follow during shrinking
3670 // const SMDS_MeshNode* srcNode = edge._nodes[0];
3671 // const SMDS_MeshNode* tgtNode = edge._nodes.back();
3673 // gp_XY srcUV = helper.GetNodeUV( F, srcNode );
3674 // gp_XY tgtUV = helper.GetNodeUV( F, tgtNode );
3675 // gp_Vec2d uvDir( srcUV, tgtUV );
3676 // double uvLen = uvDir.Magnitude();
3679 // // Select shrinking step such that not to make faces with wrong orientation.
3680 // // IMPORTANT to have src nodes NOT yet REPLACED by tgt nodes in shrinked faces
3681 // const double minStepSize = uvLen / 20;
3682 // double stepSize = uvLen;
3683 // SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
3684 // while ( fIt->more() )
3686 // const SMDS_MeshElement* f = fIt->next();
3687 // if ( !faceSubMesh->Contains( f )) continue;
3688 // const int nbNodes = f->NbCornerNodes();
3689 // for ( int i = 0; i < nbNodes; ++i )
3691 // const SMDS_MeshNode* n = f->GetNode(i);
3692 // if ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE || n == srcNode)
3694 // gp_XY uv = helper.GetNodeUV( F, n );
3695 // gp_Vec2d uvDirN( srcUV, uv );
3696 // double proj = uvDirN * uvDir;
3697 // if ( proj < stepSize && proj > minStepSize )
3703 // const int nbSteps = ceil( uvLen / stepSize );
3704 // gp_XYZ srcUV0( srcUV.X(), srcUV.Y(), 0 );
3705 // gp_XYZ tgtUV0( tgtUV.X(), tgtUV.Y(), 0 );
3706 // edge._pos.resize( nbSteps );
3707 // edge._pos[0] = tgtUV0;
3708 // for ( int i = 1; i < nbSteps; ++i )
3710 // double r = i / double( nbSteps );
3711 // edge._pos[i] = (1-r) * tgtUV0 + r * srcUV0;
3716 //================================================================================
3718 * \brief Move target node to it's final position on the FACE during shrinking
3720 //================================================================================
3722 bool _LayerEdge::SetNewLength2d( Handle(Geom_Surface)& surface,
3723 const TopoDS_Face& F,
3724 SMESH_MesherHelper& helper )
3727 return false; // already at the target position
3729 SMDS_MeshNode* tgtNode = const_cast< SMDS_MeshNode*& >( _nodes.back() );
3731 if ( _sWOL.ShapeType() == TopAbs_FACE )
3733 gp_XY curUV = helper.GetNodeUV( F, tgtNode );
3734 gp_Pnt2d tgtUV( _pos[0].X(), _pos[0].Y());
3735 gp_Vec2d uvDir( _normal.X(), _normal.Y() );
3736 const double uvLen = tgtUV.Distance( curUV );
3738 // Select shrinking step such that not to make faces with wrong orientation.
3739 const double kSafe = 0.8;
3740 const double minStepSize = uvLen / 10;
3741 double stepSize = uvLen;
3742 for ( unsigned i = 0; i < _simplices.size(); ++i )
3744 const SMDS_MeshNode* nn[2] = { _simplices[i]._nPrev, _simplices[i]._nNext };
3745 for ( int j = 0; j < 2; ++j )
3746 if ( const SMDS_MeshNode* n = nn[j] )
3748 gp_XY uv = helper.GetNodeUV( F, n );
3749 gp_Vec2d uvDirN( curUV, uv );
3750 double proj = uvDirN * uvDir * kSafe;
3751 if ( proj < stepSize && proj > minStepSize )
3757 if ( stepSize == uvLen )
3764 newUV = curUV + uvDir.XY() * stepSize;
3767 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
3768 pos->SetUParameter( newUV.X() );
3769 pos->SetVParameter( newUV.Y() );
3772 gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
3773 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
3774 dumpMove( tgtNode );
3777 else // _sWOL is TopAbs_EDGE
3779 TopoDS_Edge E = TopoDS::Edge( _sWOL );
3780 const SMDS_MeshNode* n2 = _simplices[0]._nPrev;
3782 const double u2 = helper.GetNodeU( E, n2, tgtNode );
3783 const double uSrc = _pos[0].Coord( U_SRC );
3784 const double lenTgt = _pos[0].Coord( LEN_TGT );
3786 double newU = _pos[0].Coord( U_TGT );
3787 if ( lenTgt < 0.99 * fabs( uSrc-u2 ))
3793 newU = 0.1 * uSrc + 0.9 * u2;
3795 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
3796 pos->SetUParameter( newU );
3798 gp_XY newUV = helper.GetNodeUV( F, tgtNode, _nodes[0]);
3799 gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
3800 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
3801 dumpMove( tgtNode );
3807 //================================================================================
3809 * \brief Perform laplacian smooth on the FACE
3810 * \retval bool - true if the node has been moved
3812 //================================================================================
3814 bool _SmoothNode::Smooth(int& badNb,
3815 Handle(Geom_Surface)& surface,
3816 SMESH_MesherHelper& helper,
3817 const double refSign,
3820 const TopoDS_Face& face = TopoDS::Face( helper.GetSubShape() );
3822 // compute new UV for the node
3824 for ( unsigned i = 0; i < _simplices.size(); ++i )
3825 newPos += helper.GetNodeUV( face, _simplices[i]._nPrev );
3826 newPos /= _simplices.size();
3828 // count quality metrics (orientation) of triangles around the node
3830 gp_XY tgtUV = helper.GetNodeUV( face, _node );
3831 for ( unsigned i = 0; i < _simplices.size(); ++i )
3832 nbOkBefore += _simplices[i].IsForward( tgtUV, face, helper, refSign );
3835 for ( unsigned i = 0; i < _simplices.size(); ++i )
3836 nbOkAfter += _simplices[i].IsForward( newPos, face, helper, refSign );
3838 if ( nbOkAfter < nbOkBefore )
3841 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( _node->GetPosition() );
3842 pos->SetUParameter( newPos.X() );
3843 pos->SetVParameter( newPos.Y() );
3850 gp_Pnt p = surface->Value( newPos.X(), newPos.Y() );
3851 const_cast< SMDS_MeshNode* >( _node )->setXYZ( p.X(), p.Y(), p.Z() );
3855 badNb += _simplices.size() - nbOkAfter;
3856 return ( (tgtUV-newPos).SquareModulus() > 1e-10 );
3859 //================================================================================
3861 * \brief Delete _SolidData
3863 //================================================================================
3865 _SolidData::~_SolidData()
3867 for ( unsigned i = 0; i < _edges.size(); ++i )
3869 if ( _edges[i] && _edges[i]->_2neibors )
3870 delete _edges[i]->_2neibors;
3875 //================================================================================
3877 * \brief Add a _LayerEdge inflated along the EDGE
3879 //================================================================================
3881 void _Shrinker1D::AddEdge( const _LayerEdge* e, SMESH_MesherHelper& helper )
3884 if ( _nodes.empty() )
3886 _edges[0] = _edges[1] = 0;
3890 if ( e == _edges[0] || e == _edges[1] )
3892 if ( e->_sWOL.IsNull() || e->_sWOL.ShapeType() != TopAbs_EDGE )
3893 throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
3894 if ( _edges[0] && _edges[0]->_sWOL != e->_sWOL )
3895 throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
3898 const TopoDS_Edge& E = TopoDS::Edge( e->_sWOL );
3900 BRep_Tool::Range( E, f,l );
3901 double u = helper.GetNodeU( E, e->_nodes[0], e->_nodes.back());
3902 _edges[ u < 0.5*(f+l) ? 0 : 1 ] = e;
3906 const SMDS_MeshNode* tgtNode0 = _edges[0] ? _edges[0]->_nodes.back() : 0;
3907 const SMDS_MeshNode* tgtNode1 = _edges[1] ? _edges[1]->_nodes.back() : 0;
3909 if ( _nodes.empty() )
3911 SMESHDS_SubMesh * eSubMesh = helper.GetMeshDS()->MeshElements( E );
3912 if ( !eSubMesh || eSubMesh->NbNodes() < 1 )
3914 TopLoc_Location loc;
3915 Handle(Geom_Curve) C = BRep_Tool::Curve(E, loc, f,l);
3916 GeomAdaptor_Curve aCurve(C, f,l);
3917 const double totLen = GCPnts_AbscissaPoint::Length(aCurve, f, l);
3919 int nbExpectNodes = eSubMesh->NbNodes() - e->_nodes.size();
3920 _initU .reserve( nbExpectNodes );
3921 _normPar.reserve( nbExpectNodes );
3922 _nodes .reserve( nbExpectNodes );
3923 SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
3924 while ( nIt->more() )
3926 const SMDS_MeshNode* node = nIt->next();
3927 if ( node->NbInverseElements(SMDSAbs_Edge) == 0 ||
3928 node == tgtNode0 || node == tgtNode1 )
3929 continue; // refinement nodes
3930 _nodes.push_back( node );
3931 _initU.push_back( helper.GetNodeU( E, node ));
3932 double len = GCPnts_AbscissaPoint::Length(aCurve, f, _initU.back());
3933 _normPar.push_back( len / totLen );
3938 // remove target node of the _LayerEdge from _nodes
3940 for ( unsigned i = 0; i < _nodes.size(); ++i )
3941 if ( !_nodes[i] || _nodes[i] == tgtNode0 || _nodes[i] == tgtNode1 )
3942 _nodes[i] = 0, nbFound++;
3943 if ( nbFound == _nodes.size() )
3948 //================================================================================
3950 * \brief Move nodes on EDGE from ends where _LayerEdge's are inflated
3952 //================================================================================
3954 void _Shrinker1D::Compute(bool set3D, SMESH_MesherHelper& helper)
3956 if ( _done || _nodes.empty())
3958 const _LayerEdge* e = _edges[0];
3959 if ( !e ) e = _edges[1];
3962 _done = (( !_edges[0] || _edges[0]->_pos.empty() ) &&
3963 ( !_edges[1] || _edges[1]->_pos.empty() ));
3965 const TopoDS_Edge& E = TopoDS::Edge( e->_sWOL );
3967 if ( set3D || _done )
3969 Handle(Geom_Curve) C = BRep_Tool::Curve(E, f,l);
3970 GeomAdaptor_Curve aCurve(C, f,l);
3973 f = helper.GetNodeU( E, _edges[0]->_nodes.back(), _nodes[0] );
3975 l = helper.GetNodeU( E, _edges[1]->_nodes.back(), _nodes.back() );
3976 double totLen = GCPnts_AbscissaPoint::Length( aCurve, f, l );
3978 for ( unsigned i = 0; i < _nodes.size(); ++i )
3980 if ( !_nodes[i] ) continue;
3981 double len = totLen * _normPar[i];
3982 GCPnts_AbscissaPoint discret( aCurve, len, f );
3983 if ( !discret.IsDone() )
3984 return throw SALOME_Exception(LOCALIZED("GCPnts_AbscissaPoint failed"));
3985 double u = discret.Parameter();
3986 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
3987 pos->SetUParameter( u );
3988 gp_Pnt p = C->Value( u );
3989 const_cast< SMDS_MeshNode*>( _nodes[i] )->setXYZ( p.X(), p.Y(), p.Z() );
3994 BRep_Tool::Range( E, f,l );
3996 f = helper.GetNodeU( E, _edges[0]->_nodes.back(), _nodes[0] );
3998 l = helper.GetNodeU( E, _edges[1]->_nodes.back(), _nodes.back() );
4000 for ( unsigned i = 0; i < _nodes.size(); ++i )
4002 if ( !_nodes[i] ) continue;
4003 double u = f * ( 1-_normPar[i] ) + l * _normPar[i];
4004 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
4005 pos->SetUParameter( u );
4010 //================================================================================
4012 * \brief Restore initial parameters of nodes on EDGE
4014 //================================================================================
4016 void _Shrinker1D::RestoreParams()
4019 for ( unsigned i = 0; i < _nodes.size(); ++i )
4021 if ( !_nodes[i] ) continue;
4022 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
4023 pos->SetUParameter( _initU[i] );
4028 //================================================================================
4030 * \brief Replace source nodes by target nodes in shrinked mesh edges
4032 //================================================================================
4034 void _Shrinker1D::SwapSrcTgtNodes( SMESHDS_Mesh* mesh )
4036 const SMDS_MeshNode* nodes[3];
4037 for ( int i = 0; i < 2; ++i )
4039 if ( !_edges[i] ) continue;
4041 SMESHDS_SubMesh * eSubMesh = mesh->MeshElements( _edges[i]->_sWOL );
4042 if ( !eSubMesh ) return;
4043 const SMDS_MeshNode* srcNode = _edges[i]->_nodes[0];
4044 const SMDS_MeshNode* tgtNode = _edges[i]->_nodes.back();
4045 SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
4046 while ( eIt->more() )
4048 const SMDS_MeshElement* e = eIt->next();
4049 if ( !eSubMesh->Contains( e ))
4051 SMDS_ElemIteratorPtr nIt = e->nodesIterator();
4052 for ( int iN = 0; iN < e->NbNodes(); ++iN )
4054 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
4055 nodes[iN] = ( n == srcNode ? tgtNode : n );
4057 mesh->ChangeElementNodes( e, nodes, e->NbNodes() );
4062 //================================================================================
4064 * \brief Creates 2D and 1D elements on boundaries of new prisms
4066 //================================================================================
4068 bool _ViscousBuilder::addBoundaryElements()
4070 SMESH_MesherHelper helper( *_mesh );
4072 for ( unsigned i = 0; i < _sdVec.size(); ++i )
4074 _SolidData& data = _sdVec[i];
4075 TopTools_IndexedMapOfShape geomEdges;
4076 TopExp::MapShapes( data._solid, TopAbs_EDGE, geomEdges );
4077 for ( int iE = 1; iE <= geomEdges.Extent(); ++iE )
4079 const TopoDS_Edge& E = TopoDS::Edge( geomEdges(iE));
4081 // Get _LayerEdge's based on E
4083 map< double, const SMDS_MeshNode* > u2nodes;
4084 if ( !SMESH_Algo::GetSortedNodesOnEdge( getMeshDS(), E, /*ignoreMedium=*/false, u2nodes))
4087 vector< _LayerEdge* > ledges; ledges.reserve( u2nodes.size() );
4088 TNode2Edge & n2eMap = data._n2eMap;
4089 map< double, const SMDS_MeshNode* >::iterator u2n = u2nodes.begin();
4091 //check if 2D elements are needed on E
4092 TNode2Edge::iterator n2e = n2eMap.find( u2n->second );
4093 if ( n2e == n2eMap.end() ) continue; // no layers on vertex
4094 ledges.push_back( n2e->second );
4096 if (( n2e = n2eMap.find( u2n->second )) == n2eMap.end() )
4097 continue; // no layers on E
4098 ledges.push_back( n2eMap[ u2n->second ]);
4100 const SMDS_MeshNode* tgtN0 = ledges[0]->_nodes.back();
4101 const SMDS_MeshNode* tgtN1 = ledges[1]->_nodes.back();
4102 int nbSharedPyram = 0;
4103 SMDS_ElemIteratorPtr vIt = tgtN0->GetInverseElementIterator(SMDSAbs_Volume);
4104 while ( vIt->more() )
4106 const SMDS_MeshElement* v = vIt->next();
4107 nbSharedPyram += int( v->GetNodeIndex( tgtN1 ) >= 0 );
4109 if ( nbSharedPyram > 1 )
4110 continue; // not free border of the pyramid
4112 if ( getMeshDS()->FindFace( ledges[0]->_nodes[0], ledges[0]->_nodes[1],
4113 ledges[1]->_nodes[0], ledges[1]->_nodes[1]))
4114 continue; // faces already created
4116 for ( ++u2n; u2n != u2nodes.end(); ++u2n )
4117 ledges.push_back( n2eMap[ u2n->second ]);
4119 // Find out orientation and type of face to create
4121 bool reverse = false, isOnFace;
4123 map< TGeomID, TopoDS_Shape >::iterator e2f =
4124 data._shrinkShape2Shape.find( getMeshDS()->ShapeToIndex( E ));
4126 if (( isOnFace = ( e2f != data._shrinkShape2Shape.end() )))
4128 F = e2f->second.Oriented( TopAbs_FORWARD );
4129 reverse = ( helper.GetSubShapeOri( F, E ) == TopAbs_REVERSED );
4130 if ( helper.GetSubShapeOri( data._solid, F ) == TopAbs_REVERSED )
4135 // find FACE with layers sharing E
4136 PShapeIteratorPtr fIt = helper.GetAncestors( E, *_mesh, TopAbs_FACE );
4137 while ( fIt->more() && F.IsNull() )
4139 const TopoDS_Shape* pF = fIt->next();
4140 if ( helper.IsSubShape( *pF, data._solid) &&
4141 !_ignoreShapeIds.count( e2f->first ))
4145 // Find the sub-mesh to add new faces
4146 SMESHDS_SubMesh* sm = 0;
4148 sm = getMeshDS()->MeshElements( F );
4150 sm = data._proxyMesh->getFaceSubM( TopoDS::Face(F), /*create=*/true );
4152 return error("error in addBoundaryElements()", data._index);
4155 const int dj1 = reverse ? 0 : 1;
4156 const int dj2 = reverse ? 1 : 0;
4157 for ( unsigned j = 1; j < ledges.size(); ++j )
4159 vector< const SMDS_MeshNode*>& nn1 = ledges[j-dj1]->_nodes;
4160 vector< const SMDS_MeshNode*>& nn2 = ledges[j-dj2]->_nodes;
4162 for ( unsigned z = 1; z < nn1.size(); ++z )
4163 sm->AddElement( getMeshDS()->AddFace( nn1[z-1], nn2[z-1], nn2[z], nn1[z] ));
4165 for ( unsigned z = 1; z < nn1.size(); ++z )
4166 sm->AddElement( new SMDS_FaceOfNodes( nn1[z-1], nn2[z-1], nn2[z], nn1[z]));